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.

feat(macos): ask for permissions just in time, with macOS's own dialog (#320)

Ruben Lütke939031f208b1
diff --git a/.github/workflows/desktop-installers.yml b/.github/workflows/desktop-installers.yml
index 26fdf7b33c..f8bfcb89d8 100644
--- a/.github/workflows/desktop-installers.yml
+++ b/.github/workflows/desktop-installers.yml
@@ -193,11 +193,14 @@ jobs:
with:
node-version: ${{ env.NODE_VERSION }}
- - name: Install Personal Jarvis (desktop + dev)
+ # desktop-macos carries the pyobjc frameworks the permission port loads by
+ # name (AVFoundation, ScreenCaptureKit, ...); without them the frozen app
+ # cannot even read its microphone permission (BUG-222).
+ - name: Install Personal Jarvis (desktop + macOS frameworks + dev)
shell: bash
run: |
python -m pip install --upgrade pip
- python scripts/pip_install.py -e ".[desktop,dev]"
+ python scripts/pip_install.py -e ".[desktop,desktop-macos,dev]"
# The script decides what to do with these: with them it codesigns with
# the Developer ID identity and notarizes; without them it ad-hoc signs,
@@ -215,6 +218,13 @@ jobs:
chmod +x packaging/macos/build.sh
./packaging/macos/build.sh
+ # The permission port loads pyobjc frameworks by name and the bundle's
+ # Info.plist decides how LaunchServices runs it; neither shows in the
+ # headless smoke test below, so look at the built app itself (BUG-222).
+ - name: Verify the app bundle can use macOS permissions
+ shell: bash
+ run: python scripts/ci/check_frozen_macos_app.py --app "dist/Personal Jarvis.app"
+
- name: Preserve native wheel diagnostics on build failure
if: failure() && hashFiles('jarvis/assets/browser/wheels/*.whl') != ''
uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882
diff --git a/.github/workflows/macos-desktop.yml b/.github/workflows/macos-desktop.yml
index 0680c41e30..18123137f9 100644
--- a/.github/workflows/macos-desktop.yml
+++ b/.github/workflows/macos-desktop.yml
@@ -1,7 +1,8 @@
# Native macOS desktop verification on both supported processor families.
# TCC dialogs require a signed, foreground GUI app and therefore cannot be
# approved in CI. This workflow verifies the full dependency install, stable
-# bundle construction, permission fail-closed behavior, and Computer-Use math;
+# bundle construction, permission fail-closed behavior (an ask outside the
+# installed app is refused, never made), and Computer-Use math;
# the release checklist retains one physical-Mac grant/click sign-off.
name: macOS desktop
@@ -84,10 +85,157 @@ jobs:
- name: Import native permission frameworks
run: python -c "import AVFoundation, ApplicationServices, AppKit, Foundation, HIServices, Quartz, ScreenCaptureKit"
- - name: Verify headless TCC requests fail closed
+ # A bare Python on a runner is not the installed app, so the permission
+ # service must not start a native request of its own there (design P6):
+ # the ask is refused with the reason "outside the installed app" and
+ # nothing is requested. The runner's own TCC grants (a pre-granted
+ # responsible process) are read as they are, never refused. Every state the
+ # runner can report (granted, not determined, denied, restricted, no
+ # desktop session) must pass: the step asserts only that nothing was
+ # requested and that nothing but a granted state reads as granted.
+ #
+ # The three native request seams of the real port are replaced by tripwires
+ # BEFORE the call, so "nothing was requested" is proven at the port and not
+ # only through the service's own bookkeeping, and a regression can never
+ # reach a real dialog on the runner.
+ - name: Verify headless permission asks fail closed
shell: bash
run: |
- python -c "from jarvis.platform.permissions import PermissionId, SystemPermissionPort; p=SystemPermissionPort(); s=p.snapshot(); assert s['platform']=='darwin'; op=p.request(PermissionId.MICROPHONE); assert not op.performed"
+ python - <<'PY'
+ from jarvis.platform.permission_service import PermissionOutcome, get_permission_service
+ from jarvis.platform.permissions import (
+ PermissionId,
+ PermissionState,
+ get_system_permission_port,
+ )
+
+ port = get_system_permission_port()
+ assert port.platform == "darwin", port.platform
+ assert port.outside_installed_app is True
+
+ attempts = []
+
+ def forbidden(*_args, **_kwargs):
+ attempts.append(1)
+ raise AssertionError("a native permission request was made outside the installed app")
+
+ port.request_native = forbidden
+ port._iohid_request = forbidden
+ port._automation_consent_runner = forbidden
+
+ result = get_permission_service().ensure(PermissionId.MICROPHONE, feature="voice")
+ print(result.outcome, result.state, result.asked, result.outside_installed_app)
+ assert attempts == [], "the port was asked to make a native request"
+ assert result.asked is False, "a native request was made outside the installed app"
+ if result.state is not PermissionState.GRANTED:
+ assert result.outcome is not PermissionOutcome.GRANTED
+ PY
+
+ # Symbol binding: every framework function the permission port and the
+ # service bind by name must resolve on the runner's macOS. A rename or a
+ # missing symbol fails here instead of silently reading as "unavailable"
+ # on a user's Mac. Only the symbols the port reads without a fallback are
+ # required; the optional ones are reported.
+ - name: Probe the native permission symbols
+ shell: bash
+ run: |
+ python - <<'PY'
+ import importlib
+
+ REQUIRED = {
+ "AVFoundation": ["AVCaptureDevice", "AVMediaTypeAudio"],
+ "ApplicationServices": [
+ "AXIsProcessTrusted",
+ "AXIsProcessTrustedWithOptions",
+ "kAXTrustedCheckOptionPrompt",
+ ],
+ "AppKit": ["NSWorkspace", "NSRunningApplication"],
+ "Foundation": ["NSBundle", "NSURL"],
+ "Quartz": [
+ "CGPreflightScreenCaptureAccess",
+ "CGRequestScreenCaptureAccess",
+ "CGPreflightListenEventAccess",
+ "CGRequestListenEventAccess",
+ "CGEventTapCreate",
+ ],
+ }
+ OPTIONAL = {
+ "AVFoundation": [
+ "AVAuthorizationStatusNotDetermined",
+ "AVAuthorizationStatusRestricted",
+ "AVAuthorizationStatusDenied",
+ "AVAuthorizationStatusAuthorized",
+ ],
+ "Quartz": ["CGPreflightPostEventAccess", "CGRequestPostEventAccess"],
+ }
+
+ missing = []
+ for module_name, names in REQUIRED.items():
+ module = importlib.import_module(module_name)
+ missing += [f"{module_name}.{name}" for name in names if not hasattr(module, name)]
+ for module_name, names in OPTIONAL.items():
+ module = importlib.import_module(module_name)
+ for name in names:
+ if not hasattr(module, name):
+ print(f"optional symbol absent: {module_name}.{name}")
+ assert not missing, f"native permission symbols did not bind: {missing}"
+ PY
+
+ # Smoke of the service against the real frameworks, never interactive: every
+ # state read must come back as a PermissionState (types only; the runner's
+ # grants are whatever they are), a background ensure must never ask, and the
+ # non-asking Apple Event probe must return on its own (it runs on a daemon
+ # thread with a deadline: a hang is the failure this step exists to catch).
+ - name: Smoke the permission service without asking
+ shell: bash
+ timeout-minutes: 5
+ run: |
+ python - <<'PY'
+ import threading
+
+ from jarvis.platform.permission_service import PermissionOutcome, get_permission_service
+ from jarvis.platform.permissions import (
+ PermissionId,
+ PermissionState,
+ get_system_permission_port,
+ )
+
+ port = get_system_permission_port()
+ service = get_permission_service()
+
+ attempts = []
+
+ def forbidden(*_args, **_kwargs):
+ attempts.append(1)
+ raise AssertionError("a native permission request was made without a gesture")
+
+ port.request_native = forbidden
+ port._iohid_request = forbidden
+ port._automation_consent_runner = forbidden
+
+ for permission in PermissionId:
+ state = service.check(permission)
+ assert isinstance(state, PermissionState), (permission, state)
+ result = service.ensure(permission, feature="voice", interactive=False)
+ print(permission.value, state.value, result.outcome)
+ assert result.asked is False, permission
+ if result.outcome is PermissionOutcome.GRANTED:
+ assert result.granted and result.state in (
+ PermissionState.GRANTED,
+ PermissionState.NOT_REQUIRED,
+ ), permission
+ assert attempts == [], "a native request was made without a gesture"
+
+ answer = []
+ probe = threading.Thread(
+ target=lambda: answer.append(port._automation_probe("com.apple.Music", False)),
+ daemon=True,
+ )
+ probe.start()
+ probe.join(30)
+ assert not probe.is_alive(), "the non-asking Automation probe did not return"
+ assert answer[0] is None or isinstance(answer[0], int), answer
+ PY
- name: Build and self-probe the native app identity
shell: bash
@@ -121,8 +269,18 @@ jobs:
tests/integration/test_admin_unix_loopback.py \
tests/unit/admin/test_unix_socket_transport.py \
tests/unit/platform/test_permissions.py \
+ tests/unit/platform/test_permission_service*.py \
+ tests/unit/platform/test_permission_characterization.py \
+ tests/unit/platform/test_permissions_state_api.py \
+ tests/unit/platform/test_permission_agent_boundary.py \
+ tests/unit/platform/test_fake_tcc.py \
+ tests/unit/platform/test_no_legacy_permission_api.py \
+ tests/unit/core/test_permission_events.py \
+ tests/contract/test_permission_service_contract.py \
tests/unit/audio/test_capture_permission_gate.py \
tests/unit/ui/web/test_permissions_routes.py \
+ tests/unit/ui/web/test_permissions_snapshot.py \
+ tests/unit/ui/web/test_keybinds_input_monitoring_ask.py \
tests/unit/ui/test_desktop_macos_permission_gate.py \
tests/unit/setup/test_macos_app_bundle.py \
tests/unit/setup/test_desktop_integration.py \
@@ -144,4 +302,14 @@ jobs:
tests/unit/vision/test_ax_tree.py \
tests/unit/vision/test_element_at_point.py \
tests/unit/vision/test_select_capture_monitor.py \
- tests/unit/trigger/test_hotkey_backends.py
+ tests/unit/trigger/test_hotkey_backends.py \
+ tests/unit/trigger/test_quartz_jit_permissions.py \
+ tests/unit/platform/test_screen_access.py \
+ tests/unit/audio/test_ducking_permissions.py \
+ tests/unit/dictation/test_insert_permission.py \
+ tests/unit/cu/test_system_dialogs.py \
+ tests/unit/speech/test_voice_permission_jit.py \
+ tests/unit/packaging/test_macos_privacy_strings.py \
+ tests/unit/packaging/test_macos_build_script.py \
+ tests/unit/ci/test_check_frozen_macos_app.py \
+ tests/unit/ci/test_macos_desktop_permission_step.py
diff --git a/.github/workflows/macos-hotkey-spike.yml b/.github/workflows/macos-hotkey-spike.yml
new file mode 100644
index 0000000000..e2e116e072
--- /dev/null
+++ b/.github/workflows/macos-hotkey-spike.yml
@@ -0,0 +1,114 @@
+# Dispatch-only evidence run for a FUTURE Carbon RegisterEventHotKey hotkey
+# backend. Nothing in this repository ships that backend: macOS global shortcuts
+# still use the listen-only CGEventTap. This workflow runs
+# scripts/ci/macos_carbon_hotkey_spike.py on an Intel and an Apple Silicon
+# runner; the script records the TCC context first, then runs each risky
+# variant in a child process so a native crash becomes data. A crash in a
+# variant is NOT a failed job: the job fails only when the harness itself breaks.
+#
+# Runner evidence only. Runners pre-grant TCC to bash/osascript/Terminal, no
+# dialog is shown, no physical keyboard exists, and no key-hold semantics are
+# exercised. The default of a hotkey backend must never be decided from this
+# run alone: flipping it also needs a built-app probe on both architectures, a
+# physical-Mac sign-off and one opt-in release cycle.
+
+name: macOS hotkey spike
+
+on:
+ workflow_dispatch:
+ inputs:
+ include_macos_26:
+ description: >-
+ Also run on the macos-26 label. UNVERIFIED that this runner label
+ exists for this repository: a job on a missing label stays queued.
+ type: boolean
+ default: false
+
+permissions:
+ contents: read
+
+jobs:
+ plan:
+ name: Plan the runner matrix
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ outputs:
+ matrix: ${{ steps.matrix.outputs.matrix }}
+ steps:
+ - name: Build the matrix
+ id: matrix
+ shell: bash
+ env:
+ INCLUDE_MACOS_26: ${{ inputs.include_macos_26 }}
+ run: |
+ rows='{"runner":"macos-15-intel","arch":"x86_64"},{"runner":"macos-15","arch":"arm64"}'
+ if [ "$INCLUDE_MACOS_26" = "true" ]; then
+ rows="$rows"',{"runner":"macos-26","arch":"arm64"}'
+ fi
+ printf 'matrix={"include":[%s]}\n' "$rows" >> "$GITHUB_OUTPUT"
+
+ spike:
+ name: Carbon spike / ${{ matrix.runner }} (${{ matrix.arch }})
+ needs: plan
+ strategy:
+ fail-fast: false
+ matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 30
+ env:
+ SPIKE_RUNNER_LABEL: ${{ matrix.runner }}
+ SPIKE_EXPECTED_ARCH: ${{ matrix.arch }}
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+
+ - name: Set up Python
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: "3.12"
+
+ - name: Verify native architecture
+ shell: bash
+ run: |
+ python -c "import os, platform; actual = platform.machine(); expected = os.environ['SPIKE_EXPECTED_ARCH']; print(actual); assert actual == expected, (actual, expected)"
+
+ # The script needs only the standard library and ctypes. It never touches
+ # the network and exits 0 when a variant crashes. The synthetic key is the
+ # one thing that needs System Events automation, which the runner image
+ # pre-grants to osascript.
+ - name: Run the Carbon hotkey spike
+ shell: bash
+ run: |
+ mkdir -p spike-out
+ python scripts/ci/macos_carbon_hotkey_spike.py \
+ --out "spike-out/carbon-hotkey-spike-${SPIKE_RUNNER_LABEL}.json" \
+ --summary-md spike-out/summary.md \
+ --inject-synthetic-key
+
+ - name: Publish the step summary
+ if: always()
+ shell: bash
+ run: |
+ {
+ if [ -f spike-out/summary.md ]; then
+ cat spike-out/summary.md
+ else
+ echo "### macOS Carbon hotkey spike"
+ echo
+ echo "The spike did not produce a summary: the harness itself failed, see the run log."
+ echo
+ echo "Runner evidence only: runners pre-grant TCC to bash/osascript/Terminal; no dialog is shown, no physical keyboard exists, no key-hold semantics were exercised."
+ fi
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Upload the spike JSON
+ if: always()
+ uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
+ with:
+ name: carbon-hotkey-spike-${{ matrix.runner }}
+ path: spike-out/
+ if-no-files-found: warn
+ retention-days: 30
diff --git a/AGENTS.md b/AGENTS.md
index 84a70c6cbd..ab04e7465b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -163,8 +163,12 @@ wake upgrade only on the out-of-process inference probe, never on CUDA presence
(AP-25); verify a wake word on audio energy and candidate shape, never on
transcript content (AP-27); a WebGL scene releases its context and survives
losing it (AP-32); a reconnect without jitter and without a shared connect
-budget is an outage of the whole machine, not an app bug (AP-33). Detail and
-history for any of them: `docs/BUGS.md`.
+budget is an outage of the whole machine, not an app bug (AP-33); a macOS
+feature asks the OS at first use, from a user gesture, through
+`jarvis/platform/permission_service.py` — no preflight refuses before the OS was
+asked, nothing is asked at launch, nothing acts without a live grant, an agent
+never answers a system dialog (AP-35; `docs/macos-permissions.md`, ADR-0038).
+Detail and history for any of them: `docs/BUGS.md`.
## 4. How work ships
@@ -234,4 +238,5 @@ voice-ready path.
**Pointers:** [`docs/architecture-overview.md`](docs/architecture-overview.md) ·
[`docs/BUGS.md`](docs/BUGS.md) (symptom → cause) · `docs/adr/` ·
[`docs/os-parity.md`](docs/os-parity.md) ·
+[`docs/macos-permissions.md`](docs/macos-permissions.md) ·
[`docs/jarvis-cli.md`](docs/jarvis-cli.md).
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e2cf76d47b..fbcef6ec81 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,32 @@ versioning per [SemVer](https://semver.org/).
### Added
+- **macOS asks when a feature needs a permission.** The first time you use a feature that needs a macOS permission, Personal Jarvis asks right then and macOS shows its own dialog: the microphone at the first dictation, push-to-talk, voice conversation, wake-word switch or microphone check; Screen Recording at the first screen capture you start; Accessibility when Jarvis first has to type, click or focus a window for you; Input Monitoring when you save a global shortcut (or choose the Call shortcut in setup); Music and Spotify control when you switch on "Mute music while dictating" with a player running. Nothing is asked at launch, and Personal Jarvis draws nothing of its own around macOS's dialog. If you say no, only that feature stops, and one short toast says so with one action ("Open System Settings"). Checked against faked macOS frameworks and macOS CI runners, not yet on a Mac of your own.
+- **One short toast after a macOS "no", in English, German and Spanish.** macOS never asks twice and says nothing after a denial, so when a feature you started is blocked by a permission, the app shows one sentence in its normal toast with one action: "Open System Settings", "Ask macOS now" (a development run outside the installed app) or "Quit and reopen" (access is on but needs a restart). It shows once per problem and again whenever you try the feature again after dismissing it, in the main desktop window only, and never for background work; the one exception is the wake word, which you switched on and which tells you once per session when it cannot listen. There is no permissions page, banner, card or inline note.
+- **`jarvis permissions reset <permission>`.** Forgets what macOS recorded for the installed Personal Jarvis app (the downloaded app or the installer's app, or `--bundle-id` for the other one) so macOS asks again on next use. It runs `tccutil` on your Mac behind `--yes`, never touches another app, and prints one line and exits with an error on other systems. The raw `tccutil` commands are in the troubleshooting guide.
+- **macOS permission dialogs in German and Spanish.** New builds of the downloaded app and fresh installs of the installer's app carry German and Spanish versions of the text macOS shows in its permission dialogs (the Apple Events and folder sentences are shorter and name no single app); an installer's app already on your Mac gets them the next time it is rebuilt for another reason, because the bundle version is deliberately not bumped (a bump would reset its permissions). Whether a Mac shows them is not yet tried on a Mac of your own.
+- **Honest checks for silent macOS failures.** A flat wallpaper-only screen capture is refused instead of handed to the model, and five seconds of exact-zero microphone audio produce one "denied or muted" notice. Computer Use pauses while a macOS permission dialog is in front, so an agent never answers one.
+- **A dispatch-only macOS hotkey spike.** A manually started workflow records, on Intel and Apple Silicon runners, whether the native Carbon hotkey calls crash the process. It changes no shipped behaviour.
+
+### Changed
+
+- **Global shortcuts need only Input Monitoring on macOS.** The listen-only shortcut tap no longer also requires Accessibility, is not started at launch unless already allowed, and re-arms in place when you grant access. A restart is suggested only after real typing produced no events, never forced.
+- **macOS permissions are checked silently and read live.** Features check the grant without prompting and act only on a live "granted"; a native request's result is never treated as proof. Identity now decides only who may ask automatically and who may reset, so a terminal-launched run asks for nothing on its own and offers an explicit "Ask macOS now" confirmation in the toast.
+- **The macOS bundles carry one table of usage strings.** The camera, speech and system-administration keys and the camera entitlement, which nothing in Jarvis uses, are removed; Screen Recording, Apple events, Desktop, Documents, Downloads and volumes are described in one place for both the `.dmg` app and the managed app.
+- Scheduling lives on agent routines; the separate Automations section is retired.
+- Routines can be created, paused, resumed or test-run by voice without a second confirmation.
+
+### Removed
+
+- **The Settings > Privacy page, the permission card and every inline permission note.** The floating card, the notes in dictation, the wake-word panel, mute-music, Shortcuts, Appshots and voice chat, the "Enable global shortcuts" buttons and tip, the "Mic blocked" line in the sidebar and the Privacy entry in Settings are gone (about 170 translated strings per language); macOS's own dialog and the one toast above replace them. The global-shortcut status that served the Shortcuts note is removed from the keybinds API too.
+- **The permissions banner, "Set up everything" and the setup permissions step.** The app-wide warning banner and its "Not now", the Optional and wanted-row bookkeeping, the guided wizard with its automatic restart, the refresh event and the onboarding permissions step are gone, along with the Music and Spotify consent file and the hidden launch of those apps, the "macOS treats the app as new" identity note and the global restart-required flag. Old leftovers on disk are never read and never prompt; the source installer deletes the two leftover state files on its next run, the downloaded app leaves them in place (harmless).
+
+### Fixed
+
+- **macOS: the wake word, dictation and Computer Use no longer sit dead behind a permission check that never asked macOS.** Protected features used to refuse until the app's own check said "granted", so on a Mac that had never answered a dialog macOS was never asked from the feature, and only a banner, Settings buttons or setup could raise it. The features now ask macOS themselves (see Added). Checked against faked macOS frameworks, not yet on a Mac of your own.
+- **macOS: the downloaded app is recognised as an installed app.** The `.dmg` app was never accepted as one, so (checked against faked macOS frameworks, not yet on a Mac) its microphone, shortcuts and Computer Use stayed disabled even with every permission granted, and no Allow button was offered. It is now recognised, `jarvis permissions` finds it, and `jarvis permissions reset` targets its own permission records.
+- **macOS: the downloaded app is built to be able to use its permissions.** The v2.5.0 image (read on Linux, not run on a Mac) was missing the microphone framework in its frozen archive and was marked background-only in its `Info.plist`. The build now includes the framework, clears the flag, and new checks fail the macOS job if either comes back — including one that boots the built app and asks it for its microphone permission. Built and checked on both macOS CI runners (Apple Silicon and Intel); not yet tried on a Mac of your own.
+- **macOS: the release workflow is prepared to sign and notarize the image.** `packaging/macos/build.sh` now imports the Developer ID certificate secrets the workflow already passed along (rehearsed and run against a stand-in keychain command, not yet end to end). Until the Apple secrets are added the image stays ad-hoc signed: the first launch needs Open Anyway and an update can ask for the permissions again.
- A quiet, Claude-style front page: one greeting, one composer, and a voice mode that lives inside the chat with a flowing aurora glow.
- Open any agent's chat on the front page from the sidebar; `@` in the Jarvis chat names your agents and connected plugins.
- Reasoning traces drawn as a threaded rail, with a wider, calmer column for agent chats.
@@ -21,14 +47,6 @@ versioning per [SemVer](https://semver.org/).
- Onboarding: the pet walks you through the app right after setup, then offers ten first steps.
- Routines and chat channels keep running after the app window closes.
- Jarvis can drive the Agentic IDE by voice and open coding agents in a named workspace.
-
-### Changed
-
-- Scheduling lives on agent routines; the separate Automations section is retired.
-- Routines can be created, paused, resumed or test-run by voice without a second confirmation.
-
-### Fixed
-
- Dictation works during a live call instead of hanging it up.
- A new agent's first prompt in the Agentic IDE is reliably submitted.
- Light-mode terminal panes are crisp and readable.
diff --git a/README.md b/README.md
index 166bf4daf7..440b12430c 100644
--- a/README.md
+++ b/README.md
@@ -41,6 +41,12 @@ your setup, permissions, and the tools you connect.
[macOS (Intel)](https://github.com/PersonalJarvis/PersonalJarvis/releases/latest/download/PersonalJarvis-macOS-x64.dmg) ·
[Linux AppImage](https://github.com/PersonalJarvis/PersonalJarvis/releases/latest/download/PersonalJarvis-Linux-x86_64.AppImage)
+> **macOS:** the downloaded disk image is not Apple-notarized yet, so the first
+> launch needs **System Settings > Privacy & Security > Open Anyway** (macOS 15;
+> right-click > Open works up to macOS 14), and an update can ask for the macOS
+> permissions again. The one-line installer below builds the app on your Mac, so
+> it needs no Open Anyway step.
+
Prefer the command line? Use the installer below.
**Windows — PowerShell**
diff --git a/docs/BUGS.md b/docs/BUGS.md
index d2225ecbd2..c23598e182 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -4201,6 +4201,14 @@ never one dialog at a time.
## BUG-058: Third macOS first-boot abort at onboarding start — unserialized PortAudio re-init + ungated Quartz event tap (HIGH, HARDENED 2026-07-14, on-device confirmation pending)
+> **Superseded in part by BUG-225 (2026-10-02).** The class rule at the end of this entry ("any
+> macOS permission-gated native surface must preflight a non-prompting probe and
+> degrade honestly") is narrowed: it still holds for the event tap (the tap is
+> created only after `CGPreflightListenEventAccess()` is true, never to provoke a
+> prompt) and for a missing usage string (checked before a native request), but a
+> preflight must never refuse a feature before the OS was asked (AP-35, ADR-0038).
+> The history below is kept as written.
+
**Symptom.** With BUG-056+057 shipped, a fresh Mac boot now shows the
desktop window and enters first-launch onboarding — then "Python quit
unexpectedly" again, seconds in, before any meaningful interaction. No
@@ -5728,6 +5736,14 @@ unexplainable early abort.
## BUG-083: macOS permissions "auto-denied" after an app update, Settings deep links landing on the wrong pane, and a dead second Allow button (HIGH, FIXED 2026-07-18)
+> **Superseded in part by BUG-225 (2026-10-02).** The in-app request path described here (the
+> Allow buttons, the per-row "Ask again", the Settings deep-link rule, the
+> restart gating) is now the just-in-time service
+> `jarvis/platform/permission_service.py`; the rebuild keeps the live reads, the
+> own-bundle `tccutil reset` and the quit-System-Settings-before-a-deep-link rule,
+> and drops the "can_request is false while a restart is pending" machinery. The
+> history below is kept as written.
+
**Symptom (live Intel test Mac, macOS 15.7, first run after the v1.0.11
update).** The onboarding permissions view showed Input Monitoring and Input
Control as DENIED although macOS never showed a prompt; Microphone had
@@ -11109,6 +11125,16 @@ chat hook already ran the `TriggerMatcher` and were never affected.
## BUG-159: macOS permissions read as missing although System Settings shows them enabled — a sticky restart flag, a hidden recovery, and a silent grant-wiping rebuild (HIGH, FIXED 2026-08-20)
+> **Superseded in part by BUG-225 (2026-10-02).** Cause 1 (the sticky pending-restart flag and the
+> global `restart_required`), the readiness aggregate (`features[...].ready`),
+> fix (d) (the `identity_reset` marker file and its note), fix (f)
+> (`_reset_or_explain()`, which wiped the grants once per unresolved round) and the
+> banner and wizard renderings of `can_reset` no longer exist: a restart is only a per-row hint
+> produced after a real failed attempt, the snapshot carries no readiness or
+> identity-reset keys, and a rebuild that changes nothing needs no note. The
+> `can_reset` capability and the own-bundle reset stay (served on Settings >
+> Privacy and the permission card). The history below is kept as written.
+
**Symptom (maintainer's Mac, reported 2026-08-20).** Every start warned that
macOS permissions were not enabled. Clicking the warning's button opened
System Settings, where the permission was already switched ON. Toggling it off
@@ -11279,6 +11305,14 @@ the facts handed to the composer carry the content and never the URLs).
## BUG-161: macOS permissions still read as missing after BUG-159 — every start rebuilt the app bundle, and a copy in /Applications was treated as a stranger (HIGH, FIXED 2026-08-21)
+> **Superseded in part by BUG-225 (2026-10-02).** The banner referred to here no longer exists.
+> The "canonical location" rule (both `~/Applications` and `/Applications`) survives as one
+> input to `stable`, but `stable` now decides only whether Jarvis may ask automatically and
+> whether it may reset, never whether a feature may act (AP-35 principle 6). The finding that TCC pins a grant to the
+> bundle id and signature, never to a path, is what the rebuild relies on. The live
+> window-title proof for Screen Recording stays (still unverified on a Mac). The
+> history below is kept as written.
+
**Symptom (maintainer's Mac, reported 2026-08-21).** The app kept asking for
permissions it had already been given. Granting them again changed nothing;
neither did a restart. This is BUG-159's symptom surviving BUG-159's fix,
@@ -12654,6 +12688,10 @@ policy as well, so the app does not depend on every shell agreeing with it.
## BUG-181: clicking Restart sometimes only shut the window down (HIGH, FIXED 2026-08-25)
+> **Superseded in part by BUG-225 (2026-10-02).** The permissions banner named in the symptom was
+> removed (no restart control lives in a permission banner any more); the restart
+> machinery this entry fixes is unchanged.
+
**Symptom.** Click Restart (top bar, Settings, the permissions banner). The
window closes. Sometimes nothing comes back. A Start-menu click later starts
it normally. Intermittent: the same button often works.
@@ -15281,6 +15319,15 @@ blocks `lsregister`), `tests/unit/diagnostics/test_doctor_diagnostics.py`
## BUG-217: macOS asked for every permission again after each rebuild, and the Music prompt never stuck (HIGH, FIXED 2026-09-16)
+> **Superseded in part by BUG-225 (2026-10-02).** The Automation **consent file**
+> (`macos-automation-consent.json`), the **hidden launch** of a closed Music or
+> Spotify, and **Set up everything** with its automatic restart are removed:
+> Automation is asked once, when the user switches "Mute music while dictating" on
+> while a player is running, through the killable consent runner (120 s), and a
+> grant is re-read live per send. Root causes 1 and 2 (the certificate identity,
+> `AppleEvents` in the reset sweep, the 120 s wait) and the `/Applications`
+> follow-up stand. The history below is kept as written.
+
**Symptom.** After an update or reinstall, Personal Jarvis asked for
Microphone, Screen Recording, Accessibility, Input Monitoring and Input
Control all over again. The "Music / Spotify" Automation dialog appeared in
@@ -15513,3 +15560,365 @@ plain daemon worker through a `queue.SimpleQueue` (documented reentrant and
safe in destructors); `__del__` only enqueues and takes no lock. The worker is
started in ordinary code (`LockedRecognizer.__init__`, `release_recognizer`).
Guard: `tests/unit/plugins/wake/test_vosk_native.py::test_dropping_the_proxy_inside_an_executor_submit_does_not_deadlock`.
+
+## BUG-222: the downloaded macOS app could not use a single permission — it was never accepted as "the installed app", it shipped without the microphone framework, and its Info.plist said background-only (HIGH, FIXED 2026-10-01; built and booted on macOS CI runners, not yet tried on a user's Mac)
+
+> **Superseded in part by BUG-225 (2026-10-02).** The identity fix stands (`ACCEPTED_BUNDLE_IDS`,
+> the own-id reset, the packaging fixes and the frozen-app probe), but its premise
+> that a wrong identity "disables the whole permission surface" is gone: identity
+> now decides only who may ask automatically and who may reset, never whether a
+> feature may act (AP-35 principle 6). The `identity_ready`, `can_request` and
+> "no request button means no way to be asked" wording describes the removed
+> readiness model. The history below is kept as written.
+
+**Symptom (the identity part reproduced against the port with faked macOS
+frameworks; none of it observed on a Mac).** Run as the `.dmg` app with every
+grant present, the permission screens read every feature "not ready", refuse
+microphone capture (wake word and voice dead), tell the user to relaunch the app
+from its installed location — where it already is — and offer no **Allow** or
+**Open Settings** button. With no request button, a user has no in-app way to be
+asked at all, and enabling the app by hand in System Settings would not change
+the verdict.
+
+**Cause, three layers.** The first is code; the other two were read off the
+published v2.5.0 arm64 image (extracted and opened on Linux — its `Info.plist`,
+and the module table of the archive frozen into its executable, read with
+PyInstaller's own reader):
+
+1. **Identity.** `SystemPermissionPort` accepted exactly one bundle id,
+ `com.personal-jarvis.desktop`, the managed local bundle. The `.dmg` build
+ (`jarvis.spec`) has its own id, `ai.personaljarvis.desktop` — deliberately
+ different, because BUG-218 keeps the managed installer from rebuilding over
+ it. Run against the port with every grant present, the `.dmg` identity gave
+ `stable=False`, all six features `identity_ready=False`,
+ `runtime_access_granted(microphone)` false and every `can_request` /
+ `can_open_settings` false. The gate fails closed by design (granting Terminal
+ or a bare Python would be unsafe), so one wrong constant disabled the whole
+ permission surface — and nothing ever ran the port as the `.dmg` app.
+2. **No `AVFoundation` in the frozen app.** The port loads its frameworks by
+ NAME (`SystemPermissionPort._load("AVFoundation")`), which PyInstaller's
+ static analysis cannot follow, and the macOS job installed `.[desktop,dev]`
+ without the `desktop-macos` extra that carries `pyobjc-framework-AVFoundation`
+ (no other direct dependency requires it), so there was nothing on the build
+ machine for a hidden import to collect either. The published image's module
+ table has no `AVFoundation`. By the code path the microphone permission then
+ reads "unavailable" for good, and the voice gate has nothing to open on.
+3. **`LSBackgroundOnly` in the published `Info.plist`.** PyInstaller sets it to
+ true whenever the last executable of the `COLLECT` is a console one, and the
+ `jarvis` CLI is. LaunchServices reads the key as "this app has no Dock icon,
+ no menu bar and no windows". Whether the published app showed its window
+ regardless has not been observed.
+
+No headless smoke run can see layers 2 and 3: it starts the executable directly
+instead of the way a user does.
+
+**Fix.**
+
+- `jarvis.core.branding.MACOS_DMG_BUNDLE_ID` names the second legitimate
+ identity; `permissions.ACCEPTED_BUNDLE_IDS` is what the identity gate, the
+ `jarvis permissions` CLI and the UI's "expected id" now use. Anything else
+ (Terminal, Python, an app that merely shares the name) is still refused.
+- `tccutil reset` targets the id of the app that is RUNNING, and `reset` refuses
+ outright from any process that is not the installed app (it used to fall back
+ to the managed id, which would have wiped the rows of a different app). It is
+ scoped to one bundle id, so resetting the managed id would have left the
+ `.dmg` app's own rows untouched (the documented behaviour of `tccutil`; not
+ observed).
+- `jarvis permissions request|open-settings` find the `.dmg` app instead of
+ reporting "app not found" (`installed_macos_app_bundle_path`).
+- `jarvis.spec` collects `AVFoundation` on macOS and sets `LSBackgroundOnly` to
+ `False` explicitly; the macOS job installs `.[desktop,desktop-macos,dev]`.
+- `scripts/ci/check_frozen_macos_app.py` runs on the built `.app` in the macOS
+ job and fails the build when the bundle id is not the accepted one, the plist
+ is background-only, the executable or the microphone usage string is missing,
+ or the frozen archive lacks one of `AVFoundation`, `ApplicationServices`,
+ `AppKit`, `Foundation`, `Quartz`, `objc`. Run by hand against the published
+ v2.5.0 arm64 image it exits 1 and names exactly the two defects above.
+- The frozen smoke (`scripts/ci/check_frozen_browser.py`) boots the app on macOS
+ and asks it for `/api/permissions/status`: a microphone row that reads
+ "unavailable", or a bundle id the port does not accept, fails the job. This is
+ the only check that sees a framework whose own dependencies were left out of
+ the archive, because the port swallows an import that fails at run time.
+
+**Guards.** `tests/unit/platform/test_permissions.py` (the `.dmg` identity is
+stable and gets its buttons back, foreign ids are refused, reset hits the right
+id and refuses from a stranger), `tests/unit/setup/test_macos_dmg_identity.py`
+(the literal in `jarvis.spec` equals the branding constant, the two ids stay
+distinct, the lookup), `tests/unit/cli_ctl/test_commands_permissions.py`,
+`tests/unit/ci/test_check_frozen_macos_app.py`,
+`tests/unit/packaging/test_frozen_browser_smoke.py` (the decision, and `boot()`
+itself against a stand-in app).
+
+**Verification.** Unit level on Linux, against faked AppKit / Quartz /
+AVFoundation: the new `.dmg` tests fail on the old code, and the probe fails on
+the published image. On macOS CI runners: a branch dispatch of "Desktop
+installers" (run 36923225371, commit 43eeb7ae, no release published) built the
+image with the new `jarvis.spec` and `desktop-macos` extra on both the Apple
+Silicon (`macos-15`) and the Intel (`macos-15-intel`) runner; on both,
+`check_frozen_macos_app.py` passed, and the smoke booted the frozen app twice and
+read its permission status from it: microphone `granted`, bundle id
+`ai.personaljarvis.desktop` — so AVFoundation loads inside the app and the
+published image's "unavailable" is gone. The `granted` itself reflects the hosted
+runner's setup, not a user's decision. A first dispatch on the commit before the
+booted-app check existed (run 36922688589, arm64 only, cancelled afterwards)
+passed the same build and probe. **Not verified:** anything on a user's Mac —
+the window and Dock behaviour with `LSBackgroundOnly` off (the smoke starts the
+executable directly, not through LaunchServices), the permission prompts
+themselves, Gatekeeper and notarization (the runs were ad-hoc signed: no Apple
+secrets).
+
+**Known limits, not changed here.** `Contents/MacOS/jarvis` (the CLI inside the
+bundle) resolves to the same main bundle, so started from a terminal it would be
+read as the app although macOS attributes that process to the terminal — the
+same for the managed bundle. The Control key's Keychain-ownership migration
+(`jarvis/core/control_key.py`) recognises only the managed bundle id, so for the
+`.dmg` app that step is skipped and an item created by an earlier ad-hoc build
+may ask once more (read from the code; not observed).
+
+**Class rule.** A fail-closed identity gate needs a test that runs it as EVERY
+shipped identity. An id duplicated in a build spec that cannot import the
+constant needs a parity test, or it drifts silently. A module a runtime loads by
+NAME is invisible to a freezer: assert it in the built artifact, not in the
+source.
+
+## BUG-223: every public macOS download was ad-hoc signed — the first launch was blocked and every update forgot every grant (HIGH, FIXED IN CODE 2026-10-01; signing still needs the maintainer's Apple account)
+
+> **Superseded in part by BUG-225 (2026-10-02).** The signing finding stands (a Developer ID
+> signature is what lets grants persist across updates; the path has still never
+> run). References to the re-ask explanation note ("macOS treats the app as new")
+> describe the removed `identity_reset` note. The history below is kept as
+> written.
+
+**Symptom.** The `.dmg` behind the README's macOS link opens with "Apple cannot
+check it for malicious software", and after each update the app asks for every
+permission again.
+
+**Evidence.** The v2.5.0 "Desktop installers" run, macOS arm64 job, printed:
+
+ NOTICE: APPLE_SIGNING_IDENTITY is not set - ad-hoc signing this build. It is
+ NOT notarized; macOS will refuse the first double-click ...
+ codesign --force --deep -s - .../Personal Jarvis.app
+ NOTICE: this build is ad-hoc signed and unnotarized - suitable for local
+ testing, not for public download.
+
+and that build is the published asset.
+
+**Cause, two layers.**
+
+1. No Developer ID identity is configured: that needs an Apple Developer Program
+ membership and its credentials, which only the maintainer can provide.
+2. Configuring it would not have worked. The workflow passed
+ `APPLE_CERTIFICATE_P12_BASE64` / `APPLE_CERTIFICATE_PASSWORD` to `build.sh`,
+ which never read them; a GitHub runner starts with an empty keychain, so
+ `codesign --sign "Developer ID Application: ..."` could only fail.
+
+An ad-hoc signature is a hash of the app's bytes, and macOS pins every privacy
+grant to it: each release is a stranger and its grants are gone (BUG-083,
+BUG-217). A Developer ID signature gives the app one identity — Team ID plus
+bundle id — across versions, so its grants can persist. (BUG-218 calls the
+`.dmg` build "notarized": it is built to be, but every image published so far is
+ad-hoc.)
+
+**Fix.** `packaging/macos/build.sh` imports the certificate into a throw-away
+keychain when both secrets are present, reads the signing identity from it when
+`APPLE_SIGNING_IDENTITY` is not given, and does all of that BEFORE the web bundle
+and the ~12-minute freeze, so a certificate that cannot be used fails in
+seconds. An exit trap removes the decoded certificate file, puts the user
+keychain search list back (captured before the throw-away keychain is created)
+and deletes the keychain — also after a failed import. No secret reaches the
+log. Without secrets nothing changes. **Still open, by nature:** the Apple
+secrets (five required, `APPLE_SIGNING_IDENTITY` optional;
+`docs/desktop-installers.md` §4) have to be added before a build can be signed
+and notarized, and that path has never run.
+
+**Guards.** `tests/unit/packaging/test_macos_build_script.py` rehearses the
+script with `DRY_RUN=1` in a scratch copy of the layout (unchanged ad-hoc path
+without secrets, import order, no secret in the output, early refusal) and runs
+the REAL import branch against a stand-in `security` command: call order, the
+identity read back from the certificate, search list restored and keychain
+deleted on success and on failure, no certificate file left behind.
+
+**Verification.** Off a Mac only: `bash -n`, ShellCheck `-S style`, the tests
+above. They were also run under GNU bash 3.2.39 — the macOS shell's series (macOS
+itself ships 3.2.57), taken from an old Ubuntu package because this sandbox has
+neither a Mac nor Docker: `scripts/ci/check_shell_bash32.py --require` parses
+every tracked script, and the 12 build-script tests execute `build.sh` under it.
+Not run: a real keychain, `codesign`, `notarytool`, `stapler`, or anything on
+macOS itself.
+
+## BUG-224: macOS asked for Music and Spotify control — and opened both apps — for a feature that is off (MEDIUM, FIXED 2026-10-01, unit-tested only)
+
+> **Superseded by BUG-225 (2026-10-02).** `wanted`,
+> `features[...].active`, `active_features()`, the "Optional" tag, the banner's
+> "Not now" and the refresh event no longer exist. The over-asking they patched is
+> removed at the root: a feature the user has not switched on never touches its
+> permission (principle 7), and Automation is asked only by switching "Mute music
+> while dictating" on. The history below is kept as written.
+
+**Symptom (from the code paths of BUG-217's guided flow; not yet observed on a
+Mac).** "Set up everything" and the app-wide banner demanded the Automation
+(Music & Spotify) permission on every Mac — Music ships with macOS — started
+Music (and Spotify, when installed) hidden to show the consent dialog, and kept
+the banner on screen until it was answered, although "Mute music while
+dictating" is opt-in and off by default.
+
+**Cause.** `FEATURE_REQUIREMENTS` marked every permission needed by some
+feature as missing, whether or not the user had turned that feature on.
+
+**Fix.** The snapshot carries the policy: `features[...].active` and
+`permissions[...].wanted` (a feature the user has turned on needs it).
+`permissions.active_features(config)` switches `audio_ducking` off while
+`[ducking].enabled` is false; the routes derive it from the live configuration
+and hand it to every operation, so the status and each request/reset/open
+response agree. The banner, the guided "Set up everything" flow and the
+Settings poll consider only wanted rows; Settings still lists every row, with
+an "Optional" tag, so it can be allowed by hand. The banner also gained
+"Not now": per row, expiring after a week (re-read at every status refresh, so
+a window that stays open for days still brings it back), and a row that turns up
+later (a feature switched on afterwards) shows again; when the browser storage
+refuses the write the choice is kept in memory for that window. Switching "Mute
+music" on or off asks every open permission view to re-read the status, so the
+Automation row follows the switch without waiting for a focus event. The "macOS
+treats the app as new" note retires when the WANTED grants are back — an
+Automation row nobody asked for no longer keeps it alive.
+
+**Guards.** `tests/unit/platform/test_permissions.py` (policy, shared
+permissions stay wanted, operations report the same policy, the note retires),
+`tests/unit/ui/web/test_permissions_routes.py`, `usePermissions.test.tsx`
+(an optional row does not poll), `useMuteMusic.test.tsx`,
+`PermissionsAlertBanner.test.tsx` (expiry on refresh, unwritable storage, a
+restart that stays visible), `PermissionsPanel.test.tsx`,
+`src/lib/permissionsBannerDismissal.test.ts`.
+
+**Verification.** Unit tests with faked native frameworks, vitest, a production
+build and a light/dark look at the banner and the rows in Chromium on Linux.
+Nothing was run in the macOS desktop app.
+
+
+---
+
+## BUG-225: macOS was never asked — every protected feature refused behind the app's own permission check, so a banner, a wizard and a restart machine grew around the missing dialog (HIGH, FIXED IN CODE 2026-10-02; not yet exercised on a physical Mac)
+
+**Symptom (class: a preflight wall in front of the OS ask).** On a Mac that had
+never answered a dialog, the wake word was dead, dictation said microphone access
+was "not ready", computer use and global shortcuts refused, and no macOS dialog
+ever appeared from using the feature. The only road to a dialog was the app's own
+UI: an app-wide banner, **Set up everything** in Settings, and an onboarding step.
+The same wall produced the reports of BUG-159, BUG-161, BUG-222 and BUG-224: a
+banner that stayed although the switch was on, features dead for the whole session
+with every grant present, a whole surface disabled by one wrong identity constant,
+and Music and Spotify opened hidden for a feature that was off. The user's own
+words quoted in the history ("the permissions are extremely annoying") describe the
+result.
+
+**Cause.** `SystemPermissionPort.runtime_access_granted()` was true only for a
+stable bundle identity AND an already-granted probe, and every feature path asked it
+before touching the OS API (`audio/capture.py`, `cu/actuate/base.py`,
+`cu/capture.py`, `trigger/backends/quartz.py`, `platform/window_state.py`,
+`screen_context`, `vision/*`, dictation insert, the voice activation gate). For a
+permission in `not_determined` the answer was no, so the feature raised before the
+microphone, the tap or the capture was opened and macOS never got the chance to show
+its own dialog. The frozen plan said the opposite (AD-13: probe at first use, degrade,
+never hard-block); the shipped code inverted it on 2026-07-15 without a recorded
+decision (reconstruction in `docs/macos-permissions.md` section 2). Each later layer
+repaired a symptom of the wall instead of removing it: banner, dead-Allow fixes, sticky
+restart flag, identity-reset note, wizard with auto-restart, Automation consent file,
+`wanted` flag, "Not now". The wall also cost time on hot paths (per-frame, per-keystroke
+and per-0.25 s probes; a tap callback that overran its deadline and was disabled).
+
+**Fix (stages, all revertible).**
+
+- `jarvis/platform/permission_service.py` is the single just-in-time layer: `check`
+ (silent, never prompts) and `ensure` / `ensure_async` / `ensure_all` (interactive, only
+ from a user gesture), one coalesced episode per (pane family, feature), a backend
+ watcher that publishes `PermissionResolved` on a grant, and the `PermissionNeeded` /
+ `PermissionResolved` events (AP-4 parity). Off macOS it returns NOT_REQUIRED before
+ touching the port. Consumers receive it through the `PermissionGate` protocol.
+- Features ask at their gesture: microphone at dictation, push-to-talk, a voice session,
+ the wake-word switch and the mic self-test; Screen Recording at the first
+ user-started capture; Accessibility when Jarvis first types, clicks or focuses;
+ Input Monitoring when the user saves a global shortcut (a background listener has no
+ "on use" moment; `PUT /api/settings/keybinds` asks, the onboarding Call-shortcut click asks
+ once); Automation when the user switches "Mute music while dictating" on with a player
+ running. Helpers `check()` and
+ degrade; the computer-use engine keeps one silent Screen Recording gate and pauses
+ while a macOS consent window is frontmost.
+- Silent-failure traps are checked at the source: a flat wallpaper-only frame while the
+ state claims granted, five seconds of exact zeros from the microphone while granted.
+- Deleted: the banner and its dismissal store, the wizard and polling, the refresh
+ event, the onboarding `permissions` step, `features` / `wanted` / `active` /
+ `identity_reset` / `restart_required` / `foreground` in the snapshot, the Automation
+ consent file and hidden launch, the identity-reset marker. Packaging got one usage-string
+ table and lost the camera, speech and system-administration keys.
+- AP-35 and ADR-0038 record the rule; `docs/macos-permissions.md` is the design, the
+ evidence table and the manual Mac checklist.
+
+**Prevention (AP-35).** A feature asks the OS at first use from a user gesture through
+the service. No code path may refuse because our own preflight says "not granted"
+before the OS was asked, and none may act on a permission the OS has not granted
+(`EnsureResult.granted` only for GRANTED / NOT_REQUIRED; a native request's return value
+is never evidence). Nothing is asked at launch (boot rule), denied is a stable state with
+one toast and one click to the pane, identity decides who may ask and reset but not whether a feature may
+act, an opt-in feature owns its permission, and an agent never answers a system dialog
+(routine triggers exclude both permission events; no agent tool exposes ensure, request,
+open-settings or reset). Review rule: a new macOS-gated feature that adds its own
+"is it granted" refusal ahead of the OS ask, a banner, a wizard or a persisted "asked"
+flag is this bug again.
+
+**Guards.** `tests/contract/test_permission_service_contract.py` (scenario table on a
+macOS-shaped and a non-macOS host), `tests/unit/platform/test_permission_service.py`,
+`test_permission_service_hardening.py` and `test_permission_service_status_helpers.py`
+(episodes, cooldowns, no second native request), `tests/fakes/fake_tcc.py` with
+`tests/unit/platform/test_fake_tcc.py` (a stateful TCC simulator with an ordered call
+log), `tests/unit/platform/test_no_legacy_permission_api.py` (a ratchet: the deleted
+wall, its readiness aggregate, the identity-reset marker and the Automation consent
+file must not return to `jarvis/`, `scripts/` or `.github/`),
+`tests/unit/platform/test_permission_characterization.py` (what must survive; its last
+test fails if a `test_legacy_*` test, one that would pin the removed wall, comes back),
+`tests/unit/platform/test_permission_agent_boundary.py` and
+`tests/unit/cu/test_permission_not_agent_exposed.py` (no agent-facing tool),
+`tests/unit/platform/test_screen_access.py` and `tests/unit/cu/test_capture_permissions.py`
+(a wallpaper-only frame is refused; a failed use is reported),
+`tests/unit/speech/test_voice_permission_jit.py` (first press makes exactly one
+microphone request, a denied press adds none, boot with every permission undecided asks
+nothing, an upgrader sees zero cards, a non-macOS host consults nothing),
+`tests/unit/audio/test_capture_permission_gate.py` (the microphone is asked once at open,
+no per-frame probe), `tests/unit/audio/test_ducking_permissions.py` (only switching on
+asks), `tests/unit/dictation/test_insert_permission.py`,
+`tests/unit/trigger/test_quartz_jit_permissions.py` (no tap before the preflight is true),
+`tests/unit/screen_context/test_service_permissions.py`,
+`tests/unit/core/test_permission_events.py` (event vocabulary),
+`tests/unit/ui/web/test_permissions_routes.py` and `test_permissions_snapshot.py`
+(snapshot v2 never prompts), `tests/unit/ui/test_desktop_macos_permission_gate.py`,
+`tests/unit/ci/test_macos_desktop_permission_step.py` (the macOS lane's permission
+scripts run against FakeTCC so a step cannot rot into one that always passes), and the
+frontend `permissionToast.test.ts` (the toast planner; the earlier card, inline-note and
+Privacy-page tests were deleted with their UI, see the note below).
+
+**Follow-up note (2026-10-02, UI reset).** The custom UI this fix first shipped (a floating card,
+inline notes in five places, a Shortcuts status note and tip, the Settings > Privacy page and its
+"Ask again") was judged unfit by the user and deleted: macOS shows its own dialog and the app adds
+ONE toast with one action after a user-started use failed (`PermissionNeeded`, `origin="user"`,
+`phase="blocked"`, owner window, once per episode and again on the next try; the wake word tells a denied microphone once per
+session). The service, routes, snapshot v2, events and the boot rule are unchanged. Input Monitoring
+is asked when a shortcut is saved; the way back from a stuck "denied" is the switch in System
+Settings or the local `jarvis permissions reset <permission>` (macOS only; the HTTP reset route
+still refuses scripts). The Info.plist strings became target-neutral and gained German and
+Spanish `InfoPlist.strings` in both bundles. Details: ADR-0038 "Amendment: the UI is reduced to a
+toast". Prevention addition: a new permission surface of our own around the OS dialog (card, note,
+status page, up-front screen) is this bug's UI twin again. Guards added:
+`tests/unit/ui/web/test_keybinds_input_monitoring_ask.py`,
+`tests/unit/cli_ctl/test_commands_permissions.py` (reset), `tests/unit/packaging/test_macos_privacy_strings.py`
+(localisations) and `tests/unit/ci/test_check_frozen_macos_app.py`.
+
+**Verification.** Fake-framework unit and contract tests, vitest, Linux static gates, and
+macOS CI runners for the packaging and frozen-app probe (ad-hoc signed; a runner is not a
+user's Mac: it pre-grants TCC to its tools and shows no dialog). **Not verified, because
+nothing ran on a physical Mac:** every real dialog and its wording, whether a running
+process sees a new Screen Recording grant, hold-key semantics, the notarized build, macOS
+26 and 27, the second dialog in the embedded WebView, and the Appshot both-Option
+permission need. The rows to close these are in `docs/macos-permissions.md` section 7.
+
+**Related.** BUG-058, BUG-083, BUG-159, BUG-161, BUG-217, BUG-222, BUG-223, BUG-224
+(each carries a "superseded" note), ADR-0038, `docs/os-parity.md`,
+`docs/product/privacy-safety-and-support/permissions.md`.
diff --git a/docs/LLM-CONTEXT.md b/docs/LLM-CONTEXT.md
index 7f21873544..7d21250908 100644
--- a/docs/LLM-CONTEXT.md
+++ b/docs/LLM-CONTEXT.md
@@ -576,7 +576,7 @@ Line length 100. Target `py311`.
## 21. ADR + Phase doc index
-**ADRs in `docs/adr/`** (18 files; duplicate-number cleanup pending):
+**ADRs in `docs/adr/`** (38 files; duplicate-number cleanup pending; the list below covers ADR-0001 to ADR-0015 only):
- ADR-0001 — IPC Named-Pipe HMAC (Admin-Helper)
- ADR-0002 — UIA Tree Pruning (Vision)
diff --git a/docs/adr/0038-macos-permissions-ask-when-needed.md b/docs/adr/0038-macos-permissions-ask-when-needed.md
new file mode 100644
index 0000000000..e7ed071a43
--- /dev/null
+++ b/docs/adr/0038-macos-permissions-ask-when-needed.md
@@ -0,0 +1,328 @@
+# ADR-0038 — macOS permissions are asked for when a feature needs them
+
+**Status:** Implemented on the branch that introduces it; **not yet exercised on a
+physical Mac**. The behaviour is proven against fake frameworks and Linux gates; the
+macOS runners have run the .dmg packaging probe and the hot-key spike (a macOS lane
+step list that also covers the permission tests was extended later and has not been
+run yet). See "Verification status".
+**Amended 2026-10-02:** the custom permission UI of this change (card, inline notes, Settings >
+Privacy page) was deleted and replaced by one toast; see "Amendment: the UI is reduced to a toast"
+at the end. The rule, the service and the events are unchanged.
+**Date:** 2026-10-02
+**Reference:** AP-35 (`AGENTS.md`); `docs/macos-permissions.md` (full design, evidence,
+risk register and the manual Mac checklist); BUG-225 (`docs/BUGS.md`); supersedes
+the permission behaviour described in BUG-159, BUG-161, BUG-217, BUG-222, BUG-223
+and BUG-224; revives frozen decision AD-13 of the cross-platform plan.
+
+## Context
+
+Before this change the app put a wall of its own in front of macOS. Every protected
+feature (microphone capture, computer-use input and capture, global shortcuts,
+window control, screen context, dictation paste) asked
+`SystemPermissionPort.runtime_access_granted()` first. That call was true only for a
+stable bundle identity AND an already-granted probe. When it said no, the feature
+refused before touching the operating system. macOS was therefore never asked from a
+feature path. The only route to a system dialog was the app's own UI: an app-wide
+banner, a Settings wizard ("Set up everything") and an onboarding step.
+
+The plan the project froze in May 2026 said the opposite. AD-13 (`docs/plans/cross-platform-mac-linux/_FROZEN-DECISIONS.md`)
+reads "probe at first use; if missing, log an English onboarding message and fall
+back; never hard-block". The shipped code inverted it on 2026-07-15, in two commits
+whose messages do not mention it, and no written human decision to ask up front
+exists anywhere in the repository (history reconstructed in `docs/macos-permissions.md`
+section 2). The only stated reason in code was about where a prompt would appear.
+
+Every later layer repaired a symptom of the wall instead of removing it: the banner
+(a wake word that was dead because the app had never opened the microphone, so macOS
+never showed its dialog), the dead-Allow-button fixes, the sticky restart flag
+(BUG-159), the identity-reset note, the "Set up everything" wizard with an
+automatic restart, the Automation consent file with a hidden launch of Music and
+Spotify (BUG-217), and the `wanted` flag with the banner's "Not now" (BUG-224). One
+wrong identity constant disabled the whole surface twice (BUG-161, BUG-222). The
+wall also cost time on hot paths (per-frame and per-keystroke probes).
+
+Some constraints in that history are real and stay (below). None of them requires a
+banner, a wizard, a readiness gate or refusing to let the OS show its own dialog.
+
+## Decision
+
+**Ask when needed.** A feature asks the operating system at the moment the user first
+uses it or switches it on, from a user gesture, through one module,
+`jarvis/platform/permission_service.py`. macOS shows its own dialog. A denial degrades
+that one feature honestly (originally with a card and a passive Settings > Privacy page; since
+the amendment below, with one short toast and one action). Nothing is asked at launch and
+nothing nags.
+
+This is rule AP-35. Its nine principles are binding:
+
+1. **Just in time.** Ask when a feature that needs the permission is first used or
+ switched on by the user. Never at launch, never in a banner, never as a wizard.
+2. **The feature may ask; it must never act on anything but a live grant.** No path
+ refuses because our own preflight says "not granted" before the OS was asked, and
+ no path acts on a permission the OS has not granted. `EnsureResult.granted` is true
+ only for GRANTED and NOT_REQUIRED; pending, needs-settings, denied and unavailable
+ never proceed; the return value of a native request is never evidence of success.
+ Silent-failure traps are checked at the source (wallpaper-only screen capture,
+ all-zero audio, input dropped without trust).
+3. **Let the OS ask where it asks by itself; call the explicit prompt API where it does
+ not.** Never ask by touching an API that fails silently. Never create an event tap
+ to provoke a prompt (BUG-058 class): the ask is `CGRequestListenEventAccess` or
+ `IOHIDRequestAccess`, and the tap is created only after the preflight is true.
+4. **Denied is a stable state, not an error to retry.** Degrade the one feature, say
+ why where the user is, offer one click to the right pane, stop. No repeated
+ prompting, no polling banner. `tccutil reset` stays an explicit way to ask again
+ (the in-app "Ask again" button is gone since the UI reset; the way is now
+ `jarvis permissions reset <permission>`).
+5. **Grants are detected by silent probing owned by the backend** and applied in
+ process. A restart is only a hint, never forced.
+6. **Identity decides who may reset and whether we may auto-ask, not whether we may
+ act.** We act on whatever grant exists. Native requests are made only from an
+ installed app bundle, or after an explicit confirmation (since the UI reset: one click on a toast that
+ says the app that started Jarvis receives the grant).
+ Reset runs only from the installed app's own bundle id.
+7. **Opt-in features own their permission.** A feature the user has not switched on
+ never touches its permission (wake word, mute music, computer use, global shortcuts).
+8. **Honest degradation, always.** Every refusal carries a stable reason and a full
+ English sentence; the app shows one toast with at most one action, only for a
+ user-started use that failed (amended; this originally read "one card").
+9. **An AI agent never answers a system dialog.** Agent-facing text is prohibitive; the
+ computer-use engine pauses while a macOS consent window is frontmost.
+
+The contract is the `PermissionGate` protocol (`jarvis/core/protocols.py`): `check`
+(silent, never prompts), `ensure` and `ensure_async` (interactive, only from a gesture
+entry), `ensure_all` and `open_settings`. The service
+(`jarvis/platform/permission_service.py`) adds `outstanding`, `add_listener`,
+`report_failed_use`, `report_use_ok`, `note_reset` and `attach_bus`, which consumers reach
+only through the service or by capability lookup. Off macOS it returns NOT_REQUIRED
+before touching the port. Two frozen events, `PermissionNeeded` and
+`PermissionResolved`, ride the existing `/ws` forwarder; the Python and TypeScript
+sides are pinned by parity tests (AP-4).
+
+## Consequences
+
+**Deleted.** The app-wide permissions banner and its dismissal store; the Settings
+wizard (`setupAll`, ordering, auto-restart, polling) and the refresh-event plumbing;
+the onboarding `permissions` step (a stored legacy step id maps to `voice`); the
+readiness aggregate, `wanted`, `active`, `identity_reset`, the global
+`restart_required` and `foreground` in the snapshot; the Automation consent file and
+the hidden launch of Music and Spotify; the identity-reset marker file. Leftovers on
+upgrade (`macos-tcc-reset.json`, `macos-automation-consent.json`, the stored banner
+dismissal key, a stored onboarding step `permissions`) are never read, or mapped,
+and never prompt. The port's old members (`FEATURE_REQUIREMENTS`, `active_features`,
+`runtime_access_granted`, the legacy `snapshot` / `request`) are deleted from
+`jarvis/platform/permissions.py`, and a ratchet test
+(`tests/unit/platform/test_no_legacy_permission_api.py`) fails if one returns. The
+source installer removes the two leftover state files once, on its next run
+(`remove_leftover_state_files`, called from `ensure_macos_app_bundle`). The frozen
+`.dmg` app never gets them deleted, because `ensure_desktop_integration` returns early
+for frozen builds; that is harmless, since nothing reads either file.
+
+**Stays, because the constraint is real.** A stable signed identity (BUG-060, BUG-217,
+BUG-223); live uncached state reads; the own-bundle `tccutil reset` from the installed
+app; the restart hint; the honest wallpaper-only and zero-audio checks; the CI probe
+of the built app; acceptance of both bundle ids for the reset gate and the
+outside-app logic; the Keychain and login-item rows.
+
+**The identity rule changes meaning.** Identity used to decide whether a feature may
+run. It now decides only who may ask automatically and who may reset. A process that
+is not the installed app (a terminal-launched dev run) does not fire a native request
+on its own; the UI offers an explicit confirmation naming the app that would receive
+the grant. It still acts on any grant macOS reports.
+
+**Restart is a hint.** Evidence about whether a running process sees a new Screen
+Recording grant conflicts, so the design works either way: the backend re-probes,
+tries a real capture, and offers "Quit and reopen" only after a real failed attempt.
+The app never restarts itself for a permission.
+
+**Event catalog exclusion.** `jarvis/tasks/event_catalog.py` excludes
+`PermissionNeeded` and `PermissionResolved` from routine triggers. A routine or agent
+reacting to a permission event could end up answering or steering a system dialog,
+which principle 9 forbids; the exclusion is a one-way decision recorded here. No agent
+or router tool exposes ensure, request, open-settings or reset
+(`tests/unit/platform/test_permission_agent_boundary.py`).
+
+**Boot rule.** With every permission undecided, including `wake_word_enabled=True`,
+launch makes no OS dialog, no input-stream open, no event-tap creation and no capture
+call; an upgrader with every grant present sees zero cards and zero requests. The
+service singleton is lazy, imports no framework at module scope and does no I/O at
+import (AP-26). `scripts/ci/check_boot_budget.py` runs after touching startup.
+
+**No persisted "asked" memory.** The once-per-process and cooldown rules live in
+memory. A persisted memory would resurrect the dead end of BUG-083 after a
+`tccutil reset`, a re-sign or another bundle id.
+
+**Cost.** The first use of a feature can now show an Apple dialog in the middle of a
+task (a held dictation key pressed while the microphone dialog is open is not started
+retroactively; the user presses again). That is the intended trade for removing a
+wall that blocked the OS from asking at all.
+
+### Verification status
+
+This is a shared-contract change (T3). Proven so far: logic against a stateful
+framework-level simulator (`tests/fakes/fake_tcc.py`) and the contract scenario table
+(`tests/contract/test_permission_service_contract.py`) on macOS-shaped and non-macOS
+hosts; frontend unit tests; the Linux static gates; the `.dmg` packaging and frozen-app
+probe on macOS runners (BUG-222, ad-hoc signed). **Unverified, because nobody ran it
+on a physical Mac:** every real dialog and its wording, the behaviour of a grant in a
+running process, hold-key semantics, the Developer ID or notarized build, macOS 26 and
+27, the double dialog in the embedded WebView, the Appshot both-Option permission need,
+and the light and dark look of the card on a real window. Each is a row of the manual
+checklist in `docs/macos-permissions.md` section 7 awaiting a sign-off, and the live
+sign-off checklist (`docs/plans/cross-platform-mac-linux/LIVE-SIGNOFF-CHECKLIST.md`,
+rows TCC-1 to TCC-7) is rewritten to this behaviour. Windows and Linux are unchanged
+(NOT_REQUIRED, empty request log).
+
+## Alternatives considered
+
+- **Keep the banner and the wizard.** Rejected: they are repairs for a wall that
+ stopped the OS from asking, they nag users about features they never turned on, they
+ need a polling loop and a restart machine, and every extra layer produced its own
+ bugs (BUG-159, BUG-161, BUG-224).
+- **Ask during onboarding.** Rejected: onboarding cannot know which features a person
+ will use, a dialog without the feature in front of the user has no context and is
+ easy to deny by reflex, and Apple's guidance is to wait until a feature needs access.
+ A required permissions step also reads as mandatory (the wording problem corrected in
+ commit `930f8bc9c`). The onboarding step is removed instead.
+- **A persisted "already asked" memory.** Rejected: it contradicts a live state read
+ after `tccutil reset`, a re-sign or another bundle id, and recreates the dead end of
+ BUG-083 (no dialog, no button, a switch that does nothing).
+- **Carbon `RegisterEventHotKey` hotkeys now.** Rejected for this change: it needs no
+ Input Monitoring according to community reports (Apple's documentation does not say
+ so), but it cannot express modifier-only, Fn, side-specific or two-key chords, its
+ crash surface has not been exercised, and a flag nothing reads would break AP-31.
+ Only the evidence tool ships (`macos-hotkey-spike.yml`, dispatch only; the
+temporary branch push trigger of commit `59749f859` was reverted in `945fe7949`).
+- **Per-turn computer-use permission cards.** Rejected for the first version: one
+ floating card (now one toast) plus the mission's own `blocked_permission` ending (the spoken or
+ written sentence; no separate deck journal line was built, and nothing resumes the
+ mission after a grant: the person asks again) is enough, and a card per agent
+ turn invites the model or the user to treat a system dialog as part of the task
+ (principle 9).
+
+## Follow-ups
+
+- **Carbon backend flip rule.** The default may become Carbon-first only after the
+ runner spike is green on macOS 15 arm64, 15 Intel and the current release; a
+ built-app probe on both architectures passes; one physical-Mac sign-off from a
+ clean reset (hold-to-dictate including modifier-first release, no dialog, Secure
+ Input, quit in under 5 s) is recorded; and one opt-in release cycle ends with no
+ quarantine reports. The crash-surface list is in `docs/macos-permissions.md` 4.15.
+ The spike ran once (run `36954304202`, `macos-15` arm64 and `macos-15-intel`, both
+ jobs green); its arm64 report is marked unusable as TCC evidence because runners
+ pre-grant TCC, and variant G is not covered, so the criterion stays open. Runner
+ evidence only.
+- **macOS Call and Hangup defaults.** The shipped defaults (`f3+f4`, `f1+f2`) stay on
+ the event tap. Platform-specific defaults are a maintainer decision and need the
+ five-layer pattern with a parity test (AP-4, AP-31).
+- **WKWebView media-capture delegate.** The embedded window's WebKit decision sits on
+ top of the TCC dialog and has no handler. The UI asks from the gesture before
+ `getUserMedia`; the delegate grant stays an open item (risk R1).
+- **`report_failed_use` coverage.** `report_failed_use` produces the `restart_hint` only
+ for Screen Recording and Input Monitoring (`_RESTART_HINT_FAMILIES`). Its callers for
+ those are the Input Monitoring tap (`jarvis/trigger/backends/quartz.py`, once per tap
+ when no raw events arrive) and the Screen Recording capture path
+ (`screen_access._unusable_grant_refusal`, when other apps' windows show no readable
+ title while the state reads granted). Automation has its own path: the ducking module
+ reports a send refused with `-1743` although the probe read granted
+ (`report_failed_use(AUTOMATION, target=<player>, reason="needs_settings",
+ origin="background")`), which opens ONE background `needs_settings` episode that names
+ the player. It is not a restart hint (Apple Events are checked per send), never asks,
+ never raises a toast, and a probe that reads granted never closes it; only a
+ later send that lands (`report_use_ok`), `note_reset` or the ten minute TTL does. Its
+ effect on a real Mac is unverified (Apple documents `-1743` only as an error code).
+ Accessibility input still has no such path (not implemented).
+- **Sign-off.** Run section 7 of `docs/macos-permissions.md` on an Apple Silicon and an
+ Intel Mac, on a `.dmg` and a managed install, and record the results before any row
+ is called verified.
+
+## Amendment: the UI is reduced to a toast (2026-10-02)
+
+### Context
+
+The just-in-time service worked, but the user judged the interface built around it as
+not fit for the product: a floating permission card, five kinds of inline note, a Shortcuts status note
+and tip, a dictation popover, an "Enable global shortcuts" button on four pages and a
+Settings > Privacy page, about 4,200 source lines and 5,500 test lines and 184 translated
+strings per language to say again what macOS already says. macOS shows its own dialog the
+moment a feature first needs a permission, and Apple's HIG asks apps to wait for that
+moment and to avoid pre-alerts. Where a permission has to be accepted before a feature can
+work, "then it has to be that way", but nothing of ours should dress it up. What macOS does
+not do is say anything after a denial (it never asks twice) or when a granted permission
+still fails; that silence is the only gap left.
+
+### Decision
+
+1. **Nothing of ours around Apple's dialog.** No card, banner, wizard, inline note, status
+ note, tip, popover or Settings page for permissions. The deleted frontend pieces,
+ their tests, the Python parity tests that read their TypeScript twins, the
+ `shortcuts_status` field of `GET /api/settings/keybinds` with
+ `jarvis/trigger/shortcuts_status.py`, and about 170 of the 184 permission strings per
+ language are removed. The service, its episodes and watcher, the routes (`status`, `{id}`,
+ `request`, `open-settings`, `reset`), snapshot v2, the events, the CLI, the wake-loop resume,
+ the hotkey re-arm and the boot rule stay.
+2. **One toast, one action.** When a user-started use failed because a permission is off
+ (`PermissionNeeded`, `origin="user"`, `phase="blocked"`), the app shows ONE short localized
+ sentence (en, de, es; no pane names) in its existing toast (extended by an optional action and
+ TTL), in the owner window only (the embedded desktop window on macOS), once per episode and
+ again on the person's next try: the service re-announces a still-open episode when a USER
+ gesture lands on it (at most once per 10 s), and the window forgets an episode as soon as its
+ toast is gone. A toast raised while the window was hidden is not queued. The
+ action is **Open System Settings**; **Ask macOS now** when macOS can still ask or the app runs
+ outside the installed bundle (the one click is the confirmation; the sentence says generically
+ that the app that started Jarvis receives the access, it names no app); **Quit and reopen**
+ for a granted permission that does not work. A background origin never toasts, except one
+ toast per app session for a denied microphone for the wake word. The native bar text and the
+ spoken computer-use readbacks are unchanged.
+3. **Input Monitoring is asked when a shortcut is saved.** A global shortcut is a background
+ listener, so nothing at the moment of use can carry a dialog. `PUT /api/settings/keybinds` asks
+ once after the save (macOS only, only while the key tap is not listening, never for a clear or
+ for a re-save of the combo already in force, `wait_s=0`, never failing the save; any caller
+ that passes the route's auth counts as the gesture, like the wake-word switch), and the onboarding voice step's "Skip, I'll use the Call
+ shortcut" click asks once. Nothing at launch.
+4. **Reset is a local command.** `jarvis permissions reset <permission>` runs `tccutil reset`
+ for the installed app's own bundle id (both ids), macOS only, behind `--yes`. It does not use
+ the HTTP route, which keeps refusing scripts (principle 4 and the prompt-loop argument stand).
+5. **The Info.plist strings are neutral and localized.** The Apple Events string names no single
+ app, the folder strings are short, and German and Spanish `InfoPlist.strings` plus
+ `CFBundleLocalizations` ship in both the `.dmg` build (written before signing) and the
+ managed bundle. The bundle format version is not bumped.
+
+AP-35 and the nine principles stay true as written; principle 8's UI half is amended above.
+
+### Consequences
+
+- The permission surface of the app is one toast. Apple's dialog stays the place a person
+ decides; ours only explains a silent failure.
+- The toast is web-styled, not an Apple alert, and invisible while the Jarvis window is hidden
+ (the native bar and the spoken readbacks cover dictation and computer use; a deaf shortcut
+ tap has no other surface). Its look in the real web view is unverified.
+- The `?activated=1` refocus hint of the GET routes has no caller any more; a PROMPT-ONCE episode
+ turns `blocked` on its timer only. The parameter stays with the routes this round.
+- A person with a stuck "denied" answer has no button for it: the way back is the switch in
+ System Settings or the CLI command, documented in the user guides.
+- The deleted code leaves no dangling reference (config fields, i18n keys, CI allowlists, docs
+ manifest were checked).
+
+### Alternatives considered
+
+- **Keep a passive Settings > Privacy page.** Rejected: it duplicates System Settings, needs
+ per-row copy in three languages and a refresh machine, and was part of what the user rejected.
+- **An osascript or AppKit alert instead of a toast.** Rejected for now: in-process `NSAlert` is
+ app-modal and a wrong thread aborts the process; an osascript dialog can steal focus from the
+ app being dictated into, carries a generic icon, and needs its own strings in the backend. It
+ stays the fallback if the toast look is rejected on a real Mac.
+- **A macOS notification.** Rejected: it needs a permission of its own, and Apple's HIG says to
+ use an alert, not a notification, for errors.
+- **An up-front permissions step.** Rejected again for the reasons above; where a permission has
+ to be accepted before a feature works, it is asked when that feature is switched on or saved.
+
+### Verification status of the amendment
+
+Logic, parity and wiring were run against fakes and on Linux (the toast planner and its
+event parity, the keybinds ask against `FakeTCC` and `FakePermissionService`, the reset command
+with a recording runner, `FakeTCC` and a fake executable, the Info.plist and `.lproj` content and the
+frozen-app probe on a synthesized bundle, and the build script's dry run). **Unverified, because
+nobody ran it on a physical Mac:** the toast's look in the real web view, that "Open System
+Settings" lands on the right pane, that macOS shows the localized usage strings, that a UTF-8
+`.strings` file is accepted, the real `tccutil` behaviour, and every Apple dialog. The checklist
+rows are in `docs/macos-permissions.md` 7.2 and 7.3.
diff --git a/docs/appshots.md b/docs/appshots.md
index 9f5b534754..62109fb82a 100644
--- a/docs/appshots.md
+++ b/docs/appshots.md
@@ -64,10 +64,10 @@ and served with `Cache-Control: no-store`.
| | Windows | macOS | Linux/X11 | Wayland / headless |
|---|---|---|---|---|
-| Both-Alt shortcut | `GetAsyncKeyState` (AltGr counts as right Alt) | `CGEventSourceKeyState`, needs the Input Monitoring grant | `XQueryKeymap` via python-xlib | Unavailable, reason shown on the page; voice and the button still work where capture works |
+| Both-Alt shortcut | `GetAsyncKeyState` (AltGr counts as right Alt) | `CGEventSourceKeyState`; whether this read needs the Input Monitoring grant is **unverified** (not measured on a Mac), so the page shows no Input Monitoring row for it | `XQueryKeymap` via python-xlib | Unavailable, reason shown on the page; voice and the button still work where capture works |
| Other shortcuts | Shared hotkey backends (`jarvis/trigger/backends`) | same | same | same as above |
| Flash + thumbnail | PySide6 overlay, excluded from capture | PySide6 overlay | PySide6 overlay | No overlay; the appshot is still taken where capture works |
-| Capture | Screen Context engine | Needs Screen Recording | X11 | Honest refusal |
+| Capture | Screen Context engine | Needs Screen Recording; macOS asks for it at the first appshot you take | X11 | Honest refusal |
Only the instance that owns ambient duties (the default app, not the dev
instance) arms the shortcut.
diff --git a/docs/authoring/public-docs-manifest.yaml b/docs/authoring/public-docs-manifest.yaml
index e828c06876..2108e313f8 100644
--- a/docs/authoring/public-docs-manifest.yaml
+++ b/docs/authoring/public-docs-manifest.yaml
@@ -842,11 +842,15 @@ pages:
file: docs/product/privacy-safety-and-support/permissions.md
title: App Permissions
diataxis: howto
- summary: Grant only the microphone, screen, accessibility, and input permissions needed for voice, global shortcuts, and Computer Use.
+ summary: See when macOS asks for microphone, screen, accessibility, and input access, and how to change an answer later.
authoritative_sources:
- - jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx
+ - jarvis/ui/web/frontend/src/lib/permissionToast.ts
+ - jarvis/ui/web/frontend/src/i18n/locales/en.json
+ - jarvis/cli_ctl/commands/permissions.py
+ - jarvis/core/macos_privacy_strings.py
- jarvis/ui/web/permissions_routes.py
- jarvis/platform/permissions.py
+ - jarvis/platform/permission_service.py
- jarvis/platform/capabilities.py
related:
- first-run-setup
diff --git a/docs/ci-pipeline.md b/docs/ci-pipeline.md
index 0d22ece25d..c3f8571b94 100644
--- a/docs/ci-pipeline.md
+++ b/docs/ci-pipeline.md
@@ -25,7 +25,7 @@ agent branch ──► pull request ──► CI (lanes) ──► CI gate ─
| `tests windows` | Four shards on full runs; on a pull request one runner takes only the tests the diff can reach. | `scripts/ci/select_tests.py` |
| `tests macos 1..3` | Nightly and manual runs only (~10x runner cost). | — |
| `test report + floor` | Sums all Linux shards, enforces the min-passed floor, lists baselined failures that now pass, and on main refreshes the per-file duration cache that balances the shards. | `scripts/ci/ratchet_tests.py` |
-| Lanes | `frontend`, `jarvisctl`, `deps`, `realtime` (3 OS + slim container), `updater` (3 OS: in-app update, native handover, restart helper), `dragdrop`, `browser`, `macOS desktop`, `installer smoke` — each only when its paths change. | — |
+| Lanes | `frontend`, `jarvisctl`, `deps`, `realtime` (3 OS + slim container), `updater` (3 OS: in-app update, native handover, restart helper), `dragdrop`, `browser`, `macOS desktop`, `installer smoke` — each only when its paths change. The `macOS desktop` lane's path gate covers every directory that asks for or acts on a macOS permission (`jarvis/audio/`, `cu/`, `dictation/`, `screen_context/`, `trigger/`, `vision/`, `platform/`), the packaging inputs (`jarvis.spec`, `packaging/macos/`, `jarvis/core/macos_privacy_strings.py`) and `permissions_routes.py` (`scripts/ci/classify_changes.py`); see [`macos-permissions.md`](macos-permissions.md). | — |
| `CI gate` | Aggregates every job. **The only required check.** Skipped lanes pass; the nightly run is strict and fails on any skip. | `scripts/ci/required_results.py` |
### Known failures: the ratchet
@@ -44,6 +44,20 @@ python scripts/ci/ratchet_tests.py update --out scripts/ci/test-baseline-linux.j
A missing list puts that OS in report-only mode until the first full run
produces one.
+### Dispatch-only evidence runs
+
+`.github/workflows/macos-hotkey-spike.yml` runs only on `workflow_dispatch`: it is
+in no lane, no schedule and not in the `CI gate`. It runs
+`scripts/ci/macos_carbon_hotkey_spike.py` on an Intel and an Apple Silicon macOS runner
+(optionally `macos-26`, whose label for this repository is unverified). The script
+records the TCC context first, then runs each risky Carbon `RegisterEventHotKey`
+variant in a child process so a native crash becomes data, not a failed job. It is
+runner evidence only: runners pre-grant TCC to their tools, show no dialog and have no
+physical keyboard, so its result never decides a default on its own (the flip rule is
+in `macos-permissions.md`, section 4.15). It ran once from the feature branch as run
+`36954304202` at commit `59749f859` on `macos-15` (arm64) and `macos-15-intel` (harness green;
+the recorded result and its limits are in `macos-permissions.md`, section 4.15).
+
### Concurrency
A pull request keeps only its
diff --git a/docs/desktop-installers.md b/docs/desktop-installers.md
index 8fb711a9c5..939bd6b36c 100644
--- a/docs/desktop-installers.md
+++ b/docs/desktop-installers.md
@@ -122,12 +122,67 @@ The wizard itself is `packaging/windows/PersonalJarvis.iss`:
# -> dist/installers/PersonalJarvis-macOS-<arm64|x64>.dmg
```
-Owned by `packaging/macos/`. It reads `APPLE_SIGNING_IDENTITY`, `APPLE_ID`,
+Owned by `packaging/macos/`. It reads `APPLE_CERTIFICATE_P12_BASE64` and
+`APPLE_CERTIFICATE_PASSWORD` (imported into a throw-away keychain before the long
+freeze, so an unusable certificate fails early), `APPLE_SIGNING_IDENTITY`
+(optional: read from the imported certificate when absent), `APPLE_ID`,
`APPLE_TEAM_ID` and `APPLE_APP_SPECIFIC_PASSWORD`; with none of them set it
ad-hoc signs, skips notarization and prints a one-line notice. The `.app`'s
-identity (bundle id, minimum system version, and the microphone / speech /
-camera / Apple-Events usage strings macOS requires before it will let the
-process touch those APIs) comes from the `BUNDLE` block in `jarvis.spec`.
+identity (bundle id, minimum system version) comes from the `BUNDLE` block in
+`jarvis.spec`. The usage strings macOS shows in its permission dialogs
+(microphone, screen capture, Apple events, the Desktop / Documents / Downloads /
+removable-volume / network-volume folders, local network) come from ONE table,
+`jarvis/core/macos_privacy_strings.py`, which `jarvis.spec` and the managed
+source-install app both load by path, so the two apps cannot drift apart. The same
+table carries the German and Spanish versions: `jarvis.spec` declares the languages
+(`CFBundleLocalizations`) and `build.sh` writes
+`Contents/Resources/{de,es}.lproj/InfoPlist.strings` into the finished `.app`
+(`packaging/macos/add_localizations.py`) BEFORE it signs it, because the files are
+part of the code seal. There
+is deliberately no camera string, no speech-recognition string and no camera
+entitlement: Jarvis has no caller for either. The entitlements embedded by the
+Developer ID path live in `packaging/macos/entitlements.plist` (no comments; the
+reasoning is in `packaging/macos/README.md`).
+
+Several things in that block are easy to get wrong and invisible to a headless
+smoke run, so the macOS job checks the finished bundle
+(`python scripts/ci/check_frozen_macos_app.py --app "dist/Personal Jarvis.app"`):
+
+- `LSBackgroundOnly` must be `False`. PyInstaller sets it to true whenever the
+ last executable of the bundle is a console one (the `jarvis` CLI is), and
+ LaunchServices then treats the app as having no Dock icon and no windows.
+- The pyobjc frameworks the permission code loads by name (`AVFoundation`
+ above all) must be in the frozen archive. That needs the `desktop-macos` extra
+ on the build machine; the macOS job installs it.
+- Every usage string of the table must be in `Info.plist` with exactly that
+ text, and the removed keys must not be.
+- The bundle must declare its German and Spanish localisation, and each
+ `{de,es}.lproj/InfoPlist.strings` must exist with exactly the text of the table.
+- On a signed build, `codesign -d --entitlements :-` must report every
+ entitlement of `entitlements.plist` and not the camera one. An ad-hoc or
+ unsigned build embeds no entitlements, so the check skips itself with a NOTE
+ line; that is a skip, not a pass, and the hardened-runtime behaviour of a
+ signed build has never been run on a Mac (unverified).
+
+The frozen smoke boots the app twice and, on macOS, also reads its permission
+status each time: a microphone row that reads "unavailable" means the framework
+did not load inside the app (the check above only sees that the module is in the
+archive). The v2.5.0 image shipped with the first two defects (BUG-222).
+
+**Permission prompts.** Personal Jarvis asks for a macOS permission at the moment
+a feature you start needs it (the first dictation asks for the microphone, the
+first screen capture for Screen Recording, and so on) and never at launch;
+nothing is requested up front and no banner or wizard nags. Apple's own dialog or
+System Settings pane does the asking and the app draws nothing around it. Declining
+a permission degrades that one feature and leaves the rest of the app working; the
+app then shows one short toast with one click to the right System Settings pane.
+The dialog text is German and Spanish on a German or Spanish Mac (the build writes
+the `.lproj` strings before signing). `jarvis permissions reset <permission>` makes
+macOS ask again. This is the designed behaviour; it has not been exercised on a real
+Mac yet (unverified). The
+downloaded app and the managed source-install app are separate apps to macOS
+(`ai.personaljarvis.desktop` and `com.personal-jarvis.desktop`) and each keeps its
+own grants.
### Linux
@@ -150,12 +205,25 @@ working installer and says, in one line, that it is unsigned.
| Platform | Mechanism | Secrets |
| -------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------- |
| Windows | Azure Trusted Signing | `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_SIGNING_ENDPOINT`, `AZURE_CODE_SIGNING_ACCOUNT`, `AZURE_CERTIFICATE_PROFILE` |
-| macOS | Developer ID + notarization | `APPLE_SIGNING_IDENTITY`, `APPLE_ID`, `APPLE_TEAM_ID`, `APPLE_APP_SPECIFIC_PASSWORD` |
+| macOS | Developer ID + notarization | `APPLE_ID`, `APPLE_TEAM_ID`, `APPLE_APP_SPECIFIC_PASSWORD`, `APPLE_CERTIFICATE_P12_BASE64`, `APPLE_CERTIFICATE_PASSWORD` (and optionally `APPLE_SIGNING_IDENTITY`; `build.sh` reads it from the imported certificate) |
| Linux | none (AppImage is unsigned) | - |
Private key material only ever exists as a GitHub Actions secret (AP-29); no
signing step ever reads a file from the repository.
+Without the macOS secrets the published `.dmg` is ad-hoc signed and not
+notarized: macOS blocks the first launch (System Settings > Privacy & Security >
+Open Anyway) and treats every update as a new app, so every permission is asked
+for again. `packaging/macos/build.sh` is written to import the certificate into
+a temporary keychain on the runner and read the signing identity from it; that
+step has been rehearsed (`DRY_RUN`) and run against a stand-in `security`
+command, but not yet against a real keychain or with an Apple account.
+`packaging/macos/README.md` lists how to obtain the certificate.
+
+A run started by hand from a branch (`workflow_dispatch`) builds the installers
+without publishing a release, which is the way to try the macOS job, its
+certificate import and the app probe before tagging.
+
On Windows the workflow signs the **setup executable**. That is the file the
browser marks with Mark-of-the-Web, so it is the signature SmartScreen weighs;
files the installer then writes carry no MOTW of their own. Signing the inner
@@ -171,8 +239,10 @@ PyInstaller bootloaders, and can be added the same way.
manually via `workflow_dispatch`):
1. `windows`, `macos` (arm64 + x64) and `linux` each install Python 3.12 and
- Node 22, `pip install -e ".[desktop,dev]"`, run their OS build script and
- upload the artifact.
+ Node 22, `pip install -e ".[desktop,dev]"` (macOS adds `desktop-macos`), run
+ their OS build script and upload the artifact. The macOS jobs also read the
+ finished `.app` with `scripts/ci/check_frozen_macos_app.py` before the
+ headless smoke test.
2. `release` downloads all of them, refuses to continue if any promised asset is
missing, verifies the tag equals `jarvis.__version__`, writes
`installers-SHA256SUMS.txt` (plain `sha256sum` format, flat file names),
diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.md
index 79938bd07d..ee56c4b0d1 100644
--- a/docs/jarvis-cli-reference.md
+++ b/docs/jarvis-cli-reference.md
@@ -191,8 +191,9 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`
## permissions
- `jarvis permissions open-settings <permission_id> --yes --dry-run` — Open the matching macOS privacy pane through LaunchServices.
-- `jarvis permissions request <permission_id> --yes --dry-run` — Show the native macOS prompt for one permission.
-- `jarvis permissions status` — Show permission and feature readiness without caching native state.
+- `jarvis permissions request <permission_id> --yes --dry-run` — Ask macOS for one permission through the same service the app uses.
+- `jarvis permissions reset <permission_id> --bundle-id --yes --dry-run` — Forget what macOS recorded for Personal Jarvis, so it asks again on next use (macOS only).
+- `jarvis permissions status --include-automation` — Show each macOS privacy permission and what is waiting on one. Never prompts.
## refresh
diff --git a/docs/jarvis-cli.md b/docs/jarvis-cli.md
index e49e76a4c0..0e47208d57 100644
--- a/docs/jarvis-cli.md
+++ b/docs/jarvis-cli.md
@@ -153,6 +153,48 @@ while a configured role still points at it, unless `--reassign` names another
installed model — then the roles are rewritten first, and the delete runs only
on a valid config. `--json` before the group prints the untouched API payload.
+## macOS privacy permissions from the terminal
+
+Personal Jarvis asks macOS for a permission at the moment a feature first needs
+it, never at launch. The `permissions` group is the terminal view of that:
+
+```bash
+jarvis permissions status # read only: never prompts, never blocks
+jarvis permissions status --include-automation # also read Music/Spotify (they must be running)
+jarvis permissions request microphone --yes # ask now, through the same service the app uses
+jarvis permissions open-settings microphone --yes # open the matching System Settings pane
+jarvis permissions reset microphone --dry-run # preview the tccutil command, run nothing
+jarvis permissions reset microphone --yes # forget macOS's answer so it asks again (macOS only)
+```
+
+`status` prints each permission (`granted`, `not_determined`, `denied`, `restricted`,
+`not_required` off macOS, ...) and `needed`, the features currently waiting on one.
+`request` answers at once with an outcome (`granted`, `pending` while macOS may be
+showing its dialog, `needs_settings`, `denied`, `unavailable`); the person's answer
+arrives afterwards, so run `status` again. A denial is final from macOS's side: it
+does not ask a second time, and `request` does not pretend otherwise. When Jarvis
+is not running as the installed app, `request` asks nothing and says so. The CLI
+only ever asks for the installed app: without the installed bundle `request`
+refuses before anything is sent, and a grant for the app that started Jarvis (a
+terminal, an IDE) can only be confirmed in the Jarvis window, never from the
+CLI. An AI agent driving the CLI must never answer a macOS dialog on the user's
+behalf. Both `request` and `open-settings` are rate limited by
+the server (HTTP 429). Off macOS every permission reads `not_required` and
+`request` does nothing.
+
+`reset` is the way back from a stuck "denied" answer, since macOS never asks twice
+and the app has no permissions page. It runs `/usr/bin/tccutil reset <Service>
+<bundle id>` on this Mac, for the installed app's own bundle id only (the
+installer's `com.personal-jarvis.desktop` or the downloaded app's
+`ai.personaljarvis.desktop`; read from the app's `Info.plist`, or named with
+`--bundle-id` when both are installed), never another app's. It does not go
+through the running app (the app's own reset route refuses scripts on purpose),
+so it works with Jarvis closed; quit and reopen Jarvis afterwards, then use the
+feature and macOS asks again. It needs `--yes` (or `JARVIS_CLI_ASSUME_YES=1`) and
+`--dry-run` prints the exact `tccutil` argv. Off macOS it prints one line and
+exits 1. Permissions without a macOS privacy record (the Keychain) are refused.
+The raw `tccutil` commands are in the troubleshooting guide.
+
## Safety model
The CLI is agent-first, so it stays out of your way for safe work and only gates
diff --git a/docs/macos-permissions.md b/docs/macos-permissions.md
new file mode 100644
index 0000000000..442ee82514
--- /dev/null
+++ b/docs/macos-permissions.md
@@ -0,0 +1,1157 @@
+# macOS permissions: ask when a feature needs them
+
+Status: implemented, **not yet exercised on a physical Mac** (section 7 is the checklist that
+closes that gap). Last reviewed: 2026-10-02, reconciled with the finished code on that date
+(AP-35 is in `AGENTS.md`, ADR-0038 and BUG-225; the legacy permission wall is deleted; the
+custom permission UI was then reduced to one toast, 4.10 and the ADR-0038 amendment). Scope:
+Personal Jarvis on macOS (the downloadable `.dmg` app and the managed source-install app).
+
+## 1. Summary
+
+1. **Wrong:** features refused to run until our own permission check passed, so macOS was never asked from a feature path.
+2. **Why:** the plan said degrade, never hard-block (AD-13); the code inverted it on 2026-07-15 with no recorded decision (2).
+3. **Real, kept:** stable signed identity, live state reads, usage strings, entitlements, silent-failure checks (wallpaper, all-zero audio).
+4. **Now:** a feature asks at first use, macOS shows its own dialog, and the app draws nothing around it. After a denial macOS stays silent, so the app adds ONE short toast with ONE action (4.10); the way back to a clean slate is `jarvis permissions reset` (4.16).
+5. **Proof:** fake-framework tests and Linux gates (counts in 7.4) plus one earlier macOS-runner packaging run; the macOS lane steps have no recorded result for this branch; the hotkey spike ran once on two macOS runners but its arm64 report is unusable as TCC evidence (4.15); nothing ran on a physical Mac (7.4).
+
+## Conventions: evidence labels
+
+Every statement about macOS behaviour carries a label. A statement without Apple documentation or a
+macOS runner result is never presented as fact. Rule name in code comments and commits: AP-35 (4.2).
+
+| Label | Meaning |
+|---|---|
+| **[A]** | Apple primary source: developer documentation, HIG, WWDC transcript, SDK header. |
+| **[D]** | Post by an Apple Developer Technical Support engineer on the developer forums. Authoritative, not formal documentation. |
+| **[C]** | Community report: forum user, GitHub issue or pull request, blog, search-result summary. A hypothesis. |
+| **[I]** | Inference. Must be verified on a Mac before it is treated as fact. |
+| **[code]** | Read in this repository (file path given). |
+| **[commit]** | Read in git history (hash and date given). |
+| **[runner]** | Result of a macOS CI runner run. Runners are not user Macs: they pre-grant TCC to their tools and show no dialogs. |
+| **unverified** | Not proven by any of the above for macOS. The code comments say the same. |
+
+## 2. Root-cause analysis from git history
+
+Method: `git log -p`, `git show`, `git blame`, the bug register (`docs/BUGS.md`), the
+cross-platform plan set (`docs/plans/cross-platform-mac-linux/`), ADRs and `docs/os-parity.md`.
+Dates are commit dates. Author names are left out on purpose: git alone cannot say which
+sentence is human intent, so rationales are quoted from the artefact and not attributed.
+
+### 2.1 What the plan said
+
+| Source | Text |
+|---|---|
+| `docs/plans/cross-platform-mac-linux/_FROZEN-DECISIONS.md`, AD-13 | "Permission-UX is detect-and-degrade. macOS AX/Input-Monitoring ...: probe at first use; if missing, log an English onboarding message + fall back, never silently empty ... and never hard-block." |
+| `docs/plans/cross-platform-mac-linux/HARD-NEGATIVES.md`, HN-5 | "probe -> if missing, log an onboarding message AND fall back - never silently empty, never hard-block." |
+| `docs/plans/cross-platform-mac-linux/DEEP-DIVE-AUDIT-2026-06-19.md`, H1 and M7 | H1: without the Screen Recording grant the capture library returns the bare wallpaper with no error; the remedy asked for is a probe plus an honest message. M7: a microphone denial degrades to "no mic" with no hint; the remedy asked for is a hint. |
+
+Both audit findings describe real technical problems. Both ask for a probe and a message, not
+for a gate that stops macOS from asking.
+
+### 2.2 Timeline of the decisive commits
+
+| Date | Commit | What happened | Reading |
+|---|---|---|---|
+| 2026-07-14 | `0eebcc051` | BUG-060: first real `.app` bundle. Stated reason: a bundle gives TCC an identity, so the microphone dialog names the app instead of "whichever terminal started the process". | Technically required (stable code identity). |
+| 2026-07-14 | `86f99bf4a` | BUG-058: first fail-closed gate, a preflight before the keyboard event tap. The register entry itself says no log confirmed the crash theory. | Hypothesis. BUG-077 (2026-07-17, `3b924a249`) later found the real crash was a keyboard-layout API called off the main thread, and the preflight "gated the tap correctly" but was not what prevented a crash. |
+| 2026-07-15 | `29f488e60` | Computer-use input and capture probe the permission before every action. | Start of the per-action wall. |
+| 2026-07-15 | `562232023` | One commit creates the whole up-front stack: `SystemPermissionPort` with `runtime_access_granted()` = stable identity AND live grant, a feature-readiness table, request routes, Settings panel, an onboarding step whose Continue was disabled until all five permissions were granted, a 2.5 s polling hook, the microphone gate (re-checked every 0.25 s in the read loop) and the voice-activation gate. Empty commit body, no co-author trailer. | **The inversion.** In-code reason (`jarvis/ui/desktop_app.py`, lines 2381-2382 at that commit, since removed): "macOS must never discover microphone permission by opening the device: that would throw an unmanaged TCC prompt before the guided onboarding step." That is a UX preference about where the prompt appears. |
+| 2026-07-15 | `f0d4f77ee` | Five minutes later, a commit titled as an architecture, bug-register, CLI and release-notes refresh, with an empty body, rewrites the live sign-off checklist (`LIVE-SIGNOFF-CHECKLIST.md`): row AX-2 changes from "falls back to the pixel path and still clicks (AD-13)" to "refuses to inject input. No pixel-click bypass"; new rows TCC-2 ("no dialog appears merely from installing, booting, or opening the page") and TCC-4 ("fails closed before touching the protected API"). | Where *degrade* became *refuse*. The message does not mention it. AD-13 and HN-5 stay in the frozen file unchanged. |
+| 2026-07-17 | `4a53eb424` | App-wide amber banner. Commit body: "A missing TCC grant (microphone, screen recording, accessibility, ...) silently kills wake word, voice, and Computer-Use; until now only the Settings panel and onboarding knew." | [I] (our inference, not stated in the commit): the silent death was produced by the gate (it never opened the microphone, so macOS never showed its dialog). The banner treats the symptom. |
+| 2026-07-17 | `9728bf57a`, `e2e5651dc` | Dead Allow buttons for Input Monitoring: a tri-state `IOHIDCheckAccess` probe added. Ducking `prewarm()` asks for Automation when the feature is switched on. | The first, narrow just-in-time behaviour in the history. |
+| 2026-07-18 | `5ea2fcc83` | BUG-083, first live finding (an Intel Mac, macOS 15.7): ad-hoc signature pins grants to a per-build hash; System Settings ignores deep-link anchors while already running (the app now quits it first); frozen Screen Recording preflight. | Real constraints, found three days after the wall shipped. |
+| 2026-07-18 | `b25e63520` | "Ask again" (`POST /{id}/reset`, `tccutil reset` for the app's own id); onboarding permissions step moved last. | Recovery action, legitimate. |
+| 2026-07-20 .. 08-03 | `b0f9ff2e2`, `b66cb179a` | Per-action probes measured as a cost. `b66cb179a` says its per-keystroke probe inside the event-tap callback made the shortcuts "go intermittently dead"; its mechanism (a callback that overruns its deadline gets the tap disabled by macOS) is the commit author's hypothesis, unverified; `jarvis/trigger/backends/quartz.py` carries a comment in the same spirit [code]. | Bugs caused by the gate. |
+| 2026-08-20 / 08-21 | `7d75c6fbc`, `d377bffe8`, `96ebffcc0` | BUG-159 and BUG-161: "Every start warned that permissions were not enabled" while they were on; the app rejected `/Applications` as a tampering signal although "TCC pins a grant to the bundle id and its signature, never to a path". | The gate itself is the bug. |
+| 2026-09-16 | `b7d92746e` | Per-user self-signed certificate: the identity is bundle id plus certificate, not a per-build hash. Reported verified on macOS 15.7.4 in the BUG-217 register entry (a live Mac session; not re-verified for this branch) [commit `b7d92746e`, register]. | The structural fix for BUG-083/159/161. Technically required. |
+| 2026-09-16 | `5e3d07db3`, `4af1cc766` | Automation row with a consent file and hidden launch of Music and Spotify; "Set up everything" wizard with auto-restart ("Six buttons and a restart to find, per permission, is how 'the permissions are extremely annoying' reads from the user's side"). | The wizard automates the up-front flow instead of removing the need for it. |
+| 2026-09-30 | `4e2570d76`, `9af34286a` | Onboarding card rebuilt: the permissions step becomes non-blocking. | Softened, still a dedicated up-front step. |
+| 2026-10-01 | `3597dbf5d` | BUG-222 / BUG-224 (details in 2.6). Adds the "wanted" flag and banner "Not now". | One wrong constant disabled the whole permission surface of the `.dmg` app. |
+| 2026-10-01 | `930f8bc9c` | Doc fix: "Telling people they must grant everything is exactly the impression that makes the permission list feel mandatory." | The repo itself notes the effect. |
+| 2026-10-02 | the UI-reset package of this branch | After the just-in-time service was in, the user judged the custom surfaces built around it ("this UI looks completely bad ... Apple already provides the permissions and its UI looks good already"): a floating card, inline notes, a Settings > Privacy page and "Enable global shortcuts" buttons. | **The last layer removed.** macOS shows its own dialog; the app adds one toast after a denial (4.10). The decision is recorded in the ADR-0038 amendment. |
+
+### 2.3 Technically required versus grown
+
+Separation, element by element. "Required" means an OS or signing fact forces something;
+"grown" means a layer added in response to a symptom the up-front wall itself created.
+
+**Technically required (carried forward):**
+
+| Constraint | Evidence | What it justifies |
+|---|---|---|
+| TCC keys a grant on code identity, not on the app name; ad-hoc or unsigned builds look like a new app after every update and prompt again. | [D] Apple DTS, "On File System Permissions" (developer forums thread 678819); BUG-083, BUG-217 [commit `b7d92746e`]. | A stable signed identity (self-signed certificate for the managed app, Developer ID for the `.dmg`). Not a runtime refusal. |
+| A responsible-code identity is a native Mach-O main executable, not a script. | [D] same thread; BUG-060 [commit `0eebcc051`]. | A real bundle with a native launcher. |
+| Usage-description strings are mandatory for the microphone and Apple events and fatal when missing. | [A] Apple Info.plist key pages; BUG-058 class. | One table of strings, a capability check before any native request. |
+| Under the hardened runtime, microphone and Apple-event access need the `audio-input` and `apple-events` entitlements or the prompt never appears. | [A] entitlement documentation; [D] DTS thread 741303; [C] CowAgent#3181. | Entitlements in `packaging/macos/entitlements.plist`. Never run on a notarized build yet (unverified). |
+| TCC state changes outside the process (Settings toggle, `tccutil`, revocation) and there is no change notification for most services. | [A] status calls return a plain Bool for Accessibility and Screen Recording [A signatures]. | Live, uncached state reads; a silent episode watcher. |
+| macOS does not ask again after a decision (per-permission wording in 3.6). | [A for iOS/UIKit, applied to macOS by inference [I]] UIKit "Requesting access to protected resources": "If the person denies permission, the access attempt that initiates the prompt, and any further attempts, fail" (wording not re-verified against the live page). | A stable "denied" state, one click to the right pane, an own-bundle `tccutil reset` as explicit recovery. |
+| Silent failures: Screen Recording without the grant returns the desktop wallpaper, not an error; a denied microphone yields zeros; synthetic input without trust is dropped. | [A] "audio recordings contain only silence"; [C] driveshot#54, Slack screen-share reports; audit H1. | A pixel sanity check at the capture site and a digital-silence guard on the microphone. |
+| `tccutil reset` is scoped to a bundle id; the wrong id wipes another app. | [A] Apple Files and Folders pages; [commit `38aa4fc08`]. | Reset only from the installed app, only its own id. |
+| An Automation consent cannot be queried for a closed target (`procNotFound`, -600). | [A] `AppleEvents.h`: "The target ... must refer to an already running application." | Ask only while a player runs; never launch one to ask. |
+
+**Grown (removed or demoted):**
+
+| Element | Introduced | Stated reason | Verdict |
+|---|---|---|---|
+| Fail-closed identity gate in front of microphone, computer use, hotkeys, window control | `562232023`, `29f488e60` | Prompt placement (UX); BUG-058 hypothesis | **Accreted.** Identity matters for who may reset and whether to auto-ask, not whether to act on an existing grant. It disabled whole features twice by false negatives (BUG-161 #3, BUG-222). |
+| Canonical-path rule for the bundle | `562232023`, repaired in BUG-161 | Tampering signal | **Accreted.** The register's own verdict: "the strict rule bought no safety and costs everything". |
+| App-wide warning banner | `4a53eb424` | Dead wake word nobody knew about | **Accreted.** A response to a symptom of the gate. |
+| "Set up everything" wizard, ordering table, auto-restart, 180 s per-row timeouts | `4af1cc766` | "extremely annoying" | **Accreted.** It automates the up-front flow. |
+| `wanted` / `active_features` flag and banner "Not now" with one-week expiry | `3597dbf5d` (BUG-224) | Automation demanded of every Mac | **Accreted.** A real bug fix for over-asking, but a patch on the up-front model. |
+| Restart machinery (`_RESTART_AFTER_CHANGE`, sticky pending-restart flag, global `restart_required`) | `562232023` (`_RESTART_AFTER_CHANGE` [code]) | "both only fully apply after a relaunch" (`b25e63520`, 2026-07-18; said about ordering the onboarding steps, not about the restart machinery) | **Mostly accreted.** The sticky flag caused BUG-159. Only the Screen Recording part rests on an OS observation, and that observation is contested (3.6). |
+| `identity_reset` note and marker file | `7d75c6fbc` (BUG-159d) | A rebuild wiped grants invisibly | **Was justified, now vestigial.** After the certificate fix a rebuild changes nothing; per `5176bc0ff` only the managed installer ever wrote it. |
+| Onboarding `permissions` step | `562232023`, softened `4e2570d76` | Guided first run | **Accreted.** Its position comment (added in `4e2570d76` / `9af34286a`, 2026-09-30; "... macOS microphone grant exists before the wake-word group's microphone test") only exists because the gate refused the test without a grant. |
+| Feature-readiness aggregate (`FEATURE_REQUIREMENTS` rolled up to ready / not ready) | `562232023` | Banner sentence | **Accreted.** The feature-to-permission *map* is neutral domain knowledge and is kept as `used_for` metadata. |
+| Automation consent file and hidden launch of Music/Spotify | `5e3d07db3` | Wanted an answer for a closed app | **Accreted.** The real defect was a 3 s timeout that tore the dialog down; the original `prewarm()` was already just in time. |
+| Per-frame and per-keystroke probes (microphone read loop, tap callback) | `562232023` | Fail closed on revocation | **Accreted**, and measurably harmful (`b0f9ff2e2`, `b66cb179a`). |
+| 2.5 s polling while any wanted grant is missing | `562232023` | Follow a user through Settings | **Accreted.** Focus refresh plus refresh-after-action is enough for a passive page. |
+| The custom permission UI of the just-in-time rebuild: a floating card, inline notes in five places, a Shortcuts status note and tip, a Settings > Privacy page | the first just-in-time implementation (2026-10) | Say what is off and offer the way back, in the app | **Removed (2026-10-02).** About 4,200 frontend source lines and 5,500 test lines to re-explain what macOS already shows, plus 170 translated strings per language. The one thing macOS does not do, speaking after a denial, is now one toast (4.10). |
+
+Each of these was a deliberate, reasoned response when it was written. The finding is not that
+anyone acted carelessly; it is that every one of them answers a problem the first wall created.
+
+### 2.4 The inverted AD-13, and the missing decision
+
+- The repository currently contains two contradictory rules: AD-13 / HN-5 (degrade, never
+ hard-block) and the rewritten checklist rows AX-2, TCC-2 and TCC-4 (refuse, fail closed). The
+ frozen file "wins on any conflict" (`docs/plans/cross-platform-mac-linux/README.md`).
+- **No human decision to ask up front is recorded anywhere** in git or in the documents. The
+ plan files are marked as generated by a planning orchestrator; `f0d4f77ee` has an empty
+ body; many permission commits carry an agent co-author trailer. The one documented human
+ signal is the user complaint quoted in `4af1cc766`, and it was answered with more up-front
+ tooling.
+- The sign-off rows TCC-1 to TCC-5 were never filled in (`SIGNOFF-LOG.md` has no TCC rows).
+
+### 2.5 The always-on wake word, fairly
+
+A fair reading of the original intent: the wake word opens the microphone at boot, so "first
+use" and "app start" coincide, and asking at a controlled moment is a legitimate wish. That does
+not require a gate. The wake loop can wait, say why, and start when the permission is granted
+(this is what the code does now, 4.6). Nothing in the history evaluated that alternative.
+
+### 2.6 The BUG-058 / 083 / 159 / 161 / 217 / 222 / 223 / 224 chain
+
+| BUG | Date | Real OS or signing constraint | Self-inflicted by the gate, restart or identity logic |
+|---|---|---|---|
+| 058 | 07-14 | None confirmed (hypothesis) | Preflight added on an unconfirmed crash theory; real cause was BUG-077 |
+| 083 | 07-18 | Ad-hoc hash identity; System Settings ignores anchors while running; frozen Screen Recording preflight | A forced bundle rebuild orphaned the grants; dead Allow button |
+| 159 | 08-20 | Grant stranded after a signature change | Sticky restart flag disabled features with every grant in place; reset hidden |
+| 161 | 08-21 | Frozen Screen Recording preflight | `/Applications` rejected by the app's own rule; a rebuild loop wiped grants on every start |
+| 217 | 09-16 | Ad-hoc signature = per-build hash; Automation consent not queryable for a closed app | Automation outside the model; a 3 s timeout killed the dialog |
+| 222 | 10-01 | Frozen-app packaging (AVFoundation had to be named, `LSBackgroundOnly`) | The gate accepted one bundle id; the whole permission surface of the `.dmg` app was dead (no Allow button at all) |
+| 223 | 10-01 | A public image needs an Apple account to be signed and notarized | The build script never read the certificate secrets |
+| 224 | 10-01 | Automation consent needs a running target | Asked for a feature that is off and launched Music and Spotify hidden to show a dialog |
+
+BUG-222, 223 and 224 were verified only against faked frameworks and macOS CI runners, never on a
+user's Mac; their register entries say so.
+
+### 2.7 What the history cannot answer
+
+- Whether macOS really registers an app as denied when it created an input listener before being
+ asked (the `b25e63520` claim rests on one Mac and is not corroborated by Apple).
+- Whether the native first-use prompt works cleanly for every permission under the current
+ bundles. Nothing has been tried; every "verified" statement is on fakes or runners.
+- Whether any human explicitly asked for up-front or fail-closed behaviour: nothing shows it.
+
+### 2.8 Verdict
+
+It grew. There was a real technical cost to doing it just in time (the always-on wake word, the
+need to detect silent failures) that was never weighed, and a small set of real constraints that
+got conflated with it. None of the real constraints requires a banner, a wizard, a readiness gate
+or refusing to let the OS show its own dialog.
+
+## 3. How other apps do it, and what Apple says
+
+### 3.1 Evidence quality (read first)
+
+- Vendor domains (OpenAI help centre and developer pages, Raycast manual, Zoom, Slack,
+ 1Password, Loom, CleanShot, Alfred, a dictation app, a dictation app) were **not reachable** from the
+ research environment. Most vendor statements below come from **search-result summaries of the
+ official page**, university or IT how-to pages that mirror the vendor knowledge base, and
+ third-party reviews. They are weaker than a direct read.
+- Pages read directly: the Claude desktop and computer-use documentation, one Claude support
+ article, and GitHub issues of public repositories (these quote real dialog text and bundle ids
+ but are user reports, not vendor statements).
+- Nothing was observed on a Mac. A "no wall found" statement means "none documented", never
+ "none exists".
+- Source types: **direct** (page read), **summary** (search summary of the official page),
+ **how-to** (third-party or institutional write-up), **issue** (GitHub issue).
+
+### 3.2 Comparison table
+
+| App | When it asks | Explanation before / after | On denial | Route to System Settings | Confidence, source type |
+|---|---|---|---|---|---|
+| **ChatGPT desktop** | At first use of a feature: Work with Apps (Accessibility), Record and voice (Microphone, Screen & System Audio Recording), Computer Use after an explicit opt-in. No launch wall found. | Help-centre prose plus the OS dialog; an own pre-prompt card was not verified. Computer Use adds app-level approvals independent of TCC ("allow once / Always allow"). | Feature unavailable; Computer Use reports "permissions are still pending" when the grant sits on the wrong client (a helper is a separate TCC client, openai/codex#46776). | Text path to the Privacy & Security pane; a deep link is unverified. | Partly documented. Summary of vendor help pages plus issues (read). |
+| **Claude desktop** | Computer use is off by default; the user flips a Settings toggle and must grant two permissions "before the toggle takes effect". Quick Entry shows an in-app opt-in card at first launch of the updated app (an app-level consent card, not a TCC prompt). | Docs table with one line per permission and a status badge per permission in Settings. | Toggle stays inert until both are granted; if off, Claude says in chat it could do the task if enabled. | "Click the badge to open the relevant System Settings pane" (documented). Restart after a grant: not stated for Desktop. | Documented for computer use (direct). Partly documented for the timing of the OS dialogs and for Quick Entry denial. |
+| **Claude Code** (terminal) | Nothing up front. Computer use is a built-in server, off by default; "the first time Claude tries to use your computer" a prompt appears. Protected folders prompt on first touch (plain OS template). | Inline card in the session with links to the panes and a **Try again** button. | Try again, no nagging. Folder denial surfaces as an unexplained error (issues). | Links in the prompt. "macOS may require you to restart Claude Code after granting Screen Recording." | Documented for the flow (direct). Attribution is mixed: the docs name the terminal app; issues show the Claude binary as its own client (a version path in Automation dialogs, per-update re-prompts). |
+| **Raycast** | Per feature at first use (summary of the manual); feature setup views for Screen Awareness and Dictation. Whether Accessibility is also asked in first-run onboarding is **conflicting** across third-party sources. | Setup view per feature and an inline "Grant Permission" card. | Feature degrades; Screen Recording is optional for Screen Awareness. | Button opens the pane; a changelog entry fixes "would not open System Settings when requesting access for a denied permission" (summary). Auto-restart and resume is asserted by one summary only. | Partly documented. Summary of the manual and changelog; third-party how-tos. |
+| **Zoom** | Camera and microphone at first use; Screen Recording at the first share; Accessibility only when someone requests remote control. No permission onboarding documented. | OS dialog with the usage string; for Accessibility "Open System Preferences" on the dialog, which as far as can be told is the standard macOS dialog, not an own one. | Feature dead; all how-tos tell the user to fix it manually in Privacy & Security. | Button for Accessibility; OS asks to restart Zoom after Screen Recording. | Partly documented. How-tos mirroring the vendor KB. |
+| **Slack** | First huddle (microphone), first video or share (camera, Screen Recording). | OS dialog (inferred). | **Silent degrade**: sharing shows the wallpaper and menu bar. A cautionary example. | Help text, quit and reopen; `tccutil reset ScreenCapture <bundle id>` as a last resort (third party). | Partly documented / inferred. Third-party sources. |
+| **1Password** | Screen Recording at the first QR or setup-code scan; Accessibility only for the opt-in Universal Autofill and shortcuts. The vault works with no permission at all. | OS dialog; the help page is named after the dialog text ("1Password would like to record this screen"). | QR scan unavailable until granted and restarted; core product unaffected. | "Open System Settings" on the dialog, then "Quit & Reopen". | Partly documented. Summary of vendor pages. |
+| **Loom** | The install article says users "will be prompted" when installing the desktop app; microphone and camera when selected (inferred). Exact order not documented. | Unknown. | Manual toggles; `tccutil reset` commands documented as a fix for stuck state (a known pain point). | Help-article steps; no in-app deep link confirmed. | Partly documented. Summary of help articles. |
+| **CleanShot X** | Screen Recording and Accessibility during setup (a screenshot tool whose whole purpose needs Screen Recording, so up front equals first use); microphone when a recording uses it. | Short onboarding; wording unknown. | Capture does not work; the app appears in the Screen Recording list only after a capture attempt. | Quit and reopen needed (third party). | Inferred / partly documented. Third-party reviews. |
+
+### 3.3 Closest comparators (voice, hotkey, insert text)
+
+| App | Finding | Confidence |
+|---|---|---|
+| **a dictation app** | First-launch setup with two cards (Accessibility, Microphone), each with an own priming sentence and an Allow button, then Continue and a microphone test; resumable. Input Monitoring only if the user binds Caps Lock alone; screen capture not needed for dictation; re-checks permissions when brought to the foreground (community guide); warns that a missing Accessibility grant is a silent failure. | Documented (summary of vendor docs); runtime recovery behaviour from a community guide. |
+| **a dictation app** | First-launch wizard for Microphone and Accessibility; a changelog note says a re-prompt after completed onboarding was fixed. | Partly documented. |
+| **Alfred** | Hybrid: a first-launch checklist plus a permanent "Request Permissions..." button in Preferences; Contacts and Automation are asked by macOS only when needed. | Partly documented. |
+| **Codex desktop** | Opt-in toggles (Computer Use, Chronicle) then the OS prompts, then per-app approvals; helper identities are separate TCC clients (issues #46776, #18507); a prompt for a feature the user never enabled is perceived as a bug (#37378, "access data from other apps" about daily with Computer Use off). | Partly documented; issues read. |
+
+### 3.4 What the comparison supports, and what it does not
+
+- Documented only for the Claude products (direct read): the OS dialog hangs off a feature
+ toggle or first use, with a feature-local explanation and a link to the right pane. For the
+ other apps the evidence is summary, how-to or inference. a dictation app, a dictation app, Alfred,
+ CleanShot X and (inferred) Loom run short first-launch permission flows, which is a setup
+ wizard of the kind Jarvis removes. No source found documents a persistent app-wide banner or a
+ "set up everything" wizard, but absence of documentation is not absence of the feature.
+ This comparison is therefore not evidence for the "no wizard" decision; that decision rests on
+ the Apple HIG quotes (3.5).
+- Not supported: "no app asks at launch". Claude desktop shows a first-launch opt-in card;
+ a dictation app, a dictation app, CleanShot X and Alfred have short first-launch flows scoped to what
+ the product cannot work without; Raycast onboarding is uncertain. State it as "none documented
+ as a persistent wall".
+- Two-layer consent for agent features (an app-level toggle, then per-app approvals, then the
+ OS dialog) appears in the Claude and Codex products. Jarvis already has its own risk tiers
+ for tool use; this change adds no new app-level approval layer.
+- Helper-identity pitfall (issues only): when a helper does the capture, the grant must be on the
+ helper. Ask from, and check, the process that will call the API (4.7, attribution).
+
+### 3.5 Apple reference points
+
+HIG, "Privacy" [A] (the page covers all Apple platforms; the quoted wording was not re-verified against the live page for this review):
+
+> "Ideally, wait to request permission until people actually use an app feature that requires access."
+
+> "Avoid requesting permission at launch unless the data or resource is required for your app to function."
+
+> "If it's essential to provide additional details, you can display a custom screen or window before the system alert appears." Such a screen should "include only one button" with a term like "Continue" or "Next", should not use "Allow" as the button title, and must not offer a way to leave without viewing the system alert.
+
+UIKit "Requesting access to protected resources" [A for iOS/iPadOS; applied to macOS by inference [I]; wording not re-verified against the live page]: "Because a person can change authorization at any time using Settings, always check the authorization status of a feature before accessing it. In cases without a dedicated API, prepare your app to gracefully handle access failures."
+
+What Apple does **not** say (do not over-claim): the HIG has no sentence "do not nag after a denial". That rule is derived from the API behaviour (the system remembers the choice) and from the nagging reports for the Accessibility prompt call [C]. Apple's own `kAXTrustedCheckOptionPrompt` documentation suggests warning "on application startup"; the HIG governs product behaviour and says to avoid launch-time requests.
+
+### 3.6 Per-permission API distinctions
+
+"Request class" is how macOS asks. DIALOG: an OS dialog with an answer button. PROMPT-ONCE: a
+request shows at most one dialog that, as far as is known, only offers "Open System Settings"
+and the user must flip a switch (the shape is community-observed, **unverified**). NATIVE: the
+OS prompts by itself on first access.
+
+| Permission (service name for `tccutil`) | Status read without prompting | Ask | Class | Restart after a grant | After a denial | Info.plist key |
+|---|---|---|---|---|---|---|
+| Microphone (`Microphone`) | `AVCaptureDevice.authorizationStatus` (tri-state) [A] | `AVCaptureDevice.requestAccess` [A] | DIALOG | Not documented [A silent]; treat as none [I] | Never asked again; recording yields only silence [A] | `NSMicrophoneUsageDescription`; app exits without it [A] |
+| Screen Recording (`ScreenCapture`) | `CGPreflightScreenCaptureAccess()` returns a Bool, no tri-state [A] | `CGRequestScreenCaptureAccess()` | PROMPT-ONCE | **Conflicting** [C]: some reports say the preflight is frozen per process and a relaunch is needed; one report (macOS 26.6.2) measured no relaunch. Apple documents neither. | Sticky; no re-prompt API. A removed-and-re-added entry can need a reboot [D] thread 818415. | None documented; the repo ships one for parity, effect **unverified** |
+| Accessibility (`Accessibility`) | `AXIsProcessTrusted()` Bool, no tri-state [A] | `AXIsProcessTrustedWithOptions(prompt)` [A]; the prompt call can show again while untrusted [C], so we rate-limit it | PROMPT-ONCE | **Conflicting** [C] | Toggle in Settings | None |
+| Input Monitoring (`ListenEvent`) | `CGPreflightListenEventAccess()`; `IOHIDCheckAccess` tri-state [A] | `CGRequestListenEventAccess()` / `IOHIDRequestAccess` [A]. A listen-only event tap needs Input Monitoring only; an active tap needs Accessibility [A, WWDC19 session 701]. | PROMPT-ONCE | Not documented; a tap created before the grant may stay deaf [C] | Sticky | None |
+| Post synthetic events (`PostEvent`) | `CGPreflightPostEventAccess()`; `IOHIDCheckAccess` [A] | `CGRequestPostEventAccess()` | PROMPT-ONCE; **alias of Accessibility for asking** in this repo (one request, one pane, one episode) | Conflicting / [I] | Sticky | None |
+| Automation (`AppleEvents`) | `AEDeterminePermissionToAutomateTarget(..., askUserIfNeeded=false)`: noErr granted, -1744 not yet decided, -1743 denied, -600 target not running [A header]. Not on the main thread; can hang (Apple forums thread 666528 [D], "clearly a bug"). | Same call with `true`, or the first Apple event | DIALOG | No; checked per send [I] | -1743 forever; `tccutil reset AppleEvents <id>` | `NSAppleEventsUsageDescription` plus the hardened-runtime entitlement [A] |
+| Files and Folders (`SystemPolicy*Folder`, `RemovableVolumes`, `NetworkVolumes`) | None; attempt the access [D] | None; the first access prompts, only in a GUI login session [D] | NATIVE | No | Remembered; normal `EPERM` handling | `NSDesktopFolderUsageDescription` etc., optional but recommended [A] |
+| Login / background item | `SMAppService.status` [A] | `SMAppService.register()` (non-prompting; the OS shows its own notice) [A] | n/a | No | `openSystemSettingsLoginItems()` is the supported opener [A] | None |
+| Keychain | Not TCC | Not TCC | none | n/a | n/a | None |
+
+Camera, speech recognition, Contacts, Calendars, Photos, Location, Bluetooth, Notifications and
+Full Disk Access are **not used by Personal Jarvis** and carry no string and no entitlement.
+
+Deep links: `x-apple.systempreferences:com.apple.preference.security?Privacy_<Service>` anchors
+are an unsupported implementation detail [D]. They have been observed to land on the wrong pane
+when System Settings is already running (BUG-083, macOS 15.7).
+
+### 3.7 macOS version changes that matter
+
+| Version | Change | Evidence |
+|---|---|---|
+| 10.14 | Automation consent, `AEDeterminePermissionToAutomateTarget`, mandatory usage strings, hardened-runtime Apple-events entitlement | [A] header and key pages |
+| 10.15 | Screen Recording, Input Monitoring, Files and Folders; `CGPreflight/Request*Access`, `IOHIDCheckAccess/RequestAccess` | [A] WWDC19 session 701 |
+| 13 | `SMAppService`, Login Items pane, "Background Items Added" notice; System Settings redesign broke old anchors | [A] SMAppService docs; [C] for the notice |
+| 14 | `SCContentSharingPicker`; legacy `CGDisplayStream` triggers extra consent alerts | [A] docs; [D] thread 760483 |
+| 15 | Screen Recording re-confirmation (weekly in betas, relaxed to monthly; cadence of 15.1 and later not verified); "requesting to bypass the system private window picker" alert for non-picker ScreenCaptureKit use; pane named "Screen & System Audio Recording"; Local Network enforcement | [D] thread 765103 for the alert; [C] press snippets for the cadence |
+| 26 | No Apple-documented change to the consent model found; cadence of the re-confirmation contradictory across sources | [C] |
+| 27 ("Golden Gate", reported released 2026-09-14, search snippets only) | The Accessibility pane is reported renamed "Device Control and Data Access"; local TCC database no longer readable by apps; MDM changes | [C] four developer issues; **unverified**, Apple's notes were unreachable |
+
+Design consequence: "Screen Recording was granted but capture now fails or an alert appears" is a
+normal runtime state, not an error. Pane names are static text (no OS sniffing).
+
+### 3.8 Attribution (responsible code) and frozen apps
+
+[D] Apple DTS: the exact algorithm "is not documented, has changed in the past, and may well
+change in the future". Documented cases: run from Terminal, the responsible code is Terminal;
+spawned as a child or helper, "the parent app is treated as the responsible code"; run by
+launchd, the app must be registered through `SMAppService` or the plist needs
+`AssociatedBundleIdentifiers`. Applied to Jarvis:
+
+- Launched from Finder or as a login item: the app bundle is the client; children (the Python
+ backend, `osascript`, `screencapture`) are **expected, not guaranteed** to be attributed to it [I].
+- Launched from a terminal (`python -m jarvis`, the CLI, a dev run): the terminal is responsible,
+ the dialog names it, and the grant lands on it. A "granted" state seen in a dev run says nothing
+ about the shipped app [D, C].
+- The `.dmg` app (`ai.personaljarvis.desktop`) and the managed app (`com.personal-jarvis.desktop`)
+ are two TCC clients with separate grants [I, follows from bundle-id keying].
+- An exec wrapper that replaces itself with the interpreter makes the interpreter the target [C].
+- An ad-hoc or re-signed build loses its grants; a development-signed and a Developer-ID-signed
+ build have incompatible designated requirements [D].
+
+## 4. Target architecture
+
+### 4.1 Decision
+
+Remove the wall, then remove our own UI around it. The feature asks at the moment it first
+needs the permission, from a user gesture; macOS shows its own dialog and the app draws nothing
+around it (no wall, banner, wizard, card, inline note or Settings page). Denial degrades that one
+feature honestly, and because macOS stays silent after a denial, the app says it ONCE in its
+existing toast with one action (4.10); nothing is asked at launch; nothing nags. Where a
+permission cannot be asked "on use" (a global shortcut is a background listener), the
+user's save of the shortcut is the gesture (4.5). The way back to a clean slate is the local
+command `jarvis permissions reset` (4.16).
+
+### 4.2 Principles (rule AP-35)
+
+AP-35 is the rule name used in code comments and commit messages. It is recorded in the
+`AGENTS.md` register (section 3), in `docs/adr/0038-macos-permissions-ask-when-needed.md` (the
+same nine principles) and as the prevention rule of BUG-225 in `docs/BUGS.md`; this table is the
+detailed statement.
+
+| # | Principle |
+|---|---|
+| P1 | **Just in time.** Ask when a feature that needs the permission is first used or switched on by the user, never at launch, never in a banner, never as a wizard (HIG, 3.5). |
+| P2 | **The feature may ask; it must never act on anything but a live GRANTED.** No path refuses because our own preflight says "not granted" before the OS was asked, and none acts on a permission the OS has not granted. `EnsureResult.granted` is true only for GRANTED and NOT_REQUIRED; PENDING, NEEDS_SETTINGS, DENIED and UNAVAILABLE never proceed; a native request's return value is never evidence of success. Silent-failure traps are checked at the source. |
+| P3 | **Let the OS ask where it asks by itself; call the explicit prompt API where it does not.** Never ask by "touching" an API that fails silently. Never create an event tap to provoke a prompt (BUG-058 class): the ask is `CGRequestListenEventAccess` / `IOHIDRequestAccess`, and the tap is created only after the preflight is true. |
+| P4 | **Denied is a stable state, not an error to retry.** Degrade the one feature, say why where the user is, offer one click to the right pane, stop. No repeated prompting, no polling banner. `tccutil reset` stays an explicit, user-run reset (`jarvis permissions reset`). |
+| P5 | **Grants are detected by silent probing owned by the backend** (an episode watcher), applied in process; a restart is only a hint, because the evidence conflicts (3.6). |
+| P6 | **Identity decides who may reset and whether we may auto-ask, not whether we may act.** We act on whatever grant exists. Native requests are made only when running as an installed app bundle, or after an explicit confirmation that names the grantee (`outside_installed_app`). Reset only from the installed app's own bundle id. |
+| P7 | **Opt-in features own their permission.** A feature the user has not switched on never touches its permission (wake word, mute music, computer use, global shortcuts). |
+| P8 | **Honest degradation, always.** Every refusal carries a stable reason and a full English sentence (logs, support, agents); the app shows ONE toast with at most one action, in its own localized copy, only for a user-started use that failed. |
+| P9 | **An AI agent never answers a system dialog.** Agent-facing text is prohibitive; the computer-use engine pauses while a macOS consent window is frontmost. |
+
+### 4.3 Layers
+
+| Layer | Module | Role |
+|---|---|---|
+| Port (OS adapter) | `jarvis/platform/permissions.py`, `SystemPermissionPort` | Live, uncached, non-prompting `state` reads (shallow by default); `request_native` (returns `dialog_shown`, `no_dialog`, `timed_out` or `unavailable`, never evidence of a grant); `usage_string_present`; `outside_installed_app`; `open_pane`; `reset_row` (own bundle id only). It decides nothing about whether a feature may run. Keeps `ACCEPTED_BUNDLE_IDS`, `AUTOMATION_TARGETS`, `PANE_FAMILY`, `REQUEST_CLASS` and the module-loader seams for fakes, plus `remove_leftover_state_files` (4.13). |
+| Service | `jarvis/platform/permission_service.py`, `PermissionService` | The just-in-time layer: `check`, `ensure`, `ensure_all`, `ensure_async`, `ensure_all_async`, `outstanding`, `add_listener`, `open_settings`, `report_failed_use`, `report_use_ok`, `note_reset`, `note_app_activated`, `refresh_episodes`, `invalidate`, `check_deep`, `app_info`, `can_request`, `attach_bus`. No framework import at module scope, no I/O at import (AP-26); off macOS `ensure` returns NOT_REQUIRED before the port is asked anything. Resolves the port per call, so test stubs apply. |
+| Protocol | `jarvis/core/protocols.py`, `PermissionGate` | `check`, `ensure`, `ensure_async`, `ensure_all`, `open_settings`. Consumers receive the gate through an injectable hook with a default resolver to the service singleton; `tests/fakes/fake_permission_service.py` injects there. `force_ask`, `report_failed_use`, `report_use_ok`, `note_reset` and `add_listener` are service-only; consumers reach them by capability lookup. |
+| Consumers | audio, speech pipeline, desktop app gates, computer use, screen capture (`jarvis/platform/screen_access.py`) and context, dictation insert, window control, ducking, hotkeys | Low-level helpers only `check()` and degrade silently; interactive `ensure` exists only at entry points that carry a user gesture (4.6). |
+| Routes | `jarvis/ui/web/permissions_routes.py` | Passive snapshot v2 and single-row GETs; `POST /{id}/request`, `/open-settings`, `/reset` (4.9). The toast calls `request` and `open-settings`; the CI probe, the CLI and agents read the snapshot. `/reset` has no UI caller any more and still refuses scripts. |
+| CLI | `jarvis/cli_ctl/commands/permissions.py` | `jarvis permissions status`, `request`, `open-settings` (all through the routes) and `reset`, which runs `/usr/bin/tccutil` locally and never uses the route (4.16). |
+| Events | `jarvis/core/events.py` | `PermissionNeeded`, `PermissionResolved` over the existing `/ws` wildcard forwarder (4.9). |
+| Frontend | `jarvis/ui/web/frontend/src` (the frontend paths on this page are relative to it) | One toast (4.10): the event twin `lib/permissionEvents.ts`, the planner and state `lib/permissionToast.ts`, the app's existing toast layer and store (`components/ToastLayer.tsx`, `store/events.ts`) and the `permissions.toast.*` strings. Nothing else renders a permission. |
+
+### 4.4 Service contract
+
+`PermissionOutcome`: `granted`, `pending`, `denied`, `needs_settings`, `unavailable`,
+`not_required`. `EnsureResult` carries `permission`, `outcome`, `state`, `asked`,
+`outside_installed_app`, `agent_detail`, `user_detail`, `reason`, `can_prompt`,
+`can_open_settings`, `target`; `granted` is true only for GRANTED and NOT_REQUIRED.
+
+`ensure(permission, *, feature, interactive=True, wait_s=0.0, target=None, trace_id=None,
+allow_outside_app=False, force_ask=False)`:
+
+1. Non-darwin: NOT_REQUIRED, publishes nothing, no port access.
+2. A read of the state. GRANTED resolves any open episode.
+3. RESTRICTED: refuse with reason `restricted` (explanation only, no Settings button).
+ UNAVAILABLE (no GUI session, framework missing): refuse with `unavailable`.
+4. `interactive=False` (a background consumer): never a native request; opens a
+ `background`-origin episode (snapshot only, never a toast, except the wake word in 4.10).
+5. `interactive=True` outside an installed app and without `allow_outside_app`: no native
+ request; the result says `outside_installed_app` so the toast can offer "Ask macOS now" with
+ an explicit confirmation (`allow_outside_app`, a person at the window only).
+6. `interactive=True` otherwise: first a capability check (`usage_string_present`; a missing key
+ would terminate the process, BUG-058 class), then:
+ - DIALOG class and `not_determined`: `request_native`, then wait up to `wait_s` in 250 ms
+ polls (`wait_s=0` returns PENDING at once);
+ - PROMPT-ONCE class: native request unless one was already made in this process within the
+ cooldown, then PENDING or NEEDS_SETTINGS (never "denied" while a dialog may be open);
+ - DENIED: no native call, outcome DENIED;
+ - Automation: the target must be in `AUTOMATION_TARGETS` (else UNAVAILABLE, logged); asked
+ through the killable runner, never under a lock.
+7. Never raises for a native failure: UNAVAILABLE with a fixed-template sentence and a debug log
+ (AP-30). An unknown permission id is a programming error (`ValueError`).
+
+Per-process cooldown between two native requests, from `_REASK_AFTER_S` in the service
+(these are our own figures, not Apple's): microphone 120 s and Automation 120 s (while a dialog
+may still be open), Accessibility 600 s, Input Monitoring 600 s, Screen Recording once per
+process. An explicit click (`force_ask`) skips the PROMPT-ONCE cooldown and the per-episode single request
+(`PermissionService._claim`), never a denial and never a DIALOG dialog that may still be open. A failed native request is not retried automatically for
+30 s.
+
+**There is no persisted "asked" memory.** It would resurrect the BUG-083 dead end after
+`tccutil reset`, a re-sign or another bundle id (red-team finding, recorded in the service
+docstring).
+
+`report_failed_use(permission, *, feature, target=None, trace_id=None, reason=None,
+origin=None)` is how a consumer reports a REAL failed attempt to use a permission it was granted.
+It never asks and never restarts anything. Two families have a producer, each with ONE reason it
+can carry (`reason=None` means that default; a reason the family cannot carry, or any other
+permission, falls back to a plain non-interactive `ensure`). `origin` (`user` or `background`)
+overrides the family default; a value outside the event vocabulary is ignored, and the existing
+callers pass neither argument and behave as before:
+
+- **Screen Recording and Input Monitoring: `restart_hint`**, episode origin `user` by default. The
+ one producer of that reason: a consumer calls it after a real capture or tap failure while the
+ state reads granted (or after the user returned from Settings and the preflight is still
+ negative). Never an automatic restart (`_RESTART_HINT_FAMILIES` in
+ `jarvis/platform/permission_service.py`).
+- **Automation: `needs_settings`**, episode origin `background` by default. A send to ONE player
+ (`target`, a bundle id from `AUTOMATION_TARGETS`; anything else is refused with UNAVAILABLE, opens
+ no episode and is never echoed) was refused with `-1743` although the probe read GRANTED. It is
+ NOT a restart hint (Apple Events are checked per send) and it never asks: no native request,
+ `can_prompt` false. The live state is read once through the guarded Automation read; if it no
+ longer reads granted, the plain `ensure` path describes its real reason instead. Otherwise the
+ slot of that (feature, player) episode is marked `refused_use` and ONE `blocked` /
+ `needs_settings` event is published (a repeat is deduplicated, so a refusal on every voice session
+ start stays one event and refreshes the ten minute clock). Its detail is a fixed sentence that
+ names the player and says the access reads as allowed but the Apple Event was refused. **A granted
+ probe never ends it** (the watcher, a status read and `ensure` all keep it open, because that
+ probe is exactly what lied). It ends through `report_use_ok(permission, *, feature,
+ target=None)` (a later send to that player landed: `PermissionResolved(granted=True)`), through
+ `note_reset` (a reset dropped the decision), or after ten minutes without a report. The
+ restart hints of the other two families still end through `note_reset`. While the state reads
+ granted, a following `ensure` still answers GRANTED (P2: it is the send that decides, not the
+ probe). The effect on a real Mac is unverified: Apple documents `-1743` only as an error code,
+ and whether the child `osascript` is attributed to the grantee is open (A14, R5).
+
+It has three callers, all exercised only against fakes:
+
+- Input Monitoring: `jarvis/trigger/backends/quartz.py` (`report_if_deaf`), once per tap when the
+ tap runs, the grant is visible, no raw event arrived, Secure Event Input is off and key activity
+ was seen. A raw event arriving later ends the episode again (`note_reset`).
+- Screen Recording: `jarvis/platform/screen_access.py` (`_unusable_grant_refusal`, reached from
+ `verify_frame_is_real`), when the state reads granted yet other apps' windows show no readable
+ title. Only a user-started capture reports; a background capture stays quiet. A later frame whose
+ window list shows a readable title ends the episode (`_clear_failed_use`, through `note_reset`).
+ `jarvis/cu/capture.py` deliberately does not report for a native-capture timeout while the grant
+ reads live, because nothing failed for good there.
+- Automation: `jarvis/audio/ducking/macos.py` (`mute_others`, a voice session start), when the
+ duck script to a player whose probe read GRANTED fails with `-1743`. The player is skipped for
+ that session (the other player still ducks), and the ducker reports with `reason="needs_settings"`
+ and `origin="background"` on the player's bounded call slot (never longer than the probe timeout:
+ the controller holds its lock around `mute_others`). A send that lands for a player that was
+ reported calls `report_use_ok`; the switch-on ask (`prewarm`) does too when a fresh ask was
+ allowed for such a player, and otherwise keeps answering `needs_settings` for it. A healthy
+ session never calls either report. A gate without these methods (a scripted stub) gets the older
+ non-interactive `ensure`, which opens an episode only when the live state is no longer granted.
+ The ducker retries the player on every session start: that is how a fix in Settings is noticed.
+
+Accessibility input still has no such path (not implemented).
+
+`note_reset(permission)` drops a slot's restart hint or refused-use mark and forgets the per-process
+ask cooldown; the reset route calls it after a successful reset. The local `jarvis permissions reset`
+command (4.16) is a separate process and cannot call it: the running app notices the changed state
+through its live reads, and the command tells the person to quit and reopen the app.
+
+### 4.5 The permission table: trigger, request, denial, route back, after a grant
+
+Class: DIALOG, PROMPT-ONCE, NATIVE (3.6). EVENT_POSTING is an alias of ACCESSIBILITY for asking.
+
+| Permission | Request kind | Trigger (a user gesture) | How we ask | If not granted | Route back | After a grant |
+|---|---|---|---|---|---|---|
+| **Microphone** | DIALOG | Dictation key or button; push-to-talk; the Call chord and a voice session; switching the **wake word** on (the route asks with `wait_s=0`); the wake self-test button (`wait_s=60`, the test is the JIT moment). In the embedded window, "speak in this conversation" reaches the microphone through the web view's own `getUserMedia`; the app adds no pre-ask (R1) | `request_native` (`AVCaptureDevice requestAccess...`) when `not_determined`, then the stream opens | Voice and dictation refuse (`DictationRefused("microphone_unavailable")` plus `PermissionNeeded`): the native bar shows its own localized sentence, the app shows ONE toast; typed chat unaffected; zeros are never recorded silently | The toast's **Open System Settings** (System Settings > Privacy & Security > Microphone) | Usable at once [I; Apple does not document a restart requirement]. The wake loop that was parked wakes on `PermissionResolved`. A HOLD key pressed during the dialog is **not** started retroactively: press again. |
+| **Screen Recording** | PROMPT-ONCE | First capture started by a user goal: computer-use perception, the `screen_snapshot` tool body, a user-requested screen-context or Appshot capture | `CGRequestScreenCaptureAccess()` (once per process; an explicit Allow always) | Capture refuses with an honest error, never a wallpaper frame; `PermissionNeeded(needs_settings)` and, for a user-started capture, ONE toast | The toast's **Open System Settings** (pane "Screen & System Audio Recording"; the pane naming per macOS version is [C], unverified; "Screen Recording" before macOS 15; the toast sentence names no pane). On macOS 15 and later the first capture may also show the OS "bypass the system picker" alert. A stuck entry may need a reboot [D 818415]; `jarvis permissions reset screen_recording` (4.16) forgets the stale record. | The window-title oracle (`_screen_capture_live_check`) decides. A capture timeout while the state reads granted is PENDING ("macOS may be asking you to confirm"), not DENIED. A restart is offered only after a real failed attempt. |
+| **Accessibility** and post-event | PROMPT-ONCE | First time Jarvis must type, click or focus for the user: computer-use input, dictation auto-paste, window focus and maximize. AX **reads** (tree, element at point) are background: never prompt, degrade | `AXIsProcessTrustedWithOptions(prompt)`, at most once per 10 minutes per process; an explicit Allow always | Dictation falls back to `clipboard_only`; computer-use tools return `[permission_needed:accessibility] ...`; window tools return the same prefix; a user-started use also shows ONE toast | The toast's **Open System Settings** (pane "Accessibility", reported renamed on macOS 27, 3.7; the toast names no pane, no OS sniffing) | A silent watcher; taps and observers are rebuilt on a false-to-true edge. The first paste after an in-process grant reports `paste_sent` until delivery is observed. |
+| **Input Monitoring** | PROMPT-ONCE | A global shortcut is a background listener, so nothing at the moment of USE can carry a dialog; the user's SAVE of a shortcut is the gesture: `PUT /api/settings/keybinds` asks after the save when the key tap is not listening (macOS only, never for a cleared shortcut, never for a re-save of the combo already in force, `wait_s=0`; any caller that passes the route's auth counts as the gesture, like the wake-word switch), and the onboarding voice step's "Skip, I'll use the Call shortcut" click asks once. Never at boot | `CGRequestListenEventAccess()` / `IOHIDRequestAccess` only; the event tap is created only after the preflight is true | The shortcut stays dead and the app keeps working from button and voice; the Esc-to-cancel pill never claims a dead key; a denied save shows ONE toast | The toast's **Open System Settings** (pane "Input Monitoring"; the toast never says "you denied": the entry is reportedly auto-registered after a request, BUG-083 live finding on one Mac, [C], unverified) | The watcher re-arms the hotkey in process (a listener sets the existing reload path). "No raw events arrived" is a restart hint (toast variant "Quit and reopen"), never an automatic restart. |
+| **Automation** (Music and Spotify only) | DIALOG | Switching "Mute music while dictating" on **while a player runs**. Never mid-dictation, never by launching a player. (A sign-in or coding-agent window opened through AppleScript for Terminal is outside this service: macOS asks by itself, unverified.) | The killable `osascript` consent runner (120 s, own daemon thread) | Ducking skips that player; a denied switch-on shows ONE toast ("Personal Jarvis needs your permission to control another app.") | The toast's **Open System Settings** (pane "Automation") | Checked per send. A send refused with `-1743` after a GRANTED read becomes one background `needs_settings` episode naming the player (`report_failed_use`, 4.4); it ends when a later send to that player lands (`report_use_ok`), never because a probe reads granted. |
+| **Files and Folders** | NATIVE | Whenever the user or an agent touches the folder | The OS prompts by itself; never pre-checked or enumerated "to check"; needs a GUI login session [D] | Normal `EPERM` handling | System Settings > Files & Folders | Immediate |
+| **Keychain** | not TCC | Reading a stored key | The `security` vault, then the 0600 file fallback (existing) | File fallback; no UI of its own | `jarvis permissions status` reports the storage kind; `jarvis permissions request credential_store` replays the read | n/a |
+| **Login item** | not TCC | Autostart (existing, default on) | A LaunchAgent; the OS shows its own notice [C], see R7 | n/a | Login Items | n/a |
+| Camera, Contacts, Calendars, Notifications, Full Disk Access, Location | n/a | Not used | n/a | n/a | n/a | n/a |
+
+**Input Monitoring is asked when a shortcut is saved, from the backend.** `PUT /api/settings/keybinds`
+saves, live-applies and persists first, then (macOS only, only for a combo that is actually bound, only
+while the key tap is not listening) calls `service.ensure(INPUT_MONITORING,
+feature="global_shortcuts", wait_s=0)` from the sync handler (a worker thread). It never waits for the
+dialog, never fails the save (a failing ask is logged, AP-30), never asks for a clear, from a GET, from
+a rejected save, or off macOS, and never at launch. The outcome reaches the app as `PermissionNeeded` /
+`PermissionResolved` (the hotkey trigger re-arms itself on the grant, 4.6). The same route used to
+carry a `shortcuts_status` field for the deleted status note; it is gone (4.13). The onboarding voice
+step has one more gesture: choosing the Call shortcut instead of a wake word posts
+`/api/permissions/input_monitoring/request` once.
+
+### 4.5a The whole user-visible surface: trigger, Apple's dialog, denial
+
+Everything a person sees about a permission, in one table. Apple draws the dialog; the app draws
+nothing before or around it. Labels as in the conventions: only the Info.plist keys, the toast and the
+refusal texts are **[code]**; every statement about what macOS shows is community-observed or an
+inference and **unverified** on a Mac (7.4).
+
+| Permission | Triggered by (a user gesture) | What macOS shows itself | Our words inside Apple's dialog | After a denial or a silent failure |
+|---|---|---|---|---|
+| Microphone | Dictation key or button, push-to-talk, Call chord or voice session, switching the wake word on, the wake self-test | The system microphone dialog; the answer is final and macOS never asks again [A]; button labels are not documented ("Don't Allow" / "OK" is an inference [I]) | `NSMicrophoneUsageDescription` (en, de, es) | Toast "Personal Jarvis needs microphone access to hear you." with **Open System Settings**. A refused dictation also shows the native bar's own localized sentence (`ui/orb/bus_bridge.py`, unchanged). Typed chat works. All-zero audio while granted: one "denied or muted" notice |
+| Screen Recording | The first capture a user starts: computer use, `screen_snapshot`, a screen-context request, an appshot | A one-shot alert that mainly leads to System Settings, no Allow button [C]; on macOS 15 and later an extra "bypass the system picker" alert may follow [D 765103] | None (no usage-string key exists; the string we ship is for parity, effect unverified) | Toast "Personal Jarvis needs screen recording access to see your screen." The capture itself refuses with an honest sentence, never a wallpaper frame; a computer-use mission ends with its spoken readback (`cu_blocked_*`, unchanged) |
+| Accessibility | The first time Jarvis must type, click or focus for the user: computer-use input, dictation auto-paste, window control | The same one-shot alert pointing at System Settings [C] | None | Toast "Personal Jarvis needs accessibility access to control other apps for you." Dictated text stays on the clipboard (`clipboard_only`); tools return `[permission_needed:accessibility]` |
+| Input Monitoring | Saving a global shortcut; choosing the Call shortcut in onboarding (4.5) | The same one-shot alert pointing at System Settings [C] | None | Toast "Personal Jarvis needs input monitoring access so your shortcuts work in other apps." The shortcut stays dead, buttons and voice work |
+| Automation | Switching "Mute music while dictating" on while a player runs | The Automation consent dialog naming the app under control [A behaviour]; labels not documented | `NSAppleEventsUsageDescription`, target-neutral (the dialog names the app itself) | Toast "Personal Jarvis needs your permission to control another app." Ducking skips that player |
+| Files and Folders | The first access to Desktop, Documents, Downloads, a removable or a network volume | The system prompt, quoted by an Apple engineer: "'AAA' would like to access files in your Desktop folder. [Don't Allow] [OK]" [D 678819] | `NSDesktopFolderUsageDescription` and its siblings, one short sentence each (en, de, es) | Normal `EPERM` handling; no event, so no toast |
+| Keychain | The first read of a stored key | The Keychain prompt | None | The 0600 file fallback; no UI |
+
+The toast sentences never name a settings pane (the names change per macOS version) and are
+localized in en, de and es (`permissions.toast.*`). Two more variants exist for every permission: a
+**restart** sentence ("Access to {what} is on, but it only works after Personal Jarvis restarts.",
+action **Quit and reopen**, only after a real failed use) and, in a development run outside the
+installed app, an **outside** sentence with the action **Ask macOS now** (an explicit confirmation of
+the grantee, 4.9). A device-policy restriction gets a sentence and no action. The conditions under
+which a toast appears at all are in 4.10.
+
+### 4.6 Per-consumer behaviour (execution context is part of the contract)
+
+Rule: `ensure(wait_s>0)` only from a worker thread or via `ensure_async`; a loop, Tk or tap
+caller uses `check()` or `wait_s=0`.
+
+| Site | Context | Behaviour |
+|---|---|---|
+| `jarvis/audio/capture.py`, `MicrophoneCapture` | async | One `ensure_async` at open (`permission_feature`, `interactive`). No per-frame or 0.25 s probes. The watchdog's existing 1 s tick calls `check(MICROPHONE)`; a revoke raises `MicrophoneAccessError` (carries the `EnsureResult`). **Digital-silence guard:** 5 s of exact zeros while the OS says granted triggers one re-check and one `PermissionNeeded` ("access is probably denied or muted"); unverified on a Mac. Restarts are non-interactive. |
+| `jarvis/ui/desktop_app.py` gates, `jarvis/speech/pipeline.py` | loop | Two silent predicates: background capture (wake word, barge-in) needs a live GRANTED; a user gesture (push-to-talk, a voice session, dictation) needs "not denied", because the gesture itself asks. The wake loop parks on a reload event set by `PermissionResolved(microphone)`, never a 2 s churn. First press: `ensure("microphone", wait_s=0)`. |
+| `jarvis/ui/web/settings_routes.py` | route | Wake switch on: blocking `ensure(wait_s=0)` from the sync handler (a worker thread); the response carries `permission:{outcome, reason, can_open_settings}`. Wake self-test: `ensure_async(wait_s=60)`. GET mic-level uses `check` only. Mute-music PUT asks only when switching on with a player running. `PUT /api/settings/keybinds` asks for Input Monitoring after the save (4.5): blocking `ensure(wait_s=0)`, macOS only, only for a bound combo and only while the key tap is not listening; `GET /api/settings/keybinds` never asks. |
+| `jarvis/cu/actuate/base.py` | tool body, worker | `ensure_all([ACCESSIBILITY], wait_s=0)` after the executor authorised the call; non-granted raises `PermissionNeededError`, whose text starts `[permission_needed:accessibility] `. `ToolResult` is unchanged. |
+| `jarvis/cu/engine.py` `_dispatch_tool` | worker | Keeps a **silent** Screen Recording gate before every engine action (the AP-3 choke point and the blind-input guard), never interactive there; maps the `[permission_needed:` prefix to a terminal `blocked_permission` mission state with a user Retry, not a model retry loop. **System-consent guard:** while a macOS consent window is frontmost (`jarvis/cu/system_dialogs.py`, an owner-name list that is itself unverified) nothing is dispatched. |
+| `jarvis/cu/capture.py`, `jarvis/platform/screen_access.py`, `screen_snapshot`, screen context (`jarvis/screen_context/service.py`) | mixed | Helpers `check()` and degrade; gesture entries (`require_screen_recording[_async]`, `wait_s=0`) ask. A screen-context capture is always a user gesture, so its silent probe is followed by one `require_screen_recording_async`; the status route only runs the silent probe. `verify_frame_is_real` runs a pixel sanity check after the grab while the state claims GRANTED (other apps' windows on screen with no readable title refuses with honest text, flat frame or not) and reports the failed use (4.4). GET status routes never prompt. |
+| `jarvis/vision/ax_tree.py`, `element_at_point.py` | worker | AX reads: `check()` and degrade, never a toast. |
+| `jarvis/platform/window_state.py` | worker | `ensure(ACCESSIBILITY, feature="window_control", wait_s=0)`; refusal text starts with the `[permission_needed:accessibility]` prefix. |
+| `jarvis/dictation/insert.py` | worker | First paste: `ensure(ACCESSIBILITY, feature="dictation_insert", wait_s=0)`; `clipboard_only` is a success state (the text is one paste away); `paste_sent` is the honest middle for the first paste after an in-process grant; never sends Return while a dialog could be frontmost. |
+| `jarvis/audio/ducking/macos.py` | worker | Switching on is the only asking path (`prewarm`, off every lock); `mute_others` is non-interactive: it skips and opens a `background` episode. A duck script refused with `-1743` although the read said GRANTED skips that player for the session and calls `report_failed_use(AUTOMATION, target=<player>, reason="needs_settings", origin="background")`; the next send that lands calls `report_use_ok` (only for a player that was reported; a gate without the methods gets a plain non-interactive `ensure`). The controller lock is never held across an ask, and every service call made while it is held is bounded by the probe timeout on the player's own call slot. |
+| `jarvis/trigger/hotkey.py`, `trigger/backends/quartz.py` | loop, tap thread | Requirement is Input Monitoring only. Boot start is silent. `HotkeyTrigger` registers a grant listener that re-arms the backend off the loop (`asyncio.to_thread`). The tap callback never calls `ensure` and takes no service lock; it reads a cached verdict. A raw-callback counter feeds `deaf_tap_suspected`, and `report_if_deaf` (worker thread) turns that into one `report_failed_use` per tap (4.4). |
+
+### 4.7 Boot rule
+
+With every permission `not_determined` (including `wake_word_enabled=True`), launch makes **no
+OS dialog, no input-stream open, no event-tap creation and no capture call**; an upgrader with
+every grant present sees zero toasts and zero requests. The service singleton is lazy; boot order:
+construct (no I/O), then `attach_bus(bus, loop)` in `jarvis/ui/desktop_app.py` right after the
+`WebServer` constructor (before the speech task can ask for the microphone) and again as the first
+line of `WebServer.start()` in `jarvis/ui/web/server.py`; the call only stores two references. `scripts/ci/check_boot_budget.py` runs after touching startup. Tests that
+pin it: `tests/unit/speech/test_voice_permission_jit.py` (boot with all `not_determined`, boot of
+an upgrader, boot on a non-macOS host) and `tests/unit/ui/test_desktop_macos_permission_gate.py`.
+
+### 4.8 Threading, episodes, watcher
+
+- The service lock guards dictionary mutation only; a native call, a poll, a publish, a listener
+ call and a log line never run under it.
+- **Episode:** one coalesced "feature X is waiting on permissions Y", keyed by (pane family,
+ feature). A feature has at most one open record per permission regardless of `wait_s`; a retry
+ loop that re-enters gets PENDING with `asked=False`; at most one native request per permission
+ per episode, except that an explicit "Ask now" click (`force_ask`) may repeat a PROMPT-ONCE request
+ (Accessibility, Input Monitoring, Screen Recording); a DIALOG-class dialog is never asked twice. An episode ends when every permission it needs is granted
+ (`PermissionResolved(granted=True)`) or after ten minutes untouched (`granted=False`). A slot a
+ failed-use report marked (a `restart_hint`, or a refused Automation send, 4.4) stays open while
+ the state reads granted: its probe is what proved unreliable. A refused Automation send ends
+ through `report_use_ok`, `note_reset` or the same ten minutes.
+- **Watcher:** an asyncio task (or one daemon thread without a loop) polls open permissions every
+ 2 s, publishes the edges, calls listeners (cheap, never raising, run on the loop thread when one
+ is attached) and stops when nothing is open.
+- **Phases and origins:** `phase="os_dialog"` (macOS is asking: the app shows nothing) turns
+ `blocked` when the user has to act. For PROMPT-ONCE permissions that is after an app refocus or
+ about 15 s still ungranted; for DIALOG permissions when the dialog was open 130 s or the state
+ turned denied (our own figures). Only `origin="user"` and `phase="blocked"` may produce the
+ toast; `origin="background"` fills the status snapshot only, with ONE exception: a denied
+ microphone for the wake word (4.10). Events are published on a state change, never from
+ repeated silent checks.
+- **Automation reads** can hang [D thread 666528], so every Automation read goes through a guard
+ with a hard timeout, one call in flight per player and a quarantine after a timeout. On an
+ event-loop thread an Automation read never waits.
+- **Screen Recording oracle:** the window-title check enumerates on-screen windows; it runs on a
+ gesture entry and, for a gesture-opened episode, at most every 10 s. Whether the enumeration
+ itself can trigger the macOS 15 alert is **unverified**, hence the low cadence. A proven grant is
+ remembered for SHALLOW reads (the preflight is frozen per process and can only go stale
+ negative); a deep read (the computer-use pre-dispatch gate, the episode watcher) never answers
+ from that memory and drops it when it finds no grant, so a revoke is seen before the next
+ action. The oracle only proves positively, so "no readable window title" also reads as "not
+ granted" there; the next deep read that finds a titled window proves the grant again. The GET
+ status probes (`/api/screen-context/status`) are shallow: they run no oracle.
+
+### 4.9 Events and snapshot v2
+
+Events (frozen dataclasses in `jarvis/core/events.py`, AP-4 parity: Python tuples regex-read
+against the TypeScript twin `jarvis/ui/web/frontend/src/lib/permissionEvents.ts`):
+
+- `PERMISSION_FEATURES`: `voice`, `dictation`, `wake_word`, `computer_use`, `screen_context`,
+ `appshot`, `window_control`, `dictation_insert`, `global_shortcuts`, `audio_ducking`,
+ `browser_voice`.
+- `PERMISSION_NEEDED_REASONS`: `not_determined`, `denied`, `restricted`, `needs_settings`,
+ `restart_hint`, `unavailable`. `PERMISSION_NEEDED_PHASES`: `os_dialog`, `blocked`.
+ `PERMISSION_NEEDED_ORIGINS`: `user`, `background`.
+- `PermissionNeeded(permissions, feature, reason, phase, origin, target, can_prompt,
+ can_open_settings, outside_app, detail)`; `PermissionResolved(permissions, feature, granted)`.
+ `detail` is a fixed-template English sentence for logs and support, never rendered by the UI
+ (the toast has its own localized sentences) and never carrying exception text, paths or
+ window titles (AP-34 spirit).
+- `DictationRefused` is unchanged; the microphone case publishes both it and `PermissionNeeded`.
+- The routine-trigger catalog excludes both events (`2ee24af3c`): the scheduler never dispatches a
+ permission episode to a routine.
+
+`GET /api/permissions/status` (sync, never prompts, never blocks):
+`{platform, supported, headless, app_identity{app_name, bundle_id, bundle_path,
+launched_as_bundle, stable}, outside_installed_app, permissions:[{id, label, status, used_for,
+can_request, can_open_settings, can_reset, restart_hint, detail, settings_path}], needed:[open
+episodes]}`. The Automation row is computed only while `[ducking].enabled` or `?include=automation`
+(reading it asks a running player). Screen Recording is the shallow preflight here (it can only go
+stale negative; a grant shows once the service has proven it, 4.8). EVENT_POSTING has no row of its
+own. `GET /api/permissions/{id}` returns one cheap row. Both GET routes accept `?activated=1`: the
+route calls `note_app_activated()` so a PROMPT-ONCE dialog the person left to flip a switch is
+promoted to `blocked` at once. It is a hint about what the user just did, never a prompt (only
+the UI's `activated=1` counts). **Nothing sends it since the permission UI was removed** (the toast
+does not poll or refetch), so a PROMPT-ONCE episode now turns `blocked` on the roughly 15 s timer of
+4.8 only. The parameter stays this round because the routes do (candidate for a later cleanup, or for
+a window-focus caller of the toast). The snapshot is read by the CI probe, the CLI and agents; no
+frontend seeds from `needed[]` any more.
+
+`restart_hint` on a row is true while a `restart_hint` episode is open for that permission, **even
+when the state reads granted** (that is the case it is reported for: granted, yet a real use
+failed); the row's `detail` is then the fixed restart sentence. The Keychain row has no request
+call: its `can_request` means "Try again", which replays the Keychain read.
+
+A refused Automation send (`report_failed_use`, 4.4) shows as a `needs_settings` / `blocked` /
+`background` entry in `needed[]` that carries the player in `target` and a fixed sentence in
+`detail` naming it (`feature` `audio_ducking`, `can_prompt` false, `can_open_settings` true on a
+macOS desktop). The Automation row keeps the probe's `status` (granted; no key was added to the row,
+AP-4), `restart_hint` stays false, `can_request` stays false (nothing to ask), and its `detail` is
+that sentence for each such player followed by the "checked only while a player is running" note. A
+row names a player only when an open `needs_settings` episode targets it while its own probe reads
+granted, so a plain `needs_settings` (the ask withheld outside the installed app, a dialog nobody
+answered) is not called a refusal. Both GET routes only read: they never ask, and a probe that
+reads granted never closes the episode (only a later landed send does, 4.4). Nothing offers a
+reset for it (the state reads granted, so there is nothing to reset). Its `origin` is `background`,
+so no toast ever shows it: it is for `jarvis permissions status` and agents.
+
+`POST /{id}/request` hands the permission to `ensure(interactive=True, wait_s=0)` and answers at
+once. The body may carry `allow_outside_app` (refused with 403 for an agent: confirming a grantee is for
+a person at the UI), `feature` and `target`. The person at the Jarvis window is identified
+positively: its session cookie, or (open local access has no cookie) the browser-set
+`Sec-Fetch-Site: same-origin` header on a request with no `Authorization` header. Every other
+caller is an agent: a script with the control key and equally a local process that presents no
+credential at all. A request from the UI passes `force_ask=True` to the service (an explicit click
+on the toast's "Ask macOS now" skips the PROMPT-ONCE cooldown); an agent's does not, so a script cannot loop it. For an
+agent `/reset` is refused with 403 (a reset forgets the cooldown, so "reset, then request" would
+be a prompt loop) and `?activated=1` is ignored. The route has no UI caller now; the person's way to
+reset is the local command in 4.16, which does not go through the route. The UI and every other caller have separate
+cooldowns and global caps, so a loop from a shell cannot starve the person's click. Residual limit:
+a local process that deliberately forges `Sec-Fetch-Site` is indistinguishable from the WebView;
+this guards against an agent that follows its instructions, not against malware (the dialog itself
+stays macOS's), and whether the macOS WebView sends the header on every supported release is
+unverified (a WebView without it only loses `allow_outside_app` and the cooldown skip).
+Opening a pane quits a running System Settings first (it ignores the anchor while running,
+BUG-083, observed on macOS 15.7, not documented by Apple), except when the same pane URL was the
+last one this process opened (`_last_opened_url` in `SystemPermissionPort._open_settings`); the user
+may have navigated since, so this is an approximation. `/reset` and `/open-settings`
+answer 409 when the operation did not happen (a reset: while the live state is GRANTED, when the
+state cannot be reset, or off macOS). Each of the three routes has its own 5 s per-(action, permission
+family) cooldown (429 with Retry-After); all three share a global cap of 20 calls per 60 s. Handlers are sync `def`. No agent or router tool exposes ensure, request,
+open-settings or reset (guarded by `tests/unit/platform/test_permission_agent_boundary.py`).
+
+### 4.10 The UI: macOS's own dialog, plus one toast
+
+**What the app draws:** nothing before macOS asks, nothing around its dialog. There is no wall,
+banner, wizard, floating card, inline note, status note, tip, dictation popover, "Enable global
+shortcuts" button or Settings page for permissions. The only thing the app adds is for the one
+moment macOS stays silent: a user-started use FAILED because a permission is off (macOS never asks
+twice, so after a denial nothing tells the person why the feature does nothing), or a granted
+permission still does not work. Then ONE short toast with at most ONE action appears.
+
+**The toast reuses the app's existing toast** (`pushToast` and `ToastLayer` in `store/events.ts`
+and `components/ToastLayer.tsx`), extended by an optional `action` (`{label, onAction, keepOpen}`)
+and an optional `ttlMs`. No new component, so it looks exactly like every other toast in light and
+dark mode and over a terminal pane (theme tokens only). The permission toast stays 20 s (the
+default is 3.5 s, 12 s for a toast with a button) and the layer sits at `z-[115]`: above the first-run
+spotlight, whose scrim would otherwise swallow the click, and below the caption bar. The source is
+the two bus events `PermissionNeeded` and `PermissionResolved` (twin `lib/permissionEvents.ts`,
+parity-tested, AP-4), handled in `lib/permissionToast.ts` from the WebSocket hook.
+
+**When it shows (all must hold):**
+
+1. `origin === "user"` and `phase === "blocked"` (macOS is not asking right now), and the reason is
+ not `unavailable` (nothing to tell, nothing to do).
+2. This window owns host-level prompts: the main window of the embedded desktop app on macOS
+ (`lib/embeddedDesktop.ts`). Every window has a socket and the server broadcasts, so without an
+ owner N windows would toast N times; a detached solo window, a remote browser (it must never
+ offer "Open System Settings" for another computer) and other operating systems never toast.
+3. The episode is not already on screen in this window (dedupe per episode and reason). The memory
+ is dropped when `PermissionResolved` ends the episode (a grant also takes a still-open toast
+ down) and as soon as the toast is gone (dismissed or expired) after a short cooldown, so the
+ person's next press of a feature that ends blocked again is told again. The service cooperates:
+ a USER gesture that lands on a still-open episode makes it publish the current state once more
+ (at most once per 10 s per episode, `_REANNOUNCE_MIN_S`; a background check never does, and
+ re-announcing never asks macOS again). A re-save of an identical shortcut is no gesture (4.5).
+
+A **background** origin never toasts, with ONE exception: a denied microphone for the **wake word**
+(the always-listening feature the person switched on) is told once per app session.
+
+**The sentences and the one action** (`permissions.toast.*`, en, de and es, short and calm, no pane
+names, no jargon):
+
+| Situation | Sentence (en) | Action |
+|---|---|---|
+| Denied or needs the switch, per permission | "Personal Jarvis needs microphone access to hear you." and one such sentence each for screen recording, accessibility, input monitoring, automation, plus a generic one | **Open System Settings**: `POST /api/permissions/{id}/open-settings` |
+| Not asked yet but macOS can still ask | The same sentence | **Ask macOS now**: `POST /api/permissions/{id}/request` with the feature |
+| Development run, not the installed app | "... It is not running as an installed app, so macOS will give the access to the app that started it." | **Ask macOS now** with `allow_outside_app: true` (only the person's own click may confirm the grantee, 4.9) |
+| Allowed but a real use failed (a `restart_hint` episode) | "Access to {what} is on, but it only works after Personal Jarvis restarts." | **Quit and reopen** (`useRestartApp`; a failure shows the existing `permissions.restart_failed` toast; the toast stays open after the press so a "missions are running" answer can be retried) |
+| Device policy (restricted) | "Your Mac does not allow Personal Jarvis to use {what}. Only an administrator can change that." | none |
+| Wake word, microphone denied (once per session) | "The wake word cannot listen: microphone access is off for Personal Jarvis." | **Open System Settings** |
+| An action request failed | "That did not work. Please open System Settings yourself." | none |
+
+**Browser voice in the embedded window** has no pre-ask (R1): when the web view's `getUserMedia`
+is refused by macOS, the realtime control shows a desktop-worded sentence (not the browser "site
+settings" one) and reports the refusal once, from the person's own press, with
+`POST /api/permissions/microphone/request?dry_run=false` and `{"feature": "browser_voice"}`; the
+service opens a user-origin episode, so the microphone toast above takes over. A wake-started call
+never reports. Outside the embedded Mac window the browser's own sentence stays.
+
+**Kept unchanged** (they are the other feedback layers, not permission chrome): the native bar and orb
+text for a refused dictation (`ui/orb/bus_bridge.py`, en/de/es), the spoken computer-use readbacks
+(`jarvis/voice/action_phrases.py`, regex-only, AP-11), the `DictationRefused` and
+`ErrorOccurred(ui.web.dictation)` handling that resets the recording pill, and the
+`permissions.restart_failed`, `topbar.restart_missions_running` and `sidebar.realtime_microphone_*`
+strings. The sidebar "Mic blocked" line and the voice-warming banner's blocked line are gone with the rest.
+
+**Deleted on 2026-10-02:** the floating card and its host and action table, all inline notes (dictation,
+wake word, appshot, browser voice, mute music), the Shortcuts status note and tip, the Settings >
+Privacy page with its nav and search entries, and the stores, hooks and libraries behind them:
+about 4,200 source lines and 5,500 test lines, and roughly 170 of the 184 permission-related
+strings per language. The Python parity tests that read the deleted TypeScript twins were removed or
+retargeted in the same change.
+
+**Honest limits.** The toast is web-styled, not an Apple alert (that was the trade for deleting the
+custom surfaces). It is invisible while the Jarvis window is hidden or not frontmost: a refused
+dictation then still shows on the native bar and a computer-use mission is read out, but a deaf
+shortcut tap has no other surface. A toast raised while the window was hidden is not queued: it is
+told again only when the person tries the feature again with the window visible (the re-announce
+above), so the way out of "no message appeared" is to try again, or to open System Settings >
+Privacy & Security yourself, or `jarvis permissions reset <permission>` (4.16). Its look in the real WKWebView, whether "Open System Settings" lands
+on the right pane on the current macOS, and the whole flow on a Mac are unverified (7.3, M-TOAST-1).
+Definition of done for any change here: production build, light and dark appearance and the
+terminal-pane appearance inspected (AGENTS.md), vitest and locale parity green, no restart ever
+asked of the user. Build and appearance results are not recorded on this page (7.4).
+
+### 4.11 What stays
+
+Stable signed identity (BUG-060, 217, 223); live uncached state reads; the own-bundle `tccutil
+reset` (the route from the installed app, the local `jarvis permissions reset` for the person, 4.16;
+and the one reset the managed installer runs when a rebuild changed
+the bundle's signing identity, `_reset_after_identity_change` in `jarvis/setup/macos_app_bundle.py`;
+the explanatory marker it used to leave is gone); the restart *hint* (never a forced restart); the honest
+wallpaper-only and zero-audio checks; the CI probe of the built app (`scripts/ci/check_frozen_macos_app.py`);
+acceptance of both bundle ids (`ACCEPTED_BUNDLE_IDS` in `jarvis/platform/permissions.py`) for the
+reset gate and the outside-app logic.
+
+### 4.12 Packaging
+
+- **One usage-string table:** `jarvis/core/macos_privacy_strings.py`, stdlib-only, loaded by path
+ from `jarvis.spec` and from the managed bundle's `Info.plist` writer, so the two apps cannot
+ drift. Keys: microphone, screen capture (parity, effect unverified), Apple events, Desktop,
+ Documents, Downloads, removable volumes, network volumes, local network. A parity test and the
+ frozen-app probe assert it on the built bundle. The wording is short and calm: the Apple Events
+ string is **target-neutral** (it names no app: the system dialog itself names the app under
+ control, and the same string serves Music, Spotify and Terminal), and the folder strings say
+ "works with files in your ... folder when you ask it to" (the dialog already names the folder).
+- **German and Spanish dialog text.** The same module holds the de and es strings. Both bundles are
+ localised: `Info.plist` declares `CFBundleDevelopmentRegion` (`en`) and `CFBundleLocalizations`
+ (`en`, `de`, `es`), and `Contents/Resources/{de,es}.lproj/InfoPlist.strings` carries the
+ translated usage strings (UTF-8; English stays the base text in `Info.plist` itself, so there is no
+ `en.lproj`). The `.dmg` app gets the files from `packaging/macos/add_localizations.py`, which
+ `packaging/macos/build.sh` runs on the finished `.app` BEFORE it signs it (the files are part of
+ the code seal, so one added later would break the signature and the notarization); the
+ languages are declared by `jarvis.spec`. The managed bundle writes the same files when it lays
+ out the bundle (`jarvis/setup/macos_app_bundle.py`). `scripts/ci/check_frozen_macos_app.py` asserts
+ the two plist keys and that each `.strings` file equals the table. The bundle format version is
+ **not** bumped (a bump would rebuild every installed bundle, and an ad-hoc rebuild is a new
+ identity that re-asks every permission): an installed managed bundle carries the new strings after
+ the next rebuild that happens for another reason. German and Spanish text is allowed here because
+ this is the closed product surface (`scripts/ci/german-allowlist.txt`). That macOS shows the
+ localised string in its permission dialog on a German or Spanish system, and that it accepts a
+ UTF-8 `.strings` file there, is **unverified** (no Mac was available; Apple's own tooling writes
+ UTF-16).
+- **Removed:** `NSCameraUsageDescription` plus the camera entitlement,
+ `NSSpeechRecognitionUsageDescription`, `NSSystemAdministrationUsageDescription` (the wrong key
+ for Accessibility and Input Monitoring, which have no key). A build that brings one back fails CI.
+- **Entitlements** (`packaging/macos/entitlements.plist`): `device.audio-input`,
+ `automation.apple-events`, `cs.allow-unsigned-executable-memory`,
+ `cs.disable-library-validation`. Apple says an entitlements property list must have no comments
+ [D thread 701514]; the file has none and the build normalises it with `plutil`. On a signed build
+ the probe asserts `codesign -d --entitlements :-`. The shipped images so far were ad-hoc signed
+ without the hardened runtime, so **no entitlement has run on a notarized build** (unverified).
+- The `.dmg` and managed bundles also had packaging defects fixed in BUG-222 (AVFoundation not
+ frozen, `LSBackgroundOnly`), proven on macOS runners (7.4).
+
+### 4.13 What was deleted
+
+Consumer-visible: the banner and its dismissal store, the wizard and its polling, the onboarding
+permissions step, the readiness aggregate in the snapshot (`features`), `wanted`, `active`,
+`identity_reset`, the global `restart_required` and `foreground`; then, in the UI reset of
+2026-10-02, the whole custom permission UI (4.10) and, on the backend, `jarvis/trigger/
+shortcuts_status.py` with the `shortcuts_status` field of `GET /api/settings/keybinds` and
+`HotkeyTrigger.deaf_tap_suspected()` (the shortcut status note was their only reader; the
+backend-level `deaf_tap_suspected` that feeds `report_if_deaf` stays). The routes and snapshot v2
+stay (the CI probe, the CLI and agents read them). Backend: the Automation consent
+file and the hidden launch of Music and Spotify, the identity-reset marker, the readiness
+aggregation, and (BUG-159 fix f) `_reset_or_explain`.
+
+**State of the port (checked by grep, 2026-10-02):** the old members `FEATURE_REQUIREMENTS`,
+`active_features`, `runtime_access_granted` and `runtime_feature_ready`, the legacy `snapshot()` /
+`request()`, `identity_reset_*` and `automation_consent_path` are deleted from
+`jarvis/platform/permissions.py` and from `jarvis/platform/probes.py` (`screen_recording_granted`).
+`tests/unit/platform/test_no_legacy_permission_api.py` fails if any of those names returns to
+`jarvis/`, `scripts/` or `.github/`. The macOS CI step that asserted the old behaviour was replaced
+by "Verify headless permission asks fail closed" (the name is historical): it replaces the three
+native request seams with tripwires, then asserts that outside an installed bundle `ensure`
+requests nothing (`asked` is false) and that nothing but a granted state reads as granted. Two more
+steps were added to `.github/workflows/macos-desktop.yml`: "Probe the native permission symbols" and
+"Smoke the permission service without asking". `tests/unit/ci/test_macos_desktop_permission_step.py`
+runs those scripts against the FakeTCC simulator on any host.
+
+**Leftovers on upgrade.** `macos-tcc-reset.json` and `macos-automation-consent.json` are never read
+any more. The managed source installer deletes them once, best-effort, on its next run
+(`remove_leftover_state_files`, called from `ensure_macos_app_bundle`). The frozen `.dmg` app never
+gets them deleted: `ensure_desktop_integration` returns early for frozen builds, so that cleanup is
+not reached. That is harmless, since nothing reads either file. A stored banner-dismissal key and a
+stored onboarding step `permissions` are ignored or mapped to `voice`, and never prompt.
+
+### 4.14 Non-darwin ledger
+
+| Surface | Windows / Linux behaviour | Pinned by |
+|---|---|---|
+| `ensure` / `check` | NOT_REQUIRED, no events, no port access, no framework import | `tests/contract/test_permission_service_contract.py` (off-macOS scenarios) |
+| Snapshot v2 | Rows `not_required`, `needed: []` | route tests |
+| Onboarding step list | `permissions` is gone from the platform-agnostic list `welcome, keys, subscriptions, voice, ready` (the UI showed it on macOS only); both sides tested | `tests/unit/setup/test_onboarding_meta.py`, `components/onboarding/setup/setupSteps.test.ts` |
+| `jarvis permissions reset` | Prints one line ("only works on macOS") and exits 1; never runs `tccutil` | `tests/unit/cli_ctl/test_commands_permissions.py` |
+| `PUT /api/settings/keybinds` | Never touches the permission layer (no ask off macOS) | `tests/unit/ui/web/test_keybinds_input_monitoring_ask.py` |
+| Settings nav | There is no Privacy or Permissions section on any OS | `tests/unit/ui/web/test_no_permissions_settings_page.py` |
+| Consumers | No gating, no request (FakeTCC call log empty) | consumer tests |
+| Hotkey factory | Unchanged | `tests/contract/test_hotkey_backend_protocol.py` |
+| Windows microphone-privacy analogue, all-zero audio detection off macOS | Out of scope (A9) | n/a |
+
+### 4.15 Global hotkeys: stage S0 now, a Carbon backend later
+
+**Facts [code]:** on macOS global shortcuts use `QuartzHotkeyBackend`, a listen-only event tap
+(`jarvis/trigger/backends/quartz.py`); pynput is the Linux X11 backend. Before this change the
+tap required both Accessibility and Input Monitoring, which is stricter than Apple's rule
+(listen-only needs Input Monitoring only [A, WWDC19 session 701]).
+
+**Stage S0 (this change):** Input Monitoring only; the tap is not created at boot unless already
+granted; re-arm on grant through the service listener (no second path); the asking moment of 4.5 (the
+save of a shortcut; the first status note was deleted again, 4.10); stale texts fixed; a raw-callback counter replaces the dead
+`received_any_event()` liveness signal. A restart hint appears only when the preflight is true and
+no raw event arrived after the user typed (an explicit "still not working" report would need its
+own route and UI and does not exist); never an automatic restart. The Appshot both-Option gesture is **not** an Input Monitoring row: its
+permission need is unverified (`jarvis/appshot/gesture.py` records that it is unverified whether the
+`CGEventSourceKeyState` Option-key read needs Input Monitoring; `jarvis/trigger/hotkey.py` notes that
+the sibling `CGEventSourceFlagsState` read needs no event tap and no Accessibility grant, and says
+nothing about Input Monitoring; neither read was measured on a Mac); nothing in the app asks or says anything about it.
+
+**Documented follow-up, not shipped here (AP-31: no flag before code reads it):** a Carbon
+`RegisterEventHotKey` backend for chords of "modifiers plus exactly one key". Carbon delivers
+press and release [A header `CarbonEvents.h`: `kEventHotKeyReleased`] and is widely reported to
+need no Accessibility or Input Monitoring [C]; the Apple header and docs do not say so. It cannot
+express modifier-only, Fn, side-specific or two-key chords (the shipped Call `f3+f4` and Hangup
+`f1+f2` stay on the tap); macOS 15.0 and 15.1 refused hotkeys whose only modifier was Option or
+Option+Shift (fixed in 15.2 [D thread 763878]); whether release is delivered when a modifier is
+lifted first is unverified. Default Call/Hangup chords for macOS are a maintainer decision.
+
+The red-team **crash-surface list** a Carbon shim must satisfy before any default flips:
+
+1. `restype=c_void_p` on `GetApplicationEventTarget` / `GetEventDispatcherTarget` (otherwise
+ 64-bit pointer truncation and SIGSEGV); `EventHotKeyID` passed by value.
+2. The callback, the `EventTypeSpec` array and the user data are module-level singletons.
+3. Main-thread hop in an event-tracking run-loop mode: use the common modes, and treat a hop
+ timeout as "deferred", never "failed" (a false failure causes a double registration).
+4. At process shutdown do **not** unregister (the OS releases hot keys); a live re-arm waits at
+ most 1 s and is non-fatal (the red team cites a 90 s quit stall seen on 2026-09-30).
+5. Liveness check is "`NSApp` already instantiated and running", otherwise report "unavailable in
+ this mode" and never create an `NSApplication`.
+6. The callback only schedules work onto the loop and returns `eventNotHandledErr` on an internal
+ error (returning 0 would consume the event).
+7. A process-wide `CarbonRegistry`: one handler installed once and never removed, a monotonic
+ hot-key id, refcounted OS registrations with fan-out to owners (four `HotkeyTrigger` instances
+ exist), diff-based re-registration, per-row results.
+8. A sentinel with strike quarantine scoped by app version and macOS build, written after the
+ first successful registration and removed in `shutdown()` before `os._exit`; two consecutive
+ strikes with the same version and build resolve to the tap and say why.
+9. A frozen-app explicit-path load probe.
+
+**Flip rule** (default `auto` may become Carbon-first only if all hold): spike variants green on
+macOS 15 arm64, 15 Intel and the current release with every preflight false; a built-app probe on
+both architectures (load, register, synthetic chord delivered, unregister, clean exit); one
+physical-Mac sign-off from a clean `tccutil reset` (hold-to-dictate including modifier-first
+release, no dialog from the hotkey, Secure Input, window drag during re-arm, ten Settings-save
+re-arms, quit in under 5 s); one opt-in release cycle with no quarantine reports; and the
+`docs/os-parity.md` wording updated.
+
+**The runner spike (shipped):** `scripts/ci/macos_carbon_hotkey_spike.py` and
+`.github/workflows/macos-hotkey-spike.yml` (`workflow_dispatch` only; the temporary branch `push`
+trigger of commit `59749f859` was reverted in `945fe7949`). Runner matrix: `macos-15-intel` and `macos-15`, plus `macos-26`
+only when the dispatch input asks for it (that the label exists for this repository is unverified).
+The script records the TCC context first (`CGPreflightListenEventAccess`, `CGPreflightPostEventAccess`,
+`AXIsProcessTrusted`, `IOHIDCheckAccess`, macOS build, architecture) with non-prompting reads in a
+child process, then runs each risky variant in its own child process group under a hard timeout with
+the exit signal captured: register and unregister under a real `NSApplication` loop (plus 200
+register/unregister cycles and 50 synthetic presses), register with no `NSApplication`, unregister
+off the main thread, duplicate registration, secure event input, installing the handler twice, the
+Appshot both-Option read (key actually held, three injection routes), and two controls that tell a
+harness bug from a Carbon crash. The report is written after every experiment, so a killed parent
+still leaves a table; the verdict "Carbon needs no TCC grant" needs the preflights false in the same
+process that received a hot key event, otherwise it reads `inconclusive`. Limits it states itself:
+runners pre-grant TCC to bash, `osascript` and Terminal; no dialog; no physical keyboard; no hold
+semantics (modifier lifted first, auto-repeat); the hop-mode variant and the off-main register half
+are not covered, so flip criterion 1 stays open. **Result:** it ran once from the branch as run `36954304202` on `macos-15` (arm64, macOS 15.7.9)
+and `macos-15-intel`; both jobs were green. On arm64 all 11 experiments finished and only the
+deliberate control crashed (SIGABRT, as designed); every other variant, including register and
+unregister under `NSApplication`, 200 register/unregister cycles with 50 synthetic presses
+delivered, duplicate registration, secure event input and the Appshot Option read, ended `ok`. The
+report itself marks the run unusable as TCC evidence (`usable=False`: a preflight read granted in
+the test process, because runners pre-grant TCC), so it does not settle whether Carbon needs a
+grant. Variant G and the off-main register half are still not covered, so flip criterion 1 stays
+open. Runner evidence only; nothing on a physical Mac. The Intel per-variant table has not been
+transcribed here. The Linux self-test is `tests/unit/ci/test_macos_carbon_hotkey_spike.py`.
+
+### 4.16 Starting over: `jarvis permissions reset`
+
+macOS never asks twice. After a "Don't Allow", or after a re-sign orphaned a record (BUG-083), the
+only ways back are the switch in System Settings and `tccutil reset`. The Settings > Privacy page and
+its "Ask again" button are gone, so the person's way to a clean slate is a local command:
+
+```
+jarvis permissions reset <permission> [--bundle-id <id>] [--yes] [--dry-run]
+```
+
+- **macOS only.** Elsewhere it prints one line ("permissions reset only works on macOS ...") and
+ exits 1 without running anything, even with `--dry-run`.
+- **Runs locally, not through the app.** It runs `/usr/bin/tccutil reset <Service> <bundle id>` with
+ the service name from the one table the port uses (`tcc_reset_service`: Microphone, ScreenCapture,
+ Accessibility, ListenEvent, PostEvent, AppleEvents). It does NOT call `POST /{id}/reset`, which
+ correctly refuses scripts and Bearer callers with 403 (a reset forgets the re-ask cooldown, so
+ "reset, then request" from an agent would be a prompt loop), and it works with Jarvis closed.
+ `credential_store` has no TCC record and is refused.
+- **On the PATH.** A downloaded-`.dmg` user has no `jarvis` on the PATH until the app's console
+ entry is linked (`packaging/macos/README.md`, "Reaching the CLI"): run
+ `"/Applications/Personal Jarvis.app/Contents/MacOS/jarvis" permissions reset ...` through the
+ bundle (never a copy: a launch from outside it is another identity), or link it once. The user
+ guides say so and give the raw `tccutil reset <Service> <bundle id>` one-liners as the way that
+ needs no command.
+- **Whose record.** The bundle id comes from the installed app's own `Info.plist` (the managed
+ `com.personal-jarvis.desktop` bundle, else the downloaded `ai.personaljarvis.desktop` app), never
+ from the process that runs the command (a terminal). `--bundle-id` accepts only those two ids,
+ for a Mac that has both; any other id is refused (exit 2), so it can never reset another app.
+- **Guard.** It changes the machine directly, so it fails closed without `--yes` (or
+ `JARVIS_CLI_ASSUME_YES=1`), like every destructive CLI action; `--dry-run` prints the exact
+ `tccutil` argv and runs nothing. The subprocess passes `NO_WINDOW_CREATIONFLAGS` and decodes UTF-8
+ (AP-1); a failing `tccutil` exits 1 with its status.
+- **Afterwards.** Quit and reopen Personal Jarvis, then use the feature: macOS asks again. The
+ command cannot tell the running app (a separate process), whose live reads see the new state
+ anyway. `ScreenCapture`, `Accessibility`, `ListenEvent` and `PostEvent` are system-wide services
+ for which `tccutil` may need elevated rights or may toggle instead of deleting (A15).
+- **Raw commands** (the same thing without Jarvis, and for the services the repo never resets) are in
+ the user troubleshooting guide and in 7.1.
+
+Evidence: the command is exercised on Linux with a recording runner, with `FakeTCC.run_tccutil`
+(only the named bundle's row returns to "not asked yet") and with a fake executable standing in for
+`/usr/bin/tccutil`; every permission and both bundle ids are checked against the exact argv. That the
+real `tccutil` accepts each service name and really removes the entry is unverified (A15, M-RESET-1).
+
+## 5. Assumptions
+
+| # | Assumption |
+|---|---|
+| A1 | Autostart stays default-on. |
+| A2 | The Carbon backend and macOS-specific Call/Hangup defaults are deferred; only the spike ships (one runner run, unusable as TCC evidence; see 4.15). |
+| A3 | The camera and speech strings, and the camera entitlement, are removed (no caller). |
+| A4 | No strings for services only a child process could reach (Contacts, Calendars, Photos, Location, Bluetooth); unsupported until an agent feature needs one. |
+| A5 | The WKWebView media-capture delegate (the WebKit decision that sits on top of the TCC dialog) is an open item; the app does not pre-ask before `getUserMedia` (R1): the web view's own request raises the dialog, and a refusal in the embedded Mac window is reported to the service (`POST /api/permissions/microphone/request`, feature `browser_voice`) so the toast can say what to do. |
+| A6 | The macOS 27 Accessibility label is static text; no OS sniffing. |
+| A7 | The Appshot both-Option permission need is unverified. |
+| A8 | No telemetry. The field signal is the support-visible `PermissionNeeded` detail in logs. |
+| A9 | A Windows microphone-privacy analogue and cross-OS all-zero audio detection are out of scope; the digital-silence guard is macOS-only. |
+| A10 | There is no persisted "asked" memory; the once-per-process and cooldown rules are in memory. |
+| A11 | The PROMPT-ONCE shape (the dialog only offers "Open System Settings") is community-observed, not Apple-documented. |
+| A12 | The timing figures (15 s "blocked" after a PROMPT-ONCE request, 130 s DIALOG ceiling, 10 s oracle cadence, 120 s and 600 s cooldowns, the 5 s zero-audio window) are our own choices, not Apple's. |
+| A13 | The list of system consent window owner names in `jarvis/cu/system_dialogs.py` is unverified; a miss leaves the other layers (prohibitive agent text, the grant itself) in force. |
+| A14 | An `osascript` child is attributed to the app for Automation (the ducking sender); unverified. Apple documents `-1743` only as an error code; its behaviour after a grant on a real Mac is unverified. A `-1743` after a GRANTED read is reported as one background `needs_settings` episode naming the player (`report_failed_use`, 4.4) and ends only when a later send lands (`report_use_ok`). |
+| A15 | `tccutil reset` for the system-wide services (`ScreenCapture`, `Accessibility`, `ListenEvent`, `PostEvent`) may need elevated rights or may toggle rather than delete [D thread 788454]; `jarvis permissions reset` for them is unverified (the route additionally verifies the state after a reset; the local command only reports the exit status of `tccutil`). |
+| A16 | Keeping `NSScreenCaptureUsageDescription` is harmless; whether macOS uses it is unverified in both directions. |
+| A17 | Screen Recording consent re-confirmation on macOS 15 and later is a recurring normal state, not an error (3.7). |
+| A18 | The toast (4.10) is the whole permission UI. It is web-styled, shown only in the owner window while it is visible, and its look in the real web view is unverified. The ~20 s lifetime, the 10 s re-announce window and the dedupe rule are our own choices. |
+| A19 | `CGRequestListenEventAccess` called from the save of a shortcut shows macOS's Input Monitoring alert (community-observed for the PROMPT-ONCE class, unverified); the save is chosen because a background listener has no "on use" moment. |
+| A20 | macOS shows the German or Spanish `InfoPlist.strings` text in its permission dialogs on a system in that language, and accepts a UTF-8 `.strings` file there; unverified. English is the fallback for every other language (`CFBundleDevelopmentRegion`). |
+
+## 6. Open points and risks
+
+Everything below is **unverified on a physical Mac**. "Closes with" refers to rows in section 7.
+
+| # | Risk or open point | Why it matters | What the code does today | Closes with |
+|---|---|---|---|---|
+| R1 | **WKWebView `getUserMedia` double dialog.** In the embedded window, `getUserMedia` reaches the same microphone permission; WebKit's own media-capture decision (`WKUIDelegate`) is additional. No handler exists in `jarvis/`. | A user may see two prompts, or WebKit may deny after TCC allowed. | Since the UI reset the app no longer asks before `getUserMedia`: macOS asks when the web view first opens the microphone, and a refusal in the embedded Mac window shows a desktop-worded sentence under the realtime control and is reported once, from the person's own press, to the service (feature `browser_voice`), which opens a user-origin episode so the one toast ("Open System Settings") takes over. The delegate grant is a tracked open item (A5). | M-MIC-3 |
+| R2 | **macOS 27 pane naming.** The Accessibility pane is reported renamed; whether the `Privacy_Accessibility` anchor still resolves is unknown. `NSWorkspace.openURL` returns success even when the wrong pane opens. | The "Open System Settings" button could land on the wrong page. | The toast sentence names no pane; the app quits a running System Settings before opening a pane, unless this process last opened the same pane (an approximation: the user may have navigated since). | M-AX-4 |
+| R3 | **Screen Recording restart conflict.** Reports conflict on whether a running process sees the grant. | Wrong either way: a forced restart annoys, no restart leaves a dead feature. | Re-probe (shallow preflight, then the window-title oracle), try a real capture, offer "Quit and reopen" only after a real failure. | M-SR-4 |
+| R4 | **Accessibility re-prompt and attribution.** The prompt call may show again while untrusted [C]; a Ventura toggle bug returned wrong values [C]. | Nagging or a false "granted". | Rate-limited to once per 10 minutes per process; the paste after an in-process grant reports `paste_sent`. | M-AX-2, M-AX-3 |
+| R5 | **Attribution of child processes.** DTS says the algorithm is undocumented; helper binaries have been separate TCC clients in other products. | The ducker's `osascript`, `screencapture`, ffmpeg or agent CLIs may need their own grant, or may be attributed to Terminal in a dev run. | Expected, not guaranteed. A `-1743` from the ducker's `osascript` after a granted read is reported as a background `needs_settings` episode that names the player (4.4, 4.9). No in-app text about attribution exists (there is no permission page); saying that a grant applies to Jarvis and the tools it starts only as far as macOS attributes them stays a documentation point (the user guide). | M-DEV-1, M-AUTO-3 |
+| R6 | **Appshot both-Option need.** Unverified whether the `CGEventSourceKeyState` Option-key read needs Input Monitoring (`jarvis/appshot/gesture.py`); `jarvis/trigger/hotkey.py` notes that the sibling `CGEventSourceFlagsState` read needs no event tap and no Accessibility grant, and says nothing about Input Monitoring; neither read was measured on a Mac. | It is the default Appshot shortcut and has no gesture that "enables" it. | Not an Input Monitoring row; nothing asks or says anything about it. The runner spike can read it, but runners cannot prove the permission outcome for a real user. | M-HK-5 |
+| R7 | **Autostart notice.** The LaunchAgent runs `/usr/bin/open` without `AssociatedBundleIdentifiers`, so Login Items shows the program or organisation name, and macOS posts its own "Background Items Added" notice [A for attribution, C for the notice]. | Looks like an unexplained permission prompt. | Autostart stays default-on (A1); documented as a product decision. | M-LOGIN-1 |
+| R8 | **Hardened-runtime entitlements never ran on a notarized build.** | A missing `audio-input` entitlement silently suppresses the microphone prompt [C, D]. | The probe asserts `codesign -d --entitlements :-` on a signed build; every runner build so far was ad-hoc signed. | M-SIGN-1 |
+| R9 | **Keyboard-layout and input-source collision.** The default dictation toggle chord equals a macOS input-source shortcut when several input sources exist [I]. | A dead shortcut that is not a permission problem. | Not changed. | M-HK-4 |
+| R10 | **Intel versus Apple Silicon.** Runners cover both; grants and prompts were never compared on hardware. | Architecture-specific frozen-app defects. | Runner smoke on both. | M-ARCH-1 |
+| R11 | **Screen Recording first-capture double dialog and the monthly alert** on macOS 15 and later; an app cannot suppress it. | A first capture may show two dialogs; a capture timeout while an alert is up is not a denial. | A timeout while the state reads granted is PENDING; no periodic background capture without opt-in (P7). | M-SR-2, M-SR-5 |
+| R12 | **Stranded grant after a re-sign** (checkmark on, kernel refuses). | Settings shows the switch on and the feature does not work. | The person runs `jarvis permissions reset screen_recording` (4.16) and reopens the app, or removes the entry with minus and re-adds it (reboot hint). The app offers no button for it. | M-SR-6 |
+| R13 | **Files and Folders in a headless session.** The prompt appears only in a GUI login session [D]. | A launchd-started backend is silently denied. | Normal `EPERM` handling; nothing pre-checks or enumerates those folders. | M-FF-1 |
+| R14 | **Digital-silence guard threshold.** 5 s of exact zeros while granted is our own figure. | Could mis-report a deliberately muted source, or miss a quiet one. | One report, stays open, the stream is not torn down. | M-MIC-5 |
+
+Follow-ups, not part of this change: the Carbon backend (4.15), macOS Call/Hangup defaults, the
+`WKUIDelegate` media-capture grant, `AssociatedBundleIdentifiers` for the LaunchAgent, a
+`Capabilities.ax_permission_granted` cleanup (the probe still exists in `jarvis/platform/probes.py`
+and feeds the capability record), a `report_failed_use` path for Accessibility input (4.4; the
+Automation path for ducking exists), and any per-turn computer-use permission message (cut from v1: the one toast plus the mission's `blocked_permission` ending; a deck journal
+line by trace id was never built). Also open: a window-focus caller for the `?activated=1` hint (4.9), and a surface for a deaf
+shortcut tap while the Jarvis window is hidden (the toast is invisible then, 4.10).
+
+## 7. Manual test checklist for a real Mac
+
+Nothing in this section has been run: no physical Mac existed while the design and the UI reset were
+built. Each row is a check that fakes and Linux gates cannot make.
+
+### 7.0 Prerequisites
+
+- **Macs and versions:** at least one Apple Silicon Mac and one Intel Mac, on macOS 15 (the version
+ with the live findings in 2.2) and on the current release; a macOS VM snapshot is preferred (7.1).
+ Record the macOS version and build, the architecture and the app version in every row.
+- **Builds:** the `.dmg` app from a release or from the desktop installers workflow
+ (`docs/desktop-installers.md`, "macOS"); drag it to Applications. The managed source-install app
+ comes from the one-line installer in `README.md` (`install/install.sh`). Both are listed with
+ their bundle ids in 7.1. State which build and signature (ad-hoc, self-signed, Developer ID)
+ each row ran on.
+- **Voice turns:** use a subscription or a local model; send one turn, never a loop against a paid
+ provider.
+- **Where things are (UI strings from `en.json`):** there is **no** permissions page and no
+ **Privacy** entry in Settings. The dictation keys are on **Voice > Shortcuts** ("Push to talk",
+ "Hands-free"); read them there and write them down: the defaults in `jarvis/core/config.py` are
+ `ctrl+right_alt+j` (hold to talk) and `ctrl+right_alt+space` (press to start, press again to
+ stop); on a Mac keyboard record what the page shows for the right-hand Alt key. Saving a
+ shortcut is possible on **Voice > Shortcuts**, on the **Keyboard shortcuts** page and under
+ **Settings > Keyboard shortcuts**. "Mute music while dictating" is under **Settings > Overlay &
+ taskbar**. The wake word is under **Settings > Wake word** ("Activate wake word", "Test wake
+ word"). The composer's dictation button is labelled "Dictate"; the voice-conversation control is
+ "Speak in this conversation". The one toast in the top-right corner is the whole permission UI of
+ the app (4.10).
+- **Result column:** write PASS or FAIL. A row whose Expected cell says "record" passes when the
+ observation is written down in the Result cell and shows no crash, no hang and no dialog the row
+ does not predict; anything else is FAIL with a note.
+
+### 7.1 Setup, identities and reset commands
+
+- Bundle ids used by the repo (`jarvis/core/branding.py`, `ACCEPTED_BUNDLE_IDS`):
+ - `.dmg` app: **`ai.personaljarvis.desktop`**;
+ - managed source-install app: **`com.personal-jarvis.desktop`**.
+- Each is a separate TCC client with separate grants. Test each one; always reset the id of the
+ app under test.
+- **Quit Jarvis first, then reset, then start it.** A reset while the app runs leaves stale state in
+ the running process. After any reset, open System Settings > Privacy & Security and check the
+ list: an unchanged list means the reset did nothing (see the caveats below).
+- **The supported reset is the CLI (4.16):** `jarvis permissions reset <permission> --yes` for the
+ installed app, or with `--bundle-id <id>` for the other one. The raw `tccutil` commands below are
+ what it runs, and they also cover services the repo never resets (the `SystemPolicy*` names are [C] /
+ unverified). That each name is accepted by `tccutil`, and that each reset really removes the entry,
+ is unverified for every macOS version: check each command on the Mac under test.
+
+Reset everything for one app (replace the bundle id with the one under test):
+
+```bash
+for s in Microphone ScreenCapture Accessibility PostEvent ListenEvent AppleEvents \
+ SystemPolicyDesktopFolder SystemPolicyDocumentsFolder SystemPolicyDownloadsFolder \
+ SystemPolicyRemovableVolumes SystemPolicyNetworkVolumes; do
+ tccutil reset "$s" ai.personaljarvis.desktop # or com.personal-jarvis.desktop
+done
+```
+
+Single services, used by the rows in 7.3 (`<id>` is the bundle id under test):
+
+| Permission | CLI | Raw command |
+|---|---|---|
+| Microphone | `jarvis permissions reset microphone --yes` | `tccutil reset Microphone <id>` |
+| Screen Recording | `jarvis permissions reset screen_recording --yes` | `tccutil reset ScreenCapture <id>` (system-wide service, may need `sudo`, may toggle instead of delete) |
+| Accessibility | `jarvis permissions reset accessibility --yes` | `tccutil reset Accessibility <id>` |
+| Post synthetic events | `jarvis permissions reset event_posting --yes` | `tccutil reset PostEvent <id>` (reset it together with Accessibility) |
+| Input Monitoring | `jarvis permissions reset input_monitoring --yes` | `tccutil reset ListenEvent <id>` |
+| Automation | `jarvis permissions reset automation --yes` | `tccutil reset AppleEvents <id>` |
+| Files and Folders | none | `tccutil reset SystemPolicyDesktopFolder <id>`, `tccutil reset SystemPolicyDocumentsFolder <id>`, `tccutil reset SystemPolicyDownloadsFolder <id>`, `tccutil reset SystemPolicyRemovableVolumes <id>`, `tccutil reset SystemPolicyNetworkVolumes <id>` |
+
+- Prefer a fresh macOS VM snapshot between runs (Apple DTS: "the most reliable way to test TCC is
+ in a VM, restoring to a fresh snapshot between each test" [D]; the thread id was not recorded
+ when this page was written, so the wording is unconfirmed).
+- "Dialog" below always means Apple's own system dialog. Jarvis shows its own toast only where a row
+ says so, and never while a dialog is open.
+
+### 7.2 Environment-level rows
+
+| ID | Scenario | Steps | Expected | Result | Signed off (name, date) |
+|---|---|---|---|---|---|
+| M-FRESH-1 | Fresh install (`.dmg`) | Quit the app; run the "reset everything" loop of 7.1 for `ai.personaljarvis.desktop`; install the `.dmg` (drag to Applications); start the app from Applications; walk the first-run setup (welcome, keys, subscriptions, voice, ready) | App starts. No Apple dialog, no toast, no banner, no wizard at launch or on the welcome, keys and subscriptions steps, and no permissions step in setup. On the voice step, switching the wake word on is a user gesture and raises Apple's microphone dialog (expected; record its text and language). If the wake word stays off, no dialog appears during setup. Settings has no Privacy entry | | |
+| M-FRESH-2 | Fresh install (managed app) | Same loop for `com.personal-jarvis.desktop`; install with the one-line installer (7.0) | Same as M-FRESH-1, including the voice-step microphone dialog | | |
+| M-FRESH-3 | Boot with the wake word on and nothing granted | Enable the wake word in a previous run, quit the app, run the microphone reset for the app under test, start the app | No dialog at launch; no input stream opened; no toast (the wake loop only parks); record whether anything is visible. After pressing the dictation button the dialog appears. Separately deny the microphone and restart: exactly one toast "The wake word cannot listen: microphone access is off for Personal Jarvis." with **Open System Settings**, once per app session | | |
+| M-UPG-1 | Upgrader with all grants present | Grant everything, then update or restart the app | Zero toasts, zero requests, features work at once | | |
+| M-DEV-1 | Terminal-launched dev run (outside the installed app) | `python -m jarvis` (or the dev launcher) from a terminal | The outside-app path: no native request without the confirmation. After a user-started use, the toast says Jarvis is not running as an installed app and offers **Ask macOS now**; pressing it asks macOS, whose dialog names the terminal app as the grantee. A "granted" state here proves nothing about the installed app | | |
+| M-APP-1 | `.dmg` app versus managed app | Grant the microphone to one, start the other | The other app is not granted and asks on its own first use | | |
+| M-ARCH-1 | Intel and Apple Silicon | Repeat M-FRESH-1 and the microphone and Screen Recording rows on one Mac of each architecture | Same behaviour; record any difference | | |
+| M-UI-1 | Light and dark appearance of the toast | Trigger a blocked episode (deny the microphone, press **Dictate** again) in light and in dark mode, and over a terminal pane | One toast in the top-right column: the app's normal toast look (nothing different from, say, a "saved" toast except its button), one sentence, the button **Open System Settings**; legible and on theme tokens in both modes, does not cover the terminal controls, does not take focus from the dictation target, stays about 20 s, closes on the X and on the button. Record how it looks in the real WebView | | |
+| M-UI-2 | Toast during first-run setup | Provoke a blocked episode while the setup spotlight is up (switch the wake word on, deny the dialog) | The toast sits above the spotlight scrim and its button is clickable | | |
+| M-TOAST-1 | Owner window and duplicates | With the main window and one detached window open, provoke a blocked episode; then open the app in a remote browser | The main window shows one toast; the detached window and the remote browser show none | | |
+| M-TOAST-2 | Dedupe | Provoke the same blocked episode twice in a row | One toast for the episode; after the permission is granted and revoked again, a new failed use may show a new one. A grant while the toast is open takes it down | | |
+| M-TOAST-3 | Hidden window | Hide or minimise the Jarvis window, then dictate into another app with the microphone denied | No toast is visible (expected); record that the native bar shows its own sentence and that nothing else is missing. Press **Open System Settings** later from the visible toast, if one was kept | | |
+| M-TOAST-4 | Button wiring per variant | For one denied permission press **Open System Settings**; for a not-yet-asked one press **Ask macOS now**; for a restart hint press **Quit and reopen** | Settings opens on the right pane (R2); the native dialog appears; the app restarts (and refuses while a mission runs, with the existing message) | | |
+| M-LOC-1 | Localised dialog text | Check `ls "<app>/Contents/Resources"` for `de.lproj` and `es.lproj` in both builds and `plutil -lint` on each `InfoPlist.strings`; `codesign --verify --deep --strict "<app>"`; set the macOS language to German, reset the microphone, press **Dictate** | The files exist and lint; the signature verifies (the strings are inside the seal); the microphone dialog shows the German sentence (record), Spanish the same, any other language the English text; the Automation and folder dialogs carry the short target-neutral wording | | |
+| M-RESET-1 | `jarvis permissions reset` | With the app closed, run `jarvis permissions reset microphone --dry-run`, then with `--yes`, for each bundle id (`--bundle-id` for the other one); also try it from a non-macOS host and with a foreign `--bundle-id` | The dry run prints `/usr/bin/tccutil reset Microphone <id>` and runs nothing; the real run exits 0 and the entry disappears from System Settings; the next use asks again; another app's entry is untouched; the foreign id is refused (exit 2); off macOS one line and exit 1. Record whether `screen_recording`, `accessibility` and `input_monitoring` need `sudo` or only toggle (A15) | | |
+| M-SIGN-1 | Signed build entitlements | On a Developer ID signed build: `codesign -d --entitlements :- "<app>"` | Lists `audio-input`, `apple-events`, the two `cs.*` keys; no camera key; the microphone dialog appears on first use | | |
+
+### 7.3 Per permission
+
+For every row: record the exact dialog text, whether the app was frontmost, and whether anything
+unexpected appeared (a second dialog, a hang). "The toast" is the one toast of 4.10; the sentence per
+permission is in 4.5a.
+
+| ID | Permission | Trigger action | Expected dialog or behaviour | Denial path | Route back | After-grant behaviour |
+|---|---|---|---|---|---|---|
+| M-MIC-1 | Microphone | Quit the app, reset the microphone (7.1), start it, then press **Dictate** in the chat composer (UI-started) | Apple microphone dialog naming the app with the usage string; no toast while the dialog is up | Press Don't Allow: the native bar shows its refusal sentence and the app shows the toast "Personal Jarvis needs microphone access to hear you." with **Open System Settings**; typed chat still works | The toast's **Open System Settings** opens System Settings > Privacy & Security > Microphone | Allow it there: dictation works without a restart (a second press of **Dictate**); the toast, if still open, goes away |
+| M-MIC-2 | Microphone, hold key | Same reset as M-MIC-1, then press and hold the hold-to-talk shortcut (7.0) | First press raises the dialog; releasing does not start a late recording | After Allow, nothing starts on its own; the next hold works | as above | as above |
+| M-MIC-3 | Microphone, voice conversation | Same reset as M-MIC-1, then press **Speak in this conversation** (embedded window) | The web view's own microphone request (R1: note whether WebKit adds a second dialog); the app adds no pre-ask | Deny: the realtime control shows its desktop-worded "microphone access was denied" sentence AND the microphone toast with **Open System Settings** appears (the press reports the refusal to the service, R1) | System Settings > Microphone | Press again after allowing |
+| M-MIC-4 | Microphone, wake word | Same reset as M-MIC-1, then switch **Settings > Wake word > Activate wake word** on; separately try **Test wake word** | The switch is the gesture: the dialog appears; the test button waits up to a minute for the answer | Deny: the wake loop stays parked; the switch's own ask (a user gesture) shows the microphone toast; on later starts with the wake word on and the microphone denied, exactly one wake-word toast per app session says it cannot listen | as above | The parked wake loop starts on its own after the grant |
+| M-MIC-5 | Microphone, zeros | With the app granted, set the input to a muted or disconnected source (or revoke while running) | After about 5 s of exact zeros: one "denied or muted" notice, no crash; revoking while running ends the stream within a few seconds and shows the toast | n/a | as above | Restore and retry |
+| M-SR-1 | Screen Recording | Quit, reset `screen_recording`, start; ask Jarvis to look at the screen (the snapshot tool or computer use) | `CGRequestScreenCaptureAccess` dialog offering Open System Settings; the capture refuses honestly (**no wallpaper frame**) | Don't allow or ignore: the toast "Personal Jarvis needs screen recording access to see your screen." appears about 15 s after the unanswered or ignored dialog (4.9: nothing sends the `activated` hint any more, so a refocus alone does not raise it), no repeated prompting | Pane "Screen & System Audio Recording" (or "Screen Recording" before macOS 15); the toast's **Open System Settings** | After flipping the switch, return to Jarvis: note whether capture works in the running process (R3), and whether the **Quit and reopen** variant appears (only after a real failed capture) |
+| M-SR-2 | Screen Recording, macOS 15 and later | Capture twice, as a user, after the grant | Note any "bypass the system picker" or "Allow for one month" alert, its timing, and that a capture timeout during it is shown as pending, not denied | n/a | n/a | n/a |
+| M-SR-3 | Screen Recording, computer use | Start a computer-use task | One coalesced episode for Screen Recording and Accessibility if both are missing (one toast, one sentence for the first); the agent text tells the agent not to touch the dialog; with a consent window frontmost nothing is dispatched | Mission ends as `blocked_permission` with the spoken readback and a Retry | panes | Retry continues |
+| M-SR-4 | Restart conflict | Grant while Jarvis runs, return to Jarvis, capture again | Record: works without restart / works only after restart / still blocked; the restart toast appears only after a real failed attempt | n/a | n/a | n/a |
+| M-SR-5 | Lapse | Revoke the grant while running, run a computer-use task | The next action fails closed with an honest message | n/a | pane | n/a |
+| M-SR-6 | Stranded entry | After a re-sign or a manual remove and re-add, the switch shows on but capture fails | The restart toast, or no toast at all (nothing reads "denied"); run `jarvis permissions reset screen_recording --yes` with the app closed, reopen, retry | n/a | the CLI reset, or remove with minus and re-add; reboot if the entry is stuck | macOS asks again on the next capture; record |
+| M-AX-1 | Accessibility | Quit, reset `accessibility` and `event_posting`, start; use dictation into another app (auto-paste), or a computer-use click | First time Jarvis must type or click: Apple Accessibility dialog (offers Open System Settings); until granted the dictation falls back to the clipboard and says so | Deny: text stays on the clipboard (`clipboard_only`); the toast "Personal Jarvis needs accessibility access to control other apps for you." | Pane "Accessibility" (macOS 27: note the actual label, R2) | Flip the switch: the first paste after the grant is reported as sent, not as inserted, until observed |
+| M-AX-2 | Accessibility, no re-prompt | Click the same action repeatedly while untrusted | At most one dialog per 10 minutes per process, and one toast per episode | n/a | n/a | n/a |
+| M-AX-3 | Accessibility reads | Without the grant, use anything that reads the UI tree | No dialog, no toast; the feature degrades quietly | n/a | n/a | n/a |
+| M-AX-4 | Deep link | Press the toast's **Open System Settings** for Accessibility, Input Monitoring and Screen Recording with System Settings already open on another pane | The right pane opens (the app quits a running System Settings unless this process last opened the same pane, then opens the anchor); on macOS 27 note whether the anchor resolves. Extra step: open pane A, navigate manually to another pane in System Settings, press the button for A again, and record whether the pane shown is A | n/a | n/a | n/a |
+| M-IM-1 | Input Monitoring, saving a shortcut | Quit, reset `input_monitoring`, start; open **Voice > Shortcuts**, record a new Call chord and save it | Apple Input Monitoring dialog right after the save; **nothing at boot**; the shortcut is saved either way; saving again in the same episode asks nothing new; clearing a shortcut asks nothing; with the permission granted and the tap listening a save asks nothing | Deny: the toast "Personal Jarvis needs input monitoring access so your shortcuts work in other apps." with **Open System Settings**; buttons and voice keep working; Esc-to-cancel never claims a dead key | Pane "Input Monitoring" | The shortcut works in the running process or after a restart: record which; the restart sentence appears as the **Quit and reopen** toast only after real typing produced no events |
+| M-IM-2 | Input Monitoring, onboarding | Fresh install, voice step: choose "Skip, I'll use the Call shortcut" | The ONE click asks for Input Monitoring (Apple dialog); the sentence "No wake word? The Call shortcut works anytime." is true afterwards; no dialog if the wake word was chosen | Deny: no toast during setup is expected (the click is the gesture; record whether one appears) | as above | as above |
+| M-HK-1 | Hold-to-dictate | Hold the dictation shortcut in another app | Dictation starts on press and ends on release | n/a | n/a | n/a |
+| M-HK-2 | Hold-to-dictate, modifier released first | Hold the dictation shortcut, release the modifier key before the letter key | Record whether dictation ends, or keeps recording until the letter key is released (settles part of the Carbon flip rule in 4.15) | n/a | n/a | n/a |
+| M-HK-3 | Re-arm and quit | After a clean reset and one grant: save a shortcut in Settings ten times in a row; drag a window during a re-arm; then quit the app and time it | Each save re-arms the shortcut without a dialog; dragging stays smooth; the app quits in under 5 s. Record any miss | n/a | n/a | n/a |
+| M-HK-4 | Chord collision | Check the default toggle chord against System Settings > Keyboard > Keyboard Shortcuts > Input Sources | Record any collision (R9) | n/a | n/a | n/a |
+| M-HK-5 | Appshot both-Option | With Input Monitoring **not** granted, press both Option keys | Record whether it fires (settles R6) | n/a | n/a | n/a |
+| M-AUTO-1 | Automation | With Music running (a window open), switch **Mute music while dictating** on (Settings > Overlay & taskbar) | Apple Automation dialog naming the app and Music, with the target-neutral usage string; Music is not launched by Jarvis; with no player running, no dialog | Deny: the toast "Personal Jarvis needs permission to control another app for this."; dictation continues without ducking | Pane "Automation" | Ducking works on the next dictation |
+| M-AUTO-2 | Automation off | Keep the switch off | No Automation dialog ever, no player launched | n/a | n/a | n/a |
+| M-AUTO-3 | Attribution | After Allow, dictate while music plays | The volume drops (a `-1743` after Allow means the grant is not attributed to the app that sends; record it, R5). If it does not drop, `jarvis permissions status --include-automation` names the player (one background `needs_settings` episode, never a toast); after the switch is fixed, the next dictation ducks | n/a | n/a | n/a |
+| M-AUTO-4 | Terminal | Start a subscription sign-in that opens a Terminal window | Record whether macOS shows a separate "control Terminal" Automation dialog (outside the permission service) and what a denial looks like | n/a | n/a | n/a |
+| M-FF-1 | Files and Folders | Ask Jarvis to list or save a file in Desktop, Documents or Downloads | Apple's own prompt on first access, with the short usage string; nothing pre-checks the folders | Deny: normal error handling, no toast | System Settings > Files & Folders | Immediate |
+| M-KC-1 | Keychain | First read of a stored key after install or update | The Keychain prompt; after a declined dialog Jarvis keeps working from the local file (`jarvis permissions status` reports the storage kind) | n/a | `jarvis permissions request credential_store` replays the read | n/a |
+| M-LOGIN-1 | Autostart | Reboot or log in again with autostart on | Record the "Background Items Added" notice and the name shown in Login Items (R7) | n/a | Login Items | n/a |
+| M-AGENT-1 | An agent never answers a dialog | With a dialog on screen, start a computer-use task | Nothing is dispatched; the mission stops with `blocked_permission` | n/a | n/a | n/a |
+
+### 7.4 Evidence ledger: what was verified, and how
+
+**NOT verified on a physical Mac.** Nothing in this table is a substitute for section 7.3.
+
+| Layer | What | How | Result recorded | Strength |
+|---|---|---|---|---|
+| Unit and contract tests on a framework-level simulator | The service's outcomes, episodes, cooldowns, events, the scenario table on macOS and off it; boot with every permission undecided; an upgrader with all grants; a non-macOS host never touches TCC; the consumers (audio capture, ducking, dictation insert, hotkey tap, screen capture and context, computer use, window control); the routes and snapshot v2; **since the UI reset:** the keybinds ask on save, the `jarvis permissions reset` command, the Info.plist and `.lproj` content, the frozen-app probe and the build script | `tests/fakes/fake_tcc.py` (a stateful TCC simulator: per-service states, scripted dialog policy, no re-ask after a decision, a frozen Screen Recording preflight until relaunch, an ordered call log of probes, requests and implicit prompts, a `tccutil` stand-in), `tests/fakes/fake_permission_service.py`, and the test files named in 4.5, 4.12 and 4.16 | **2026-10-02, Linux sandbox, Python 3.11, no GPU, no audio hardware, real bash 3.2 first on `PATH`:** `python -m pytest -p no:cacheprovider tests/unit/cli_ctl tests/unit/ci tests/unit/packaging tests/unit/setup tests/unit/trigger tests/contract/test_hotkey_backend_protocol.py tests/contract/test_permission_service_contract.py tests/unit/platform tests/unit/core/test_permission_events.py tests/unit/ui/web/test_keybinds_input_monitoring_ask.py tests/unit/ui/test_keybinds_route.py tests/unit/ui/web/test_wake_activation_permission.py tests/unit/ui/web/test_permissions_routes.py tests/unit/ui/web/test_permissions_snapshot.py tests/unit/ui/web/test_dictation_start_failures_parity.py tests/unit/scripts` gave **2846 passed, 25 skipped, 1 failed** (237 s). The one failure, `tests/unit/setup/test_macos_app_bundle.py::test_a_changed_interpreter_still_earns_a_fresh_rebuild`, asserts that the running interpreter is not Python 3.11 and fails the same way on the untouched branch (a sandbox-only failure). A second run of `tests/unit/ui/web` together with the keybinds, mic-level, voice-permission, ducking and dictation-insert tests (1012 tests) gave 1009 passed and 3 failed (a skills-route name, a society-figure asset path, and a timing-sensitive local-models overlap test that passes alone); the first two fail identically on a clean checkout of the base commit, none touches permissions. The 25 skips are platform or optional-dependency skips | The fake models what the code believes about macOS, not macOS itself. It proves the logic, not the OS behaviour |
+| Frontend tests | The toast planner and its event parity, the toast layer's action, the i18n parity of `permissions.toast.*`, the production build, the light, dark and terminal-pane inspection | Vitest, `npm run build`, a browser harness | **Not recorded on this page.** They belong to the frontend package of the UI reset and are reported there; a Linux browser is not the macOS web view, so the real look stays a checklist row (M-UI-1) | Logic and a browser look only; no real web view |
+| Linux gates | Docs privacy scan, public-docs (manifest, links, front matter, word budget), generated CLI references, language gate, silent-exception and dead-config gates, bash 3.2 parse, `actionlint` on the touched workflow, the frozen-app probe against a synthesized bundle, the build script's `DRY_RUN` | `scripts/ci/run_gates.py --base origin/main --pr` with the real bash 3.2 first on `PATH`, `actionlint .github/workflows/macos-desktop.yml`, `scripts/ci/check_frozen_macos_app.py`'s `check_app` on a bundle laid out with `packaging/macos/add_localizations.py`, `DRY_RUN=1 packaging/macos/build.sh` | **2026-10-02:** every gate passed (private keys, dist consistency, brand logos, mirrors, CLI coverage, danger metadata, install methods, dead config switches, silent exceptions, async routes, WebGL, plugin auth contract, reference docs, docs privacy, public docs, bash 3.2 parse of all 9 shell scripts, privacy, no new German, history); `actionlint` printed nothing; the probe reported both missing `.lproj` files on the bare bundle, passed after the build step ran, and flagged a tampered Spanish file; the dry run prints `add_localizations.py` before the first `codesign`. The privacy and language gates compare committed history, so the working-tree additions were also checked with the gate's own functions (no violations; without the allowlist entry for the string table it reports 10) | Static and portable-code checks |
+| macOS CI lane | Imports of the native frameworks; a tripwire proof that nothing asks outside an installed bundle; symbol binding; a service smoke that never asks; the bundle self-probe; a curated test list | `.github/workflows/macos-desktop.yml` (steps in 4.13); its scripts also run against FakeTCC in `tests/unit/ci/test_macos_desktop_permission_step.py` | **No runner result is recorded for this branch.** The lane steps exist and their scripts pass against the simulator on Linux; the lane itself has not been seen to run green on a macOS runner with the new steps | Runner only; informational shards once it runs |
+| Installer workflow dispatch | The `.dmg` app builds with the new spec on Apple Silicon and Intel, `scripts/ci/check_frozen_macos_app.py` passes, the frozen app boots twice and reads its permission status: microphone "granted" under `ai.personaljarvis.desktop`, so AVFoundation loads inside the app | Desktop installers workflow, run 36923225371 at commit `43eeb7aed`, 2026-10-01, no release published (as recorded in commit `ed489bece`) | Passed on both architectures, **ad-hoc signed**, no hardened runtime, no notarization. It predates the just-in-time rebuild, so it says nothing about the new service | Runner evidence. It proves packaging, not prompts, not Gatekeeper |
+| Runner spike | Carbon hot-key crash surface | `.github/workflows/macos-hotkey-spike.yml` (dispatch only, 4.15) | Run `36954304202` at commit `59749f859`: harness green on `macos-15` (arm64) and `macos-15-intel`; the arm64 report's verdict is `usable=False` (a preflight read granted in the test process), so it is not TCC evidence; variant G and the off-main register are not covered | Runner only |
+
+What none of the above shows: any real dialog, wording of any dialog, the behaviour of a grant in
+a running process, hold-key semantics, the Developer ID or notarized build, macOS 26 and 27
+behaviour, a user's Intel Mac, light and dark appearance of the toast in the real web view, that its
+button opens the right pane, that macOS shows the German and Spanish usage strings or accepts the
+UTF-8 `.strings` files, the real `tccutil` behaviour of each service name, or the double dialog in the
+embedded WebView. Each is a row in 7.2 and 7.3 awaiting a sign-off.
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 20d3450175..a8ce70f04a 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -657,8 +657,11 @@ can actually deliver it, with nothing raising in between:
- **Event-tap permission probe.** The TCC grant check ran on EVERY reconcile,
i.e. two native ObjC calls per keystroke the machine sees, inside the tap
callback. macOS DISABLES a tap whose callback overruns its deadline — the
- "works sometimes, or not at all" report. Now throttled (1 s TTL) while
- staying fail-closed.
+ "works sometimes, or not at all" report. Now throttled (1 s TTL).
+ **Superseded 2026-10-02:** the tap callback reads only a lock-free cached
+ verdict from the silent `PermissionService.check`, never calls `ensure` and
+ takes no service lock; the tap itself is created only after the Input
+ Monitoring preflight is true (see the 2026-10-02 pass below).
- **Computer-Use numpad.** `base._NAMED_KEYS` accepts `numpad0`-`numpad9`
plus the five operators and Windows maps every one; the POSIX table mapped
none, so the identical action died off-Windows with
@@ -703,9 +706,10 @@ Windows, macOS and Linux/X11: a call-scoped capture session, deferred BGRX
conversion, area-filtered thumbnails, and bounded polling with persistent
effect confirmation. Windows' native window capture remains a capability-
gated first choice with the shared rectangle path as its fallback. The
-existing macOS Screen Recording gate, Wayland refusal and headless refusal are
-unchanged, so an unavailable capture backend never becomes permission to act
-blindly. The cross-platform tkinter engine rig remains the release oracle.
+macOS Screen Recording gate (a silent check before the engine acts; the grant
+itself is asked for at the first user-started capture, 2026-10-02 pass below),
+Wayland refusal and headless refusal are unchanged, so an unavailable capture
+backend never becomes permission to act blindly. The cross-platform tkinter engine rig remains the release oracle.
**Fix pass 2026-08-16 (the app is findable as an app).** BUG-138 was a Windows
defect, but its shape was shared: on all three systems the launcher file was
@@ -750,11 +754,165 @@ with it, so macOS pins privacy grants to `identifier + certificate` instead of
the per-build CDHash: rebuilds and updates keep every grant. Without a GUI
session, or if the dialog is declined, signing stays ad-hoc and the previous
"reset on identity change" behaviour applies. The Music/Spotify Automation
-consent is a permission row of its own (`automation`), asked up front through
-`AEDeterminePermissionToAutomateTarget` with a hidden launch of a closed
-player, and **Set up everything** walks all rows and ends in a single restart.
-Windows and Linux: no TCC, no signing identity, the rows read "not required"
-as before.
+consent is a permission row of its own (`automation`), read live through
+`AEDeterminePermissionToAutomateTarget` for a running player. **Superseded
+2026-10-02:** the up-front ask with a hidden launch of a closed player, the
+consent file and the **Set up everything** wizard that this pass added are
+removed; Automation is asked when "Mute music while dictating" is switched on
+while a player runs (below). Windows and Linux: no TCC, no signing identity,
+the rows read "not required" as before.
+
+**Fix pass 2026-10-01 (macOS: the downloaded app, and what is worth asking
+for, BUG-222/223/224).** Four findings behind a report of a Mac that asked for
+far too many permissions.
+(1) The `.dmg` app carries its own bundle id (`ai.personaljarvis.desktop`) and
+the permission port accepted only the managed bundle's id, so the downloaded app
+read every grant as unusable: no microphone capture, no hotkeys, no request
+buttons. Both ids are now installed identities (`ACCEPTED_BUNDLE_IDS`), reset
+targets the running app's id (and refuses from any other process), and
+`jarvis permissions` finds either app.
+(2) The published v2.5.0 image — opened and read on Linux, not run on a Mac —
+had no `AVFoundation` module in its frozen archive (the port loads it by name, so
+the microphone permission reads "unavailable" for good) and `LSBackgroundOnly` in
+its `Info.plist` (PyInstaller sets it when the last executable is a console one).
+`jarvis.spec` and the macOS job now cover both, and
+`scripts/ci/check_frozen_macos_app.py` fails a build that regresses. A branch
+dispatch of the installer workflow built the image on the Apple Silicon and the
+Intel runner, the check passed, and the booted app reported a readable
+microphone permission under the `.dmg` bundle id (BUG-222); still not tried on a
+user's Mac.
+(3) The published `.dmg` was ad-hoc signed and not notarized (the v2.5.0 build
+log says so), and the workflow's certificate secrets were never imported by
+`build.sh`: it now imports them into a throw-away keychain, before the long
+freeze, so the Apple secrets (five required, the signing identity optional) are
+what is still missing to attempt a Developer-ID-signed, notarized image — a path
+that has never run; until then the first launch needs **System Settings >
+Privacy & Security > Open Anyway** (macOS 15) and an update can re-ask the
+permissions.
+(4) The snapshot then marked which rows a feature the user turned on needs
+(`wanted`, `features[...].active`), with a banner that skipped optional rows and
+could be put off with "Not now". **Superseded 2026-10-02:** those keys, the
+banner and the wizard are gone; a feature the user has not switched on simply
+never touches its permission (below). **Not verified:**
+all of it ran against faked native frameworks, a `DRY_RUN` rehearsal and a
+stand-in `security` command on Linux; no Mac, no Apple account and no real
+notarization were available. Windows and Linux are unchanged — no TCC, no
+signing identity.
+
+**Fix pass 2026-10-01 (macOS: one table of usage strings).** The two macOS
+bundles declared different, partly wrong `NS...UsageDescription` sets: the
+downloadable `.dmg` app had no screen-capture string, the managed app had no
+Desktop / Documents / Downloads string, and the `.dmg` plist carried
+`NSSystemAdministrationUsageDescription` (the wrong key for Accessibility and
+Input Monitoring, which have none), a speech-recognition string and a camera
+string plus the camera entitlement, for APIs Jarvis never calls. Both bundles now
+load one stdlib-only table, `jarvis/core/macos_privacy_strings.py`, by path (the
+spec runs before the package is importable): microphone, screen capture (kept for
+parity; whether macOS reads that key is unverified), Apple events, Desktop,
+Documents, Downloads, removable and network volumes, and local network (reworded
+to the LAN hosts the person configures). The three unused keys and the camera
+entitlement are gone, `entitlements.plist` carries no XML comments (the reasoning
+moved to `packaging/macos/README.md`), and `scripts/ci/check_frozen_macos_app.py`
+asserts the table on the built app and, on a signed build, the entitlements
+`codesign` reports. The managed bundle's format version is deliberately NOT bumped
+(a bump rebuilds every installed bundle, and an ad-hoc rebuild is a new identity that
+re-asks every permission): an installed app carries the new strings after its next
+rebuild for another reason. **Not verified:** no Mac, no
+hardened signed build and no real `codesign` output were available; the checks
+ran against the real `jarvis.spec` with stand-in PyInstaller names and recorded
+`codesign` output shapes on Linux. Windows and Linux are unchanged — no TCC, no
+usage strings.
+
+**Fix pass 2026-10-02 (macOS: permissions are asked for when a feature needs
+them, BUG-225, AP-35, ADR-0038).** Before this pass every protected macOS
+feature first asked `runtime_access_granted()` (stable identity AND a live
+grant) and refused when it said no, so macOS was never asked from a feature path
+and an app-wide banner, **Set up everything** and an onboarding step stood in
+front of the dialog. Now a feature asks at the user's gesture through
+`jarvis/platform/permission_service.py` and acts only on a live grant; denial
+degrades that one feature (one toast with one click to System Settings, see the UI
+reset below). What changed per surface (Windows and Linux are unchanged: NOT_REQUIRED, nothing
+asked, nothing gated):
+
+- **Microphone.** Dictation, push-to-talk, a voice session, the wake-word switch
+ and the microphone self-test ask. The wake loop stays parked, with no dialog and
+ no input stream, until a grant exists. A denial refuses voice and dictation with
+ the native bar's sentence and the one toast; typed chat is unaffected. A hold key
+ pressed while the dialog is up is not started retroactively. Five seconds of
+ exact zeros while the state claims granted produce one "denied or muted" notice.
+- **Screen and computer use.** The first user-started capture asks for Screen
+ Recording; a flat wallpaper-only frame is refused, never delivered. Accessibility
+ is asked when Jarvis first types, clicks or focuses a window; tools return
+ `[permission_needed:accessibility]`, and the mission ends `blocked_permission`
+ with a Retry, not a model retry loop. AX reads never prompt. The engine keeps one
+ silent Screen Recording gate and dispatches nothing while a macOS consent window
+ is frontmost (an agent never answers a system dialog; the owner-name list is
+ unverified).
+- **Dictation insert.** The first paste asks for Accessibility; until granted the
+ transcript stays on the clipboard (`clipboard_only`) and the bar says so.
+- **Global shortcuts.** The listen-only tap needs Input Monitoring only (it used
+ to need Accessibility too). It is not created at boot unless already granted,
+ never created to provoke a prompt, and re-arms in process when the grant
+ arrives. Saving a shortcut asks for Input Monitoring (below). The Esc-to-cancel pill
+ claims the key only while the tap runs.
+- **Ducking.** Switching "Mute music while dictating" on while a player runs is
+ the only asking path (120 s consent runner, no hidden launch of a player);
+ `mute_others` is non-interactive and skips a player that has not consented. A
+ player that refuses the Apple event with `-1743` although its read says granted
+ is skipped too and reported as one background `needs_settings` episode that
+ names it (`jarvis permissions status`, never a toast); it ends when
+ a later send to that player lands, not because a probe reads granted. Windows
+ and Linux: nothing happens (no TCC, empty call log); the effect on a real Mac is
+ unverified.
+- **Appshot both-Option shortcut.** Not an Input Monitoring row: whether the
+ `CGEventSourceKeyState` read needs a grant is unverified (the repo contradicts
+ itself), so nothing asks or says anything about it.
+- **Boot rule.** With every permission undecided, including the wake word on,
+ launch makes no OS dialog, no input-stream open, no event-tap creation and no
+ capture call; an upgrader with every grant shows zero toasts and zero requests.
+
+The onboarding `permissions` step, the banner, the wizard and the refresh event are
+removed. **Not verified:** all of it ran against a stateful fake of the macOS
+frameworks, vitest and Linux gates; the packaging and frozen-app probes ran on
+macOS runners (which pre-grant TCC to their tools and show no dialog). No Mac
+showed a dialog, a hold-key release, the second dialog of the embedded WebView or
+a grant taking effect in a running process; the rows are in
+`docs/macos-permissions.md` section 7. The Carbon hotkey backend and macOS-specific
+Call/Hangup defaults are follow-ups, not shipped.
+
+**Fix pass 2026-10-02, UI reset (macOS: macOS's own dialog plus one toast,
+ADR-0038 amendment).** The first just-in-time implementation also drew a floating
+card, inline notes, a Shortcuts status note and a Settings > Privacy page around
+macOS's dialog. All of it is deleted. macOS shows its own dialog at first use; the
+app adds ONE short toast with ONE action only when a user-started use failed
+because a permission is off (macOS never asks twice, so nothing else would say
+so). Per surface (Windows and Linux are unchanged: NOT_REQUIRED, nothing asked,
+nothing shown, and the permission UI code paths do nothing off macOS):
+
+- **The toast.** Source: the `PermissionNeeded` / `PermissionResolved` events. Shown
+ only in the owner window (the embedded desktop window on macOS; never a detached
+ window, a remote browser or another OS), for `origin="user"` and `phase="blocked"`,
+ once per episode and again on the person's next try; a background origin never toasts except one toast per session for
+ a denied microphone for the wake word. Actions: Open System Settings, Ask macOS now
+ (not asked yet, or a development run outside the installed app), Quit and reopen
+ (granted but unusable). en, de, es; no pane names. The native bar's dictation text
+ and the spoken computer-use readbacks are unchanged. Unverified: the look in the real
+ web view and that the pane opens on the current macOS.
+- **Global shortcuts.** A global shortcut is a background listener, so nothing at the
+ moment of use can carry a dialog; saving one is the gesture. `PUT
+ /api/settings/keybinds` asks for Input Monitoring after the save on macOS, only
+ while the tap is not listening, never for a clear, never blocking the save; the
+ onboarding Call-shortcut click asks once. Off macOS the permission layer is not
+ touched. `GET /api/settings/keybinds` no longer carries `shortcuts_status`.
+- **Reset.** `jarvis permissions reset <permission>` (macOS only, behind `--yes`) runs
+ `tccutil reset` for the installed app's own bundle id (either bundle id); on
+ Windows and Linux it prints one line and exits 1. The HTTP reset route is unchanged
+ and still refuses scripts.
+- **Dialog text.** The Apple Events usage string is target-neutral and the folder
+ strings are shorter. German and Spanish `InfoPlist.strings` and
+ `CFBundleLocalizations` ship in both bundles (the `.dmg` app writes the files before
+ signing, the managed bundle when it lays out the app); the bundle format version is
+ not bumped. Not verified on a Mac: that the localized strings appear in the dialogs.
## Audit verdict summary
@@ -768,10 +926,11 @@ implementations, not stubs.
| Area | Verdict |
|---|---|
-| Computer-Use / desktop actions (click, type, hotkey, scroll, drag, windows, apps, screenshots, UI trees) | Full per-OS backends (Win32/UIA, Quartz/AX, xdotool/AT-SPI); honest degradation on Wayland/headless/missing TCC grants |
-| On-demand Screen Context | One-shot capture is wired into the production brain on Windows, macOS, and Linux/X11; UIA/AX/AT-SPI text is source-filtered, the indicator precedes capture, and Wayland/headless/missing grants refuse honestly |
-| Appshots (front-window capture on a shortcut, button or request) | Capture, privacy and delivery are OS-neutral (Screen Context engine, `jarvis/appshot`). The both-Alt shortcut reads key state per OS: Windows `GetAsyncKeyState`, macOS `CGEventSourceKeyState` (Input Monitoring grant), Linux/X11 `XQueryKeymap`; Wayland/headless report it unavailable on the Appshots page. The flash is the PySide6 overlay where one can run. Verified live on Windows only; see `docs/appshots.md` |
-| Voice / audio (capture, playback, VAD, wake, STT, TTS, realtime) | Clean; headless disables voice honestly; WASAPI logic is inert-by-data off Windows |
+| Computer-Use / desktop actions (click, type, hotkey, scroll, drag, windows, apps, screenshots, UI trees) | Full per-OS backends (Win32/UIA, Quartz/AX, xdotool/AT-SPI); honest degradation on Wayland/headless/missing TCC grants. macOS: Accessibility is asked when Jarvis first types, clicks or focuses a window, Screen Recording at the first user-started capture; AX reads never prompt, and nothing is asked at launch |
+| On-demand Screen Context | One-shot capture is wired into the production brain on Windows, macOS, and Linux/X11; UIA/AX/AT-SPI text is source-filtered, the indicator precedes capture, and Wayland/headless/missing grants refuse honestly (on macOS a flat wallpaper-only frame is refused, never delivered) |
+| Appshots (front-window capture on a shortcut, button or request) | Capture, privacy and delivery are OS-neutral (Screen Context engine, `jarvis/appshot`). The both-Alt shortcut reads key state per OS: Windows `GetAsyncKeyState`, macOS `CGEventSourceKeyState` (whether this read needs the Input Monitoring grant is UNVERIFIED; the repo contradicts itself and no Mac measured it, so it is not an Input Monitoring row — see `docs/macos-permissions.md`), Linux/X11 `XQueryKeymap`; Wayland/headless report it unavailable on the Appshots page. The flash is the PySide6 overlay where one can run. Verified live on Windows only; see `docs/appshots.md` |
+| Voice / audio (capture, playback, VAD, wake, STT, TTS, realtime) | Clean; headless disables voice honestly; WASAPI logic is inert-by-data off Windows. macOS microphone: asked at the first dictation, push-to-talk, voice session, wake-word switch or mic self-test, never at launch (2026-10-02 pass) |
+| macOS privacy permissions (TCC) | One just-in-time service (`jarvis/platform/permission_service.py`, AP-35, ADR-0038): `check` is silent, `ensure` asks only from a user gesture and only from the installed app (or after a confirmation naming the grantee); Windows and Linux return NOT_REQUIRED before touching anything. The app draws nothing around macOS's dialog; after a denied user-started use it shows one toast with one action. Verified against fake frameworks and runner packaging probes only, not on a physical Mac (`docs/macos-permissions.md` section 7) |
| Core (launcher, config, keyring, restart, autostart, tray, elevation, paths) | Clean; per-OS autostart (Registry / LaunchAgent / XDG `.desktop`), keyring falls back to a 0600 file on headless hosts |
| Data / agents (wiki, contacts, telephony, sessions, missions, skills, self-mod, channels, MCP) | Clean; mission workers run on POSIX with a real process-group reaper |
| Agent society hands (own shell, browser via browser-use, learned skills) | Shell: local subprocess in the agent's workspace on every OS (Git Bash/PowerShell/bash/sh pick as the chat's folder tools), no container by decision. Browser: browser-use lives in a managed venv under the data dir (its pins collide with the app's), installed on demand — `uv`/`venv`, a 3.11–3.13 interpreter preferred, Chromium downloaded once; headless runs need no display, so a headless Linux box runs agents' browsers; the headed login session needs a display (409 without one is the follow-up); attach mode needs a running Chrome with `--remote-debugging-port`. Learning is pure files + the brain, OS-neutral |
@@ -790,7 +949,7 @@ experiences today.
|---|---|---|---|---|---|
| P-29 | Low | Subscription voice | The dedicated ChatGPT-subscription voice login is an interactive browser flow, so a headless Linux host — and a graphical Linux desktop that ships no terminal emulator able to host the login for its full lifetime — can never CONNECT the profile there (an existing login still reports ready and calls work through the browser voice bridge) | `jarvis/codex_app_server.py::_login_required_state`, `_linux_login_terminal_missing`, `start_codex_subscription_login`, `jarvis/codex_auth.py::_LINUX_LOGIN_TERMINALS` | Both cases report the same `lifecycle_unavailable` truth on every surface (card, activation, voice-mode, Test), each with its own actionable reason — "run Jarvis on a desktop" or "install one of these terminals" — and never an enabled Connect button that can only produce an error toast |
| P-24 | Medium | Dictation shortcut | The global dictation/call shortcut needs `pynput` on Linux/X11, and `pynput` hard-requires `evdev` — which is published **source-only** (verified on PyPI 2026-07-28: evdev 1.9.3 ships an sdist and no wheels) and compiles against the kernel headers. Putting it in `[full]` would break the one advertised install path on a stock `python:3.11-slim`, so it is the opt-in `[desktop-linux]` extra instead. Wayland is a separate, unfixable-by-install case: the compositor owns global shortcuts by design (the XDG `GlobalShortcuts` portal lets the *compositor* assign the keys, and no wlroots compositor implements it at all) | `pyproject.toml` (`desktop-linux`), `jarvis/platform/probes.py::has_hotkey`, `jarvis/trigger/backends/noop.py::explain_unavailable` | X11 without the extra: no global shortcut, and the log/UI now names the actual cause and the exact `pip install` that fixes it (it used to blame Wayland unconditionally). Wayland: no global shortcut at all — bind a compositor shortcut to `jarvis api dictation start`. On both, dictation still works from the Jarvis Bar, the Dictation view and the CLI, and voice still works via the wake word |
-| P-25 | Medium | Dictation insertion | Pasting the transcript into another application is blocked, silently, in three OS-specific situations: Windows UIPI when the foreground window is elevated and Jarvis is not (`SendInput` reports success and the input is discarded), macOS Secure Input while a password field is focused, and Wayland outright (no synthetic input). Detection exists for the first two; Wayland is refused up front. Two further silent failures are Windows-only in their FIX: a chord the target does not bind as "paste" (an xterm.js terminal in a Tauri/Electron app swallows Ctrl+V as `^V`), and a target that reads the clipboard late (an async WebView bridge on a busy machine) after the 120 ms restore timer had already put the previous clipboard back | `jarvis/dictation/insert.py::describe_target`, `_insert_windows_verified`, `jarvis/platform/clipboard_offer.py`, `jarvis/platform/input_isolation.py::windows_foreground_window_is_elevated`, `macos_secure_input_enabled` | All three blocks degrade to the SAME honest outcome instead of silence: the transcript is left on the clipboard, the result is reported as `clipboard_only`, and the bar plus the Dictation view say why and that Ctrl+V will paste it. **Windows** offers the text with delayed rendering and sends exactly one configured paste shortcut. Only a render requested by the captured target process confirms clipboard consumption; merely opening the clipboard or a watcher reading it is not confirmation. A missing acknowledgement never triggers another shortcut, character typing, or an executable-wide learned route. Unconfirmed delivery reports `paste_sent` and leaves the transcript on the clipboard for a late or manual paste, without a restore timer. Focus changes or held modifiers before key emission leave the text available as `clipboard_only`. Confirmed reads may restore the previous clipboard only while the offer still owns it. The explicit typing setting remains available. Regression tests cover delayed readers, watchers, focus changes, and offer shutdown; these checks do not establish compatibility with every third-party editor. **macOS / Linux X11**: plain chord + 120 ms timer restore, unchanged — no delayed-rendering equivalent exists there (NSPasteboard promises and X11 selections notify the owner too, but are a follow-up). macOS Secure Input detection is implemented but has not been verified on real hardware from this machine |
+| P-25 | Medium | Dictation insertion | Pasting the transcript into another application is blocked, silently, in three OS-specific situations: Windows UIPI when the foreground window is elevated and Jarvis is not (`SendInput` reports success and the input is discarded), macOS Secure Input while a password field is focused, and Wayland outright (no synthetic input). Detection exists for the first two; Wayland is refused up front. Two further silent failures are Windows-only in their FIX: a chord the target does not bind as "paste" (an xterm.js terminal in a Tauri/Electron app swallows Ctrl+V as `^V`), and a target that reads the clipboard late (an async WebView bridge on a busy machine) after the 120 ms restore timer had already put the previous clipboard back | `jarvis/dictation/insert.py::describe_target`, `_insert_windows_verified`, `jarvis/platform/clipboard_offer.py`, `jarvis/platform/input_isolation.py::windows_foreground_window_is_elevated`, `macos_secure_input_enabled` | All three blocks degrade to the SAME honest outcome instead of silence: the transcript is left on the clipboard, the result is reported as `clipboard_only`, and the bar plus the Dictation view say why and that Ctrl+V will paste it. **Windows** offers the text with delayed rendering and sends exactly one configured paste shortcut. Only a render requested by the captured target process confirms clipboard consumption; merely opening the clipboard or a watcher reading it is not confirmation. A missing acknowledgement never triggers another shortcut, character typing, or an executable-wide learned route. Unconfirmed delivery reports `paste_sent` and leaves the transcript on the clipboard for a late or manual paste, without a restore timer. Focus changes or held modifiers before key emission leave the text available as `clipboard_only`. Confirmed reads may restore the previous clipboard only while the offer still owns it. The explicit typing setting remains available. Regression tests cover delayed readers, watchers, focus changes, and offer shutdown; these checks do not establish compatibility with every third-party editor. **macOS / Linux X11**: plain chord + 120 ms timer restore, unchanged — on macOS the first paste asks for Accessibility (`dictation_insert`, at the gesture), without it the result is `clipboard_only` with the reason, and the first paste after an in-process grant reports `paste_sent` until delivery is observed (unverified on a Mac) — no delayed-rendering equivalent exists there (NSPasteboard promises and X11 selections notify the owner too, but are a follow-up). macOS Secure Input detection is implemented but has not been verified on real hardware from this machine |
| P-04 | Medium | CU typing | Linux desktop Unicode text input needs the system `xdotool` binary (pip cannot install it); the pyautogui fallback used on Linux drops non-ASCII chars (umlauts, CJK, emoji) without it | `jarvis/cu/actuate/posix.py::type_text`, `jarvis/plugins/tool/type_text.py` | With `xdotool` (installer provisions it since 2026-07-15): fine. Without, the drop is now reported HONESTLY (2026-07-23): an all-non-ASCII text fails with an actionable "install xdotool" error, and a mixed text types its ASCII portion and warns that the rest was dropped — no more silent success |
| P-05 | Low | Wiki | Wiki search hard-fails (RuntimeError with actionable apt/pysqlite3 remediation) on distros whose system SQLite lacks FTS5 | `jarvis/memory/wiki/fts_index.py:279` | `python:3.11-slim` and macOS ship FTS5 — only exotic/old distros affected; message is honest. Decision 2026-07-16: kept as honest hard error — a pysqlite3 shim would rewire seven wiki modules for an exotic audience |
| P-07 | Low | Audio | No macOS/Linux host-API preference exists (the Windows-name-driven tables are intentionally inert off Windows — documented in-code since 2026-07-16), and headset-name heuristics are Windows-centric | `jarvis/audio/player.py`, `jarvis/audio/capture.py` | Device auto-pick falls back to OS default order — works, less clever than on Windows |
@@ -813,7 +972,7 @@ experiences today.
| P-39 | Low | Coding-CLI panes | Cursor CLI panes ship single-login. Sign-in is `agent login` (browser) or `CURSOR_API_KEY`; the on-disk layout of that store has not been verified against a live install, so a seat switcher would report switches that did not happen. The installer is OS-split (`https://cursor.com/install?win32=true` on native Windows, `https://cursor.com/install` on macOS/Linux/WSL); the binary lands in `~/.local/bin` as `agent`, with `cursor-agent` as the unambiguous Windows alias | `jarvis/workspace/agents.py` (the `cursor` entry) | All OSes: one Cursor login, and the account switcher does not offer the CLI. Unblocked by verifying the login store and a dedicated override |
| P-22 | Low | Coding-CLI panes | Kimi Code uses the bundled Git Bash as its shell environment on Windows, so without Git for Windows installed the binary answers `--version` correctly and the agent then cannot run a single shell command | Kimi vendor docs; `jarvis/workspace/agents.py` (the `kimi` entry) | Windows without Git for Windows: the pane opens, the CLI reports a healthy version, and shell commands fail inside it. macOS/Linux unaffected. `KIMI_SHELL_PATH` points at a non-standard `bash.exe`. An install check that only runs `--version` cannot see this |
| P-23 | Info | Coding-CLI panes | Kimi Code's alternate screen cannot be disabled (an open upstream request notes it is the outlier versus Claude Code, Codex and the Gemini CLI), so it may conflict with the pane's own scrollback the way a Claude Code pane once did | Upstream issue; `jarvis/agentic_ide/screen.py` | All OSes equally — not an OS gap, recorded here because it is the same class of pane defect and is expected to need the same kind of fix |
-| P-27 | Low | Mouse-button shortcuts | A shortcut may now be a MOUSE BUTTON (middle, and the two side buttons — `mouse_middle` / `mouse_x1` / `mouse_x2`). All three OSes are implemented in the same change and share one token vocabulary, but the delivery is not uniform: Windows needs nothing extra (the backend polls `GetAsyncKeyState`, which reports mouse buttons); macOS needs pyobjc `Quartz` plus the Accessibility + Input Monitoring grants the hotkey tap already requires; Linux/X11 needs `pynput`, which is the opt-in `[desktop-linux]` extra for the reason recorded in P-24 (`evdev` is source-only). Wayland cannot do it at all — no global button grab exists, the same design reason keyboard shortcuts degrade there. The left and right buttons are deliberately not bindable on any OS: their meaning follows the system "swap mouse buttons" setting, so a shortcut recorded as "left" would fire on the physical right button for a left-handed user | `jarvis/trigger/hotkey.py::mouse_hotkeys_available`, `backends/global_hotkeys.py::_MOUSE_TOKEN_TO_VK`, `backends/pynput.py::_start_mouse_listener`, `backends/quartz.py::_MOUSE_BUTTON_TO_TOKEN` | Every host answers the capability question BEFORE offering the control: `mouse_hotkeys_available()` returns an English sentence naming what is missing and what still works, and a backend that cannot start its mouse hook logs the same thing and keeps the KEYBOARD shortcuts alive rather than failing the whole binding. macOS/Linux desktop with the extras: full parity with Windows. Wayland and headless: key combinations only |
+| P-27 | Low | Mouse-button shortcuts | A shortcut may now be a MOUSE BUTTON (middle, and the two side buttons — `mouse_middle` / `mouse_x1` / `mouse_x2`). All three OSes are implemented in the same change and share one token vocabulary, but the delivery is not uniform: Windows needs nothing extra (the backend polls `GetAsyncKeyState`, which reports mouse buttons); macOS needs pyobjc `Quartz` plus the Input Monitoring grant, the one requirement of the listen-only tap (it was Accessibility and Input Monitoring before 2026-10-02), asked when the user enables global shortcuts and never at launch; Linux/X11 needs `pynput`, which is the opt-in `[desktop-linux]` extra for the reason recorded in P-24 (`evdev` is source-only). Wayland cannot do it at all — no global button grab exists, the same design reason keyboard shortcuts degrade there. The left and right buttons are deliberately not bindable on any OS: their meaning follows the system "swap mouse buttons" setting, so a shortcut recorded as "left" would fire on the physical right button for a left-handed user | `jarvis/trigger/hotkey.py::mouse_hotkeys_available`, `backends/global_hotkeys.py::_MOUSE_TOKEN_TO_VK`, `backends/pynput.py::_start_mouse_listener`, `backends/quartz.py::_MOUSE_BUTTON_TO_TOKEN` | Every host answers the capability question BEFORE offering the control: `mouse_hotkeys_available()` returns an English sentence naming what is missing and what still works, and a backend that cannot start its mouse hook logs the same thing and keeps the KEYBOARD shortcuts alive rather than failing the whole binding. macOS/Linux desktop with the extras: parity with Windows once the macOS grant exists (not exercised on a Mac). Wayland and headless: key combinations only |
| P-43 | Low | Keybind recorder modifiers | The settings recorder used to trust only DOM keydown/keyup. On macOS WKWebView a lone Option/Command/Control can arrive as `flagsChanged` (not a DOM event) or as a keydown whose keyup never comes, so the recorder previewed the key and then hung (GitHub #98). The recorder now (a) syncs the modifier flag word from every keyboard and mouse event, and (b) while capturing, polls `GET /api/settings/keybinds/held`, which is a capability probe (`modifier_snapshot`): Windows `GetAsyncKeyState` for Shift/Ctrl/Alt/Win; macOS `CGEventSourceFlagsState` (no event tap and no Accessibility grant); Linux/X11 falls back to the running pynput held-set when the listener is up; Wayland/headless/missing extras answer `available: false` and the on-screen picker still works. A lagging first poll that says "nothing held" does not commit a chord the user just pressed — the snapshot may only DROP a modifier it has already seen down | `jarvis/trigger/hotkey.py::modifier_snapshot`, `jarvis/ui/web/settings_routes.py::get_keybind_held`, `jarvis/ui/web/frontend/src/views/settings/KeybindRow.tsx` | Windows: live modifier snapshot, no extra packages. macOS with pyobjc Quartz: live snapshot even when the hotkey tap is not running. macOS without Quartz / Wayland / headless: honest `available: false`, click-to-assign and letter+modifier chords still record. Linux/X11 with pynput running: snapshot from the listener held-set. Fn is still not a portable key (the OS often swallows it) and is not offered |
| P-28 | Low | Local realtime | The one-click managed install AND the 2026-08-08 supervisor (prewarm, pidfile ownership, start/stop routes, Ollama keep-alive warm ping) are built cross-platform — pathlib, `os.name` venv layout with a POSIX `lib/python*/site-packages` glob, per-hardware torch flavor, `start_new_session` + `killpg` SIGTERM→SIGKILL escalation on POSIX, `HF_HUB_DISABLE_SYMLINKS` Windows-only — but have only been RUN on the Windows dev box. The preflight narrows the SHARED accelerator probe to the two sources this stack can drive -- NVIDIA VRAM (nvidia-smi) and Apple-Silicon unified memory (total RAM), which the derived launch command maps to `cuda`/`mps`. The shared probe itself also reads AMD and Intel cards now (BUG-206), for the local-model fit verdicts; the preflight deliberately drops those to `(0.0, "none")` via `_DRIVEABLE_SOURCES`, because clearing the memory floor and then launching with a torch device the box does not have is worse than the refusal. An AMD/Intel/no-nvidia-smi host therefore still gets the honest "no supported accelerator" blocker (unit-tested) | `jarvis/realtime/local_server/{preflight,install,supervisor}.py` | Any host under 12 GB usable accelerator memory (including every GPU-less/headless box) gets the honest blocker with a cloud pointer instead of an install — verified by unit tests. macOS Apple-Silicon: preflight and install should work but the smoke boot (`--qwen3_tts_device mps`) is UNVERIFIED on real hardware; a failure is honest (install ends in an error state naming the smoke log, readiness stays fail-closed). Linux+NVIDIA: expected to work via the same cu130 wheel index, unverified; the supervisor's POSIX kill/spawn branches are unit-tested but not live-run. The bring-your-own-server URL socket keeps full parity everywhere |
@@ -843,7 +1002,7 @@ verifies against before it replaces anything.
| OS | Artifact | Built by | Native window | Signing | Shell registration | Where it has actually run |
|---|---|---|---|---|---|---|
| Windows 10/11 x64 | `PersonalJarvis-Setup-x64.exe` (Inno Setup, per-user, no admin prompt, fixed AppId for in-place upgrades) | `packaging/windows/build.ps1` | Yes — WebView2, the shipping desktop window | Owned by the Windows packaging work; see `packaging/windows/` | The installer creates and removes the Start-Menu / Desktop entries | Owned by the Windows packaging work — not verified from here |
-| macOS 12+, arm64 and x64 | `PersonalJarvis-macOS-arm64.dmg`, `PersonalJarvis-macOS-x64.dmg` (`Personal Jarvis.app` + an `/Applications` symlink) | `packaging/macos/build.sh` | Yes — WKWebView through pywebview | Developer ID + Hardened Runtime + notarization when `APPLE_SIGNING_IDENTITY`/`APPLE_ID`/`APPLE_TEAM_ID`/`APPLE_APP_SPECIFIC_PASSWORD` are set; ad-hoc signing and a printed "right-click > Open" notice otherwise | The user drags the app to `/Applications`; the app registers nothing | **No real run yet.** `bash -n`, ShellCheck 0.11.0 `-S style` (zero findings) and a full `DRY_RUN=1` rehearsal of both the signed and unsigned paths. A macOS runner or a physical Mac is the outstanding gate |
+| macOS 12+, arm64 and x64 | `PersonalJarvis-macOS-arm64.dmg`, `PersonalJarvis-macOS-x64.dmg` (`Personal Jarvis.app` + an `/Applications` symlink) | `packaging/macos/build.sh` | Yes — WKWebView through pywebview | Developer ID + Hardened Runtime + notarization when `APPLE_SIGNING_IDENTITY`/`APPLE_ID`/`APPLE_TEAM_ID`/`APPLE_APP_SPECIFIC_PASSWORD` are set; ad-hoc signing and a printed notice otherwise (as of v2.5.0 every published image is the ad-hoc one; the certificate itself comes from the `APPLE_CERTIFICATE_P12_BASE64` / `APPLE_CERTIFICATE_PASSWORD` secrets, which `build.sh` imports into a temporary keychain) | The user drags the app to `/Applications`; the app registers nothing | The ad-hoc path runs for real on the macOS runners (every published image comes from it). The signed/notarized path has **never run**: only `bash -n`, ShellCheck 0.11.0 `-S style` (zero findings), a `DRY_RUN=1` rehearsal of both paths and the certificate import against a stand-in `security` command. A Mac with the Apple secrets is the outstanding gate |
| Linux x86_64 | `PersonalJarvis-Linux-x86_64.AppImage`, `personal-jarvis_<version>_amd64.deb` | `packaging/linux/build.sh` | **No** — serves its interface over loopback HTTP and opens the default browser (P-38) | None. AppImage has no signing story in this project; the release's SHA-256 sums are the integrity check | `.deb` installs a `.desktop` entry, the hicolor icon, `/usr/bin/jarvis` and `/usr/bin/personal-jarvis`. The AppImage carries its `.desktop` inside itself for AppImageLauncher/`appimaged` | Full build proven in a `python:3.12-bookworm` container on 2026-08-25 (~2 min, 156 MB AppImage + 172 MB `.deb`): `appimagetool` digest check, `desktop-file-validate`, both executables out of one freeze, `--version` through the packaged AppImage and through `AppRun`, `AppRun serve` answering `/api/health` in 1-3 s, and the browser hand-off calling the opener with the right URL. Not run on a real desktop distribution or with FUSE |
**Frozen builds register nothing themselves.** For a native install the
@@ -904,7 +1063,7 @@ build: the first release with this code needs one live update per OS.
|---|---|---|---|---|---|
| P-38 | Medium | Native installer / desktop window | The Linux AppImage and `.deb` have **no native desktop window**. Windows (WebView2) and macOS (WKWebView) get one from the frozen bundle; Linux does not, because pywebview's GTK backend needs PyGObject and a frozen interpreter can never import the distribution's `python3-gi` (it is compiled against the system CPython), while bundling GTK 3 + WebKit2GTK portably means shipping its helper processes, GIO modules, pixbuf loaders, GSettings schemas and typelibs. The Qt route is also closed today: the `[desktop]` extra installs `pyside6-essentials`, which has no QtWebEngine, and `jarvis.spec` excludes PySide6 outright. Adding `pyside6-addons` and dropping that exclusion is the realistic fix, at roughly +400 MB | `packaging/linux/README.md` ("The window question"), `jarvis/ui/desktop_app.py::_degrade_to_browser_ui`, `jarvis.spec` `excludes`, `pyproject.toml` `[desktop]` | Linux: honest degradation, verified against a real build — the app catches pywebview's `WebViewException`, keeps the backend serving, and `AppRun` waits for `/api/health` and opens the interface with `xdg-open`. Everything except the window frame works, including the whole CLI. A source/pipx install on a Linux desktop with `python3-gi` + `gir1.2-webkit2-4.1` still gets the native window; only the frozen build does not. Sub-gap: the app's fallback message advises installing those system packages, which does not help a frozen build |
-| P-39 | Medium | Dictation hold-key watchdog | A HOLD-started dictation is owed a release edge, and that edge can be lost between the OS hotkey listener and the pipeline (a checker restart mid-hold, a re-arm, a handler that raised). The recording then ran to its 30-minute cap with the bar's X dead and every key press refused (BUG-191). The repair asks the keyboard instead of trusting edges: `HotkeyBackend.chord_is_down(combo)` is a three-way capability — `True`/`False` when the backend can see the keyboard, `None` when it cannot — and the recording finishes itself once the chord has read "up" for one second. The three OS backends can see different amounts: Windows reads `GetAsyncKeyState` (ground truth, the poller's own source); macOS answers from the event tap's held-set, whose modifier half is re-synced from every event's flags word; Linux/X11 answers from pynput's held-set, which is edge-fed like the matcher itself | `jarvis/trigger/backends/__init__.py::HotkeyBackend.chord_is_down`, `backends/global_hotkeys.py::chord_is_down`, `backends/quartz.py::chord_is_down`, `backends/pynput.py::chord_is_down`, `backends/noop.py`, `jarvis/speech/pipeline.py::_watch_dictation_hold_key`, `tests/contract/test_hotkey_backend_protocol.py` | Windows: the watchdog sees the physical key and ends a lost-release recording within ~1 s. macOS / Linux-X11: the watchdog runs on the listener's own bookkeeping — it catches a release the pipeline missed, not one the listener itself missed. Wayland / no listener: the backend answers `None`, the watchdog stands down, and the other stop gestures carry alone — the key (a press during a running dictation is its stop), the bar's X, the Dictation view, `jarvis api dictation stop`. On no host does `None` ever read as "up": a phantom release is the one failure this must never produce |
+| P-39 | Medium | Dictation hold-key watchdog | A HOLD-started dictation is owed a release edge, and that edge can be lost between the OS hotkey listener and the pipeline (a checker restart mid-hold, a re-arm, a handler that raised). The recording then ran to its 30-minute cap with the bar's X dead and every key press refused (BUG-191). The repair asks the keyboard instead of trusting edges: `HotkeyBackend.chord_is_down(combo)` is a three-way capability — `True`/`False` when the backend can see the keyboard, `None` when it cannot — and the recording finishes itself once the chord has read "up" for one second. The three OS backends can see different amounts: Windows reads `GetAsyncKeyState` (ground truth, the poller's own source); macOS answers from the event tap's held-set, whose modifier half is re-synced from every event's flags word, and answers `None` while the tap is not running (a normal fresh-Mac state until Input Monitoring is granted), so the watchdog stands down instead of trusting a stale view; Linux/X11 answers from pynput's held-set, which is edge-fed like the matcher itself | `jarvis/trigger/backends/__init__.py::HotkeyBackend.chord_is_down`, `backends/global_hotkeys.py::chord_is_down`, `backends/quartz.py::chord_is_down`, `backends/pynput.py::chord_is_down`, `backends/noop.py`, `jarvis/speech/pipeline.py::_watch_dictation_hold_key`, `tests/contract/test_hotkey_backend_protocol.py` | Windows: the watchdog sees the physical key and ends a lost-release recording within ~1 s. macOS / Linux-X11: the watchdog runs on the listener's own bookkeeping — it catches a release the pipeline missed, not one the listener itself missed. Wayland / no listener: the backend answers `None`, the watchdog stands down, and the other stop gestures carry alone — the key (a press during a running dictation is its stop), the bar's X, the Dictation view, `jarvis api dictation stop`. On no host does `None` ever read as "up": a phantom release is the one failure this must never produce |
| P-40 | Low | JarvisBar | The Prompt Mode switch (`[dictation].prompt_mode`, every dictation comes out as a written prompt) is a control on the native bar since 2026-08-28: a sparkle in the resting pill's left slot, drawn ONLY while the SETTING is on (visible without a hover — the pill opens as it does for mute). A click PAUSES the rewriting rather than changing the setting: the mark goes red with a slash through it, jarvis.toml is untouched, and the same click brings it back. The pause is runtime-only and clears on restart or on any write of the setting. With the setting off nothing is drawn there and the spot starts a session as before. The glyph mirrors the mic's inset rather than the close-X's, which is left untouched on a live bar. The switch has ONE writer (`jarvis/dictation/prompt_mode_switch.py`) and one broadcast (`DictationPromptModeChanged`) that the bar, the front-page pill and the settings card all redraw from | `jarvis/ui/jarvisbar/renderer.py::_draw_sparkle`, `interaction.py::resolve_click` (`prompt_mode_toggle`), `overlay.py` / `qt_overlay.py` / `subprocess_overlay.py` (`set_prompt_mode`, `set_on_prompt_mode_toggle`), `host.py` (op `set_prompt_mode`, event `prompt_mode_toggle`), `ui/orb/bus_bridge.py` | Windows/Linux (Tk bar, in-process) and macOS (Qt bar in the companion host, over the existing IPC protocol): the same sparkle, the same click, the same event. Headless / `orb_style = none`: the NullOverlay accepts both methods as no-ops; the pill on the front page and the settings card remain the switch. Guards: `tests/unit/ui/jarvisbar/test_prompt_mode_button.py`, `test_prompt_mode_bridge.py`, `test_surface_contract.py`, `test_host_protocol.py` |
| P-41 | Medium | Dictation final pass | The dictation lane reads its final pass on the machine, in front of any configured cloud provider, through the same out-of-process worker the live preview uses (`jarvis.dictation.preview_worker`) with a stronger checkpoint (`[dictation].local_model`, default `large-v3-turbo`, `int8_float16`, beam 5). 2026-09-02 forensics: 220 of 220 dictations had run on a cloud recognizer the settings did not name, because the VOICE lane had been moved there to keep CUDA out of the desktop process, and the dictation lane inherited the move — round-trips as lag, near-empty answers on 25 s windows as "truncated window" repairs. The provider declines itself with a CROSSABLE failure (HTTP-503-shaped, `LocalEngineUnavailable`) so the configured provider is one step behind on every press and never a restart away: too little free accelerator memory (`[dictation].local_min_free_gb`, default 1.5; an UNKNOWN reading never blocks), a worker that only comes up on the CPU, a missing local runtime, a worker that died. A call abandoned at its ceiling leaves its answer in the pipe, so the next call kills that worker instead of reading it (AP-24) | `jarvis/dictation/local_final.py::LocalFinalSTT`, `jarvis/speech/pipeline.py::_dictation_local_final`, `_dictation_stt`, `jarvis/dictation/local_preview.py::_spawn_worker_model` (`compute`), `preview_worker.py` (`beam_size`, `segments`), `jarvis/hardware/detection.py::free_accelerator_gb` | Windows/Linux with an NVIDIA card and the local runtime: the final pass runs locally when ≥ 1.5 GB is free, else the cloud chain. macOS: no NVIDIA reading → the memory gate passes as unknown, and the worker's own device ladder decides; a CPU-only worker is declined for the final pass (a beam decode of a 25 s window on a CPU is slower than the cloud it would replace), so Apple Silicon stays on the configured provider until a Metal-backed runtime exists. Headless `python:3.11-slim` (no `faster-whisper`): the provider is never built and the chain is exactly what it was. Switch: `[dictation].local_engine = false`. Guards: `tests/unit/dictation/test_local_final.py`, `test_preview_worker.py` |
| P-41 | Low | CLI install / connect terminal | Pressing **Install** or **Connect** in the CLI section opens a REAL terminal window and runs the command there, because an interactive OAuth login belongs in a shell the user can see and type into. That spawn was Windows-only until 2026-08-28 (`wt` -> `pwsh` -> `powershell`), so on macOS and Linux the two buttons reported "No external terminal available" and no CLI could be installed from the app at all. macOS now goes through `osascript` to Terminal.app, Linux through the first of seven emulators that exists (Debian's `x-terminal-emulator` alternative first, so the user's own default wins), and the window is held open afterwards the way `-NoExit` holds it on Windows. One install click now carries all the way to signed in: the terminal runs the install, refreshes PATH in that same shell, and continues into the CLI's login command, stopping at the first step that fails. The chain operator differs per OS on purpose — Windows PowerShell 5.1 is a possible fallback shell and `&&` is a parser error there, so the Windows spelling nests `if ($?)` instead | `jarvis/clis/external_terminal.py` (`_spawn_windows`, `_spawn_macos`, `_spawn_linux`, `chain_commands`, `path_refresh_command`), `jarvis/ui/web/cli_routes.py::spawn_external`, `tests/unit/clis/test_install_path.py` | Windows: verified live (wt path, composed install+login command). macOS/Linux: same code path, the branch itself unverified from this machine. A box with no screen has no window to open, so there the endpoint falls back to the in-app streaming install job and the UI says so instead of claiming a terminal appeared — a headless server can still install a CLI, it just cannot run an interactive login |
diff --git a/docs/plans/cross-platform-mac-linux/LIVE-SIGNOFF-CHECKLIST.md b/docs/plans/cross-platform-mac-linux/LIVE-SIGNOFF-CHECKLIST.md
index 060aec486d..ee6a8e414f 100644
--- a/docs/plans/cross-platform-mac-linux/LIVE-SIGNOFF-CHECKLIST.md
+++ b/docs/plans/cross-platform-mac-linux/LIVE-SIGNOFF-CHECKLIST.md
@@ -46,13 +46,32 @@ macOS version, display arrangement, and per-display scaling in the sign-off log.
## 0. App identity and macOS privacy grants
+> Rewritten 2026-10-02 to the ask-when-needed behaviour (AP-35,
+> [ADR-0038](../../adr/0038-macos-permissions-ask-when-needed.md)): a feature asks
+> macOS at the moment the user first uses it, from that gesture; nothing is asked at
+> launch, in onboarding or by a banner, and the app draws nothing around macOS's dialog (its only
+> addition is one toast after a user-started use failed, UI reset 2026-10-02). The earlier rows (press each Allow button in
+> onboarding, fail closed before the OS is asked) described the removed preflight wall;
+> git history keeps them. None of these rows has been signed off on a physical Mac.
+> The full row set with the exact dialogs to record is section 7 of
+> [`docs/macos-permissions.md`](../../macos-permissions.md) (ids `M-*`).
+>
+> **Before each row** quit Jarvis, run `jarvis permissions reset <permission> --yes` (or
+> `tccutil reset <Service> <bundle id>`) for the permission under test (Microphone,
+> ScreenCapture, Accessibility plus PostEvent, ListenEvent, AppleEvents), start the app again, then check System Settings > Privacy &
+> Security: an unchanged list means the reset did nothing. Test both installed apps (the
+> `.dmg` app `ai.personaljarvis.desktop` and the managed app `com.personal-jarvis.desktop`)
+> and the one you are not testing must keep its own state.
+
| # | Scenario | Manual step | Expected observation | PASS / FAIL / N/A |
|---|---|---|---|---|
-| TCC-1 | Stable installed identity | Run the public install command, then inspect the launched process and `~/Applications/Personal Jarvis.app` | The installer launches through LaunchServices; status reports bundle ID `com.personal-jarvis.desktop`, `launched_as_bundle=true`, and `stable=true`. Terminal/Python never receives the grants | _____ |
-| TCC-2 | Explicit first-run grants | In onboarding, press each Allow button in order: Microphone, Screen Recording, Accessibility, Input Monitoring, Input Control | Every dialog is initiated by that button; no dialog appears merely from installing, booting, or opening the page. Returning from System Settings refreshes status without manual reload | _____ |
-| TCC-3 | Denial and recovery | Deny each permission once, then use Open Settings and grant it | The affected feature stays disabled with an honest status; text chat remains usable; recovery is entirely in-app and never edits the TCC database | _____ |
-| TCC-4 | Revocation | Revoke each previously granted permission while Jarvis is running, then retry the affected feature | The next microphone, capture, hotkey, window, or input action fails closed before touching the protected API; restoring the grant recovers through the supported UI flow | _____ |
-| TCC-5 | Identity persistence | Update/relaunch and enable login autostart | Manual launch, restart, updater relaunch, and LaunchAgent all re-enter through the same app bundle; grants do not migrate to Terminal/Python or unexpectedly reset | _____ |
+| TCC-1 | Stable installed identity | Install through the public install command (managed app) or drag the `.dmg` app to Applications; start it from there; read `jarvis permissions status` | The app runs from the installed bundle; status reports its bundle ID (`com.personal-jarvis.desktop` managed, `ai.personaljarvis.desktop` for the `.dmg`), `launched_as_bundle=true`, `stable=true`. Terminal/Python never receives the grants. A terminal-launched dev run asks for no grant on its own: the toast offers **Ask macOS now**, a confirmation that names the app that started Jarvis | _____ |
+| TCC-2 | First use asks, nothing at launch | With every permission reset: start the app and wait 30 s with the wake word off; then press the dictation button in the composer (microphone); ask Jarvis to look at the screen (Screen Recording); dictate into another app or run one computer-use click (Accessibility); save a new shortcut on Voice > Shortcuts (Input Monitoring); with Music running switch **Mute music while dictating** on (Automation) | **No dialog, toast, banner or wizard at launch or while the page is open.** Each protected action raises Apple's own dialog for exactly that permission, from that gesture, naming Personal Jarvis with the usage string where one exists; Jarvis shows its own toast only when the permission is blocked, never while an Apple dialog is up. Record the dialog text and whether the app was frontmost | _____ |
+| TCC-3 | Denial and recovery | Answer **Don't Allow** (or leave a Screen Recording or Accessibility dialog unanswered) for each permission once, retry the feature, then use **Open System Settings** from the toast and switch it on | Only the affected feature degrades with an honest sentence (dictation: the microphone is off; capture refuses, **no wallpaper frame**; dictation paste stays on the clipboard as `clipboard_only`); typed chat stays usable; the retry does not raise a second dialog (a decision is not asked twice); the toast's button opens the right pane; after the switch the feature works without a restart for the microphone, and the observation for Screen Recording and Input Monitoring (works at once, or only after "Quit and reopen") is written down. Recovery never edits the TCC database | _____ |
+| TCC-4 | Revocation | Revoke each previously granted permission in System Settings while Jarvis is running, then retry the affected feature | The next microphone stream ends within a few seconds (or after about 5 s of exact zeros shows one "denied or muted" notice), the next capture, shortcut, window or input action refuses honestly **without** acting on a stale grant, and restoring the grant recovers through the toast's button or System Settings. No crash | _____ |
+| TCC-5 | Identity persistence | Update/relaunch and enable login autostart | Manual launch, restart, updater relaunch, and LaunchAgent all re-enter through the same app bundle; grants do not migrate to Terminal/Python or unexpectedly reset. Record the "Background Items Added" notice and the name Login Items shows | _____ |
+| TCC-6 | Upgrader and boot rule | With every grant present, update or restart the app; then, with the wake word on and the microphone reset, start it again | An upgrader sees zero toasts and zero requests and every feature works at once. With the microphone reset and the wake word on, launch shows no dialog and opens no input stream and no toast (the one wake-word toast appears only for a DENIED microphone) | _____ |
+| TCC-7 | An agent never answers a dialog | With an Apple permission dialog on screen, start a computer-use task | Nothing is dispatched while the consent window is frontmost; the mission ends `blocked_permission` with a Retry; the agent text says not to touch the dialog | _____ |
---
@@ -61,7 +80,7 @@ macOS version, display arrangement, and per-display scaling in the sign-off log.
| # | Feature × OS | Probe command | Manual step | Expected observation | PASS / FAIL / N/A |
|---|---|---|---|---|---|
| AX-1 | UI-element-click (macOS) | `signoff_probe.py --feature ax` | Grant System Settings › Privacy & Security › Accessibility; bring a normal app (e.g. TextEdit) to the foreground | `make_ui_tree_source()` returns `AXTreeSource`; `observe()` yields **non-empty** `UIANode`s with canonical roles (`AXButton`→`Button`); a `click_element` by name lands on its bounds | _____ |
-| AX-2 | UI-element-click (macOS) — degrade | `signoff_probe.py --feature ax` | **Revoke** the Accessibility grant, retry | Tree is empty; one English permission message is returned and Computer-Use refuses to inject input. No pixel-click bypass, crash, or silent empty result | _____ |
+| AX-2 | UI-element-click (macOS) — degrade | `signoff_probe.py --feature ax` | **Revoke** the Accessibility grant, retry | AX reads degrade quietly (empty tree, no dialog, no card); the first input action asks for Accessibility (`TCC-2`) and, while it is off, Computer-Use returns one `[permission_needed:accessibility]` message and refuses to inject input. No pixel-click bypass, crash, or silent empty result | _____ |
| AX-3 | UI-element-click (Linux) | `signoff_probe.py --feature ax` | `apt install python3-pyatspi gir1.2-atspi-2.0`; ensure the AT-SPI bus is up; foreground a GTK app | `make_ui_tree_source()` returns `AtspiTreeSource`; `observe()` returns a **non-empty** tree normalized to canonical roles | _____ |
| AX-4 | UI-element-click (Linux) — degrade | `signoff_probe.py --feature ax` | Stop the AT-SPI bus / uninstall `pyatspi`, retry | `NullUITreeSource`; **one** English degrade line ("AT-SPI bus unavailable — install python3-pyatspi …"); pixel-click fallback still clicks. No crash | _____ |
@@ -77,8 +96,8 @@ macOS version, display arrangement, and per-display scaling in the sign-off log.
| # | Feature × OS | Probe command | Manual step | Expected observation | PASS / FAIL / N/A |
|---|---|---|---|---|---|
-| HK-1 | Hotkey (macOS) | `signoff_probe.py --feature hotkey` | Grant Accessibility and Input Monitoring; press `ctrl+right_alt+j` | `PynputBackend` **captures** the combo; Jarvis enters LISTENING | _____ |
-| HK-2 | Hotkey (macOS) — missing grant | `signoff_probe.py --feature hotkey` | Without Input-Monitoring, press the combo | The "registered but zero events → grant Input-Monitoring/Accessibility" detection fires (AD-8); no crash | _____ |
+| HK-1 | Hotkey (macOS) | `signoff_probe.py --feature hotkey` | Save a shortcut on Voice > Shortcuts, which asks for Input Monitoring, and allow it (Accessibility is not needed for the listen-only tap); press `ctrl+right_alt+j` | `QuartzHotkeyBackend` **captures** the combo; Jarvis enters LISTENING | _____ |
+| HK-2 | Hotkey (macOS) — missing grant | `signoff_probe.py --feature hotkey` | Without Input Monitoring (never asked, or denied), press the combo | Nothing is asked at launch; the shortcut does nothing and, after a denied save, one toast offers **Open System Settings**; the buttons and voice keep working; a restart hint appears only when the preflight reads granted and typing then produced no events (AD-8); never an automatic restart; no crash | _____ |
| HK-3 | Hotkey (Linux X11) | `signoff_probe.py --feature hotkey` | On an X11 session, press the combo | `PynputBackend` captures the press; Jarvis enters LISTENING | _____ |
| HK-4 | Hotkey (Linux Wayland) — degrade | `signoff_probe.py --feature hotkey` | On a Wayland session, press the combo, then say the wake word | `NoopBackend`; the combo does nothing but logs **once** "global hotkey unavailable on Wayland by OS design; lean on the wake word"; the wake word still summons Jarvis (AD-8). No crash, no spam | _____ |
diff --git a/docs/product/everyday-use/voice-conversations.md b/docs/product/everyday-use/voice-conversations.md
index e8145cdec2..df4a292638 100644
--- a/docs/product/everyday-use/voice-conversations.md
+++ b/docs/product/everyday-use/voice-conversations.md
@@ -8,7 +8,7 @@ order: 2
diataxis: explanation
status: active
owner: maintainers
-last_reviewed: 2026-07-30
+last_reviewed: 2026-10-02
phase: "-"
audience: end-user
tags: [voice, microphone, wake-word, speech-recognition, text-to-speech, pipeline, realtime, language]
@@ -28,8 +28,8 @@ reason, act, or speak a reply.
- Wait for **Voice starting…** to become **Ready**.
- Choose a working microphone and speaker under **Settings > Audio devices**.
-- On macOS, allow **Microphone** access. The Call shortcut can also need
- Accessibility and Input Monitoring access. Other systems use their own audio
+- On macOS, allow **Microphone** access. The Call shortcut also needs
+ Input Monitoring access, which macOS asks for when you save a shortcut. Other systems use their own audio
and shortcut permissions.
- Open **API Keys & Providers** and review **Voice engine**. Realtime needs one
compatible live voice connection. Pipeline needs usable Voice Input, Brain,
diff --git a/docs/product/extend-and-automate/computer-use.md b/docs/product/extend-and-automate/computer-use.md
index c5abb789ec..1961f0891c 100644
--- a/docs/product/extend-and-automate/computer-use.md
+++ b/docs/product/extend-and-automate/computer-use.md
@@ -8,7 +8,7 @@ order: 6
diataxis: howto
status: active
owner: maintainers
-last_reviewed: 2026-07-21
+last_reviewed: 2026-10-02
phase: "-"
audience: end-user
tags: [computer-use, desktop, vision, permissions, safety, providers]
@@ -37,9 +37,11 @@ infallible. Watch the screen and start with a small, reversible task.
- Open **API Keys & Providers > Tool Model**. Connect a provider, choose a
model that understands images, select **Set active**, and run the card's
test. The Tool Model is separate from the model that writes chat replies.
-- On macOS, open **Settings > Privacy permissions > macOS permissions** and
- grant **Screen Recording**, **Accessibility**, and **Input Control**. Restart
- the app when the permission view asks you to do so.
+- On macOS, Computer Use needs **Screen Recording** and **Accessibility**.
+ macOS asks the first time Computer Use needs each one. If you said no, use
+ **Open System Settings** on the short message Jarvis shows (or start over, see
+ [Permissions](permissions)); use **Quit and reopen** only when that message
+ offers it.
- On Linux X11, keep `xdotool` installed when you need to type accented text,
emoji, or non-Latin characters. The standard installer tries to provide it;
without it, the fallback input backend can drop non-ASCII characters.
@@ -222,7 +224,7 @@ completion message arrives after that state appears, not before it.
|---|---|---|
| Jarvis says Computer Use is not active, or reports Wayland or no display | An older installation kept the feature off, desktop components are missing, or the session cannot provide global capture and input | Enable it with `jarvis config set computer_use.enabled true`; otherwise use the full desktop install in a Windows, macOS, or Linux X11 session, then restart Jarvis and repeat the harmless check |
| Jarvis says no model can see the screen | The Tool Model is missing, text-only, out of credit, rate limited, or unavailable across all compatible fallbacks | Open **API Keys & Providers > Tool Model**, test a connected image-capable model, and activate a healthy option |
-| Jarvis cannot see or control the screen on macOS | Screen Recording, Accessibility, or Input Control is missing, belongs to an older app identity, or needs a restart | Open **Settings > Privacy permissions > macOS permissions**, grant each listed item, use **Restart now** when shown, then try again |
+| Jarvis cannot see or control the screen on macOS | Screen Recording or Accessibility is off, denied, or belongs to an older app identity, or a change needs a restart | Use **Open System Settings** on the message Jarvis shows for each item that is off, use **Quit and reopen** when it is offered, or start over with `jarvis permissions reset`, then try again |
| The pointer, drag, or typed text is wrong | Focus or display layout changed, an elevated Windows window blocked input, or Linux lacks `xdotool` for non-ASCII typing | Bring a normal non-administrator app window forward, keep the layout stable, install `xdotool` on X11 when needed, and retry one named control |
| Jarvis stops at a sensitive screen, reports no progress, or rejects completion | It needs a human-only login step, the interface changed, or the visible result could not be verified | Complete sensitive input yourself; otherwise check the screen and retry a shorter goal with one visible result |
diff --git a/docs/product/extend-and-automate/screen-context.md b/docs/product/extend-and-automate/screen-context.md
index a664e357df..23ee630664 100644
--- a/docs/product/extend-and-automate/screen-context.md
+++ b/docs/product/extend-and-automate/screen-context.md
@@ -8,7 +8,7 @@ order: 9
diataxis: howto
status: active
owner: maintainers
-last_reviewed: 2026-07-30
+last_reviewed: 2026-10-02
phase: "-"
audience: end-user
tags: [screen-context, vision, privacy, accessibility, ocr, desktop]
@@ -22,8 +22,10 @@ name; this guide says “your assistant” so it fits every chosen name.
## Before You Start
- Connect a provider that can inspect images.
-- Open **Settings > Permissions** and grant the operating-system permissions
- listed for your platform.
+- On macOS, nothing needs setting up first: the first time you ask your
+ assistant to look at the screen, macOS asks for **Screen Recording**.
+ If you say no, Jarvis shows one short message with a button that opens the
+ right System Settings pane.
- Move private information away or add a privacy rule before testing. Redaction
cannot recognize every secret in arbitrary pixels.
@@ -106,15 +108,19 @@ changing settings also clears captures made under old rules.
| Linux with Wayland | Unavailable until a supported desktop-portal capture backend is installed | Does not make global capture available |
| Headless server | Unavailable because there is no addressable display | Not applicable |
-Missing support produces a refusal, not a blank screenshot. Reopen the macOS
-app if the system requests it after a permission change.
+Missing support produces a refusal, not a blank screenshot. On macOS, the
+capture you start is the moment macOS asks for Screen Recording; if you decline,
+the capture is refused with a message and one click opens the right System
+Settings pane. Reopen the app only if the message says macOS needs it after a
+permission change. Reading on-screen text never opens a dialog: without
+Accessibility the image still works and the text is simply left out.
## How It Fits Together
| Related feature | Relationship to Screen Context |
|---|---|
| [Computer Use](computer-use) | Screen Context reads once without action tools. Computer Use performs desktop actions separately. |
-| [Permissions](permissions) | Shows and requests macOS Screen Recording and Accessibility access; Screen Context checks the current state on every capture. |
+| [Permissions](permissions) | Explains when macOS asks for Screen Recording and Accessibility access and how to start over; Screen Context checks the current state on every capture and asks only for a capture you started. |
| [Providers and API Keys](providers-and-api-keys) | A vision-capable provider interprets the filtered image. |
| [CLI Reference](cli-reference) | The same authenticated local API is available through the `screen-context` group: check readiness, classify wording without capture, request one capture, consume or discard it, and manage settings. |
@@ -136,7 +142,7 @@ rules, the announcement, single use, and expiry.
|---|---|---|
| Your assistant asks whether it should look | The wording was ambiguous | Confirm on the same conversation, or repeat with “screen” or “this window” |
| The wrong monitor was captured | The pointer was on another monitor when the request triggered | Place the pointer on the intended monitor and ask again, or name the focused window |
-| Capture is unavailable on macOS | Screen Recording permission is missing or was revoked | Grant it under **Privacy & Security**, then reopen the app if macOS requires it |
+| Capture is unavailable on macOS | Screen Recording was declined or revoked | Use **Open System Settings** on the message Jarvis shows, or open **Privacy & Security** in System Settings yourself, then reopen the app if asked |
| The image works but visible text is missing | Accessibility permission, AT-SPI, or usable accessibility nodes are absent | Fix that platform support; optionally install and enable OCR |
| A privacy rule blocks a safe window | A denylist fragment or custom pattern is too broad | Narrow the entry, save, and retry only after checking what it matches |
| A capture disappears before API consumption | It was already consumed, discarded, or its retention time expired | Make a fresh explicit request; single-use captures cannot be recovered |
diff --git a/docs/product/personalize-and-connect/audio-and-wake-word.md b/docs/product/personalize-and-connect/audio-and-wake-word.md
index e2553cb1da..ee0cd77cde 100644
--- a/docs/product/personalize-and-connect/audio-and-wake-word.md
+++ b/docs/product/personalize-and-connect/audio-and-wake-word.md
@@ -8,7 +8,7 @@ order: 2
diataxis: howto
status: active
owner: maintainers
-last_reviewed: 2026-07-30
+last_reviewed: 2026-10-02
phase: "-"
audience: end-user
tags: [audio, microphone, speaker, wake-word, voice, pipeline, realtime]
@@ -26,8 +26,9 @@ processed locally even when the later conversation uses hosted speech or AI.
- Connect the headset, microphone, or speakers you want to use.
- Wait until the desktop app shows **Ready**, not **Voice starting...**.
-- Allow microphone access in the operating system. macOS users should also
- review **Settings > Privacy permissions**.
+- Allow microphone access in the operating system. On macOS, the first
+ voice feature you use shows Apple's own dialog; if you said no earlier, see
+ [Permissions](permissions) to start over.
- Never use a password, recovery code, or other secret as a wake phrase.
Voice is optional. Chats and other text features continue on a computer with
@@ -152,8 +153,8 @@ For fewer missed or accidental wakes:
- Windows, macOS, and Linux can use local wake detection when desktop audio and
compatible packages are available.
-- macOS requires Microphone permission; global shortcuts can also require
- Accessibility and Input Monitoring.
+- macOS requires Microphone permission; global shortcuts also require Input
+ Monitoring, which macOS asks for when you save a shortcut.
- Linux global shortcuts need a supported X11 hotkey backend. Wayland normally
blocks them, so use wake activation or an in-app control.
- A headless host has no native wake listener, Call shortcut, Dictation target,
diff --git a/docs/product/personalize-and-connect/settings-and-appearance.md b/docs/product/personalize-and-connect/settings-and-appearance.md
index 0fe2b7498c..ffcad2a28f 100644
--- a/docs/product/personalize-and-connect/settings-and-appearance.md
+++ b/docs/product/personalize-and-connect/settings-and-appearance.md
@@ -8,7 +8,7 @@ order: 4
diataxis: howto
status: active
owner: maintainers
-last_reviewed: 2026-07-21
+last_reviewed: 2026-10-02
phase: "-"
audience: end-user
tags: [settings, appearance, startup, keyboard-shortcuts, jarvis-bar, sound]
@@ -46,7 +46,6 @@ that have their own guides.
|---|---|---|
| **Languages** | Interface, Voice Recognition Language, and Reply Language | Interface and reply choices apply live. After changing recognition, end any Realtime call and restart Jarvis for Pipeline recognition |
| **App settings** | Launch the app when you sign in | The operating-system startup entry is added or removed immediately |
-| **Privacy permissions** | Microphone, Screen Recording, Accessibility, Input Monitoring, Input control, and Keychain access on macOS | Status updates live; Jarvis shows **Restart now** when a new grant needs it |
| **Realtime voice (browser)** | Pipeline or Realtime voice mode | Saves immediately. An active desktop call reconnects when its mode changes; otherwise the next call uses the choice |
| **System Prompt** | The assistant's general style and behavior | On the next message; no restart |
| **Wake Word** | Activation, phrase, spoken language, detection engine, and self-test | Usually live when desktop voice is ready; otherwise on the next voice start |
@@ -148,6 +147,8 @@ device.
by the other action. These markers are optional visual aids.
4. Select **Save**. If Jarvis shows a restart message, restart after important
work has finished; otherwise the running voice listener is already updated.
+ On a Mac, the first save is the moment macOS asks for Input Monitoring, which
+ lets a shortcut work while another app is in front; Clear never asks.
Press **Escape** while recording to restore the previously saved combination.
**Reset to default** places the default in the field; select **Save** to apply
@@ -209,7 +210,7 @@ returns to idle.
| **Realtime voice (browser)** is unavailable | No installed Realtime provider has a usable credential, or this build does not include the optional Realtime engine | Connect OpenAI Realtime or Gemini Live under **API Keys**. If the control stays unavailable, use Pipeline |
| Music keeps playing after you enable muting | The platform backend is unavailable, macOS Automation access was denied, or the media app is unsupported | Accept the macOS Automation prompt when offered. On Linux or for unsupported players, use the operating system or media app controls |
| **Save** stays disabled for a shortcut | The combination is incomplete, reserved, or overlaps another action | Follow the inline message and the on-screen keyboard markers, then choose a distinct combination |
-| A macOS feature remains blocked | The operating system has not granted the required access, or the new grant needs an app restart | Use **Settings > Privacy permissions > Allow**, **Open Settings**, or **Ask again**, then select **Restart now** when shown |
+| A macOS feature remains blocked | The operating system has not granted the required access, or the new grant needs an app restart | Use the button on the short message Jarvis shows (**Open System Settings**, **Ask macOS now**, or **Quit and reopen**); [App Permissions](permissions) explains how to start over |
| A change works now but returns after restart | The live update succeeded, but the saved preference could not be written | Try the control again, then use [Troubleshooting](troubleshooting) if it still does not survive a restart |
| **Autopilot Toasts** has no effect | The visible switch is not currently connected to a saved preference | Do not rely on this control until a future app update wires it to behavior |
diff --git a/docs/product/privacy-safety-and-support/permissions.md b/docs/product/privacy-safety-and-support/permissions.md
index 77289dd14c..e8a2b0a5b8 100644
--- a/docs/product/privacy-safety-and-support/permissions.md
+++ b/docs/product/privacy-safety-and-support/permissions.md
@@ -1,158 +1,166 @@
---
title: "App Permissions"
slug: permissions
-summary: "Grant only the microphone, screen, accessibility, and input permissions needed for voice, global shortcuts, and Computer Use."
+summary: "See when macOS asks for microphone, screen, accessibility, and input access, and how to change an answer later."
section: "Privacy, safety, and support"
section_order: 6
order: 3
diataxis: howto
status: active
owner: maintainers
-last_reviewed: 2026-07-21
+last_reviewed: 2026-10-02
phase: "-"
audience: end-user
tags: [permissions, macos, privacy, computer-use, safety, approvals]
related: [first-run-setup, audio-and-wake-word, computer-use, privacy-and-local-data]
---
-Use App Permissions to grant only the local access required by the features
-you use. Personal Jarvis has no master permission that unlocks your computer,
-accounts, and tool actions at once.
+Personal Jarvis asks macOS for a permission only when a feature that needs it is
+first used or switched on. Nothing is asked when the app starts or from a warning
+banner, and setup never needs a permission to continue; a switch you turn on during
+setup, such as the wake word, asks at that moment. No master permission unlocks your
+computer, accounts, and tool actions at once.
-The current card manages seven items for the installed macOS desktop app. Six
-are macOS privacy permissions. The seventh reports whether API keys use macOS
-Keychain. Browser permissions, connected-account access, and Jarvis safety
-approvals remain separate.
+On a Mac, the feature you start shows Apple's own dialog at that moment, and
+Jarvis draws nothing of its own around it. If you say no, only that feature
+stops. macOS does not ask a second time and says nothing afterwards, so Jarvis
+shows one short message with one button, and the button opens the right System
+Settings pane. There is no permissions page to maintain. Browser permissions,
+connected-account access, and Jarvis safety approvals remain separate.
## Before You Start
-- On macOS, open the installed **Personal Jarvis** app and bring it to the
- foreground. Do not grant access to Terminal, Python, or a copied app bundle.
- macOS records access against the exact app identity.
-- Decide which features you need. Text chat does not require microphone,
- screen, accessibility, or input access.
-- Finish or stop active Jarvis-Agent missions before a permission change that
- needs a restart. **Restart now** refuses to stop a running mission.
-- Enter credentials only in **API Keys & Providers** or the relevant connection
- screen. A system permission prompt never needs an API key, password, token,
- or recovery code.
-
-During first-run setup, an interactive Mac shows all seven rows. **Continue** is
-enabled when every row is ready or is waiting for the final setup restart.
-Choose **Skip for now, text only** to skip the remaining grants. Completing
-setup restarts the installed desktop app when that restart is available.
+- On macOS, use the installed **Personal Jarvis** app. The app from the installer
+ and the app from the downloaded disk image both count; each is its own app to
+ macOS, with its own permissions. Do not grant access to Terminal, Python, or a
+ copied app bundle. If Jarvis was started from a terminal, it does not ask on
+ its own: after something you started needs a permission, the message offers
+ **Ask macOS now**, and macOS records the answer for the app that started Jarvis
+ (the terminal), not for the installed app. A copy running outside Applications
+ does the same, for that copy only.
+- Decide which features you need. Text chat requires none of these permissions.
+- Finish or stop active Jarvis-Agent missions first: **Quit and reopen** refuses to
+ stop a running mission.
+- Enter credentials only in **API Keys & Providers** or the connection screen. A
+ system permission prompt never needs an API key, password, token, or recovery code.
## Check Your Platform
-| Platform | What App Permissions shows | What you still need to check |
+| Platform | What you see | What you still need to check |
|---|---|---|
-| macOS desktop | Seven permission rows, **Set up everything**, and the per-row actions | The installed app identity, native prompts, and any restart notice |
-| Windows desktop | **No extra desktop privacy permissions are required on this operating system.** | Windows microphone privacy, User Account Control, file access, and the feature itself |
-| Linux desktop | The same **Not required** message | Audio device access, file ownership, desktop session, and required desktop tools |
+| macOS desktop | Apple dialogs at first use (German and Spanish text in new builds, English otherwise), and one short Jarvis message only when something you started is blocked | The installed app identity, the native dialogs, and any restart notice |
+| Windows desktop | **No extra desktop privacy permissions are asked by Jarvis on this operating system.** Nothing is shown | Windows microphone privacy, User Account Control, file access, and the feature itself |
+| Linux desktop | The same: nothing is asked and nothing is shown | Audio device access, file ownership, desktop session, and required desktop tools |
| Headless or remote browser | No local desktop grant can create a microphone or live display | Browser site access and whether the host has the required device or desktop session |
-The **Not required** message means only that this card has no macOS grant to
-manage. It is not a device-health check. Current global shortcuts and Computer
-Use cannot inject input in a Linux Wayland session. Computer Use also needs a
-live desktop, so it is unavailable on a headless server.
+Not asking means only that Jarvis has no macOS permission to manage; it is not a
+device-health check. Current global shortcuts and Computer Use cannot inject
+input in a Linux Wayland session, and Computer Use needs a live desktop, so it is
+unavailable on a headless server.
-## Grant and Review macOS Access
+## When macOS Asks
-Open **Settings > Privacy permissions > macOS permissions**. The card uses
-these visible row names:
-
-| Permission | What it allows | Needed for | Restart after request or settings visit |
+| Permission | What it allows | When Jarvis asks | If you say no |
|---|---|---|---|
-| **Microphone** | Capture local microphone audio | Wake word and local voice input | No |
-| **Screen Recording** | Capture visible screen content | Computer Use and screen-based vision | Yes |
-| **Accessibility** | Read supported interface structure, focus or move windows, and support reliable input | Computer Use, window control, and global shortcuts | Yes |
-| **Input Monitoring** | Listen for configured system-wide keyboard shortcuts | Global shortcuts | Yes |
-| **Input control** | Post mouse and keyboard events | Computer Use | No |
-| **Automation (Music & Spotify)** | Send Apple Events to Music and Spotify | Mute music while dictating | No |
-| **Keychain (API keys)** | Store API keys in macOS Keychain | Encrypted operating-system credential storage | No |
-
-Current macOS versions may name the Screen Recording pane **Screen & System
-Audio Recording**. **Input control** is Jarvis's label for posting input
-events. Its state can follow **Accessibility**, and **Open Settings** may open
-the Accessibility pane rather than a separate pane named Input control.
-
-**Set up everything** runs the whole list for you: it raises each native
-dialog in turn, opens the matching System Settings pane for the rows macOS
-only grants there, waits until the switch is on, and finishes with one
-automatic restart when a grant needs a fresh process. **Stop** ends the flow at
-any point; nothing already granted is lost. **Automation** briefly opens a
-closed Music or Spotify in the background so macOS can ask, and closes it
-again.
-
-Grants made this way are recorded against the app's local signing
-certificate, which the installer creates once (macOS asks for your login
-password that one time). They survive every later update and rebuild of the
-app.
-
-Grant one item at a time instead:
-
-1. Move focus to **Allow** for the row you need and activate it. Read the
- native macOS prompt before you approve or deny it.
-2. If **Open Settings** is available, activate it to open the matching privacy
- pane. Turn on Personal Jarvis, then return to the app.
-3. Wait for the card to check again. It refreshes when the app regains focus
- and, while access is missing, about every 2.5 seconds while visible.
-4. If a row says **Denied**, use **Ask again** to remove only Personal Jarvis's
- recorded decision. This does not grant access. Activate **Allow** afterward
- and answer the new system prompt. You can also use **Open Settings**.
-5. If **Restart now** appears, finish or stop active missions and activate the
- button. Screen Recording, Accessibility, and Input Monitoring changes are
- treated as unavailable until a fresh app process applies them.
-6. Test the dependent feature. **Allowed** confirms the native grant, not the
- health of a microphone, model, provider, connection, or target app.
-
-**Keychain (API keys)** has no **Open Settings** or **Ask again** action. If
-Keychain access was declined, Jarvis keeps working with a permission-restricted
-local file and the row stays **Not allowed**. Use **Allow** to retry Keychain
-access. The local file is a compatibility fallback, not encrypted Keychain
-storage.
-
-### Read Each Status
-
-| Status | Meaning | What to do |
-|---|---|---|
-| **Allowed** | The native check reports access | Test the feature; restart first if the card asks |
-| **Not requested** | macOS reports that no choice has been recorded | Use **Allow** and answer the native prompt |
-| **Not allowed** | The check cannot confirm access; some native checks cannot distinguish a previous denial from no choice | Use **Allow** or **Open Settings** when available |
-| **Denied** | macOS reports a denied decision | Use **Ask again**, then **Allow**, or change the switch in System Settings |
-| **Restricted** | Device policy or a system rule prevents the grant | Ask the device administrator or review the Mac's policy |
-| **Unavailable** | Jarvis cannot use the native permission check on this installation | Reopen the installed app, use **Check again**, and review the installation if it persists |
-| **Restart pending** | A requested Screen Recording change is waiting for a fresh process | Use **Restart now** after active missions finish |
-| **Not required** | The macOS permission flow does not apply to this host | Check the operating system, browser, device, or desktop session directly |
+| **Microphone** | Capture local microphone audio | The first time you press the dictation key or button, start a voice conversation, use push-to-talk, switch the wake word on, or run the microphone check | Voice and dictation stop with a note; typed chat is unaffected |
+| **Screen Recording** | Capture visible screen content | The first time you ask Jarvis to look at your screen: Computer Use, a screen snapshot, screen context, or an appshot | The capture is refused with a message, never a blank or wallpaper-only picture |
+| **Accessibility** | Click, type, focus, and move windows for you | The first time Jarvis must type or click for you: Computer Use input, typing dictated text into another app, window control | Dictated text stays on the clipboard so you can paste it; Computer Use input is refused |
+| **Input Monitoring** | Listen for system-wide keyboard shortcuts | When you save a global shortcut (on **Voice > Shortcuts** or the Keyboard shortcuts page), or choose the Call shortcut in setup. A shortcut works while another app is in front, so no single key press could carry the question | Shortcuts that work while another app is in front stay off; the app's buttons and voice keep working |
+| **Automation (Music & Spotify)** | Send Apple Events to Music and Spotify | When you switch **Mute music while dictating** on while a player is running | Jarvis skips volume control for that player and dictation continues |
+| **Keychain (API keys)** | Store API keys in macOS Keychain | When Jarvis first stores or reads a key; macOS shows its own Keychain prompt | Keys are kept in a permission-restricted local file instead |
+
+Jarvis does not ask for a permission that a feature you have not turned on needs.
+Features that only read the interface structure of another app never open a dialog;
+they quietly do less. macOS owns the wording and the look of its dialogs. On
+some macOS versions the system may add its own extra Screen Recording
+confirmation; that comes from macOS, not from Jarvis.
+
+The Appshots both-Option shortcut is not listed under Input Monitoring: it is not
+established whether macOS requires that permission for it.
+
+## If You Say No
+
+macOS normally does not ask again after you decide, and it shows nothing when a
+feature then fails. So when a feature you started is blocked by a permission,
+Jarvis shows one short message in its usual notification corner, with one button.
+It is never shown while an Apple dialog is open and never for something that started
+in the background. It is not repeated while on screen, but comes back if you dismiss
+it, or it fades, and you try the feature again. It appears in the main desktop
+window only (not a detached window or a browser), and only while that window is
+visible: a message due while it was hidden is not saved for later. The wording is calm
+and names no settings pane, for example "Personal Jarvis needs microphone access
+to hear you." The button is one of:
+
+- **Open System Settings**, which opens the matching pane. Turn on Personal
+ Jarvis, then use the feature again.
+- **Ask macOS now**, when macOS can still ask, or when Jarvis was started from a
+ terminal or a copy (the message then says the app that started Jarvis gets the
+ access).
+- **Quit and reopen**, only when a permission is on but macOS applies it to a
+ fresh process, and only after a real attempt failed.
+
+A Mac restricted by device policy gets a sentence and no button. One background feature may speak up: if the wake word you switched
+on cannot listen because the microphone is off, Jarvis says so once per session.
+Dictation also shows its own short line on the bar, and Computer Use reads its
+reason aloud.
+
+A permission you turn on in System Settings is expected to work at once. If a switch
+shows on but the feature still fails, as can happen after an update changed the
+app's signature, start over (next section).
+
+## Start Over for One Permission
+
+There is no permissions page and no reset button in the app. To make macOS forget
+its answer for Personal Jarvis, so that it asks again the next time you use the
+feature, run this in a terminal on the Mac (it works with Jarvis closed):
+
+```bash
+jarvis permissions reset microphone --yes
+```
+
+If the terminal says `jarvis: command not found` (the downloaded app does not put it on
+your path), run `"/Applications/Personal Jarvis.app/Contents/MacOS/jarvis"` instead, or
+use `tccutil reset Microphone ai.personaljarvis.desktop` (installer's app:
+`com.personal-jarvis.desktop`); [Troubleshooting](troubleshooting) has the rest.
+
+Replace `microphone` with `screen_recording`, `accessibility`, `input_monitoring`,
+or `automation`. The command resets only Personal Jarvis's own record for that one
+permission, for the installed app (`--bundle-id` names the other app when both the
+installer's and the downloaded app are installed), never another app's. `--dry-run`
+shows the exact `tccutil` command without running it. Quit and reopen Jarvis
+afterwards, then use the feature. Other systems print one line and stop. The raw
+`tccutil` commands are in [Troubleshooting](troubleshooting). `jarvis permissions
+status` shows where each permission stands and never asks.
+
+**Keychain (API keys)** has no System Settings pane and no reset. If Keychain access
+was declined, Jarvis keeps working with a permission-restricted local file;
+`jarvis permissions request credential_store` retries Keychain access. The local
+file is a compatibility fallback, not encrypted Keychain storage.
To revoke access, turn off Personal Jarvis in the matching macOS **Privacy &
Security** pane. The app has no **Revoke** or **Reset all permissions** button.
-**Ask again** is recovery for one denied row, not a revocation control. Return
-to the app after a change and restart when asked.
+Revoking stops later use; it does not delete audio, screenshots, action records, or
+provider data that already exists.
-Revoking access stops later use of that capability. It does not delete audio,
-screenshots, action records, or provider data that already exists.
+Grants for the app the installer builds are recorded against a local signing
+certificate it creates once (macOS asks for your login password that one time), so
+they survive updates. The downloaded disk-image app is signed differently: unless it
+carries a stable Apple signature, macOS may treat a new version as a new app.
-## Permissions This Card Does Not Manage
+## Permissions This Page Does Not Cover
### Files and Notifications
-The **Mute music while dictating** setting uses the **Automation (Music &
-Spotify)** row above. If you deny it, Jarvis skips player-specific volume
-control and voice can continue; **Ask again** clears the recorded decision so
-macOS can prompt once more.
+There is no general **Files** row, and Jarvis does not require **Full Disk
+Access**. File access depends on the operating-system account running Jarvis, the
+folder you choose, a browser file picker, a connected service, or a Jarvis-Agent
+mission workspace. macOS may separately ask for **Files & Folders** access to
+protected locations the first time something touches them. Grant the narrow access
+the task needs instead of Full Disk Access.
-There is no general **Files** row, and this flow does not require **Full Disk
-Access**. File access depends on the operating-system account running Jarvis,
-the folder you choose, a browser file picker, a connected service, or a
-Jarvis-Agent mission workspace. macOS may separately ask for **Files &
-Folders** access to protected locations. Grant the narrow access the task needs
-instead of Full Disk Access.
-
-Notification delivery is also outside this card. Manage it in the operating
-system or browser that displays the notification. A browser can separately ask
-for microphone, camera, download, or notification access for one site and one
-browser profile.
+Notification delivery is outside Jarvis's permission handling: manage it in the
+operating system or browser that displays it. A browser can separately ask for
+microphone, camera, download, or notification access per site and profile.
### App Permissions and Tool Approvals
@@ -170,36 +178,37 @@ Jarvis classifies a proposed tool call as **safe**, **monitor**, **ask**, or
**block**. Safe and monitored calls can run without a prompt. Ask-level calls
need a supported confirmation, and no answer is treated as a denial. Blocked
calls do not run. Granting screen or input access never bypasses this decision.
-Read [Safety and Approvals](safety-and-approvals) before allowing
-consequential or unattended work.
+An AI agent never answers a macOS permission dialog: while one is on screen,
+Computer Use dispatches nothing and the task stops until you act. Read [Safety and
+Approvals](safety-and-approvals) before allowing consequential or unattended work.
## How It Fits Together
A feature works only when every required boundary is ready:
1. You start the feature from the app, voice, a shortcut, or a scheduled task.
-2. On macOS, Jarvis checks the live native grant, the installed app identity,
- and any pending restart. Revoking a grant can stop the next capture or input
- action.
+2. On macOS, Jarvis asks the operating system the first time the feature needs a
+ permission, from the action you took, and then acts only on a live grant. A
+ revoked grant stops the next capture or input action.
3. The device, desktop session, model, plugin, or connected account must also
be available.
4. Jarvis applies the safety decision to the exact proposed tool call.
5. The operating system or external service can still refuse the operation.
-For example, macOS Computer Use needs **Screen Recording**,
-**Accessibility**, and **Input control**, plus a live desktop and a working
-image-capable model. The screen grant does not approve a click, and a safety
-approval cannot create a missing screen grant.
+For example, macOS Computer Use needs **Screen Recording** and **Accessibility**,
+a live desktop, and an image-capable model. A safety approval cannot create a
+missing screen grant.
## Check That It Works
Use the microphone as a small, harmless check:
-1. On macOS, open **Settings > Privacy permissions > macOS permissions** and
- confirm that **Microphone** says **Allowed**.
-2. Open the wake-word **Microphone check** and activate **Test your
- microphone**.
-3. Speak a short phrase. A usable level confirms that both the macOS grant and
+1. On a Mac where you have not answered the microphone question, press the
+ dictation button in the composer. macOS shows its microphone dialog; allow it.
+2. Open **System Settings > Privacy & Security > Microphone** and confirm that
+ Personal Jarvis is on.
+3. Open the wake-word **Microphone check**, activate **Test your microphone**,
+ and speak a short phrase. A usable level confirms that both the macOS grant and
the selected microphone work.
On Windows, Linux, or a browser, run the same microphone check and review that
@@ -207,15 +216,22 @@ platform's device or site settings if it cannot capture audio. To verify screen
and input access, use the non-private calculator check in [Computer
Use](computer-use).
+The macOS behaviour on this page is not verified on a real Mac yet; see
+[Platform Support](platform-support) for the verification record.
+
## Troubleshooting
| What you see | What it usually means | What to do |
|---|---|---|
-| App identity warning or no permission actions | Jarvis is not the foreground installed app, or the session is headless | Quit it and open the installed Personal Jarvis app in an interactive macOS session |
-| **Denied** or **Not allowed**, but no prompt appears | macOS already recorded a choice or the native check cannot distinguish it | Use **Ask again** for a denied privacy row, then **Allow**; otherwise use **Open Settings**. For Keychain, use **Allow** |
-| **Restart now** refuses to restart | A Jarvis-Agent mission is still running | Finish or stop the mission, then use **Restart now** again |
-| The card says **Not required**, but the feature is blocked | The host is not macOS, or a browser, device, display session, Wayland, or file boundary owns the failure | Test the feature directly and review the relevant host or browser settings |
-| Every required row says **Allowed**, but the feature fails | A restart, device, model, connection, account scope, or target application is still unavailable | Clear any restart notice, then follow the dependent feature's troubleshooting steps |
+| A feature says access is off, but no dialog appeared | macOS already recorded your earlier answer and does not ask twice | Use **Open System Settings** on the message and turn Personal Jarvis on, or start over with `jarvis permissions reset` |
+| No message appeared, but the feature does nothing | The Jarvis window was hidden when the message was due, or the use was started in the background | Open the main Jarvis window and press the feature again, or switch Personal Jarvis on yourself in **System Settings > Privacy & Security** |
+| System Settings shows the switch on, but the feature still fails | The record may belong to an older version of the app | Run `jarvis permissions reset <permission> --yes` with Jarvis closed, reopen it, and use the feature; if that fails, turn the switch off and on, then restart the Mac |
+| The message says Jarvis is not running as an installed app | Jarvis was started from a terminal or a copy, so macOS would record access for that program | Open the installed Personal Jarvis app, or choose **Ask macOS now** for the program that started Jarvis |
+| The permission dialog is in the wrong language | German and Spanish text needs a system in that language and a new build (an installer's app already on your Mac gets it when next rebuilt); otherwise it is English | Change the system language, or reply to the dialog as it is shown |
+| Permissions are asked for again after an update | The new version was signed differently, so macOS treats it as a new app | Answer once more. A build signed with a stable certificate keeps its grants |
+| **Quit and reopen** refuses to restart | A Jarvis-Agent mission is still running | Finish or stop the mission, then try again |
+| `jarvis permissions status` says `not_required` but the feature is blocked | The host is not macOS, or a browser, device, display session, Wayland, or file boundary owns the failure | Test the feature directly and review the relevant host or browser settings |
+| Every permission reads `granted`, but the feature fails | A restart, device, model, connection, account scope, or target application is still unavailable | Follow the dependent feature's troubleshooting steps |
## Next Steps
diff --git a/docs/product/privacy-safety-and-support/troubleshooting.md b/docs/product/privacy-safety-and-support/troubleshooting.md
index 121d4bea37..cf4b6e75b9 100644
--- a/docs/product/privacy-safety-and-support/troubleshooting.md
+++ b/docs/product/privacy-safety-and-support/troubleshooting.md
@@ -8,7 +8,7 @@ order: 5
diataxis: troubleshooting
status: active
owner: maintainers
-last_reviewed: 2026-07-21
+last_reviewed: 2026-10-02
phase: "-"
audience: end-user
tags: [troubleshooting, diagnostics, recovery, startup, providers, voice, connections, support]
@@ -52,7 +52,7 @@ reinstalling the app.
| Docs only | **Docs** loading or error panel | Select **Try again** |
| Chat replies | **API Keys & Providers > Brain** | Run **Test** on the selected provider |
| Wake, listening, or speech | **Settings > Audio devices** and **Wake Word** | Rescan devices, then run **Test wake word** |
-| An action is denied | The permission card or approval message | Grant or approve only the named access |
+| An action is denied | The short permission message or the approval message | Grant or approve only the named access |
| A plugin, MCP server, or CLI | **Skills, Plugins & MCPs** or **CLIs** | Check that connection's status and one read-only action |
| A task, agent mission, or file | **Tasks**, the Agents view, or **Outputs** | Read its status or timeline before retrying |
@@ -156,7 +156,7 @@ Voice is a chain. Check the first step that fails.
| Symptom | Check |
|---|---|
-| **Voice starting…** remains visible | Wait for the current warm-up once. If it never clears, check microphone access, the selected input, and the voice provider cards. |
+| **Voice starting…** remains visible | Wait for the warm-up once. If it never clears, check microphone access, the selected input, and the voice provider cards. |
| The wake phrase does nothing | Open **Settings > Wake Word**, keep **Auto (recommended)** unless you have a reason to choose another engine, and run **Test wake word**. |
| Listening starts but the transcript is wrong or empty | Select the intended microphone under **Settings > Audio devices**, then use **Rescan devices** if it is missing. |
| The transcript is correct but no reply is heard | Check the selected output device and the active **Voice Output** provider. |
@@ -164,18 +164,17 @@ Voice is a chain. Check the first step that fails.
| Normal conversation triggers the wake phrase | Choose a distinct two-word or three-word phrase with a prefix. There is no sensitivity slider. |
**Test wake word** checks the configured engine, model or vocabulary when
-applicable, and microphone level. It does not prove that the engine will
-recognize your spoken phrase. After it passes, say the phrase once for an
-end-to-end check.
+applicable, and microphone level. It does not prove the engine recognizes your
+phrase; after it passes, say the phrase once.
-On macOS, use **Settings > Privacy permissions** for microphone access and
-restart only if the card shows **Restart now**. A Realtime session opened in a
+On macOS, use the button on the message that appears when the microphone is
+off, and restart only if it offers **Quit and reopen**. A Realtime session opened in a
browser uses that browser's microphone permission and device, not the native
desktop audio selection.
-For a recorded voice turn, **Transcription** and **Run Inspector** can show
-whether speech recognition, a provider, a tool, or spoken output was the last
-recorded stage. They do not diagnose a turn that was never recorded.
+For a recorded voice turn, **Transcription** and **Run Inspector** can show which
+stage (speech recognition, provider, tool, or spoken output) was last recorded.
+They do not diagnose a turn that was never recorded.
### A Permission or Approval Blocks an Action
@@ -184,18 +183,33 @@ questions. The operating system controls microphone, screen, accessibility,
and input access. Jarvis then decides whether a particular action is safe,
needs confirmation, or must be blocked.
-- On macOS, open **Settings > Privacy permissions** and act on the named row.
- Current controls include **Allow**, **Open Settings**, **Check again**, and
- **Restart now**. Current states include **Allowed**, **Not requested**,
- **Denied**, **Restricted**, **Not allowed**, **Unavailable**, **Not
- required**, and **Restart pending**.
-- Windows and Linux do not show the macOS permission cards. Use the operating
+- On macOS, if you said no to Apple's dialog, it never asks again. Use the button
+ on the short message Jarvis shows, or start over (below).
+- Windows and Linux do not show the macOS permission message. Use the operating
system's own microphone, display, and accessibility controls when the
affected feature requires them.
-- Review the exact target and effect before approving an action. Do not weaken
- a safety rule merely to make an unclear request proceed.
-- **Allowed** proves the operating system grant. It does not prove that the
- action is supported or that Jarvis will approve every later request.
+- Review the exact target and effect before approving an action. Never weaken a
+ safety rule just to make an unclear request proceed.
+- A granted permission proves only the operating system grant, not that the action
+ is supported or that Jarvis will approve it.
+
+### Start Over for One macOS Permission
+
+If macOS shows no dialog, or a switch is on but the feature fails, quit
+Personal Jarvis and run `jarvis permissions reset <permission>
+--yes` (add `--bundle-id` for the other app). If `jarvis` is not found, the
+downloaded app's command is `/Applications/Personal Jarvis.app/Contents/MacOS/jarvis`.
+Without the command, run `tccutil` with
+`ai.personaljarvis.desktop` (downloaded app) or `com.personal-jarvis.desktop`
+(installer's app):
+
+```bash
+for s in Microphone ScreenCapture Accessibility ListenEvent AppleEvents; do
+ tccutil reset "$s" ai.personaljarvis.desktop
+done
+```
+
+Reopen Jarvis; macOS asks again.
### A Plugin, MCP Server, or CLI Is Disconnected
@@ -296,13 +310,12 @@ Verify only the path you repaired:
**Offline** state has cleared.
2. Run its smallest harmless check. Reload one Doc, run one provider **Test**,
use **Test wake word**, recheck one connection, or refresh one task.
-3. Complete one end-to-end action with no external side effect. For chat, ask
- for a short reply. For voice, ask one short question and confirm the
- transcript and spoken reply.
+3. Complete one end-to-end action with no external side effect: a short chat
+ reply, or one short voice question with its transcript and spoken reply.
4. If it was a recorded voice problem, open **Transcription** and **Run
Inspector** and confirm that the new session contains the expected turn.
5. Stop when the focused check passes. Do not rotate unrelated credentials or
- change several working settings as a precaution.
+ change working settings as a precaution.
## Next Steps
diff --git a/docs/product/reference/platform-support.md b/docs/product/reference/platform-support.md
index 594f40ffe8..11f03edd53 100644
--- a/docs/product/reference/platform-support.md
+++ b/docs/product/reference/platform-support.md
@@ -8,7 +8,7 @@ order: 6
diataxis: reference
status: active
owner: maintainers
-last_reviewed: 2026-07-21
+last_reviewed: 2026-10-02
phase: "-"
audience: end-user
tags: [platforms, windows, macos, linux, headless, requirements, compatibility]
@@ -107,7 +107,8 @@ backends, an accessibility tree, an overlay, cursor access, and elevation.
Failed probes report **unavailable** instead of stopping startup.
Windows uses UI Automation and native input. macOS Computer Use needs the
-matching Accessibility and Screen Recording permissions. Linux uses AT-SPI
+matching Accessibility and Screen Recording permissions; macOS asks for them
+the first time Computer Use needs them, not at startup. Linux uses AT-SPI
when its packages and desktop bus are available. Without a native interface
tree, screenshots and pixel positions can work but cannot identify controls by
name.
@@ -118,8 +119,8 @@ name.
- **Headless:** there is no display to capture or control. Chat, APIs, browser
views, missions, and file work still run.
-On macOS, grant permissions to **Personal Jarvis**, not Terminal or Python, so
-they stay attached to the app bundle. The Bar and mascot use its desktop
+On macOS, answer the permission dialogs for **Personal Jarvis**, not Terminal or
+Python, so they stay attached to the app bundle. The Bar and mascot use its desktop
companion.
Linux overlays are best effort. With no compatible X11, compositor, and Tk
@@ -138,7 +139,7 @@ surface, Jarvis falls back to the tray or no visible surface; chat continues.
| Linux AT-SPI packages and desktop bus | Only for native Linux UI labels | Named interface elements for more reliable Computer Use on X11 |
| Linux global-hotkey backend | Only for global voice shortcuts on X11 | Shortcut capture; it is not part of the current Linux full-profile dependency set |
| Xcode Command Line Tools on macOS | Required to build the managed desktop launcher | The installer compiles and signs the local app launcher and stops with an installation hint when `clang` is unavailable |
-| macOS privacy grants | Only for the feature named by each grant | Microphone, global shortcuts, screen capture, accessibility, and input control |
+| macOS privacy grants | Only for the feature that needs each one; macOS asks when you first use or switch on that feature (or, for global shortcuts, when you save one) | Microphone, global shortcuts, screen capture, accessibility, and input control |
| Graphical display | Only for desktop surfaces | Desktop window, overlays, screen capture, and physical Computer Use |
## Storage and Network Defaults
@@ -225,7 +226,7 @@ capability works.
On a desktop, choose **Settings > Audio devices > Rescan devices** and confirm
the intended devices appear. Then run the relevant **Test wake word** action,
-macOS permission check, or a reversible Computer Use action.
+check the macOS permissions in **System Settings > Privacy & Security** (or with `jarvis permissions status` when the `jarvis` command is available), or run a reversible Computer Use action.
On headless Linux, open the printed local address and test text chat first.
Configure authenticated HTTPS access before using a remote browser microphone.
@@ -237,7 +238,7 @@ Configure authenticated HTTPS access before using a remote browser microphone.
| Python is rejected | Outside 3.11 through 3.14 | Let the installer choose, or install a supported version |
| Linux opens a server | No X11 or Wayland display | Use the printed address, or install from a graphical session |
| Linux audio is unavailable | PortAudio, access, or device missing | Install PortAudio, reconnect, then choose **Rescan devices** |
-| A macOS shortcut or screen action fails | Privacy grant missing | Review **Settings > Privacy permissions** and restart when asked |
+| A macOS shortcut or screen action fails | Privacy grant missing or declined | Use the button on the short message Jarvis shows (**Open System Settings**), and a restart only when it says so; `jarvis permissions reset` starts over (see [App Permissions](permissions) if the command is not found) |
| Linux Computer Use refuses | Wayland or no display | Use X11; text and browser features still work |
| Linux control names are missing | AT-SPI or its bus is unavailable | Install accessibility packages; pixel fallback may work |
| A local voice engine is unavailable | No compatible native package | Choose another local, browser, or online speech path |
diff --git a/docs/product/start-here/first-run-setup.md b/docs/product/start-here/first-run-setup.md
index 2455d35422..e08f0b1a61 100644
--- a/docs/product/start-here/first-run-setup.md
+++ b/docs/product/start-here/first-run-setup.md
@@ -8,7 +8,7 @@ order: 3
diataxis: tutorial
status: active
owner: maintainers
-last_reviewed: 2026-10-01
+last_reviewed: 2026-10-02
phase: "-"
audience: end-user
tags: [setup, onboarding, tour, language, permissions, microphone, wake-word, providers]
@@ -26,8 +26,8 @@ follow and let you try the assistant for real.
- Open the installed desktop app. The first launch may take several seconds.
- Have one API key ready (OpenAI or Google Gemini is the shortest path), or run
Ollama with one installed model for a keyless Brain.
-- On macOS, launch the signed app from its application bundle before granting
- access; permissions belong to that exact app identity.
+- On macOS, launch the installed app from its application bundle; permissions
+ belong to that exact app identity. Setup does not ask for any of them.
> [!warning] Paste a provider credential only into the masked key field on the
> **API Keys** page. Never paste one into chat, speak it, put it in a wake word,
@@ -90,22 +90,19 @@ billed per use.
The card lists every subscription that is signed in, and **Continue** unlocks
once there is one. **I'll connect one later** moves on.
-### 5. Allow access on this Mac (macOS only)
-
-Setup opens **Settings > Privacy permissions**. Use **Allow** or **Open
-Settings** on each row you want, return, and wait for the row to update. The
-restart at the end applies the grants. Windows and Linux skip this step.
-
-### 6. Choose your wake word
+### 5. Choose your wake word
Setup opens **Settings** at the **Wake Word** group. **Hey** is fixed; type
your own word after it and save. The word also becomes the assistant's name,
for example **Hey Nova** makes an assistant called Nova. The card confirms when
the wake word is on, and **Continue** unlocks once one is saved. Without a
wake word, choose **Skip, I'll use the Call shortcut**; the Call keyboard
-shortcut then starts a conversation.
+shortcut then starts a conversation. On a Mac, switching the wake word on is
+the moment macOS asks for microphone access, and choosing the Call shortcut is
+the moment it asks for Input Monitoring, which lets a shortcut work while another
+app is in front; setup has no separate permissions step.
-### 7. All set
+### 6. All set
The last card reads back the active Brain, the connected agent subscriptions
and how voice starts, and offers **Start at login** if your system supports
@@ -150,7 +147,9 @@ open the Agentic IDE.
- Change the interface and reply languages under **Settings > Languages**.
- Connect and test models under **API Keys**; the same page connects coding
agents by key or subscription.
-- Repair macOS access under **Settings > Privacy permissions**.
+- Repair macOS access in **System Settings > Privacy & Security**; when a feature
+ you started needs a permission, Personal Jarvis shows one short message with a
+ button that opens it. [App Permissions](permissions) explains how to start over.
- Change the phrase, spoken wake language, activation switch, or local wake
pack under **Settings > Wake Word**, and the Call shortcut under **Settings >
Voice Keybinds**.
diff --git a/docs/product/start-here/start-your-first-voice-conversation.md b/docs/product/start-here/start-your-first-voice-conversation.md
index 58d8522809..cc7fb1fc0d 100644
--- a/docs/product/start-here/start-your-first-voice-conversation.md
+++ b/docs/product/start-here/start-your-first-voice-conversation.md
@@ -8,7 +8,7 @@ order: 6
diataxis: tutorial
status: active
owner: maintainers
-last_reviewed: 2026-07-30
+last_reviewed: 2026-10-02
phase: "-"
audience: end-user
tags: [voice, microphone, wake-word, keyboard-shortcut, realtime, pipeline, dictation, tutorial]
@@ -34,8 +34,8 @@ text without asking the Brain or speaking a reply.
warming up.
- Connect a microphone and speaker or headset, then check both under
**Settings > Audio devices**.
-- On macOS, allow **Microphone** access. The Call shortcut can also require
- Accessibility or Input Monitoring access. Review
+- On macOS, allow **Microphone** access. The Call shortcut also requires
+ Input Monitoring access, which macOS asks for when you save a shortcut. Review
[Permissions](permissions) if the app reports that access is missing.
- Under **API Keys & Providers**, connect only what your voice engine needs:
one compatible live provider for Realtime, or usable Voice Input, Brain,
diff --git a/docs/screen-context.md b/docs/screen-context.md
index 280db4fbc7..1ebd503669 100644
--- a/docs/screen-context.md
+++ b/docs/screen-context.md
@@ -160,8 +160,9 @@ user speaks
│
▼
[2] permission check (screen recording; accessibility for UI text)
- ├── denied → "technical" refusal: logged, turn CONTINUES on the old path
- │ (see Wave 2 — a missing permission is not a prohibition)
+ ├── denied → (macOS: ask once through the permission service) if still
+ │ not granted: "technical" refusal, logged, turn CONTINUES on the
+ │ old path (see Wave 2 — a missing permission is not a prohibition)
└── granted ↓
│
▼
@@ -342,12 +343,17 @@ OS text is otherwise both faster and more accurate.
| OS | Capture | UI text | Failure mode |
|---|---|---|---|
| Windows | none required | none required | — |
-| macOS | Screen Recording (TCC) | Accessibility (TCC) | Capture without the grant returns *wallpaper only*, with no error — so it is probed on every capture and refused honestly rather than returned as a successful blank. |
+| macOS | Screen Recording (TCC), asked at the first capture a person starts | Accessibility (TCC), read in the background and never asked for here | Capture without the grant returns *wallpaper only*, with no error — so it is probed on every capture and refused honestly rather than returned as a successful blank. |
| Linux/X11 | none required | AT-SPI session | — |
| Linux/Wayland | no addressable global capture | AT-SPI | Refused with the X11/XWayland message; the compositor owns capture. |
Permission state is never cached across captures: macOS can revoke a grant while
-the app runs. The probe is one call and it is the first thing after intent.
+the app runs. The probe is one call and it is the first thing after intent. The
+probe itself is silent (the status route calls it too). Because a capture is
+always started by a person, a missing Screen Recording grant then goes through
+the just-in-time permission service (`screen_access.require_screen_recording_async`),
+which asks macOS once per episode; only a live grant lets the capture continue
+(ADR-0038, `docs/macos-permissions.md`).
Every denial produces a message that names the exact setting to change and is
recoverable in-app (AGENTS.md §3) — never a stack trace, never a silent no-op.
diff --git a/docs/superpowers/specs/2026-06-27-computer-use-zoom-before-click-design.md b/docs/superpowers/specs/2026-06-27-computer-use-zoom-before-click-design.md
index 1b00534158..02e99971a3 100644
--- a/docs/superpowers/specs/2026-06-27-computer-use-zoom-before-click-design.md
+++ b/docs/superpowers/specs/2026-06-27-computer-use-zoom-before-click-design.md
@@ -184,6 +184,11 @@ happens *inside* attempt 0 and does not add an attempt.
- **macOS** needs the Screen-Recording TCC permission, which is already probed
(`screen_recording_granted`); without it, capture returns and the step
degrades to the coarse click.
+ *(Annotation 2026-10-02: `screen_recording_granted` in `jarvis/platform/probes.py`
+ has since been deleted. The state is now read through
+ `jarvis/platform/screen_access.py` and `jarvis/platform/permission_service.py`
+ (ADR-0038, `docs/macos-permissions.md`); the capture a person starts is where
+ macOS is asked. The design above is otherwise unchanged.)*
- **Linux/Wayland** screenshot restrictions are already handled by the graceful
`None` return from `_grab_region_jpeg` → coarse click.
- **Browsers** need no special handling: the crop is application-agnostic. A
diff --git a/install/README.md b/install/README.md
index 827ecef3ac..6ba0ba3282 100644
--- a/install/README.md
+++ b/install/README.md
@@ -36,20 +36,28 @@ repair these artifacts, and uninstall removes them again. Developer checkouts
and headless Linux hosts are deliberately not registered.
On macOS, every launch path enters through the same app bundle so privacy
-grants stay attached to one identity. The source installer builds a native
-py2app alias launcher, signs it with a per-user code-signing certificate it
+grants stay attached to one identity. The source installer compiles a small
+native launcher (`jarvis/setup/macos_stub_launcher.c`) into
+`Personal Jarvis.app`, signs it with a per-user code-signing certificate it
creates on the first run (macOS asks for the login password once to trust
it; grants then survive every rebuild and update), verifies the identity from
inside a LaunchServices process, and preserves the bundle unchanged across
ordinary updates. Without that certificate the launcher is ad-hoc signed and a
rebuild costs one round of re-granting. A separately distributed binary still requires the release
-pipeline's Developer-ID signing and notarization. Apple does not permit an installer to
-silently grant Microphone, Screen Recording, Accessibility, Input Monitoring,
-or input-control access. The app therefore presents one explicit button per
-permission during first launch, uses only Apple's native prompt/System Settings
-flows, and remains fully usable for text when the user declines. The installer
-stops instead of claiming success if the full profile or app-bundle registration
-fails.
+pipeline's Developer-ID signing and notarization. The installer stops instead of
+claiming success if the full profile or app-bundle registration fails.
+
+Apple does not permit an installer to silently grant Microphone, Screen
+Recording, Accessibility, Input Monitoring or input-control access, so the
+installer asks for none of them and neither does the first launch. Personal
+Jarvis asks at the moment a feature you start needs a permission: the first
+dictation asks for the microphone, the first screen capture asks for Screen
+Recording, and so on, each through Apple's own dialog or System Settings pane.
+If you decline, only that one feature is unavailable, with one click to the
+right System Settings pane (one short toast offers it), and everything else (typed
+chat included) keeps working. `jarvis permissions reset <permission>` makes macOS ask
+again. This is how the app is built to behave; it has not been exercised on a real
+Mac yet (unverified).
## Current cryptography on every architecture
diff --git a/jarvis.spec b/jarvis.spec
index 29adeb4dab..31106970ef 100644
--- a/jarvis.spec
+++ b/jarvis.spec
@@ -66,6 +66,24 @@ def _package_version() -> str:
VERSION = _package_version()
+def _macos_privacy_strings():
+ """Load ``jarvis/core/macos_privacy_strings.py`` by path.
+
+ The spec runs before ``jarvis`` is importable, and the managed app's
+ ``Info.plist`` loads the very same file the very same way, so the two
+ bundles cannot drift apart (tests/unit/packaging/test_macos_privacy_strings.py).
+ """
+ import importlib.util
+
+ path = PROJECT_ROOT / "jarvis" / "core" / "macos_privacy_strings.py"
+ loader_spec = importlib.util.spec_from_file_location("_jarvis_macos_privacy_strings", path)
+ if loader_spec is None or loader_spec.loader is None:
+ raise SystemExit(f"cannot load the macOS usage strings from {path}")
+ module = importlib.util.module_from_spec(loader_spec)
+ loader_spec.loader.exec_module(module)
+ return module
+
+
# --- Data files -------------------------------------------------------------
datas = []
@@ -224,6 +242,20 @@ for pkg in _optional_hidden:
continue
hiddenimports.append(pkg)
+# macOS: the permission port loads pyobjc frameworks BY NAME
+# (``SystemPermissionPort._load("AVFoundation")``), which no static import
+# analysis can see. Without AVFoundation the frozen app read the microphone
+# permission as "unavailable" for good, so the voice gate never opened - the
+# v2.5.0 image shipped exactly like that (BUG-222). It needs the
+# ``[desktop-macos]`` extra on the build machine; a build without it is refused
+# by scripts/ci/check_frozen_macos_app.py instead of being shipped quietly.
+if sys.platform == "darwin":
+ for pkg in ("AVFoundation",):
+ try:
+ hiddenimports += collect_submodules(pkg)
+ except Exception as exc:
+ print(f"[jarvis.spec] WARNING: cannot collect {pkg}: {exc}")
+
# --- Bundle-size exclusions -------------------------------------------------
@@ -427,46 +459,27 @@ if sys.platform == "darwin":
"CFBundleShortVersionString": VERSION,
"CFBundleVersion": VERSION,
"CFBundlePackageType": "APPL",
+ # PyInstaller sets LSBackgroundOnly=True whenever the LAST executable
+ # of the COLLECT is a console one - and the `jarvis` CLI is. A
+ # background-only app gets no Dock icon, no menu bar and no windows
+ # from LaunchServices; the v2.5.0 image shipped that way. This is a
+ # windowed app (the CLI entry runs from a terminal, not through
+ # LaunchServices), so say so explicitly.
+ "LSBackgroundOnly": False,
"LSMinimumSystemVersion": MACOS_MIN_SYSTEM_VERSION,
"LSApplicationCategoryType": "public.app-category.productivity",
"NSHighResolutionCapable": True,
- # Personal Jarvis is voice-first: without a usage string macOS kills
- # the process the moment it touches the matching API.
- "NSMicrophoneUsageDescription": (
- "Personal Jarvis listens for your wake word and your spoken "
- "requests. Audio stays on this Mac unless you configure a cloud "
- "speech provider yourself."
- ),
- "NSSpeechRecognitionUsageDescription": (
- "Personal Jarvis turns what you say into text so it can act on "
- "your request."
- ),
- "NSCameraUsageDescription": (
- "Personal Jarvis uses the camera only for features you start "
- "yourself, such as showing it what is in front of you."
- ),
- "NSAppleEventsUsageDescription": (
- "Personal Jarvis controls other applications on your behalf "
- "when you ask it to, for example to open a file or a window."
- ),
- "NSSystemAdministrationUsageDescription": (
- "Personal Jarvis needs Accessibility and Input Monitoring "
- "access to type, click and read the screen for the automation "
- "tasks you ask it to run."
- ),
- "NSDesktopFolderUsageDescription": (
- "Personal Jarvis saves the files it produces for you to your "
- "Desktop."
- ),
- "NSDocumentsFolderUsageDescription": (
- "Personal Jarvis reads and writes the documents you point it at."
- ),
- "NSDownloadsFolderUsageDescription": (
- "Personal Jarvis opens the downloads you ask it to work with."
- ),
- "NSLocalNetworkUsageDescription": (
- "Personal Jarvis serves its own interface to your browser on "
- "this machine."
- ),
+ # Every NS...UsageDescription string comes from the single table in
+ # jarvis/core/macos_privacy_strings.py, which the managed app's
+ # Info.plist loads too. Without the microphone string macOS ends the
+ # process the moment it touches the microphone, so the table is
+ # asserted on the built app (scripts/ci/check_frozen_macos_app.py).
+ # Add or reword a string THERE, never here.
+ **_macos_privacy_strings().usage_descriptions(),
+ # German and Spanish usage strings: the languages are declared here,
+ # the <lang>.lproj/InfoPlist.strings files themselves are written
+ # into the finished .app by packaging/macos/build.sh (before signing,
+ # because they are part of the seal) from the same table.
+ **_macos_privacy_strings().localization_plist_keys(),
},
)
diff --git a/jarvis/agent_screen/runner/server.py b/jarvis/agent_screen/runner/server.py
index 7b50211502..01831d418f 100644
--- a/jarvis/agent_screen/runner/server.py
+++ b/jarvis/agent_screen/runner/server.py
@@ -65,9 +65,26 @@ class ScreenServer:
def _get_actuator(self) -> Any:
if self._actuator is None and not self._actuator_error:
try:
- from jarvis.cu.actuate import get_actuator # noqa: PLC0415
-
+ from jarvis.cu.actuate import ( # noqa: PLC0415
+ PermissionNeededError,
+ get_actuator,
+ )
+ except Exception as exc: # noqa: BLE001 — reported per action
+ # The import itself failed (a missing optional dependency): cache
+ # the real message. Kept apart from the call below so the
+ # ``except PermissionNeededError`` clause never names an unbound
+ # symbol.
+ self._actuator_error = str(exc)
+ raise RuntimeError(self._actuator_error) from exc
+ try:
self._actuator = get_actuator()
+ except PermissionNeededError:
+ # Not unavailability: the person may allow Accessibility at any
+ # moment, so this is never cached. The next action asks again
+ # (``get_actuator`` re-reads the live state each call) instead of
+ # failing forever with the first refusal. The error itself carries
+ # the prohibitive "[permission_needed:...]" text for the engine.
+ raise
except Exception as exc: # noqa: BLE001 — reported per action
self._actuator_error = str(exc)
if self._actuator is None:
diff --git a/jarvis/appshot/gesture.py b/jarvis/appshot/gesture.py
index 21bd2318e6..fcbdc10551 100644
--- a/jarvis/appshot/gesture.py
+++ b/jarvis/appshot/gesture.py
@@ -7,9 +7,13 @@ primitive each OS offers — a key-state read every 50 ms, no hook, no tap:
* Windows: ``GetAsyncKeyState`` on ``VK_LMENU`` / ``VK_RMENU`` (AltGr raises
``VK_RMENU`` too, so the gesture works on AltGr layouts).
-* macOS: ``CGEventSourceKeyState`` on the left/right Option key codes. Needs
- the same Input Monitoring grant as every other global shortcut; without it
- the read stays false and nothing fires.
+* macOS: ``CGEventSourceKeyState`` on the left/right Option key codes. Whether
+ this read needs a privacy grant (Input Monitoring) is UNVERIFIED: the repo
+ contradicts itself (``CGEventSourceFlagsState`` is documented in
+ ``jarvis/trigger/hotkey.py`` as needing none) and neither was measured on a
+ Mac. It is therefore not treated as an Input Monitoring feature and never
+ triggers a permission request; if the gesture does nothing the status text
+ (``jarvis/appshot/hotkey.py``) points to another key combination.
* Linux/X11: ``XQueryKeymap`` through python-xlib (pynput's own dependency).
* Wayland, headless, missing packages: :func:`make_probe` returns ``None``
with the reason, and the caller reports the shortcut as unavailable.
diff --git a/jarvis/appshot/hotkey.py b/jarvis/appshot/hotkey.py
index c7d3b62038..30f5a44b4d 100644
--- a/jarvis/appshot/hotkey.py
+++ b/jarvis/appshot/hotkey.py
@@ -30,6 +30,22 @@ class ShortcutStatus:
return {"hotkey": self.hotkey, "armed": self.armed, "detail": self.detail}
+#: Status text for the both-Option gesture on a Mac. Its permission need is
+#: UNVERIFIED (see ``jarvis.appshot.gesture``), so the hint names no permission:
+#: sending someone to grant one it may not need is worse than saying nothing.
+BOTH_OPTION_MAC_NOTE = (
+ "If the both-Option shortcut does nothing on this Mac, pick a key "
+ "combination instead."
+)
+
+
+def _both_alt_note() -> str:
+ """The macOS-only hint that goes with an armed both-Option gesture."""
+ from jarvis.platform import detect_platform # noqa: PLC0415
+
+ return BOTH_OPTION_MAC_NOTE if detect_platform() == "darwin" else ""
+
+
def normalize_hotkey(value: str) -> str:
"""Canonical spelling: lower case, no spaces, both-Alt aliases folded."""
combo = "+".join(part.strip().lower() for part in str(value or "").split("+") if part.strip())
@@ -115,7 +131,7 @@ class AppshotShortcut:
watcher = BothAltWatcher(self._fire_threadsafe, probe=probe)
watcher.start()
self._watcher = watcher
- return ShortcutStatus(hotkey=BOTH_ALT, armed=True)
+ return ShortcutStatus(hotkey=BOTH_ALT, armed=True, detail=_both_alt_note())
def _arm_combo(self, hotkey: str) -> ShortcutStatus:
from jarvis.platform.probes import has_hotkey # noqa: PLC0415
diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.py
index d1440084f8..0b3abace03 100644
--- a/jarvis/audio/capture.py
+++ b/jarvis/audio/capture.py
@@ -13,7 +13,6 @@ from __future__ import annotations
import asyncio
import math
-import sys
import time
from collections.abc import AsyncIterator, Callable, Iterator, Sequence
from typing import TYPE_CHECKING, Any
@@ -25,6 +24,9 @@ if TYPE_CHECKING:
# Type-checkers see the real module so `sd.InputStream` annotations resolve;
# at runtime the guarded import below binds sd (or None when absent).
import sounddevice as sd
+
+ from jarvis.core.protocols import PermissionGate
+ from jarvis.platform.permission_service import EnsureResult
else:
try:
import sounddevice as sd
@@ -33,6 +35,7 @@ else:
from jarvis.audio import topology
from jarvis.audio.device_select import is_legacy_primary_mapper
+from jarvis.core.events import PERMISSION_FEATURES, PermissionNeeded
from jarvis.core.protocols import AudioChunk
SAMPLE_RATE = 16_000 # Whisper native rate
@@ -89,37 +92,73 @@ def capture_chunks_for_duration(seconds: float) -> int:
DEFAULT_QUEUE_CHUNKS = capture_chunks_for_duration(2.0)
-class MicrophoneAccessError(PermissionError):
- """The current process is not allowed to open the local microphone."""
+# The permission this module asks about. The service takes the plain id string
+# (``PermissionId`` is a ``StrEnum``), which keeps ``jarvis.platform`` out of this
+# module's import graph: a headless install must import capture without it.
+_MICROPHONE = "microphone"
+_GRANTED_STATES = frozenset({"granted", "not_required"})
+# Exact digital silence (all-zero samples) for this long while the OS says the
+# microphone is granted means macOS is feeding zeros (a denied or muted input):
+# the capture reports it once and stays open (unverified on a real Mac).
+_SILENCE_REPORT_AFTER_S = 5.0
+_SILENCE_DETAIL = (
+ "The microphone delivers only silence: access is probably denied or muted."
+)
+_NOT_GRANTED_MESSAGE = "Microphone access is not granted for Personal Jarvis."
-def _macos_microphone_access_gate() -> Callable[[], bool] | None:
- """Build an uncached, non-prompting TCC gate for a macOS capture.
- Importing the native permission port is deliberately deferred so the base
- audio module remains portable on Windows, Linux, and headless installs.
- The returned port probes both the grant and app-bundle identity on every
- call; it never invokes an Apple request API.
+class MicrophoneAccessError(PermissionError):
+ """The microphone may not be opened, or was revoked while it was open.
+
+ ``result`` is the permission layer's :class:`EnsureResult` for the refusal
+ (``user_detail`` is a finished sentence for people, ``agent_detail`` the
+ prohibitive one for a tool error), so a consumer can say WHY without asking
+ the OS again. It is ``None`` only for an error raised by code that never
+ consulted the layer.
"""
- if sys.platform != "darwin":
- return None
- try:
- from jarvis.platform.permissions import ( # noqa: PLC0415
- PermissionId,
- get_system_permission_port,
- )
- port = get_system_permission_port()
- except Exception: # noqa: BLE001 - protected capture must fail closed
- return lambda: False
+ def __init__(self, message: str = "", *, result: EnsureResult | None = None) -> None:
+ super().__init__(message)
+ self.result = result
- def _allowed() -> bool:
- try:
- return port.runtime_access_granted(PermissionId.MICROPHONE)
- except Exception: # noqa: BLE001 - a probe failure is not permission
- return False
- return _allowed
+def _state_value(state: Any) -> str:
+ return str(getattr(state, "value", state))
+
+
+def _legacy_gate_result(allowed: bool) -> EnsureResult:
+ """An ``EnsureResult`` for an injected boolean ``access_gate`` (a test seam)."""
+ from jarvis.platform.permission_service import ( # noqa: PLC0415 - lazy: keeps capture headless-light
+ EnsureResult,
+ PermissionOutcome,
+ agent_detail_for,
+ user_detail_for,
+ )
+ from jarvis.platform.permissions import PermissionId, PermissionState # noqa: PLC0415
+
+ if allowed:
+ return EnsureResult(
+ permission=PermissionId.MICROPHONE,
+ outcome=PermissionOutcome.GRANTED,
+ state=PermissionState.GRANTED,
+ asked=False,
+ outside_installed_app=False,
+ agent_detail="",
+ user_detail="",
+ )
+ return EnsureResult(
+ permission=PermissionId.MICROPHONE,
+ outcome=PermissionOutcome.DENIED,
+ state=PermissionState.DENIED,
+ asked=False,
+ outside_installed_app=False,
+ agent_detail=agent_detail_for(PermissionId.MICROPHONE, "denied"),
+ user_detail=user_detail_for(PermissionId.MICROPHONE, "denied"),
+ reason="denied",
+ can_open_settings=True,
+ )
+
# Queue depth for a REAL-TIME detection consumer (VAD endpointing, wake, barge).
# ~0.6 s: shallow enough that on a CPU which can't process every frame in real
@@ -722,7 +761,6 @@ class MicrophoneCapture:
# reliable detection is "no callback for X seconds".
_STALL_THRESHOLD_S: float = 3.0
_WATCHDOG_TICK_S: float = 1.0
- _ACCESS_RECHECK_S: float = 0.25
def __init__(
self,
@@ -733,10 +771,27 @@ class MicrophoneCapture:
max_queue_chunks: int = DEFAULT_QUEUE_CHUNKS,
device_priority: Sequence[str] | None = None,
access_gate: Callable[[], bool] | None = None,
+ permission_feature: str = "voice",
+ interactive: bool = False,
+ permission_wait_s: float = 0.0,
+ permission_gate: PermissionGate | None = None,
) -> None:
- self._access_gate = (
- access_gate if access_gate is not None else _macos_microphone_access_gate()
- )
+ if permission_feature not in PERMISSION_FEATURES:
+ raise ValueError(f"Unknown permission feature: {permission_feature!r}")
+ # Permission contract (docs/macos-permissions.md, 4.6): ONE service ``ensure`` when the
+ # stream opens, then one cheap ``check`` per watchdog tick. ``interactive``
+ # says whether a user gesture started this capture (it may make macOS ask);
+ # the default is the safe one, a background start that never asks.
+ # ``permission_wait_s`` > 0 waits for the OS dialog and is for a caller
+ # that is not an edge gesture (a held key passes 0).
+ self._permission_feature = permission_feature
+ self._interactive = bool(interactive)
+ self._permission_wait_s = max(0.0, float(permission_wait_s))
+ # ``access_gate`` is the legacy boolean test seam: when given it REPLACES
+ # the service (no ask, no episode). ``permission_gate`` injects a
+ # ``PermissionGate`` (the real service by default, resolved per call).
+ self._access_gate = access_gate
+ self._permission_gate = permission_gate
# 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.
@@ -799,21 +854,68 @@ class MicrophoneCapture:
self._last_chunk_monotonic: float = 0.0
self._watchdog_task: asyncio.Task | None = None
self._restart_count: int = 0
+ # Permission bookkeeping. ``_watch_access``: the watchdog re-checks the
+ # grant each tick (False off macOS, where the service answers
+ # NOT_REQUIRED and the capture never touches it again). ``_revoked`` /
+ # ``_access_error``: the grant was lost while open; ``stream()`` raises.
+ self._watch_access = False
+ self._unreadable_ticks = 0
+ self._revoked = False
+ self._access_error: MicrophoneAccessError | None = None
+ # Digital-silence guard (macOS only, armed when the OS said GRANTED).
+ self._silence_guard_armed = False
+ self._zero_since: float | None = None
+ self._silence_reported = False
+
+ def _service_gate(self) -> PermissionGate:
+ """The injected gate, else the process service (resolved per call)."""
+ gate = self._permission_gate
+ if gate is not None:
+ return gate
+ from jarvis.platform.permission_service import ( # noqa: PLC0415 - lazy: keeps capture headless-light
+ get_permission_service,
+ )
+
+ return get_permission_service()
- def _require_microphone_access(self) -> None:
- """Fail before a native open and whenever a live grant is revoked."""
+ def _legacy_gate_allows(self) -> bool:
gate = self._access_gate
if gate is None:
- return
+ return True
try:
- allowed = bool(gate())
- except Exception: # noqa: BLE001 - protected capture must fail closed
- allowed = False
- if not allowed:
- raise MicrophoneAccessError(
- "Microphone capture requires a granted macOS permission under "
- "the installed Personal Jarvis app identity."
+ return bool(gate())
+ except Exception as exc: # noqa: BLE001 - a gate that raises is not a grant
+ _log.debug("Mic access gate raised ({}); treated as not granted.", exc)
+ return False
+
+ @staticmethod
+ def _access_error_for(result: EnsureResult) -> MicrophoneAccessError:
+ return MicrophoneAccessError(result.user_detail or _NOT_GRANTED_MESSAGE, result=result)
+
+ async def _ensure_access(self, *, interactive: bool) -> None:
+ """The ONE permission ensure of an open; raises unless the mic is granted.
+
+ Runs before CoreAudio is touched, so a refused open never creates a
+ device. The service makes the native request only for an interactive
+ caller, publishes the episode itself and never raises.
+ """
+ if self._access_gate is not None:
+ result = _legacy_gate_result(self._legacy_gate_allows())
+ else:
+ result = await self._service_gate().ensure_async(
+ _MICROPHONE,
+ feature=self._permission_feature,
+ interactive=interactive,
+ wait_s=self._permission_wait_s if interactive else 0.0,
)
+ if not result.granted:
+ raise self._access_error_for(result)
+ # Off macOS the answer is NOT_REQUIRED: nothing to watch, no guard. The
+ # guard is for a real service grant only (an injected gate is a test seam).
+ os_granted = _state_value(result.outcome) == "granted"
+ self._watch_access = self._access_gate is not None or os_granted
+ self._silence_guard_armed = self._access_gate is None and os_granted
+ self._unreadable_ticks = 0
def _callback(self, indata, frames, time_info, status) -> None:
"""PortAudio callback — runs in the audio thread, NOT in the asyncio loop.
@@ -879,12 +981,29 @@ class MicrophoneCapture:
except asyncio.QueueFull:
return
+ def _track_silence(self, pcm: bytes, now: float) -> None:
+ """Remember since when the stream has carried only exact zeros.
+
+ Runs per frame on the event loop, so it must stay cheap: ``frombuffer``
+ is a view of the bytes already in hand (no copy) and ``any()`` stops at
+ the first non-zero sample. The watchdog tick reads the verdict.
+ """
+ if len(pcm) < 2 or len(pcm) % 2:
+ return
+ if np.frombuffer(pcm, dtype=np.int16).any():
+ self._zero_since = None
+ self._silence_reported = False
+ elif self._zero_since is None:
+ self._zero_since = now
+
def _safe_put(self, chunk: AudioChunk) -> None:
"""Runs in the event loop — safe put with drop-OLDEST on full."""
# Heartbeat update for the stall watchdog. Even if the queue is full,
# the stream is considered alive — we update the timestamp before the
# put; otherwise drops would corrupt the stall signal.
self._last_chunk_monotonic = time.monotonic()
+ if self._silence_guard_armed:
+ self._track_silence(chunk.pcm, self._last_chunk_monotonic)
try:
self._queue.put_nowait(chunk)
except asyncio.QueueFull:
@@ -908,14 +1027,21 @@ class MicrophoneCapture:
pass
self._drops += 1
- async def _try_open_stream(self) -> None:
+ async def _try_open_stream(self, *, interactive: bool | None = None) -> None:
"""Open the preferred mic, then recover through safe alternatives.
Extracted from ``__aenter__`` so the stall watchdog can reuse the same
logic. Automatic/name-based selection may fail over to another physical
input; an explicit numeric device remains pinned.
+
+ The permission is ensured ONCE here, before any device is opened
+ (``MicrophoneAccessError`` otherwise). ``interactive=None`` means the
+ constructor's choice; the watchdog restarts pass ``False`` because a
+ restart is never a user gesture.
"""
- self._require_microphone_access()
+ await self._ensure_access(
+ interactive=self._interactive if interactive is None else interactive
+ )
preferred_attempts: list[int | str | None] = [self._preferred_device]
try:
if isinstance(self._preferred_device, int):
@@ -959,7 +1085,6 @@ class MicrophoneCapture:
attempt_count = 0
for attempt, capture_rate, physical_fallback in _open_candidates():
attempt_count += 1
- self._require_microphone_access()
stream = None
try:
capture_blocksize = (
@@ -1088,6 +1213,10 @@ class MicrophoneCapture:
Logic: if no chunk has arrived in the callback for more than
_STALL_THRESHOLD_S, stop+close+open the stream. Consumers of
stream() only notice a brief audio gap.
+
+ The same tick is where the microphone grant is watched: one cheap
+ ``check`` per tick (never per frame), and a revoke ends the capture
+ with ``MicrophoneAccessError``.
"""
# Initial grace pulse: wait until the first chunk has safely arrived
# before starting the watchdog, otherwise it fires before the first frame.
@@ -1096,8 +1225,17 @@ class MicrophoneCapture:
await asyncio.sleep(self._WATCHDOG_TICK_S)
if self._closed:
return
+ if await self._access_revoked():
+ return
elapsed = time.monotonic() - self._last_chunk_monotonic
if elapsed <= self._STALL_THRESHOLD_S:
+ if (
+ self._silence_guard_armed
+ and not self._silence_reported
+ and self._zero_since is not None
+ and time.monotonic() - self._zero_since >= _SILENCE_REPORT_AFTER_S
+ ):
+ await self._report_digital_silence()
# The stream is delivering — keep the resolve cache fresh so a
# capture constructed moments after this one closes (the
# wake→session handover) skips the ~0.4s device enumeration.
@@ -1128,9 +1266,14 @@ class MicrophoneCapture:
# because this watchdog runs on the loop that also serves the
# desktop window.
await self._discard_stream_off_loop(old_stream)
+ self._zero_since = None
try:
- await self._try_open_stream()
+ await self._try_open_stream(interactive=False)
_log.info("Mic-Restart #{} succeeded.", self._restart_count)
+ except MicrophoneAccessError as exc:
+ # The grant is gone: no retry loop, the capture ends like a revoke.
+ self._end_revoked(exc)
+ return
except Exception as exc: # noqa: BLE001
_log.error(
"Mic-Restart #{} failed: {} — next attempt in 5s.",
@@ -1144,6 +1287,128 @@ class MicrophoneCapture:
# Reset the heartbeat — grace window for the first frame after reopen.
self._last_chunk_monotonic = time.monotonic()
+ def _end_revoked(self, error: MicrophoneAccessError) -> None:
+ """Mark the capture revoked and wake a reader parked in ``stream()``."""
+ self._revoked = True
+ self._access_error = error
+ self._wake_parked_reader()
+
+ async def _access_revoked(self) -> bool:
+ """One watchdog-tick permission check. ``True``: the capture was ended.
+
+ ``check`` is silent and cheap. A grant that is no longer there closes
+ the native stream, publishes the permission episode through the service
+ (``PermissionNeeded`` with the real reason, an episode that may toast when
+ a user started this capture) and makes ``stream()`` raise
+ ``MicrophoneAccessError`` carrying the ``EnsureResult``.
+ """
+ if not self._watch_access:
+ return False
+ if self._access_gate is not None:
+ if self._legacy_gate_allows():
+ return False
+ result = _legacy_gate_result(False)
+ else:
+ try:
+ result = await self._read_revoke_result()
+ except Exception: # noqa: BLE001 - an injected gate that raises must not end the watchdog
+ # The real service never raises, but a custom PermissionGate may.
+ # Treat the tick as "not revoked" so stall recovery and the next
+ # tick's check keep working; the revoke is caught on a later tick.
+ _log.debug("Mic permission watch tick failed; capture kept.", exc_info=True)
+ return False
+ if result is None:
+ return False
+ _log.warning("Mic access is no longer granted ({}); ending the capture.", result.reason)
+ # Release the device first: when a consumer learns of the revoke, the
+ # native stream (and the OS microphone indicator) is already gone.
+ stream, self._stream = self._stream, None
+ if stream is not None:
+ await self._discard_stream_off_loop(stream)
+ self._end_revoked(self._access_error_for(result))
+ return True
+
+ async def _read_revoke_result(self) -> Any | None:
+ """The service half of one watchdog tick: ``None`` while the grant stands.
+
+ ``check`` first (silent, cheap); only a lost grant goes on to ``ensure``,
+ whose ``EnsureResult`` describes the revoke. May raise when a custom gate
+ does: the caller contains that.
+ """
+ gate = self._service_gate()
+ state = _state_value(gate.check(_MICROPHONE))
+ if state in _GRANTED_STATES:
+ self._unreadable_ticks = 0
+ return None
+ if state == "unavailable":
+ # A failed native read is not a revoke: one such tick is forgiven
+ # so a transient error cannot kill a working dictation.
+ self._unreadable_ticks += 1
+ if self._unreadable_ticks < 2:
+ return None
+ # ensure() publishes the episode and re-reads the state. A denial
+ # makes no native request, so an interactive capture may use it to
+ # upgrade the episode to a user-origin card; every other state is
+ # published as background (a lost stream is never a reason to ask).
+ result = await gate.ensure_async(
+ _MICROPHONE,
+ feature=self._permission_feature,
+ interactive=self._interactive and state == "denied",
+ wait_s=0.0,
+ )
+ if result.granted:
+ self._unreadable_ticks = 0
+ return None
+ return result
+
+ async def _report_digital_silence(self) -> None:
+ """5 s of exact zeros while the OS says granted: re-check once, report once.
+
+ macOS feeds zeros to a denied or muted input instead of raising an error
+ (unverified on a real Mac), so a silent capture would otherwise be
+ recorded as if it were speech. The stream stays open: this is a notice,
+ not a verdict. A re-check that finds the grant gone is left to the next
+ tick's revoke path.
+ """
+ self._silence_reported = True
+ try:
+ gate = self._service_gate()
+ invalidate = getattr(gate, "invalidate", None)
+ if callable(invalidate):
+ invalidate(_MICROPHONE) # drop the cached GRANTED so the re-check is live
+ if _state_value(gate.check(_MICROPHONE)) not in _GRANTED_STATES:
+ return
+ except Exception: # noqa: BLE001 - a notice must never end the watchdog
+ _log.debug("Mic silence re-check failed; no notice published.", exc_info=True)
+ return
+ _log.warning(
+ "Mic delivered only digital silence for {:.0f}s while access reads as "
+ "granted (denied or muted input).",
+ _SILENCE_REPORT_AFTER_S,
+ )
+ try:
+ from jarvis.core.bus import get_default_bus # noqa: PLC0415 - only on this rare path
+
+ await get_default_bus().publish(
+ PermissionNeeded(
+ source_layer="audio.capture",
+ permissions=(_MICROPHONE,),
+ feature=self._permission_feature,
+ reason="denied",
+ phase="blocked",
+ # Background on purpose: the OS says granted, so this is more
+ # likely a muted or noise-gated input than a denial, and a
+ # an "Open System Settings" toast would be wrong. The notice has
+ # no service episode (so no close on the first audible frame):
+ # a closable "denied or muted" episode is a service API request.
+ origin="background",
+ can_open_settings=True,
+ detail=_SILENCE_DETAIL,
+ )
+ )
+ except Exception: # noqa: BLE001 - a notice must never break the capture
+ _log.debug("Mic silence notice could not be published.", exc_info=True)
+
def discard_native_stream(self) -> None:
"""Drop the native stream so the stall watchdog reopens it (BUG-102).
@@ -1275,33 +1540,32 @@ class MicrophoneCapture:
Important: the loop condition no longer depends on stream.active —
on silent stream death that flag lies and continues to report True.
The stall watchdog repairs the stream in the background; the consumer
- only sees a brief audio gap and continues reading.
+ only sees a brief audio gap and continues reading. When the watchdog
+ finds the microphone grant gone, the next read raises
+ ``MicrophoneAccessError`` (no per-frame permission probe happens here).
"""
while not self._closed:
- self._require_microphone_access()
- if self._access_gate is None:
- chunk = await self._queue.get()
- else:
- try:
- # ``asyncio.timeout``, not ``wait_for``: the latter can
- # swallow a consumer's cancellation on Python 3.11 when a
- # frame arrives in the same step (CPython gh-86296,
- # BUG-185), and this loop runs per frame.
- async with asyncio.timeout(self._ACCESS_RECHECK_S):
- chunk = await self._queue.get()
- except TimeoutError:
- # No audio frame is still a live interval: recheck TCC so a
- # revoke closes a stalled/silent stream without waiting for
- # PortAudio to produce another callback.
- continue
+ self._raise_if_revoked()
+ chunk = await self._queue.get()
if self._closed:
# Woken by ``__aexit__``: the device is gone and so is the
# reason for this consumer to exist. A reader parked here on an
# empty queue used to sit forever after close (BUG-185).
return
- self._require_microphone_access()
+ # Woken by the watchdog's revoke marker (or a frame that raced it).
+ self._raise_if_revoked()
yield chunk
+ def _raise_if_revoked(self) -> None:
+ error = self._access_error
+ if error is not None:
+ raise MicrophoneAccessError(str(error), result=error.result)
+
+ @property
+ def revoked(self) -> bool:
+ """``True`` once the microphone grant was lost while the capture was open."""
+ return self._revoked
+
@property
def dropped_frames(self) -> int:
"""Number of frames lost due to a full queue."""
diff --git a/jarvis/audio/ducking/__init__.py b/jarvis/audio/ducking/__init__.py
index f5ffee8e3a..24bc570f98 100644
--- a/jarvis/audio/ducking/__init__.py
+++ b/jarvis/audio/ducking/__init__.py
@@ -3,8 +3,9 @@
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.
+fallback; the Automation consent it needs is asked once, when the user switches
+the feature on while a player is open, and never during a voice session. A
+logged no-op elsewhere so the base headless install boots unaffected.
"""
from __future__ import annotations
diff --git a/jarvis/audio/ducking/controller.py b/jarvis/audio/ducking/controller.py
index 4419f74de5..159a43f91e 100644
--- a/jarvis/audio/ducking/controller.py
+++ b/jarvis/audio/ducking/controller.py
@@ -4,6 +4,10 @@ Subscribes ``VoiceSessionStarted`` (mute others) / ``VoiceSessionEnded``
(restore). The blocking backend work runs in ``asyncio.to_thread`` with
``CoInitialize`` so it never touches the event loop. Our own PID is excluded
from the mute sweep, which automatically protects Jarvis's own TTS voice.
+
+A session never asks the OS for anything: ``mute_others`` is non-interactive.
+The only asking path is :meth:`AudioDuckController.set_enabled` (the user turning
+the feature on), which runs the backend's ``prewarm`` off ``self._lock``.
"""
from __future__ import annotations
@@ -74,20 +78,30 @@ class AudioDuckController:
await self._restore_locked()
# ---- public live controls ------------------------------------------
- async def set_enabled(self, enabled: bool) -> None:
- """Live-apply the toggle. Turning OFF mid-session restores immediately."""
+ async def set_enabled(self, enabled: bool) -> Any:
+ """Live-apply the toggle. Turning OFF mid-session restores immediately.
+
+ Turning ON is the user's gesture, so it is the ONE place that may ask the
+ OS for a permission: the backend's ``prewarm`` (macOS: Automation consent
+ for each running player, through the permission service) runs here, on a
+ worker thread and NOT under ``self._lock``, so a session that starts while
+ a dialog is open is never held up by it. Returns the backend's permission
+ report (``DuckPermissionReport``), or ``None`` when the backend has none
+ (Windows, no backend) or the feature was switched off.
+ """
try:
self._cfg.ducking.enabled = bool(enabled)
except Exception: # noqa: BLE001
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).
+ return None
pre = getattr(self._ducker, "prewarm", None)
if callable(pre):
- await self._run(pre)
+ report = await self._run(pre)
+ # _run answers [] when the backend call failed (already logged).
+ return report if hasattr(report, "as_dict") else None
+ return None
async def restore(self) -> None:
"""Force-restore (live path: turning the toggle off)."""
@@ -134,7 +148,11 @@ class AudioDuckController:
log.info("ducking: restored %d session(s)", len(pids))
async def _run(self, fn: Any, *args: Any, **kwargs: Any) -> Any:
- """Run a blocking pycaw call off the loop, with COM init on the worker."""
+ """Run a blocking backend call off the loop, with COM init on the worker.
+
+ Never called with ``self._lock`` held around an ask: only the silent,
+ bounded ``mute_others`` / ``restore`` calls run under the lock.
+ """
def _call() -> Any:
initialized = False
diff --git a/jarvis/audio/ducking/factory.py b/jarvis/audio/ducking/factory.py
index 7591552bfc..6ff0cd152d 100644
--- a/jarvis/audio/ducking/factory.py
+++ b/jarvis/audio/ducking/factory.py
@@ -24,6 +24,9 @@ def _osascript_available() -> bool:
def make_audio_ducker(cfg: Any | None = None) -> AudioDucker:
"""Windows + pycaw → WindowsPycawDucker; macOS + osascript →
MacOSScriptDucker; otherwise a logged NullDucker.
+
+ The macOS ducker resolves the permission service itself (lazily, per call),
+ so nothing here asks the OS for anything.
"""
if sys.platform == "win32" and _pycaw_available():
from jarvis.audio.ducking.windows import WindowsPycawDucker
diff --git a/jarvis/audio/ducking/macos.py b/jarvis/audio/ducking/macos.py
index 8686f187bb..bd579ff9a1 100644
--- a/jarvis/audio/ducking/macos.py
+++ b/jarvis/audio/ducking/macos.py
@@ -12,9 +12,17 @@ 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.
+The Automation consent is owned by ``jarvis.platform.permission_service`` and
+asked ONLY from :meth:`MacOSScriptDucker.prewarm`, which runs when the user
+switches the feature on while a player is open. ``mute_others`` never asks: it
+scripts a player only when the service reads its Automation grant as GRANTED,
+and a player without the grant is skipped for the session (a running one is
+recorded through a background episode, status snapshot only). A player whose
+Apple Event is refused with ``-1743`` although the read said GRANTED is skipped
+too, and the service is told through ``report_failed_use`` (one background
+``needs_settings`` episode naming the player); the next send that lands tells it
+through ``report_use_ok`` and the episode ends. The player list is shared with
+the port so the scripts and the permission row can never disagree.
CRITICAL script shape: a bare ``tell application ...`` LAUNCHES the app, so
every script guards with ``if application id "..." is running`` INSIDE the
@@ -25,11 +33,16 @@ from __future__ import annotations
import logging
import subprocess
+import threading
from collections.abc import Callable
-from typing import Any
+from typing import TYPE_CHECKING, Any
+from jarvis.audio.ducking.protocol import DuckPermissionReport, PlayerPermission
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
-from jarvis.platform.permissions import AUTOMATION_TARGETS
+from jarvis.platform.permissions import AUTOMATION_TARGETS, PermissionId, PermissionState
+
+if TYPE_CHECKING:
+ from jarvis.core.protocols import PermissionGate
log = logging.getLogger("jarvis.audio.ducking")
@@ -41,11 +54,38 @@ _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.
+# A duck/restore script must never stall a voice session. It never carries an
+# Automation consent dialog either: mute_others scripts a player only after the
+# permission service read its grant as GRANTED, so there is nothing for a 3 s
+# kill to tear down (it used to kill the dialog before the user could click, and
+# every session asked again). The ask lives in prewarm(), through the service.
_SCRIPT_TIMEOUT_S = 3.0
-_CONSENT_TIMEOUT_S = 120.0
+
+# The permission-service feature name every ducking read and ask is filed under.
+_FEATURE = "audio_ducking"
+# How long mute_others waits for a silent Automation read before it skips the
+# player. The read is an in-process Apple Event that can hang for a running
+# player without a window (Apple forums thread 666528); it must never stall a
+# voice session nor the controller lock above it.
+_PROBE_TIMEOUT_S = 2.5
+# The budget of ONE ask inside prewarm(): the port's consent runner is killed after
+# 120 s, so a call that is still out after this long has hung. It is per player, not
+# per prewarm: a shared deadline let the second ask start with only the leftover (a
+# few seconds), time out, report "unavailable" and still leave its dialog on screen.
+_ASK_BUDGET_S = 130.0
+# The Automation request runs on the service's own daemon thread and ensure(wait_s=0)
+# answers PENDING at once, so prewarm() (a WORKER thread, never the loop or a lock)
+# passes wait_s and waits on the request thread's event. The wait ends a margin
+# BEFORE the budget above, so the service can answer "pending" itself and the budget
+# stays the backstop for a native call that hangs. The margin also covers reading the
+# answer after the consent runner is killed (120 s).
+_ASK_WAIT_MARGIN_S = 5.0
+
+
+def _ask_wait_s() -> float:
+ """How long ensure() may wait for one player's dialog: the budget minus a margin."""
+ budget = _ASK_BUDGET_S
+ return max(0.0, budget - min(_ASK_WAIT_MARGIN_S, budget * 0.1))
def _run_osascript(
@@ -62,10 +102,6 @@ def _run_osascript(
)
-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 (
@@ -89,15 +125,6 @@ def _restore_script(bundle_id: str, volume: int) -> str:
)
-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 _is_running_script(bundle_id: str) -> str:
"""Pure running-state query — never launches or scripts the app itself."""
return (
@@ -117,8 +144,60 @@ def _master_duck_script(target: int) -> str:
)
+def _refused_not_authorized(proc: Any) -> bool:
+ """Whether a script failed with the Automation denial ``-1743`` (documented)."""
+ if getattr(proc, "returncode", 0) == 0:
+ return False
+ return "-1743" in (getattr(proc, "stderr", "") or "")
+
+
+class _BoundedCall:
+ """Run ONE call at a time on a daemon thread and wait for it at most ``timeout_s``.
+
+ A native Apple Event can hang (see :data:`_PROBE_TIMEOUT_S`) and an Automation
+ ask blocks until its dialog is answered. The caller gets ``(False, None)`` after
+ the timeout and the call keeps its thread; while that thread lives no second one
+ starts, so a hung call cannot pile up threads. A late answer is discarded.
+ """
+
+ def __init__(self, name: str) -> None:
+ self._name = name
+ self._lock = threading.Lock()
+ self._thread: threading.Thread | None = None
+
+ def run(self, call: Callable[[], Any], timeout_s: float) -> tuple[bool, Any]:
+ box: dict[str, Any] = {}
+
+ def target() -> None:
+ try:
+ box["value"] = call()
+ except Exception: # noqa: BLE001 - the thread must not die loudly; the caller degrades
+ log.debug("The bounded %s call failed.", self._name, exc_info=True)
+ else:
+ box["ok"] = True
+
+ with self._lock:
+ if self._thread is not None and self._thread.is_alive():
+ log.debug("A bounded %s call is still out; not starting another.", self._name)
+ return False, None
+ thread = threading.Thread(target=target, name=f"ducking-{self._name}", daemon=True)
+ self._thread = thread
+ thread.start()
+ thread.join(max(0.0, timeout_s))
+ if thread.is_alive():
+ log.debug("The bounded %s call did not finish within %.1f s.", self._name, timeout_s)
+ return False, None
+ return bool(box.get("ok")), box.get("value")
+
+
class MacOSScriptDucker:
- """Tiered AppleScript ducker: known players first, opt-in master fallback."""
+ """Tiered AppleScript ducker: known players first, opt-in master fallback.
+
+ Automation (Apple Events to Music/Spotify) is the only permission involved.
+ ``access_gate`` is the permission layer (``PermissionGate``); the default
+ resolves the process-wide service on every call, so a test that installs its
+ own port or injects a fake gate is honoured.
+ """
def __init__(
self,
@@ -126,15 +205,28 @@ 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,
+ access_gate: PermissionGate | 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._access_gate = access_gate
self._saved: dict[int, int] = {} # token -> previous volume
+ # One bounded slot per player for the silent reads, one for the ask, so a
+ # hung read of one player never blocks another player or the ask.
+ self._reads = {
+ bundle_id: _BoundedCall(f"read-{name}") for name, bundle_id in _PLAYERS.values()
+ }
+ self._ask_slot = _BoundedCall("ask")
+ # Players whose volume command was refused with -1743 although the service
+ # read their grant as GRANTED (the grant may belong to another app: the
+ # attribution of a child osascript is UNVERIFIED), and whose refusal has not
+ # been followed by a send that landed. mute_others() reports the refusal to
+ # the service (report_failed_use) and, on the next landed send, the success
+ # (report_use_ok, only for a player in this set, so a healthy session never
+ # calls the service); prewarm() reports such a player as needs_settings
+ # instead of "granted", the same thing the status snapshot says.
+ self._refused_after_grant: set[str] = set()
@classmethod
def from_config(cls, cfg: Any | None) -> MacOSScriptDucker:
@@ -155,6 +247,17 @@ class MacOSScriptDucker:
``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).
+
+ NON-INTERACTIVE: a player is scripted only when the permission service
+ reads its Automation grant as GRANTED. Scripting a player macOS has not
+ been asked about would raise the consent dialog in the middle of a
+ dictation, so a player without the grant is skipped for this session and
+ nothing is ever asked from here (see :meth:`prewarm`). A player that
+ refuses the Apple Event with ``-1743`` although the read said GRANTED is
+ skipped too and reported to the service (``report_failed_use``, one
+ background episode); the next send that lands reports the success
+ (``report_use_ok``). Every service call from here is bounded, because the
+ controller holds its lock around this method. Never launches a player.
"""
del own_pid # per-app player volumes never touch our own process
skip = self._normalized_never(never)
@@ -171,10 +274,16 @@ class MacOSScriptDucker:
skipped.append((name, bundle_id))
continue
try:
+ if not self._may_script(name, bundle_id):
+ continue # no live grant: skipped, never asked from a session
proc = self._run(_duck_script(bundle_id, self._duck))
+ if _refused_not_authorized(proc):
+ self._note_refused_after_grant(name, bundle_id)
+ continue
prev = self._parse_volume(proc, name)
if prev is None:
continue # not running, or the script failed → not handled
+ self._note_send_landed(name, bundle_id)
player_running = True
if prev > self._duck:
self._saved[token] = prev
@@ -231,7 +340,14 @@ class MacOSScriptDucker:
return ducked
def restore(self, pids: list[int]) -> None:
- """Restore exactly the given tokens. Idempotent; unknown token = no-op."""
+ """Restore exactly the given tokens. Idempotent; unknown token = no-op.
+
+ Deliberately NOT permission-gated: it only undoes a duck that was made under a
+ live grant, a grant revoked since fails with ``-1743`` (kept for re-adoption
+ below, and macOS shows no dialog for a decision on file), and a skipped
+ restore would leave the user's music silent for good. It also runs on the
+ shutdown path, which must never wait for an Automation read.
+ """
for token in pids:
prev = self._saved.get(token)
if prev is None:
@@ -258,15 +374,235 @@ class MacOSScriptDucker:
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.
+ def prewarm(self) -> DuckPermissionReport:
+ """Ask for Automation, once, for each player that is running. THE asking path.
+
+ Called when the user switches "Mute music while dictating" on: the switch
+ is the gesture. Run it from a WORKER thread (it blocks until the macOS
+ dialog is answered, up to 120 s per player) and never under a lock. The
+ ask goes through the permission service and its killable consent runner;
+ a player that is not running is neither launched nor asked (macOS only
+ shows the dialog for a running player), and a decision already on file is
+ never asked again. The returned report says, per player that ran, what
+ the OS answered; the request's return value is never taken as a grant.
+ "Running" is the pure ``is running`` query, which sends no Apple event to the
+ player (UNVERIFIED on a real Mac).
"""
+ players: list[PlayerPermission] = []
+ not_running: list[str] = []
for _token, (name, bundle_id) in _PLAYERS.items():
+ if not self._any_running([(name, bundle_id)]):
+ not_running.append(name)
+ continue
+ players.append(self._ask_player(name, bundle_id))
+ note = ""
+ if not players:
+ names = " or ".join(name for name, _bundle_id in _PLAYERS.values())
+ note = (
+ f"Automation access is checked while the player is running. {names} is not "
+ "open, so nothing was asked. Switch this on again while a player is open."
+ )
+ return DuckPermissionReport(
+ players=tuple(players), not_running=tuple(not_running), note=note
+ )
+
+ # ---- permission ---------------------------------------------------------
+ def _gate(self) -> PermissionGate:
+ """The permission layer, resolved per call so a test's port or gate applies."""
+ if self._access_gate is not None:
+ return self._access_gate
+ from jarvis.platform.permission_service import get_permission_service
+
+ return get_permission_service()
+
+ def _may_script(self, name: str, bundle_id: str) -> bool:
+ """``True`` only for a live GRANTED Automation read. Silent: never asks.
+
+ A player without the grant is skipped. When it is running, the miss is
+ recorded as a ``background`` episode (status snapshot only, never a
+ toast) so the person can find out why the music was not ducked.
+ """
+ state = self._read_state(name, bundle_id)
+ if state is PermissionState.GRANTED:
+ return True
+ if state is PermissionState.NOT_REQUIRED:
+ return False # not installed (or not macOS): nothing to duck
+ log.debug("ducking: skipping %s (Automation read %s)", name, state.value)
+ if self._any_running([(name, bundle_id)]):
+ self._record_background_episode(name, bundle_id)
+ return False
+
+ def _read_state(self, name: str, bundle_id: str) -> PermissionState:
+ """One bounded, silent Automation read of ONE player; UNAVAILABLE on no answer."""
+ finished, state = self._reads[bundle_id].run(
+ lambda: self._gate().check(PermissionId.AUTOMATION, target=bundle_id),
+ _PROBE_TIMEOUT_S,
+ )
+ if finished:
try:
- self._consent_run(_prewarm_script(bundle_id))
- except Exception: # noqa: BLE001
- log.debug("ducking prewarm skip (%s)", name, exc_info=True)
+ return PermissionState(state)
+ except ValueError:
+ log.debug("ducking: the Automation read for %s was not a state", name)
+ else:
+ log.debug("ducking: the Automation read for %s gave no answer", name)
+ return PermissionState.UNAVAILABLE
+
+ def _record_background_episode(self, name: str, bundle_id: str) -> None:
+ """Open (or join) the ``background`` episode of a running, ungranted player.
+
+ ``interactive=False``: the service never makes a native request for it.
+ """
+ finished, _result = self._reads[bundle_id].run(
+ lambda: self._gate().ensure(
+ PermissionId.AUTOMATION,
+ feature=_FEATURE,
+ interactive=False,
+ target=bundle_id,
+ ),
+ _PROBE_TIMEOUT_S,
+ )
+ if not finished:
+ log.debug("ducking: the background episode for %s was not recorded", name)
+
+ def _note_refused_after_grant(self, name: str, bundle_id: str) -> None:
+ """The player refused a volume command (-1743) although its grant read GRANTED.
+
+ The grant may belong to another app (the attribution of a child
+ ``osascript`` is UNVERIFIED) or it was just revoked. The player is
+ skipped for this session and the permission cache is dropped so the next
+ read is live. The service is told through ``report_failed_use``: ONE
+ ``background`` ``needs_settings`` episode naming the player (status snapshot
+ only, never a toast), and no native request is made
+ because of it. A live state that no longer reads granted is described by
+ the service itself (its real reason). A gate without the call (a scripted
+ stub) gets the older, weaker path: a non-interactive ensure, which opens an
+ episode only when the live state is no longer granted. prewarm() keeps
+ reporting such a player as ``needs_settings`` until a send lands again.
+ """
+ log.info(
+ "ducking: %s refused the volume command although Automation read as granted "
+ "(-1743); skipping it",
+ name,
+ )
+ self._refused_after_grant.add(bundle_id)
+ invalidate = getattr(self._gate(), "invalidate", None)
+ if callable(invalidate):
+ invalidate(PermissionId.AUTOMATION)
+ report = getattr(self._gate(), "report_failed_use", None)
+ if not callable(report):
+ self._record_background_episode(name, bundle_id)
+ return
+ self._tell_service(
+ name,
+ bundle_id,
+ "report_failed_use",
+ lambda: report(
+ PermissionId.AUTOMATION,
+ feature=_FEATURE,
+ target=bundle_id,
+ reason="needs_settings",
+ origin="background",
+ ),
+ )
+
+ def _note_send_landed(self, name: str, bundle_id: str) -> None:
+ """A volume command to the player landed: a refusal reported earlier is over.
+
+ Only a player that was reported as refused costs a service call, so a
+ healthy session never touches the service here. The memory is dropped
+ whether or not the call finishes (the send did land; prewarm() must not keep
+ calling the player blocked), and a gate without ``report_use_ok`` is simply
+ not told (the episode then ends through its own ten minute TTL).
+ """
+ if bundle_id not in self._refused_after_grant:
+ return
+ self._refused_after_grant.discard(bundle_id)
+ report = getattr(self._gate(), "report_use_ok", None)
+ if not callable(report):
+ return
+ self._tell_service(
+ name,
+ bundle_id,
+ "report_use_ok",
+ lambda: report(PermissionId.AUTOMATION, feature=_FEATURE, target=bundle_id),
+ )
+
+ def _tell_service(self, name: str, bundle_id: str, what: str, call: Callable[[], Any]) -> None:
+ """Run ONE service report on the player's bounded slot, never past the probe timeout.
+
+ ``mute_others`` runs under the controller's lock, so a report is as bounded
+ as a read: a service call that hangs costs at most :data:`_PROBE_TIMEOUT_S`
+ and the session goes on without it. Nothing here asks the OS anything.
+ """
+ finished, _result = self._reads[bundle_id].run(call, _PROBE_TIMEOUT_S)
+ if not finished:
+ log.debug("ducking: %s for %s was not delivered to the permission service", what, name)
+
+ def _ask_player(self, name: str, bundle_id: str) -> PlayerPermission:
+ """Ask the service about ONE running player (interactive, off every lock).
+
+ Every ask gets the full :data:`_ASK_BUDGET_S`, so a consent run (killed by
+ the port after 120 s) is never cut off by the time an earlier player used.
+ The service runs the consent on its own thread and answers PENDING at once
+ for ``wait_s=0``, so this worker thread passes :func:`_ask_wait_s` and waits
+ for the answer there; a dialog still open at the end of the wait is reported
+ as ``pending`` (the answer then arrives through ``PermissionResolved``).
+ """
+ finished, result = self._ask_slot.run(
+ lambda: self._gate().ensure(
+ PermissionId.AUTOMATION,
+ feature=_FEATURE,
+ interactive=True,
+ wait_s=_ask_wait_s(),
+ target=bundle_id,
+ ),
+ _ASK_BUDGET_S,
+ )
+ if not finished or result is None:
+ # A hung native call: nothing was decided, so it is never "granted".
+ log.debug("ducking: the Automation ask for %s did not finish", name)
+ return self._player_answer(name, bundle_id, "unavailable")
+ if result.granted and bundle_id in self._refused_after_grant:
+ if result.asked:
+ # A fresh ask just went through the real sender and was allowed: that
+ # is a send that landed, so the refusal reported earlier is over.
+ self._note_send_landed(name, bundle_id)
+ else:
+ return self._player_answer(name, bundle_id, "needs_settings", refused_use=True)
+ return PlayerPermission(
+ player=name,
+ target=bundle_id,
+ outcome=str(result.outcome.value),
+ reason=result.reason,
+ can_open_settings=result.can_open_settings,
+ asked=result.asked,
+ outside_installed_app=result.outside_installed_app,
+ detail=result.user_detail,
+ )
+
+ @staticmethod
+ def _player_answer(
+ name: str, bundle_id: str, reason: str, *, refused_use: bool = False
+ ) -> PlayerPermission:
+ """An answer the ducker decided itself (not the service): fixed-template sentence.
+
+ ``refused_use`` is the sentence of a player whose volume command was refused
+ although its access reads as allowed (the same one the service's episode carries).
+ """
+ from jarvis.platform.permission_service import user_detail_for
+
+ return PlayerPermission(
+ player=name,
+ target=bundle_id,
+ outcome=reason,
+ reason=reason,
+ can_open_settings=reason == "needs_settings",
+ asked=False,
+ outside_installed_app=False,
+ detail=user_detail_for(
+ PermissionId.AUTOMATION, reason, target=bundle_id, refused_use=refused_use
+ ),
+ )
# ---- internals ---------------------------------------------------------
def _any_running(self, players: list[tuple[str, str]]) -> bool:
diff --git a/jarvis/audio/ducking/protocol.py b/jarvis/audio/ducking/protocol.py
index b779739864..9c4a117858 100644
--- a/jarvis/audio/ducking/protocol.py
+++ b/jarvis/audio/ducking/protocol.py
@@ -1,10 +1,18 @@
"""The audio-ducker backend contract."""
from __future__ import annotations
-from typing import Protocol
+from dataclasses import dataclass
+from typing import Any, Protocol
class AudioDucker(Protocol):
+ """A backend that lowers other apps' audio for the length of a voice session.
+
+ A backend MAY also offer ``prewarm() -> DuckPermissionReport``: the one place
+ that asks the OS for a permission, run when the user switches the feature on.
+ ``mute_others`` and ``restore`` never ask (macOS: Automation).
+ """
+
def mute_others(self, *, own_pid: int, never: frozenset[str]) -> list[int]:
"""Mute every other app's audio session. Returns the PIDs muted."""
...
@@ -12,3 +20,59 @@ class AudioDucker(Protocol):
def restore(self, pids: list[int]) -> None:
"""Unmute exactly the given PIDs."""
...
+
+
+@dataclass(frozen=True, slots=True)
+class PlayerPermission:
+ """The permission answer for ONE media player, as a route or a status snapshot shows it.
+
+ ``outcome`` and ``reason`` carry the ``PermissionOutcome`` / ``PermissionNeeded``
+ vocabulary of ``jarvis.platform.permission_service`` verbatim; ``detail`` is its
+ fixed-template sentence (never exception text, a path or a window title).
+ """
+
+ player: str # display name, e.g. "Music"
+ target: str # bundle id, e.g. "com.apple.Music"
+ outcome: str
+ reason: str
+ can_open_settings: bool
+ asked: bool
+ outside_installed_app: bool
+ detail: str
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "player": self.player,
+ "target": self.target,
+ "outcome": self.outcome,
+ "reason": self.reason,
+ "can_open_settings": self.can_open_settings,
+ "asked": self.asked,
+ "outside_installed_app": self.outside_installed_app,
+ "detail": self.detail,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class DuckPermissionReport:
+ """What switching "Mute music while dictating" on found out about permissions.
+
+ Automation is per player and macOS only answers for a player that is RUNNING,
+ so ``players`` holds only the players that were running (and therefore checked
+ or asked). ``not_running`` names the rest: nothing was asked for them. ``note``
+ is a full English sentence, set only when no player could be checked at all.
+ """
+
+ players: tuple[PlayerPermission, ...] = ()
+ not_running: tuple[str, ...] = ()
+ note: str = ""
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "feature": "audio_ducking",
+ "checked": bool(self.players),
+ "asked": any(player.asked for player in self.players),
+ "note": self.note,
+ "not_running": list(self.not_running),
+ "players": [player.as_dict() for player in self.players],
+ }
diff --git a/jarvis/cli_ctl/command_index.py b/jarvis/cli_ctl/command_index.py
index a8ddd007fb..b9d3212598 100644
--- a/jarvis/cli_ctl/command_index.py
+++ b/jarvis/cli_ctl/command_index.py
@@ -174,7 +174,7 @@ COMMAND_INDEX: dict[str, tuple[str, ...]] = {
"import-claude-desktop",
"delete <name>",
),
- "permissions": ("status", "request", "open-settings"),
+ "permissions": ("status", "request", "open-settings", "reset"),
"socials": ("list", "add", "edit", "delete"),
"telephony": ("status", "config", "outbound"),
}
diff --git a/jarvis/cli_ctl/commands/permissions.py b/jarvis/cli_ctl/commands/permissions.py
index 47d796e301..2ed82b26ab 100644
--- a/jarvis/cli_ctl/commands/permissions.py
+++ b/jarvis/cli_ctl/commands/permissions.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import importlib
+import plistlib
import subprocess
import time
from pathlib import Path
@@ -10,10 +11,10 @@ from typing import Annotated, NoReturn
import typer
-from jarvis.cli_ctl import invoke, options, render
+from jarvis.cli_ctl import invoke, options, render, safety
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
from jarvis.platform import detect_platform
-from jarvis.platform.permissions import EXPECTED_BUNDLE_ID, PermissionId
+from jarvis.platform.permissions import ACCEPTED_BUNDLE_IDS, PermissionId, tcc_reset_service
app = typer.Typer(
no_args_is_help=True,
@@ -22,9 +23,9 @@ app = typer.Typer(
def _installed_macos_app() -> Path:
- from jarvis.setup.macos_app_bundle import macos_app_bundle_path
+ from jarvis.setup.macos_app_bundle import installed_macos_app_bundle_path
- return macos_app_bundle_path()
+ return installed_macos_app_bundle_path()
def _activation_error(message: str) -> NoReturn:
@@ -39,8 +40,10 @@ def _activate_macos_app_for_tcc() -> None:
bundle = _installed_macos_app()
if not bundle.is_dir():
_activation_error(
- "The installed Personal Jarvis app was not found. Run the standard "
- "installer before requesting macOS permissions."
+ "The installed Personal Jarvis app was not found, so nothing was "
+ "requested: macOS permissions are only requested for the installed app, "
+ "never for the terminal that runs this command. Run the standard "
+ "installer, or allow the permission in System Settings yourself."
)
try:
completed = subprocess.run(
@@ -63,7 +66,7 @@ def _activate_macos_app_for_tcc() -> None:
while time.monotonic() < deadline:
frontmost = workspace.frontmostApplication()
raw_id = frontmost.bundleIdentifier() if frontmost is not None else None
- if raw_id and str(raw_id) == EXPECTED_BUNDLE_ID:
+ if raw_id and str(raw_id) in ACCEPTED_BUNDLE_IDS:
return
time.sleep(0.05)
except Exception as exc: # noqa: BLE001 - native verification fails closed
@@ -78,9 +81,24 @@ def _activate_macos_app_for_tcc() -> None:
@app.command()
-def status() -> None:
- """Show permission and feature readiness without caching native state."""
- invoke.run("GET", "/api/permissions/status")
+def status(
+ include_automation: Annotated[
+ bool,
+ typer.Option(
+ "--include-automation",
+ help=(
+ "Also read the Automation row (checks a running Music or Spotify, "
+ "without asking)."
+ ),
+ ),
+ ] = False,
+) -> None:
+ """Show each macOS privacy permission and what is waiting on one. Never prompts."""
+ invoke.run(
+ "GET",
+ "/api/permissions/status",
+ params={"include": "automation"} if include_automation else None,
+ )
@app.command()
@@ -92,13 +110,19 @@ def request(
yes: bool = options.yes_opt(),
dry_run: bool = options.dry_opt(),
) -> None:
- """Show the native macOS prompt for one permission."""
+ """Ask macOS for one permission through the same service the app uses.
+
+ Only the installed app is asked for: confirming a grant for the app that
+ started Jarvis (a terminal, an IDE) needs the Jarvis window, so there is no
+ flag for it here and nothing is requested without the installed bundle.
+ """
invoke.run(
"POST",
f"/api/permissions/{permission_id.value}/request",
assume_yes=yes,
dry_run=dry_run,
dangerous=True,
+ # The installed app is the only grantee this command asks for.
before_request=_activate_macos_app_for_tcc,
)
@@ -123,4 +147,142 @@ def open_settings(
)
+# The system tool that forgets one app's answer for one privacy service. A fixed
+# absolute path: nothing from PATH may stand in for it.
+_TCCUTIL = "/usr/bin/tccutil"
+_TCCUTIL_TIMEOUT_S = 30
+
+
+def _installed_bundle_id() -> str:
+ """The bundle id of the installed app (managed or downloaded), or exit with a reason.
+
+ Read from the app's own ``Info.plist`` (never from the process that runs this
+ command, which is a terminal): the managed bundle and the downloaded .dmg app
+ carry different ids and therefore keep different privacy records.
+ """
+ bundle = _installed_macos_app()
+ info_path = bundle / "Contents" / "Info.plist"
+ if not bundle.is_dir() or not info_path.is_file():
+ _activation_error(
+ "The installed Personal Jarvis app was not found, so nothing was reset. "
+ "Pass --bundle-id to name the app, or run `tccutil reset <service> <bundle id>` "
+ "yourself (see docs/product/privacy-safety-and-support/troubleshooting.md)."
+ )
+ try:
+ with info_path.open("rb") as stream:
+ raw_id = plistlib.load(stream).get("CFBundleIdentifier")
+ except (OSError, ValueError, plistlib.InvalidFileException) as exc:
+ _activation_error(
+ f"The installed app's Info.plist could not be read ({type(exc).__name__}), "
+ "so nothing was reset. Pass --bundle-id."
+ )
+ if not isinstance(raw_id, str) or raw_id not in ACCEPTED_BUNDLE_IDS:
+ _activation_error(
+ "The installed app's bundle id is not one of Personal Jarvis's "
+ f"({', '.join(ACCEPTED_BUNDLE_IDS)}), so nothing was reset. Pass --bundle-id."
+ )
+ return raw_id
+
+
+def _run_tccutil(argv: list[str]) -> subprocess.CompletedProcess[str]:
+ """Run ``tccutil`` (the one seam tests replace); UTF-8, no console window (AP-1)."""
+ return subprocess.run( # noqa: S603 - fixed argv, no shell
+ argv,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=_TCCUTIL_TIMEOUT_S,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+
+
+def reset(
+ permission_id: Annotated[
+ PermissionId,
+ typer.Argument(help="Permission whose macOS answer should be forgotten."),
+ ],
+ bundle_id: Annotated[
+ str | None,
+ typer.Option(
+ "--bundle-id",
+ help=(
+ "App to reset: ai.personaljarvis.desktop (the downloaded app) or "
+ "com.personal-jarvis.desktop (the managed app). Default: the installed app; "
+ "name it when both are installed."
+ ),
+ ),
+ ] = None,
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Forget what macOS recorded for Personal Jarvis, so it asks again on next use (macOS only).
+
+ Runs `/usr/bin/tccutil reset <service> <bundle id>` on this Mac. This is the
+ way out of a stuck "denied" answer, since macOS never asks twice by itself
+ and Personal Jarvis has no Privacy page. It only touches this app's own
+ record for one service and never another app's. It does not use the running
+ app (the app's own reset route refuses scripts on purpose), so it works with
+ Jarvis closed; quit and reopen the app afterwards, then use the feature.
+ """
+ from jarvis.cli_ctl.__main__ import as_json
+
+ if detect_platform() != "darwin":
+ render.error(
+ "permissions reset only works on macOS: other systems have no per-app "
+ "privacy record to reset."
+ )
+ raise typer.Exit(code=1)
+ service = tcc_reset_service(permission_id)
+ if service is None:
+ render.error(f"{permission_id.value} has no macOS privacy record to reset.")
+ raise typer.Exit(code=1)
+ if bundle_id is not None and bundle_id not in ACCEPTED_BUNDLE_IDS:
+ render.error(
+ f"--bundle-id must be one of: {', '.join(ACCEPTED_BUNDLE_IDS)} "
+ "(this command only resets Personal Jarvis's own record)."
+ )
+ raise typer.Exit(code=2)
+ target = bundle_id if bundle_id is not None else _installed_bundle_id()
+ argv = [_TCCUTIL, "reset", service, target]
+ plan = {
+ "permission_id": permission_id.value,
+ "service": service,
+ "bundle_id": target,
+ "argv": argv,
+ }
+ if dry_run:
+ render.emit({"dry_run": True, **plan}, as_json=as_json())
+ return
+ safety.require_yes_for_local_action(
+ f"Resetting the {permission_id.value} permission ({' '.join(argv)})", assume_yes=yes
+ )
+ try:
+ completed = _run_tccutil(argv)
+ except (OSError, subprocess.SubprocessError) as exc:
+ render.error(f"tccutil could not run ({type(exc).__name__}).")
+ raise typer.Exit(code=1) from exc
+ if completed.returncode != 0:
+ detail = (completed.stderr or completed.stdout or "").strip()[-200:]
+ render.error(
+ f"tccutil exited with status {completed.returncode}"
+ + (f": {detail}" if detail else ".")
+ )
+ raise typer.Exit(code=1)
+ render.emit(
+ {
+ "ok": True,
+ "performed": True,
+ **plan,
+ "message": (
+ f"The {permission_id.value} record of {target} was reset. Quit and reopen "
+ "Personal Jarvis, then use the feature: macOS asks again."
+ ),
+ },
+ as_json=as_json(),
+ )
+
+
__all__ = ["app"]
diff --git a/jarvis/cli_ctl/safety.py b/jarvis/cli_ctl/safety.py
index 87e2d37da0..1a8f1f6852 100644
--- a/jarvis/cli_ctl/safety.py
+++ b/jarvis/cli_ctl/safety.py
@@ -73,6 +73,23 @@ def _assume_yes_env() -> bool:
return os.environ.get("JARVIS_CLI_ASSUME_YES", "").strip().lower() in _TRUE
+def require_yes_for_local_action(description: str, *, assume_yes: bool) -> None:
+ """Fail closed unless ``--yes`` (or ``JARVIS_CLI_ASSUME_YES``) authorizes a local action.
+
+ For a curated command that changes this machine directly instead of sending a
+ request (``permissions reset`` runs ``tccutil``): the same rule as a
+ destructive request, so an agent that follows ``--help`` meets the same gate.
+ """
+ if assume_yes or _assume_yes_env():
+ return
+ render.error(
+ f"{description} changes this machine directly; re-run with --yes "
+ "(or set JARVIS_CLI_ASSUME_YES=1) to authorize it, or --dry-run to "
+ "preview exactly what would run."
+ )
+ raise typer.Exit(code=1)
+
+
def _print_preview(
method: str, path: str, body: object, auth_attached: bool, *, as_json: bool
) -> None:
diff --git a/jarvis/core/branding.py b/jarvis/core/branding.py
index 2ddcacaa4b..c4bb75eca1 100644
--- a/jarvis/core/branding.py
+++ b/jarvis/core/branding.py
@@ -42,6 +42,11 @@ MACOS_APP_NAME = PRODUCT_NAME
MACOS_APP_DIR_NAME = f"{MACOS_APP_NAME}.app"
MACOS_EXECUTABLE_NAME = PRODUCT_COMPACT_NAME
MACOS_BUNDLE_ID = f"com.{PRODUCT_SLUG}.desktop"
+# The downloadable .dmg (PyInstaller, ``jarvis.spec``) is a second, equally
+# legitimate installed app: its own bundle id and therefore its own macOS
+# privacy grants. ``jarvis.spec`` cannot import this module, so a parity test
+# (``tests/unit/setup/test_macos_dmg_identity.py``) pins its literal to this.
+MACOS_DMG_BUNDLE_ID = f"ai.{PRODUCT_COMPACT_NAME.lower()}.desktop"
MACOS_AUTOSTART_LABEL = f"com.{PRODUCT_SLUG}.autostart"
# Common name of the per-user self-signed code-signing certificate the
# installer creates so the app bundle keeps one TCC identity across rebuilds.
@@ -94,6 +99,7 @@ __all__ = [
"MACOS_APP_NAME",
"MACOS_AUTOSTART_LABEL",
"MACOS_BUNDLE_ID",
+ "MACOS_DMG_BUNDLE_ID",
"MACOS_EXECUTABLE_NAME",
"MACOS_SIGNING_IDENTITY_LABEL",
"MANAGED_INSTALL_MARKER",
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index dc78c824cf..69bb035dd8 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -5169,9 +5169,10 @@ _PLATFORM_KEYRING_BACKEND: Any | None = None
# The credential slot whose OS-keyring read failed most recently. On macOS a
# user who clicks "Deny" on the Keychain prompt lands exactly here: the read
# raises, the process degrades to the file backend, and only a fresh read of a
-# real existing item makes macOS show the prompt again. The permissions UI
-# replays this slot on a user-initiated retry (a probe on a brand-new item
-# would silently succeed without ever re-prompting).
+# real existing item makes macOS show the prompt again. The credential_store
+# permission request (``jarvis permissions request credential_store``) replays this
+# slot on a user-initiated retry (a probe on a brand-new item would silently
+# succeed without ever re-prompting).
_LAST_KEYRING_FAILED_SLOT: str | None = None
_SECRET_REVISION_LOCK = threading.Lock()
_SECRET_REVISIONS: dict[str, int] = {}
@@ -5516,7 +5517,7 @@ def credential_store_backend() -> str:
Credential Manager / Secret Service) serves reads and writes. ``file``
means this process degraded to the local 0600 JSON fallback — on macOS
that is the observable state after the user declined the Keychain prompt.
- The desktop permissions UI maps this onto its Keychain row.
+ The permission snapshot maps this onto its Keychain row.
"""
_ensure_keyring_backend()
try:
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index cf7dad15c5..e25af555fa 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -310,7 +310,11 @@ class DictationCompleted(Event):
#:
#: ``microphone_unavailable``
#: The local capture gate is closed — the desktop app is not visible, or
-#: microphone permission has not been granted.
+#: microphone permission has not been granted. When the cause is the
+#: permission, a ``PermissionNeeded`` event for the microphone is published
+#: alongside this refusal; a UI that can render the permission episode
+#: should prefer it for its one toast (it carries the system dialog phase and
+#: the route to System Settings) and keep this refusal for the recording pill.
#: ``no_stt``
#: No speech-to-text provider is wired, so nothing could transcribe.
#: ``already_running``
@@ -405,12 +409,144 @@ class DictationRefused(Event):
``reason`` is a stable token from ``DICTATION_REFUSAL_REASONS``; ``detail``
is a complete, user-facing English sentence, matching the contract of
``DictationCompleted.detail``.
+
+ The ``microphone_unavailable`` case ALSO publishes ``PermissionNeeded``
+ (see below). This event stays the signal for the key that did nothing; the
+ permission episode is what a UI should prefer for the toast that explains
+ the permission and offers the way back.
"""
reason: str = ""
detail: str = ""
+# ----------------------------------------------------------------------
+# Permissions (just-in-time)
+# ----------------------------------------------------------------------
+
+#: Every product feature that can ask for an OS permission, in the vocabulary a
+#: ``PermissionNeeded`` / ``PermissionResolved`` event carries. Declared ONCE
+#: here because the value crosses the permission service, the bus, the REST/WS
+#: surface and the i18n copy keyed per (feature, reason) — the exact shape of
+#: drift AP-4 / BUG-008 exists for. The TypeScript twin is
+#: ``frontend/src/lib/permissionEvents.ts``; a pytest regex read pins them.
+PERMISSION_FEATURES: Final[tuple[str, ...]] = (
+ "voice",
+ "dictation",
+ "wake_word",
+ "computer_use",
+ "screen_context",
+ "appshot",
+ "window_control",
+ "dictation_insert",
+ "global_shortcuts",
+ "audio_ducking",
+ "browser_voice",
+)
+
+#: Why a feature is waiting on a permission.
+#:
+#: ``not_determined``
+#: The OS has not been asked yet.
+#: ``denied``
+#: The user answered no, or revoked the grant later. The OS will not ask
+#: again by itself.
+#: ``restricted``
+#: A profile or parental control forbids the permission. Explanation only:
+#: the user cannot change it from the app's settings pane.
+#: ``needs_settings``
+#: The OS dialog (if any) can only point at System Settings; the user has
+#: to flip the switch there.
+#: ``restart_hint``
+#: The grant may only take effect after the app is quit and reopened. A hint
+#: after a real failed attempt, never an automatic restart.
+#: ``unavailable``
+#: The permission cannot be asked for here (no GUI session, a framework or
+#: usage string is missing).
+PERMISSION_NEEDED_REASONS: Final[tuple[str, ...]] = (
+ "not_determined",
+ "denied",
+ "restricted",
+ "needs_settings",
+ "restart_hint",
+ "unavailable",
+)
+
+#: Where an episode is in front of the user.
+#:
+#: ``os_dialog``
+#: macOS is asking right now; the app shows nothing of its own.
+#: ``blocked``
+#: The user has to act (Settings, a restart) before the feature can work.
+PERMISSION_NEEDED_PHASES: Final[tuple[str, ...]] = ("os_dialog", "blocked")
+
+#: What caused the episode.
+#:
+#: ``user``
+#: A gesture caused it, so the app may show its one toast.
+#: ``background``
+#: A background consumer hit it; the app shows nothing (the one exception is
+#: the always-listening wake word the user switched on).
+PERMISSION_NEEDED_ORIGINS: Final[tuple[str, ...]] = ("user", "background")
+
+
+@dataclass(frozen=True, slots=True)
+class PermissionNeeded(Event):
+ """A feature is waiting on an OS permission the user has to settle.
+
+ One coalesced episode per (permission family, feature): ``permissions``
+ lists every ``PermissionId`` value the episode needs (``event_posting`` is
+ folded into ``accessibility``). Published on a state change, never on a
+ repeated silent check, so a surface can treat each event as an edge.
+
+ ``feature`` comes from ``PERMISSION_FEATURES``, ``reason`` from
+ ``PERMISSION_NEEDED_REASONS``, ``phase`` from ``PERMISSION_NEEDED_PHASES``
+ and ``origin`` from ``PERMISSION_NEEDED_ORIGINS``. ``target`` is the
+ Automation target's bundle id and empty for every other permission.
+ ``can_prompt`` / ``can_open_settings`` say which actions the UI may offer;
+ ``outside_app`` means Jarvis is not running as an installed app, so the
+ grant would belong to the app that started it. The toast says so in one
+ generic sentence (it does not name the app: the event carries no app name),
+ and its single "Ask macOS now" click is the confirmation that sends
+ ``allow_outside_app``.
+
+ ``detail`` is a full English sentence built from fixed templates for logs
+ and support. The UI never renders it: copy comes from i18n per
+ (feature, reason). It never carries exception text, paths or window titles.
+ """
+
+ #: ``PermissionId`` values of this episode, as plain strings.
+ permissions: tuple[str, ...] = ()
+ feature: str = ""
+ reason: str = ""
+ phase: str = ""
+ origin: str = ""
+ target: str = ""
+ can_prompt: bool = False
+ can_open_settings: bool = False
+ outside_app: bool = False
+ detail: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class PermissionResolved(Event):
+ """The episode ended: the permission is now granted, or the episode was closed unresolved.
+
+ Published by the permission service's episode watcher once the live state
+ changes, so consumers that parked on a missing permission (the wake word
+ loop, a hotkey backend) re-arm in process instead of polling. ``granted``
+ is the live verdict when the episode closed; a consumer that needs the
+ permission acts on ``True`` only. ``False`` means nobody touched the episode
+ for ten minutes and the permission was still not granted at the last read
+ (it does not mean the user withdrew anything), and a grant that arrives later
+ is no longer announced until a gesture opens a new episode.
+ """
+
+ permissions: tuple[str, ...] = ()
+ feature: str = ""
+ granted: bool = False
+
+
# ----------------------------------------------------------------------
# Intent & Routing
# ----------------------------------------------------------------------
diff --git a/jarvis/core/macos_privacy_strings.py b/jarvis/core/macos_privacy_strings.py
new file mode 100644
index 0000000000..276077a5ca
--- /dev/null
+++ b/jarvis/core/macos_privacy_strings.py
@@ -0,0 +1,258 @@
+"""The one table of macOS ``Info.plist`` usage-description strings.
+
+Standard-library-only, no ``jarvis`` imports and no work at import time (the one
+file-writing function, :func:`write_localizations`, runs only when a build calls it).
+Two callers cannot import the package normally and therefore load THIS FILE BY
+PATH (``importlib.util.spec_from_file_location``), so neither carries a private
+copy of the strings:
+
+* ``jarvis.spec`` - PyInstaller evaluates the spec from the checkout before the
+ package is importable, and the strings end up in the downloadable ``.dmg``
+ app's ``Info.plist``.
+* ``jarvis.setup.macos_app_bundle._bundle_plist`` - the managed source-install
+ app's ``Info.plist`` (a source checkout, so the file is on disk).
+
+``tests/unit/packaging/test_macos_privacy_strings.py`` loads the same file and
+asserts that the spec's plist dict, the managed bundle's plist and this table
+agree, and ``scripts/ci/check_frozen_macos_app.py`` asserts the table on the
+built ``.app``. Keep this module loadable by path: constants and plain
+functions only (a ``dataclass`` or ``enum`` here would need the module to be
+registered in ``sys.modules`` first).
+
+What the strings are for. macOS shows the string of the RESPONSIBLE app in the
+system dialog, so each one must say, in one plain sentence, which feature the
+person is about to use. The wording follows Apple's guidance for purpose
+strings (a brief, complete sentence, specific, in the active voice, ending in a
+period). Personal Jarvis asks only when a feature needs a permission, never at
+launch, so every sentence names that feature.
+
+Why some keys are deliberately absent (least privilege; nothing is requested
+"just in case"): Jarvis has no caller for the camera, for Apple's speech
+recognition service or for system-administration APIs, so a string for them
+would promise something the app never does. :data:`REMOVED_USAGE_KEYS` lists
+those keys so a build that brings one back is caught by CI. Accessibility,
+Input Monitoring and posting synthetic events have no usage-description key at
+all (their dialog text is fixed by macOS). Services only a child process could
+reach (Contacts, Calendars, Photos, Location, Bluetooth) get no string either:
+an agent feature that needs one must add it here together with its caller.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+# Must equal ``jarvis.core.branding.PRODUCT_NAME``; a parity test pins it
+# (this file may not import the package).
+PRODUCT_NAME = "Personal Jarvis"
+
+_USAGE_DESCRIPTIONS: dict[str, str] = {
+ "NSMicrophoneUsageDescription": (
+ f"{PRODUCT_NAME} uses the microphone when you dictate, talk to it, "
+ "or switch on the wake word."
+ ),
+ # Kept for parity between the two bundles. Apple's documentation index has
+ # no page for this key, so its effect on macOS is UNVERIFIED; Screen
+ # Recording is granted in System Settings whether or not the key exists.
+ "NSScreenCaptureUsageDescription": (
+ f"{PRODUCT_NAME} captures the screen when you ask it to look at what "
+ "is on screen or to control an app for you."
+ ),
+ # Target-neutral on purpose: macOS names the app being controlled in the
+ # dialog itself ("... wants access to control Music"), and the targets today
+ # are Music, Spotify (lowering music while you dictate) and Terminal (sign-in
+ # and coding-agent windows opened through AppleScript). A sentence naming one
+ # of them would be wrong in the other two dialogs.
+ "NSAppleEventsUsageDescription": (
+ f"{PRODUCT_NAME} sends commands to other apps, such as a music player "
+ "or a terminal, when a feature you use needs it."
+ ),
+ # The folder sentences stay short: the system dialog already names the folder.
+ "NSDesktopFolderUsageDescription": (
+ f"{PRODUCT_NAME} works with files in your Desktop folder when you ask it to."
+ ),
+ "NSDocumentsFolderUsageDescription": (
+ f"{PRODUCT_NAME} works with files in your Documents folder when you ask it to."
+ ),
+ "NSDownloadsFolderUsageDescription": (
+ f"{PRODUCT_NAME} works with files in your Downloads folder when you ask it to."
+ ),
+ "NSRemovableVolumesUsageDescription": (
+ f"{PRODUCT_NAME} works with files on an external drive when you ask it to."
+ ),
+ "NSNetworkVolumesUsageDescription": (
+ f"{PRODUCT_NAME} works with files on a network drive when you ask it to."
+ ),
+ # The app itself serves only 127.0.0.1; the local-network prompt is about
+ # the devices and hosts the person configures (a smart-home hub, a local AI
+ # server), which is the one real LAN use of this key.
+ "NSLocalNetworkUsageDescription": (
+ f"{PRODUCT_NAME} connects to devices and hosts on your local network "
+ "that you set up, such as a smart-home hub or a local AI server."
+ ),
+}
+
+# Every key a built bundle must carry, in table order.
+REQUIRED_USAGE_KEYS: tuple[str, ...] = tuple(_USAGE_DESCRIPTIONS)
+
+# Keys that must NOT appear in any bundle: no caller exists, so the string (and,
+# for the camera, the matching entitlement) would claim access Jarvis never uses.
+REMOVED_USAGE_KEYS: tuple[str, ...] = (
+ "NSCameraUsageDescription",
+ "NSSpeechRecognitionUsageDescription",
+ "NSSystemAdministrationUsageDescription",
+)
+
+
+def usage_descriptions() -> dict[str, str]:
+ """A fresh ``{Info.plist key: usage string}`` dict, safe for the caller to mutate."""
+ return dict(_USAGE_DESCRIPTIONS)
+
+
+# --- Localisation (German and Spanish) ----------------------------------------
+#
+# macOS shows the usage string of the user's preferred language when the bundle
+# is localised for it: ``Contents/Resources/<lang>.lproj/InfoPlist.strings``
+# overrides the base ``Info.plist`` value, and ``CFBundleLocalizations`` lists the
+# languages the bundle carries. English stays the base text in ``Info.plist``
+# itself (and the development region), so a language without a table falls back to
+# it. The two bundles share this one table: ``jarvis.spec`` lists the languages in
+# its plist and ``packaging/macos/add_localizations.py`` writes the files into the
+# built ``.dmg`` app before it is signed; the managed bundle does both itself.
+# The wording follows the English table and the in-app German/Spanish copy ("du" /
+# "tu"). German and Spanish are allowed here because this is the closed product
+# surface (``scripts/ci/german-allowlist.txt``). That macOS shows these strings in
+# the permission dialog of a localised system is UNVERIFIED (no Mac was available).
+
+#: Languages the bundles ship an Info.plist for; ``en`` is the base text.
+LOCALIZATIONS: tuple[str, ...] = ("en", "de", "es")
+
+#: ``CFBundleDevelopmentRegion``: the language of the base ``Info.plist`` strings.
+DEVELOPMENT_REGION = "en"
+
+_LOCALIZED_USAGE_DESCRIPTIONS: dict[str, dict[str, str]] = {
+ "de": {
+ "NSMicrophoneUsageDescription": (
+ f"{PRODUCT_NAME} verwendet das Mikrofon, wenn du diktierst, mit Jarvis "
+ "sprichst oder das Wake-Word einschaltest."
+ ),
+ "NSScreenCaptureUsageDescription": (
+ f"{PRODUCT_NAME} erfasst den Bildschirm, wenn du Jarvis bittest, ihn "
+ "anzusehen oder eine App für dich zu steuern."
+ ),
+ "NSAppleEventsUsageDescription": (
+ f"{PRODUCT_NAME} sendet Befehle an andere Apps, etwa an einen "
+ "Musikplayer oder eine Konsole, wenn eine Funktion, die du nutzt, "
+ "es braucht."
+ ),
+ "NSDesktopFolderUsageDescription": (
+ f"{PRODUCT_NAME} arbeitet mit Dateien in deinem Schreibtischordner, "
+ "wenn du darum bittest."
+ ),
+ "NSDocumentsFolderUsageDescription": (
+ f"{PRODUCT_NAME} arbeitet mit Dateien in deinem Dokumentenordner, "
+ "wenn du darum bittest."
+ ),
+ "NSDownloadsFolderUsageDescription": (
+ f"{PRODUCT_NAME} arbeitet mit Dateien in deinem Downloads-Ordner, "
+ "wenn du darum bittest."
+ ),
+ "NSRemovableVolumesUsageDescription": (
+ f"{PRODUCT_NAME} arbeitet mit Dateien auf einem externen Laufwerk, "
+ "wenn du darum bittest."
+ ),
+ "NSNetworkVolumesUsageDescription": (
+ f"{PRODUCT_NAME} arbeitet mit Dateien auf einem Netzwerklaufwerk, "
+ "wenn du darum bittest."
+ ),
+ "NSLocalNetworkUsageDescription": (
+ f"{PRODUCT_NAME} verbindet sich mit Geräten und Hosts in deinem "
+ "lokalen Netzwerk, die du eingerichtet hast, etwa einem "
+ "Smart-Home-Hub oder einem lokalen KI-Server."
+ ),
+ },
+ "es": {
+ "NSMicrophoneUsageDescription": (
+ f"{PRODUCT_NAME} usa el micrófono cuando dictas, hablas con Jarvis "
+ "o activas la palabra de activación."
+ ),
+ "NSScreenCaptureUsageDescription": (
+ f"{PRODUCT_NAME} captura la pantalla cuando le pides que mire lo "
+ "que hay en ella o que controle una app por ti."
+ ),
+ "NSAppleEventsUsageDescription": (
+ f"{PRODUCT_NAME} envía comandos a otras apps, como un reproductor "
+ "de música o una terminal, cuando una función que usas lo necesita."
+ ),
+ "NSDesktopFolderUsageDescription": (
+ f"{PRODUCT_NAME} trabaja con archivos de tu carpeta Escritorio cuando se lo pides."
+ ),
+ "NSDocumentsFolderUsageDescription": (
+ f"{PRODUCT_NAME} trabaja con archivos de tu carpeta Documentos cuando se lo pides."
+ ),
+ "NSDownloadsFolderUsageDescription": (
+ f"{PRODUCT_NAME} trabaja con archivos de tu carpeta Descargas cuando se lo pides."
+ ),
+ "NSRemovableVolumesUsageDescription": (
+ f"{PRODUCT_NAME} trabaja con archivos de una unidad externa cuando se lo pides."
+ ),
+ "NSNetworkVolumesUsageDescription": (
+ f"{PRODUCT_NAME} trabaja con archivos de una unidad de red cuando se lo pides."
+ ),
+ "NSLocalNetworkUsageDescription": (
+ f"{PRODUCT_NAME} se conecta con dispositivos y equipos de tu red "
+ "local que hayas configurado, como un hub doméstico inteligente o "
+ "un servidor de IA local."
+ ),
+ },
+}
+
+#: The languages that get an ``<lang>.lproj/InfoPlist.strings`` (English is the base).
+LOCALIZED_LANGUAGES: tuple[str, ...] = tuple(_LOCALIZED_USAGE_DESCRIPTIONS)
+
+
+def localized_usage_descriptions(language: str) -> dict[str, str]:
+ """A fresh ``{Info.plist key: usage string}`` dict for ``language`` (``de`` / ``es``)."""
+ return dict(_LOCALIZED_USAGE_DESCRIPTIONS[language])
+
+
+def localization_plist_keys() -> dict[str, object]:
+ """The two ``Info.plist`` keys that declare the localisations (a fresh dict)."""
+ return {
+ "CFBundleDevelopmentRegion": DEVELOPMENT_REGION,
+ "CFBundleLocalizations": list(LOCALIZATIONS),
+ }
+
+
+def _strings_literal(text: str) -> str:
+ """``text`` as the body of a quoted ``.strings`` value (backslash and quote escaped)."""
+ return text.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
+
+
+def info_plist_strings_text(language: str) -> str:
+ """The content of ``<language>.lproj/InfoPlist.strings`` (UTF-8 text, one key per line)."""
+ lines = [
+ "/* Generated from jarvis/core/macos_privacy_strings.py - do not edit by hand. */",
+ ]
+ texts = localized_usage_descriptions(language)
+ for key in REQUIRED_USAGE_KEYS:
+ lines.append(f'"{key}" = "{_strings_literal(texts[key])}";')
+ return "\n".join(lines) + "\n"
+
+
+def write_localizations(resources_dir: Path) -> list[Path]:
+ """Write every ``<lang>.lproj/InfoPlist.strings`` into ``resources_dir``; return the files.
+
+ ``resources_dir`` is a bundle's ``Contents/Resources``. Called by the build
+ step that runs before the bundle is signed (the files are part of the seal)
+ and when the managed bundle is laid out; never at import time. The write is
+ UTF-8, which macOS reads for a ``.strings`` file (Apple's own tooling writes
+ UTF-16; UTF-8 acceptance on a real Mac is UNVERIFIED).
+ """
+ written: list[Path] = []
+ for language in LOCALIZED_LANGUAGES:
+ directory = resources_dir / f"{language}.lproj"
+ directory.mkdir(parents=True, exist_ok=True)
+ target = directory / "InfoPlist.strings"
+ target.write_text(info_plist_strings_text(language), encoding="utf-8", newline="\n")
+ written.append(target)
+ return written
diff --git a/jarvis/core/protocols.py b/jarvis/core/protocols.py
index f51f4e6c0f..fea4c49f88 100644
--- a/jarvis/core/protocols.py
+++ b/jarvis/core/protocols.py
@@ -11,9 +11,9 @@ Streaming is first-class: every Brain/STT/TTS/Harness response is an
from __future__ import annotations
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Iterable
from dataclasses import dataclass, field
-from typing import Any, Literal, Protocol, runtime_checkable
+from typing import TYPE_CHECKING, Any, Literal, Protocol, runtime_checkable
from uuid import UUID
from .chat_turn import ChatCompletion as ChatCompletion
@@ -22,6 +22,10 @@ from .chat_turn import current_chat_turn as current_chat_turn
from .trigger_context import RoutineDeferred as RoutineDeferred
from .trigger_context import current_trigger_path as current_trigger_path
+if TYPE_CHECKING: # pragma: no cover - typing only; the contract has no runtime import
+ from jarvis.platform.permission_service import EnsureResult
+ from jarvis.platform.permissions import PermissionId, PermissionState
+
class ChatControlAdapter(Protocol):
"""One owner of a chat's native goal loop; absence falls back to Jarvis."""
@@ -784,3 +788,78 @@ class MarsStationExecutor(Protocol):
) -> dict[str, Any]:
"""Request cancellation through the owning task service, then report its state."""
...
+
+
+# ----------------------------------------------------------------------
+# PermissionGate (just-in-time OS permissions)
+# ----------------------------------------------------------------------
+
+
+@runtime_checkable
+class PermissionGate(Protocol):
+ """What a feature may ask of the OS-permission layer.
+
+ The concrete implementation is ``jarvis.platform.permission_service``; a
+ consumer receives it through an ``access_gate``-style hook whose default
+ resolves the process singleton, and a test injects
+ ``tests.fakes.fake_permission_service.FakePermissionService``.
+
+ Threading rule: ``check`` is silent, lock-free and never prompts, so the
+ event loop, a Tk callback and an event-tap callback may call it. ``ensure``
+ with ``wait_s > 0`` blocks and belongs on a worker thread; the event loop uses
+ ``ensure_async``. Only ``result.granted`` lets an action proceed: PENDING,
+ NEEDS_SETTINGS, DENIED and UNAVAILABLE never do, and a native request's
+ return value is never evidence of a grant.
+ """
+
+ def check(
+ self, permission: PermissionId | str, *, target: str | None = None
+ ) -> PermissionState:
+ """The live state of one permission; never asks, never publishes."""
+ ...
+
+ def ensure(
+ self,
+ permission: PermissionId | str,
+ *,
+ feature: str,
+ interactive: bool = True,
+ wait_s: float = 0.0,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ allow_outside_app: bool = False,
+ ) -> EnsureResult:
+ """Make sure a permission is granted, asking macOS at most once per episode."""
+ ...
+
+ async def ensure_async(
+ self,
+ permission: PermissionId | str,
+ *,
+ feature: str,
+ interactive: bool = True,
+ wait_s: float = 0.0,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ allow_outside_app: bool = False,
+ ) -> EnsureResult:
+ """``ensure`` for the event loop; never pins an executor worker while it waits."""
+ ...
+
+ def ensure_all(
+ self,
+ permissions: Iterable[PermissionId | str],
+ *,
+ feature: str,
+ interactive: bool = True,
+ wait_s: float = 0.0,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ allow_outside_app: bool = False,
+ ) -> list[EnsureResult]:
+ """``ensure`` for several permissions: ONE coalesced episode and ONE event."""
+ ...
+
+ def open_settings(self, permission: PermissionId | str) -> bool:
+ """Open the System Settings pane of a permission; ``False`` when it cannot."""
+ ...
diff --git a/jarvis/cu/actuate/__init__.py b/jarvis/cu/actuate/__init__.py
index 42aeeef33f..160d528cac 100644
--- a/jarvis/cu/actuate/__init__.py
+++ b/jarvis/cu/actuate/__init__.py
@@ -18,6 +18,7 @@ from jarvis.cu.actuate.base import (
ActResult,
ActuationUnavailable,
Actuator,
+ PermissionNeededError,
get_actuator,
verified_click,
verified_drag,
@@ -29,6 +30,7 @@ __all__ = [
"ActuationUnavailable",
"Actuator",
"LANDING_TOLERANCE",
+ "PermissionNeededError",
"get_actuator",
"verified_click",
"verified_drag",
diff --git a/jarvis/cu/actuate/base.py b/jarvis/cu/actuate/base.py
index 72077a3211..be011eea49 100644
--- a/jarvis/cu/actuate/base.py
+++ b/jarvis/cu/actuate/base.py
@@ -21,6 +21,7 @@ import sys
import threading
from collections.abc import Callable
from dataclasses import dataclass
+from typing import Any
logger = logging.getLogger(__name__)
@@ -61,6 +62,32 @@ class ActuationUnavailable(RuntimeError):
"""
+#: Used only when a gate result carries no sentence of its own (a hand-written stub).
+_PERMISSION_FALLBACK_MSG = (
+ "[permission_needed:accessibility] This action cannot run: Accessibility access "
+ "has not been allowed yet and the user has to allow it. You must not try to "
+ "answer, click or dismiss any macOS system dialog yourself, you must not retry "
+ "this action, and you must not look for a workaround. Tell the user that this "
+ "feature needs the permission and stop."
+)
+
+
+class PermissionNeededError(ActuationUnavailable):
+ """macOS has not granted the Accessibility access that synthetic input needs.
+
+ ``str(exc)`` is the service's AGENT-facing sentence: it starts with
+ ``[permission_needed:accessibility] `` (the prefix the computer-use engine maps
+ to a terminal "blocked on permission" outcome) and forbids a model from
+ answering a system dialog, retrying or looking for a workaround (P9). A caller
+ that talks to a PERSON (dictation) reads ``result.user_detail`` instead. The
+ subclass keeps every existing ``except ActuationUnavailable`` handler working.
+ """
+
+ def __init__(self, result: Any) -> None:
+ self.result = result
+ super().__init__(str(getattr(result, "agent_detail", "") or _PERMISSION_FALLBACK_MSG))
+
+
@dataclass(frozen=True)
class ActResult:
"""Outcome of one actuation primitive."""
@@ -349,45 +376,43 @@ _NO_BACKEND_MSG = (
)
-def _require_macos_input_permissions() -> None:
- """Fail closed unless macOS currently permits synthetic input.
+def _permission_gate() -> Any:
+ """The permission layer (``PermissionGate``); a test replaces this seam.
+
+ Resolved per call and never cached, so the process singleton can be reset.
+ """
+ from jarvis.platform.permission_service import get_permission_service # noqa: PLC0415
+
+ return get_permission_service()
+
+
+def _ensure_macos_input_permission(feature: str) -> None:
+ """Ask macOS for the access synthetic input needs, or refuse. No-op off macOS.
+
+ Synthetic input needs Accessibility (``event_posting`` is an alias of it: one
+ switch, one request). This is the just-in-time ask: the tool call that got
+ here was already authorised by ``ToolExecutor.execute()`` (AP-3), so this is
+ not a second authority and no tool can reach ``ensure`` or the native request
+ itself. ``wait_s=0``: the OS dialog is answered later and the watcher reports
+ the grant; a tool body never blocks on a person.
- TCC grants can be revoked while Jarvis is running, so this deliberately
- creates a fresh permission port and probes both grants for every action.
- No result is cached in the actuator layer.
+ Only a live GRANTED lets the action proceed. The grant is re-read on every
+ call (a revocation must fail closed); the service caches a grant for about
+ one second, so a click burst does not pay a native read per click.
"""
if sys.platform != "darwin":
return
+ from jarvis.platform.permissions import PermissionId # noqa: PLC0415
- from jarvis.platform.permissions import ( # noqa: PLC0415
- PermissionId,
- PermissionState,
- get_system_permission_port,
+ results = _permission_gate().ensure_all(
+ [PermissionId.ACCESSIBILITY], feature=feature, wait_s=0.0
)
-
- port = get_system_permission_port()
- requirements = (
- (PermissionId.ACCESSIBILITY, "Accessibility"),
- (PermissionId.EVENT_POSTING, "Input Control"),
- )
- missing: list[str] = []
- for permission_id, label in requirements:
- if not port.runtime_access_granted(permission_id):
- state = port.state(permission_id)
- detail = (
- state.value
- if state is not PermissionState.GRANTED
- else "grant belongs to an unstable app identity or needs restart"
- )
- missing.append(f"{label} ({detail})")
- if missing:
- joined = ", ".join(missing)
- raise ActuationUnavailable(
- "Cannot control the mouse or keyboard on macOS because these "
- f"permissions are not granted: {joined}. Open Personal Jarvis "
- "> Settings > Permissions (or System Settings > Privacy & "
- "Security), grant the listed access, then retry."
- )
+ for result in results:
+ if not result.granted:
+ raise PermissionNeededError(result)
+ if not results:
+ # An empty answer is not a grant: never act on it.
+ raise PermissionNeededError(None)
#: Process-wide backend instance. Building a PosixActuator constructs pynput
@@ -404,13 +429,17 @@ def get_actuator() -> Actuator:
"""Resolve the platform input backend by runtime capability.
Raises :class:`ActuationUnavailable` with an actionable English message
- when the host cannot receive synthetic input. Never returns a backend
- that is known-broken for the session type. The permission and session
- probes run on EVERY call (revocation must fail closed); only the backend
- construction is reused.
+ when the host cannot receive synthetic input; on macOS without the
+ Accessibility grant that is the :class:`PermissionNeededError` subclass
+ (the first such call also makes macOS show its own dialog). Never returns a
+ backend that is known-broken for the session type. The permission and
+ session probes run on EVERY call (revocation must fail closed); only the
+ backend construction is reused. A caller with a different feature than
+ computer use (dictation paste) asks first with its own feature name, so the
+ permission toast says what the access is for; this call then finds it granted.
"""
global _ACTUATOR_CACHE
- _require_macos_input_permissions()
+ _ensure_macos_input_permission("computer_use")
if os.name == "nt":
from jarvis.cu.actuate.windows import WindowsActuator # noqa: PLC0415
diff --git a/jarvis/cu/capture.py b/jarvis/cu/capture.py
index 35dda48238..1a23f86681 100644
--- a/jarvis/cu/capture.py
+++ b/jarvis/cu/capture.py
@@ -115,36 +115,94 @@ def _capture_thumb(raw: _RawCapture) -> bytes:
def _require_macos_screen_recording_permission() -> None:
- """Fail closed unless macOS currently permits screen capture.
+ """The SILENT Screen Recording gate: never asks, raises unless live GRANTED.
+
+ The engine's per-action choke point (a user can revoke the grant while
+ Jarvis runs, and no input may be dispatched against a screen Jarvis may not
+ see) uses this. It reads the state through the permission service, including
+ the window-title oracle, so a grant given mid-session is seen; it never makes
+ macOS show a dialog. Perception does NOT use it: the capture entry
+ (:func:`_ensure_screen_recording_for_perception`) is the one that asks.
+ Off macOS the service reports NOT_REQUIRED and this returns at once.
+ """
+ from jarvis.platform import screen_access # noqa: PLC0415
+
+ state = screen_access.screen_recording_state()
+ if not screen_access.state_allows_capture(state):
+ raise screen_access.refusal_for_state(state)
+
- The native state is probed before every grab, not only at mission start,
- because a user can revoke Screen Recording while Jarvis is running.
+def _ensure_screen_recording_for_perception() -> None:
+ """Gesture entry of a perception frame: ask macOS if the grant is missing.
+
+ A Computer-Use mission is started by a person, so its first frame is where
+ the Screen Recording question belongs. The granted fast path is one cached
+ read per FRAME (not per stability re-grab); only a missing grant reaches the
+ permission service, which asks at most once per episode and never loops. A
+ refusal raises :class:`~jarvis.platform.screen_access.ScreenCaptureRefused`
+ (a ``RuntimeError``) whose text names the permission.
"""
- from jarvis.platform import detect_platform # noqa: PLC0415
+ from jarvis.platform import screen_access # noqa: PLC0415
+
+ screen_access.require_screen_recording("computer_use")
- if detect_platform() != "darwin":
- return
- from jarvis.platform.permissions import ( # noqa: PLC0415
- PermissionId,
- PermissionState,
- get_system_permission_port,
+def _verify_perception_frame(raw: _RawCapture) -> None:
+ """Refuse a blank frame the permission state cannot explain (never a success).
+
+ Once per frame, after the final grab. See
+ :func:`jarvis.platform.screen_access.verify_frame_is_real` for the rule.
+ """
+ from jarvis.platform import screen_access # noqa: PLC0415
+
+ screen_access.verify_frame_is_real(
+ _capture_size(raw),
+ raw.data if isinstance(raw, _CapturedPixels) else raw[1],
+ feature="computer_use",
+ bytes_per_pixel=4 if isinstance(raw, _CapturedPixels) else 3,
)
- port = get_system_permission_port()
- if not port.runtime_access_granted(PermissionId.SCREEN_RECORDING):
- state = port.state(PermissionId.SCREEN_RECORDING)
- detail = (
- state.value
- if state is not PermissionState.GRANTED
- else "grant belongs to an unstable app identity or needs restart"
- )
- raise RuntimeError(
- "Cannot capture the screen on macOS because Screen Recording "
- f"permission is not ready ({detail}). Open Personal Jarvis "
- "> Settings > Permissions (or System Settings > Privacy & "
- "Security > Screen Recording), grant access, then retry."
+
+def _helper_capture_blocked() -> bool:
+ """Silent "may a helper grab pixels now" read for the region/probe helpers.
+
+ Helpers never ask: a blocked state degrades them to "cannot tell".
+ """
+ from jarvis.platform import screen_access # noqa: PLC0415
+
+ return screen_access.screen_recording_blocked()
+
+
+def _refuse_if_confirmation_pending(reason: str = "pending_confirmation") -> None:
+ """A native window capture timed out: refuse unless the live grant explains the rect grab.
+
+ When the live state says granted the rect grab is safe and the caller carries
+ on with it (after one warning, so the soft failure is not invisible). When it
+ does not, a rect grab would return the wallpaper, so refuse honestly: a
+ ``pending_confirmation`` (a request is still in flight, macOS may be asking)
+ is reported as pending, never as a denial, and a plain ``timeout`` that the
+ state does not explain reports the state itself. Silent: nothing is asked here.
+
+ The live-grant branch stays a log line on purpose and is NOT reported through
+ ``report_failed_use``: nothing failed for good (the rect grab that follows may
+ well work, and ``verify_frame_is_real`` reports it when that frame is wallpaper),
+ and ``report_failed_use`` only produces a user-origin ``restart_hint`` episode,
+ which would nag a user whose capture works.
+ """
+ from jarvis.platform import screen_access # noqa: PLC0415
+
+ state = screen_access.screen_recording_state()
+ if screen_access.state_allows_capture(state):
+ logger.warning(
+ "[cu] native window capture timed out (%s) while the Screen Recording grant "
+ "reads as live; macOS may be waiting for a confirmation. Falling back to "
+ "the rect grab.",
+ reason,
)
+ return
+ if reason == "pending_confirmation":
+ raise screen_access.refusal_pending()
+ raise screen_access.refusal_for_state(state)
def mss_grab(bbox: dict[str, int]) -> tuple[tuple[int, int], bytes]:
@@ -196,11 +254,15 @@ def grabber_for(
# Native per-window capture can still include an overlapping
# topmost overlay on some platforms — same guard as mss_grab.
+ window_capture.clear_grab_failure()
with indicator_suppressed():
raw = window_capture.grab_window(handle, bbox)
if raw is not None:
return raw
native_alive = False
+ failure = window_capture.last_grab_failure()
+ if failure in ("pending_confirmation", "timeout"):
+ _refuse_if_confirmation_pending(failure)
return rect_grab(bbox)
return grab
@@ -525,12 +587,14 @@ def capture_stable_frame(
plus the encoded image size: the one central translation.
"""
deadline = time.monotonic() + max(0.0, stability_timeout_s)
- # One permission probe per FRAME, not per re-grab: the stability loop can
+ # One permission read per FRAME, not per re-grab: the stability loop can
# re-grab repeatedly inside 1.2 s, and a grant cannot plausibly be revoked
- # and matter within that window — the engine independently re-probes
- # before every dispatched action, which is the check that prevents blind
- # input after a revocation.
- _require_macos_screen_recording_permission()
+ # and matter within that window — the engine independently re-reads it
+ # (silently) before every dispatched action, which is the check that
+ # prevents blind input after a revocation. This is the perception entry of
+ # a mission a person started, so a MISSING grant is asked for here (once per
+ # episode, by the permission service) instead of being refused unasked.
+ _ensure_screen_recording_for_perception()
stable = False
with _frame_grabber(monitor, grab) as grabber:
@@ -563,6 +627,10 @@ def capture_stable_frame(
current = nxt
current_thumb = nxt_thumb
+ # macOS returns the wallpaper, not an error, for a capture it does not
+ # allow: a blank frame while the state claims GRANTED is never a success.
+ _verify_perception_frame(current)
+
jpeg, iw, ih = _downscale_and_encode(
current,
max_dimension=max_dimension,
@@ -613,14 +681,17 @@ def grab_region(
"""One raw region grab for pre/post verification diffs.
Returns ``None`` on capture failures (headless, transient GDI error, or a
- revoked macOS grant) so pixel-effect verification can report "cannot
- tell". The Computer-Use dispatcher independently rechecks Screen Recording
- immediately before every action, so this degradation cannot permit blind
- input after a revoked grant.
+ macOS grant that is missing or revoked) so pixel-effect verification can
+ report "cannot tell". A helper never asks: it reads the state silently and
+ degrades. The Computer-Use dispatcher independently rechecks Screen
+ Recording immediately before every action, so this degradation cannot permit
+ blind input after a revoked grant.
"""
grabber = grab or mss_grab
try:
- _require_macos_screen_recording_permission()
+ if _helper_capture_blocked():
+ logger.debug("[cu] region grab skipped: Screen Recording is not granted")
+ return None
return grabber(bbox)
except Exception: # noqa: BLE001
logger.debug("[cu] region grab failed (non-fatal)", exc_info=True)
@@ -662,7 +733,9 @@ def grab_visual_probe(
tri-state ``None``; it never becomes proof of success or failure.
"""
try:
- _require_macos_screen_recording_permission()
+ if _helper_capture_blocked():
+ logger.debug("[cu] visual probe skipped: Screen Recording is not granted")
+ return None
import mss # noqa: PLC0415
from jarvis.cu.indicator.capture_guard import ( # noqa: PLC0415
diff --git a/jarvis/cu/engine.py b/jarvis/cu/engine.py
index 92fa44db8a..c63fe2b6b3 100644
--- a/jarvis/cu/engine.py
+++ b/jarvis/cu/engine.py
@@ -36,6 +36,7 @@ from __future__ import annotations
import asyncio
import base64
import logging
+import re
import sys
import time
from collections.abc import AsyncIterator
@@ -389,6 +390,168 @@ def _signature_still_valid(
return live == expected or signatures_same_app(expected, live)
+#: Stable reason code of a mission that stopped because a macOS permission or a
+#: system dialog needs the person. It rides on the existing tool-failure exit code
+#: (``_EXIT_TOOL``) in the final ``stderr`` as ``"[cu] blocked_permission at
+#: step-N: <sentence>"`` rather than as a new status value, so nothing persisted
+#: or localised needs a new member; the layer that turns the result into a card
+#: keys off this token and offers the Retry. Never a model retry loop.
+CU_REASON_BLOCKED_PERMISSION = "blocked_permission"
+
+#: The prefix every agent-facing permission refusal starts with
+#: (``jarvis.platform.permission_service.agent_detail_for``). Matched ANYWHERE in a
+#: tool error because the engine wraps some of them ("could not select existing
+#: text before replacement: <detail>").
+_PERMISSION_NEEDED_RE = re.compile(r"\[permission_needed:([a-z_]+)\]")
+
+_SR_REASON_BY_STATE = {
+ "not_determined": "not_determined",
+ "denied": "denied",
+ "restricted": "restricted",
+ "not_granted": "needs_settings",
+ "unavailable": "unavailable",
+}
+
+
+def _permission_gate() -> Any:
+ """The permission layer; a test replaces this seam. Resolved per call."""
+ from jarvis.platform.permission_service import get_permission_service # noqa: PLC0415
+
+ return get_permission_service()
+
+
+def _frontmost_system_consent_owner() -> str:
+ """The frontmost window's owner when it is a macOS consent surface, else ``""``.
+
+ macOS only: every other host answers ``""`` without touching a native API.
+ A test replaces this seam.
+ """
+ if sys.platform != "darwin":
+ return ""
+ from jarvis.cu import system_dialogs # noqa: PLC0415
+
+ return system_dialogs.frontmost_consent_owner()
+
+
+def _blocked_before_dispatch() -> str | None:
+ """The silent guards that run BEFORE any action reaches ``executor.execute()``.
+
+ Returns the agent-facing refusal text, or ``None`` when the action may go on.
+ Blocking (a window-title oracle and a window list): call it off the loop.
+ Never interactive and it never asks macOS for anything.
+
+ 1. Screen Recording. A grant can be revoked after perception and before
+ actuation, and input without a screen to verify against is blind input,
+ so no action runs against a screen Jarvis may not observe. The deep read
+ is used on purpose (not the preflight-only ``check``): the preflight is
+ frozen per process on some macOS versions, and a grant the user just gave
+ must be seen. Off macOS the service answers NOT_REQUIRED.
+ 2. System consent guard (P9): while a macOS permission / authorization
+ dialog is frontmost nothing is dispatched. An AI agent never answers a
+ system dialog.
+ """
+ from jarvis.platform.permission_service import agent_detail_for # noqa: PLC0415
+ from jarvis.platform.permissions import PermissionId, PermissionState # noqa: PLC0415
+
+ gate = _permission_gate()
+ read = getattr(gate, "check_deep", None) or gate.check
+ state = read(PermissionId.SCREEN_RECORDING)
+ if state not in (PermissionState.GRANTED, PermissionState.NOT_REQUIRED):
+ # Record a background episode (it never asks and never raises) so the
+ # grant is noticed and the status snapshot says why the Retry fails.
+ try:
+ gate.ensure(
+ PermissionId.SCREEN_RECORDING,
+ feature="computer_use",
+ interactive=False,
+ wait_s=0.0,
+ )
+ except Exception: # noqa: BLE001 - the refusal below stands either way
+ log.debug("Recording the screen-recording episode failed.", exc_info=True)
+ reason = _SR_REASON_BY_STATE.get(str(state), "needs_settings")
+ return agent_detail_for(PermissionId.SCREEN_RECORDING, reason)
+
+ if _frontmost_system_consent_owner():
+ from jarvis.cu import system_dialogs # noqa: PLC0415
+
+ return system_dialogs.agent_detail()
+ return None
+
+
+def _guard_failure_refusal() -> str | None:
+ """What a guard that could not run answers: macOS refuses, every other host proceeds."""
+ if sys.platform != "darwin":
+ return None
+ from jarvis.platform.permission_service import agent_detail_for # noqa: PLC0415
+ from jarvis.platform.permissions import PermissionId # noqa: PLC0415
+
+ return agent_detail_for(PermissionId.SCREEN_RECORDING, "unavailable")
+
+
+#: The refusal reasons the agent text distinguishes, in the order they are tried.
+#: ``needs_settings`` comes before ``not_determined`` because the two share one
+#: agent sentence: the ambiguous case keeps the "turn it on in Settings" wording.
+_REFUSAL_REASONS = (
+ "restricted",
+ "unavailable",
+ "denied",
+ "restart_hint",
+ "needs_settings",
+ "not_determined",
+)
+
+
+def _refusal_situation(family: Any, detail: str) -> tuple[str, bool]:
+ """``(reason, asking)`` of a permission refusal, read back from its agent text.
+
+ The agent text is built from fixed templates, so it is matched against the
+ templates themselves instead of being parsed. An unmatched text (a wrapped or
+ shortened one) falls back to ``needs_settings``.
+ """
+ from jarvis.platform.permission_service import agent_detail_for # noqa: PLC0415
+
+ for reason in _REFUSAL_REASONS:
+ for asking in (False, True):
+ if agent_detail_for(family, reason, asking=asking) in detail:
+ return reason, asking
+ return "needs_settings", False
+
+
+def _permission_block(detail: str) -> str | None:
+ """The user sentence when a tool error is a permission refusal, else ``None``.
+
+ The sentence follows the REASON the refusal carries: a restricted or an
+ unavailable permission is explained and nothing more (there is no switch to
+ flip), the others say what to turn on and to try the task again.
+ """
+ match = _PERMISSION_NEEDED_RE.search(detail or "")
+ if match is None:
+ return None
+ token = match.group(1)
+ from jarvis.cu import system_dialogs # noqa: PLC0415
+
+ if token == system_dialogs.SYSTEM_DIALOG_BLOCK:
+ return system_dialogs.user_detail()
+ from jarvis.platform.permission_service import user_detail_for # noqa: PLC0415
+ from jarvis.platform.permissions import PermissionId # noqa: PLC0415
+
+ try:
+ family = PermissionId(token)
+ except ValueError:
+ # Not a permission this build knows: the generic sentence is the intended
+ # degradation, the token itself is not shown to people.
+ log.debug("Unknown permission token in a tool error.", exc_info=True)
+ return (
+ "A macOS permission is needed to continue, so the task stopped. "
+ "Try the task again once it is allowed."
+ )
+ reason, asking = _refusal_situation(family, detail)
+ sentence = user_detail_for(family, reason, asking=asking)
+ if reason in ("restricted", "unavailable") or asking:
+ return sentence
+ return f"{sentence} Then try the task again."
+
+
async def _dispatch_tool(
ctx: Any,
tool_name: str,
@@ -396,17 +559,17 @@ async def _dispatch_tool(
trace_id: Any,
) -> tuple[bool, str]:
"""Run one action through the ToolExecutor (AP-3 choke point)."""
- # A macOS Screen Recording grant can be revoked after perception but
- # before actuation. Re-probe at the final dispatcher choke point so no CU
- # action can run against a screen Jarvis is no longer allowed to observe.
+ # The final dispatcher choke point: no CU action runs against a screen Jarvis
+ # is no longer allowed to observe, and none while a system dialog is up. The
+ # refusal text starts with "[permission_needed:" and the loop ends the mission
+ # on it (blocked_permission); the model never sees it and never retries.
try:
- from jarvis.cu.capture import ( # noqa: PLC0415
- _require_macos_screen_recording_permission,
- )
-
- _require_macos_screen_recording_permission()
- except RuntimeError as exc:
- return False, str(exc)
+ blocked = await asyncio.to_thread(_blocked_before_dispatch)
+ except Exception: # noqa: BLE001 - on macOS a failing guard refuses, never acts
+ log.debug("The pre-dispatch permission guard failed.", exc_info=True)
+ blocked = _guard_failure_refusal()
+ if blocked is not None:
+ return False, blocked
tools = ctx.tools or {}
tool = tools.get(tool_name)
@@ -980,6 +1143,26 @@ async def run_cu_loop(
"foreground window changed during capture; retrying with a fresh frame"
)
except Exception as exc: # noqa: BLE001 — capture is inherently flaky
+ # A Screen Recording refusal (ScreenCaptureRefused, "[permission_needed:..."
+ # agent text) is not flaky capture: retrying it only re-asks the OS and
+ # burns the budget. It ends the mission as blocked_permission, exactly
+ # like a dispatch-time refusal, so the person gets the sentence and a
+ # Retry instead of "I couldn't see the screen".
+ blocked_sentence = _permission_block(str(exc))
+ if blocked_sentence is not None:
+ log.info(
+ "[cu] step %d: perception refused (%s)",
+ step_idx,
+ CU_REASON_BLOCKED_PERMISSION,
+ )
+ yield _final(
+ stderr=(
+ f"[cu] {CU_REASON_BLOCKED_PERMISSION} at step-{step_idx}: "
+ f"{blocked_sentence}\n"
+ ),
+ exit_code=_EXIT_TOOL,
+ )
+ return
observe_failures += 1
log.warning("[cu] observe failed (step %d): %s", step_idx, exc)
if observe_failures > _MAX_OBSERVE_FAILURES:
@@ -1524,6 +1707,13 @@ async def run_cu_loop(
},
trace_id,
)
+ if not ok2 and _permission_block(detail2) is not None:
+ # The retry was refused by the permission or
+ # consent guard (a dialog opened after the first
+ # click): end the mission now instead of paying
+ # another model call to find out.
+ ok = False
+ detail = detail2
if ok2:
ledger.record(
action,
@@ -1786,6 +1976,24 @@ async def run_cu_loop(
)
yield _progress(f"[cu] step {step_idx}: {summary} ok")
else:
+ blocked_sentence = _permission_block(detail)
+ if blocked_sentence is not None:
+ # A permission refusal is a terminal state with a stable
+ # reason code, never a failure the model may retry around.
+ log.info(
+ "[cu] step %d: %s -> %s (a permission or a system dialog)",
+ step_idx,
+ summary,
+ CU_REASON_BLOCKED_PERMISSION,
+ )
+ yield _final(
+ stderr=(
+ f"[cu] {CU_REASON_BLOCKED_PERMISSION} at step-{step_idx}: "
+ f"{blocked_sentence}\n"
+ ),
+ exit_code=_EXIT_TOOL,
+ )
+ return
consecutive_failures += 1
history.append(
f"step {step_idx}: {summary} -> FAILED: {detail[:180]}",
diff --git a/jarvis/cu/indicator/controller.py b/jarvis/cu/indicator/controller.py
index fba9ea7031..dde9683ad5 100644
--- a/jarvis/cu/indicator/controller.py
+++ b/jarvis/cu/indicator/controller.py
@@ -16,9 +16,12 @@ uses — the engine exits with code 130 and reports an honest cancel.
Degradations (each logs one English line, never crashes, never blocks a
mission): headless / Wayland / PySide6 missing → no border; hotkey
-backend unavailable (Wayland, missing macOS permission) → no Escape and
+backend unavailable (Wayland, macOS without Input Monitoring) → no Escape and
therefore no "Esc to cancel" pill (the border must not promise a key that
-cannot work).
+cannot work). The pill is shown only after the Escape listener's backend
+reported that it is actually listening; on macOS that means the event tap is
+running, i.e. Input Monitoring is granted. Nothing here asks for that
+permission and no toast is forced.
"""
from __future__ import annotations
@@ -40,6 +43,11 @@ from jarvis.cu.indicator import capture_guard, protocol, self_input
log = logging.getLogger(__name__)
+# How long the pill waits for the Escape listener to report whether its backend
+# is really listening (the macOS tap handshake alone can take a few seconds).
+# An unconfirmed listener never earns the pill.
+_ESC_READY_TIMEOUT_S = 6.0
+
# "Esc to cancel" pill copy — ALL supported output locales (repo rule:
# a phrase table always carries every supported language and resolves its
# key through the one turn-language resolver).
@@ -112,6 +120,11 @@ class CUIndicatorController:
self._command_lock = threading.Lock()
self._acks: queue.Queue[str] = queue.Queue()
self._esc_task: asyncio.Task | None = None
+ # Handshake with the Escape listener: ``_esc_ready`` is set once the
+ # listener's backend answered, ``_esc_holds_key`` says whether it is
+ # actually listening (a dead key must not be promised on the pill).
+ self._esc_ready = asyncio.Event()
+ self._esc_holds_key = False
self._sidecar_warned = False
# Monotonic deadline until which an appshot effect owns the sidecar.
self._snap_until = 0.0
@@ -160,7 +173,7 @@ class CUIndicatorController:
self._screen_active.add(event.trace_id)
hint = (
_ESC_HINTS.get(_resolve_hint_language(), _ESC_HINTS["en"])
- if self._active and self._esc_task is not None
+ if self._active and self._esc_task is not None and self._esc_holds_key
else ""
)
visible = await self._show_border(hint=hint, required=True)
@@ -181,7 +194,7 @@ class CUIndicatorController:
# ------------------------------------------------------------- activation
async def _activate(self) -> None:
- esc_armed = self._arm_escape()
+ esc_armed = self._arm_escape() and await self._esc_claims_key()
hint = (
_ESC_HINTS.get(_resolve_hint_language(), _ESC_HINTS["en"])
if esc_armed
@@ -479,6 +492,8 @@ class CUIndicatorController:
except Exception: # noqa: BLE001
return False
if self._esc_task is None or self._esc_task.done():
+ self._esc_ready = asyncio.Event()
+ self._esc_holds_key = False
self._esc_task = asyncio.get_running_loop().create_task(
self._esc_watch(), name="cu-indicator-esc",
)
@@ -486,11 +501,33 @@ class CUIndicatorController:
def _disarm_escape(self) -> None:
task, self._esc_task = self._esc_task, None
+ self._esc_holds_key = False
if task is not None and not task.done():
task.cancel()
+ async def _esc_claims_key(self) -> bool:
+ """May the pill promise "Esc to cancel"? Only if the listener really runs.
+
+ Waits (bounded) for the Escape listener's backend to answer. A backend
+ that cannot tell (Windows, Linux) answers "listening" as before; the
+ macOS tap answers "no" while Input Monitoring is missing. No task means
+ nothing was armed here, so nothing is asked.
+ """
+ if self._esc_task is None:
+ return True
+ try:
+ await asyncio.wait_for(self._esc_ready.wait(), timeout=_ESC_READY_TIMEOUT_S)
+ except TimeoutError:
+ log.info("[cu-indicator] the Escape listener did not report in time — no Esc hint.")
+ return False
+ return self._esc_holds_key
+
async def _esc_watch(self) -> None:
"""Armed only while ≥1 CU mission runs; Esc cancels them all."""
+ # This task's own handshake: a replaced task finishing late must not
+ # flip the state of its successor.
+ ready = self._esc_ready
+ me = asyncio.current_task()
try:
from jarvis.trigger.hotkey import HotkeyTrigger # noqa: PLC0415
@@ -500,6 +537,18 @@ class CUIndicatorController:
# itself is typing/clicking.
trigger = HotkeyTrigger({"cu_cancel": _esc_binding()})
async with trigger:
+ # ``None`` = the backend cannot say (Windows, Linux): keep the
+ # pill, as before. ``False`` = no listener exists (the macOS
+ # tap without Input Monitoring, the no-op backend, no backend
+ # at all): never promise the key.
+ self._esc_holds_key = trigger.listening() is not False
+ if not self._esc_holds_key:
+ log.info(
+ "[cu-indicator] Escape-to-cancel is off: the global key "
+ "listener is not running (macOS Input Monitoring is not "
+ "allowed). Cancel via voice or the tray."
+ )
+ ready.set()
async for event_name in trigger.events():
if event_name != "cu_cancel":
continue
@@ -517,6 +566,12 @@ class CUIndicatorController:
"[cu-indicator] Escape listener failed — cancel via voice/"
"tray/kill-hotkey still works.", exc_info=True,
)
+ finally:
+ # Whatever happened, release a pill that is waiting on the answer;
+ # the key is no longer held once this listener is gone.
+ ready.set()
+ if self._esc_task is me:
+ self._esc_holds_key = False
@staticmethod
def _cancel_all_missions() -> None:
diff --git a/jarvis/cu/system_dialogs.py b/jarvis/cu/system_dialogs.py
new file mode 100644
index 0000000000..7092ae97d7
--- /dev/null
+++ b/jarvis/cu/system_dialogs.py
@@ -0,0 +1,269 @@
+"""macOS system consent surfaces that an AI agent must never answer (P9).
+
+A permission prompt, an authorization sheet or a Touch ID request is a decision
+that belongs to the person at the keyboard. The computer-use engine therefore
+refuses to dispatch ANY action while one of these windows is frontmost, and
+dictation never sends a keystroke into one: the mission stops with the stable
+reason code ``blocked_permission`` and the person answers the dialog.
+
+This module is data plus one pure matcher. Nothing is imported at module scope
+that a headless host lacks, and nothing runs at import time (AP-26). The owner
+list is UNVERIFIED: nobody can run macOS in the development sandbox, the names
+are the owning process names (``kCGWindowOwnerName``) that community write-ups
+and this repo's own bug history report for these dialogs, and macOS versions
+move them around. A miss only means the guard stays quiet for that dialog; the
+other layers (the prohibitive agent text, the Accessibility grant itself) are
+unchanged.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from collections.abc import Callable, Mapping, Sequence
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+#: The ``<token>`` in ``[permission_needed:<token>] `` when the block is a system
+#: dialog on screen rather than a missing permission.
+SYSTEM_DIALOG_BLOCK: Final = "system_dialog"
+
+#: Owner process names of windows that ask the person for a system-level consent,
+#: casefolded (UNVERIFIED, see the module docstring). ``UserNotificationCenter``
+#: and ``universalaccessd`` show the privacy prompts (Accessibility, Screen
+#: Recording, Input Monitoring, ...); ``SecurityAgent``, ``authorizationhost`` and
+#: ``coreautha`` show password and Touch ID authorization; ``CoreServicesUIAgent``
+#: shows the Gatekeeper "downloaded from the internet" confirmation.
+SYSTEM_CONSENT_OWNERS: Final[frozenset[str]] = frozenset(
+ {
+ "usernotificationcenter",
+ "universalaccessd",
+ "securityagent",
+ "authorizationhost",
+ "coreautha",
+ "coreservicesuiagent",
+ }
+)
+
+#: System Settings is only a consent surface while it shows a privacy pane (the
+#: pane where the person flips the switch), not for every Settings window: a
+#: mission that was asked to change the wallpaper must still work. The match is
+#: on the window title, which needs Screen Recording (the engine only dispatches
+#: with it), so a title the OS withholds simply does not match (UNVERIFIED).
+SYSTEM_SETTINGS_OWNERS: Final[frozenset[str]] = frozenset({"system settings", "system preferences"})
+#: The owner NAME is probably localized on a non-English Mac (UNVERIFIED), so System
+#: Settings is also recognised by the bundle id of the owning process.
+SYSTEM_SETTINGS_BUNDLE_IDS: Final[frozenset[str]] = frozenset({"com.apple.systempreferences"})
+_PRIVACY_PANE_TITLE_TOKENS: Final[tuple[str, ...]] = (
+ "privacy",
+ "accessibility",
+ "screen recording",
+ "screen & system audio",
+ "input monitoring",
+ "microphone",
+ "automation",
+ "full disk access",
+ "camera",
+ "files & folders",
+ "developer tools",
+ "app management",
+ "contacts",
+ "calendars",
+ "reminders",
+ "photos",
+ "location services",
+ "local network",
+ "speech recognition",
+ "datenschutz", # i18n-allow: macOS pane title
+ "bedienungshilfen", # i18n-allow: macOS pane title
+ "bildschirmaufnahme", # i18n-allow: macOS pane title
+ "eingabeüberwachung", # i18n-allow: macOS pane title
+ "mikrofon", # i18n-allow: macOS pane title
+ "automatisierung", # i18n-allow: macOS pane title
+ "kamera", # i18n-allow: macOS pane title
+ "dateien und ordner", # i18n-allow: macOS pane title
+ "entwicklerwerkzeuge", # i18n-allow: macOS pane title
+ "kontakte", # i18n-allow: macOS pane title
+ "ortungsdienste", # i18n-allow: macOS pane title
+ "privacidad", # i18n-allow: macOS pane title
+ "accesibilidad", # i18n-allow: macOS pane title
+ "grabación de pantalla", # i18n-allow: macOS pane title
+ "cámara", # i18n-allow: macOS pane title
+ "archivos y carpetas", # i18n-allow: macOS pane title
+ "herramientas de desarrollo", # i18n-allow: macOS pane title
+ "contactos", # i18n-allow: macOS pane title
+ "localización", # i18n-allow: macOS pane title
+)
+
+#: Windows that sit above everything but are never a consent dialog and must not
+#: hide one that is behind them in the front-to-back list: the menu bar, the Dock,
+#: status items and notification banners.
+_CHROME_OWNERS: Final[frozenset[str]] = frozenset(
+ {
+ "window server",
+ "dock",
+ "systemuiserver",
+ "control center",
+ "notification center",
+ "notificationcenter",
+ "spotlight",
+ }
+)
+
+WindowLister = Callable[[], Sequence[Mapping[str, Any]]]
+
+
+def _title_names_privacy_pane(title: str) -> bool:
+ lowered = (title or "").casefold()
+ return any(token in lowered for token in _PRIVACY_PANE_TITLE_TOKENS)
+
+
+def is_system_consent_window(owner: str, title: str = "", bundle_id: str = "") -> bool:
+ """Whether a window of this owner (and title) is a system consent surface.
+
+ ``bundle_id`` is the bundle id of the owning process when the caller knows it:
+ System Settings is recognised by it even when its localized owner name is not
+ in :data:`SYSTEM_SETTINGS_OWNERS`.
+ """
+ name = (owner or "").strip().casefold()
+ if name in SYSTEM_CONSENT_OWNERS:
+ return True
+ if name in SYSTEM_SETTINGS_OWNERS or (bundle_id or "").strip() in SYSTEM_SETTINGS_BUNDLE_IDS:
+ return _title_names_privacy_pane(title)
+ return False
+
+
+def _bundle_id_of_pid(pid: int) -> str:
+ """The bundle id of a running process, else ``""`` (macOS only; the import is lazy)."""
+ try:
+ from AppKit import NSRunningApplication # type: ignore[import-not-found] # noqa: PLC0415
+
+ app = NSRunningApplication.runningApplicationWithProcessIdentifier_(int(pid))
+ return str(app.bundleIdentifier() or "") if app is not None else ""
+ except Exception: # noqa: BLE001 - no AppKit or no such process: the owner name decides alone
+ log.debug("The bundle id of a window owner could not be read.", exc_info=True)
+ return ""
+
+
+def _quartz_on_screen_windows() -> Sequence[Mapping[str, Any]]:
+ """The on-screen windows, front to back (macOS only; the import is lazy)."""
+ import Quartz # type: ignore[import-not-found] # noqa: PLC0415
+
+ options = Quartz.kCGWindowListOptionOnScreenOnly | Quartz.kCGWindowListExcludeDesktopElements
+ return list(Quartz.CGWindowListCopyWindowInfo(options, Quartz.kCGNullWindowID) or [])
+
+
+def _is_visible_surface(entry: Mapping[str, Any]) -> bool:
+ """A window that can actually be seen: not fully transparent, not a 1-px sliver."""
+ try:
+ if float(entry.get("kCGWindowAlpha", 1.0) or 0.0) <= 0.0:
+ return False
+ bounds = entry.get("kCGWindowBounds") or {}
+ return float(bounds.get("Width", 2) or 0) > 1 and float(bounds.get("Height", 2) or 0) > 1
+ except (TypeError, ValueError, AttributeError):
+ # A malformed entry is treated as visible: a dialog must never be skipped
+ # because its geometry could not be read.
+ log.debug("A window entry has unreadable geometry or alpha.", exc_info=True)
+ return True
+
+
+def _is_own_window(entry: Mapping[str, Any], own_pid: int) -> bool:
+ """A window of this very process (Jarvis's own overlays, cursor and pill)."""
+ try:
+ return int(entry.get("kCGWindowOwnerPID", -1)) == own_pid
+ except (TypeError, ValueError):
+ # Not provably ours, so it stays in the scan: a dialog must not be skipped.
+ log.debug("A window entry has an unreadable owner pid.", exc_info=True)
+ return False
+
+
+def _is_normal_window(entry: Mapping[str, Any]) -> bool:
+ """A window on the ordinary application layer (0). A missing layer reads as 0."""
+ try:
+ return int(entry.get("kCGWindowLayer", 0) or 0) == 0
+ except (TypeError, ValueError):
+ log.debug("A window entry has an unreadable layer; treated as normal.", exc_info=True)
+ return True
+
+
+def frontmost_consent_owner(
+ window_lister: WindowLister | None = None,
+ bundle_lookup: Callable[[int], str] | None = None,
+) -> str:
+ """The owner of a system consent surface that is in front of every normal window, else ``""``.
+
+ macOS only: the caller decides the platform (the engine calls this on darwin
+ only). The window list is ordered front to back. Menu-bar, Dock and
+ notification windows, invisible slivers and Jarvis's OWN windows (the orb
+ overlay, the virtual cursor, the Esc pill: always-on-top, so they would mask a
+ dialog behind them) are skipped. The scan then walks the whole prefix of
+ floating windows (layer above 0, other apps' overlays included) and reports the
+ first consent surface in it; the first normal application window (layer 0) of
+ another app ends the scan with ``""``, because a normal window in front means
+ the person already moved on. An unreadable list answers ``""`` (fail open, with
+ a debug line): a failed probe must not stop every mission, and a missing consent
+ dialog is the case the prohibitive agent text and the grant itself still cover.
+ UNVERIFIED on a real Mac: the real window levels of the consent dialogs. A window
+ whose title names a privacy pane is also looked up by the bundle id of its owner
+ (``bundle_lookup``, default AppKit), so a localized System Settings name still
+ matches.
+ """
+ lister = window_lister or _quartz_on_screen_windows
+ lookup = bundle_lookup or _bundle_id_of_pid
+ try:
+ entries = lister()
+ except Exception: # noqa: BLE001 - an unreadable window list is "no dialog seen"
+ log.debug("The on-screen window list could not be read.", exc_info=True)
+ return ""
+ own_pid = os.getpid()
+ for entry in entries:
+ owner = str(entry.get("kCGWindowOwnerName") or "")
+ if owner.strip().casefold() in _CHROME_OWNERS or not _is_visible_surface(entry):
+ continue
+ if _is_own_window(entry, own_pid):
+ continue
+ title = str(entry.get("kCGWindowName") or "")
+ bundle_id = ""
+ if _title_names_privacy_pane(title):
+ try:
+ bundle_id = lookup(int(entry.get("kCGWindowOwnerPID", -1)))
+ except Exception: # noqa: BLE001 - a failed lookup leaves the owner name to decide
+ log.debug("The owner bundle id lookup failed.", exc_info=True)
+ if is_system_consent_window(owner, title, bundle_id):
+ return owner
+ if _is_normal_window(entry):
+ return ""
+ return ""
+
+
+def agent_detail() -> str:
+ """The prohibitive sentence for an LLM tool error while a system dialog is open."""
+ return (
+ f"[permission_needed:{SYSTEM_DIALOG_BLOCK}] This action cannot run: a macOS system "
+ "dialog is open on screen and only the user may answer it. You must not try to "
+ "answer, click or dismiss any macOS system dialog yourself, you must not retry "
+ "this action, and you must not look for a workaround. Tell the user to answer "
+ "the dialog and stop."
+ )
+
+
+def user_detail() -> str:
+ """The sentence for people: fixed template, no window title, no owner name."""
+ return (
+ "A macOS system dialog is open. Personal Jarvis never answers system dialogs "
+ "for you: answer it yourself, then try the task again."
+ )
+
+
+__all__ = [
+ "SYSTEM_CONSENT_OWNERS",
+ "SYSTEM_DIALOG_BLOCK",
+ "SYSTEM_SETTINGS_BUNDLE_IDS",
+ "SYSTEM_SETTINGS_OWNERS",
+ "WindowLister",
+ "agent_detail",
+ "frontmost_consent_owner",
+ "is_system_consent_window",
+ "user_detail",
+]
diff --git a/jarvis/dictation/insert.py b/jarvis/dictation/insert.py
index dd2e1e6cb2..8d253fba14 100644
--- a/jarvis/dictation/insert.py
+++ b/jarvis/dictation/insert.py
@@ -428,6 +428,110 @@ def insert_text(
_INSERT_LOCK.release()
+#: Set when macOS may only just have started honouring synthetic keystrokes for
+#: this process: Accessibility was refused for a paste earlier in this process, or
+#: the permission layer reported a grant while an episode was open. Whether an
+#: in-process grant takes effect for already-running event posting is UNVERIFIED
+#: (the evidence conflicts), and on macOS delivery can never be observed, so the
+#: FIRST paste afterwards reports ``paste_sent`` and keeps the transcript on the
+#: clipboard instead of claiming ``inserted`` and restoring over it.
+_FIRST_PASTE_AFTER_GRANT = threading.Event()
+_PASTE_PERMISSION_FALLBACK = (
+ "Personal Jarvis needs Accessibility access to paste into other apps."
+)
+_grant_listener_gate: object | None = None
+
+
+def _permission_gate():
+ """The permission layer (``PermissionGate``); a test replaces this seam."""
+ from jarvis.platform.permission_service import get_permission_service # noqa: PLC0415
+
+ return get_permission_service()
+
+
+def _watch_for_grant(gate: object) -> None:
+ """Flag the first paste after an in-process Accessibility grant (once per gate)."""
+ global _grant_listener_gate
+ if _grant_listener_gate is gate:
+ return
+ add_listener = getattr(gate, "add_listener", None)
+ if add_listener is None:
+ return
+ from jarvis.platform.permissions import PermissionId # noqa: PLC0415
+
+ try:
+ add_listener(PermissionId.ACCESSIBILITY, _FIRST_PASTE_AFTER_GRANT.set)
+ except Exception: # noqa: BLE001 - the flag is advisory; a paste must not fail on it
+ log.debug("could not watch for the Accessibility grant", exc_info=True)
+ return
+ _grant_listener_gate = gate
+
+
+def _macos_paste_refusal() -> str:
+ """``""`` when Jarvis may send the paste keystroke, else a sentence for the PERSON.
+
+ macOS only (every other host answers ``""`` without touching the permission
+ layer). The first paste asks macOS for Accessibility (``wait_s=0``: the
+ dialog is answered later and the text waits on the clipboard); only a live
+ GRANTED sends a keystroke. The sentence is the service's ``user_detail`` (a
+ fixed template, never the agent-facing text, never an exception message).
+ """
+ if sys.platform != "darwin":
+ return ""
+ from jarvis.platform.permissions import PermissionId # noqa: PLC0415
+
+ gate = _permission_gate()
+ _watch_for_grant(gate)
+ result = gate.ensure(PermissionId.ACCESSIBILITY, feature="dictation_insert", wait_s=0.0)
+ if result.granted:
+ return ""
+ _FIRST_PASTE_AFTER_GRANT.set()
+ return result.user_detail or _PASTE_PERMISSION_FALLBACK
+
+
+def _macos_dialog_block_reason() -> str:
+ """A sentence when a macOS system dialog is frontmost, else ``""``.
+
+ Nothing is sent while a consent or authorization dialog could be in front: a
+ Return, or any key, must never answer one (P9). This module never appends a
+ Return itself; a recorded custom paste chord may contain one, which is why the
+ guard covers every chord.
+ """
+ try:
+ from jarvis.cu import system_dialogs # noqa: PLC0415
+
+ owner = system_dialogs.frontmost_consent_owner()
+ except Exception: # noqa: BLE001 - an unreadable window list is "no dialog seen"
+ log.debug("could not check for a frontmost system dialog", exc_info=True)
+ return ""
+ if not owner:
+ return ""
+ return (
+ "A macOS system dialog is open, so nothing was typed into it. The text is on "
+ "your clipboard; paste it once the dialog is closed."
+ )
+
+
+def _first_paste_after_grant_result(
+ *, parked: bool, method: str, chord_name: str
+) -> InsertResult | None:
+ """The honest ``paste_sent`` for the first paste after an in-process grant, once."""
+ if not _FIRST_PASTE_AFTER_GRANT.is_set():
+ return None
+ _FIRST_PASTE_AFTER_GRANT.clear()
+ return InsertResult(
+ status="paste_sent",
+ detail=(
+ "The paste was sent right after macOS allowed Personal Jarvis to control "
+ "the keyboard. If no text appeared, paste it from your clipboard or "
+ "dictation history."
+ ),
+ clipboard_holds_text=parked,
+ method=method or f"clipboard+{chord_name}",
+ clipboard_restored=False,
+ )
+
+
def _insert_text(
text: str,
*,
@@ -520,12 +624,30 @@ def _insert_text(
clipboard_holds_text=parked,
)
+ refusal = _macos_paste_refusal()
+ if refusal:
+ # macOS has not (yet) allowed keystrokes: nothing is sent, the text stays
+ # on the clipboard (the honest fallback) and the person is told why.
+ return InsertResult(
+ status="clipboard_only" if parked else "unavailable",
+ detail=f"{refusal} The text is on your clipboard — paste it where you want it.",
+ clipboard_holds_text=parked,
+ )
+
try:
actuator = get_actuator()
except Exception as exc: # noqa: BLE001 — ActuationUnavailable + anything else
+ # A permission refusal carries the PERSON's sentence; ``str(exc)`` is the
+ # agent-facing text and must never be shown to a user.
+ from jarvis.cu.actuate.base import PermissionNeededError # noqa: PLC0415
+
+ if isinstance(exc, PermissionNeededError):
+ shown = getattr(exc.result, "user_detail", "") or _PASTE_PERMISSION_FALLBACK
+ else:
+ shown = str(exc)
return InsertResult(
status="clipboard_only" if parked else "unavailable",
- detail=(f"{exc} The text is on your clipboard — paste it where you want it."),
+ detail=(f"{shown} The text is on your clipboard — paste it where you want it."),
clipboard_holds_text=parked,
)
@@ -545,6 +667,9 @@ def _insert_text(
),
clipboard_holds_text=parked,
)
+ first = _first_paste_after_grant_result(parked=parked, method="type", chord_name="")
+ if first is not None:
+ return first
restored = (
_restore(clipboard, previous)
if restore_clipboard and _clipboard_still_holds(clipboard, text)
@@ -596,6 +721,12 @@ def _insert_text(
# snatches the text away before the target app has read it.
time.sleep(delay_after_ms / 1000.0)
+ first = _first_paste_after_grant_result(
+ parked=parked, method=f"clipboard+{chord_name}", chord_name=chord_name
+ )
+ if first is not None:
+ return first
+
if os.name == "nt" or not paste_chord_is_curated(chord_name):
# Without Windows rendering evidence, or with an arbitrary recorded
# chord, sending input does not establish that the field pasted it.
@@ -673,6 +804,10 @@ def _foreground_target() -> tuple[int, int] | None:
def _input_block_reason(target: tuple[int, int] | None) -> str:
"""Do not send a chord to a changed window or with physically held modifiers."""
+ if sys.platform == "darwin":
+ # No foreground-target or held-key probe exists on macOS; the one thing
+ # to refuse is a keystroke while a system dialog could be answering it.
+ return _macos_dialog_block_reason()
if os.name != "nt" or sys.platform != "win32":
return ""
if target is not None and _foreground_target() != target:
diff --git a/jarvis/platform/permission_service.py b/jarvis/platform/permission_service.py
new file mode 100644
index 0000000000..9bc7c55088
--- /dev/null
+++ b/jarvis/platform/permission_service.py
@@ -0,0 +1,2763 @@
+"""Just-in-time macOS permissions: ask when a feature first needs the access.
+
+This is the layer between the features (voice, dictation, computer use, screen
+capture, global shortcuts, audio ducking) and ``SystemPermissionPort``, the OS
+adapter. A feature calls :meth:`PermissionService.ensure` at the moment a user
+gesture needs a permission. The service asks macOS through the port, never
+refuses an action because OUR OWN preflight said "not granted" before the OS was
+asked, and never lets an action proceed on anything but a live grant
+(``EnsureResult.granted`` is true only for GRANTED and NOT_REQUIRED). A denial
+degrades that one feature honestly; nothing is asked at launch and nothing nags.
+
+THREADING RULE (read before calling)
+
+* The tap callback, any event-loop callback and any Tk callback call
+ :meth:`check` only. It is lock-free, silent, never prompts and never publishes.
+* ``ensure(wait_s > 0)`` blocks the calling thread: call it from a WORKER thread
+ only. A loop caller uses :meth:`ensure_async`, which makes ONE ``to_thread``
+ call for the native request and then ``await asyncio.sleep`` polls, so a wait
+ never pins an executor worker; or it passes ``wait_s=0`` (the request is made,
+ the answer arrives later through :class:`PermissionResolved`). Even
+ ``ensure(wait_s=0)`` from a loop thread stays cheap: it never runs the
+ window-title oracle there and never waits for an Automation probe.
+* Nothing here raises for a native failure: every one becomes UNAVAILABLE with a
+ fixed-template sentence and a debug log. The one exception is a programming
+ error, an unknown permission id (``ValueError``).
+* The service lock guards ONLY dictionary mutation. A native call, a poll, a
+ publish, a listener call and a log line never run under it.
+* Automation is the one permission whose state read can HANG (Apple forums
+ thread 666528: ``AEDeterminePermissionToAutomateTarget`` for a running player
+ without a window) and whose request blocks for as long as a dialog is open. Both
+ therefore run on daemon threads: every Automation read goes through
+ :class:`_AutomationGuard` (a hard timeout, one call in flight per player, a
+ quarantine after a timeout), and the Automation request runs on its own daemon
+ thread, so ``ensure`` answers PENDING at once and the answer arrives through
+ :class:`PermissionResolved`. On an event-loop thread an Automation read never
+ waits at all.
+
+EPISODES
+
+An episode is one coalesced "feature X is waiting on permissions Y". A feature
+has at most one open record per permission regardless of ``wait_s``: a call that
+overlaps an open episode of the same feature joins it (so granting one member of a
+coalesced pair never opens a second record), and a retry loop that re-enters inside
+an episode gets PENDING with ``asked=False`` and never a second native request.
+At most ONE native request is made per permission per episode, and a per-process
+cooldown (Accessibility and Input Monitoring: once per 10 minutes, Screen
+Recording: once per process, the OS dialog class: while a dialog may still be
+open) covers the retries across episodes. An explicit click (``force_ask``) skips
+that cooldown and the per-episode rule for the PROMPT-ONCE permissions, never a
+denial and never a DIALOG-class dialog that may still be open. There is NO
+persisted "asked" memory: it would resurrect the dead end after ``tccutil reset``, a
+re-sign or another bundle id (BUG-083). An episode ends when every permission it
+needs is granted (``PermissionResolved(granted=True)``), or when nobody touched it
+for ten minutes (``PermissionResolved(granted=False)``: it is closed unresolved, the
+permission was still not granted at the last read). Each state is published once per
+episode, except that a USER gesture landing on a still-open episode re-announces it
+(at most once per ``_REANNOUNCE_MIN_S``): the toast the person dismissed, or that
+fired into a hidden window, comes back on their next try instead of staying lost
+until the grant.
+
+The EPISODE WATCHER (an asyncio task when :meth:`attach_bus` gave the service a
+loop, else one daemon thread) polls the open permissions every two seconds,
+publishes the edges, calls the listeners and stops when nothing is open. Listeners
+(:meth:`add_listener`) are zero-argument callables run when ONE permission turns
+granted inside an open episode. With a loop attached they run ON that loop's
+thread (so a consumer can set an ``asyncio.Event``); without one they run on the
+thread that observed the edge. They must be cheap and must not raise.
+
+Boot: construction does no I/O, no pyobjc/framework is imported here and the
+process singleton is lazy (AP-26). Off macOS ``ensure`` returns NOT_REQUIRED
+before the port is asked for anything. Every macOS behaviour that Apple does not
+document stays labelled unverified where it is relied on.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import math
+import threading
+import time
+from collections.abc import Callable, Iterable, Sequence
+from dataclasses import dataclass, field
+from enum import StrEnum
+from typing import Any, Final
+from uuid import UUID, uuid4
+
+from jarvis.core.events import (
+ PERMISSION_FEATURES,
+ PERMISSION_NEEDED_ORIGINS,
+ PermissionNeeded,
+ PermissionResolved,
+)
+from jarvis.platform import permissions as _permissions_module
+from jarvis.platform.permissions import (
+ APP_NAME,
+ AUTOMATION_TARGETS,
+ PANE_FAMILY,
+ REQUEST_CLASS,
+ SETTINGS_PATH_TEXT,
+ PermissionId,
+ PermissionState,
+ RequestClass,
+)
+
+log = logging.getLogger(__name__)
+
+_SOURCE_LAYER: Final = "platform.permission_service"
+
+# check() cache. A grant is cached briefly so a hot path (a capture loop, the
+# watchdog tick) does not pay a native read per call; a negative is cached for a
+# quarter of a second only, so a grant the user just gave is seen almost at once.
+_GRANTED_TTL_S: Final = 1.0
+_NEGATIVE_TTL_S: Final = 0.25
+
+# How often a waiting ensure() re-reads the state (the contract says 250 ms).
+_POLL_S: Final = 0.25
+# How often the episode watcher re-reads the open permissions.
+_WATCH_INTERVAL_S: Final = 2.0
+# An episode nobody touched for this long is closed without a grant.
+_EPISODE_TTL_S: Final = 600.0
+# A user gesture that lands on an episode which is still open re-announces it (the
+# toast the person dismissed or missed would otherwise never come back until the
+# grant). At most once per this window, so a retry loop of one gesture never floods.
+_REANNOUNCE_MIN_S: Final = 10.0
+# A PROMPT-ONCE dialog only offers "Open System Settings" (community-observed,
+# UNVERIFIED): once this long has passed since the request (or the app was
+# refocused) and the switch is still off, the user is "blocked" on Settings and
+# the app may show its toast. Both the 15 s and the 130 s below are our own
+# figures, not Apple's.
+_BLOCKED_AFTER_S: Final = 15.0
+# A DIALOG-class dialog (microphone, automation) that has been open this long
+# without an answer stops being "macOS is asking" and turns "blocked", so a
+# dialog the user ignored never leaves the feature silently dead.
+_DIALOG_CEILING_S: Final = 130.0
+
+# The Screen Recording window-title oracle enumerates the on-screen windows. It
+# runs on a gesture entry (an interactive ensure) and, for an episode a gesture
+# opened, at most this often (or at once after an app refocus). Whether the
+# enumeration itself can trigger the macOS 15 "bypass the system picker" alert is
+# UNVERIFIED, hence the low cadence; the shallow preflight is read every pass.
+_ORACLE_EVERY_S: Final = 10.0
+
+# Automation reads: a hard timeout for one Apple Event probe, and how long a
+# target that did not answer is left alone afterwards. A watcher pass or a poll
+# waits only this long for a probe (a hung one must not stall the other
+# permissions), picking the answer up on the next pass.
+_AUTOMATION_READ_TIMEOUT_S: Final = 5.0
+_AUTOMATION_QUARANTINE_S: Final = 600.0
+_AUTOMATION_REFRESH_WAIT_S: Final = 0.25
+
+# After a native request FAILED (the call raised or the symbol was missing) a retry
+# loop must not hammer it: the next automatic attempt waits this long. An explicit
+# click is never held back, and a failure is not "asked once per process" any more.
+_FAILED_RETRY_S: Final = 30.0
+
+# Per-process cooldown between two native requests for one permission. The OS
+# dialog class keeps a request "in flight" for as long as its dialog may be open
+# (the Automation runner is killed after 120 s); Accessibility's prompt call can
+# re-show while untrusted, so we rate-limit it ourselves; Screen Recording shows
+# its request at most once per process (community-observed, UNVERIFIED: Apple
+# documents only the declaration of ``CGRequestScreenCaptureAccess``).
+_REASK_AFTER_S: Final[dict[PermissionId, float]] = {
+ PermissionId.MICROPHONE: 120.0,
+ PermissionId.AUTOMATION: 120.0,
+ PermissionId.SCREEN_RECORDING: math.inf,
+ PermissionId.ACCESSIBILITY: 600.0,
+ PermissionId.INPUT_MONITORING: 600.0,
+}
+
+# The permissions whose grant may only work after a restart, so a real failed
+# attempt can produce the ``restart_hint`` reason (see ``report_failed_use``).
+# Automation is deliberately NOT here: Apple Events are checked per send, so its
+# failed-use report (-1743 after a granted read) is ``needs_settings``, a different
+# reason with a different way out (``report_use_ok``).
+_RESTART_HINT_FAMILIES: Final = frozenset(
+ {PermissionId.SCREEN_RECORDING, PermissionId.INPUT_MONITORING}
+)
+
+_READY_STATES: Final = frozenset({PermissionState.GRANTED, PermissionState.NOT_REQUIRED})
+_UNDECIDED_STATES: Final = frozenset({PermissionState.NOT_DETERMINED, PermissionState.NOT_GRANTED})
+_DECIDED_STATES: Final = frozenset(
+ {PermissionState.GRANTED, PermissionState.DENIED, PermissionState.RESTRICTED}
+)
+_ASKABLE_CLASSES: Final = frozenset({RequestClass.DIALOG, RequestClass.PROMPT_ONCE})
+
+# The reason shown for a coalesced episode when its permissions disagree: the
+# first one in this order wins (the most final, least actionable-by-us first).
+_REASON_PRIORITY: Final = (
+ "restricted",
+ "unavailable",
+ "denied",
+ "needs_settings",
+ "restart_hint",
+ "not_determined",
+)
+
+_LABELS: Final[dict[PermissionId, str]] = {
+ PermissionId.MICROPHONE: "Microphone",
+ PermissionId.SCREEN_RECORDING: "Screen Recording",
+ PermissionId.ACCESSIBILITY: "Accessibility",
+ PermissionId.INPUT_MONITORING: "Input Monitoring",
+ PermissionId.EVENT_POSTING: "Accessibility",
+ PermissionId.AUTOMATION: "Automation",
+ PermissionId.CREDENTIAL_STORE: "Keychain",
+}
+
+
+# ----------------------------------------------------------------------
+# Public result types
+# ----------------------------------------------------------------------
+
+
+class PermissionOutcome(StrEnum):
+ """What an ``ensure`` call can tell its caller.
+
+ ``GRANTED`` / ``NOT_REQUIRED``
+ The caller may proceed. Nothing else ever lets it proceed.
+ ``PENDING``
+ Not decided yet and nothing blocks it for good: macOS may be showing its
+ dialog right now, or the feature has not been allowed to ask yet.
+ ``NEEDS_SETTINGS``
+ The user has to flip a switch in System Settings (or confirm the grantee
+ when Jarvis runs outside an installed app).
+ ``DENIED``
+ The user answered no. macOS will not ask again by itself.
+ ``UNAVAILABLE``
+ It cannot be asked for here (restricted by policy, no GUI session, a
+ missing framework or usage string, a failed native call).
+ """
+
+ GRANTED = "granted"
+ PENDING = "pending"
+ DENIED = "denied"
+ NEEDS_SETTINGS = "needs_settings"
+ UNAVAILABLE = "unavailable"
+ NOT_REQUIRED = "not_required"
+
+
+_PROCEED_OUTCOMES: Final = frozenset({PermissionOutcome.GRANTED, PermissionOutcome.NOT_REQUIRED})
+
+
+@dataclass(frozen=True, slots=True)
+class EnsureResult:
+ """The answer of one ``ensure`` call for one permission.
+
+ ``agent_detail`` is for an LLM tool error: prohibitive, starts with
+ ``[permission_needed:<permission>] `` and tells the model not to answer a
+ system dialog itself and not to retry (P9). ``user_detail`` is for people and
+ the UI: a full English sentence from fixed templates only, never exception
+ text, a path or a window title. Both are empty when the call may proceed.
+
+ ``reason``, ``can_prompt`` and ``can_open_settings`` mirror what the
+ ``PermissionNeeded`` event says, for a caller (a route answer, an inline
+ note) that has no bus. ``reason`` is empty when the call may proceed.
+ """
+
+ permission: PermissionId
+ outcome: PermissionOutcome
+ state: PermissionState
+ asked: bool
+ outside_installed_app: bool
+ agent_detail: str
+ user_detail: str
+ reason: str = ""
+ can_prompt: bool = False
+ can_open_settings: bool = False
+ target: str = ""
+
+ @property
+ def granted(self) -> bool:
+ """``True`` only for GRANTED and NOT_REQUIRED: the one way to proceed."""
+ return self.outcome in _PROCEED_OUTCOMES
+
+
+@dataclass(frozen=True, slots=True)
+class Episode:
+ """A read-only copy of one open episode (the server-side truth a UI hydrates from)."""
+
+ permissions: tuple[str, ...]
+ feature: str
+ reason: str
+ phase: str
+ origin: str
+ target: str
+ can_prompt: bool
+ can_open_settings: bool
+ outside_app: bool
+ detail: str
+ trace_id: str
+ opened_at_ns: int
+
+ def as_dict(self) -> dict[str, Any]:
+ """A JSON-friendly copy (the ``needed`` list of the status snapshot)."""
+ return {
+ "permissions": list(self.permissions),
+ "feature": self.feature,
+ "reason": self.reason,
+ "phase": self.phase,
+ "origin": self.origin,
+ "target": self.target,
+ "can_prompt": self.can_prompt,
+ "can_open_settings": self.can_open_settings,
+ "outside_app": self.outside_app,
+ "detail": self.detail,
+ "trace_id": self.trace_id,
+ "opened_at_ns": self.opened_at_ns,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class AppInfo:
+ """Who this process is to macOS, as the status snapshot reports it.
+
+ ``stable`` says "this is the installed app bundle under an accepted bundle id":
+ it decides who may RESET a permission, never who may act (design P6), and
+ ``outside_installed_app`` is its inverse on macOS. ``headless`` means no
+ desktop session was found. Off macOS there is no app bundle: the bundle fields
+ are empty, ``stable`` and ``outside_installed_app`` are ``False``.
+ """
+
+ platform: str
+ app_name: str
+ bundle_id: str | None
+ bundle_path: str | None
+ launched_as_bundle: bool
+ stable: bool
+ outside_installed_app: bool
+ headless: bool
+
+
+# ----------------------------------------------------------------------
+# Fixed-template sentences
+# ----------------------------------------------------------------------
+
+
+def _player_name(bundle_id: str) -> str | None:
+ for name, known in AUTOMATION_TARGETS:
+ if known == bundle_id:
+ return name
+ return None
+
+
+def _subject(family: PermissionId, target: str) -> str:
+ """``"Microphone access"``; ``"Automation access for Music"`` for a player."""
+ label = _LABELS[family]
+ if family is PermissionId.AUTOMATION:
+ name = _player_name(target)
+ if name is not None:
+ return f"{label} access for {name}"
+ return f"{label} access"
+
+
+def user_detail_for(
+ family: PermissionId,
+ reason: str,
+ *,
+ target: str = "",
+ asking: bool = False,
+ outside_app: bool = False,
+ launched_as_bundle: bool = False,
+ refused_use: bool = False,
+) -> str:
+ """The full English sentence about the situation: built from fixed templates only.
+
+ Never carries exception text, a filesystem path or a window title. The Settings
+ path it names comes from the fixed table in the port. ``asking`` means macOS
+ is showing (or may be showing) its own dialog right now. Agents read these
+ sentences too (``jarvis permissions status``), so each one states a fact about
+ the user's situation and none is an imperative aimed at the reader (P9).
+ ``launched_as_bundle`` tells a real ``.app`` run from the wrong place (a mounted
+ disk image: the grantee is Personal Jarvis itself) from a terminal or IDE run.
+ ``refused_use`` (Automation, ``needs_settings`` only) says the access READS as
+ allowed but a real Apple Event to the named player was refused anyway, so the
+ sentence does not claim the switch is off.
+ """
+ family = PANE_FAMILY[family]
+ subject = _subject(family, target)
+ pane = SETTINGS_PATH_TEXT.get(family)
+ where = f" in {pane}" if pane else ""
+ if outside_app:
+ if launched_as_bundle:
+ return (
+ "Personal Jarvis is running from outside its installed location, so "
+ f"macOS may record {subject} for this copy only. The user has to confirm "
+ "that to continue, or allow it in System Settings."
+ )
+ return (
+ "Personal Jarvis is not running as an installed app, so "
+ f"{subject} would be granted to the app that started it. The user has to "
+ "confirm that to continue, or allow it in System Settings."
+ )
+ if reason == "restricted":
+ return (
+ f"{subject} is restricted on this Mac by a profile or a parental control, "
+ "so Personal Jarvis cannot use it. This cannot be changed from the app."
+ )
+ if reason == "unavailable":
+ return f"Personal Jarvis cannot ask for {subject} in this session."
+ if reason == "denied":
+ return f"{subject} is turned off for Personal Jarvis. The user has to turn it on{where}."
+ if reason == "restart_hint":
+ return f"{subject} may only take effect after Personal Jarvis is quit and reopened."
+ if reason == "needs_settings":
+ player = _player_name(target) if family is PermissionId.AUTOMATION else None
+ if refused_use and player is not None:
+ return (
+ f"macOS refused an Apple event that Personal Jarvis sent to {player}, "
+ f"although {subject} reads as allowed. The user has to check that "
+ f"Personal Jarvis is switched on{where}."
+ )
+ if asking:
+ return (
+ f"macOS may be showing a dialog about {subject}. The user has to turn "
+ f"Personal Jarvis on{where}, then return to the app."
+ )
+ return f"{subject} is off for Personal Jarvis. The user has to turn it on{where}."
+ # not_determined
+ if asking:
+ return f"Waiting for the user to answer the macOS dialog about {subject}."
+ return f"Personal Jarvis needs {subject} for this feature and has not asked for it yet."
+
+
+def agent_detail_for(
+ family: PermissionId,
+ reason: str,
+ *,
+ target: str = "",
+ asking: bool = False,
+) -> str:
+ """The prohibitive sentence for an LLM tool error (P9).
+
+ It starts with ``[permission_needed:<permission>] `` so a consumer can map the
+ prefix to a terminal "blocked on permission" state, and it forbids the three
+ things a model might try: answering the system dialog itself, retrying, and
+ looking for a workaround.
+ """
+ family = PANE_FAMILY[family]
+ subject = _subject(family, target)
+ if reason == "restricted":
+ situation = f"{subject} is restricted by a device policy and cannot be allowed here."
+ elif reason == "unavailable":
+ situation = f"{subject} cannot be requested in this session."
+ elif reason == "denied":
+ situation = f"{subject} is turned off and the user has to turn it on in System Settings."
+ elif reason == "restart_hint":
+ situation = (
+ f"{subject} is allowed but does not work in this running app yet; "
+ "the user may have to quit and reopen Personal Jarvis."
+ )
+ elif asking:
+ situation = f"macOS is asking the user about {subject} right now."
+ else:
+ situation = f"{subject} has not been allowed yet and the user has to allow it."
+ return (
+ f"[permission_needed:{family.value}] This action cannot run: {situation} "
+ "You must not try to answer, click or dismiss any macOS system dialog yourself, "
+ "you must not retry this action, and you must not look for a workaround. "
+ "Tell the user that this feature needs the permission and stop."
+ )
+
+
+# ----------------------------------------------------------------------
+# Internal records
+# ----------------------------------------------------------------------
+
+_SlotKey = tuple[PermissionId, str]
+_EpisodeKey = tuple[str, tuple[tuple[str, str], ...]]
+
+
+@dataclass(frozen=True, slots=True)
+class _View:
+ """How one permission looks right now, in the vocabulary of events and results."""
+
+ outcome: PermissionOutcome
+ reason: str
+ phase: str
+ can_prompt: bool
+ can_open_settings: bool
+ outside: bool
+ # Only meaningful with ``outside``: the process IS a real ``.app``, run from the
+ # wrong place, so the grantee is Personal Jarvis itself and not a terminal.
+ outside_bundle: bool = False
+
+ @property
+ def asking(self) -> bool:
+ return self.phase == "os_dialog"
+
+
+@dataclass(slots=True)
+class _Slot:
+ """One permission inside an episode. Plain attribute writes; see the module docstring."""
+
+ family: PermissionId
+ target: str
+ probe: PermissionId
+ state: PermissionState = PermissionState.NOT_DETERMINED
+ # When THIS episode made the native request (monotonic), else None.
+ asked_at: float | None = None
+ # True: a native request was withheld because Jarvis is not the installed app.
+ outside: bool = False
+ # True: the permission cannot be asked for here (no usage string, a failed
+ # native call, an invalid target).
+ unavailable: bool = False
+ # True: the app was refocused after a PROMPT-ONCE request, so the user is
+ # known to have left the dialog.
+ promoted: bool = False
+ notified: bool = False
+ # With ``outside``: the process is a real bundle run from the wrong place.
+ outside_bundle: bool = False
+ # True while the Automation request runs on its own daemon thread (the dialog
+ # may be open); ``ask_done`` is set when that thread has finished.
+ asking: bool = False
+ ask_done: threading.Event | None = None
+ # True: a real attempt to USE the permission failed although the state reads
+ # granted (or the user came back from Settings and it still fails), so the
+ # honest advice is "quit and reopen" (:meth:`PermissionService.report_failed_use`).
+ restart_hint: bool = False
+ # True (Automation only): a real Apple Event to this player was refused with
+ # -1743 although the probe read GRANTED (:meth:`PermissionService.report_failed_use`).
+ # The probe is exactly what lied, so a granted read never clears it: only
+ # :meth:`PermissionService.report_use_ok` (a later send landed), ``note_reset``
+ # or the episode's ten minute TTL does.
+ refused_use: bool = False
+ # When the Screen Recording window-title oracle last ran for this slot.
+ deep_at: float | None = None
+
+ @property
+ def key(self) -> _SlotKey:
+ return (self.family, self.target)
+
+ @property
+ def failed_use(self) -> bool:
+ """A real use failed although the state may read granted: the slot stays open."""
+ return self.restart_hint or self.refused_use
+
+ def refused_while(self, state: PermissionState) -> bool:
+ """Whether the "refused although granted" view applies: flagged AND the probe reads granted.
+
+ A flagged slot whose state turned denied, restricted or undecided is described
+ by that state instead (the more specific and more actionable reason).
+ """
+ return self.refused_use and state in _READY_STATES
+
+
+@dataclass(slots=True)
+class _Episode:
+ """An open episode. Fields change only through the service."""
+
+ key: _EpisodeKey
+ feature: str
+ slots: dict[_SlotKey, _Slot]
+ origin: str
+ trace_id: UUID
+ opened_ns: int
+ touched: float
+ reason: str = ""
+ phase: str = ""
+ can_prompt: bool = False
+ can_open_settings: bool = False
+ outside_app: bool = False
+ detail: str = ""
+ published: set[tuple[Any, ...]] = field(default_factory=set)
+ # When the published set was last forgotten for a user gesture (or when the
+ # episode was opened): see ``_REANNOUNCE_MIN_S``.
+ announced_at: float = 0.0
+ closed: bool = False
+ # Callers of ``_start`` that have not finished their asks yet. While it is
+ # positive the episode is invisible (no event, not in ``outstanding``): its
+ # slots are not claimed yet, so a classify now would say "blocked, can_prompt"
+ # while the OS dialog is still being requested.
+ starting: int = 0
+
+
+@dataclass(slots=True)
+class _Item:
+ """One requested permission inside one ``ensure`` call."""
+
+ requested: PermissionId
+ family: PermissionId
+ target: str
+ state: PermissionState = PermissionState.NOT_DETERMINED
+ asked: bool = False
+ bad_target: bool = False
+ slot: _Slot | None = None
+
+ @property
+ def slot_key(self) -> _SlotKey:
+ return (self.family, self.target)
+
+
+@dataclass(slots=True)
+class _Plan:
+ items: list[_Item]
+ feature: str
+ interactive: bool
+ episode: _Episode | None = None
+ # An explicit user click: skips the per-process cooldown of PROMPT-ONCE asks.
+ force_ask: bool = False
+ # Whether this call may run the window-title oracle (a gesture entry that is
+ # not on an event-loop thread).
+ deep: bool = False
+
+
+@dataclass(frozen=True, slots=True)
+class _GuardRead:
+ """What one guarded Automation read produced.
+
+ ``kind`` is ``"value"`` (``state`` is the port's answer), ``"pending"`` (the
+ probe is still running; ``state`` is the last answer, or ``None``),
+ ``"quarantined"`` (a probe hung and the target is left alone) or ``"failed"``.
+ """
+
+ kind: str
+ state: PermissionState | None = None
+
+
+@dataclass(slots=True)
+class _GuardCall:
+ done: threading.Event
+ # Real time (``time.monotonic``) after which the call counts as hung.
+ deadline: float
+
+
+class _AutomationGuard:
+ """Runs every Automation state read on a daemon thread, with a hard timeout.
+
+ ``AEDeterminePermissionToAutomateTarget`` can hang for a running player that
+ has no window (Apple forums thread 666528, a DTS engineer called it a bug), and
+ a native call cannot be cancelled. So a read never runs on the caller's thread:
+ at most ONE call is in flight per target (a second reader joins it), a reader
+ waits at most ``wait_s`` (0 on an event loop), and a call that outlives
+ ``timeout_s`` quarantines its target for ``quarantine_s``: the target reads
+ "unknown" at once and no further thread is started for it, so a hung probe
+ never piles up threads and never stalls the other permissions. The hung thread
+ is simply abandoned; its late answer is discarded.
+ """
+
+ def __init__(
+ self, *, timeout_s: float, quarantine_s: float, clock: Callable[[], float]
+ ) -> None:
+ self._timeout_s = timeout_s
+ self._quarantine_s = quarantine_s
+ self._clock = clock
+ self._lock = threading.Lock()
+ self._inflight: dict[str, _GuardCall] = {}
+ self._quarantine: dict[str, float] = {}
+ self._last: dict[str, PermissionState] = {}
+ self._failed: set[str] = set()
+
+ @property
+ def timeout_s(self) -> float:
+ return self._timeout_s
+
+ def read(
+ self, target: str, probe: Callable[[], PermissionState], *, wait_s: float
+ ) -> _GuardRead:
+ now = self._clock()
+ with self._lock:
+ until = self._quarantine.get(target)
+ if until is not None:
+ if now < until:
+ return _GuardRead("quarantined")
+ del self._quarantine[target]
+ call = self._inflight.get(target)
+ if call is not None and call.done.is_set():
+ del self._inflight[target]
+ call = None
+ if call is not None and time.monotonic() >= call.deadline:
+ # The previous probe is still hung: do not start a second thread.
+ self._quarantine_locked(target, now)
+ return _GuardRead("quarantined")
+ if call is None:
+ call = _GuardCall(
+ done=threading.Event(), deadline=time.monotonic() + self._timeout_s
+ )
+ self._inflight[target] = call
+ self._failed.discard(target)
+ threading.Thread(
+ target=self._run,
+ args=(target, probe, call),
+ name="permission-automation-probe",
+ daemon=True,
+ ).start()
+ if wait_s > 0:
+ call.done.wait(min(wait_s, max(0.0, call.deadline - time.monotonic())))
+ with self._lock:
+ if call.done.is_set():
+ if self._inflight.get(target) is call:
+ del self._inflight[target]
+ if target in self._failed:
+ return _GuardRead("failed")
+ return _GuardRead("value", self._last.get(target))
+ if time.monotonic() >= call.deadline:
+ self._quarantine_locked(target, self._clock())
+ return _GuardRead("quarantined")
+ return _GuardRead("pending", self._last.get(target))
+
+ def _quarantine_locked(self, target: str, now: float) -> None:
+ self._quarantine[target] = now + self._quarantine_s
+ self._last.pop(target, None)
+ log.debug("The Automation probe for %s hung; it is left alone for a while.", target)
+
+ def _run(self, target: str, probe: Callable[[], PermissionState], call: _GuardCall) -> None:
+ try:
+ state = probe()
+ except Exception: # noqa: BLE001 - the thread must never die loudly; the reader reports it
+ log.debug("The Automation probe for %s failed.", target, exc_info=True)
+ with self._lock:
+ self._failed.add(target)
+ else:
+ with self._lock:
+ if target not in self._quarantine:
+ self._last[target] = state
+ finally:
+ call.done.set()
+
+ def forget(self) -> None:
+ """Drop every record (tests and process teardown)."""
+ with self._lock:
+ self._inflight.clear()
+ self._quarantine.clear()
+ self._last.clear()
+ self._failed.clear()
+
+
+# ----------------------------------------------------------------------
+# The service
+# ----------------------------------------------------------------------
+
+
+class PermissionService:
+ """Ask macOS for a permission when a feature needs it. See the module docstring."""
+
+ def __init__(
+ self,
+ *,
+ clock: Callable[[], float] = time.monotonic,
+ sleep: Callable[[float], None] = time.sleep,
+ poll_s: float = _POLL_S,
+ watch_interval_s: float = _WATCH_INTERVAL_S,
+ episode_ttl_s: float = _EPISODE_TTL_S,
+ granted_ttl_s: float = _GRANTED_TTL_S,
+ negative_ttl_s: float = _NEGATIVE_TTL_S,
+ automation_timeout_s: float = _AUTOMATION_READ_TIMEOUT_S,
+ automation_quarantine_s: float = _AUTOMATION_QUARANTINE_S,
+ automation_refresh_wait_s: float = _AUTOMATION_REFRESH_WAIT_S,
+ oracle_every_s: float = _ORACLE_EVERY_S,
+ ask_runner: Callable[[Callable[[], None]], None] | None = None,
+ ) -> None:
+ # Seams, so a test drives time without sleeping.
+ self._clock = clock
+ self._sleep = sleep
+ self._poll_s = poll_s
+ self._watch_interval_s = watch_interval_s
+ self._episode_ttl_s = episode_ttl_s
+ self._granted_ttl_s = granted_ttl_s
+ self._negative_ttl_s = negative_ttl_s
+ self._automation_refresh_wait_s = automation_refresh_wait_s
+ self._oracle_every_s = oracle_every_s
+ # Starts the Automation request off the calling thread (a daemon thread by
+ # default); a test injects a synchronous runner to keep the answer inline.
+ self._ask_runner = ask_runner if ask_runner is not None else _start_daemon_thread
+ self._automation = _AutomationGuard(
+ timeout_s=automation_timeout_s, quarantine_s=automation_quarantine_s, clock=clock
+ )
+
+ self._lock = threading.Lock()
+ # check() cache: immutable (state, expires_at) tuples, assigned whole, so
+ # a read needs no lock. ``_cache_gen`` counts invalidations: a read that
+ # started before one never stores its (possibly stale) answer.
+ self._cache: dict[tuple[PermissionId, str], tuple[PermissionState, float, bool]] = {}
+ self._cache_gen = 0
+ # True once the window-title oracle (or the preflight) proved Screen
+ # Recording granted in this process. The per-process-frozen preflight can
+ # only go stale NEGATIVE (BUG-161), so a proven grant must not flap back to
+ # "not granted" when the 1 s cache entry expires; only a capture error
+ # (:meth:`invalidate`), a reset or a deep read that finds no grant drops it.
+ self._sr_proven = False
+ # Ports whose ``state()`` takes no ``deep``/``target`` (a pre-JIT stub).
+ self._episodes: dict[_EpisodeKey, _Episode] = {}
+ # Per-process "last native request" stamps (the cooldown); never persisted.
+ self._last_native: dict[_SlotKey, float] = {}
+ # When a native request last FAILED, per slot (see ``_FAILED_RETRY_S``).
+ self._failed_native: dict[_SlotKey, float] = {}
+ self._listeners: dict[PermissionId, tuple[Callable[[], None], ...]] = {}
+ # (bus, loop) as ONE tuple so a reader never sees half of an attach.
+ self._sink: tuple[Any, asyncio.AbstractEventLoop] | None = None
+
+ self._watch_running = False
+ self._watch_kind = ""
+ self._watch_gen = 0
+ self._watch_thread: threading.Thread | None = None
+ self._watch_task: asyncio.Task[None] | None = None
+ self._watch_loop: asyncio.AbstractEventLoop | None = None
+ self._watch_stop = threading.Event()
+
+ # ------------------------------------------------------------ wiring
+
+ def attach_bus(self, bus: Any | None, loop: asyncio.AbstractEventLoop | None) -> None:
+ """Give the service the event bus and the loop that owns it.
+
+ Publishing goes through ``asyncio.run_coroutine_threadsafe`` and never
+ waits for the result. Without a bus the service still keeps its episode
+ registry and writes a debug line, and never raises. ``attach_bus(None,
+ None)`` detaches.
+ """
+ sink = (bus, loop) if bus is not None and loop is not None else None
+ with self._lock:
+ self._sink = sink
+
+ def _port(self) -> Any:
+ # Resolved per call and never cached, so a test stub applies at once.
+ return _permissions_module.get_system_permission_port()
+
+ def _call_state(
+ self, port: Any, perm: PermissionId, target: str, deep: bool
+ ) -> PermissionState:
+ """One ``port.state`` call, in the vocabulary the port understands."""
+ return PermissionState(port.state(perm, target=target or None, deep=deep))
+
+ @staticmethod
+ def _is_darwin(port: Any) -> bool:
+ platform = getattr(port, "platform", None)
+ if platform is None:
+ from jarvis.platform import detect_platform
+
+ platform = detect_platform()
+ return platform == "darwin"
+
+ # ------------------------------------------------------------- check
+
+ def check(
+ self, permission: PermissionId | str, *, target: str | None = None
+ ) -> PermissionState:
+ """The live state of one permission. Silent, lock-free, never prompts.
+
+ Safe from the event loop, a Tk callback and an event-tap callback. A
+ GRANTED answer is cached for about one second (bypassed on purpose by
+ :meth:`invalidate` after a capture error), a negative for about 250 ms.
+ Off macOS it answers NOT_REQUIRED without asking the port anything.
+
+ Screen Recording reads the preflight only, but an oracle-proven grant (an
+ ``ensure`` or the watcher saw it) is remembered, so it never flaps back to
+ "not granted" while the frozen preflight still says so. Automation needs a
+ ``target`` (without one it answers UNAVAILABLE: the aggregate read would
+ probe every player); its read runs on a guarded daemon thread, answers
+ UNAVAILABLE for a player whose probe hung, and on an event-loop thread never
+ waits (the last answer, else NOT_DETERMINED while the probe still runs).
+ """
+ perm = PermissionId(permission)
+ try:
+ port = self._port()
+ if not self._is_darwin(port):
+ return PermissionState.NOT_REQUIRED
+ return self._read_state(port, perm, target or "")
+ except Exception: # noqa: BLE001 - check() is called from hot paths and never raises
+ log.debug("Reading the %s permission failed.", perm.value, exc_info=True)
+ return PermissionState.UNAVAILABLE
+
+ def invalidate(self, permission: PermissionId | str | None = None) -> None:
+ """Forget the cached answer(s) so the next read goes to the OS.
+
+ Call it after a capture error that suggests the grant changed (a revoked
+ Screen Recording grant must not stay "granted" for another second). It also
+ drops the remembered Screen Recording proof, so the next deep read decides
+ again. A read already in flight when this runs never stores its answer.
+ """
+ self._cache_gen += 1
+ if permission is None:
+ self._cache = {}
+ self._sr_proven = False
+ return
+ perm = PermissionId(permission)
+ if PANE_FAMILY[perm] is PermissionId.SCREEN_RECORDING:
+ self._sr_proven = False
+ # dict.copy() is one C-level call, so it cannot see a concurrent insert
+ # half-way (iterating list(items()) of a dict another thread mutates can
+ # raise "dictionary changed size during iteration").
+ snapshot = self._cache.copy()
+ self._cache = {key: value for key, value in snapshot.items() if key[0] is not perm}
+
+ def check_deep(
+ self, permission: PermissionId | str, *, target: str | None = None
+ ) -> PermissionState:
+ """:meth:`check`, but fresh and with the Screen Recording window-title oracle.
+
+ The oracle sees a grant the per-process-frozen preflight still denies
+ (BUG-161) at the price of enumerating the on-screen windows, so this is for
+ a gesture route or a worker thread, never the event loop, a Tk callback or
+ an event tap. Never prompts, never raises.
+ """
+ perm = PermissionId(permission)
+ try:
+ port = self._port()
+ if not self._is_darwin(port):
+ return PermissionState.NOT_REQUIRED
+ return self._read_state(port, perm, target or "", fresh=True, deep=True)
+ except Exception: # noqa: BLE001 - a deep read is advisory and never raises
+ log.debug("Reading the %s permission (deep) failed.", perm.value, exc_info=True)
+ return PermissionState.UNAVAILABLE
+
+ def app_info(self) -> AppInfo:
+ """The identity block of the status snapshot. Never prompts, never raises.
+
+ On macOS it asks AppKit whether a desktop session exists, one window-server
+ round trip: a status route calls it, a hot path does not. A port that cannot
+ describe itself (a hand-written stub) reads as "no bundle, not stable".
+ """
+ port = self._port()
+ platform = str(getattr(port, "platform", "") or "")
+ if not platform:
+ from jarvis.platform import detect_platform
+
+ platform = detect_platform()
+ read_identity = getattr(port, "_app_identity", None)
+ try:
+ if read_identity is None:
+ raise AttributeError("the port has no identity reader")
+ identity, headless = read_identity()
+ except Exception: # noqa: BLE001 - the status snapshot degrades to "identity unknown"
+ log.debug("Reading the app identity failed.", exc_info=True)
+ return AppInfo(platform, APP_NAME, None, None, False, False, False, False)
+ return AppInfo(
+ platform=platform,
+ app_name=str(identity.app_name),
+ bundle_id=identity.bundle_id,
+ bundle_path=identity.bundle_path,
+ launched_as_bundle=bool(identity.launched_as_bundle),
+ stable=bool(identity.stable),
+ outside_installed_app=platform == "darwin" and self._outside_installed_app(port),
+ headless=bool(headless),
+ )
+
+ def can_request(
+ self,
+ permission: PermissionId | str,
+ state: PermissionState | None = None,
+ *,
+ target: str | None = None,
+ ) -> bool:
+ """Whether a gesture could make macOS show something for this permission now.
+
+ ``False`` for a permission that is already decided (granted, denied,
+ restricted, unavailable) and for one with no native request to make; a
+ denial is a stable state and macOS will not ask again. It does not look at
+ the installed-app verdict: outside the installed app an ask is still
+ possible after an explicit confirmation (:meth:`ensure` ``allow_outside_app``),
+ and it does not look at the per-process cooldown either: the "Allow" button
+ is an explicit click, and an explicit click (``force_ask``) skips the
+ cooldown of the PROMPT-ONCE permissions, so the button never does nothing.
+ """
+ perm = PermissionId(permission)
+ family = PANE_FAMILY[perm]
+ if REQUEST_CLASS.get(family) not in _ASKABLE_CLASSES:
+ return False
+ port = self._port()
+ if not self._is_darwin(port):
+ return False
+ if state is None and family is PermissionId.AUTOMATION and not target:
+ # Without a player the port would read every installed one and rewrite
+ # its consent record (the aggregate read); a caller names a player or
+ # hands the state it already has.
+ return False
+ current = state if state is not None else self.check(perm, target=target)
+ if current not in _UNDECIDED_STATES:
+ return False
+ return self._usage_string_ok(port, family)
+
+ def _read_state(
+ self,
+ port: Any,
+ perm: PermissionId,
+ target: str,
+ *,
+ fresh: bool = False,
+ deep: bool = False,
+ automation_wait_s: float | None = None,
+ ) -> PermissionState:
+ """One state read, through the cache unless ``fresh``.
+
+ ``deep`` adds the Screen Recording window-title oracle, which sees a grant
+ the per-process-frozen preflight still denies (BUG-161) but enumerates the
+ on-screen windows. Only a gesture entry or the watcher (never a hot path,
+ never the event loop) passes it; ``check()`` never does. An oracle-proven
+ grant is remembered (``_sr_proven``) so a SHALLOW read does not undo it; a
+ deep read is never answered from that memory (it decides, and a deep read
+ that finds no grant drops the proof).
+
+ Automation reads go through :class:`_AutomationGuard`; ``automation_wait_s``
+ is how long this call may wait for the probe (default: the guard's hard
+ timeout, and nothing at all on an event-loop thread).
+ """
+ key = (perm, target)
+ family = PANE_FAMILY[perm]
+ now = self._clock()
+ if family is PermissionId.AUTOMATION and not target:
+ # The aggregate read probes every running player and rewrites the
+ # consent record: a caller names a player.
+ return PermissionState.UNAVAILABLE
+ if not fresh:
+ entry = self._cache.get(key)
+ # A shallow negative must not answer a deep read: the oracle may know better.
+ if (
+ entry is not None
+ and entry[1] > now
+ and (entry[2] or not deep or entry[0] in _READY_STATES)
+ ):
+ return entry[0]
+ gen = self._cache_gen
+ if family is PermissionId.AUTOMATION:
+ wait = automation_wait_s
+ if wait is None:
+ wait = 0.0 if _on_event_loop_thread() else self._automation.timeout_s
+ got = self._automation.read(
+ target, lambda: self._call_state(port, perm, target, deep), wait_s=wait
+ )
+ if got.kind == "value" and got.state is not None:
+ state = got.state
+ elif got.kind == "pending":
+ # Still answering: the last answer, else "unknown" (the port's own
+ # reading of a player it cannot see). Not cached.
+ return got.state if got.state is not None else PermissionState.NOT_DETERMINED
+ else:
+ return PermissionState.UNAVAILABLE
+ else:
+ try:
+ state = self._call_state(port, perm, target, deep)
+ except Exception: # noqa: BLE001 - a native failure is "unavailable", never a crash
+ log.debug("The %s state read failed.", perm.value, exc_info=True)
+ state = PermissionState.UNAVAILABLE
+ if family is PermissionId.SCREEN_RECORDING and gen == self._cache_gen:
+ if state is PermissionState.GRANTED:
+ self._sr_proven = True
+ elif deep and state is not PermissionState.UNAVAILABLE:
+ # A deep read is the one that decides: the oracle had its chance and
+ # the preflight says no, so the remembered proof must not paper over
+ # a grant that was revoked since (the Computer-Use pre-dispatch gate
+ # reads deep to see exactly that). The oracle only ever proves
+ # positively, so "no readable window title" also lands here: the
+ # next shallow read then reports the honest negative and the next
+ # deep read that finds a titled window proves the grant again.
+ self._sr_proven = False
+ elif self._sr_proven and state in _UNDECIDED_STATES:
+ # Shallow read only: the frozen preflight can go stale negative
+ # (BUG-161), a proven grant must not flap back every second.
+ state = PermissionState.GRANTED
+ ttl = self._granted_ttl_s if state is PermissionState.GRANTED else self._negative_ttl_s
+ if gen == self._cache_gen:
+ self._cache[key] = (state, now + ttl, deep)
+ self._observe(perm, target, state)
+ return state
+
+ def _observe(self, perm: PermissionId, target: str, state: PermissionState) -> None:
+ """A decision for an OS-dialog permission ends its "request in flight" cooldown."""
+ family = PANE_FAMILY[perm]
+ key = (family, target if family is PermissionId.AUTOMATION else "")
+ if (
+ REQUEST_CLASS.get(family) is RequestClass.DIALOG
+ and state in _DECIDED_STATES
+ and key in self._last_native
+ ):
+ # One atomic dict operation, no lock: check() must stay lock-free (design
+ # 3.2 item 10), and a stamp a concurrent claim reads just before this is
+ # harmless (it only delays one re-ask).
+ self._last_native.pop(key, None)
+
+ def note_reset(self, permission: PermissionId | str, *, target: str | None = None) -> None:
+ """A ``tccutil reset`` happened: forget the per-process cooldown for it.
+
+ The route that resets a permission calls this so "Ask again" really asks.
+ An Automation reset without a ``target`` forgets every player (``tccutil``
+ resets the whole Apple Events row of the app).
+ """
+ perm = PermissionId(permission)
+ family = PANE_FAMILY[perm]
+ every_player = family is PermissionId.AUTOMATION and not target
+ key = (family, (target or "") if family is PermissionId.AUTOMATION else "")
+
+ def matches(slot_key: _SlotKey) -> bool:
+ return slot_key[0] is family if every_player else slot_key == key
+
+ with self._lock:
+ # ``_observe`` pops ``_last_native`` without this lock (check() is
+ # lock-free), so iterate a C-level copy, never the live dict.
+ for stamp_key in [k for k in self._last_native.copy() if matches(k)]:
+ self._last_native.pop(stamp_key, None)
+ for stamp_key in [k for k in self._failed_native.copy() if matches(k)]:
+ self._failed_native.pop(stamp_key, None)
+ # An episode that is still open remembers it already asked (one native
+ # request per permission per episode); after a reset that memory
+ # describes a decision macOS no longer has, so the next ensure may ask.
+ for episode in self._episodes.values():
+ for slot in episode.slots.values():
+ if matches(slot.key):
+ slot.asked_at = None
+ slot.restart_hint = False
+ slot.refused_use = False
+ slot.promoted = False
+ self.invalidate(perm)
+
+ # ------------------------------------------------------------ ensure
+
+ def ensure(
+ self,
+ permission: PermissionId | str,
+ *,
+ feature: str,
+ interactive: bool = True,
+ wait_s: float = 0.0,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ allow_outside_app: bool = False,
+ force_ask: bool = False,
+ ) -> EnsureResult:
+ """Make sure a permission is granted, asking macOS at most once per episode.
+
+ ``interactive=True`` (a user gesture) may make the native request;
+ ``interactive=False`` (a background consumer) never does and only records a
+ background-origin episode. ``wait_s`` > 0 waits for the answer in 250 ms
+ polls: WORKER THREADS ONLY (see the module docstring); 0 returns PENDING at
+ once. ``force_ask`` marks an explicit click on an "Allow" button: it skips
+ the per-process cooldown of the PROMPT-ONCE permissions (never the
+ per-episode single request, never a denial). Never raises for a native
+ failure.
+ """
+ return self.ensure_all(
+ [permission],
+ feature=feature,
+ interactive=interactive,
+ wait_s=wait_s,
+ target=target,
+ trace_id=trace_id,
+ allow_outside_app=allow_outside_app,
+ force_ask=force_ask,
+ )[0]
+
+ def ensure_all(
+ self,
+ permissions: Iterable[PermissionId | str],
+ *,
+ feature: str,
+ interactive: bool = True,
+ wait_s: float = 0.0,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ allow_outside_app: bool = False,
+ force_ask: bool = False,
+ ) -> list[EnsureResult]:
+ """``ensure`` for several permissions: ONE coalesced episode and ONE event.
+
+ Computer use needs Screen Recording and Accessibility together; the user
+ sees one prompt for the pair. The results come back in request order.
+ """
+ wanted = [PermissionId(item) for item in permissions]
+ tgt = _fixed_target(target)
+ try:
+ port = self._port()
+ if not self._is_darwin(port):
+ return [self._not_required(perm) for perm in wanted]
+ plan = self._start(
+ port,
+ wanted,
+ target or "",
+ feature,
+ interactive,
+ trace_id,
+ allow_outside_app,
+ force_ask,
+ )
+ if wait_s > 0 and interactive:
+ if _on_event_loop_thread():
+ # A synchronous wait here would freeze the loop for up to wait_s
+ # while the OS dialog is open: ensure_async is the loop's API.
+ log.debug("ensure(%s) waited on the event loop; not waiting.", feature)
+ else:
+ self._wait_sync(port, plan, wait_s)
+ return self._finish(plan)
+ except Exception: # noqa: BLE001 - ensure() never raises (contract)
+ log.debug("ensure(%s) failed.", feature, exc_info=True)
+ return [self._unavailable(perm, tgt) for perm in wanted]
+
+ async def ensure_async(
+ self,
+ permission: PermissionId | str,
+ *,
+ feature: str,
+ interactive: bool = True,
+ wait_s: float = 0.0,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ allow_outside_app: bool = False,
+ force_ask: bool = False,
+ ) -> EnsureResult:
+ """``ensure`` for the event loop: native async, never pins an executor worker.
+
+ The native request runs in ONE ``asyncio.to_thread`` call; the wait is
+ ``await asyncio.sleep`` polls, each of which reads the state on the loop
+ only when that read is cheap (a probe that can be slow, the window-title
+ oracle and Automation, takes one short thread hop instead).
+ """
+ results = await self.ensure_all_async(
+ [permission],
+ feature=feature,
+ interactive=interactive,
+ wait_s=wait_s,
+ target=target,
+ trace_id=trace_id,
+ allow_outside_app=allow_outside_app,
+ force_ask=force_ask,
+ )
+ return results[0]
+
+ async def ensure_all_async(
+ self,
+ permissions: Iterable[PermissionId | str],
+ *,
+ feature: str,
+ interactive: bool = True,
+ wait_s: float = 0.0,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ allow_outside_app: bool = False,
+ force_ask: bool = False,
+ ) -> list[EnsureResult]:
+ """The coalesced, loop-friendly form of :meth:`ensure_all`."""
+ wanted = [PermissionId(item) for item in permissions]
+ tgt = _fixed_target(target)
+ try:
+ port = self._port()
+ if not self._is_darwin(port):
+ return [self._not_required(perm) for perm in wanted]
+ args = (
+ port,
+ wanted,
+ target or "",
+ feature,
+ interactive,
+ trace_id,
+ allow_outside_app,
+ force_ask,
+ )
+ if self._all_ready_cheaply(port, wanted):
+ # Nothing to ask and no native call to make: no thread hop needed.
+ plan = self._start(*args)
+ else:
+ plan = await asyncio.to_thread(self._start, *args)
+ if wait_s > 0 and interactive:
+ deadline = self._clock() + wait_s
+ while self._waiting(plan):
+ remaining = deadline - self._clock()
+ if remaining <= 0:
+ break
+ await asyncio.sleep(min(self._poll_s, remaining))
+ if self._needs_thread_poll(plan):
+ # The window-title oracle enumerates windows and an
+ # Automation probe can be slow: one short thread hop per
+ # poll, never a worker held across the sleep.
+ await asyncio.to_thread(self._poll, port, plan)
+ else:
+ self._poll(port, plan)
+ return self._finish(plan)
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 - ensure() never raises (contract)
+ log.debug("ensure_async(%s) failed.", feature, exc_info=True)
+ return [self._unavailable(perm, tgt) for perm in wanted]
+
+ def _all_ready_cheaply(self, port: Any, wanted: Sequence[PermissionId]) -> bool:
+ """Whether every permission reads granted without a possibly slow probe.
+
+ Automation is excluded: its probe can hang for a running player, so it
+ never runs on the loop.
+ """
+ if not wanted or any(PANE_FAMILY[perm] is PermissionId.AUTOMATION for perm in wanted):
+ return False
+ return all(self._read_state(port, perm, "") in _READY_STATES for perm in wanted)
+
+ # ---- ensure: the shared core ------------------------------------------
+
+ def _start(
+ self,
+ port: Any,
+ wanted: Sequence[PermissionId],
+ target: str,
+ feature: str,
+ interactive: bool,
+ trace_id: UUID | str | None,
+ allow_outside_app: bool,
+ force_ask: bool = False,
+ ) -> _Plan:
+ """Read the states, open or join the episode, make the native request if allowed.
+
+ Blocking (it may call into the OS), so the async path runs it in a thread.
+ It never waits for an answer. The window-title oracle runs only for an
+ interactive call that is not on an event-loop thread: a background consumer
+ and a loop caller read the preflight alone.
+ """
+ if feature not in PERMISSION_FEATURES:
+ log.warning("ensure() was called with the unknown feature %r.", feature)
+ feature = ""
+ now = self._clock()
+ deep = interactive and not _on_event_loop_thread()
+ items: list[_Item] = []
+ for perm in wanted:
+ family = PANE_FAMILY[perm]
+ tgt = _fixed_target(target) if family is PermissionId.AUTOMATION else ""
+ item = _Item(requested=perm, family=family, target=tgt)
+ if family is PermissionId.AUTOMATION and not tgt:
+ # Only the fixed player table may be asked about (nothing else is
+ # ever interpolated into the consent script, echoed or published).
+ log.debug("Automation was requested for a target that is not a scriptable player.")
+ item.bad_target = True
+ item.state = PermissionState.UNAVAILABLE
+ else:
+ item.state = self._read_state(port, perm, tgt, deep=deep)
+ items.append(item)
+
+ plan = _Plan(
+ items=items, feature=feature, interactive=interactive, force_ask=force_ask, deep=deep
+ )
+ pending = [item for item in items if item.state not in _READY_STATES]
+ for item in items:
+ if item.state in _READY_STATES:
+ self._note_ready(item)
+ if not pending:
+ return plan
+
+ episode = self._open_episode(feature, pending, interactive, trace_id, now)
+ plan.episode = episode
+ try:
+ for item in pending:
+ item.slot = episode.slots[item.slot_key]
+ item.slot.state = item.state
+ item.slot.notified = False
+ if deep and item.family is PermissionId.SCREEN_RECORDING:
+ item.slot.deep_at = now
+ self._maybe_ask(port, plan, item, allow_outside_app, now)
+ finally:
+ with self._lock:
+ episode.starting -= 1
+ self._emit_episode(episode)
+ self._ensure_watcher()
+ return plan
+
+ def _maybe_ask(
+ self, port: Any, plan: _Plan, item: _Item, allow_outside_app: bool, now: float
+ ) -> None:
+ slot = item.slot
+ if slot is None or plan.episode is None:
+ return
+ if item.bad_target:
+ slot.unavailable = True
+ return
+ if item.state in (
+ PermissionState.RESTRICTED,
+ PermissionState.UNAVAILABLE,
+ PermissionState.DENIED,
+ ):
+ # A decision (or an impossibility) is on file: macOS will not ask again.
+ return
+ if REQUEST_CLASS.get(item.family) not in _ASKABLE_CLASSES:
+ return
+ if not plan.interactive:
+ return # a background consumer never asks
+ # Everything below is decided afresh on every gesture: an earlier
+ # "unavailable" (a player that was not running) must not stick to the slot
+ # for the rest of the episode. A request that FAILED stays "unavailable"
+ # for a short while, so a retry loop does not hammer a broken native call.
+ slot.unavailable = not plan.force_ask and self._failed_recently(slot.key, now)
+ if not self._desktop_session_ok(port):
+ # No window server (a headless backend, an ssh session, a launchd job):
+ # nothing could be shown, and a native request there is a silently dead
+ # feature (P8). The same case is where a bundle-less process fools the
+ # usage-string guard below, so it is refused first.
+ slot.unavailable = True
+ return
+ outside = self._outside_installed_app(port) and not allow_outside_app
+ slot.outside = outside
+ slot.outside_bundle = outside and self._launched_as_bundle(port)
+ if outside:
+ return
+ if not self._usage_string_ok(port, item.family):
+ slot.unavailable = True
+ return
+ if not self._claim(plan.episode, slot, now, force=plan.force_ask):
+ return
+ # The state read above can be stale by now (another thread's request may
+ # have been answered in between): never ask about a decision that exists.
+ deep = self._deep_for(plan, slot, now)
+ current = self._read_state(port, item.requested, item.target, fresh=True, deep=deep)
+ if current not in _UNDECIDED_STATES:
+ item.state = current
+ slot.state = current
+ self._release_claim(slot)
+ return
+ if item.family is PermissionId.AUTOMATION:
+ # The consent runner blocks for as long as the dialog is open (up to
+ # 120 s): it runs on its own daemon thread and the caller hears PENDING.
+ item.asked = True
+ self._begin_automation_ask(port, plan.episode, slot, item)
+ return
+ outcome = self._request_native(port, item)
+ item.asked = True
+ if outcome == "unavailable":
+ # Nothing is in flight: a later attempt may try again (after the retry
+ # window, or at once for an explicit click).
+ slot.unavailable = True
+ self._release_claim(slot, failed=True)
+ return
+ # Right after the request: an answer that arrived at once (a dialog answered
+ # in place, a switch already on) must be seen by THIS call, oracle included.
+ fresh = self._read_state(port, item.requested, item.target, fresh=True, deep=plan.deep)
+ item.state = fresh
+ slot.state = fresh
+ if plan.deep and item.family is PermissionId.SCREEN_RECORDING:
+ slot.deep_at = self._clock()
+
+ def _begin_automation_ask(self, port: Any, episode: _Episode, slot: _Slot, item: _Item) -> None:
+ """Run the (blocking) Automation request off the calling thread."""
+ done = threading.Event()
+ slot.asking = True
+ slot.ask_done = done
+
+ def work() -> None:
+ try:
+ outcome = self._request_native(port, item)
+ self._settle_automation_ask(port, slot, item, outcome)
+ except Exception: # noqa: BLE001 - a thread must not die loudly
+ log.debug("Settling the Automation request failed.", exc_info=True)
+ slot.unavailable = True
+ self._release_claim(slot)
+ finally:
+ slot.asking = False
+ done.set()
+ self._emit_episode(episode)
+
+ try:
+ self._ask_runner(work)
+ except Exception: # noqa: BLE001 - e.g. the process cannot start another thread
+ log.debug("The Automation request could not be started.", exc_info=True)
+ slot.asking = False
+ slot.unavailable = True
+ done.set()
+ self._release_claim(slot)
+
+ def _settle_automation_ask(self, port: Any, slot: _Slot, item: _Item, outcome: str) -> None:
+ """Read the answer after the consent runner returned and classify what it means."""
+ fresh = self._read_state(
+ port,
+ item.requested,
+ item.target,
+ fresh=True,
+ automation_wait_s=self._automation.timeout_s,
+ )
+ item.state = fresh
+ slot.state = fresh
+ if outcome == "unavailable":
+ slot.unavailable = True
+ self._release_claim(slot, failed=True)
+ elif fresh in _UNDECIDED_STATES:
+ if outcome == "no_dialog":
+ # The runner finished without a dialog and nothing was decided: the
+ # player is not running. Nothing is in flight, so a later attempt
+ # (once the player runs) may ask again.
+ slot.unavailable = True
+ self._release_claim(slot)
+ elif outcome == "timed_out":
+ # Nobody answered before the runner was killed: a slow user is not a
+ # missing player. The view is "not asked yet, may ask" again.
+ self._release_claim(slot)
+
+ @staticmethod
+ def _outside_installed_app(port: Any) -> bool:
+ return bool(getattr(port, "outside_installed_app", False))
+
+ @staticmethod
+ def _launched_as_bundle(port: Any) -> bool:
+ return bool(getattr(port, "launched_as_bundle", False))
+
+ @staticmethod
+ def _desktop_session_ok(port: Any) -> bool:
+ """Whether a window server answers (a stub port without the probe is assumed to)."""
+ check = getattr(port, "has_desktop_session", None)
+ if check is None:
+ return True
+ try:
+ return bool(check())
+ except Exception: # noqa: BLE001 - an unreadable session fails closed, like the port
+ log.debug("Reading the desktop session failed.", exc_info=True)
+ return False
+
+ @staticmethod
+ def _usage_string_ok(port: Any, family: PermissionId) -> bool:
+ check = getattr(port, "usage_string_present", None)
+ if check is None:
+ return True
+ try:
+ return bool(check(family))
+ except Exception: # noqa: BLE001 - an unreadable bundle must not look present
+ log.debug("The usage string check for %s failed.", family.value, exc_info=True)
+ return False
+
+ @staticmethod
+ def _request_native(port: Any, item: _Item) -> str:
+ """The one native call. Never raises, never holds a lock."""
+ try:
+ if item.family is PermissionId.AUTOMATION:
+ outcome = port.request_native(item.family, target=item.target)
+ else:
+ outcome = port.request_native(item.family)
+ except Exception: # noqa: BLE001 - the native request boundary never raises
+ log.debug("The native %s request failed.", item.family.value, exc_info=True)
+ return "unavailable"
+ return str(outcome)
+
+ def _claim(self, episode: _Episode, slot: _Slot, now: float, *, force: bool = False) -> bool:
+ """Atomically decide that THIS caller makes the native request.
+
+ At most one per permission per episode, and at most one per cooldown
+ window per process. ``force`` (an explicit click on "Allow") skips both for
+ a PROMPT-ONCE permission, nothing else: a person re-clicking is not a retry
+ loop, and the button would otherwise do nothing for the ten minutes an
+ episode lives (the route rate limits the clicks). A DIALOG-class dialog may
+ still be open, so it is never asked twice. The decision and the stamp are one
+ critical section, so many threads racing here produce one request; the
+ request itself runs after the lock is released.
+ """
+ window = _REASK_AFTER_S.get(slot.family, math.inf)
+ skip_cooldown = force and REQUEST_CLASS.get(slot.family) is RequestClass.PROMPT_ONCE
+ with self._lock:
+ if slot.asked_at is not None and not skip_cooldown:
+ return False
+ if not force and self._failed_recently(slot.key, now):
+ return False
+ last = self._last_native.get(slot.key)
+ if not skip_cooldown and last is not None and now - last < window:
+ return False
+ self._last_native[slot.key] = now
+ slot.asked_at = now
+ return True
+
+ def _release_claim(self, slot: _Slot, *, failed: bool = False) -> None:
+ with self._lock:
+ slot.asked_at = None
+ self._last_native.pop(slot.key, None)
+ if failed:
+ self._failed_native[slot.key] = self._clock()
+
+ def _failed_recently(self, key: _SlotKey, now: float) -> bool:
+ failed_at = self._failed_native.get(key)
+ return failed_at is not None and now - failed_at < _FAILED_RETRY_S
+
+ # ---- waiting ----------------------------------------------------------
+
+ def _waiting(self, plan: _Plan) -> bool:
+ """Whether some asked permission can still change (a dialog may be open)."""
+ for item in plan.items:
+ slot = item.slot
+ if slot is None or item.state not in _UNDECIDED_STATES:
+ continue
+ if slot.unavailable or slot.outside or item.bad_target:
+ continue
+ if REQUEST_CLASS.get(item.family) not in _ASKABLE_CLASSES:
+ continue
+ if slot.asking or slot.asked_at is not None or slot.key in self._last_native:
+ return True
+ return False
+
+ @staticmethod
+ def _needs_thread_poll(plan: _Plan) -> bool:
+ """Whether a poll may be slow: the oracle enumerates windows, Automation can hang."""
+ return any(
+ item.state not in _READY_STATES
+ and (
+ item.family is PermissionId.AUTOMATION
+ or (item.family is PermissionId.SCREEN_RECORDING and plan.deep)
+ )
+ for item in plan.items
+ )
+
+ @staticmethod
+ def _pending_ask(plan: _Plan) -> threading.Event | None:
+ """The "finished" event of an Automation request still running for this plan."""
+ for item in plan.items:
+ slot = item.slot
+ if slot is not None and slot.asking and slot.ask_done is not None:
+ return slot.ask_done
+ return None
+
+ def _oracle_due(self, slot: _Slot, now: float) -> bool:
+ return slot.deep_at is None or now - slot.deep_at >= self._oracle_every_s
+
+ def _deep_for(self, plan: _Plan, slot: _Slot, now: float) -> bool:
+ """Whether this read may run the window-title oracle: a gesture entry, rate limited.
+
+ ``_start`` stamps the slot when it ran the oracle, so the claim re-read and the
+ polls of the same ``ensure`` call stay shallow (the one read right after a
+ request is the exception: it must see an answer that arrived at once).
+ """
+ return (
+ plan.deep
+ and slot.family is PermissionId.SCREEN_RECORDING
+ and self._oracle_due(slot, now)
+ )
+
+ def _poll(self, port: Any, plan: _Plan) -> None:
+ now = self._clock()
+ for item in plan.items:
+ slot = item.slot
+ if slot is None or item.state in _READY_STATES:
+ continue
+ deep = self._deep_for(plan, slot, now)
+ state = self._read_state(
+ port,
+ item.requested,
+ item.target,
+ fresh=True,
+ deep=deep,
+ automation_wait_s=self._automation_refresh_wait_s,
+ )
+ item.state = state
+ slot.state = state
+ if deep:
+ slot.deep_at = now
+
+ def _wait_sync(self, port: Any, plan: _Plan, wait_s: float) -> None:
+ deadline = self._clock() + wait_s
+ # A second, real-time bound: while a request thread runs we wait on ITS
+ # event in real seconds, which an injected test clock does not advance.
+ real_deadline = time.monotonic() + wait_s
+ while self._waiting(plan):
+ remaining = min(deadline - self._clock(), real_deadline - time.monotonic())
+ if remaining <= 0:
+ break
+ step = min(self._poll_s, remaining)
+ ask = self._pending_ask(plan)
+ if ask is not None:
+ ask.wait(step) # wakes the moment the request thread has finished
+ else:
+ self._sleep(step)
+ self._poll(port, plan)
+
+ # ---- results ----------------------------------------------------------
+
+ def _finish(self, plan: _Plan) -> list[EnsureResult]:
+ now = self._clock()
+ results: list[EnsureResult] = []
+ for item in plan.items:
+ slot = item.slot
+ if slot is None:
+ results.append(self._result(item, self._ready_view(item.state)))
+ continue
+ # The slot is the shared truth (the watcher and the request thread write
+ # it too); the item may be one poll behind.
+ item.state = slot.state
+ if item.state in _READY_STATES:
+ # A grant is a grant (P2): a restart hint on the slot never turns a
+ # live GRANTED into a refusal, it only keeps the toast honest.
+ results.append(self._result(item, self._ready_view(item.state)))
+ else:
+ results.append(self._result(item, self._classify(slot, item.state, now)))
+ if plan.episode is not None:
+ self._emit_episode(plan.episode)
+ return results
+
+ @staticmethod
+ def _ready_view(state: PermissionState) -> _View:
+ outcome = (
+ PermissionOutcome.NOT_REQUIRED
+ if state is PermissionState.NOT_REQUIRED
+ else PermissionOutcome.GRANTED
+ )
+ return _View(outcome, "", "", False, False, False)
+
+ def _result(self, item: _Item, view: _View) -> EnsureResult:
+ if view.outcome in _PROCEED_OUTCOMES:
+ return EnsureResult(
+ permission=item.requested,
+ outcome=view.outcome,
+ state=item.state,
+ asked=item.asked,
+ outside_installed_app=False,
+ agent_detail="",
+ user_detail="",
+ target=item.target,
+ )
+ return EnsureResult(
+ permission=item.requested,
+ outcome=view.outcome,
+ state=item.state,
+ asked=item.asked,
+ outside_installed_app=view.outside,
+ agent_detail=agent_detail_for(
+ item.family, view.reason, target=item.target, asking=view.asking
+ ),
+ user_detail=user_detail_for(
+ item.family,
+ view.reason,
+ target=item.target,
+ asking=view.asking,
+ outside_app=view.outside,
+ launched_as_bundle=view.outside_bundle,
+ refused_use=item.slot is not None and item.slot.refused_while(item.state),
+ ),
+ reason=view.reason,
+ can_prompt=view.can_prompt,
+ can_open_settings=view.can_open_settings,
+ target=item.target,
+ )
+
+ @staticmethod
+ def _not_required(perm: PermissionId) -> EnsureResult:
+ return EnsureResult(
+ permission=perm,
+ outcome=PermissionOutcome.NOT_REQUIRED,
+ state=PermissionState.NOT_REQUIRED,
+ asked=False,
+ outside_installed_app=False,
+ agent_detail="",
+ user_detail="",
+ )
+
+ @staticmethod
+ def _unavailable(perm: PermissionId, target: str) -> EnsureResult:
+ family = PANE_FAMILY[perm]
+ tgt = _fixed_target(target) if family is PermissionId.AUTOMATION else ""
+ return EnsureResult(
+ permission=perm,
+ outcome=PermissionOutcome.UNAVAILABLE,
+ state=PermissionState.UNAVAILABLE,
+ asked=False,
+ outside_installed_app=False,
+ agent_detail=agent_detail_for(family, "unavailable", target=tgt),
+ user_detail=user_detail_for(family, "unavailable", target=tgt),
+ reason="unavailable",
+ target=tgt,
+ )
+
+ # ---- classification ---------------------------------------------------
+
+ def _classify(self, slot: _Slot, state: PermissionState, now: float) -> _View:
+ """Turn (state, what we did) into an outcome, a reason and a phase.
+
+ The phase is ``os_dialog`` while macOS is (or may be) asking and ``blocked``
+ once the user has to act. A PROMPT-ONCE dialog only points at Settings, so
+ it turns ``blocked`` after :data:`_BLOCKED_AFTER_S` seconds or an app
+ refocus, and a DIALOG-class dialog after :data:`_DIALOG_CEILING_S` without an
+ answer (UNVERIFIED how long a real dialog stays up; both figures are ours).
+ """
+ family = slot.family
+ cls = REQUEST_CLASS.get(family, RequestClass.NONE)
+ has_pane = family in SETTINGS_PATH_TEXT
+ if slot.restart_hint:
+ # A real attempt failed although the state may read granted: the one
+ # honest advice left is "quit and reopen" (never an automatic restart).
+ return _View(
+ PermissionOutcome.NEEDS_SETTINGS, "restart_hint", "blocked", False, has_pane, False
+ )
+ if slot.refused_while(state):
+ # A real Apple Event was refused (-1743) although the probe reads granted:
+ # the probe is what lied, so the honest advice is the Automation pane. It
+ # is never asked for again from here (``can_prompt`` is False) and never a
+ # restart hint: Apple Events are checked per send.
+ return _View(
+ PermissionOutcome.NEEDS_SETTINGS,
+ "needs_settings",
+ "blocked",
+ False,
+ has_pane,
+ False,
+ )
+ if state in _READY_STATES:
+ return self._ready_view(state)
+ if state is PermissionState.RESTRICTED:
+ return _View(
+ PermissionOutcome.UNAVAILABLE, "restricted", "blocked", False, False, False
+ )
+ if state is PermissionState.UNAVAILABLE or slot.unavailable:
+ return _View(
+ PermissionOutcome.UNAVAILABLE, "unavailable", "blocked", False, False, False
+ )
+ if state is PermissionState.DENIED or cls not in _ASKABLE_CLASSES:
+ return _View(PermissionOutcome.DENIED, "denied", "blocked", False, has_pane, False)
+ if slot.outside:
+ return _View(
+ PermissionOutcome.NEEDS_SETTINGS,
+ "needs_settings",
+ "blocked",
+ True,
+ has_pane,
+ True,
+ slot.outside_bundle,
+ )
+ stamp = slot.asked_at if slot.asked_at is not None else self._last_native.get(slot.key)
+ if stamp is None:
+ # Never asked in this process: waiting for a gesture.
+ return _View(
+ PermissionOutcome.PENDING, "not_determined", "blocked", True, has_pane, False
+ )
+ if cls is RequestClass.DIALOG:
+ if slot.asking or now - stamp < _DIALOG_CEILING_S:
+ return _View(
+ PermissionOutcome.PENDING, "not_determined", "os_dialog", False, has_pane, False
+ )
+ return _View(
+ PermissionOutcome.NEEDS_SETTINGS,
+ "needs_settings",
+ "blocked",
+ False,
+ has_pane,
+ False,
+ )
+ if slot.promoted or now - stamp >= _BLOCKED_AFTER_S:
+ return _View(
+ PermissionOutcome.NEEDS_SETTINGS,
+ "needs_settings",
+ "blocked",
+ False,
+ has_pane,
+ False,
+ )
+ return _View(
+ PermissionOutcome.PENDING, "needs_settings", "os_dialog", False, has_pane, False
+ )
+
+ # ----------------------------------------------------------- episodes
+
+ def _open_episode(
+ self,
+ feature: str,
+ pending: Sequence[_Item],
+ interactive: bool,
+ trace_id: UUID | str | None,
+ now: float,
+ ) -> _Episode:
+ """Get or create the one record for this feature and these permissions.
+
+ An open episode of the same feature that shares a permission with the
+ pending set is JOINED (and gains the slots it lacks), so granting one member
+ of a coalesced pair never opens a second record for the same permission.
+ The caller gets it with ``starting`` raised and must lower it again.
+ """
+ slot_keys = sorted({item.slot_key for item in pending}, key=lambda k: (k[0].value, k[1]))
+ key: _EpisodeKey = (feature, tuple((fam.value, tgt) for fam, tgt in slot_keys))
+ origin = "user" if interactive else "background"
+ trace = _coerce_trace(trace_id)
+ with self._lock:
+ episode = self._episodes.get(key)
+ if episode is None:
+ wanted_keys = set(slot_keys)
+ episode = next(
+ (
+ candidate
+ for candidate in self._episodes.values()
+ if candidate.feature == feature
+ and not candidate.closed
+ and wanted_keys & set(candidate.slots)
+ ),
+ None,
+ )
+ if episode is None:
+ episode = _Episode(
+ key=key,
+ feature=feature,
+ slots={},
+ origin=origin,
+ trace_id=trace,
+ opened_ns=time.time_ns(),
+ touched=now,
+ announced_at=now,
+ )
+ self._episodes[key] = episode
+ else:
+ episode.touched = now
+ if interactive:
+ # A gesture upgrades a background episode: the toast may show now.
+ episode.origin = "user"
+ if now - episode.announced_at >= _REANNOUNCE_MIN_S:
+ # The person is trying again while the permission is still
+ # missing: forget what was published so the next emit says
+ # it once more (the toast they dismissed or never saw).
+ episode.published.clear()
+ episode.announced_at = now
+ if trace_id is not None:
+ episode.trace_id = trace
+ for item in pending:
+ slot_key = item.slot_key
+ existing = episode.slots.get(slot_key)
+ probe = (
+ PermissionId.EVENT_POSTING
+ if item.requested is PermissionId.EVENT_POSTING
+ else item.family
+ )
+ if existing is None:
+ episode.slots[slot_key] = _Slot(
+ family=item.family, target=item.target, probe=probe, state=item.state
+ )
+ elif probe is PermissionId.EVENT_POSTING:
+ existing.probe = probe
+ episode.starting += 1
+ return episode
+
+ def _note_ready(self, item: _Item) -> None:
+ """A permission was seen granted: advance every open episode that waits on it."""
+ with self._lock:
+ waiting = [ep for ep in self._episodes.values() if item.slot_key in ep.slots]
+ for episode in waiting:
+ slot = episode.slots.get(item.slot_key)
+ if slot is not None:
+ slot.state = item.state
+ self._emit_episode(episode)
+
+ def _emit_episode(self, episode: _Episode, fired: set[PermissionId] | None = None) -> None:
+ """Bring subscribers up to date with an episode: grants, closing, one event.
+
+ Idempotent: the dedup key is (permissions, feature, reason, phase, origin),
+ so a repeated silent call changes nothing. An episode whose caller has not
+ finished its asks yet (``starting``) is left alone: nothing is claimed
+ there, so a classify would announce "blocked, can prompt" while the OS
+ dialog is still being requested. ``fired`` collects the families whose
+ listeners already ran in this pass, so two episodes for one permission
+ call a re-arm once.
+ """
+ if episode.closed or episode.starting > 0:
+ return
+ now = self._clock()
+ views: list[tuple[_Slot, _View]] = []
+ newly_granted: list[_Slot] = []
+ for slot in tuple(episode.slots.values()):
+ if slot.state in _READY_STATES and not slot.failed_use:
+ if not slot.notified:
+ newly_granted.append(slot)
+ continue
+ views.append((slot, self._classify(slot, slot.state, now)))
+ if newly_granted:
+ with self._lock:
+ fresh = [slot for slot in newly_granted if not slot.notified]
+ for slot in fresh:
+ slot.notified = True
+ self._call_listeners([slot.family for slot in fresh], fired)
+ if not views:
+ self._close(episode, granted=True, fired=fired)
+ return
+
+ reason, phase, view = self._aggregate(views)
+ slot_primary = next(slot for slot, candidate in views if candidate is view)
+ permissions = tuple(slot.family.value for slot, _ in views)
+ detail = user_detail_for(
+ slot_primary.family,
+ reason,
+ target=slot_primary.target,
+ asking=phase == "os_dialog",
+ outside_app=view.outside,
+ launched_as_bundle=view.outside_bundle,
+ refused_use=slot_primary.refused_while(slot_primary.state),
+ )
+ can_prompt = any(candidate.can_prompt for _, candidate in views)
+ can_open = any(candidate.can_open_settings for _, candidate in views)
+ outside = any(candidate.outside for _, candidate in views)
+ target = next((slot.target for slot, _ in views if slot.target), "")
+ with self._lock:
+ if episode.closed:
+ return
+ episode.reason = reason
+ episode.phase = phase
+ episode.can_prompt = can_prompt
+ episode.can_open_settings = can_open
+ episode.outside_app = outside
+ episode.detail = detail
+ dedup = (permissions, episode.feature, reason, phase, episode.origin)
+ if dedup in episode.published:
+ return
+ episode.published.add(dedup)
+ origin = episode.origin
+ trace = episode.trace_id
+ log.debug(
+ "Permission needed: %s for %s (%s, %s, %s).",
+ ",".join(permissions),
+ episode.feature,
+ reason,
+ phase,
+ origin,
+ )
+ self._publish(
+ PermissionNeeded(
+ trace_id=trace,
+ source_layer=_SOURCE_LAYER,
+ permissions=permissions,
+ feature=episode.feature,
+ reason=reason,
+ phase=phase,
+ origin=origin,
+ target=target,
+ can_prompt=can_prompt,
+ can_open_settings=can_open,
+ outside_app=outside,
+ detail=detail,
+ )
+ )
+
+ @staticmethod
+ def _aggregate(views: Sequence[tuple[_Slot, _View]]) -> tuple[str, str, _View]:
+ ranked = sorted(
+ (candidate for _, candidate in views),
+ key=lambda v: _REASON_PRIORITY.index(v.reason),
+ )
+ primary = ranked[0]
+ phase = (
+ "os_dialog"
+ if all(candidate.phase == "os_dialog" for _, candidate in views)
+ else "blocked"
+ )
+ return primary.reason, phase, primary
+
+ def _close(
+ self, episode: _Episode, *, granted: bool, fired: set[PermissionId] | None = None
+ ) -> None:
+ """End an episode once: remove it, tell the bus, call the listeners."""
+ with self._lock:
+ if episode.closed:
+ return
+ episode.closed = True
+ if self._episodes.get(episode.key) is episode:
+ del self._episodes[episode.key]
+ unnotified = [
+ slot
+ for slot in episode.slots.values()
+ if slot.state in _READY_STATES and not slot.notified
+ ]
+ for slot in unnotified:
+ slot.notified = True
+ permissions = tuple(slot.family.value for slot in episode.slots.values())
+ trace = episode.trace_id
+ if unnotified:
+ self._call_listeners([slot.family for slot in unnotified], fired)
+ log.debug("Permission episode for %s ended (granted=%s).", episode.feature, granted)
+ self._publish(
+ PermissionResolved(
+ trace_id=trace,
+ source_layer=_SOURCE_LAYER,
+ permissions=permissions,
+ feature=episode.feature,
+ granted=granted,
+ )
+ )
+
+ def outstanding(self) -> list[Episode]:
+ """The open episodes, oldest first: what a UI hydrates its cards from.
+
+ An episode still being started (its asks are not finished) is not listed
+ yet, and ``permissions`` names only what is still missing (the same set the
+ ``PermissionNeeded`` event carries).
+ """
+ with self._lock:
+ open_episodes = sorted(
+ (ep for ep in self._episodes.values() if ep.starting <= 0 and ep.reason),
+ key=lambda ep: ep.opened_ns,
+ )
+ return [
+ Episode(
+ permissions=tuple(
+ slot.family.value
+ for slot in ep.slots.values()
+ if slot.state not in _READY_STATES or slot.failed_use
+ ),
+ feature=ep.feature,
+ reason=ep.reason,
+ phase=ep.phase,
+ origin=ep.origin,
+ target=next((slot.target for slot in ep.slots.values() if slot.target), ""),
+ can_prompt=ep.can_prompt,
+ can_open_settings=ep.can_open_settings,
+ outside_app=ep.outside_app,
+ detail=ep.detail,
+ trace_id=str(ep.trace_id),
+ opened_at_ns=ep.opened_ns,
+ )
+ for ep in open_episodes
+ ]
+
+ def note_app_activated(self) -> None:
+ """The app was refocused: a PROMPT-ONCE dialog the user left is now "blocked".
+
+ Reached through ``?activated=1`` on the status routes (kept for the CLI and
+ agents; the app's window has no caller for it since the UI reset, so today
+ the ~15 s timer is what turns the dialog "blocked"). A request that only
+ offered "Open System Settings" has then done all it can, and the app may
+ show its toast.
+ The refocus also makes the next watcher pass run the Screen Recording
+ oracle at once (the user probably just flipped the switch).
+ """
+ with self._lock:
+ episodes = list(self._episodes.values())
+ for episode in episodes:
+ changed = False
+ for slot in tuple(episode.slots.values()):
+ if slot.family is PermissionId.SCREEN_RECORDING:
+ slot.deep_at = None
+ if (
+ slot.asked_at is not None
+ and not slot.promoted
+ and REQUEST_CLASS.get(slot.family) is RequestClass.PROMPT_ONCE
+ ):
+ slot.promoted = True
+ changed = True
+ if changed:
+ self._emit_episode(episode)
+
+ def refresh_episodes(self) -> None:
+ """Re-read every open permission and publish the edges.
+
+ What the watcher runs every two seconds; a status route calls it too, so
+ an edge is emitted whichever path sees it first. Blocking (it reads the
+ OS): not for the event loop.
+
+ Every slot is read independently: an Automation probe that hangs costs a
+ pass at most :data:`_AUTOMATION_REFRESH_WAIT_S` (and nothing once its
+ player is quarantined), and the episodes without Automation are read and
+ published FIRST, so a stuck player never delays a microphone grant. The
+ Screen Recording oracle runs only for an episode a gesture opened, and at
+ most every ``oracle_every_s`` seconds.
+ """
+ with self._lock:
+ episodes = list(self._episodes.values())
+ if not episodes:
+ return
+ port = self._port()
+ if not self._is_darwin(port):
+ # Nothing can be open off macOS; drop a record a test planted.
+ for episode in episodes:
+ self._close(episode, granted=True)
+ return
+ episodes.sort(
+ key=lambda ep: any(slot.family is PermissionId.AUTOMATION for slot in ep.slots.values())
+ )
+ fired: set[PermissionId] = set()
+ for episode in episodes:
+ if episode.closed:
+ continue
+ now = self._clock()
+ for slot in tuple(episode.slots.values()):
+ self._refresh_slot(port, episode, slot, now)
+ if any(
+ slot.state not in _READY_STATES or slot.failed_use
+ for slot in episode.slots.values()
+ ) and (now - episode.touched > self._episode_ttl_s):
+ self._close(episode, granted=False, fired=fired)
+ continue
+ self._emit_episode(episode, fired)
+
+ def _refresh_slot(self, port: Any, episode: _Episode, slot: _Slot, now: float) -> None:
+ """Re-read one slot; a failure of this read never costs the other slots theirs."""
+ deep = (
+ slot.family is PermissionId.SCREEN_RECORDING
+ and episode.origin == "user"
+ and self._oracle_due(slot, now)
+ )
+ try:
+ slot.state = self._read_state(
+ port,
+ slot.probe,
+ slot.target,
+ deep=deep,
+ automation_wait_s=self._automation_refresh_wait_s,
+ )
+ except Exception: # noqa: BLE001 - one slot's failed read must not starve the others
+ log.debug("Re-reading the %s permission failed.", slot.family.value, exc_info=True)
+ return
+ if deep:
+ slot.deep_at = now
+
+ # ------------------------------------------------------------ watcher
+
+ def _ensure_watcher(self) -> None:
+ """Start the watcher unless one is alive. Never blocks, never raises."""
+ loop: asyncio.AbstractEventLoop | None = None
+ with self._lock:
+ if self._watcher_alive():
+ return
+ self._watch_gen += 1
+ gen = self._watch_gen
+ self._watch_running = True
+ sink = self._sink
+ loop = sink[1] if sink is not None else None
+ if loop is not None and not loop.is_closed():
+ self._watch_kind = "task"
+ self._watch_loop = loop
+ self._watch_task = None
+ else:
+ self._watch_kind = "thread"
+ self._watch_loop = None
+ self._watch_stop = threading.Event()
+ thread = threading.Thread(
+ target=self._watch_thread_main,
+ args=(gen, self._watch_stop),
+ name="permission-episode-watcher",
+ daemon=True,
+ )
+ self._watch_thread = thread
+ thread.start()
+ return
+ try:
+ loop.call_soon_threadsafe(self._spawn_watch_task, gen)
+ except RuntimeError:
+ # The loop closed between the check and the call: fall back to a thread.
+ log.debug("The attached loop is closed; the episode watcher uses a thread.")
+ with self._lock:
+ if gen != self._watch_gen:
+ return
+ self._watch_kind = "thread"
+ self._watch_loop = None
+ self._watch_stop = threading.Event()
+ thread = threading.Thread(
+ target=self._watch_thread_main,
+ args=(gen, self._watch_stop),
+ name="permission-episode-watcher",
+ daemon=True,
+ )
+ self._watch_thread = thread
+ thread.start()
+
+ def _watcher_alive(self) -> bool:
+ """Whether a watcher is running (called with the lock held; reads only)."""
+ if not self._watch_running:
+ return False
+ if self._watch_kind == "thread":
+ thread = self._watch_thread
+ return thread is not None and thread.is_alive()
+ loop = self._watch_loop
+ if loop is None or loop.is_closed():
+ return False
+ task = self._watch_task
+ return task is None or not task.done()
+
+ def _spawn_watch_task(self, gen: int) -> None:
+ """Runs on the loop thread: create the watcher task."""
+ with self._lock:
+ if gen != self._watch_gen:
+ return
+ self._watch_task = asyncio.get_running_loop().create_task(self._watch_main(gen))
+
+ async def _watch_main(self, gen: int) -> None:
+ try:
+ while True:
+ await asyncio.sleep(self._watch_interval_s)
+ # The tick reads the OS: off the loop, one short thread hop per tick.
+ if not await asyncio.to_thread(self._watch_tick, gen):
+ return
+ finally:
+ with self._lock:
+ if gen == self._watch_gen:
+ self._watch_running = False
+
+ def _watch_thread_main(self, gen: int, stop: threading.Event) -> None:
+ while not stop.wait(self._watch_interval_s):
+ if not self._watch_tick(gen):
+ return
+ with self._lock:
+ if gen == self._watch_gen:
+ self._watch_running = False
+
+ def _watch_tick(self, gen: int) -> bool:
+ """One watcher pass. ``False`` means "stop": nothing is open, or superseded."""
+ try:
+ self.refresh_episodes()
+ except Exception: # noqa: BLE001 - the watcher must outlive one bad pass
+ log.debug("The permission episode watcher pass failed.", exc_info=True)
+ with self._lock:
+ if gen != self._watch_gen:
+ return False
+ if not self._episodes:
+ self._watch_running = False
+ return False
+ return True
+
+ def _shutdown(self) -> None:
+ """Stop the watcher and drop every record (tests and process teardown)."""
+ with self._lock:
+ self._watch_gen += 1
+ self._watch_running = False
+ stop = self._watch_stop
+ task = self._watch_task
+ loop = self._watch_loop
+ self._watch_task = None
+ self._watch_thread = None
+ self._watch_loop = None
+ self._episodes = {}
+ self._last_native = {}
+ self._failed_native = {}
+ self._listeners = {}
+ self._sink = None
+ stop.set()
+ self._cache = {}
+ self._sr_proven = False
+ self._automation.forget()
+ if task is not None and loop is not None and not loop.is_closed():
+ try:
+ loop.call_soon_threadsafe(task.cancel)
+ except RuntimeError:
+ log.debug("The loop closed before the watcher task could be cancelled.")
+
+ # ----------------------------------------------------------- listeners
+
+ def add_listener(
+ self, permission: PermissionId | str, callback: Callable[[], None]
+ ) -> Callable[[], None]:
+ """Call ``callback()`` when this permission turns granted inside an open episode.
+
+ For consumers that are not on the bus: a hotkey backend that re-arms, a
+ wake loop that parks until the microphone is allowed. EVENT_POSTING is
+ folded into Accessibility. With a loop attached the callback runs on that
+ loop's thread; without one, on the observing thread. It must be cheap and
+ must not raise (a raise is logged and does not stop the other listeners).
+ Returns an idempotent unsubscribe function.
+ """
+ family = PANE_FAMILY[PermissionId(permission)]
+ with self._lock:
+ self._listeners[family] = (*self._listeners.get(family, ()), callback)
+
+ def unsubscribe() -> None:
+ with self._lock:
+ current = self._listeners.get(family, ())
+ self._listeners[family] = tuple(cb for cb in current if cb is not callback)
+
+ return unsubscribe
+
+ def _call_listeners(
+ self, families: Sequence[PermissionId], fired: set[PermissionId] | None = None
+ ) -> None:
+ """Run the listeners of these families; ``fired`` skips ones already run in this pass."""
+ callbacks: list[Callable[[], None]] = []
+ for family in families:
+ if fired is not None:
+ if family in fired:
+ continue
+ fired.add(family)
+ callbacks.extend(self._listeners.get(family, ()))
+ if not callbacks:
+ return
+ sink = self._sink
+ if sink is not None and not sink[1].is_closed():
+ try:
+ sink[1].call_soon_threadsafe(_run_callbacks, tuple(callbacks))
+ return
+ except RuntimeError:
+ log.debug("The attached loop is closed; calling the listeners directly.")
+ _run_callbacks(tuple(callbacks))
+
+ # ------------------------------------------------------------- publish
+
+ def _publish(self, event: PermissionNeeded | PermissionResolved) -> None:
+ """Hand an event to the bus from any thread; never waits, never raises."""
+ sink = self._sink
+ if sink is None:
+ log.debug(
+ "No bus attached; %s kept in the episode registry only.", type(event).__name__
+ )
+ return
+ bus, loop = sink
+ if loop.is_closed():
+ log.debug("The attached loop is closed; %s dropped.", type(event).__name__)
+ return
+ try:
+ coro = bus.publish(event)
+ except Exception: # noqa: BLE001 - a broken bus must not break a permission check
+ log.debug("The bus refused %s.", type(event).__name__, exc_info=True)
+ return
+ try:
+ future = asyncio.run_coroutine_threadsafe(coro, loop)
+ except RuntimeError:
+ coro.close()
+ log.debug("The attached loop is closed; %s dropped.", type(event).__name__)
+ return
+ future.add_done_callback(_log_publish_failure)
+
+ # ------------------------------------------------------------ settings
+
+ def open_settings(self, permission: PermissionId | str) -> bool:
+ """Open the System Settings pane of a permission. Never raises.
+
+ Light: it goes through the port's ``open_pane`` (no snapshot, so no
+ Automation probe and no oracle read) and needs a desktop session, not the
+ installed-app identity (opening a pane is not a prompt, design P6). A
+ user who goes to Settings also keeps their open episodes alive: the ten
+ minute clock starts again.
+ """
+ perm = PermissionId(permission)
+ family = PANE_FAMILY[perm]
+ try:
+ port = self._port()
+ if not self._is_darwin(port):
+ return False
+ opened = bool(port.open_pane(family))
+ except Exception: # noqa: BLE001 - opening a pane is best-effort
+ log.debug("Opening the %s pane failed.", perm.value, exc_info=True)
+ return False
+ if opened:
+ now = self._clock()
+ with self._lock:
+ for episode in self._episodes.values():
+ if any(slot.family is family for slot in episode.slots.values()):
+ episode.touched = now
+ return opened
+
+ # ------------------------------------------------------- failed attempts
+
+ def report_failed_use(
+ self,
+ permission: PermissionId | str,
+ *,
+ feature: str,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ reason: str | None = None,
+ origin: str | None = None,
+ ) -> EnsureResult:
+ """A consumer reports a REAL failed attempt to use a permission it was granted.
+
+ Two families have a producer here, each with ONE reason it can carry
+ (``reason=None`` means that default; any other value is a state that does not
+ fit and falls back to the plain path below):
+
+ * Screen Recording and Input Monitoring, ``restart_hint``: the preflight is
+ frozen per process and a tap may see no events (community-observed,
+ UNVERIFIED), so when a real capture or tap failed while the live state
+ reads granted, or the user came back from Settings and the preflight is
+ still negative, the honest advice is "quit and reopen", never an automatic
+ restart. Call it from the capture or tap site after a real failure, from a
+ user-started feature only; the episode origin defaults to ``user``.
+ * Automation, ``needs_settings``: an Apple Event to ONE player (``target``, a
+ bundle id from ``AUTOMATION_TARGETS``; anything else is refused with
+ UNAVAILABLE, opens nothing and is never echoed) was refused with ``-1743``
+ although the probe read GRANTED. The probe is exactly what lied (the grant
+ may belong to another app: the attribution of a child ``osascript`` is
+ UNVERIFIED), so this opens ONE episode that a granted read does not close,
+ and that only :meth:`report_use_ok`, :meth:`note_reset` or the episode's
+ ten minute TTL ends. It is NOT a restart hint (Apple Events are checked per
+ send), it never asks (no native request, ``can_prompt`` False) and the
+ origin defaults to ``background``: the report comes from a voice session
+ start, so only the status snapshot shows it, never the toast. A live state
+ that no longer reads granted is reported through the plain path (its real
+ reason).
+
+ ``origin`` (``user`` or ``background``) overrides the family default; a value
+ outside the event vocabulary is ignored. Anything else (another permission,
+ a state that does not fit) falls back to a plain non-interactive
+ :meth:`ensure`. The answer is the view of that episode: neither reason is ever
+ a grant, and a following ``ensure`` still answers GRANTED while the state
+ reads granted. Never raises.
+ """
+ perm = PermissionId(permission)
+ family = PANE_FAMILY[perm]
+ tgt = _fixed_target(target) if family is PermissionId.AUTOMATION else ""
+ try:
+ port = self._port()
+ if not self._is_darwin(port):
+ return self._not_required(perm)
+ if family is PermissionId.AUTOMATION:
+ return self._report_refused_automation(
+ port, perm, feature, tgt, trace_id, reason, origin
+ )
+ if family not in _RESTART_HINT_FAMILIES or reason not in (None, "restart_hint"):
+ return self.ensure(perm, feature=feature, interactive=False, target=tgt or None)
+ if feature not in PERMISSION_FEATURES:
+ log.warning("report_failed_use() was called with the unknown feature %r.", feature)
+ feature = ""
+ now = self._clock()
+ state = self._read_state(port, perm, tgt, fresh=True, deep=not _on_event_loop_thread())
+ promoted = self._promoted(feature, family)
+ if state not in _READY_STATES and not promoted:
+ return self.ensure(perm, feature=feature, interactive=False, trace_id=trace_id)
+ item = _Item(requested=perm, family=family, target=tgt, state=state)
+ episode = self._open_episode(
+ feature, [item], _failed_use_origin(origin, "user") == "user", trace_id, now
+ )
+ try:
+ slot = episode.slots[item.slot_key]
+ slot.state = state
+ slot.restart_hint = True
+ item.slot = slot
+ finally:
+ with self._lock:
+ episode.starting -= 1
+ self._emit_episode(episode)
+ self._ensure_watcher()
+ return self._result(item, self._classify(slot, state, now))
+ except Exception: # noqa: BLE001 - reporting a failure never raises
+ log.debug("report_failed_use(%s) failed.", feature, exc_info=True)
+ return self._unavailable(perm, tgt)
+
+ def _report_refused_automation(
+ self,
+ port: Any,
+ perm: PermissionId,
+ feature: str,
+ target: str,
+ trace_id: UUID | str | None,
+ reason: str | None,
+ origin: str | None,
+ ) -> EnsureResult:
+ """The Automation branch of :meth:`report_failed_use`: a send was refused (-1743).
+
+ Reads the live state once. Not granted any more: the plain non-interactive
+ :meth:`ensure` describes it (its real reason, still never a request). Granted:
+ marks the player's slot ``refused_use`` in the (feature, player) episode and
+ publishes ONE ``needs_settings`` / ``blocked`` event (a repeat of the same
+ report is deduplicated by ``_emit_episode``, so a refusal on every session
+ start stays one event). The caller holds no service lock, and the one read is
+ the guarded, hard-timeout Automation read, never a native request.
+ """
+ if not target:
+ # Only the fixed player table is ever acted on, echoed or published.
+ log.debug("A failed Automation use was reported for a target that is not a player.")
+ return self._unavailable(perm, "")
+ if reason not in (None, "needs_settings"):
+ log.debug("A failed Automation use was reported with a reason it cannot carry.")
+ return self.ensure(
+ perm, feature=feature, interactive=False, target=target, trace_id=trace_id
+ )
+ if feature not in PERMISSION_FEATURES:
+ log.warning("report_failed_use() was called with the unknown feature %r.", feature)
+ feature = ""
+ now = self._clock()
+ state = self._read_state(port, perm, target, fresh=True)
+ if state not in _READY_STATES:
+ return self.ensure(
+ perm, feature=feature, interactive=False, target=target, trace_id=trace_id
+ )
+ item = _Item(requested=perm, family=PermissionId.AUTOMATION, target=target, state=state)
+ # An episode this player's ask left behind and that is already answered closes
+ # first, so the background report below never inherits its user origin (and
+ # with it the toast).
+ self._note_ready(item)
+ user = _failed_use_origin(origin, "background") == "user"
+ episode = self._open_episode(feature, [item], user, trace_id, now)
+ try:
+ slot = episode.slots[item.slot_key]
+ slot.state = state
+ slot.refused_use = True
+ item.slot = slot
+ finally:
+ with self._lock:
+ episode.starting -= 1
+ self._emit_episode(episode)
+ self._ensure_watcher()
+ return self._result(item, self._classify(slot, state, now))
+
+ def report_use_ok(
+ self,
+ permission: PermissionId | str,
+ *,
+ feature: str,
+ target: str | None = None,
+ ) -> bool:
+ """A consumer reports that a REAL use of a permission worked: the mark is stale.
+
+ The counterpart of :meth:`report_failed_use` for Automation: a send to the
+ player landed (the volume command ran), so the ``needs_settings`` episode
+ that an earlier ``-1743`` opened is over. It clears the ``refused_use`` mark
+ of that (feature, player) slot and lets the episode close like any other
+ (``PermissionResolved(granted=True)``). A landed send is stronger evidence than
+ the probe, so the slot reads granted from here on.
+
+ This is the ONLY thing that ends such an episode early: a probe that reads
+ granted (the watcher, a status read, ``ensure``) never does, because that
+ probe is what lied. ``note_reset`` and the ten minute TTL end it too.
+
+ Returns ``True`` when a mark was cleared. Another permission, an unknown
+ player or a feature with nothing to clear returns ``False`` (the restart hints
+ of Screen Recording and Input Monitoring end through ``note_reset``). Reads no
+ state, touches no port, makes no request, never raises (an unknown permission
+ id is the one ``ValueError``, like everywhere else).
+ """
+ perm = PermissionId(permission)
+ family = PANE_FAMILY[perm]
+ tgt = _fixed_target(target) if family is PermissionId.AUTOMATION else ""
+ if family is not PermissionId.AUTOMATION or not tgt:
+ return False
+ if feature not in PERMISSION_FEATURES:
+ feature = ""
+ try:
+ cleared: list[_Episode] = []
+ with self._lock:
+ for episode in self._episodes.values():
+ slot = episode.slots.get((family, tgt))
+ if episode.closed or episode.feature != feature or slot is None:
+ continue
+ if slot.refused_use:
+ slot.refused_use = False
+ slot.state = PermissionState.GRANTED
+ cleared.append(episode)
+ for episode in cleared:
+ self._emit_episode(episode)
+ return bool(cleared)
+ except Exception: # noqa: BLE001 - tidying a status line never fails a real send
+ log.debug("report_use_ok(%s) failed.", feature, exc_info=True)
+ return False
+
+ def _promoted(self, feature: str, family: PermissionId) -> bool:
+ """Whether the user is known to have left to Settings and come back for this."""
+ with self._lock:
+ return any(
+ slot.promoted
+ for episode in self._episodes.values()
+ if episode.feature == feature
+ for slot in episode.slots.values()
+ if slot.family is family
+ )
+
+
+# ----------------------------------------------------------------------
+# Module helpers and the process singleton
+# ----------------------------------------------------------------------
+
+
+def _fixed_target(target: str | None) -> str:
+ """The Automation target if it is one of the fixed players, else ``""``.
+
+ Nothing a caller invents (an app name, a path, another bundle id) is ever echoed
+ into a result, an episode or an event.
+ """
+ return target if target and _player_name(target) is not None else ""
+
+
+def _failed_use_origin(origin: str | None, default: str) -> str:
+ """The episode origin of a failed-use report: the caller's, if it is a known one."""
+ if origin is None:
+ return default
+ if origin in PERMISSION_NEEDED_ORIGINS:
+ return origin
+ log.debug("report_failed_use() was called with an origin outside the event vocabulary.")
+ return default
+
+
+def _on_event_loop_thread() -> bool:
+ """Whether the calling thread is running an asyncio loop (it must never block)."""
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ # Not an error: "no running loop in this thread" is exactly the answer.
+ return False
+ return True
+
+
+def _start_daemon_thread(work: Callable[[], None]) -> None:
+ """The default ``ask_runner``: run ``work`` on its own daemon thread."""
+ threading.Thread(target=work, name="permission-automation-ask", daemon=True).start()
+
+
+def _coerce_trace(trace_id: UUID | str | None) -> UUID:
+ if isinstance(trace_id, UUID):
+ return trace_id
+ if isinstance(trace_id, str):
+ try:
+ return UUID(trace_id)
+ except ValueError:
+ log.debug("Ignoring a trace id that is not a UUID.")
+ return uuid4()
+
+
+def _run_callbacks(callbacks: Sequence[Callable[[], None]]) -> None:
+ """Call every listener; one that raises does not stop the others."""
+ for callback in callbacks:
+ try:
+ callback()
+ except Exception: # noqa: BLE001 - a listener must never break the watcher or the loop
+ log.warning("A permission listener raised.", exc_info=True)
+
+
+def _log_publish_failure(future: Any) -> None:
+ if future.cancelled():
+ return
+ error = future.exception()
+ if error is not None:
+ log.debug("Publishing a permission event failed: %r", error)
+
+
+_SERVICE: PermissionService | None = None
+_SERVICE_LOCK = threading.Lock()
+
+
+def get_permission_service() -> PermissionService:
+ """The lazy process-wide service. Constructing it does no I/O."""
+ global _SERVICE
+ service = _SERVICE
+ if service is None:
+ with _SERVICE_LOCK:
+ if _SERVICE is None:
+ _SERVICE = PermissionService()
+ service = _SERVICE
+ return service
+
+
+def _reset_for_tests() -> None:
+ """Drop the singleton and stop its watcher (the autouse test fixture calls this)."""
+ global _SERVICE
+ with _SERVICE_LOCK:
+ service, _SERVICE = _SERVICE, None
+ if service is not None:
+ service._shutdown()
+
+
+def attach_bus(bus: Any | None, loop: asyncio.AbstractEventLoop | None) -> None:
+ """:meth:`PermissionService.attach_bus` on the process singleton."""
+ get_permission_service().attach_bus(bus, loop)
+
+
+def check(permission: PermissionId | str, *, target: str | None = None) -> PermissionState:
+ """:meth:`PermissionService.check` on the process singleton."""
+ return get_permission_service().check(permission, target=target)
+
+
+def ensure(permission: PermissionId | str, **kwargs: Any) -> EnsureResult:
+ """:meth:`PermissionService.ensure` on the process singleton."""
+ return get_permission_service().ensure(permission, **kwargs)
+
+
+async def ensure_async(permission: PermissionId | str, **kwargs: Any) -> EnsureResult:
+ """:meth:`PermissionService.ensure_async` on the process singleton."""
+ return await get_permission_service().ensure_async(permission, **kwargs)
+
+
+def ensure_all(permissions: Iterable[PermissionId | str], **kwargs: Any) -> list[EnsureResult]:
+ """:meth:`PermissionService.ensure_all` on the process singleton."""
+ return get_permission_service().ensure_all(permissions, **kwargs)
+
+
+def outstanding() -> list[Episode]:
+ """:meth:`PermissionService.outstanding` on the process singleton."""
+ return get_permission_service().outstanding()
+
+
+def add_listener(
+ permission: PermissionId | str, callback: Callable[[], None]
+) -> Callable[[], None]:
+ """:meth:`PermissionService.add_listener` on the process singleton."""
+ return get_permission_service().add_listener(permission, callback)
+
+
+def open_settings(permission: PermissionId | str) -> bool:
+ """:meth:`PermissionService.open_settings` on the process singleton."""
+ return get_permission_service().open_settings(permission)
+
+
+__all__ = [
+ "AppInfo",
+ "Episode",
+ "EnsureResult",
+ "PermissionOutcome",
+ "PermissionService",
+ "add_listener",
+ "agent_detail_for",
+ "attach_bus",
+ "check",
+ "ensure",
+ "ensure_all",
+ "ensure_async",
+ "get_permission_service",
+ "open_settings",
+ "outstanding",
+ "user_detail_for",
+]
diff --git a/jarvis/platform/permissions.py b/jarvis/platform/permissions.py
index 2d7442bbe4..8c66c43723 100644
--- a/jarvis/platform/permissions.py
+++ b/jarvis/platform/permissions.py
@@ -1,9 +1,12 @@
-"""Uncached macOS system-permission probes and user-initiated requests.
+"""Uncached macOS system-permission probes and Apple's supported ask/settings calls.
macOS TCC permissions cannot be installed or granted programmatically. This
-port reports the native state on every call and exposes only Apple's supported
-prompt/settings flows. Platform frameworks are imported lazily so a base or
-headless installation remains importable on every operating system.
+port reports the native state on every call and exposes only the primitives the
+just-in-time ``permission_service`` composes: ``state`` (live, never asks),
+``request_native`` (the one native request, never evidence of a grant),
+``open_pane`` and ``reset_row``. It decides nothing about whether a feature may
+run. Platform frameworks are imported lazily so a base or headless installation
+remains importable on every operating system.
"""
from __future__ import annotations
@@ -14,10 +17,10 @@ import os
import sys
import time
from collections.abc import Callable
-from dataclasses import asdict, dataclass
+from dataclasses import dataclass
from enum import StrEnum
from pathlib import Path
-from typing import Any
+from typing import Any, Literal
from jarvis.core.branding import (
MACOS_APP_NAME as APP_NAME,
@@ -25,133 +28,61 @@ from jarvis.core.branding import (
from jarvis.core.branding import (
MACOS_BUNDLE_ID as EXPECTED_BUNDLE_ID,
)
+from jarvis.core.branding import (
+ MACOS_DMG_BUNDLE_ID,
+)
from . import PlatformName, detect_platform
log = logging.getLogger(__name__)
+# Both ways the app reaches a Mac are "the installed app": the managed local
+# bundle and the downloadable .dmg build. They carry different bundle ids and so
+# keep different privacy grants, but each one is the app the user launched —
+# never Terminal or a bare Python. Accepting only the managed id made every
+# permission feature of the .dmg app fail closed even with all grants given, and
+# hid every Allow / Open Settings button, so the user had no way to fix it.
+ACCEPTED_BUNDLE_IDS: tuple[str, ...] = (EXPECTED_BUNDLE_ID, MACOS_DMG_BUNDLE_ID)
+
_SYSTEM_SETTINGS_BUNDLE_ID = "com.apple.systempreferences"
-# Left behind when a bundle rebuild changed this app's ad-hoc signature and
-# the installer therefore dropped its own TCC rows. Without it the user meets
-# an app that has silently forgotten every permission and reads that as the
-# app being broken; with it the UI can say WHY it is asking again.
-_IDENTITY_RESET_FILENAME = "macos-tcc-reset.json"
+# State files an earlier build wrote next to the user's data: the "macOS sees
+# this app as new" note and the recorded Automation answers. Nothing reads
+# either one any more; the names live here only so an upgrade can delete the
+# leftovers once.
+_LEFTOVER_STATE_FILES: tuple[str, ...] = (
+ "macos-tcc-reset.json",
+ "macos-automation-consent.json",
+)
-def identity_reset_marker_path() -> Path:
- """Where the "macOS sees this app as new" note lives."""
+def _leftover_state_dir() -> Path:
from jarvis.core.paths import user_data_dir
- return user_data_dir() / _IDENTITY_RESET_FILENAME
-
-
-def record_identity_reset(services: tuple[str, ...] | list[str]) -> None:
- """Note that a signature change forced this app's TCC grants to be reset.
-
- Best-effort: a note that cannot be written costs an explanation, never a
- working install.
- """
- import json
-
- path = identity_reset_marker_path()
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(
- json.dumps(
- {"reason": "signature-change", "services": list(services)},
- sort_keys=True,
- ),
- encoding="utf-8",
- )
- 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:
- import json
-
- path = identity_reset_marker_path()
- try:
- if not path.is_file():
- return None
- payload = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, ValueError):
- # No file, no permission, or bytes that are not JSON: to every caller
- # these mean the same thing — nothing has been recorded yet, so the
- # probe runs for real instead of trusting a cache.
- return None
- return payload if isinstance(payload, dict) else None
+ return user_data_dir()
-def identity_reset_pending() -> bool:
- """Whether an earlier grant reset has not yet been answered by the user.
+def remove_leftover_state_files() -> None:
+ """Delete the two state files an earlier build left behind; never raises.
- The marker is retired by :meth:`SystemPermissionPort.snapshot` as soon as
- every TCC-governed grant is back. While it survives, the previous reset did
- NOT get the user to a working state — so repeating it can only wipe grants
- again, never fix anything.
+ Best-effort and silent for the user: nothing reads these files, so a failure
+ to remove one costs a few bytes. It never asks for anything and never touches
+ a permission.
"""
- return _read_identity_reset() is not None
-
-
-def _clear_identity_reset() -> None:
- try:
- identity_reset_marker_path().unlink(missing_ok=True)
- except OSError:
- 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)
+ directory = _leftover_state_dir()
+ except Exception: # noqa: BLE001 - housekeeping must never break an install
+ log.debug("Could not locate the data directory for the leftover cleanup.", exc_info=True)
+ return
+ for name in _LEFTOVER_STATE_FILES:
+ try:
+ (directory / name).unlink(missing_ok=True)
+ except OSError:
+ log.debug("Could not remove the leftover %s.", name, exc_info=True)
class PermissionId(StrEnum):
- """Stable identifiers shared by the API and desktop permission UI."""
+ """Stable identifiers shared by the API, the CLI and the desktop permission toast."""
MICROPHONE = "microphone"
SCREEN_RECORDING = "screen_recording"
@@ -190,22 +121,6 @@ class PermissionState(StrEnum):
NOT_REQUIRED = "not_required"
-FEATURE_REQUIREMENTS: dict[str, tuple[PermissionId, ...]] = {
- "voice": (PermissionId.MICROPHONE,),
- "computer_use": (
- PermissionId.SCREEN_RECORDING,
- PermissionId.ACCESSIBILITY,
- PermissionId.EVENT_POSTING,
- ),
- "global_hotkeys": (
- PermissionId.ACCESSIBILITY,
- PermissionId.INPUT_MONITORING,
- ),
- "window_control": (PermissionId.ACCESSIBILITY,),
- "audio_ducking": (PermissionId.AUTOMATION,),
- "api_keys": (PermissionId.CREDENTIAL_STORE,),
-}
-
_LABELS: dict[PermissionId, str] = {
PermissionId.MICROPHONE: "Microphone",
PermissionId.SCREEN_RECORDING: "Screen Recording",
@@ -237,6 +152,92 @@ _SETTINGS_URLS: dict[PermissionId, str] = {
),
}
+
+class RequestClass(StrEnum):
+ """How macOS asks for a permission (the "Class" column of the JIT policy table).
+
+ The just-in-time service reads this to decide what a native request can
+ achieve: whether to wait for an answer, or to send the user to Settings.
+ """
+
+ # An OS dialog with an answer button: the user can allow or deny in place.
+ DIALOG = "dialog"
+ # A request shows at most one dialog that, as far as we know, only offers
+ # "Open System Settings": the user still has to flip a switch there. That
+ # shape is community-observed, not documented by Apple (UNVERIFIED), and the
+ # policy treats it as the cautious reading.
+ PROMPT_ONCE = "prompt_once"
+ # The OS prompts by itself on first access; there is no request call to make.
+ # No :class:`PermissionId` has this class today (Files & Folders is not a
+ # port permission); it exists so the table speaks Apple's whole vocabulary.
+ NATIVE = "native"
+ # Nothing to ask natively (not a TCC grant).
+ NONE = "none"
+
+
+REQUEST_CLASS: dict[PermissionId, RequestClass] = {
+ PermissionId.MICROPHONE: RequestClass.DIALOG,
+ PermissionId.SCREEN_RECORDING: RequestClass.PROMPT_ONCE,
+ PermissionId.ACCESSIBILITY: RequestClass.PROMPT_ONCE,
+ PermissionId.INPUT_MONITORING: RequestClass.PROMPT_ONCE,
+ PermissionId.EVENT_POSTING: RequestClass.PROMPT_ONCE,
+ PermissionId.AUTOMATION: RequestClass.DIALOG,
+ # The Keychain is not TCC: its prompt belongs to the credential store and
+ # "Try again" replays a read, which is not a request in this sense.
+ PermissionId.CREDENTIAL_STORE: RequestClass.NONE,
+}
+
+# Permissions that share one Settings pane (and one request) share a family.
+# EVENT_POSTING is an ALIAS of ACCESSIBILITY for asking: one request, one pane,
+# one episode. The value is the canonical member of the family, which is also
+# what a UI shows and an event carries instead of the alias.
+PANE_FAMILY: dict[PermissionId, PermissionId] = {
+ PermissionId.MICROPHONE: PermissionId.MICROPHONE,
+ PermissionId.SCREEN_RECORDING: PermissionId.SCREEN_RECORDING,
+ PermissionId.ACCESSIBILITY: PermissionId.ACCESSIBILITY,
+ PermissionId.INPUT_MONITORING: PermissionId.INPUT_MONITORING,
+ PermissionId.EVENT_POSTING: PermissionId.ACCESSIBILITY,
+ PermissionId.AUTOMATION: PermissionId.AUTOMATION,
+ PermissionId.CREDENTIAL_STORE: PermissionId.CREDENTIAL_STORE,
+}
+
+# Where a person finds the switch, in plain English (the snapshot row and the docs). The
+# pane names are static text on purpose: no OS sniffing. Apple does not document
+# the label per macOS release (UNVERIFIED): the Screen Recording pane is called
+# "Screen & System Audio Recording" from macOS 15 and was "Screen Recording"
+# before, and the Accessibility pane may be renamed again by a later release.
+# The Keychain has no pane, so it has no entry (like ``_SETTINGS_URLS``).
+_SETTINGS_PATH_PREFIX = "System Settings > Privacy & Security > "
+SETTINGS_PATH_TEXT: dict[PermissionId, str] = {
+ PermissionId.MICROPHONE: f"{_SETTINGS_PATH_PREFIX}Microphone",
+ PermissionId.SCREEN_RECORDING: f"{_SETTINGS_PATH_PREFIX}Screen & System Audio Recording",
+ PermissionId.ACCESSIBILITY: f"{_SETTINGS_PATH_PREFIX}Accessibility",
+ PermissionId.INPUT_MONITORING: f"{_SETTINGS_PATH_PREFIX}Input Monitoring",
+ PermissionId.EVENT_POSTING: f"{_SETTINGS_PATH_PREFIX}Accessibility",
+ PermissionId.AUTOMATION: f"{_SETTINGS_PATH_PREFIX}Automation",
+}
+
+
+def settings_path_text(permission_id: PermissionId | str) -> str | None:
+ """The plain-English System Settings path for a permission, ``None`` without a pane."""
+ return SETTINGS_PATH_TEXT.get(PermissionId(permission_id))
+
+
+# What :meth:`SystemPermissionPort.request_native` reports. Never evidence of a
+# grant: only ``state()`` says whether access exists.
+# dialog_shown - a system dialog may be open right now, awaiting the user's
+# answer (the call returned before the answer): poll ``state()``.
+# no_dialog - nothing is open: access was already granted or decided, the
+# Automation target was not running, or the request was
+# synchronous and has finished: read ``state()`` for the answer.
+# timed_out - Automation only: the consent runner was killed after waiting
+# for an answer nobody gave. Not "the player is not running":
+# the user may simply not have looked yet, so the caller may ask
+# again later.
+# unavailable - the request could not be made (not macOS, a missing framework
+# or symbol, an unusable target, or a native error).
+NativeRequestOutcome = Literal["dialog_shown", "no_dialog", "timed_out", "unavailable"]
+
# 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).
@@ -251,19 +252,18 @@ _AUTOMATION_STATES: dict[int, PermissionState] = {
_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:
+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.
+ called. This is a silent read only: ``_ask`` is accepted for the frozen
+ two-argument seam (tests and ``FakeTCC.automation_probe`` use it) but is
+ NEVER forwarded, so passing ``True`` still reads silently, because an
+ in-process asking call blocks the caller until a dialog is answered and
+ cannot be killed. The consent dialog is raised solely through
+ ``request_native`` (a killable child runner).
"""
if sys.platform != "darwin":
return None
@@ -301,13 +301,65 @@ def _default_automation_probe(bundle_id: str, ask: bool) -> int | None:
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)
- )
+ return int(determine(ctypes.byref(target), _AE_TYPE_WILDCARD, _AE_TYPE_WILDCARD, 0))
finally:
services.AEDisposeDesc(ctypes.byref(target))
+# How long the Automation consent dialog may stay unanswered before its runner
+# is killed. A person answers a dialog; a short timeout tore it down before
+# they could click and made every attempt ask again.
+_AUTOMATION_CONSENT_TIMEOUT_S = 120.0
+
+
+def _is_automation_target(bundle_id: object) -> bool:
+ """Whether ``bundle_id`` names a player in :data:`AUTOMATION_TARGETS`."""
+ return any(bundle_id == known for _name, known in AUTOMATION_TARGETS)
+
+
+def _automation_consent_script(bundle_id: str) -> str:
+ """One benign Apple Event to a player, guarded so it is never launched.
+
+ A bare ``tell application`` launches the app, so the script asks whether it
+ is running INSIDE the same script and does nothing when it is not. Only
+ ``bundle_id`` values from :data:`AUTOMATION_TARGETS` reach this function, so
+ nothing outside the fixed table is ever interpolated.
+ """
+ return (
+ f'if application id "{bundle_id}" is running then\n'
+ f' tell application id "{bundle_id}" to get player state\n'
+ ' return "+"\n'
+ "else\n"
+ ' return "-"\n'
+ "end if"
+ )
+
+
+def _default_automation_consent_runner(script: str) -> Any:
+ """Run one AppleScript in a killable child so a dialog can be answered.
+
+ The consent dialog belongs to the app that asks. A child ``osascript`` is
+ attributed to its parent app (Apple DTS: algorithm undocumented, so
+ UNVERIFIED), and the child, unlike an in-process Apple Event call, can be
+ killed: ``subprocess.run`` kills it when the timeout passes. Returns the
+ ``CompletedProcess``; ``subprocess.TimeoutExpired`` and ``OSError`` propagate
+ to the caller, which owns the never-raise boundary.
+ """
+ import subprocess # lazy: only the darwin request path reaches this
+
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ return subprocess.run( # noqa: S603, S607 - fixed argv, no shell
+ ["osascript", "-e", script],
+ capture_output=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=_AUTOMATION_CONSENT_TIMEOUT_S,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+
+
# 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.
@@ -406,6 +458,27 @@ def _default_iohid_check(request_type: int) -> int | None:
return None
+def _default_iohid_request(request_type: int) -> bool | None:
+ """``IOHIDRequestAccess`` for one request type; ``None`` when unavailable.
+
+ The way to ask for Input Monitoring without creating an event tap (BUG-058
+ class). Only the fallback for a Quartz binding that lacks
+ ``CGRequestListenEventAccess``. Never reached by a state read, and the
+ ctypes binding itself is UNVERIFIED on a real Mac.
+ """
+ try:
+ import ctypes
+
+ iokit = ctypes.CDLL("/System/Library/Frameworks/IOKit.framework/IOKit")
+ request = iokit.IOHIDRequestAccess
+ request.restype = ctypes.c_bool
+ request.argtypes = [ctypes.c_uint32]
+ return bool(request(request_type))
+ except Exception: # noqa: BLE001 - a missing native bridge means "cannot ask"
+ log.debug("IOHIDRequestAccess is unavailable.", exc_info=True)
+ return None
+
+
def _default_credential_store_backend() -> str:
"""Ask the config layer which credential backend is live right now."""
from jarvis.core.config import credential_store_backend
@@ -431,66 +504,39 @@ _TCC_RESET_SERVICES: dict[PermissionId, str] = {
PermissionId.AUTOMATION: "AppleEvents",
}
-_READY_STATES = frozenset({PermissionState.GRANTED, PermissionState.NOT_REQUIRED})
-_RESTART_AFTER_CHANGE = frozenset(
- {
- PermissionId.SCREEN_RECORDING,
- # The global-hotkey backend exits without creating a listener when
- # Accessibility is absent. A restart is therefore required even
- # though AX itself can observe a newly granted value immediately.
- PermissionId.ACCESSIBILITY,
- PermissionId.INPUT_MONITORING,
- }
-)
+# The Info.plist key whose absence makes macOS terminate the process when the
+# permission's API is called (BUG-058 class); ``jarvis.core.macos_privacy_strings``
+# holds the strings themselves and a parity test keeps the key names equal.
+# A permission with no entry has no usage-description key. Screen Recording is
+# deliberately absent: Apple documents none (the string the bundles carry for it
+# is for parity, its effect is UNVERIFIED), so a missing one must not refuse the ask.
+_USAGE_DESCRIPTION_KEYS: dict[PermissionId, str] = {
+ PermissionId.MICROPHONE: "NSMicrophoneUsageDescription",
+ PermissionId.AUTOMATION: "NSAppleEventsUsageDescription",
+}
@dataclass(frozen=True)
class AppIdentity:
+ """Who this process is to macOS (static for the life of the process)."""
+
app_name: str
- expected_bundle_id: str
bundle_id: str | None
bundle_path: str | None
launched_as_bundle: bool
stable: bool
- foreground: bool
-
-
-@dataclass(frozen=True)
-class PermissionStatus:
- id: str
- label: str
- status: str
- required: tuple[str, ...]
- can_request: bool
- can_open_settings: bool
- # Whether dropping THIS app's own TCC row is a sensible next step. The UI
- # must never derive it from ``status == "denied"``: the boolean preflights
- # behind Screen Recording and Accessibility report a stranded grant as
- # "not_granted", so a denial-only rule hid the one control that recovers
- # them — the two permissions most often stranded (BUG-159).
- can_reset: bool
- restart_required: bool
- detail: str | None
-
- def to_dict(self) -> dict[str, Any]:
- payload = asdict(self)
- payload["required"] = list(self.required)
- return payload
@dataclass(frozen=True)
class PermissionOperation:
+ """The answer of :meth:`SystemPermissionPort.reset_row`."""
+
ok: bool
permission_id: str
action: str
performed: bool
dry_run: bool
- restart_required: bool
message: str
- snapshot: dict[str, Any]
-
- def to_dict(self) -> dict[str, Any]:
- return asdict(self)
class SystemPermissionPort:
@@ -506,6 +552,8 @@ class SystemPermissionPort:
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,
+ iohid_request: Callable[[int], bool | None] = _default_iohid_request,
+ automation_consent_runner: Callable[[str], Any] = _default_automation_consent_runner,
) -> None:
self._platform_name = platform_name
self._module_loader = module_loader
@@ -514,14 +562,17 @@ class SystemPermissionPort:
self._credential_store_backend = credential_store_backend
self._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.
- self._restart_required: set[PermissionId] = set()
+ # Seams of :meth:`request_native` only; no state read ever reaches them.
+ self._iohid_request = iohid_request
+ self._automation_consent_runner = automation_consent_runner
# Static per process: the main bundle and its on-disk path cannot
# change while this process runs. Caching it is NOT a cached
# permission probe — every TCC state read in _state() stays live.
self._bundle_identity_cache: tuple[str | None, str | None, bool, bool] | None = None
+ # The pane URL THIS process last opened in System Settings (operation
+ # state, not a probe): a running Settings is closed before an open only
+ # when it may show another pane than the one asked for.
+ self._last_opened_url: str | None = None
@property
def platform(self) -> PlatformName:
@@ -573,58 +624,125 @@ class SystemPermissionPort:
# location. False is the cautious reading and it feeds a
# stability flag the caller already reports on.
canonical_path = False
- stable = bundle_id == EXPECTED_BUNDLE_ID and launched_as_bundle and canonical_path
+ stable = bundle_id in ACCEPTED_BUNDLE_IDS and launched_as_bundle and canonical_path
self._bundle_identity_cache = (bundle_id, bundle_path, launched_as_bundle, stable)
return self._bundle_identity_cache
def _stable_identity(self) -> bool:
- """The cached static half of the runtime-access gate (darwin only)."""
+ """Whether this process is the installed app (cached; darwin only)."""
return self._bundle_identity()[3]
+ @property
+ def outside_installed_app(self) -> bool:
+ """Whether this process is NOT the installed app bundle.
+
+ ``True`` for a development run (Terminal, bare Python), for an app that
+ does not carry one of :data:`ACCEPTED_BUNDLE_IDS`, for one that runs
+ from outside the canonical application folders (a mounted ``.dmg``, the
+ Downloads folder), and everywhere off macOS, where there is no app
+ bundle at all. It is the same verdict ``app_identity.stable`` reports,
+ inverted, and it gates only whether we may start a native request on
+ our own: the grant of whatever app is responsible is still acted on
+ (design P6). Static for the life of the process.
+ """
+ if self.platform != "darwin":
+ return True
+ return not self._stable_identity()
+
+ @property
+ def launched_as_bundle(self) -> bool:
+ """Whether the main bundle is a real ``.app`` (cached; ``False`` off macOS).
+
+ Together with :attr:`outside_installed_app` it tells a copy run from a
+ mounted disk image or the Downloads folder (a bundle, wrongly placed:
+ the grantee is Personal Jarvis itself) from a terminal or IDE run (no
+ bundle: the grantee is the app that started it).
+ """
+ if self.platform != "darwin":
+ return False
+ return bool(self._bundle_identity()[2])
+
+ def has_desktop_session(self) -> bool:
+ """Whether a window server answers, so a dialog or a pane can be shown at all.
+
+ One AppKit round trip: a status route or an ask path calls it, a hot path
+ does not. Fails closed (``False``) when AppKit cannot be read, like the
+ ``headless`` flag of the status snapshot. Off macOS it is the display probe.
+ """
+ if self.platform != "darwin":
+ from .probes import display_present
+
+ return bool(display_present())
+ appkit = self._load("AppKit")
+ if appkit is None:
+ return False
+ try:
+ return appkit.NSWorkspace.sharedWorkspace().frontmostApplication() is not None
+ except Exception: # noqa: BLE001 - fail closed for prompt safety
+ log.debug("Could not read the macOS desktop session.", exc_info=True)
+ return False
+
+ def usage_string_present(self, permission_id: PermissionId | str) -> bool:
+ """Whether the main bundle carries the usage string the permission needs.
+
+ Calling the microphone or Apple Events API without its ``Info.plist``
+ string makes macOS terminate the process (BUG-058 class), so a caller
+ must refuse the native request when this is ``False``. ``True`` also
+ means "not applicable": the permission needs no key (Screen Recording,
+ Accessibility, Input Monitoring and the Keychain have none), this is not
+ macOS, or the process has no bundle id because the responsible code is a
+ terminal and not this app. An unreadable bundle fails closed (``False``).
+ """
+ permission = PermissionId(permission_id)
+ key = _USAGE_DESCRIPTION_KEYS.get(permission)
+ if key is None or self.platform != "darwin":
+ return True
+ if self._bundle_identity()[0] is None:
+ return True
+ foundation = self._load("Foundation")
+ try:
+ value = foundation.NSBundle.mainBundle().objectForInfoDictionaryKey_(key)
+ except Exception: # noqa: BLE001 - an unreadable bundle must not look present
+ log.debug("Could not read %s from the main bundle.", key, exc_info=True)
+ return False
+ present = value is not None and bool(str(value).strip())
+ if not present:
+ log.debug("The main bundle has no %s; %s must not be requested.", key, permission.value)
+ return present
+
def _app_identity(self) -> tuple[AppIdentity, bool]:
+ """``(identity, headless)``: who this process is, and whether a window server answers."""
if self.platform != "darwin":
from .probes import display_present
return (
AppIdentity(
app_name=APP_NAME,
- expected_bundle_id=EXPECTED_BUNDLE_ID,
bundle_id=None,
bundle_path=None,
launched_as_bundle=False,
stable=False,
- foreground=False,
),
not display_present(),
)
bundle_id, bundle_path, launched_as_bundle, stable = self._bundle_identity()
- foreground = False
headless = True
appkit = self._load("AppKit")
if appkit is not None:
try:
- workspace = appkit.NSWorkspace.sharedWorkspace()
- frontmost = workspace.frontmostApplication()
- current = appkit.NSRunningApplication.currentApplication()
- headless = frontmost is None
- if frontmost is not None and current is not None:
- foreground = bool(
- current.isActive() or frontmost.processIdentifier() == os.getpid()
- )
+ headless = appkit.NSWorkspace.sharedWorkspace().frontmostApplication() is None
except Exception: # noqa: BLE001 - fail closed for prompt safety
+ log.debug("Could not read the macOS desktop session.", exc_info=True)
headless = True
- foreground = False
return (
AppIdentity(
app_name=APP_NAME,
- expected_bundle_id=EXPECTED_BUNDLE_ID,
bundle_id=bundle_id,
bundle_path=bundle_path,
launched_as_bundle=launched_as_bundle,
stable=stable,
- foreground=foreground,
),
headless,
)
@@ -730,10 +848,16 @@ class SystemPermissionPort:
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."""
+ def _live_automation_state(self, bundle_id: str) -> PermissionState | None:
+ """The OS answer for a RUNNING target; ``None`` when there is none.
+
+ Always the non-asking form of the probe (``ask`` is False): a state read
+ never raises the dialog. The two-argument probe signature is the frozen
+ seam of the fakes; the consent dialog itself is only ever raised through
+ :meth:`request_native`.
+ """
try:
- status = self._automation_probe(bundle_id, ask)
+ status = self._automation_probe(bundle_id, False)
except Exception: # noqa: BLE001 - native probes never crash callers
log.debug("Automation probe for %s failed.", bundle_id, exc_info=True)
return None
@@ -741,109 +865,83 @@ class SystemPermissionPort:
return None
return _AUTOMATION_STATES.get(int(status))
+ def _player_state(self, bundle_id: str) -> PermissionState:
+ """The live Automation answer for one INSTALLED player; never asks, never writes.
+
+ Apple Events answer only for a RUNNING target, so a player that is not
+ running reads ``NOT_DETERMINED``: unknown, not "never asked" (the answer
+ may well be on file). Nothing is recorded to stand in for it, and the
+ probe can hang for a running player without a window (Apple forums
+ thread 666528), so a caller that must not block runs this off its loop.
+ """
+ appkit = self._load("AppKit")
+ if appkit is not None and self._running_automation_targets(appkit, bundle_id):
+ live = self._live_automation_state(bundle_id)
+ if live is not None:
+ return live
+ return PermissionState.NOT_DETERMINED
+
def _automation_state(self) -> PermissionState:
- """One row for every scriptable player: live when running, else recorded.
+ """One aggregate for every scriptable player, read live; the strictest answer wins.
- 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.
+ No player installed means nothing to consent to. A player that is not
+ running is unknown (``NOT_DETERMINED``). The just-in-time service reads
+ one player at a time through ``target``; this aggregate is for a caller
+ that has no target.
"""
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):
- # Nothing recorded for this player (or an unknown value
- # from a newer build): "not asked yet" is the honest read.
- 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)
+ states = [self._player_state(bundle_id) for bundle_id in installed]
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.
+ def _automation_target_state(self, bundle_id: str) -> PermissionState:
+ """The Automation state for ONE player from :data:`AUTOMATION_TARGETS`."""
+ if not _is_automation_target(bundle_id):
+ log.debug(
+ "Automation state requested for %r, which is not a scriptable player.", bundle_id
+ )
+ return PermissionState.UNAVAILABLE
+ installed = self._installed_automation_targets()
+ if installed is None:
+ return PermissionState.UNAVAILABLE
+ if bundle_id not in installed:
+ # Nothing to script, so nothing to consent to.
+ return PermissionState.NOT_REQUIRED
+ return self._player_state(bundle_id)
- 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:
+ def _state(
+ self,
+ permission_id: PermissionId,
+ *,
+ deep: bool,
+ target: str | None = None,
+ ) -> PermissionState:
if self.platform != "darwin":
return PermissionState.NOT_REQUIRED
if permission_id is PermissionId.CREDENTIAL_STORE:
return self._credential_store_state()
if permission_id is PermissionId.AUTOMATION:
+ if target is not None:
+ return self._automation_target_state(target)
return self._automation_state()
if permission_id is PermissionId.MICROPHONE:
return self._microphone_state()
if permission_id is PermissionId.SCREEN_RECORDING:
preflight = self._boolean_state("Quartz", "CGPreflightScreenCaptureAccess")
- if preflight is PermissionState.GRANTED:
+ if preflight is PermissionState.GRANTED or not deep:
return preflight
# The preflight is frozen per process and can only go stale
# NEGATIVE. Ask the window server whether the grant works right
# now before telling the user a permission they just gave is
- # missing (BUG-161).
+ # missing (BUG-161). Only a deep read does this: it enumerates the
+ # on-screen windows, which a hot path must never pay for.
return PermissionState.GRANTED if self._screen_capture_live() else preflight
if permission_id is PermissionId.ACCESSIBILITY:
return self._boolean_state("ApplicationServices", "AXIsProcessTrusted")
@@ -873,390 +971,186 @@ class SystemPermissionPort:
# Accessibility grant and do not expose the separate PostEvent API.
return ax_state
- def _live_state(self, permission_id: PermissionId) -> PermissionState:
- """Probe once and retire a pending-restart flag the OS has overtaken.
-
- A pending restart means exactly one thing: "the grant is not usable in
- THIS process yet". The moment a live probe reads it as ready that claim
- is false, so the flag must die right there — no probe can report a
- grant the process cannot use (the one per-process-frozen probe, Screen
- Recording, can only stay stale NEGATIVE; it never turns falsely
- positive). Keeping the flag past that point is what made a single
- "Open Settings" click disable Computer-Use and hotkeys until relaunch
- even though every permission was granted, and no code path ever
- cleared it again (BUG-159).
+ def state(
+ self,
+ permission_id: PermissionId | str,
+ *,
+ target: str | None = None,
+ deep: bool = False,
+ ) -> PermissionState:
+ """Probe one permission live, without asking.
+
+ Every read goes to the OS and nothing is cached. This never prompts:
+ no native request and no ``ask`` path is reachable from here.
+
+ ``target`` is only meaningful for Automation: the bundle id of one
+ player from :data:`AUTOMATION_TARGETS`. A target that is not one of
+ them reads ``UNAVAILABLE`` (logged at debug, never raised); for every
+ other permission it is ignored. Without a target, Automation reads one
+ aggregate over every installed player, live (nothing is recorded to
+ stand in for a player that is not running).
+
+ ``deep`` only matters for Screen Recording. ``False`` (the default) is the
+ preflight alone and NEVER enumerates windows. ``True`` also runs the
+ window-title oracle that sees a grant the frozen preflight still denies
+ (BUG-161); it enumerates the on-screen windows, so a hot path never asks
+ for it.
"""
- state = self._state(permission_id)
- if state in _READY_STATES:
- self._restart_required.discard(permission_id)
- return state
-
- def state(self, permission_id: PermissionId | str) -> PermissionState:
- """Probe one permission directly without constructing a full snapshot."""
- return self._live_state(PermissionId(permission_id))
-
- def runtime_access_granted(self, permission_id: PermissionId | str) -> bool:
- """Fail closed unless this installed app can use the grant right now."""
- resolved = PermissionId(permission_id)
- if self.platform != "darwin":
- return self._live_state(resolved) in _READY_STATES
- # Only the STATIC identity half gates runtime access — skip the
- # AppKit foreground probe _app_identity() also performs; its result
- # was never consulted here and it costs a window-server round trip.
- # _live_state clears any stale pending-restart flag first, so no
- # separate check against it remains: a GRANTED probe IS live access.
- return self._stable_identity() and self._live_state(resolved) is PermissionState.GRANTED
-
- def runtime_feature_ready(self, feature: str) -> bool:
- """Check every live grant for a feature under one stable app identity."""
- requirements = FEATURE_REQUIREMENTS[feature]
- if self.platform != "darwin":
- return all(self._live_state(item) in _READY_STATES for item in requirements)
- # all() short-circuits, so probe every requirement first: a later
- # requirement's stale restart flag must heal even when an earlier one
- # is still missing.
- states = [self._live_state(item) for item in requirements]
- return self._stable_identity() and all(state is PermissionState.GRANTED for state in states)
-
- 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)
- return callable(getattr(owner, "requestAccessForMediaType_completionHandler_", None))
- if permission_id is PermissionId.ACCESSIBILITY:
- module = self._load("ApplicationServices")
- return callable(getattr(module, "AXIsProcessTrustedWithOptions", None))
- module = self._load("Quartz")
- name = {
- PermissionId.SCREEN_RECORDING: "CGRequestScreenCaptureAccess",
- PermissionId.INPUT_MONITORING: "CGRequestListenEventAccess",
- PermissionId.EVENT_POSTING: "CGRequestPostEventAccess",
- }[permission_id]
- native_request = getattr(module, name, None)
- if permission_id is not PermissionId.EVENT_POSTING or callable(native_request):
- return callable(native_request)
- app_services = self._load("ApplicationServices")
- return callable(getattr(app_services, "AXIsProcessTrustedWithOptions", None))
-
- @staticmethod
- def _detail(state: PermissionState) -> str | None:
- return {
- PermissionState.GRANTED: None,
- PermissionState.NOT_REQUIRED: (
- "This operating system does not require a macOS TCC grant."
- ),
- PermissionState.NOT_DETERMINED: "The user has not chosen yet.",
- PermissionState.DENIED: "Access was denied; use System Settings.",
- PermissionState.RESTRICTED: ("Access is restricted by the system or device policy."),
- PermissionState.NOT_GRANTED: "Access has not been granted.",
- PermissionState.UNAVAILABLE: (
- "The native permission API is unavailable in this installation."
- ),
- }[state]
-
- def snapshot(self) -> dict[str, Any]:
- """Return a fresh native snapshot; no permission result is retained."""
- identity, headless = self._app_identity()
- statuses: list[PermissionStatus] = []
- states: dict[PermissionId, PermissionState] = {}
- eligible = (
- self.platform == "darwin" and identity.stable and identity.foreground and not headless
- )
- # Opening a System Settings pane is not a prompt: it works from the
- # background, so it must not disappear together with the request
- # button when the user is looking at another window.
- settings_reachable = self.platform == "darwin" and identity.stable and not headless
- for permission_id in PermissionId:
- state = self._live_state(permission_id)
- states[permission_id] = state
- required = tuple(
- feature
- for feature, requirements in FEATURE_REQUIREMENTS.items()
- if permission_id in requirements
- )
- restart_pending = permission_id in self._restart_required
- # After the first request/settings visit macOS never re-prompts in
- # this process (and the Screen Recording preflight stays frozen
- # until relaunch), so a second request button would be a dead
- # control — hide it and let the restart call-to-action take over.
- can_request = (
- eligible
- and not restart_pending
- and self._requester_available(permission_id)
- and state
- not in {
- PermissionState.GRANTED,
- PermissionState.NOT_REQUIRED,
- PermissionState.RESTRICTED,
- PermissionState.DENIED,
- PermissionState.UNAVAILABLE,
- }
- )
- detail = self._detail(state)
- if (
- permission_id is PermissionId.CREDENTIAL_STORE
- and state is PermissionState.NOT_GRANTED
- ):
- detail = (
- "Keychain access was declined, so API keys are kept in a "
- "local file for now. Allow access to store them encrypted "
- "in the macOS Keychain."
- )
- # Offer the tccutil escape hatch whenever a TCC-governed grant is
- # missing — NOT only on an explicit "denied". A stranded grant
- # (the recorded row belongs to a previous ad-hoc signature) reads
- # as plain "not granted" while System Settings still shows the
- # checkmark, and no request can ever reach the user because macOS
- # already has a decision on file.
- #
- # The one row that must NOT offer it is Screen Recording with a
- # restart pending: its preflight is frozen for the life of the
- # process, so "not granted" there may well be a grant the user
- # just gave — resetting would throw it away. Every other probe
- # reads live TCC state, so a missing grant is really missing and
- # the reset is safe even mid-restart.
- can_reset = (
- self.platform == "darwin"
- and identity.stable
- and not headless
- and permission_id in _TCC_RESET_SERVICES
- and state not in _READY_STATES
- and not (restart_pending and permission_id is PermissionId.SCREEN_RECORDING)
- )
- if restart_pending and state not in _READY_STATES:
- detail = (
- "Permission changes made in System Settings take effect "
- "after Personal Jarvis restarts."
- )
- elif can_reset and not can_request:
- # No prompt left and the grant is missing: name the only move
- # that still works instead of leaving a dead-end row.
- detail = (
- "macOS already has a decision on file for this app and "
- "will not ask again. If System Settings shows access as "
- "enabled, the recorded grant belongs to an earlier build "
- 'of the app — use "Ask again" to clear it, then allow '
- "access once more."
- )
- statuses.append(
- PermissionStatus(
- id=permission_id.value,
- label=_LABELS[permission_id],
- status=state.value,
- required=required,
- can_request=can_request,
- # The Keychain has no System Settings pane; its only
- # recovery path is the request flow above.
- can_open_settings=settings_reachable and permission_id in _SETTINGS_URLS,
- can_reset=can_reset,
- restart_required=restart_pending,
- detail=detail,
- )
- )
+ return self._state(PermissionId(permission_id), deep=deep, target=target)
- features: dict[str, dict[str, Any]] = {}
- for feature, requirements in FEATURE_REQUIREMENTS.items():
- missing = [
- permission_id.value
- for permission_id in requirements
- if states[permission_id] not in _READY_STATES
- ]
- identity_ready = self.platform != "darwin" or identity.stable
- restart_required = any(
- permission_id in self._restart_required for permission_id in requirements
- )
- features[feature] = {
- "ready": not missing and identity_ready and not restart_required,
- "missing": missing,
- "identity_ready": identity_ready,
- "restart_required": restart_required,
- }
-
- # A signature change wipes the recorded grants. Surface that as its own
- # fact so the UI can explain the re-ask instead of looking amnesic, and
- # retire the note the moment every TCC-governed grant is back.
- identity_reset = _read_identity_reset() if self.platform == "darwin" else None
- if identity_reset is not None and all(
- states[permission_id] in _READY_STATES for permission_id in _TCC_RESET_SERVICES
- ):
- _clear_identity_reset()
- identity_reset = None
-
- return {
- "platform": self.platform,
- "supported": self.platform == "darwin",
- "headless": headless,
- "app_identity": asdict(identity),
- "permissions": [status.to_dict() for status in statuses],
- "features": features,
- "identity_reset": identity_reset,
- "restart_required": bool(self._restart_required),
- }
-
- def _eligibility_error(
- self, snapshot: dict[str, Any], *, needs_foreground: bool = True
- ) -> str | None:
- if self.platform != "darwin":
- return "macOS permission requests are not required on this platform."
- if snapshot["headless"]:
- return "Permission requests require an interactive macOS desktop session."
- identity = snapshot["app_identity"]
- if not identity["stable"]:
- return (
- "Relaunch Personal Jarvis from its installed app before requesting "
- "permissions; granting access to Terminal or Python is unsafe."
- )
- # Only the native PROMPT needs the foreground — a dialog raised behind
- # other windows is a dialog the user never answers. Opening a Settings
- # pane through LaunchServices does not, and refusing it in the
- # background left the browser surface with a permission banner that
- # offered no way out at all (BUG-161).
- if needs_foreground and not identity["foreground"]:
- return "Bring Personal Jarvis to the foreground and try again."
- return None
-
- def _native_request(self, permission_id: PermissionId) -> bool | None:
- """Fire the native prompt API; return its boolean where one exists.
-
- The CG*/AX requesters report ``True`` when access is (already) granted
- and ``False`` otherwise. ``False`` covers BOTH "the dialog is up right
- now" and "macOS silently suppressed the dialog because an earlier
- decision is on record" — the caller words its answer so it stays true
- in either case. ``None`` = the API reports nothing (microphone,
- Keychain replay).
+ def request_native(
+ self,
+ permission_id: PermissionId | str,
+ *,
+ target: str | None = None,
+ ) -> NativeRequestOutcome:
+ """Perform ONLY the native request for one permission; never raises.
+
+ It makes no identity check of its own: whether we may
+ ask at all is the caller's decision (design P6), and the caller must also
+ have confirmed :meth:`usage_string_present` first. The return value
+ says what the OS may now be doing (see :data:`NativeRequestOutcome`) and
+ is NEVER evidence of a grant: only :meth:`state` is. Nothing is
+ recorded here either.
+
+ EVENT_POSTING is an alias of ACCESSIBILITY for asking, so both make the
+ one Accessibility request. Automation needs ``target`` (a bundle id from
+ :data:`AUTOMATION_TARGETS`); it runs through a killable child, never
+ launches the player, and is synchronous: it returns once the dialog was
+ answered or the child was killed after the timeout (``"timed_out"``; that
+ macOS then tears the dialog down is UNVERIFIED), so it can block for
+ minutes and belongs on a worker thread. A failure is logged at debug
+ and reported as ``"unavailable"``.
"""
+ try:
+ permission = PermissionId(permission_id)
+ except (ValueError, TypeError):
+ log.debug("Native request for the unknown permission %r ignored.", permission_id)
+ return "unavailable"
+ if self.platform != "darwin":
+ return "unavailable"
+ if permission is PermissionId.EVENT_POSTING:
+ permission = PermissionId.ACCESSIBILITY
+ try:
+ return self._issue_native_request(permission, target)
+ except Exception: # noqa: BLE001 - the native request boundary never raises
+ log.debug("The native %s request failed.", permission.value, exc_info=True)
+ return "unavailable"
+
+ def _issue_native_request(
+ self, permission_id: PermissionId, target: str | None
+ ) -> NativeRequestOutcome:
+ """The per-permission native call behind :meth:`request_native` (may raise)."""
if permission_id is PermissionId.CREDENTIAL_STORE:
# Replaying the failed Keychain read is the only supported way to
- # make macOS show the prompt again; the outcome (allowed or denied
- # once more) lands honestly in the after-snapshot.
+ # make macOS show its prompt again. Synchronous: it has been
+ # answered when this returns.
self._credential_store_recover()
- return None
+ return "no_dialog"
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 None
+ return self._request_automation_target(target)
if permission_id is PermissionId.MICROPHONE:
av = self._load("AVFoundation")
- av.AVCaptureDevice.requestAccessForMediaType_completionHandler_(
- av.AVMediaTypeAudio, lambda _granted: None
- )
- return None
+ owner = getattr(av, "AVCaptureDevice", None)
+ request = getattr(owner, "requestAccessForMediaType_completionHandler_", None)
+ if not callable(request):
+ return "unavailable"
+ # The call returns nothing: the status read beforehand is the only
+ # way to tell a dialog (not determined) from a silent no-op.
+ before = self._microphone_state()
+ request(av.AVMediaTypeAudio, lambda _granted: None)
+ return "dialog_shown" if before is PermissionState.NOT_DETERMINED else "no_dialog"
if permission_id is PermissionId.ACCESSIBILITY:
app_services = self._load("ApplicationServices")
- prompt_key = app_services.kAXTrustedCheckOptionPrompt
- return bool(app_services.AXIsProcessTrustedWithOptions({prompt_key: True}))
- quartz = self._load("Quartz")
- name = {
- PermissionId.SCREEN_RECORDING: "CGRequestScreenCaptureAccess",
- PermissionId.INPUT_MONITORING: "CGRequestListenEventAccess",
- PermissionId.EVENT_POSTING: "CGRequestPostEventAccess",
- }[permission_id]
- requester = getattr(quartz, name, None)
- if callable(requester):
- return bool(requester())
- if permission_id is PermissionId.EVENT_POSTING:
- app_services = self._load("ApplicationServices")
- prompt_key = app_services.kAXTrustedCheckOptionPrompt
- return bool(app_services.AXIsProcessTrustedWithOptions({prompt_key: True}))
- raise RuntimeError(f"Native permission request is unavailable: {name}")
-
- def request(self, permission_id: PermissionId, *, dry_run: bool = False) -> PermissionOperation:
- """Invoke Apple's supported prompt API after identity/foreground checks."""
- before = self.snapshot()
- current = next(item for item in before["permissions"] if item["id"] == permission_id.value)
- if dry_run:
- return PermissionOperation(
- ok=True,
- permission_id=permission_id.value,
- action="request",
- performed=False,
- dry_run=True,
- restart_required=False,
- message=f"Would request {_LABELS[permission_id]} access.",
- snapshot=before,
- )
- error = self._eligibility_error(before)
- if error is not None:
- return PermissionOperation(
- False, permission_id.value, "request", False, False, False, error, before
- )
- if current["status"] == PermissionState.GRANTED.value:
- restart = permission_id in self._restart_required
- return PermissionOperation(
- True,
- permission_id.value,
- "request",
- False,
- False,
- restart,
- f"{_LABELS[permission_id]} access is already granted.",
- before,
- )
- if not current["can_request"]:
- return PermissionOperation(
- False,
- permission_id.value,
- "request",
- False,
- False,
- False,
- current["detail"] or "This permission cannot be requested now.",
- before,
- )
+ trusted_with_options = getattr(app_services, "AXIsProcessTrustedWithOptions", None)
+ prompt_key = getattr(app_services, "kAXTrustedCheckOptionPrompt", None)
+ if not callable(trusted_with_options) or prompt_key is None:
+ return "unavailable"
+ # Prompting is asynchronous and does not change the return value. A
+ # False answer covers both "the dialog is up now" and "macOS
+ # suppressed it", so it is reported as a dialog that MAY be open.
+ trusted = bool(trusted_with_options({prompt_key: True}))
+ return "no_dialog" if trusted else "dialog_shown"
+ if permission_id is PermissionId.SCREEN_RECORDING:
+ quartz = self._load("Quartz")
+ request = getattr(quartz, "CGRequestScreenCaptureAccess", None)
+ if not callable(request):
+ return "unavailable"
+ return "no_dialog" if bool(request()) else "dialog_shown"
+ if permission_id is PermissionId.INPUT_MONITORING:
+ # Asked through the request calls only, never by creating an event
+ # tap (BUG-058 class). The tri-state read beforehand tells a dialog
+ # (not determined) from a decision already on file.
+ before = self._iohid_state(_IOHID_REQUEST_LISTEN_EVENT)
+ quartz = self._load("Quartz")
+ request = getattr(quartz, "CGRequestListenEventAccess", None)
+ if callable(request):
+ answer: bool | None = bool(request())
+ else:
+ answer = self._iohid_request(_IOHID_REQUEST_LISTEN_EVENT)
+ if answer is None:
+ return "unavailable"
+ if answer or before in {PermissionState.GRANTED, PermissionState.DENIED}:
+ return "no_dialog"
+ return "dialog_shown"
+ raise RuntimeError(f"No native request exists for {permission_id.value}")
+
+ def _request_automation_target(self, target: str | None) -> NativeRequestOutcome:
+ """Ask for ONE player's Automation consent through a killable child.
+
+ The child is a guarded AppleScript, so a player that is not running is
+ left alone (nothing is launched, hidden or otherwise) and nothing is
+ asked for it. Nothing here holds a lock or writes a record.
+ """
+ import subprocess # lazy: only the darwin request path reaches this
+
+ if target is None or not _is_automation_target(target):
+ log.debug("Automation consent needs a scriptable player, got %r.", target)
+ return "unavailable"
try:
- prompted = self._native_request(permission_id)
- except Exception as exc: # noqa: BLE001 - native request boundary
- return PermissionOperation(
- False,
- permission_id.value,
- "request",
- False,
- False,
- False,
- f"The native permission request failed: {type(exc).__name__}.",
- self.snapshot(),
- )
- if permission_id in _RESTART_AFTER_CHANGE:
- self._restart_required.add(permission_id)
- after = self.snapshot()
- # Read the flag back from the snapshot: a permission whose probe reads
- # live (Accessibility, Input Monitoring) is already granted again by
- # the time we get here, and _live_state retired the flag. Reporting a
- # restart the snapshot contradicts is how the banner and the row ended
- # up disagreeing (BUG-159).
- restart = permission_id in self._restart_required
- message = (
- "Permission requested. Restart Personal Jarvis after granting access."
- if restart
- else "Permission requested; the status will update after your choice."
- )
- if prompted is False:
- # macOS prompts each app identity exactly once. Name both the
- # Settings route and the reset, because a checkmark that is
- # already set there means the recorded grant is stranded on an
- # older signature and only a reset can revive the prompt.
- message = (
- "macOS did not show a dialog: it already has a decision on "
- "file for this app. Enable Personal Jarvis in System Settings "
- "> Privacy & Security — and if it is already enabled there, "
- 'use "Ask again" to clear the stale record first.'
- )
- return PermissionOperation(
- True,
- permission_id.value,
- "request",
- True,
- False,
- restart,
- message,
- after,
+ completed = self._automation_consent_runner(_automation_consent_script(target))
+ except subprocess.TimeoutExpired:
+ # The runner has killed the child. Whether macOS tears down the
+ # dialog the child raised is not documented by Apple (UNVERIFIED), so
+ # the state read stays the only truth about an answer, and the caller
+ # hears "timed_out" rather than "no_dialog" (a player that is not
+ # running): the user may simply not have looked yet.
+ log.debug("The Automation consent for %s was not answered in time.", target)
+ return "timed_out"
+ if completed is None:
+ return "unavailable"
+ log.debug(
+ "The Automation consent run for %s ended with rc=%s.",
+ target,
+ getattr(completed, "returncode", None),
)
+ return "no_dialog"
+
+ def open_pane(self, permission_id: PermissionId | str) -> bool:
+ """Open the System Settings pane of a permission; nothing else. Never raises.
+
+ Opening a pane is not a prompt and not an action on the permission, so it
+ does not need the
+ installed-app identity (design P6: identity decides who may RESET and
+ whether we may auto-ASK, not who may open a pane); it only needs a desktop
+ session. ``False`` when there is no pane, no session or the open failed.
+ """
+ try:
+ permission = PermissionId(permission_id)
+ except (ValueError, TypeError):
+ log.debug("Opening the pane of the unknown permission %r ignored.", permission_id)
+ return False
+ if self.platform != "darwin" or permission not in _SETTINGS_URLS:
+ return False
+ try:
+ if not self.has_desktop_session():
+ log.debug("No desktop session: the %s pane is not opened.", permission.value)
+ return False
+ opened = self._open_settings(permission)
+ except Exception: # noqa: BLE001 - the native settings boundary
+ log.debug("Opening the %s pane failed.", permission.value, exc_info=True)
+ return False
+ return opened
def _quit_system_settings(self, appkit: Any) -> None:
"""Close a running System Settings so the pane deep link can navigate.
@@ -1292,35 +1186,48 @@ class SystemPermissionPort:
foundation = self._load("Foundation")
if appkit is None or foundation is None:
return False
- self._quit_system_settings(appkit)
- url = foundation.NSURL.URLWithString_(_SETTINGS_URLS[permission_id])
- return bool(appkit.NSWorkspace.sharedWorkspace().openURL_(url))
-
- def reset(self, permission_id: PermissionId, *, dry_run: bool = False) -> PermissionOperation:
+ url_text = _SETTINGS_URLS[permission_id]
+ # Terminate a running Settings only when it may show ANOTHER pane than the
+ # one asked for: the anchor of a running instance is ignored (observed on
+ # macOS 15.7, not documented, UNVERIFIED), but closing the window the user
+ # already has on the right pane for no reason is rude. What this process
+ # last opened is all we know; the user may have navigated since.
+ if self._last_opened_url != url_text:
+ self._quit_system_settings(appkit)
+ url = foundation.NSURL.URLWithString_(url_text)
+ opened = bool(appkit.NSWorkspace.sharedWorkspace().openURL_(url))
+ if opened:
+ self._last_opened_url = url_text
+ return opened
+
+ def reset_row(
+ self, permission_id: PermissionId, *, dry_run: bool = False
+ ) -> PermissionOperation:
"""Drop this app's own TCC row so the native prompt can appear again.
- The in-app way out of the auto-denied trap: once ANY build of the
- app ever created an input listener before the user was asked - or a
- signature change orphaned the recorded grant (BUG-083) - macOS
- silently registers the app as DENIED and suppresses every further
- prompt. The permissions view then shows a dead "Denied" forever.
- ``tccutil reset <service> <our bundle id>`` returns that one row to
- "not determined" (never touching other apps' grants), so the real
- system dialog can fire again on the next request.
+ The in-app way out of the auto-denied trap: once ANY build of the app
+ ever created an input listener before the user was asked - or a signature
+ change orphaned the recorded grant (BUG-083) - macOS silently registers
+ the app as DENIED and suppresses every further prompt.
+ ``tccutil reset <service> <our bundle id>`` returns that one row to "not
+ determined" (never touching other apps' grants), so the real system
+ dialog can fire again on the next request.
+
+ Only the installed app may name its own bundle id: the .dmg build owns
+ ``ai.personaljarvis.desktop`` and never touched the managed bundle's rows,
+ while a development run (Terminal, bare Python) must not be able to wipe
+ the installed app's grants. A dry run changes nothing. Only ``tccutil``
+ runs here; nothing is probed, the caller reads the one permission it cares
+ about before and after.
"""
- before = self.snapshot()
- service = _TCC_RESET_SERVICES.get(permission_id)
+ service = tcc_reset_service(permission_id)
+ label = _LABELS[permission_id]
+
+ def refused(message: str) -> PermissionOperation:
+ return PermissionOperation(False, permission_id.value, "reset", False, dry_run, message)
+
if self.platform != "darwin" or service is None:
- return PermissionOperation(
- False,
- permission_id.value,
- "reset",
- False,
- dry_run,
- False,
- f"{_LABELS[permission_id]} has no resettable macOS record.",
- before,
- )
+ return refused(f"{label} has no resettable macOS record.")
if dry_run:
return PermissionOperation(
True,
@@ -1328,18 +1235,20 @@ class SystemPermissionPort:
"reset",
False,
True,
- False,
- f"Would reset this app's {_LABELS[permission_id]} record.",
- before,
+ f"Would reset this app's {label} record.",
+ )
+ bundle_id, _path, _launched, stable = self._bundle_identity()
+ if not stable or not bundle_id:
+ return refused(
+ "Relaunch Personal Jarvis from its installed app before resetting a permission."
)
import subprocess # lazy: this method is darwin-only at runtime
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
- from jarvis.setup.macos_app_bundle import BUNDLE_ID
try:
result = subprocess.run(
- ["/usr/bin/tccutil", "reset", service, BUNDLE_ID],
+ ["/usr/bin/tccutil", "reset", service, bundle_id],
capture_output=True,
text=True,
timeout=30,
@@ -1347,131 +1256,65 @@ class SystemPermissionPort:
creationflags=NO_WINDOW_CREATIONFLAGS,
)
performed = result.returncode == 0
- detail = (result.stderr or result.stdout or "").strip()
+ if not performed:
+ log.debug(
+ "tccutil reset %s failed with status %s: %s",
+ service,
+ result.returncode,
+ (result.stderr or result.stdout or "").strip()[-200:],
+ )
except (OSError, subprocess.TimeoutExpired) as exc:
- # Not silent: the reason travels on as the operation's own detail
- # and is what the user is shown when the permission call failed.
+ # The person reads a fixed sentence (no OS error text, no paths); the
+ # reason is kept in the debug log.
performed = False
- detail = str(exc)
+ log.debug("tccutil reset %s could not run", service, exc_info=exc)
if not performed:
- return PermissionOperation(
- False,
- permission_id.value,
- "reset",
- False,
- False,
- False,
- f"Could not reset the {_LABELS[permission_id]} record: "
- f"{detail[-200:] or 'unknown error'}",
- 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 refused(f"Could not reset the {label} record.")
return PermissionOperation(
True,
permission_id.value,
"reset",
True,
False,
- False,
- f"{_LABELS[permission_id]} was reset - the system prompt can "
- "appear again on the next request.",
- self.snapshot(),
+ f"{label} was reset - the system prompt can appear again on the next request.",
)
- def open_settings(
- self, permission_id: PermissionId, *, dry_run: bool = False
- ) -> PermissionOperation:
- """Open the matching System Settings pane via LaunchServices."""
- before = self.snapshot()
- if permission_id not in _SETTINGS_URLS:
- return PermissionOperation(
- False,
- permission_id.value,
- "open_settings",
- False,
- dry_run,
- False,
- f"{_LABELS[permission_id]} has no System Settings pane; "
- "use the request flow instead.",
- before,
- )
- if dry_run:
- return PermissionOperation(
- True,
- permission_id.value,
- "open_settings",
- False,
- True,
- False,
- f"Would open {_LABELS[permission_id]} in System Settings.",
- before,
- )
- error = self._eligibility_error(before, needs_foreground=False)
- if error is not None:
- return PermissionOperation(
- False,
- permission_id.value,
- "open_settings",
- False,
- False,
- False,
- error,
- before,
- )
- try:
- opened = self._open_settings(permission_id)
- except Exception: # noqa: BLE001 - native settings boundary
- opened = False
- # Only a grant that is actually MISSING can be changed into something
- # this process must restart for. Flagging a restart merely because the
- # user looked at an already-granted pane disabled the very features
- # the pane governs until relaunch (BUG-159).
- already_granted = next(
- item for item in before["permissions"] if item["id"] == permission_id.value
- )["status"] in {PermissionState.GRANTED.value, PermissionState.NOT_REQUIRED.value}
- restart = opened and permission_id in _RESTART_AFTER_CHANGE and not already_granted
- if restart:
- self._restart_required.add(permission_id)
- after = self.snapshot()
- return PermissionOperation(
- opened,
- permission_id.value,
- "open_settings",
- opened,
- False,
- restart,
- (
- "System Settings opened. Restart Personal Jarvis after changing access."
- if restart
- else (
- "System Settings opened." if opened else "System Settings could not be opened."
- )
- ),
- after,
- )
+
+def tcc_reset_service(permission_id: PermissionId) -> str | None:
+ """The ``tccutil`` service name of ``permission_id``, or ``None`` when it has no TCC row.
+
+ The one table behind ``tccutil reset <service> <bundle id>``: the port's
+ :meth:`SystemPermissionPort.reset_row` and the local ``jarvis permissions reset``
+ command both read it, so the two can never disagree about a service name.
+ """
+ return _TCC_RESET_SERVICES.get(permission_id)
_DEFAULT_SYSTEM_PERMISSION_PORT = SystemPermissionPort()
def get_system_permission_port() -> SystemPermissionPort:
- """Return the process-wide port that retains only pending-restart state."""
+ """Return the process-wide port; it keeps only the static bundle identity."""
return _DEFAULT_SYSTEM_PERMISSION_PORT
__all__ = [
+ "ACCEPTED_BUNDLE_IDS",
"APP_NAME",
"AUTOMATION_TARGETS",
"EXPECTED_BUNDLE_ID",
- "FEATURE_REQUIREMENTS",
+ "PANE_FAMILY",
+ "REQUEST_CLASS",
+ "SETTINGS_PATH_TEXT",
"AppIdentity",
+ "NativeRequestOutcome",
"PermissionId",
"PermissionOperation",
"PermissionState",
- "PermissionStatus",
+ "RequestClass",
"SystemPermissionPort",
"get_system_permission_port",
+ "remove_leftover_state_files",
+ "settings_path_text",
+ "tcc_reset_service",
]
diff --git a/jarvis/platform/probes.py b/jarvis/platform/probes.py
index f0e2a7de28..08099ac53b 100644
--- a/jarvis/platform/probes.py
+++ b/jarvis/platform/probes.py
@@ -86,32 +86,6 @@ def ax_permission_granted() -> bool | None:
return bool(os.environ.get("AT_SPI_BUS") or os.environ.get("DBUS_SESSION_BUS_ADDRESS"))
-def screen_recording_granted() -> bool | None:
- """Tri-state: is screen capture (screenshot) permitted?
-
- ``True`` granted (or no grant needed) · ``False`` explicitly denied · ``None``
- unknown (macOS where pyobjc-Quartz is absent, so we cannot probe). Only macOS
- gates screenshots behind a TCC "Screen Recording" grant; Windows and Linux
- need no per-app grant — Wayland's capture restriction is a separate, non-TCC
- concern handled at the capture site. Without the macOS grant ``mss`` returns
- only the desktop wallpaper with no error, so Computer-Use would click blind;
- callers detect-and-degrade with a clear message (AD-13), never hard-block.
- """
- if detect_platform() != "darwin":
- return True
- try:
- from Quartz import ( # type: ignore[import-not-found]
- CGPreflightScreenCaptureAccess,
- )
- except (ImportError, ModuleNotFoundError):
- return None # pyobjc-Quartz absent → unknown until installed.
- try:
- return bool(CGPreflightScreenCaptureAccess())
- except Exception: # pragma: no cover - native call guard
- log.debug("CGPreflightScreenCaptureAccess() raised; treating as unknown.")
- return None
-
-
def has_ax_tree() -> bool:
"""Is a UI-element accessibility tree backend available for this OS?"""
plat = detect_platform()
@@ -188,7 +162,6 @@ __all__ = [
"is_wayland",
"has_pty",
"ax_permission_granted",
- "screen_recording_granted",
"has_ax_tree",
"has_hotkey",
"has_cursor",
diff --git a/jarvis/platform/screen_access.py b/jarvis/platform/screen_access.py
new file mode 100644
index 0000000000..efd2c50154
--- /dev/null
+++ b/jarvis/platform/screen_access.py
@@ -0,0 +1,508 @@
+"""Screen Recording access for the capture consumers (just-in-time permissions).
+
+Every screen capture on macOS is gated by the Screen Recording permission, and
+the gate fails SILENTLY: without the grant the capture returns the desktop
+wallpaper and no error. This module is the one place the capture consumers go
+through, with two rules from the permission rebuild (docs/macos-permissions.md, 4.6):
+
+* **Helpers never ask.** A per-frame fast path, a region grab or a status probe
+ reads the state through :func:`screen_recording_state` (silent, cheap) and
+ degrades. It never makes macOS show a dialog and never raises a toast.
+* **Only a user gesture asks.** The entry point of a capture that a person
+ started (the ``screenshot`` tool body, a screen-context request, the first
+ Computer-Use frame of a step) calls :func:`require_screen_recording`. That
+ asks macOS once (the service rate-limits it) and only a live GRANTED lets the
+ capture proceed; anything else raises :class:`ScreenCaptureRefused` whose text
+ names the permission. No path refuses because OUR OWN preflight says "not
+ granted" before the OS was asked, and none captures on a state the OS has not
+ granted.
+
+The silent-failure trap is checked at the capture site by
+:func:`verify_frame_is_real`, AFTER every grab: it re-reads the state fresh (a
+revoke that lands during the grab or the stability loop is seen, the entry gate
+ran earlier) and refuses unless the state is granted; while the state claims
+GRANTED it also looks at the window list (cached for a few seconds), because a
+photographic wallpaper is not a "blank" frame. UNVERIFIED on a real Mac: that a
+denied capture is wallpaper-only and that window titles of other apps are hidden
+then (both community-observed, the title gating is what the permission port's own
+oracle relies on).
+
+Nothing here initialises at import time and no framework is imported at module
+scope (AP-26): Quartz is imported inside the one function that needs it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import math
+import os
+import time
+from collections.abc import Callable
+from typing import Any
+from uuid import UUID
+
+from jarvis.platform.permissions import PermissionId, PermissionState
+
+log = logging.getLogger(__name__)
+
+_READY: frozenset[PermissionState] = frozenset(
+ {PermissionState.GRANTED, PermissionState.NOT_REQUIRED}
+)
+# States where the window-title oracle (the deep read) may still prove a grant
+# that the per-process-frozen preflight denies (BUG-161).
+_DEEP_RETRY_STATES: frozenset[PermissionState] = frozenset(
+ {PermissionState.NOT_GRANTED, PermissionState.NOT_DETERMINED, PermissionState.DENIED}
+)
+_REASON_OF_STATE: dict[PermissionState, str] = {
+ PermissionState.DENIED: "denied",
+ PermissionState.RESTRICTED: "restricted",
+ PermissionState.UNAVAILABLE: "unavailable",
+ PermissionState.NOT_DETERMINED: "not_determined",
+}
+
+#: Largest per-channel spread (0..255) of the sampled pixels that still counts
+#: as "one flat colour". Real UI content, a photo wallpaper and a dimmed login
+#: screen all exceed it; a solid desktop, a black frame and a blank window do not.
+_BLANK_CHANNEL_SPREAD = 4
+#: How many pixels the blank test samples. A strided byte slice, no Pillow.
+_BLANK_SAMPLE_PIXELS = 2048
+#: A window smaller than this (input units) says nothing about the grant.
+_MIN_EVIDENCE_WINDOW_PX = 100
+#: How long a "the grant is usable" window-list verdict is reused (seconds). The
+#: window list is read at most this often per process on the normal path.
+_EVIDENCE_TTL_S = 5.0
+#: A flat frame is the cheap extra trigger: it accepts only a younger verdict.
+_BLANK_EVIDENCE_TTL_S = 1.0
+
+
+class ScreenCaptureRefused(RuntimeError):
+ """A screen capture macOS does not allow, with honest permission text.
+
+ ``str(exc)`` is the AGENT sentence (prohibitive, starts with
+ ``[permission_needed:screen_recording] ``): it is what a tool error or a
+ mission log carries. ``user_detail`` is the people-facing sentence for a spoken
+ or rendered refusal. Neither contains exception text, paths or window titles.
+ A ``RuntimeError`` subclass so every existing ``except RuntimeError`` around a
+ capture keeps working.
+ """
+
+ permission = PermissionId.SCREEN_RECORDING.value
+
+ def __init__(self, agent_detail: str, user_detail: str, reason: str = "") -> None:
+ super().__init__(agent_detail)
+ self.agent_detail = agent_detail
+ self.user_detail = user_detail
+ self.reason = reason
+
+
+def permission_gate() -> Any:
+ """The ``PermissionGate`` the capture consumers use: the process service.
+
+ A seam: a test monkeypatches this function (or hands a gate to the function
+ that takes one) to inject ``FakePermissionService``.
+ """
+ from jarvis.platform.permission_service import get_permission_service # noqa: PLC0415
+
+ return get_permission_service()
+
+
+# ----------------------------------------------------------------------
+# Silent reads (helpers, per-frame fast paths, GET routes)
+# ----------------------------------------------------------------------
+
+
+def screen_recording_state(gate: Any | None = None, *, deep: bool = True) -> PermissionState:
+ """The live Screen Recording state. Silent: it never asks and never publishes.
+
+ The cheap preflight comes first. The preflight is frozen per process and can
+ only go stale NEGATIVE, so a "not granted" answer is re-read once through the
+ window-title oracle (``check_deep``) before it is believed: a grant the user
+ gave mid-session must not read as missing until a restart (BUG-161). A gate
+ without ``check_deep`` (a scripted fake) answers with ``check`` alone.
+
+ ``deep=False`` is for a GET status probe: it never runs the oracle (a window
+ enumeration whose side effects on a real Mac are unverified), so it answers
+ from the preflight and the remembered proof only.
+ """
+ gate = gate if gate is not None else permission_gate()
+ state = gate.check(PermissionId.SCREEN_RECORDING)
+ if not deep or state not in _DEEP_RETRY_STATES:
+ return state
+ deep = getattr(gate, "check_deep", None)
+ if not callable(deep):
+ return state
+ return deep(PermissionId.SCREEN_RECORDING)
+
+
+def state_allows_capture(state: PermissionState) -> bool:
+ """Whether a state lets a capture proceed: GRANTED, or not required off macOS."""
+ return state in _READY
+
+
+def screen_recording_blocked(gate: Any | None = None) -> bool:
+ """``True`` when a capture would not be allowed right now. Silent."""
+ return not state_allows_capture(screen_recording_state(gate))
+
+
+def refusal_for_state(state: PermissionState) -> ScreenCaptureRefused:
+ """Honest text for a state read WITHOUT asking (a helper's degradation)."""
+ from jarvis.platform.permission_service import ( # noqa: PLC0415
+ agent_detail_for,
+ user_detail_for,
+ )
+
+ reason = _REASON_OF_STATE.get(state, "needs_settings")
+ family = PermissionId.SCREEN_RECORDING
+ return ScreenCaptureRefused(
+ agent_detail_for(family, reason),
+ user_detail_for(family, reason),
+ reason,
+ )
+
+
+def refusal_pending() -> ScreenCaptureRefused:
+ """Honest text for a capture that waits on a macOS dialog (not a denial)."""
+ from jarvis.platform.permission_service import ( # noqa: PLC0415
+ agent_detail_for,
+ user_detail_for,
+ )
+
+ family = PermissionId.SCREEN_RECORDING
+ # The Screen Recording dialog only offers "Open System Settings" (it has no
+ # Allow button), so the wording is the needs_settings one, not not_determined.
+ return ScreenCaptureRefused(
+ agent_detail_for(family, "needs_settings", asking=True),
+ user_detail_for(family, "needs_settings", asking=True),
+ "pending",
+ )
+
+
+def _refusal_from_result(result: Any) -> ScreenCaptureRefused:
+ return ScreenCaptureRefused(
+ str(getattr(result, "agent_detail", "") or ""),
+ str(getattr(result, "user_detail", "") or ""),
+ str(getattr(result, "reason", "") or ""),
+ )
+
+
+# ----------------------------------------------------------------------
+# The gesture entry points (they may ask)
+# ----------------------------------------------------------------------
+
+
+def require_screen_recording(
+ feature: str,
+ *,
+ gate: Any | None = None,
+ trace_id: UUID | str | None = None,
+) -> None:
+ """Gesture entry: make sure a capture is allowed, asking macOS if it is not.
+
+ For a capture a PERSON started. Blocking (the service may call into the OS):
+ call it from a worker thread, or use :func:`require_screen_recording_async`.
+ The granted fast path is one cached read, so a per-frame caller pays nothing.
+ Raises :class:`ScreenCaptureRefused` unless the permission is live GRANTED
+ (or not required on this platform). ``wait_s`` is 0 on purpose: the Screen
+ Recording dialog only offers "Open System Settings", so waiting for it is
+ pointless; the answer reaches the user through the permission episode.
+ """
+ gate = gate if gate is not None else permission_gate()
+ if screen_recording_state(gate) in _READY:
+ return
+ result = gate.ensure(
+ PermissionId.SCREEN_RECORDING,
+ feature=feature,
+ interactive=True,
+ wait_s=0.0,
+ trace_id=trace_id,
+ )
+ if not result.granted:
+ raise _refusal_from_result(result)
+
+
+async def require_screen_recording_async(
+ feature: str,
+ *,
+ gate: Any | None = None,
+ trace_id: UUID | str | None = None,
+) -> None:
+ """:func:`require_screen_recording` for the event loop (never blocks it)."""
+ gate = gate if gate is not None else permission_gate()
+ # The state read may enumerate windows (the deep fallback): off the loop.
+ if await asyncio.to_thread(screen_recording_state, gate) in _READY:
+ return
+ result = await gate.ensure_async(
+ PermissionId.SCREEN_RECORDING,
+ feature=feature,
+ interactive=True,
+ wait_s=0.0,
+ trace_id=trace_id,
+ )
+ if not result.granted:
+ raise _refusal_from_result(result)
+
+
+# ----------------------------------------------------------------------
+# Pixel sanity check (the silent-failure trap)
+# ----------------------------------------------------------------------
+
+# The features that told the permission service about an unusable grant and have
+# not seen a verified-real frame since: the success path only touches the service
+# for these, so a healthy per-frame path costs one set lookup.
+_failed_use_reported: set[str] = set()
+
+
+def frame_is_blank(size: tuple[int, int], pixels: Any, *, bytes_per_pixel: int = 3) -> bool:
+ """``True`` when a frame is one flat colour (or has no pixels at all).
+
+ Samples about 2048 pixels with a strided byte slice per channel, so it costs
+ microseconds and needs no Pillow. ``bytes_per_pixel`` is 3 for RGB and 4 for
+ the BGRX frames mss hands out; channel order does not matter for a spread.
+ A sparse screen (one small control on an empty window) can sample as flat: a
+ flat frame only tightens the window-list verdict in :func:`verify_frame_is_real`,
+ it never refuses on its own. The pixel step is coprime with the width, so the
+ samples do not line up on a few columns of a power-of-two native size.
+ """
+ width, height = size
+ count = int(width) * int(height)
+ stride = max(1, int(bytes_per_pixel))
+ if width <= 0 or height <= 0 or len(pixels) < count * stride:
+ return True
+ step = max(1, count // _BLANK_SAMPLE_PIXELS)
+ while step > 1 and math.gcd(step, int(width)) != 1:
+ step += 1
+ end = count * stride
+ for channel in range(min(3, stride)):
+ sample = pixels[channel : end : stride * step]
+ if not sample:
+ return True
+ if max(sample) - min(sample) > _BLANK_CHANNEL_SPREAD:
+ return False
+ return True
+
+
+def _default_window_evidence() -> tuple[int, int] | None:
+ """``(foreign windows, of them with a readable title)`` on screen, else ``None``.
+
+ Another app's window TITLE is Screen-Recording-gated data (the permission
+ port's own oracle relies on it), while the window itself is still listed. So
+ "other apps' windows exist but none has a readable title" is the signature of
+ a missing grant, and "some title is readable" proves the grant works right now.
+ UNVERIFIED on a real Mac. ``None`` when the native bridge is missing.
+ """
+ try:
+ import Quartz # type: ignore[import-not-found] # noqa: PLC0415
+
+ windows = Quartz.CGWindowListCopyWindowInfo(
+ Quartz.kCGWindowListOptionOnScreenOnly | Quartz.kCGWindowListExcludeDesktopElements,
+ Quartz.kCGNullWindowID,
+ )
+ except Exception: # noqa: BLE001 - a missing native bridge is "no evidence"
+ log.debug("The window list for the capture sanity check is unavailable.", exc_info=True)
+ return None
+ own_pid = os.getpid()
+ foreign = titled = 0
+ try:
+ for window in list(windows or ()):
+ if int(window.get("kCGWindowOwnerPID", own_pid)) == own_pid:
+ continue
+ if int(window.get("kCGWindowLayer", 0)) != 0:
+ continue # menu bar, Dock, overlays: not an app window
+ bounds = window.get("kCGWindowBounds") or {}
+ if (
+ float(bounds.get("Width", 0)) < _MIN_EVIDENCE_WINDOW_PX
+ or float(bounds.get("Height", 0)) < _MIN_EVIDENCE_WINDOW_PX
+ ):
+ continue
+ foreign += 1
+ if str(window.get("kCGWindowName") or "").strip():
+ titled += 1
+ except (AttributeError, TypeError, ValueError):
+ log.debug("The window list had an unexpected shape.", exc_info=True)
+ return None
+ return foreign, titled
+
+
+# A seam: tests replace it; production resolves the Quartz reader above.
+_window_evidence: Callable[[], tuple[int, int] | None] = _default_window_evidence
+# A seam for the verdict cache's clock.
+_monotonic: Callable[[], float] = time.monotonic
+# One slot: the reader that produced the verdict (a replaced seam never reuses a
+# stale one), when, and what it saw. Plain tuple assignment is atomic, so two
+# worker threads that race only read the window list twice.
+_evidence_cache: dict[str, tuple[Callable[[], tuple[int, int] | None], float, object]] = {}
+
+
+def reset_window_evidence_cache() -> None:
+ """Forget the cached window-list verdict (tests, and a deliberate re-check)."""
+ _evidence_cache.clear()
+ _failed_use_reported.clear()
+
+
+def _grant_unusable(max_age_s: float) -> bool:
+ """``True`` when other apps' windows are on screen and none has a readable title.
+
+ That is the window-list signature of a Screen Recording grant the OS does not
+ honour (a stale entry after a re-sign, a revoke the preflight has not
+ reported). The ONE window-list read is shared by every capture of the
+ process: a "usable" or "no evidence" verdict is reused for ``max_age_s``. An
+ unusable verdict is never cached, so a grant the user fixes is believed on the
+ next capture. UNVERIFIED on a real Mac. Known false alarm: a desktop whose
+ only big windows carry no title (a full-screen game or kiosk window) reads as
+ unusable while the grant works; the refusal then names the permission.
+ """
+ reader = _window_evidence
+ now = _monotonic()
+ cached = _evidence_cache.get("verdict")
+ if cached is not None and cached[0] is reader and 0.0 <= now - cached[1] <= max_age_s:
+ evidence = cached[2]
+ else:
+ evidence = reader()
+ _evidence_cache["verdict"] = (reader, now, evidence)
+ unusable = (
+ isinstance(evidence, tuple) and len(evidence) == 2 and evidence[0] > 0 and evidence[1] == 0
+ )
+ if unusable:
+ _evidence_cache.pop("verdict", None)
+ return unusable
+
+
+def _grant_proven() -> bool:
+ """``True`` when the last window-list verdict READ a title of another app's window.
+
+ That is positive proof the grant works right now (a missing grant hides those
+ titles); "no windows" or "no evidence" proves nothing. Reads the cached verdict
+ :func:`_grant_unusable` just produced, so it costs no second window-list read.
+ """
+ cached = _evidence_cache.get("verdict")
+ if cached is None or cached[0] is not _window_evidence:
+ return False
+ evidence = cached[2]
+ return isinstance(evidence, tuple) and len(evidence) == 2 and evidence[1] > 0
+
+
+def _unusable_grant_refusal(feature: str, gate: Any, *, interactive: bool) -> ScreenCaptureRefused:
+ """Report a REAL failed use to the service and build the honest refusal.
+
+ The state reads GRANTED yet the window list says the grant is not honoured: the
+ one case where "quit and reopen" is honest advice (the grant may only apply to
+ a new process, community-observed and UNVERIFIED). A user-started capture tells
+ the service, which opens a ``restart_hint`` episode (the toast names the restart
+ and nothing restarts by itself); a background consumer stays quiet, the service
+ only opens episodes with the user origin for this call. The frame is refused
+ either way. A gate without the call (a scripted stub) gets the plain refusal.
+ """
+ report = getattr(gate, "report_failed_use", None)
+ if interactive and callable(report):
+ result = report(PermissionId.SCREEN_RECORDING, feature=feature)
+ _failed_use_reported.add(feature)
+ if not getattr(result, "granted", True) and getattr(result, "reason", ""):
+ return _refusal_from_result(result)
+ return refusal_for_state(PermissionState.NOT_GRANTED)
+
+
+def _clear_failed_use(gate: Any) -> None:
+ """A verified-real frame ends the ``restart_hint`` episode a failed use opened.
+
+ The grant is process-wide, so ANY feature's verified-real frame proves it works
+ again, whichever feature reported the failure (the episode is per permission, not
+ per feature). The service has no hook that says "the attempt that failed works
+ now"; the one call that drops a slot's restart hint is ``note_reset`` (it also
+ forgets the per-process ask cooldown, harmless while the grant is live). The next
+ watcher pass then closes the episode as granted, so the toast does not nag a user
+ whose capture works again. Does nothing unless some feature reported a failure.
+ """
+ if not _failed_use_reported:
+ return
+ _failed_use_reported.clear()
+ reset = getattr(gate, "note_reset", None)
+ if not callable(reset):
+ return
+ try:
+ reset(PermissionId.SCREEN_RECORDING)
+ except Exception: # noqa: BLE001 - tidying a card never turns a real frame into a failure
+ log.debug("Ending the screen-recording restart hint failed.", exc_info=True)
+
+
+def verify_frame_is_real(
+ size: tuple[int, int],
+ pixels: Any,
+ *,
+ feature: str,
+ bytes_per_pixel: int = 3,
+ interactive: bool = True,
+ gate: Any | None = None,
+) -> None:
+ """Refuse a frame the permission state cannot explain: never a wallpaper success.
+
+ Runs at the capture site AFTER a grab (off macOS the state is NOT_REQUIRED and
+ nothing else happens). The entry gate ran BEFORE the grab, and the grant can
+ go away between the two (the stability loop runs up to 1.2 s, a native capture
+ timeout takes 3 s), so:
+
+ 1. the cached grant is dropped (``invalidate``) and the state is read fresh,
+ once per frame (one preflight; the window-title oracle only when that says
+ "not granted"). A state that is not granted refuses the frame, blank or
+ not, through ``ensure`` so the permission episode is opened;
+ 2. while the state says GRANTED, the window list is consulted (cached for a few
+ seconds, younger for a flat frame): other apps' windows on screen with no
+ readable title means the grant is not usable, so the frame refuses with
+ honest text. A photographic wallpaper is not a flat frame, which is why this
+ does not wait for blankness. A readable title, no windows at all or no
+ evidence means the frame passes (a flat one is then a genuinely blank
+ screen).
+
+ ``interactive`` is False for a background consumer: the episode is then
+ recorded with the ``background`` origin (status snapshot only, no toast) and no native
+ request is made. Blocking: a worker thread, never the event loop.
+ """
+ gate = gate if gate is not None else permission_gate()
+ invalidate = getattr(gate, "invalidate", None)
+ if callable(invalidate):
+ invalidate(PermissionId.SCREEN_RECORDING)
+ state = screen_recording_state(gate)
+ if state not in _READY:
+ result = gate.ensure(
+ PermissionId.SCREEN_RECORDING,
+ feature=feature,
+ interactive=interactive,
+ wait_s=0.0,
+ )
+ if result.granted:
+ # The state flipped back between the two reads: the frame was taken
+ # without a usable grant, so it is not trustworthy. The next one will be.
+ log.info("A capture finished while the grant was missing; refusing this frame.")
+ raise refusal_for_state(PermissionState.NOT_GRANTED)
+ raise _refusal_from_result(result)
+ if state is not PermissionState.GRANTED:
+ return # NOT_REQUIRED: this platform has no Screen Recording trap
+
+ blank = frame_is_blank(size, pixels, bytes_per_pixel=bytes_per_pixel)
+ if _grant_unusable(_BLANK_EVIDENCE_TTL_S if blank else _EVIDENCE_TTL_S):
+ log.warning(
+ "The Screen Recording grant reads as granted but other apps' windows are "
+ "on screen and none has a readable title. The grant is probably not usable "
+ "(unverified); refusing the frame."
+ )
+ raise _unusable_grant_refusal(feature, gate, interactive=interactive)
+ if _grant_proven():
+ _clear_failed_use(gate)
+ if blank:
+ log.debug("A blank capture is accepted: the grant works and the screen is blank.")
+
+
+__all__ = [
+ "ScreenCaptureRefused",
+ "frame_is_blank",
+ "permission_gate",
+ "refusal_for_state",
+ "refusal_pending",
+ "require_screen_recording",
+ "require_screen_recording_async",
+ "reset_window_evidence_cache",
+ "screen_recording_blocked",
+ "screen_recording_state",
+ "state_allows_capture",
+ "verify_frame_is_real",
+]
diff --git a/jarvis/platform/window_capture.py b/jarvis/platform/window_capture.py
index 21ba507fba..bcb9e9fd75 100644
--- a/jarvis/platform/window_capture.py
+++ b/jarvis/platform/window_capture.py
@@ -34,6 +34,7 @@ from __future__ import annotations
import logging
import os
+import threading
from typing import Any
from jarvis.platform import detect_platform
@@ -45,6 +46,68 @@ log = logging.getLogger(__name__)
#: perceive loop, whose own observe timeout is 12 s.
_SCK_TIMEOUT_S = 3.0
+#: Why the last :func:`grab_window` on THIS thread returned ``None``, for a
+#: caller that must tell "macOS may be asking" from "no native capture here".
+_PENDING_CONFIRMATION = "pending_confirmation"
+_TIMEOUT = "timeout"
+_failure = threading.local()
+
+
+def last_grab_failure() -> str:
+ """Why the last ``grab_window`` on this thread returned ``None``.
+
+ ``"pending_confirmation"``: the wait timed out while the live Screen Recording
+ read says granted or a request is in flight, so macOS is probably showing a
+ confirmation (the first capture on macOS 15+ may show its own "bypass the
+ system picker" alert; unverified). It is PENDING, never DENIED. ``"timeout"``:
+ it timed out and nothing explains it. ``""``: no reason recorded (no native
+ path on this host, window gone, framework missing).
+ """
+ return str(getattr(_failure, "reason", ""))
+
+
+def clear_grab_failure() -> None:
+ """Forget the recorded reason before a grab (a stale one must not leak in)."""
+ _failure.reason = ""
+
+
+def _timeout_means_pending() -> bool:
+ """Whether a capture timeout is the confirmation dialog rather than a denial.
+
+ True when the live state (preflight plus the window-title oracle) reads
+ granted, or when the permission service has a Screen Recording request in
+ flight (an open episode in the ``os_dialog`` phase). Silent: it never asks.
+ """
+ try:
+ from jarvis.platform import screen_access # noqa: PLC0415
+
+ gate = screen_access.permission_gate()
+ if screen_access.state_allows_capture(screen_access.screen_recording_state(gate)):
+ return True
+ outstanding = getattr(gate, "outstanding", None)
+ if callable(outstanding):
+ return any(
+ "screen_recording" in episode.permissions and episode.phase == "os_dialog"
+ for episode in outstanding()
+ )
+ except Exception: # noqa: BLE001 - classifying a timeout must never break the seam
+ log.debug("Could not classify a screen capture timeout.", exc_info=True)
+ return False
+
+
+def _note_timeout(what: str) -> None:
+ """Record a SCK wait timeout as PENDING when the state explains it."""
+ if _timeout_means_pending():
+ _failure.reason = _PENDING_CONFIRMATION
+ log.info(
+ "%s timed out: macOS may be asking you to confirm screen capture. "
+ "Treating it as pending, not as denied.",
+ what,
+ )
+ else:
+ _failure.reason = _TIMEOUT
+ log.debug("%s timed out (no permission state explains it)", what)
+
def grab_window(
handle: int, bbox: dict[str, int],
@@ -54,7 +117,10 @@ def grab_window(
``bbox`` is the window's frame rect in input units (advisory — the
native backends capture the window's own current bounds). Returns
``None`` whenever the host has no native per-window path; never raises.
+ A caller that needs to know WHY a ``None`` came back asks
+ :func:`last_grab_failure` on the same thread.
"""
+ _failure.reason = ""
try:
plat = detect_platform()
if plat == "win32":
@@ -193,7 +259,7 @@ def _grab_window_macos(window_id: int) -> tuple[tuple[int, int], bytes] | None:
_content_handler,
)
if not content_ready.wait(_SCK_TIMEOUT_S):
- log.debug("SCShareableContent timed out (permission prompt pending?)")
+ _note_timeout("SCShareableContent")
return None
content = content_box.get("content")
if content is None or content_box.get("error") is not None:
@@ -249,7 +315,7 @@ def _grab_window_macos(window_id: int) -> tuple[tuple[int, int], bytes] | None:
sc_filter, config, _image_handler,
)
if not image_ready.wait(_SCK_TIMEOUT_S):
- log.debug("SCScreenshotManager timed out")
+ _note_timeout("SCScreenshotManager")
return None
cg_image = image_box.get("image")
if cg_image is None or image_box.get("error") is not None:
@@ -267,4 +333,4 @@ def _grab_window_macos(window_id: int) -> tuple[tuple[int, int], bytes] | None:
return ((img.width, img.height), img.tobytes())
-__all__ = ["grab_window"]
+__all__ = ["clear_grab_failure", "grab_window", "last_grab_failure"]
diff --git a/jarvis/platform/window_state.py b/jarvis/platform/window_state.py
index 10efb72159..7ac2d707f3 100644
--- a/jarvis/platform/window_state.py
+++ b/jarvis/platform/window_state.py
@@ -544,6 +544,43 @@ def _macos_bound_ax_messaging(
log.debug("AXUIElementSetMessagingTimeout unavailable", exc_info=True)
+def _permission_gate():
+ """The permission layer (``PermissionGate``); a test replaces this seam."""
+ from jarvis.platform.permission_service import get_permission_service # noqa: PLC0415
+
+ return get_permission_service()
+
+
+def _macos_accessibility_granted() -> bool:
+ """Silent Accessibility read for background reads: never asks, never publishes."""
+ from jarvis.platform.permissions import PermissionId, PermissionState # noqa: PLC0415
+
+ state = _permission_gate().check(PermissionId.ACCESSIBILITY)
+ return state in (PermissionState.GRANTED, PermissionState.NOT_REQUIRED)
+
+
+def _macos_window_control_refusal() -> str:
+ """``""`` when focusing / maximizing may proceed, else the agent-facing refusal.
+
+ Called from a worker (the window tools run in ``asyncio.to_thread``) with
+ ``wait_s=0``: the first call makes macOS show its own Accessibility dialog and
+ returns at once, the grant is picked up by the permission watcher. Only a live
+ GRANTED proceeds. The sentence starts with ``[permission_needed:accessibility] ``
+ and forbids retrying, so the computer-use engine can end the mission on it.
+ """
+ from jarvis.platform.permissions import PermissionId # noqa: PLC0415
+
+ result = _permission_gate().ensure(
+ PermissionId.ACCESSIBILITY, feature="window_control", wait_s=0.0
+ )
+ if result.granted:
+ return ""
+ return result.agent_detail or (
+ "[permission_needed:accessibility] Accessibility access has not been allowed "
+ "yet. You must not retry this action; tell the user and stop."
+ )
+
+
def _find_and_focus_macos(title_contains: str) -> tuple[bool, str]:
"""Activate and AX-raise a matching macOS window without AppleScript.
@@ -586,24 +623,11 @@ def _find_and_focus_macos(title_contains: str) -> tuple[bool, str]:
except (ImportError, ModuleNotFoundError) as exc:
return False, f"macOS window APIs are unavailable: {exc}"
- from jarvis.platform.permissions import ( # noqa: PLC0415
- PermissionId,
- PermissionState,
- get_system_permission_port,
- )
-
- permission_port = get_system_permission_port()
- if not permission_port.runtime_access_granted(PermissionId.ACCESSIBILITY):
- accessibility_state = permission_port.state(PermissionId.ACCESSIBILITY)
- detail = (
- accessibility_state.value
- if accessibility_state is not PermissionState.GRANTED
- else "grant belongs to an unstable app identity or needs restart"
- )
- return False, (
- f"macOS Accessibility permission is not ready ({detail}) — grant it in System "
- "Settings > Privacy & Security > Accessibility so Jarvis can switch windows."
- )
+ # Focusing a window is an ACTION the user asked for: the first one asks macOS
+ # for Accessibility (wait_s=0, the answer arrives later), a refusal stops it.
+ denied = _macos_window_control_refusal()
+ if denied:
+ return False, denied
app = NSRunningApplication.runningApplicationWithProcessIdentifier_(pid)
if app is None:
@@ -685,13 +709,9 @@ def _list_windows_macos() -> list[WindowInfo]:
AXUIElementCreateApplication,
)
- from jarvis.platform.permissions import ( # noqa: PLC0415
- PermissionId,
- get_system_permission_port,
- )
-
- port = get_system_permission_port()
- if port.runtime_access_granted(PermissionId.ACCESSIBILITY):
+ # Listing is a background READ: a silent check, never a prompt. Without
+ # the grant the minimized flag is simply not read.
+ if _macos_accessibility_granted():
ax_windows_by_pid: dict[int, list[object]] = {}
for entry in entries:
pid = _macos_window_pid(entry)
@@ -1630,14 +1650,8 @@ def _resolve_macos_ax_window(win: WindowInfo) -> tuple[object | None, str]:
def _window_is_maximized_macos(win: WindowInfo) -> bool | None:
- from jarvis.platform.permissions import ( # noqa: PLC0415
- PermissionId,
- get_system_permission_port,
- )
-
- if not get_system_permission_port().runtime_access_granted(
- PermissionId.ACCESSIBILITY,
- ):
+ # A background READ: a silent check, never a prompt (None = cannot be read).
+ if not _macos_accessibility_granted():
return None
target, _error = _resolve_macos_ax_window(win)
if target is None:
@@ -1685,26 +1699,10 @@ def window_is_maximized(win: WindowInfo) -> bool | None:
def _maximize_window_macos(win: WindowInfo) -> tuple[bool, str]:
"""Set the native AXZoomed attribute without Apple Events automation."""
- from jarvis.platform.permissions import ( # noqa: PLC0415
- PermissionId,
- PermissionState,
- get_system_permission_port,
- )
-
- port = get_system_permission_port()
- if not port.runtime_access_granted(PermissionId.ACCESSIBILITY):
- state = port.state(PermissionId.ACCESSIBILITY)
- detail = (
- state.value
- if state is not PermissionState.GRANTED
- else "grant belongs to an unstable app identity or needs restart"
- )
- return False, (
- "macOS Accessibility permission is not ready "
- f"({detail}); grant it in Personal Jarvis > Settings > "
- "Permissions or System Settings > Privacy & Security > "
- "Accessibility, then retry."
- )
+ # Maximizing is an ACTION: the first one asks macOS for Accessibility.
+ denied = _macos_window_control_refusal()
+ if denied:
+ return False, denied
try:
from ApplicationServices import ( # type: ignore[import-not-found] # noqa: PLC0415
diff --git a/jarvis/plugins/harness/computer_use.py b/jarvis/plugins/harness/computer_use.py
index b1f0e9932f..f27bd41e10 100644
--- a/jarvis/plugins/harness/computer_use.py
+++ b/jarvis/plugins/harness/computer_use.py
@@ -317,6 +317,16 @@ class ComputerUseHarness:
if chunk.is_final:
final_exit_code = chunk.exit_code
final_stdout = chunk.stdout or ""
+ if not final_stdout and chunk.exit_code != 0:
+ # A mission stopped by a macOS permission or a system
+ # dialog keeps its sentence where run control reads the
+ # outcome (the "[cu] blocked_permission" line sits in
+ # stderr, which the registry does not store).
+ from jarvis.voice.action_phrases import ( # noqa: PLC0415
+ cu_blocked_permission_sentence,
+ )
+
+ final_stdout = cu_blocked_permission_sentence(chunk.stderr) or ""
if chunk.exit_code == _CANCEL_EXIT_CODE:
end_reason = "cancelled"
elif chunk.exit_code != 0:
diff --git a/jarvis/plugins/tool/screen_snapshot.py b/jarvis/plugins/tool/screen_snapshot.py
index 14164b2dc2..80adf5dbda 100644
--- a/jarvis/plugins/tool/screen_snapshot.py
+++ b/jarvis/plugins/tool/screen_snapshot.py
@@ -30,15 +30,21 @@ Flow in `execute`:
from __future__ import annotations
+import asyncio
import base64
import io
+import logging
from typing import Any
from jarvis.core.protocols import ExecutionContext, ToolResult
-from jarvis.vision.screenshot import (
- select_capture_monitor,
- warn_if_screen_recording_denied,
+from jarvis.platform.screen_access import (
+ ScreenCaptureRefused,
+ require_screen_recording_async,
+ verify_frame_is_real,
)
+from jarvis.vision.screenshot import select_capture_monitor
+
+log = logging.getLogger(__name__)
_MAX_BYTES = 500_000
_DEFAULT_JPEG_QUALITY = 85
@@ -123,18 +129,16 @@ class ScreenSnapshotTool:
# On macOS without the Screen-Recording grant, mss "succeeds" but
# captures only the desktop wallpaper — a success=True wallpaper JPEG
- # would silently blind the model. Refuse honestly instead (§3:
- # degrade with an actionable message, recoverable in-app).
- if warn_if_screen_recording_denied():
- return ToolResult(
- success=False,
- output=None,
- error=(
- "Screen capture is blocked: macOS Screen Recording "
- "permission is not granted. Grant it in System Settings "
- "> Privacy & Security > Screen Recording, then retry."
- ),
- )
+ # would silently blind the model. This tool body is the gesture entry of
+ # a capture a person asked for: it asks macOS (once per episode, through
+ # the permission service) instead of refusing on our own preflight, and
+ # only a live GRANTED captures. Anything else is an honest, prohibitive
+ # error naming the permission (the model must not answer a system dialog).
+ try:
+ await require_screen_recording_async("screen_context")
+ except ScreenCaptureRefused as refused:
+ log.debug("screen_snapshot: refused (%s)", refused.reason or "permission")
+ return ToolResult(success=False, output=None, error=refused.agent_detail)
try:
from jarvis.cu.indicator.capture_guard import ( # noqa: PLC0415
@@ -164,6 +168,19 @@ class ScreenSnapshotTool:
error=f"Screenshot failed: {exc}",
)
+ # The silent-failure trap: a blank frame while the state claims granted is
+ # never a success (the permission episode is opened by the check itself).
+ try:
+ await asyncio.to_thread(
+ verify_frame_is_real,
+ tuple(raw.size),
+ raw.rgb,
+ feature="screen_context",
+ )
+ except ScreenCaptureRefused as refused:
+ log.debug("screen_snapshot: frame refused (%s)", refused.reason or "permission")
+ return ToolResult(success=False, output=None, error=refused.agent_detail)
+
jpeg_bytes = _encode_with_budget(image, _MAX_BYTES)
data_b64 = base64.b64encode(jpeg_bytes).decode("ascii")
diff --git a/jarvis/plugins/tool/type_text.py b/jarvis/plugins/tool/type_text.py
index 6a0c6a97a7..c7e7901d41 100644
--- a/jarvis/plugins/tool/type_text.py
+++ b/jarvis/plugins/tool/type_text.py
@@ -269,10 +269,18 @@ class TypeTextTool:
output=f"Typed {len(text)} chars ({actuator.name})",
)
except ActuationUnavailable as exc:
+ # A permission refusal keeps its stable "[permission_needed:" prefix
+ # at the START of the error (the engine maps it); other causes are
+ # wrapped as before.
+ message = str(exc)
return ToolResult(
success=False,
output=None,
- error=f"text input unavailable: {exc}",
+ error=(
+ message
+ if message.startswith("[permission_needed:")
+ else f"text input unavailable: {message}"
+ ),
)
except _ForegroundTargetChanged as exc:
return ToolResult(
diff --git a/jarvis/plugins/tool/verify_localhost.py b/jarvis/plugins/tool/verify_localhost.py
index 2123896e51..a3be81b9dd 100644
--- a/jarvis/plugins/tool/verify_localhost.py
+++ b/jarvis/plugins/tool/verify_localhost.py
@@ -7,6 +7,36 @@ from typing import Any
from jarvis.core.protocols import ExecutionContext, ToolResult
+def _take_checked_screenshot() -> str:
+ """Save the primary monitor to a PNG and return its path (blocking: a worker thread).
+
+ The screenshot is an optional extra of this check, not a gesture of its own: the
+ state is read silently (never asks) and a missing grant degrades with the honest,
+ prohibitive permission text. The grabbed pixels are checked too, because macOS
+ hands back the wallpaper, not an error, for a capture it does not allow.
+ """
+ import mss # type: ignore[import-not-found] # noqa: PLC0415
+ import mss.tools # noqa: PLC0415
+
+ from jarvis.platform import screen_access # noqa: PLC0415
+
+ blocked_state = screen_access.screen_recording_state()
+ if not screen_access.state_allows_capture(blocked_state):
+ raise screen_access.refusal_for_state(blocked_state)
+
+ with mss.mss() as sct:
+ raw = sct.grab(sct.monitors[1])
+ screen_access.verify_frame_is_real(
+ (int(raw.size[0]), int(raw.size[1])),
+ raw.rgb,
+ feature="screen_context",
+ interactive=False,
+ )
+ path = "monitor-1.png" # what ``mss.shot()`` writes for the primary monitor
+ mss.tools.to_png(raw.rgb, raw.size, output=path)
+ return path
+
+
class VerifyLocalhostTool:
name = "verify_localhost"
description = (
@@ -73,23 +103,10 @@ class VerifyLocalhostTool:
if take_screenshot:
try:
- import mss # type: ignore[import-not-found]
- import mss.tools
-
- from jarvis.vision.screenshot import ( # noqa: PLC0415
- warn_if_screen_recording_denied,
- )
-
- if warn_if_screen_recording_denied():
- raise PermissionError(
- "macOS Screen Recording permission is not granted. "
- "Grant it in Personal Jarvis > Settings > Permissions "
- "and retry."
- )
-
- with mss.mss() as sct:
- sct_img = sct.shot()
- artifacts.append({"screenshot_path": sct_img})
+ # One worker-thread hop for the state read (it may enumerate
+ # windows), the grab and the pixel check: none of it on the loop.
+ path = await asyncio.to_thread(_take_checked_screenshot)
+ artifacts.append({"screenshot_path": path})
except Exception as exc: # noqa: BLE001
artifacts.append({"screenshot_error": str(exc)})
diff --git a/jarvis/screen_context/ports.py b/jarvis/screen_context/ports.py
index c5decb7f61..08b12645f4 100644
--- a/jarvis/screen_context/ports.py
+++ b/jarvis/screen_context/ports.py
@@ -381,6 +381,28 @@ class SurfaceCapturer(Protocol):
...
+def _refuse_while_confirmation_pending() -> None:
+ """A native window capture timed out while macOS may be asking the user.
+
+ PENDING, never DENIED: when the live state says granted the rect-grab fallback
+ below is safe and carries on; when it does not (a request is still in flight)
+ that fallback would return the wallpaper, so say that macOS may be asking.
+ Silent: nothing is asked here.
+ """
+ try:
+ from jarvis.platform import screen_access, window_capture # noqa: PLC0415
+
+ if window_capture.last_grab_failure() != "pending_confirmation":
+ return
+ if not screen_access.screen_recording_blocked():
+ return
+ message = screen_access.refusal_pending().user_detail
+ except Exception: # noqa: BLE001 — classifying a timeout never breaks the capture
+ log.debug("pending-confirmation check failed", exc_info=True)
+ return
+ raise CaptureUnavailable(message)
+
+
class NativeSurfaceCapturer:
"""Native per-window capture where the OS offers it, rect grab otherwise.
@@ -407,8 +429,12 @@ class NativeSurfaceCapturer:
from jarvis.cu.indicator.capture_guard import ( # noqa: PLC0415
indicator_suppressed,
)
- from jarvis.platform.window_capture import grab_window # noqa: PLC0415
+ from jarvis.platform.window_capture import ( # noqa: PLC0415
+ clear_grab_failure,
+ grab_window,
+ )
+ clear_grab_failure()
with indicator_suppressed(), _input_space():
native = grab_window(
int(window_handle),
@@ -418,6 +444,7 @@ class NativeSurfaceCapturer:
return native
except Exception: # noqa: BLE001 — platform policy below decides fallback
log.debug("native window capture failed", exc_info=True)
+ _refuse_while_confirmation_pending()
if os.name == "nt":
raise CaptureUnavailable(
"The focused Windows window could not be captured safely. "
@@ -516,13 +543,19 @@ class AccessibilityTextReader:
# --------------------------------------------------------------------------
-def capture_permission_error() -> CapturePermissionIssue | None:
+def capture_permission_error(*, deep: bool = True) -> CapturePermissionIssue | None:
"""``None`` when capture is permitted, else an actionable English message.
- Deliberately uncached: macOS can revoke a TCC grant while Jarvis runs, and
- a cached "granted" would produce a wallpaper-only capture that looks like a
- successful screenshot of an empty desktop. One native call per capture is
- the right price for not lying about what was seen.
+ SILENT: it reads the state and never asks macOS, so ``GET
+ /api/screen-context/status`` and every other status probe may call it freely.
+ ``deep=False`` (the status route) also skips the window-title oracle, which
+ enumerates the on-screen windows: only a capture a person started pays that.
+ The capture a person starts asks through the permission service first
+ (``ScreenContextService.capture``); this only describes why a capture would
+ not be allowed right now. Deliberately not cached beyond the permission
+ service's sub-second read cache: macOS can revoke a TCC grant while Jarvis
+ runs, and a stale "granted" would produce a wallpaper-only capture that looks
+ like a successful screenshot of an empty desktop.
"""
if _is_wayland():
return CapturePermissionIssue(
@@ -534,22 +567,14 @@ def capture_permission_error() -> CapturePermissionIssue | None:
),
)
try:
- from jarvis.platform.permissions import ( # noqa: PLC0415
- PermissionId,
- get_system_permission_port,
- )
+ from jarvis.platform import screen_access # noqa: PLC0415
- port = get_system_permission_port()
- if port.runtime_access_granted(PermissionId.SCREEN_RECORDING):
+ state = screen_access.screen_recording_state(deep=deep)
+ if screen_access.state_allows_capture(state):
return None
return CapturePermissionIssue(
code="capture_permission",
- message=(
- "Screen capture is blocked because this app does not have the "
- "screen-recording permission. Grant it in your system privacy "
- "settings (macOS: System Settings > Privacy & Security > Screen "
- "Recording), then ask again."
- ),
+ message=screen_access.refusal_for_state(state).user_detail,
)
except Exception: # noqa: BLE001 — an unavailable probe must not block Windows/Linux
log.debug("screen-recording permission probe failed", exc_info=True)
@@ -557,21 +582,29 @@ def capture_permission_error() -> CapturePermissionIssue | None:
def accessibility_permission_error() -> str | None:
- """``None`` when UI text may be read, else an actionable English message."""
+ """``None`` when UI text may be read, else an actionable English message.
+
+ Reading UI text is background work: it never asks for Accessibility and the
+ status route never prompts. A missing grant only drops the on-screen text;
+ the screen image stays available.
+ """
try:
- from jarvis.platform.permissions import ( # noqa: PLC0415
- PermissionId,
- get_system_permission_port,
- )
+ from jarvis.platform.permission_service import user_detail_for # noqa: PLC0415
+ from jarvis.platform.permissions import PermissionId, PermissionState # noqa: PLC0415
+ from jarvis.platform.screen_access import permission_gate # noqa: PLC0415
- port = get_system_permission_port()
- if port.runtime_access_granted(PermissionId.ACCESSIBILITY):
+ state = permission_gate().check(PermissionId.ACCESSIBILITY)
+ if state in (PermissionState.GRANTED, PermissionState.NOT_REQUIRED):
return None
+ reason = {
+ PermissionState.DENIED: "denied",
+ PermissionState.RESTRICTED: "restricted",
+ PermissionState.UNAVAILABLE: "unavailable",
+ }.get(state, "needs_settings")
return (
- "Visible UI text could not be read because the accessibility "
- "permission is missing. The screen image is still available; "
- "grant accessibility in your system privacy settings to include "
- "on-screen text."
+ "Visible UI text could not be read. "
+ f"{user_detail_for(PermissionId.ACCESSIBILITY, reason)} "
+ "The screen image is still available."
)
except Exception: # noqa: BLE001
log.debug("accessibility permission probe failed", exc_info=True)
diff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.py
index bad8ae3954..693c858e00 100644
--- a/jarvis/screen_context/service.py
+++ b/jarvis/screen_context/service.py
@@ -36,6 +36,7 @@ from dataclasses import dataclass
from typing import Any, Literal
from uuid import UUID, uuid4
+from jarvis.platform import screen_access
from jarvis.screen_context import intent as intent_module
from jarvis.screen_context import redaction, uitext
from jarvis.screen_context.last_frame import LastFrameMirror, get_last_frame_mirror
@@ -176,6 +177,7 @@ class ScreenContextService:
capturer: Any | None = None,
ui_text_reader: Any | None = None,
permission_probe: Any | None = None,
+ permission_gate: Any | None = None,
clock: Any | None = None,
last_frame_mirror: LastFrameMirror | None = None,
) -> None:
@@ -197,7 +199,11 @@ class ScreenContextService:
self._window_probe = window_probe
self._capturer = capturer
self._ui_text_reader = ui_text_reader
+ # The probe is SILENT (it only describes why a capture would not be
+ # allowed); the gate is what asks, and only from ``capture`` below. ``None``
+ # resolves the process permission service per call.
self._permission_probe = permission_probe or capture_permission_error
+ self._permission_gate = permission_gate
self._clock = clock or time.monotonic_ns
self._wall_clock = time.time_ns
self._handles: dict[str, _Handle] = {}
@@ -368,14 +374,25 @@ class ScreenContextService:
# implement the original ``str | None`` port contract.
reason_code = "capture_permission"
permission_message = str(permission_issue)
- log.info("screen_context: capture refused — %s", permission_message)
- return CaptureOutcome(
- status="refused",
- verdict=verdict,
- reason_kind="technical",
- reason_code=reason_code,
- message=permission_message,
- )
+ if reason_code == "capture_permission":
+ # A person started this capture (a spoken request, the bar
+ # button, an appshot gesture), so this is the moment macOS is
+ # asked. The probe above never asks and never decides: only a
+ # live GRANTED from the permission service lets the capture go on.
+ refused = await self._ask_for_capture_permission(verdict, trace_id)
+ if refused is None:
+ permission_issue = None
+ else:
+ permission_message = refused.user_detail or permission_message
+ if permission_issue:
+ log.info("screen_context: capture refused — %s", permission_message)
+ return CaptureOutcome(
+ status="refused",
+ verdict=verdict,
+ reason_kind="technical",
+ reason_code=reason_code,
+ message=permission_message,
+ )
# The cursor is sampled ONCE, here, and threaded through. See
# targeting.resolve_target for why re-reading it later is a race.
@@ -529,6 +546,16 @@ class ScreenContextService:
)
try:
size, rgb = await self._grab(target)
+ # macOS hands back the wallpaper, not an error, for a capture it
+ # does not allow: a blank frame while the state claims granted
+ # is never a success (and opens the permission episode).
+ await asyncio.to_thread(
+ screen_access.verify_frame_is_real,
+ size,
+ rgb,
+ feature=self._permission_feature(verdict),
+ gate=self._permission_gate,
+ )
except CaptureUnavailable as exc:
log.info("screen_context: capture failed — %s", exc)
return CaptureOutcome(
@@ -538,6 +565,15 @@ class ScreenContextService:
reason_code="capture_backend_unavailable",
message=str(exc),
)
+ except screen_access.ScreenCaptureRefused as exc:
+ log.info("screen_context: capture refused — %s", exc.reason or "permission")
+ return CaptureOutcome(
+ status="refused",
+ verdict=verdict,
+ reason_kind="technical",
+ reason_code="capture_permission",
+ message=exc.user_detail,
+ )
except Exception: # noqa: BLE001 - port bugs stay turn-local
log.error("screen_context: unexpected capture failure", exc_info=True)
return CaptureOutcome(
@@ -632,6 +668,27 @@ class ScreenContextService:
if border:
await self._dismiss_indicator(trace_id=event_trace_id)
+ @staticmethod
+ def _permission_feature(verdict: IntentVerdict) -> str:
+ """The permission-episode feature of one capture: an appshot says so in its evidence."""
+ return "appshot" if "appshot" in verdict.evidence else "screen_context"
+
+ async def _ask_for_capture_permission(
+ self, verdict: IntentVerdict, trace_id: UUID | None
+ ) -> screen_access.ScreenCaptureRefused | None:
+ """Ask for Screen Recording (the capture is a gesture). ``None`` = allowed."""
+ try:
+ await screen_access.require_screen_recording_async(
+ self._permission_feature(verdict),
+ gate=self._permission_gate,
+ trace_id=trace_id,
+ )
+ except screen_access.ScreenCaptureRefused as refused:
+ # The caller turns this into the refused outcome the person sees.
+ log.debug("screen_context: permission refused (%s)", refused.reason or "permission")
+ return refused
+ return None
+
async def _grab(self, target: CaptureTarget) -> tuple[tuple[int, int], bytes]:
"""Grab the target the way the user sees it.
diff --git a/jarvis/setup/macos_app_bundle.py b/jarvis/setup/macos_app_bundle.py
index fb14b1978d..0c7d12b4de 100644
--- a/jarvis/setup/macos_app_bundle.py
+++ b/jarvis/setup/macos_app_bundle.py
@@ -28,6 +28,7 @@ locally signed app is a notarized artifact.
from __future__ import annotations
+import importlib.util
import json
import logging
import os
@@ -40,6 +41,7 @@ import subprocess
import sys
import tempfile
from pathlib import Path
+from types import ModuleType
from jarvis.core.branding import (
MACOS_APP_DIR_NAME as APP_DIR_NAME,
@@ -51,6 +53,7 @@ from jarvis.core.branding import (
MACOS_BUNDLE_ID as BUNDLE_ID,
)
from jarvis.core.branding import (
+ MACOS_DMG_BUNDLE_ID,
MACOS_EXECUTABLE_NAME,
)
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
@@ -63,6 +66,12 @@ log = logging.getLogger(__name__)
# forces existing bundles through a rebuild on the next ensure pass.
# 3: one forced rebuild so the new signature-change TCC reset (BUG-083) heals
# bundles whose grants were orphaned by the version-2 rebuild.
+# The shared usage-string table (jarvis/core/macos_privacy_strings.py) added
+# Desktop, Documents, Downloads, volume and local-network strings that this
+# bundle never carried. They are cosmetic prompt text, so the format version is
+# deliberately NOT bumped: a bump would rebuild every installed bundle, and an
+# ad-hoc rebuild is a new identity that re-asks every permission. The next
+# rebuild that happens for another reason carries the new strings.
_BUNDLE_FORMAT_VERSION = 3
# TCC service names this app ever requests; reset scope is always limited to
@@ -102,13 +111,28 @@ def last_error() -> str | None:
return _LAST_ERROR
-_MIC_USAGE = f"{APP_NAME} listens on this microphone for your wake word and voice commands."
-_SCREEN_CAPTURE_USAGE = (
- f"{APP_NAME} captures the screen only when you ask it to see or control applications."
-)
-_APPLE_EVENTS_USAGE = (
- f"{APP_NAME} lowers Music/Spotify volume while you dictate and restores it afterwards."
-)
+_PRIVACY_STRINGS_PATH = Path(__file__).resolve().parents[1] / "core" / "macos_privacy_strings.py"
+
+
+def _privacy_strings() -> ModuleType:
+ """Load the shared usage-string table BY PATH, exactly as ``jarvis.spec`` does.
+
+ The managed app is built from a source checkout, so the file is on disk. The
+ path load (rather than an ordinary import) is what lets the parity test
+ prove that both bundles read the same file. Nothing runs when this module
+ is imported; the file is read when a plist is built (a few hundred bytes).
+ A frozen app carries no source file, and it never builds a plist (desktop
+ registration is a no-op there), so a missing file is a loud error here,
+ never an empty plist.
+ """
+ loader_spec = importlib.util.spec_from_file_location(
+ "_jarvis_macos_privacy_strings", _PRIVACY_STRINGS_PATH
+ )
+ if loader_spec is None or loader_spec.loader is None:
+ raise RuntimeError(f"cannot load the macOS usage strings from {_PRIVACY_STRINGS_PATH}")
+ module = importlib.util.module_from_spec(loader_spec)
+ loader_spec.loader.exec_module(module)
+ return module
def _version() -> str:
@@ -164,6 +188,17 @@ def macos_applications_dir(
return user
+def _bundle_identifier(candidate: Path) -> str | None:
+ """``CFBundleIdentifier`` of ``candidate``; ``None`` when it cannot be read."""
+ try:
+ with (candidate / "Contents" / "Info.plist").open("rb") as stream:
+ bundle_id = plistlib.load(stream).get("CFBundleIdentifier")
+ except (OSError, ValueError, plistlib.InvalidFileException):
+ # Missing or unreadable metadata proves nothing about ownership.
+ return None
+ return bundle_id if isinstance(bundle_id, str) and bundle_id else None
+
+
def _is_foreign_bundle(candidate: Path) -> bool:
"""Whether ``candidate`` is an app of the same NAME that is not ours.
@@ -174,13 +209,27 @@ def _is_foreign_bundle(candidate: Path) -> bool:
``Info.plist`` naming a different bundle id proves that — a damaged bundle
of ours (no or unreadable ``Info.plist``) stays ours, so it can be repaired.
"""
- try:
- with (candidate / "Contents" / "Info.plist").open("rb") as stream:
- bundle_id = plistlib.load(stream).get("CFBundleIdentifier")
- except (OSError, ValueError, plistlib.InvalidFileException):
- # Missing or unreadable metadata proves nothing about ownership.
- return False
- return isinstance(bundle_id, str) and bool(bundle_id) and bundle_id != BUNDLE_ID
+ bundle_id = _bundle_identifier(candidate)
+ return bundle_id is not None and bundle_id != BUNDLE_ID
+
+
+def installed_macos_app_bundle_path() -> Path:
+ """The app the user actually launches: the managed bundle, else the .dmg app.
+
+ ``macos_app_bundle_path`` answers for the managed install only and, on a
+ Mac that has just the downloaded .dmg app, points at a bundle that does not
+ exist — so anything that has to bring the running app to the front (the
+ ``jarvis permissions`` commands) reported "app not found" for a perfectly
+ healthy install. The .dmg app is accepted only under its own bundle id.
+ """
+ managed = macos_app_bundle_path()
+ if managed.is_dir():
+ return managed
+ for root in (SYSTEM_APPLICATIONS_DIR, user_applications_dir()):
+ candidate = root / APP_DIR_NAME
+ if candidate.is_dir() and _bundle_identifier(candidate) == MACOS_DMG_BUNDLE_ID:
+ return candidate
+ return managed
def macos_app_bundle_path(*, applications_dir: Path | None = None) -> Path:
@@ -239,14 +288,16 @@ def _is_macho_executable(path: Path) -> bool:
def _codesign_issue(bundle: Path) -> str | None:
"""Return the codesign verification failure detail, or ``None`` if valid.
- Deliberately verifies WITHOUT ``--strict`` and ``--deep``: the local app
- is a py2app *alias* bundle whose entire design is symlinking the managed
- checkout and Python runtime, and strict validation rejects every symlink
- that leaves the bundle ("invalid destination for symbolic link") — it
- failed on 100% of freshly built bundles on real macOS (Intel and Apple
- Silicon alike). The ad-hoc signature only has to give the app a stable
- local TCC identity; distribution-grade validation belongs to the separate
- Developer-ID signing and notarization pipeline.
+ Deliberately verifies WITHOUT ``--strict`` and ``--deep``: the first
+ local app was a py2app *alias* bundle (since replaced by the native stub
+ launcher) whose entire design was symlinking the managed checkout and
+ Python runtime, and strict validation rejects every symlink that leaves the
+ bundle ("invalid destination for symbolic link") — it failed on 100% of
+ freshly built bundles on real macOS (Intel and Apple Silicon alike). The
+ native stub bundle has not been checked against ``--strict`` on a real Mac
+ (unverified), so the relaxed check stays. The ad-hoc signature only has to
+ give the app a stable local TCC identity; distribution-grade validation
+ belongs to the separate Developer-ID signing and notarization pipeline.
"""
if sys.platform != "darwin":
return None
@@ -647,13 +698,27 @@ def _bundle_plist() -> dict[str, object]:
"CFBundleVersion": _version(),
"JarvisBundleFormatVersion": _BUNDLE_FORMAT_VERSION,
"LSMinimumSystemVersion": "11.0",
- "NSAppleEventsUsageDescription": _APPLE_EVENTS_USAGE,
"NSHighResolutionCapable": True,
- "NSMicrophoneUsageDescription": _MIC_USAGE,
- "NSScreenCaptureUsageDescription": _SCREEN_CAPTURE_USAGE,
+ # Every NS...UsageDescription string comes from the one table shared
+ # with jarvis.spec (the .dmg app), never from a copy kept here. The
+ # German and Spanish text is declared here and written as
+ # <lang>.lproj/InfoPlist.strings by _write_localizations.
+ **_privacy_strings().usage_descriptions(),
+ **_privacy_strings().localization_plist_keys(),
}
+def _write_localizations(resources: Path) -> None:
+ """Write the German and Spanish ``InfoPlist.strings`` into ``resources``.
+
+ Part of laying out a bundle, before it is signed (the files are in the seal).
+ Existing installed bundles are NOT rewritten: the format version stays, because
+ a bump would rebuild every bundle and an ad-hoc rebuild is a new identity that
+ re-asks every permission. The next rebuild for another reason carries them.
+ """
+ _privacy_strings().write_localizations(resources)
+
+
def _remove_path(path: Path) -> None:
if path.is_symlink() or path.is_file():
path.unlink(missing_ok=True)
@@ -677,6 +742,7 @@ def _write_cross_platform_fixture_bundle(bundle: Path) -> Path:
info["CFBundleExecutable"] = executable_name
with (contents / "Info.plist").open("wb") as stream:
plistlib.dump(info, stream)
+ _write_localizations(resources)
return bundle
@@ -864,6 +930,7 @@ def _build_native_bundle(install_root: Path, work_dir: Path) -> Path:
executable.chmod(executable.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
with (bundle / "Contents" / "Info.plist").open("wb") as stream:
plistlib.dump(plist, stream)
+ _write_localizations(resources)
return bundle
@@ -1049,7 +1116,7 @@ def _install_native_bundle(
# An ad-hoc rebuild changed the app's TCC identity: every recorded grant
# is now orphaned and would read as silently DENIED (BUG-083). With the
# certificate identity the requirement is unchanged and nothing is reset.
- _reset_or_explain(bundle, previous_identity)
+ _reset_after_identity_change(bundle, previous_identity)
return bundle
@@ -1121,41 +1188,22 @@ def _resign_bundle_in_place(bundle: Path, identity: str, *, prepare=None) -> Pat
if previous.exists() or previous.is_symlink():
previous.rename(bundle)
raise
- _reset_or_explain(bundle, previous_identity)
+ _reset_after_identity_change(bundle, previous_identity)
return bundle
-def _reset_or_explain(bundle: Path, previous_identity: str | None) -> None:
- """Reset the orphaned TCC rows once — never in a loop (BUG-159).
+def _reset_after_identity_change(bundle: Path, previous_identity: str | None) -> None:
+ """Drop the orphaned TCC rows once, when the bundle's identity changed (BUG-083).
- A rebuild that keeps recurring (a failing identity probe, a churning
- interpreter) would otherwise wipe the user's permissions on every single
- start: they grant everything, restart, and are asked again. The pending
- marker says the LAST reset never got them to a working state, so repeating
- it can only destroy grants. Skip it then and keep the explanation up — the
- permissions view carries a per-row "Ask again" that resets exactly the row
- the user chooses.
+ A rebuild loop (a failing identity probe, a churning interpreter) must not
+ wipe the user's permissions on every start (BUG-159, BUG-161): that loop is
+ stopped one layer up, by the rebuild fingerprint that refuses to build the
+ identical app again, so this only ever runs for a rebuild that really
+ happened. The app then asks again just in time, at the moment a feature
+ needs a permission; there is nothing to explain up front.
"""
- from jarvis.platform.permissions import (
- identity_reset_pending,
- record_identity_reset,
- )
-
- if not _tcc_reset_needed(previous_identity, _bundle_tcc_identity(bundle)):
- return
- if identity_reset_pending():
- log.warning(
- "The app signature changed again while an earlier permission reset "
- "is still unresolved — NOT resetting the macOS grants a second time. "
- "Rebuilds are recurring on this install; fix the cause above."
- )
- else:
+ if _tcc_reset_needed(previous_identity, _bundle_tcc_identity(bundle)):
_reset_stale_tcc_grants()
- # Either way the user now faces an app macOS treats as a stranger. Record
- # it so the permissions view explains the re-ask instead of just showing
- # everything as missing again; snapshot() retires the note once the grants
- # are back.
- record_identity_reset(_TCC_SERVICES)
def ensure_macos_app_bundle(
@@ -1173,7 +1221,11 @@ def ensure_macos_app_bundle(
)
if applications_dir is None and sys.platform == "darwin":
from jarvis.autostart.macos import retarget_launch_agent
+ from jarvis.platform.permissions import remove_leftover_state_files
+ # An upgrade drops the two state files the permission wall of an earlier
+ # build kept; nothing reads them any more.
+ remove_leftover_state_files()
# A repair that failed still leaves the app wherever it was moved to,
# and login must find it there.
target = bundle or macos_app_bundle_path()
@@ -1346,6 +1398,7 @@ __all__ = [
"last_error",
"macos_app_bundle_is_launchable",
"SYSTEM_APPLICATIONS_DIR",
+ "installed_macos_app_bundle_path",
"macos_app_bundle_path",
"macos_applications_dir",
"user_applications_dir",
diff --git a/jarvis/setup/onboarding_meta.py b/jarvis/setup/onboarding_meta.py
index 3d9018dffe..7bdfe19032 100644
--- a/jarvis/setup/onboarding_meta.py
+++ b/jarvis/setup/onboarding_meta.py
@@ -20,20 +20,23 @@ CURRENT_TERMS_VERSION = "1.0"
# Agents tab, the wake-word group in Settings) and points at it. The tour of the app runs
# AFTER the completion restart and is tracked separately
# (``tour_completed_at`` in jarvis.setup.state).
-# Restart batching (maintainer mandate 2026-07-18): permissions and voice sit
-# LAST, directly before ready, because both only take full effect after a
-# relaunch — and onboarding already ends with one unconditional fresh restart
-# (onboarding_routes._schedule_fresh_restart). Permissions precede voice so the
-# macOS microphone grant exists before the wake-word group's microphone test.
+# Restart batching (maintainer mandate 2026-07-18): voice sits LAST, directly
+# before ready, because it only takes full effect after a relaunch — and
+# onboarding already ends with one unconditional fresh restart
+# (onboarding_routes._schedule_fresh_restart).
# "how" (2026-10-01) is an interactive explainer of what the assistant is and
# how its parts connect, shown before anything is set up — new users went
# through setup without understanding the product.
+# There is NO permissions step (just-in-time permissions, AP-35): nothing asks
+# macOS for anything during first run except where a switch IS the gesture (the
+# wake-word switch on the voice step asks for the microphone there, and says so
+# inside the spotlight hole). A stored legacy step id "permissions" resumes at
+# "voice" (frontend ``resumeStep``); the backend never validates the stored id.
ONBOARDING_STEPS: list[str] = [
"welcome",
"how",
"keys",
"subscriptions",
- "permissions",
"voice",
"ready",
]
diff --git a/jarvis/speech/diagnose.py b/jarvis/speech/diagnose.py
index 7d93961775..2cacdf7559 100644
--- a/jarvis/speech/diagnose.py
+++ b/jarvis/speech/diagnose.py
@@ -32,7 +32,7 @@ try:
except Exception: # noqa: BLE001 — sounddevice/PortAudio (libportaudio2) absent (headless/slim)
sd = None # type: ignore[assignment]
-from jarvis.audio.capture import MicrophoneCapture, pcm_bytes_to_np
+from jarvis.audio.capture import MicrophoneAccessError, MicrophoneCapture, pcm_bytes_to_np
from jarvis.audio.chime import CHIME_PCM, CHIME_SAMPLE_RATE
from jarvis.audio.player import AudioPlayer
@@ -97,15 +97,32 @@ async def measure_mic_dbfs(
duration_s: float = 3.0,
*,
on_frame: Callable[[float, float, int], None] | None = None,
+ interactive: bool = False,
+ permission_wait_s: float = 0.0,
) -> float:
"""Return the max dBFS heard over ``duration_s``; -120.0 if no samples / no
device / any error. Pure measurement (no printing) — reused by the
onboarding mic-level route (``GET /api/settings/wake-word/mic-level``) and
by ``step_mic_level``'s CLI bars via the optional ``on_frame`` hook
- (called per chunk with ``(dbfs, running_max, n_samples)``). Never raises."""
+ (called per chunk with ``(dbfs, running_max, n_samples)``).
+
+ Raises ONLY ``MicrophoneAccessError`` (``.result`` carries the permission
+ layer's answer): a microphone the OS has not granted is a different fact from
+ "no microphone", so it is never folded into the -120.0 floor. A caller that
+ wants the floor for every failure catches that one type itself. Every other
+ error degrades to the floor.
+
+ ``interactive`` says a user gesture started the measurement, so the capture
+ may make macOS ask (a route that already ensured the permission passes the
+ default False and asks nothing); ``permission_wait_s`` waits for the dialog.
+ """
max_dbfs = -120.0
try:
- async with MicrophoneCapture() as mic:
+ async with MicrophoneCapture(
+ permission_feature="voice",
+ interactive=interactive,
+ permission_wait_s=permission_wait_s,
+ ) as mic:
t_end = time.time() + duration_s
async for chunk in mic.stream():
if time.time() >= t_end:
@@ -116,13 +133,27 @@ async def measure_mic_dbfs(
max_dbfs = max(max_dbfs, dbfs)
if on_frame is not None:
on_frame(dbfs, max_dbfs, len(arr))
+ except MicrophoneAccessError:
+ raise # not "no microphone": the caller reports the permission honestly
except Exception: # noqa: BLE001 — headless / no device / any error → honest floor
+ log.debug("Mic level measurement failed; reporting the floor.", exc_info=True)
return -120.0
return max_dbfs
-async def step_mic_level(duration_s: float = 10.0) -> float:
- """Measures the live mic level — the user should speak loudly, max dBFS is recorded."""
+def _print_mic_blocked(exc: MicrophoneAccessError) -> None:
+ """Say that the microphone is not granted: distinct from "no microphone"."""
+ print()
+ print(" ⚠ Microphone access is not granted, so nothing was measured.")
+ print(f" {exc}")
+
+
+async def step_mic_level(duration_s: float = 10.0) -> float | None:
+ """Measures the live mic level — the user should speak loudly, max dBFS is recorded.
+
+ Returns ``None`` when the microphone is not granted (nothing was measured):
+ that is a permission answer, not a silent room.
+ """
_print_header(2, f"Mic level test ({int(duration_s)} seconds — SPEAK NOW!)")
print("Speak loudly — count to ten or sing a bit.")
print("Max level should be in the range -20 to -5 dBFS.")
@@ -137,7 +168,18 @@ async def step_mic_level(duration_s: float = 10.0) -> float:
sys.stdout.write(f"\r level: {dbfs:6.1f} dBFS {bar:<30s} (max: {running_max:6.1f})")
sys.stdout.flush()
- max_dbfs = await measure_mic_dbfs(duration_s=duration_s, on_frame=_render_bar)
+ try:
+ # A person started this run, so the capture may ask the OS (from an
+ # installed app; a terminal run is told which app to allow instead).
+ max_dbfs = await measure_mic_dbfs(
+ duration_s=duration_s,
+ on_frame=_render_bar,
+ interactive=True,
+ permission_wait_s=60.0,
+ )
+ except MicrophoneAccessError as exc:
+ _print_mic_blocked(exc)
+ return None
print()
print(f"→ Samples received: {samples_seen} Max level: {max_dbfs:.1f} dBFS")
if samples_seen == 0:
@@ -191,7 +233,7 @@ async def step_wake_live(duration_s: float = 20.0) -> None:
last_report_t = time.time()
max_in_window = 0.0
t_end = time.time() + duration_s
- async with MicrophoneCapture() as mic:
+ async with MicrophoneCapture(permission_feature="voice", interactive=True) as mic:
async for chunk in mic.stream():
if time.time() >= t_end:
break
@@ -239,7 +281,7 @@ async def step_whisper(duration_s: float = 4.0) -> None:
collected = bytearray()
t_end = time.time() + duration_s
- async with MicrophoneCapture() as mic:
+ async with MicrophoneCapture(permission_feature="voice", interactive=True) as mic:
async for chunk in mic.stream():
if time.time() >= t_end:
break
@@ -278,9 +320,16 @@ async def _main() -> None:
logging.basicConfig(level=logging.WARNING) # quiet, we print ourselves
step_devices()
- await step_mic_level(10.0)
- await step_wake_live(20.0)
- await step_whisper(4.0)
+ level = await step_mic_level(10.0)
+ if level is None:
+ print()
+ print(" Skipping the steps that need the microphone.")
+ else:
+ try:
+ await step_wake_live(20.0)
+ await step_whisper(4.0)
+ except MicrophoneAccessError as exc: # the grant was lost between the steps
+ _print_mic_blocked(exc)
await step_chime()
await step_tts()
print()
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 0e8e56cade..d663d9129a 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -34,6 +34,7 @@ import numpy as np
from jarvis.audio import level_tap, mic_level
from jarvis.audio.capture import (
REALTIME_QUEUE_CHUNKS,
+ MicrophoneAccessError,
MicrophoneCapture,
capture_chunks_for_duration,
pcm_bytes_to_np,
@@ -73,6 +74,7 @@ from jarvis.core.events import (
ListeningStarted,
MessageSent,
ObservationCaptured,
+ PermissionResolved,
PetVisibilityToggleRequested,
SpeechSpoken,
TranscriptFinal,
@@ -948,6 +950,15 @@ _DICTATION_HANDOVER_TIMEOUT_S = 5.0
# Small enough to be imperceptible, large enough not to spin the loop.
_DICTATION_HANDOVER_POLL_S = 0.02
+# Said when a voice gesture is refused and the permission layer has no sentence of
+# its own (an unreadable permission, an injected gate that only says "no").
+_MICROPHONE_REFUSED_SENTENCE = "Microphone access is not available for Personal Jarvis right now."
+
+# How long the wake loop parks on the microphone permission before it re-reads the
+# gate on its own. The grant normally wakes it at once (PermissionResolved); this
+# is the fallback for an edge that never arrived.
+_WAKE_PERMISSION_PARK_S = 30.0
+
# How many times the FINAL dictation transcription is attempted, and how long it
# waits between attempts. Only the final call is retried: every earlier one is a
# probe tick that gets another chance a second later anyway, while this one is
@@ -2291,6 +2302,13 @@ class SpeechPipeline:
config: Any = None,
vision_provider: Any = None,
activation_gate: Callable[[], bool] | None = None,
+ # Silent predicate for a USER gesture (push-to-talk, a voice session,
+ # dictation): true unless the microphone is refused. ``activation_gate``
+ # stays the BACKGROUND one (wake word, barge-in: a live grant only).
+ # Neither asks the OS; the gesture entry points do, through
+ # ``permission_gate`` (the permission service by default).
+ user_activation_gate: Callable[[], bool] | None = None,
+ permission_gate: Any = None,
# Pre-Thinking-Ack Flash-Brain (spec: 2026-05-11-pre-thinking-ack-
# flash-brain-design.md). When provided, every user utterance kicks
# off a parallel acknowledgment LLM call BEFORE the main brain
@@ -3001,6 +3019,11 @@ class SpeechPipeline:
self._config = config
self._vision_provider = vision_provider
self._activation_gate = activation_gate or (lambda: True)
+ self._user_activation_gate = user_activation_gate or (lambda: True)
+ self._permission_gate = permission_gate
+ # True only while the wake loop is parked on the microphone permission:
+ # the one state in which a PermissionResolved edge should wake it.
+ self._wake_parked_on_permission = False
# Wave 0 (omni-latency): per-turn hot-path latency tracker. Anchored at
# utterance finalize in ``_handle_utterance``; ``None`` until a turn runs.
self._latency_tracker: LatencyTracker | None = None
@@ -3123,6 +3146,9 @@ class SpeechPipeline:
# going through the brain path. The handler speaks directly via TTS.
if self._bus is not None:
self._bus.subscribe(AnnouncementRequested, self._on_announcement)
+ # A microphone grant (from the OS dialog, or from System Settings and
+ # seen by the service watcher) wakes a wake loop parked on it.
+ self._bus.subscribe(PermissionResolved, self._on_permission_resolved)
# Fire-and-forget Jarvis-Agent: when a background run finishes,
# a proactive voice announcement ("Sir, done. <summary>") — so
# the user finds out even if they did something else in the
@@ -4430,8 +4456,13 @@ class SpeechPipeline:
return "pause"
return None
- def _capture_permission_allowed(self) -> bool:
- """Return the live local-capture gate without applying Jarvis mute."""
+ def _background_capture_allowed(self) -> bool:
+ """Silent gate for BACKGROUND capture (wake word, barge-in): a live grant only.
+
+ Never asks the OS and never opens the device. An undecided microphone is
+ closed here because nothing the user did is waiting on it: the wake loop
+ parks and a gesture elsewhere asks. Does not apply Jarvis mute.
+ """
gate = getattr(self, "_activation_gate", None)
if gate is None:
return True
@@ -4441,6 +4472,65 @@ class SpeechPipeline:
log.warning("Voice capture permission gate failed closed: %s", exc)
return False
+ def _user_capture_allowed(self) -> bool:
+ """Silent gate for USER-started capture (push-to-talk, voice session, dictation).
+
+ True unless the microphone is denied, restricted or unavailable: an
+ undecided microphone is usable because the gesture itself asks (see
+ ``_ensure_microphone``). Never asks and never opens the device.
+ """
+ gate = getattr(self, "_user_activation_gate", None)
+ if gate is None:
+ return True
+ try:
+ return bool(gate())
+ except Exception as exc: # noqa: BLE001
+ log.warning("Voice user-capture permission gate failed closed: %s", exc)
+ return False
+
+ def _permission_service(self) -> Any:
+ """The injected ``PermissionGate``, else the process service (resolved per call)."""
+ gate = getattr(self, "_permission_gate", None)
+ if gate is not None:
+ return gate
+ from jarvis.platform.permission_service import get_permission_service
+
+ return get_permission_service()
+
+ def _ensure_microphone(self, feature: str) -> str | None:
+ """THE ask of a voice gesture: ``ensure(MICROPHONE, wait_s=0)``.
+
+ Returns ``None`` when the microphone is granted (or this is not a TCC
+ platform), else a finished English sentence saying why not. ``wait_s=0``
+ is the loop-safe form: a first press may make macOS show its dialog and
+ returns PENDING at once, so the press that raised the dialog is NOT
+ started retroactively (the UI says "allowed - press again"). The service
+ publishes the ``PermissionNeeded`` episode itself, a denial included.
+ Never raises; a failed read refuses.
+ """
+ try:
+ result = self._permission_service().ensure(
+ "microphone", feature=feature, interactive=True, wait_s=0.0
+ )
+ except Exception: # noqa: BLE001 - an unreadable permission must not start the capture
+ log.warning("The microphone permission check for %s failed.", feature, exc_info=True)
+ return _MICROPHONE_REFUSED_SENTENCE
+ if result.granted:
+ return None
+ return str(result.user_detail or "") or _MICROPHONE_REFUSED_SENTENCE
+
+ async def _on_permission_resolved(self, event: PermissionResolved) -> None:
+ """A microphone grant wakes a wake loop that is parked on the permission.
+
+ Runs on the loop (bus dispatch), so setting the asyncio event is safe. A
+ resolution while the loop is not parked changes nothing: a wake capture
+ that is already running must not be torn down by a dictation's grant.
+ """
+ if not event.granted or "microphone" not in event.permissions:
+ return
+ if getattr(self, "_wake_parked_on_permission", False):
+ self._wake_reload_event.set()
+
def _dictation_blocks_activation(self) -> bool:
"""True while a running dictation must keep the wake word silent.
@@ -4483,24 +4573,54 @@ class SpeechPipeline:
return False
return time.time() < float(getattr(self, "_dictation_wake_block_until", 0.0))
- def _activation_block_reason(self) -> str:
+ def _activation_state_allows(self) -> bool:
+ """The non-permission half of the gate: mute, a running dictation, mic ownership.
+
+ Split out so a gesture entry point can refuse for these reasons BEFORE it
+ asks the OS for anything (a muted press must not raise a macOS dialog), and
+ so the wake loop can tell "waiting on the permission" from "waiting on the
+ state" and park only for the first.
+ """
+ if getattr(self, "_muted", False):
+ return False
+ if self._dictation_blocks_activation():
+ return False
+ from jarvis.live.runtime import owns_microphone
+
+ return not owns_microphone(
+ except_session_id=getattr(self, "_current_voice_session_id", None)
+ )
+
+ def _activation_block_reason(
+ self, *, explicit: bool = False, include_permission: bool = True
+ ) -> str:
"""The honest English reason ``_activation_allowed`` is saying no.
One source for every log line that reports the closed gate. It exists
because those lines used to hardcode two guesses ("muted" /
"window not visible?"), and the wrong guess once misled a live freeze
- diagnosis. Returns an empty string when the gate is open.
+ diagnosis. Returns an empty string when the gate is open. ``explicit``
+ selects the user-gesture permission predicate, as in ``_activation_allowed``.
+ ``include_permission=False`` names only the state half (a gesture entry
+ point that refused on the state alone and must not report the microphone).
"""
if getattr(self, "_muted", False):
return "voice is muted"
if self._dictation_blocks_activation():
return "a dictation is running"
- if not self._capture_permission_allowed():
- return "microphone capture is not permitted (desktop window not visible?)"
+ if not include_permission:
+ return ""
+ permitted = self._user_capture_allowed() if explicit else self._background_capture_allowed()
+ if not permitted:
+ return (
+ "microphone access is not granted"
+ if not explicit
+ else "microphone access is denied or unavailable"
+ )
return ""
def _activation_allowed(self) -> bool:
- """True when external UI/lifecycle state permits voice activation.
+ """True when external UI/lifecycle state permits BACKGROUND voice activation.
While muted (mascot doubleClick → ``_muted=True``) we always
return False so the wake-loop ignores every detection. The loop
@@ -4509,25 +4629,34 @@ class SpeechPipeline:
A running dictation closes the same gate (``_dictation_blocks_activation``)
— one edit reaches all three wake gates (loop entry, pre-emit, state
loop) plus the push-to-talk and ``request_voice_session`` entry points,
- because this predicate is the only one all of them consult.
+ because the state half of this predicate is shared with all of them
+ (``_activation_state_allows``).
+
+ The permission half is ``_background_capture_allowed``: a live microphone
+ GRANT. A deliberate user action (the call key, push-to-talk, the speak
+ button) uses ``_gesture_activation_allowed`` instead, which only needs the
+ microphone not to be refused, because the gesture is what asks the OS.
+ Neither ever asks from here.
``getattr`` defaults to False for pipelines constructed via
``__new__`` (used by privacy/vision unit tests that bypass
``__init__``) — those instances are never muted by definition.
- NB: ``dictation_available`` / ``start_dictation`` deliberately consult
- ``_capture_permission_allowed`` and NOT this predicate. Routing them
- through here would make a dictation forbid its own successor.
+ NB: ``dictation_available`` / ``start_dictation`` deliberately do NOT
+ consult this predicate. Routing them through here would make a
+ dictation forbid its own successor.
"""
- if getattr(self, "_muted", False):
- return False
- if self._dictation_blocks_activation():
- return False
- from jarvis.live.runtime import owns_microphone
+ return self._activation_state_allows() and self._background_capture_allowed()
- if owns_microphone(except_session_id=getattr(self, "_current_voice_session_id", None)):
- return False
- return self._capture_permission_allowed()
+ def _gesture_activation_allowed(self) -> bool:
+ """``_activation_allowed`` for a deliberate user action (key, button, bar click).
+
+ Same state half (mute, a running dictation, mic ownership); the permission
+ half is ``_user_capture_allowed``: true unless the microphone is denied,
+ restricted or unavailable. The wake word is NOT such an action and never
+ passes through here.
+ """
+ return self._activation_state_allows() and self._user_capture_allowed()
@property
def is_muted(self) -> bool:
@@ -6964,7 +7093,15 @@ class SpeechPipeline:
if event_name == "call":
log.info("📞 CALL via Hotkey")
# A deliberate key press — exempt from the post-hangup wake
- # lock (no speaker-echo path), same contract as PTT below.
+ # lock (no speaker-echo path), same contract as PTT below. It is
+ # also the gesture that may ask macOS for the microphone: the first
+ # press of an undecided microphone raises the dialog and starts
+ # nothing ("allowed - press again").
+ if self._state == PipelineState.IDLE and self._activation_state_allows():
+ refusal = self._ensure_microphone("voice")
+ if refusal is not None:
+ log.info("Call key ignored: %s", refusal)
+ return
self._explicit_call_pending = True
self._call_event.set()
elif event_name == "ptt_press":
@@ -7232,17 +7369,29 @@ class SpeechPipeline:
return
if self._state != PipelineState.IDLE:
return
- if not self._activation_allowed():
- # Push-to-talk is gated by the SAME predicate as wake, so a running
- # dictation refuses it too — deliberately: both lanes open their own
- # microphone stream, and two native input streams on one device is
- # the BUG-014 family. The reason is resolved, never guessed, so the
- # log cannot claim "window not visible" during a dictation.
+ if not self._activation_state_allows():
+ # Push-to-talk shares the STATE half of wake's gate (mute, mic
+ # ownership), so a running dictation refuses it too — deliberately:
+ # both lanes open their own microphone stream, and two native input
+ # streams on one device is the BUG-014 family. The reason is
+ # resolved, never guessed, so the log cannot claim "window not
+ # visible" during a dictation.
log.info(
"PTT press ignored: %s",
- self._activation_block_reason() or "activation not allowed",
+ self._activation_block_reason(explicit=True, include_permission=False)
+ or "activation not allowed",
)
return
+ # The press is the gesture that may ask macOS for the microphone. The
+ # first press of an undecided microphone raises the OS dialog and is NOT
+ # started retroactively once it is answered ("allowed - press again").
+ # The silent user predicate is deliberately NOT consulted first: a denied,
+ # restricted or unavailable microphone must still reach ``ensure`` so the
+ # press is refused WITH its ``PermissionNeeded`` toast (one per episode).
+ refusal = self._ensure_microphone("voice")
+ if refusal is not None:
+ log.info("PTT press ignored: %s", refusal)
+ return
# NB: the post-hangup wake-lock is deliberately NOT consulted here. That
# lock exists to stop Jarvis' own TTS tail from re-triggering the *wake
# word* (audio echo). PTT is an explicit key press — no echo path — so
@@ -7289,12 +7438,21 @@ class SpeechPipeline:
if self._ptt_mode or self._state != PipelineState.IDLE:
log.info("request_voice_session ignored: pipeline not idle.")
return False
- if not self._activation_allowed():
+ if not self._activation_state_allows():
log.info(
"request_voice_session ignored: %s",
- self._activation_block_reason() or "activation not allowed",
+ self._activation_block_reason(explicit=True, include_permission=False)
+ or "activation not allowed",
)
return False
+ # Gesture entry: the speak button / bar click may ask macOS for the
+ # microphone. A first request raises the dialog and returns False (the UI
+ # says "allowed - press again"); the session is never armed retroactively.
+ # As for PTT, a denied microphone reaches ``ensure`` too (toast, not silence).
+ refusal = self._ensure_microphone("voice")
+ if refusal is not None:
+ log.info("request_voice_session ignored: %s", refusal)
+ return False
if seed_messages:
brain = getattr(self, "_brain", None)
seed = getattr(brain, "seed_history", None)
@@ -8022,12 +8180,35 @@ class SpeechPipeline:
# block), so the defence is depth — enough slack that a slow
# provider call cannot cost words.
max_queue_chunks=_DICTATION_CAPTURE_QUEUE_CHUNKS,
+ # A key press / button started this capture, so a lost grant is
+ # reported as a user-origin ``dictation`` episode.
+ permission_feature="dictation",
+ interactive=True,
) as mic:
yield mic
def _wake_listening_enabled(self) -> bool:
return self._openwakeword_enabled or self._whisper_wake_enabled
+ async def _wait_while_wake_disabled(self) -> None:
+ """Wait on ``_wake_reload_event`` while both wake detectors are off.
+
+ Touches no permission and opens no episode: a switched-off wake word never
+ owns the microphone permission (P7). Returns at once when a detector is on.
+ """
+ while not self._wake_listening_enabled():
+ log.warning(
+ "Both wake detectors are disabled — wake is PARKED until a "
+ "wake-word change re-enables one (voice still works via hotkey). "
+ "Waiting on a live wake-plan reload, not sleeping forever."
+ )
+ try:
+ await asyncio.wait_for(self._wake_reload_event.wait(), timeout=30.0)
+ except TimeoutError:
+ pass # the 30 s fallback poll: no reload came, the loop re-reads the plan
+ finally:
+ self._wake_reload_event.clear()
+
async def _wake_loop(self) -> None:
"""Listen for a wake phrase through two parallel paths while idle.
@@ -8051,20 +8232,15 @@ class SpeechPipeline:
# in-app. The 30 s timeout re-logs the parked state so a genuinely dead
# listener stays visible without busy-spinning. (Mission: "no dead state
# blocks waking"; AP-22: recovery must be reachable in-app, not a restart.)
- while not self._wake_listening_enabled():
- log.warning(
- "Both wake detectors are disabled — wake is PARKED until a "
- "wake-word change re-enables one (voice still works via hotkey). "
- "Waiting on a live wake-plan reload, not sleeping forever."
- )
- try:
- await asyncio.wait_for(self._wake_reload_event.wait(), timeout=30.0)
- except TimeoutError:
- pass
- finally:
- self._wake_reload_event.clear()
+ await self._wait_while_wake_disabled()
gate_blocked_logged_at = 0.0
while True:
+ # Re-checked on EVERY pass, not only before the loop: a user who
+ # switches the wake word OFF while the loop is parked on the
+ # microphone permission must send it back to the "disabled" wait,
+ # or it would re-open a wake_word permission episode every park
+ # interval for a feature nobody switched on (P7).
+ await self._wait_while_wake_disabled()
if not self._activation_allowed():
now = time.time()
if now - gate_blocked_logged_at > 30.0:
@@ -8078,7 +8254,14 @@ class SpeechPipeline:
self._activation_block_reason() or "reason unknown",
)
gate_blocked_logged_at = now
- await asyncio.sleep(0.25)
+ if self._activation_state_allows():
+ # Only the microphone permission is missing. Mute, a running
+ # dictation and mic ownership change on their own clock and
+ # keep the short poll below; a permission changes rarely and
+ # announces itself, so the loop PARKS instead of re-probing.
+ await self._park_until_microphone_allowed()
+ else:
+ await asyncio.sleep(0.25)
continue
if self._state != PipelineState.IDLE:
await asyncio.sleep(0.1)
@@ -8089,10 +8272,56 @@ class SpeechPipeline:
getattr(self, "_wake_phrase_label", "the wake word"),
)
await self._run_parallel_wake()
+ except MicrophoneAccessError as exc:
+ # The grant is missing or was just lost: not a crash, so no
+ # traceback and no 0.5 s retry churn. Park until it is granted.
+ log.info("Wake listening paused: %s", exc)
+ await self._park_until_microphone_allowed()
except Exception as exc: # noqa: BLE001
log.exception("Wake loop failed: %s", exc)
await asyncio.sleep(0.5)
+ async def _park_until_microphone_allowed(self) -> None:
+ """Park the wake loop until the microphone is granted (never asks).
+
+ The wake word is a background feature: it must not make macOS ask, and it
+ must not poll either. So the loop opens ONE background-origin episode
+ (``ensure(interactive=False)``: no request, status snapshot only), which is
+ what lets the permission service watcher notice a grant given later in
+ System Settings and publish ``PermissionResolved``; ``_on_permission_resolved``
+ then sets ``_wake_reload_event``. ``set_wake_plan`` and the 30 s fallback
+ timeout wake the loop through the same event, so a missed edge costs at most
+ half a minute, never a restart. The episode is re-opened on each wake-up
+ that still finds the gate closed (idempotent in the service: same episode,
+ no second event), which also revives one the service expired after ten
+ minutes of nobody touching it.
+ """
+ if not self._wake_listening_enabled():
+ return # switched off since the caller read the gate: no episode (P7)
+ self._wake_parked_on_permission = True
+ try:
+ try:
+ opened = await self._permission_service().ensure_async(
+ "microphone", feature="wake_word", interactive=False
+ )
+ except Exception: # noqa: BLE001 - the park must work without the episode
+ log.debug("Opening the wake-word permission episode failed.", exc_info=True)
+ else:
+ if opened.granted:
+ # Granted between the gate read and now: no episode was opened,
+ # so no edge will come. Let the caller re-read the gate.
+ await asyncio.sleep(0.25)
+ return
+ try:
+ await asyncio.wait_for(
+ self._wake_reload_event.wait(), timeout=_WAKE_PERMISSION_PARK_S
+ )
+ except TimeoutError:
+ pass # fallback poll: the caller re-reads the gate
+ finally:
+ self._wake_parked_on_permission = False
+ self._wake_reload_event.clear()
+
def _should_show_optimistic_candidate(self) -> bool:
"""Whether an unverified OWW hit may pop the overlay bar immediately.
@@ -8472,7 +8701,13 @@ class SpeechPipeline:
# applies and is safe here.
async with _wake_capture_with_release(
MicrophoneCapture(
- device=self._input_device, device_priority=self._input_priority
+ device=self._input_device,
+ device_priority=self._input_priority,
+ # Background capture: it never makes macOS ask (the gate above
+ # already required a live grant) and reports a lost grant as
+ # ``wake_word``.
+ permission_feature="wake_word",
+ interactive=False,
),
self._wake_capture_released,
) as mic:
@@ -8804,13 +9039,21 @@ class SpeechPipeline:
getattr(self, "_explicit_call_pending", False)
) or bool(getattr(self, "_ptt_mode", False))
self._explicit_call_pending = False
- if not self._activation_allowed():
+ allowed = (
+ self._gesture_activation_allowed()
+ if explicit_call
+ else self._activation_allowed()
+ )
+ if not allowed:
# Resolved, never guessed: this backstop closes for a mute and
# for a running dictation too, and a log line that names the
# window instead is exactly what misled an earlier diagnosis.
+ # A deliberate press (``explicit_call``) is judged by the
+ # user-gesture predicate, a wake word by the background one.
log.info(
"Voice call ignored: %s.",
- self._activation_block_reason() or "activation not allowed",
+ self._activation_block_reason(explicit=explicit_call)
+ or "activation not allowed",
)
# A discarded call consumes any PTT arming with it — otherwise a
# stale ``_ptt_mode`` would reroute the NEXT (wake-word) call
@@ -10780,12 +11023,12 @@ class SpeechPipeline:
Lets the UI hide the mic button on a headless host with no capture
device (cloud-first: a missing capability is a clean no-op, AD-OE6).
+
+ The microphone PERMISSION is deliberately not a term here: the button
+ must be visible on a fresh Mac, where the first press is what asks.
+ ``start_dictation`` refuses honestly when the permission is missing.
"""
- return (
- self._utterance_stt is not None
- and self._input_device != "none"
- and self._capture_permission_allowed()
- )
+ return self._utterance_stt is not None and self._input_device != "none"
def dictation_engine_status(self) -> dict[str, Any]:
"""Which recognizer the dictation lane will really use, for the UI.
@@ -10896,13 +11139,6 @@ class SpeechPipeline:
only publishes ``DictationStarted`` / ``DictationTranscript`` /
``DictationTranscribing`` / ``DictationCompleted`` events.
"""
- if not self._capture_permission_allowed():
- self._refuse_dictation(
- "microphone_unavailable",
- "Microphone access is not ready — check the microphone "
- "permission and make sure the desktop window is available.",
- )
- return False
if self._utterance_stt is None:
self._refuse_dictation(
"no_stt",
@@ -10924,6 +11160,18 @@ class SpeechPipeline:
"The voice pipeline is not running, so dictation cannot start.",
)
return False
+ # The press is the gesture that may ask macOS for the microphone. A first
+ # press of an undecided microphone raises the OS dialog and refuses THIS
+ # press ("microphone_unavailable" + the PermissionNeeded episode the
+ # service publishes); nothing starts retroactively once it is answered, the
+ # UI says "allowed - press again". The refusal sentence comes from the
+ # permission layer's fixed templates, never from exception text.
+ refusal = self._ensure_microphone("dictation")
+ if refusal is None and not self._user_capture_allowed():
+ refusal = _MICROPHONE_REFUSED_SENTENCE
+ if refusal is not None:
+ self._refuse_dictation("microphone_unavailable", refusal)
+ return False
if self._live_call_owns_microphone():
# A live call keeps running: its input is held, not hung up.
return self._commit_dictation(
diff --git a/jarvis/tasks/event_catalog.py b/jarvis/tasks/event_catalog.py
index 4d371c8c56..8c697a7bd2 100644
--- a/jarvis/tasks/event_catalog.py
+++ b/jarvis/tasks/event_catalog.py
@@ -4,25 +4,43 @@ from __future__ import annotations
import ast
from dataclasses import fields, is_dataclass
-from typing import Any
+from typing import Any, Final
from jarvis.core.events import Event
+#: Events a routine must never trigger on, by class name. Kept out of the
+#: catalog on purpose, so they are neither advertised to the user or an agent
+#: nor accepted by ``validate_event_schedule``.
+#:
+#: ``PermissionNeeded`` / ``PermissionResolved``
+#: They describe the state of an OS consent dialog and the grants behind it.
+#: An automation reacting to them would be an agent answering a system
+#: dialog (the macOS permission rules say an AI agent never does), and
+#: their ``target`` / ``detail`` fields describe the user's machine.
+EXCLUDED_EVENT_NAMES: Final[frozenset[str]] = frozenset(
+ {"PermissionNeeded", "PermissionResolved"}
+)
+
def event_catalog() -> dict[str, list[str]]:
- """Loaded event schemas; availability still depends on a live publisher."""
+ """Loaded event schemas; availability still depends on a live publisher.
+
+ Events in ``EXCLUDED_EVENT_NAMES`` are not part of it.
+ """
pending = list(Event.__subclasses__())
result = {}
while pending:
cls = pending.pop()
pending.extend(cls.__subclasses__())
- if is_dataclass(cls):
+ if is_dataclass(cls) and cls.__name__ not in EXCLUDED_EVENT_NAMES:
result[cls.__name__] = [field.name for field in fields(cls)]
return dict(sorted(result.items()))
def validate_event_schedule(schedule: dict[str, Any]) -> None:
name = str(schedule.get("event_name") or "")
+ if name in EXCLUDED_EVENT_NAMES:
+ raise ValueError(f"Event {name!r} cannot trigger a routine")
catalog = event_catalog()
if name not in catalog:
raise ValueError(f"Unknown event {name!r}; inspect society_routines for supported events")
diff --git a/jarvis/tasks/scheduler.py b/jarvis/tasks/scheduler.py
index a69899156c..a2e1327e2c 100644
--- a/jarvis/tasks/scheduler.py
+++ b/jarvis/tasks/scheduler.py
@@ -39,6 +39,7 @@ from jarvis.core.events import (
)
from jarvis.core.misfire import is_missed, late_by_s
from jarvis.core.protocols import RoutineDeferred, current_trigger_path
+from jarvis.tasks.event_catalog import EXCLUDED_EVENT_NAMES
from jarvis.tasks.hook_events import RoutineEventReceived
from jarvis.tasks.schema import PAUSABLE_TRIGGER_TYPES, TERMINAL_STATES, TaskSpec
@@ -623,6 +624,10 @@ class TaskScheduler:
await self._enqueue_hook_event(event)
return
cls_name = type(event).__name__
+ if cls_name in EXCLUDED_EVENT_NAMES:
+ # Permission episodes describe a system dialog on the user's machine:
+ # no routine may react to one, whichever way the task was stored.
+ return
task_ids = self._on_event_index.get(cls_name)
if not task_ids:
return
diff --git a/jarvis/trigger/backends/__init__.py b/jarvis/trigger/backends/__init__.py
index 016472248f..b9722b91c7 100644
--- a/jarvis/trigger/backends/__init__.py
+++ b/jarvis/trigger/backends/__init__.py
@@ -9,7 +9,8 @@ graceful null-fallback that logs an English message and never raises.
pre-remove-on-reentry sequence carry hard-won BUG fixes (the F1+F2-went-dead
class). That logic was **relocated verbatim** into
``jarvis/trigger/backends/global_hotkeys.py`` (AD-7); it is not refactored.
-* macOS/Linux (X11) gain ``pynput`` via ``PynputBackend``.
+* macOS uses a listen-only Quartz event tap (``QuartzHotkeyBackend``); Linux
+ (X11) gains ``pynput`` via ``PynputBackend``.
* Wayland (and any box where ``capabilities.has_hotkey`` is ``False``) gets
``NoopBackend``: it logs once that global hotkeys are unavailable by OS design
and otherwise no-ops (AD-8 / AD-OE6 "zero silent drops").
@@ -48,8 +49,12 @@ class HotkeyBackend(Protocol):
The lifecycle mirrors what ``HotkeyTrigger.__aenter__``/``__aexit__`` already
drive: ``register`` arms the bindings, ``start`` begins listening,
``stop``/``unregister`` tear down. ``received_any_event`` is the AD-8
- introspection hook — on macOS a backend that registered but saw zero events
- is the signal to surface the Input-Monitoring / Accessibility grant hint.
+ introspection hook (true once a BOUND chord fired; not a liveness signal).
+ A backend may also expose optional probes the trigger reads through
+ ``getattr``: ``is_listening()``, ``waiting_for_permission`` (the macOS tap
+ declined to start for want of Input Monitoring) and ``report_if_deaf()``
+ (the liveness pass the trigger gives a worker thread; it is built on the
+ backend's own ``deaf_tap_suspected()`` raw-callback counter, see ``quartz.py``).
"""
def register(self, bindings: list[HotkeyBinding], on_event: OnEvent | None = None) -> None:
diff --git a/jarvis/trigger/backends/noop.py b/jarvis/trigger/backends/noop.py
index 1589d6f706..965e9b50ad 100644
--- a/jarvis/trigger/backends/noop.py
+++ b/jarvis/trigger/backends/noop.py
@@ -83,9 +83,9 @@ def explain_unavailable() -> str:
if platform == "darwin":
return (
- "macOS needs both the Accessibility and Input Monitoring "
- "permissions, and the pyobjc Quartz package. Grant them under "
- "Settings > Permissions, then restart Jarvis."
+ "the pyobjc Quartz package is not installed (the [full] profile "
+ "includes it). With it, global shortcuts arm themselves once "
+ "macOS has allowed Input Monitoring for Personal Jarvis."
)
return (
@@ -128,6 +128,14 @@ class NoopBackend:
def received_any_event(self) -> bool:
return False
+ def is_listening(self) -> bool:
+ """Nothing is ever armed here, and the backend knows it.
+
+ A consumer that must not promise a key it does not hold (the "Esc to
+ cancel" pill) therefore reads ``False`` instead of "cannot say".
+ """
+ return False
+
def chord_is_down(self, combo: str) -> bool | None:
"""No listener, no keyboard state to report — honestly unknown."""
return None
diff --git a/jarvis/trigger/backends/pynput.py b/jarvis/trigger/backends/pynput.py
index a5378268c6..f16e4feabe 100644
--- a/jarvis/trigger/backends/pynput.py
+++ b/jarvis/trigger/backends/pynput.py
@@ -23,11 +23,12 @@ state), avoiding the press-only limitation of ``GlobalHotKeys``.
macOS permission hint (AD-8 / AD-13)
------------------------------------
-On macOS a global listener silently fires nothing until the user grants
-Input-Monitoring / Accessibility permission. ``received_any_event()`` reports
-whether any bound chord has actually fired, so the wizard can detect the
-"registered but zero events" state and surface the grant message instead of
-leaving the user with a dead hotkey and no explanation.
+On macOS a global listener silently fires nothing until the user grants Input
+Monitoring (a listen-only event tap needs that and nothing else). The darwin
+branch of ``start`` therefore stays closed until the grant is visible; the
+macOS app itself uses ``QuartzHotkeyBackend`` (BUG-077), which carries the
+liveness counter. ``received_any_event()`` only reports whether a BOUND chord
+has fired.
Import-cleanliness (HN-7): ``pynput`` is imported lazily inside ``start`` so
``import jarvis.trigger.backends.pynput`` succeeds on a box without the package.
@@ -47,12 +48,24 @@ log = logging.getLogger(__name__)
def _macos_hotkey_permissions_granted() -> bool:
- """Probe both native grants required by a macOS keyboard event tap."""
+ """Is Input Monitoring granted, the one grant a listen-only tap needs?
+
+ Silent, lock-free and never prompting: it is ``PermissionService.check``,
+ safe from the loop, from the tap callback and at boot. It does not ask the
+ OS for anything (the request belongs to a user gesture) and does not look at
+ the app's bundle identity: we act on whatever grant exists. ``NOT_REQUIRED``
+ (a host without TCC) counts as permitted, like ``EnsureResult.granted``.
+ """
+ from jarvis.platform.permission_service import ( # noqa: PLC0415
+ get_permission_service,
+ )
from jarvis.platform.permissions import ( # noqa: PLC0415
- get_system_permission_port,
+ PermissionId,
+ PermissionState,
)
- return get_system_permission_port().runtime_feature_ready("global_hotkeys")
+ state = get_permission_service().check(PermissionId.INPUT_MONITORING)
+ return state in (PermissionState.GRANTED, PermissionState.NOT_REQUIRED)
def _macos_layout_guard_ready() -> bool:
@@ -361,10 +374,10 @@ class PynputBackend:
if sys.platform == "darwin":
# pynput's darwin backend creates a Quartz event tap on its own
- # internal thread; without Accessibility and Input Monitoring that native
- # init is useless at best and a process-level abort at worst
- # (uncatchable, BUG-058 class). Preflight the non-prompting
- # native preflights and fail CLOSED instead of touching pynput.
+ # internal thread; without Input Monitoring that native init is
+ # useless at best and a process-level abort at worst (uncatchable,
+ # BUG-058 class). Preflight the non-prompting grant and fail CLOSED
+ # instead of touching pynput.
granted = False
try:
granted = _macos_hotkey_permissions_granted()
@@ -372,11 +385,9 @@ class PynputBackend:
granted = False
if granted is not True:
log.warning(
- "Global hotkeys disabled on macOS: the Accessibility "
- "and Input Monitoring permissions are not both granted. "
- "Use Personal Jarvis > Settings > Permissions, then "
- "re-arm the shortcut or restart Jarvis — voice still "
- "works via the wake word.",
+ "Global hotkeys are off on macOS until Input Monitoring "
+ "is allowed for Personal Jarvis; voice still works via "
+ "the wake word.",
)
self._listener = None
return
diff --git a/jarvis/trigger/backends/quartz.py b/jarvis/trigger/backends/quartz.py
index 37b3e0f953..f0bf204b07 100644
--- a/jarvis/trigger/backends/quartz.py
+++ b/jarvis/trigger/backends/quartz.py
@@ -10,11 +10,25 @@ first Intel-Mac onboarding. The main thread belongs to pywebview, so the only
safe path is to avoid the TSM APIs entirely.
This backend listens with a listen-only ``CGEventTap`` on a dedicated
-CFRunLoop thread (event taps are legal off the main thread; the BUG-058 gate
-already preflights the Accessibility + Input Monitoring grants that a tap
-needs) and matches chords by PHYSICAL key: a fixed ANSI virtual-keycode table
-plus the modifier flags word. No layout translation, no TSM, no main-queue
-assertion.
+CFRunLoop thread (event taps are legal off the main thread) and matches chords
+by PHYSICAL key: a fixed ANSI virtual-keycode table plus the modifier flags
+word. No layout translation, no TSM, no main-queue assertion.
+
+Permission contract (just-in-time permissions, AP-35): a LISTEN-ONLY tap needs
+Input Monitoring and nothing else (Apple WWDC19 session 701; an Accessibility
+grant also satisfies it, which is not special-cased here). The tap is created
+LAZILY: ``start()`` is a silent INFO-level no-op while Input Monitoring is not
+granted and NEVER calls ``CGEventTapCreate`` before the grant is visible (the
+BUG-058 class: creating a tap while the permission is undecided can register
+the app as denied or abort the process). This backend never asks the user
+either: the explicit request (``CGRequestListenEventAccess``) belongs to the
+permission service at a user gesture, and the service's grant listener re-runs
+``start()`` (see ``HotkeyTrigger``). A tap that is created but receives no
+event at all is detected through a raw-callback counter, never by waiting for a
+bound chord (:meth:`QuartzHotkeyBackend.deaf_tap_suspected`); the owner's watch
+task reports such a tap once to the permission service
+(:meth:`QuartzHotkeyBackend.report_if_deaf`, a "quit and reopen" hint, never an
+automatic restart).
Known trade-offs (documented, honest):
@@ -122,12 +136,63 @@ _MOUSE_BUTTON_TO_TOKEN: dict[int, str] = {
}
# How long a grant verdict stays good inside the event-tap callback. Short
-# enough that revoking Accessibility mid-session stops the shortcuts about as
+# enough that revoking Input Monitoring mid-session stops the shortcuts about as
# fast as a human can switch back from System Settings; long enough that
# ordinary typing does not re-probe TCC natively dozens of times a second.
# See :meth:`QuartzHotkeyBackend._permitted`.
_PERMISSION_TTL_S = 1.0
+# A live tap that has seen no raw event for this long while the system saw the
+# user type is "deaf" (created, but macOS delivers nothing; community-observed
+# after a grant given while the app was running, UNVERIFIED on a real Mac).
+_DEAF_TAP_AFTER_S = 10.0
+
+
+def _seconds_since_last_key_event() -> float | None:
+ """Seconds since the session last saw a key-down, or ``None`` when unknown.
+
+ Asked of the window server's idle counter, which does not depend on our tap
+ (so it can tell "the user typed, our tap heard nothing" from "nobody typed").
+ Whether this counter needs a TCC grant is UNVERIFIED; any failure reads
+ "unknown" and the caller then never claims a deaf tap.
+ """
+ try:
+ import Quartz # type: ignore[import-untyped] # noqa: PLC0415 - lazy (HN-7)
+
+ return float(
+ Quartz.CGEventSourceSecondsSinceLastEventType(
+ Quartz.kCGEventSourceStateCombinedSessionState,
+ Quartz.kCGEventKeyDown,
+ )
+ )
+ except Exception: # noqa: BLE001 - an unreadable idle counter is "unknown"
+ log.debug("Reading the key idle counter failed.", exc_info=True)
+ return None
+
+
+def _secure_event_input_enabled() -> bool | None:
+ """Whether Secure Event Input is on right now, or ``None`` when it cannot be read.
+
+ While it is on (a focused password field, Terminal's Secure Keyboard Entry)
+ the window server hides key events from every event tap, yet the idle counter
+ behind :func:`_seconds_since_last_key_event` still advances: a healthy tap
+ looks deaf. ``IsSecureEventInputEnabled`` is a Carbon HIToolbox call, read
+ through ctypes and lazily (AP-26). Its availability and behaviour are
+ UNVERIFIED on a real Mac; any failure reads "unknown" and the caller makes no
+ claim.
+ """
+ try:
+ import ctypes # noqa: PLC0415 - lazy: nothing native at import time (AP-26)
+
+ carbon = ctypes.cdll.LoadLibrary("/System/Library/Frameworks/Carbon.framework/Carbon")
+ probe = carbon.IsSecureEventInputEnabled
+ probe.restype = ctypes.c_ubyte
+ probe.argtypes = []
+ return bool(probe())
+ except Exception: # noqa: BLE001 - an unreadable flag is "unknown"
+ log.debug("Reading the secure-event-input flag failed.", exc_info=True)
+ return None
+
class QuartzHotkeyBackend:
"""Quartz event-tap hotkey backend for macOS (AD-8).
@@ -143,6 +208,27 @@ class QuartzHotkeyBackend:
self._got_event = False
self._held: set[str] = set()
self._permission_check = _macos_hotkey_permissions_granted
+ # Raw-callback liveness: how many events the tap callback has seen since
+ # the tap came up (any key, any bound chord or not), and when. Written
+ # only by the tap thread, read lock-free by status readers.
+ self._raw_events = 0
+ self._armed_at: float | None = None
+ # True once THIS tap was reported to the permission service as deaf
+ # (:meth:`report_if_deaf`); a new tap is a new episode.
+ self._deaf_reported = False
+ # True while a ``restart_hint`` episode this backend opened is still open.
+ # Unlike the flag above it survives ``start`` (a rearm): the episode ends when
+ # a tap actually hears an event, not when a new tap is built.
+ self._deaf_episode_open = False
+ self._seconds_since_last_key = _seconds_since_last_key_event
+ self._secure_input_enabled = _secure_event_input_enabled
+ # ``start`` and ``stop`` never overlap: a grant-driven ``start`` runs in a
+ # worker thread while the owner may already be tearing the backend down,
+ # and a ``start`` that lands after ``stop`` would leave an orphan tap.
+ self._lifecycle = threading.RLock()
+ # ``start()`` declined to create the tap because Input Monitoring is not
+ # granted (as opposed to "never started" or "failed").
+ self._waiting_for_permission = False
# Last grant verdict + when it was taken (see ``_permitted``). ``None``
# means "never probed", so the first event of a session always asks.
self._permission_cache: bool | None = None
@@ -213,14 +299,14 @@ class QuartzHotkeyBackend:
def _permitted(self) -> bool:
"""The grant verdict, re-probed at most every ``_PERMISSION_TTL_S``.
- The probe itself is deliberately uncached one level down
- (``permissions.py::_state``) so a revoked grant is seen live — but it
- is a native TCC call (``AXIsProcessTrusted`` + ``IOHIDCheckAccess``),
- and it used to run on EVERY reconcile. That put two ObjC round trips
- into the event-tap callback for every keystroke the machine sees —
- not just ours, since a session tap observes the whole system. Typing
- an ordinary sentence therefore fired dozens of native probes a second
- inside a callback macOS holds the input pipeline on.
+ The probe is the silent, lock-free ``PermissionService.check`` (never
+ ``ensure``, never a service lock, never a prompt) and it reads the live
+ TCC value one level down — but it is a native call, and it used to run
+ on EVERY reconcile. That put ObjC round trips into the event-tap
+ callback for every keystroke the machine sees — not just ours, since a
+ session tap observes the whole system. Typing an ordinary sentence
+ therefore fired dozens of native probes a second inside a callback
+ macOS holds the input pipeline on.
That is not merely slow, it is how the shortcuts go dead: a tap whose
callback overruns its deadline is DISABLED by the OS
@@ -322,10 +408,18 @@ class QuartzHotkeyBackend:
# ------------------------------------------------------------------
def start(self) -> None:
+ """Create the listen-only event tap (serialised with :meth:`stop`)."""
+ with self._lifecycle:
+ self._start_locked()
+
+ def _start_locked(self) -> None:
"""Create the listen-only event tap on its own CFRunLoop thread.
Degrades to a logged no-op on any failure — missing pyobjc/Quartz,
- missing permissions, or a tap-creation refusal (AD-6).
+ missing Input Monitoring, or a tap-creation refusal (AD-6). Without
+ Input Monitoring this is silent (INFO) and creates no tap at all: it
+ runs at boot, where nothing may ask or abort. It is idempotent, so the
+ permission listener simply calls it again once the grant arrives.
"""
if self._started:
return
@@ -341,16 +435,18 @@ class QuartzHotkeyBackend:
try:
granted = self._permission_check()
except Exception: # noqa: BLE001 — the probe must never crash the trigger
+ log.debug("The Input Monitoring probe failed.", exc_info=True)
granted = False
if granted is not True:
- log.warning(
- "Global hotkeys disabled on macOS: the Accessibility "
- "and Input Monitoring permissions are not both granted. "
- "Use Personal Jarvis > Settings > Permissions, then "
- "re-arm the shortcut or restart Jarvis — voice still "
- "works via the wake word.",
+ self._waiting_for_permission = True
+ log.info(
+ "Global shortcuts are waiting for Input Monitoring: macOS has "
+ "not allowed it for Personal Jarvis yet, so no event tap is "
+ "created. They arm themselves once it is allowed; voice still "
+ "works via the wake word and the buttons.",
)
return
+ self._waiting_for_permission = False
try:
import Quartz # type: ignore[import-untyped] # lazy (HN-7)
@@ -384,6 +480,13 @@ class QuartzHotkeyBackend:
def _callback(_proxy, event_type, event, _refcon):
try:
+ if event_type not in (
+ Quartz.kCGEventTapDisabledByTimeout,
+ Quartz.kCGEventTapDisabledByUserInput,
+ ):
+ # Raw liveness counter: ANY event the tap hears, bound or
+ # not. A plain int, written only by this thread.
+ self._raw_events += 1
if event_type == Quartz.kCGEventKeyDown:
keycode = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGKeyboardEventKeycode
@@ -434,14 +537,15 @@ class QuartzHotkeyBackend:
)
if tap is None:
raise RuntimeError(
- "CGEventTapCreate returned None (permission or session "
- "restriction)"
+ "CGEventTapCreate returned None (session restriction or "
+ "a grant macOS does not honour yet)"
)
source = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
except Exception: # noqa: BLE001 — degrade, never crash the pipeline
log.error(
- "Quartz event tap could not be created — hotkeys disabled for "
- "this session; voice still works via wake word.",
+ "Quartz event tap could not be created although Input "
+ "Monitoring is granted — hotkeys disabled for this session; "
+ "voice still works via wake word.",
exc_info=True,
)
self._tap = None
@@ -449,6 +553,9 @@ class QuartzHotkeyBackend:
self._tap = tap
self._source = source
+ self._raw_events = 0
+ self._deaf_reported = False
+ self._armed_at = None
ready = threading.Event()
startup_failed = threading.Event()
@@ -483,10 +590,19 @@ class QuartzHotkeyBackend:
)
self.stop()
return
+ self._armed_at = time.monotonic()
self._started = True
def stop(self) -> None:
- """Stop the run loop and drop the tap. Idempotent, never raises."""
+ """Stop the run loop and drop the tap. Idempotent, never raises.
+
+ Waits for a ``start`` that is already running, so the tap it creates is the
+ one this call tears down.
+ """
+ with self._lifecycle:
+ self._stop_locked()
+
+ def _stop_locked(self) -> None:
tap = self._tap
source = self._source
runloop = self._runloop
@@ -549,6 +665,7 @@ class QuartzHotkeyBackend:
self._thread = None
self._tap = None
self._source = None
+ self._armed_at = None
self._held.clear()
for combo in self._combos:
combo["down"] = False
@@ -564,8 +681,114 @@ class QuartzHotkeyBackend:
self._needs_mouse = False
def received_any_event(self) -> bool:
- """True once any bound chord has fired (AD-8 macOS permission hint)."""
+ """True once any bound chord has fired (kept for the backend contract).
+
+ Not a liveness signal: it only flips when a BOUND chord fires, so it
+ cannot tell a deaf tap from "the user has not pressed yet". Liveness is
+ :meth:`raw_event_count` / :meth:`deaf_tap_suspected`.
+ """
return self._got_event
+ # ------------------------------------------------------------------
+ # Readiness and liveness (read by the Esc pill and the shortcuts status)
+ # ------------------------------------------------------------------
+
+ def is_listening(self) -> bool:
+ """True while the event tap exists and its run loop thread is up."""
+ return self._started and self._tap is not None
+
+ @property
+ def waiting_for_permission(self) -> bool:
+ """``start()`` declined to create the tap: Input Monitoring is missing."""
+ return self._waiting_for_permission and not self.is_listening()
+
+ def raw_event_count(self) -> int:
+ """Events the tap callback has seen since the tap came up (any key)."""
+ return self._raw_events
+
+ def deaf_tap_suspected(self) -> bool:
+ """Is the tap alive but hearing nothing although the grant is visible?
+
+ The one signal behind a "quit and reopen" hint, and only that: it never
+ restarts anything. True when the tap is running, Input Monitoring reads
+ granted (without the grant the answer is "needs Input Monitoring", not
+ "restart"), the raw callback count is still 0, and the system saw a
+ key-down after the tap came up more than ``_DEAF_TAP_AFTER_S`` ago. A user
+ who has not typed yet never counts as a deaf tap, and neither does one
+ typing under Secure Event Input (macOS hides those keys from every tap),
+ so that flag must read as off. (An explicit "still not working" from the
+ user would need its own route and UI; none exists.)
+ """
+ if not self.is_listening() or self._raw_events > 0:
+ return False
+ try:
+ granted = self._permission_check() is True
+ except Exception: # noqa: BLE001 - an unreadable grant is "no claim"
+ log.debug("The Input Monitoring probe failed.", exc_info=True)
+ return False
+ if not granted:
+ return False
+ armed_at = self._armed_at
+ if armed_at is None:
+ return False
+ age = time.monotonic() - armed_at
+ if age < _DEAF_TAP_AFTER_S:
+ return False
+ # Under Secure Event Input the tap is meant to hear nothing, whatever the
+ # idle counter says; an unreadable flag makes no claim either.
+ if self._secure_input_enabled() is not False:
+ return False
+ idle = self._seconds_since_last_key()
+ return idle is not None and idle < age
+
+ def report_if_deaf(self) -> bool:
+ """One liveness pass for the owner's watch task: report a deaf tap, once.
+
+ When :meth:`deaf_tap_suspected` turns true (tap running, grant visible, zero
+ raw callbacks, Secure Event Input off, key activity seen) the permission
+ service is told ONCE per tap through ``report_failed_use``: that opens a
+ ``restart_hint`` episode, "quit and reopen" offered as a toast, and nothing
+ else. It never restarts the tap, never asks for anything and never reads
+ the OS while no tap runs (a boot with Input Monitoring missing costs a flag
+ check). If the tap hears an event after the report, the episode is ended
+ again. Blocking (native reads): run it in a worker thread, never on the
+ loop. Returns ``True`` while the tap is still worth watching, ``False`` once
+ it has proven healthy.
+ """
+ if not self.is_listening():
+ return True # not up yet (waiting for the grant): nothing to judge
+ if self._raw_events > 0:
+ if self._deaf_episode_open:
+ # Also true for an episode the PREVIOUS tap opened (a rearm builds a
+ # new tap): the first event a healthy tap hears ends the episode.
+ self._deaf_episode_open = False
+ self._call_service("note_reset")
+ self._deaf_reported = False
+ return False
+ if not self._deaf_reported and self.deaf_tap_suspected():
+ self._deaf_reported = True
+ self._deaf_episode_open = True
+ self._call_service("report_failed_use")
+ return True
+
+ def _call_service(self, name: str) -> None:
+ """Run one permission-service call about Input Monitoring; never raises."""
+ try:
+ from jarvis.platform.permission_service import ( # noqa: PLC0415 - lazy (AP-26)
+ get_permission_service,
+ )
+ from jarvis.platform.permissions import PermissionId # noqa: PLC0415
+
+ service = get_permission_service()
+ if name == "report_failed_use":
+ service.report_failed_use(PermissionId.INPUT_MONITORING, feature="global_shortcuts")
+ else:
+ service.note_reset(PermissionId.INPUT_MONITORING)
+ except Exception: # noqa: BLE001 - reporting a liveness hint never harms the tap
+ log.debug(
+ "Reporting the tap to the permission service failed (%s).", name,
+ exc_info=True,
+ )
+
__all__ = ["QuartzHotkeyBackend"]
diff --git a/jarvis/trigger/hotkey.py b/jarvis/trigger/hotkey.py
index 53332268a9..f5b812b6de 100644
--- a/jarvis/trigger/hotkey.py
+++ b/jarvis/trigger/hotkey.py
@@ -9,7 +9,10 @@ per-OS work lives in ``jarvis/trigger/backends/``:
(``backends/global_hotkeys.py`` — the ``_KEY_MAP``, the single-checker
refcount, the remove-by-string + pre-remove-on-reentry sequence — relocated
**verbatim** because each line carries a hard-won BUG fix, AD-7).
- * macOS / Linux-X11 use ``pynput`` (``backends/pynput.py``).
+ * macOS uses a listen-only Quartz event tap (``backends/quartz.py``), which
+ needs Input Monitoring only and is created lazily: the trigger re-arms it
+ when the permission service reports the grant (no restart, no second path).
+ * Linux-X11 uses ``pynput`` (``backends/pynput.py``).
* Wayland / no-hotkey hosts get ``backends/noop.py`` (logged-once no-op, AD-8).
The backend is chosen by ``make_hotkey_backend()`` from the shared
@@ -48,7 +51,7 @@ from __future__ import annotations
import asyncio
import logging
-from collections.abc import AsyncIterator, Iterator
+from collections.abc import AsyncIterator, Callable, Iterator
from dataclasses import dataclass
from typing import Any
@@ -70,6 +73,21 @@ from jarvis.trigger.backends.global_hotkeys import (
log = logging.getLogger(__name__)
+# How often a trigger whose backend waits for Input Monitoring renews its
+# background permission episode. The service closes an unresolved episode after
+# 10 minutes without calling any listener, and it tells a listener about a grant
+# only inside an open episode, so a grant given later than that would never
+# re-arm the shortcuts. Renewing well inside that window keeps the episode open
+# for as long as the backend waits (a cheap silent read, never a request).
+_EPISODE_RENEW_S = 240.0
+# How often the liveness watch asks a tap that exposes ``report_if_deaf`` whether
+# it looks deaf (a cheap flag check until a tap runs and the user types). Never
+# restarts anything: a deaf tap only produces a "quit and reopen" hint.
+_LIVENESS_POLL_S = 15.0
+# How long ``__aexit__`` waits for a grant-driven ``backend.start`` that is
+# already running in a worker thread (the tap handshake takes up to 5 s).
+_GRANT_TASK_JOIN_S = 6.0
+
def __getattr__(name: str):
"""Proxy the relocated refcount so ``hk._CHECKER_REFCOUNT`` reads live.
@@ -429,8 +447,8 @@ def mouse_hotkeys_available(platform: str | None = None) -> tuple[bool, str]:
* Windows — always: the backend polls ``GetAsyncKeyState``, which reports
mouse buttons alongside keys.
* macOS — needs pyobjc's ``Quartz`` (the event tap already exists; it just
- listens for mouse events too now) plus the Accessibility / Input
- Monitoring grants the backend already checks at ``start``.
+ listens for mouse events too now) plus the Input Monitoring grant the
+ backend waits for at ``start`` (a listen-only tap needs nothing else).
* Linux/X11 — needs ``pynput`` (the opt-in ``[desktop-linux]`` extra).
Wayland has no global button grabs at all, the same reason keyboard
shortcuts degrade there.
@@ -691,6 +709,15 @@ class HotkeyTrigger:
push_to_talk: frozenset[str] | set[str] = frozenset(),
) -> None:
self._bindings_cfg = bindings
+ # Grant-driven re-arm (backends that wait for a permission only).
+ self._unsubscribe_grant: Callable[[], None] | None = None
+ self._grant_task: asyncio.Task[None] | None = None
+ # Keeps the service's background episode open while the backend waits.
+ self._keepalive_task: asyncio.Task[None] | None = None
+ # Reports a tap that hears nothing although the grant is visible.
+ self._liveness_task: asyncio.Task[None] | None = None
+ # Set once ``__aexit__`` begins: no new grant re-arm may start after that.
+ self._closing = False
# Event names that should fire on BOTH key edges (push-to-talk): such
# a binding emits ``<name>_press`` on the down edge and
# ``<name>_release`` on the up edge, so the consumer can start
@@ -757,6 +784,40 @@ class HotkeyTrigger:
return _on_press
+ def listening(self) -> bool | None:
+ """Is the backend's OS listener actually running right now?
+
+ Three answers, like ``chord_is_down``: ``True`` / ``False`` when the
+ backend can say (the macOS event tap: ``False`` while Input Monitoring is
+ missing and no tap exists; the no-op backend and a failed backend
+ selection: ``False``, nothing listens), ``None`` when it cannot (Windows
+ poller, pynput, not entered yet). A consumer that must not promise a key
+ it does not hold (the "Esc to cancel" pill) treats only ``False`` as "no".
+ """
+ backend = self._backend
+ if backend is None:
+ # Entered but no backend (selection failed) or already left: nothing
+ # listens. Before ``__aenter__`` there is nothing to say yet.
+ return False if self._loop is not None else None
+ probe = getattr(backend, "is_listening", None)
+ if not callable(probe):
+ return None
+ try:
+ return bool(probe())
+ except Exception: # noqa: BLE001 — a failed probe is "unknown"
+ log.debug("is_listening() failed", exc_info=True)
+ return None
+
+ @property
+ def armed(self) -> bool:
+ """True only when the backend positively reports a running listener."""
+ return self.listening() is True
+
+ @property
+ def needs_input_monitoring(self) -> bool:
+ """The backend declined to start because Input Monitoring is not granted."""
+ return getattr(self._backend, "waiting_for_permission", False) is True
+
def chord_is_down(self, event_name: str) -> bool | None:
"""Is the chord bound to ``event_name`` physically down right now?
@@ -854,6 +915,7 @@ class HotkeyTrigger:
async def __aenter__(self) -> HotkeyTrigger:
self._loop = asyncio.get_running_loop()
+ self._closing = False
# Choose the per-OS backend (Windows global-hotkeys / pynput / no-op).
# The factory itself never raises (AD-6); a missing optional package is
@@ -890,6 +952,7 @@ class HotkeyTrigger:
self._backend = backend
self._registered = bindings
self._combo_strings = combo_strings
+ self._watch_for_grant(backend)
log.info(
"Hotkey-Trigger armed (%s): %s",
type(backend).__name__,
@@ -899,7 +962,182 @@ class HotkeyTrigger:
)
return self
+ # ------------------------------------------------------------------
+ # Grant-driven re-arm (a backend that waits for a permission: macOS tap)
+ # ------------------------------------------------------------------
+
+ def _watch_for_grant(self, backend: HotkeyBackend) -> None:
+ """Re-arm this trigger's backend when Input Monitoring gets granted.
+
+ Only a backend that can wait for the permission (it exposes
+ ``waiting_for_permission``) takes part; Windows, Linux and the no-op
+ backend never touch the permission service. While the backend waits we
+ open a BACKGROUND episode (``interactive=False``: no native request, no
+ toast, status snapshot only) because the service tells its listeners about
+ a grant only inside an open episode. Never raises.
+ """
+ if not hasattr(backend, "waiting_for_permission"):
+ return
+ self._start_liveness_watch(backend)
+ try:
+ from jarvis.platform.permission_service import ( # noqa: PLC0415
+ get_permission_service,
+ )
+ from jarvis.platform.permissions import PermissionId # noqa: PLC0415
+
+ service = get_permission_service()
+ if self._unsubscribe_grant is None:
+ self._unsubscribe_grant = service.add_listener(
+ PermissionId.INPUT_MONITORING, self._on_input_monitoring_granted
+ )
+ if self.needs_input_monitoring:
+ service.ensure(
+ PermissionId.INPUT_MONITORING,
+ feature="global_shortcuts",
+ interactive=False,
+ )
+ self._start_episode_keepalive()
+ except Exception: # noqa: BLE001 — shortcuts must never take voice down
+ log.debug("Watching for the Input Monitoring grant failed.", exc_info=True)
+
+ def _start_liveness_watch(self, backend: HotkeyBackend) -> None:
+ """Watch a backend that can report a deaf tap (one task at most)."""
+ task = self._liveness_task
+ loop = self._loop
+ if (
+ not callable(getattr(backend, "report_if_deaf", None))
+ or (task is not None and not task.done())
+ or loop is None
+ or loop.is_closed()
+ ):
+ return
+ self._liveness_task = loop.create_task(
+ self._watch_liveness(backend), name="hotkey-liveness-watch"
+ )
+
+ async def _watch_liveness(self, backend: HotkeyBackend) -> None:
+ """Ask the backend every ``_LIVENESS_POLL_S`` whether its tap is deaf.
+
+ The backend tells the permission service ONCE per tap (a ``restart_hint``
+ episode) and ends the episode again if the tap starts hearing events; this
+ loop only gives it a worker thread and a clock. It ends when the backend
+ says the tap has proven healthy, or with the trigger. AP-18: nothing escapes.
+ """
+ try:
+ while True:
+ await asyncio.sleep(_LIVENESS_POLL_S)
+ if self._closing or self._backend is not backend:
+ return
+ if not await asyncio.to_thread(backend.report_if_deaf):
+ return
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — a lost liveness pass only delays a hint, never voice
+ log.debug("The hotkey liveness watch failed.", exc_info=True)
+
+ def _start_episode_keepalive(self) -> None:
+ """Renew the background episode while the backend waits (one task at most)."""
+ task = self._keepalive_task
+ loop = self._loop
+ if (task is not None and not task.done()) or loop is None or loop.is_closed():
+ return
+ self._keepalive_task = loop.create_task(
+ self._keep_episode_open(), name="hotkey-episode-keepalive"
+ )
+
+ async def _keep_episode_open(self) -> None:
+ """Re-touch the service episode every ``_EPISODE_RENEW_S`` while the backend waits.
+
+ ``service.ensure(interactive=False)`` blocks on a native read, so it runs
+ in a worker thread. It makes no request and shows no toast; it only keeps
+ the episode (and with it the grant listener) alive past the service's
+ own expiry. Ends once the backend no longer waits. AP-18: nothing escapes.
+ """
+ try:
+ from jarvis.platform.permission_service import ( # noqa: PLC0415
+ get_permission_service,
+ )
+ from jarvis.platform.permissions import PermissionId # noqa: PLC0415
+
+ while True:
+ await asyncio.sleep(_EPISODE_RENEW_S)
+ if self._backend is None or not self.needs_input_monitoring:
+ return
+ await asyncio.to_thread(
+ get_permission_service().ensure,
+ PermissionId.INPUT_MONITORING,
+ feature="global_shortcuts",
+ interactive=False,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — a lost renewal only delays the re-arm, never voice
+ log.debug("Renewing the Input Monitoring episode failed.", exc_info=True)
+
+ def _on_input_monitoring_granted(self) -> None:
+ """Permission-service listener: cheap, never raises, hops onto our loop."""
+ loop = self._loop
+ if loop is None or loop.is_closed():
+ return
+ try:
+ loop.call_soon_threadsafe(self._spawn_grant_rearm)
+ except RuntimeError:
+ log.debug("The loop closed before the shortcut re-arm could be scheduled.")
+
+ def _spawn_grant_rearm(self) -> None:
+ task = self._grant_task
+ if task is not None and not task.done():
+ return # one re-arm in flight is enough
+ loop = self._loop
+ if self._closing or self._backend is None or loop is None or loop.is_closed():
+ return
+ self._grant_task = loop.create_task(self._rearm_after_grant(), name="hotkey-grant-rearm")
+
+ async def _rearm_after_grant(self) -> None:
+ """Start the waiting backend off the loop once Input Monitoring is granted.
+
+ The backend already holds the bindings, so ``backend.start`` creating the tap is
+ the whole re-arm (a pipeline reload would only register the same bindings again).
+ ``backend.start`` is idempotent and blocks for the tap thread handshake,
+ so it runs in a worker thread. AP-18: nothing escapes this task.
+ """
+ backend = self._backend
+ if backend is None:
+ return
+ try:
+ await asyncio.to_thread(backend.start)
+ log.info(
+ "Input Monitoring was allowed — global shortcuts %s.",
+ "are armed" if self.listening() is not False else "could not be armed yet",
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — a failed re-arm leaves shortcuts off, never voice
+ log.error(
+ "Re-arming the global shortcuts after the grant failed — they stay off "
+ "until the next restart; voice still works via wake word / mascot click.",
+ exc_info=True,
+ )
+
async def __aexit__(self, *exc_info) -> None:
+ self._closing = True
+ unsubscribe, self._unsubscribe_grant = self._unsubscribe_grant, None
+ if unsubscribe is not None:
+ unsubscribe()
+ keepalive, self._keepalive_task = self._keepalive_task, None
+ if keepalive is not None and not keepalive.done():
+ keepalive.cancel()
+ liveness, self._liveness_task = self._liveness_task, None
+ if liveness is not None and not liveness.done():
+ liveness.cancel()
+ task, self._grant_task = self._grant_task, None
+ if task is not None and not task.done():
+ # Cancelling the task would NOT stop the worker thread already inside
+ # ``backend.start``: that start would finish after ``stop`` below and
+ # leave a live tap on a backend nobody owns. Let it finish first.
+ await asyncio.wait({task}, timeout=_GRANT_TASK_JOIN_S)
+ if not task.done():
+ task.cancel()
backend = self._backend
if backend is None:
return # never created (degraded) — nothing to tear down
@@ -939,6 +1177,11 @@ class HotkeyTrigger:
return # entered degraded (no package) — nothing to re-arm
new_bindings, combo_strings = self._build_bindings()
+ grant_task = self._grant_task
+ if grant_task is not None and not grant_task.done():
+ # A grant-driven start is in a worker thread: let it finish before the
+ # backend is torn down under it.
+ await asyncio.wait({grant_task}, timeout=6.0)
try:
backend.stop()
backend.unregister()
@@ -956,6 +1199,7 @@ class HotkeyTrigger:
backend.start()
self._registered = new_bindings
self._combo_strings = combo_strings
+ self._watch_for_grant(backend)
log.info(
"🔁 Hotkey-Live-Reload — re-armed: %s",
", ".join(
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index e7c5077e08..fbf2d6aa6e 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -175,25 +175,63 @@ def boot_overlay_style(configured: str | None, *, instance: Any | None = None) -
return configured if identity.owns_ambient_duties else "none"
+def _local_voice_microphone_state(
+ platform_name: str | None, permission_gate: Any | None
+) -> Any | None:
+ """The silent microphone state, or ``None`` off macOS (nothing to ask there)."""
+ if (platform_name or sys.platform) != "darwin":
+ return None
+ from jarvis.platform.permission_service import get_permission_service
+ from jarvis.platform.permissions import PermissionId
+
+ gate = permission_gate or get_permission_service()
+ return gate.check(PermissionId.MICROPHONE)
+
+
def _local_voice_permission_granted(
*,
platform_name: str | None = None,
- permission_port: Any | None = None,
+ permission_gate: Any | None = None,
) -> bool:
- """Return whether local voice may touch the microphone on this host."""
- platform_name = platform_name or sys.platform
- if platform_name != "darwin":
+ """Whether BACKGROUND voice (wake word, barge-in) may open the microphone.
+
+ True only for a live GRANT. Silent: it reads the state through the permission
+ service, never asks and never opens the device, so a fresh Mac boots with no
+ dialog and the wake loop simply waits (see ``SpeechPipeline._wake_loop``).
+ """
+ try:
+ state = _local_voice_microphone_state(platform_name, permission_gate)
+ except Exception: # noqa: BLE001 - background capture must fail closed
+ logging.getLogger(__name__).debug(
+ "The silent microphone read failed; background voice stays closed.", exc_info=True
+ )
+ return False
+ if state is None:
return True
- from jarvis.platform.permissions import (
- PermissionId,
- get_system_permission_port,
- )
+ return str(getattr(state, "value", state)) in ("granted", "not_required")
- port = permission_port or get_system_permission_port()
+
+def _local_voice_permission_usable(
+ *,
+ platform_name: str | None = None,
+ permission_gate: Any | None = None,
+) -> bool:
+ """Whether a USER gesture (push-to-talk, a voice session, dictation) may try the microphone.
+
+ True unless the state is denied, restricted or unavailable: an undecided
+ microphone is still usable because the gesture itself is what asks. Silent,
+ never asks; the gesture entry points call the service ``ensure`` themselves.
+ """
try:
- return bool(port.runtime_access_granted(PermissionId.MICROPHONE))
- except Exception: # noqa: BLE001 - protected capture must fail closed
+ state = _local_voice_microphone_state(platform_name, permission_gate)
+ except Exception: # noqa: BLE001 - an unreadable state must not open the device
+ logging.getLogger(__name__).debug(
+ "The silent microphone read failed; user capture stays closed.", exc_info=True
+ )
return False
+ if state is None:
+ return True
+ return str(getattr(state, "value", state)) not in ("denied", "restricted", "unavailable")
def _supported_call_kwargs(
@@ -2013,6 +2051,15 @@ class DesktopApp:
self._server = server
_db_mark("webserver_ctor")
+ # Just-in-time permissions: hand the service the bus and this loop BEFORE
+ # the speech task below can ask for the microphone. WebServer.start() does
+ # the same on its first line, but it runs behind the wake-model gate, i.e.
+ # AFTER _start_speech_and_orb. Two references are stored, nothing is probed
+ # and no OS dialog can follow from here (AP-26; design 3.6).
+ from jarvis.platform.permission_service import attach_bus as _attach_permission_bus
+
+ _attach_permission_bus(server.bus, loop)
+
# Hang the core state off the loop — thread-local, referenced only here.
supervisor = Supervisor(bus=server.bus)
# Persist text chats to data/chats.db (next to sessions.db) so the Chats
@@ -4052,30 +4099,27 @@ class DesktopApp:
logger.info("Voice stack disabled via JARVIS_VOICE=0.")
return
- # macOS must never discover microphone permission by opening the device:
- # that would throw an unmanaged TCC prompt before the guided onboarding
- # step. Keep the pipeline alive but its activation gate closed until the
- # user explicitly grants access. The probe is native and uncached, so a
- # grant (or later revocation) applies without restarting the process.
- permission_port: Any | None = None
- if sys.platform == "darwin":
- from jarvis.platform.permissions import get_system_permission_port
-
- permission_port = get_system_permission_port()
-
+ # Nothing here asks macOS for the microphone: boot never shows a dialog and
+ # never opens an input stream. Two SILENT predicates tell the pipeline
+ # what a read of the permission service says right now: background voice
+ # (the wake word, barge-in) needs a live GRANT; a user gesture (push-to-talk,
+ # a voice session, dictation) only needs the microphone not to be refused,
+ # because the gesture itself is what asks (see ``SpeechPipeline``). Both
+ # read the live state, so a grant applies without restarting the process.
def voice_activation_gate() -> bool:
- return _local_voice_permission_granted(
- platform_name=sys.platform,
- permission_port=permission_port,
- )
+ return _local_voice_permission_granted(platform_name=sys.platform)
+
+ def voice_user_gate() -> bool:
+ return _local_voice_permission_usable(platform_name=sys.platform)
if sys.platform == "darwin":
if not voice_activation_gate():
from loguru import logger
logger.info(
- "Voice activation is parked until Microphone access is "
- "granted from the in-app macOS permission guide."
+ "Wake listening waits for Microphone access; the first voice "
+ "action (a shortcut, the speak button, switching the wake word "
+ "on) asks for it."
)
# On-screen overlay in its own Tk daemon thread — the bus bridge reacts
@@ -4528,6 +4572,7 @@ class DesktopApp:
config=self.cfg,
vision_provider=voice_vision,
activation_gate=voice_activation_gate,
+ user_activation_gate=voice_user_gate,
ack_brain=voice_ack_brain,
# Resolved custom-wake-word plan: drives the OWW model + the
# phrase matcher for the verifier + rolling-whisper.
diff --git a/jarvis/ui/web/frontend/src/App.detached.test.tsx b/jarvis/ui/web/frontend/src/App.detached.test.tsx
index da7ba1dd3e..4b5a4493cd 100644
--- a/jarvis/ui/web/frontend/src/App.detached.test.tsx
+++ b/jarvis/ui/web/frontend/src/App.detached.test.tsx
@@ -42,9 +42,6 @@ vi.mock("@/components/layout/TopBar", () => ({
vi.mock("@/components/layout/MainView", () => ({
MainView: () => <div data-testid="main-view" />,
}));
-vi.mock("@/components/layout/PermissionsAlertBanner", () => ({
- PermissionsAlertBanner: () => null,
-}));
vi.mock("@/components/layout/InputIsolationBanner", () => ({
InputIsolationBanner: () => null,
}));
diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsx
index a3d5be31de..ee2571fefe 100644
--- a/jarvis/ui/web/frontend/src/App.tsx
+++ b/jarvis/ui/web/frontend/src/App.tsx
@@ -20,7 +20,6 @@ import {
import { PaneResizer } from "@/components/layout/PaneResizer";
import { useResizablePane } from "@/hooks/useResizablePane";
import { TopBar } from "@/components/layout/TopBar";
-import { PermissionsAlertBanner } from "@/components/layout/PermissionsAlertBanner";
import { ReadyCelebration } from "@/components/ReadyCelebration";
import { InputIsolationBanner } from "@/components/layout/InputIsolationBanner";
import { VoiceWarmingBanner } from "@/components/layout/VoiceWarmingBanner";
@@ -400,13 +399,9 @@ export default function App() {
top-left corner so this gray shows in the curve. */}
<div className="h-8 shrink-0" data-testid="caption-rule" />
<div className={activeSection === "agents" ? "flex min-h-0 min-w-0 flex-1 flex-col" : "jarvis-sheet flex min-h-0 min-w-0 flex-1 flex-col"}>
- {/* App-wide macOS permission alert — topmost so a missing grant is
- impossible to miss on any view. No-op on other platforms. */}
- <PermissionsAlertBanner />
{/* Outside input software (dictation, text expanders, auto-type) cannot
- reach an elevated window. Sits next to the permission alert because
- it is the same class of problem: an OS-level gate the user must be
- told about, since nothing else reports it. */}
+ reach an elevated window: an OS-level gate the user must be told
+ about, since nothing else reports it. */}
<InputIsolationBanner />
<TopBar navToggle={navToggle} />
{!(["agentic-ide", "chat-workspace", "agentic-ide-classic"].includes(activeSection)) && <VoiceWarmingBanner />}
diff --git a/jarvis/ui/web/frontend/src/components/ToastLayer.test.tsx b/jarvis/ui/web/frontend/src/components/ToastLayer.test.tsx
new file mode 100644
index 0000000000..2750056e9b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ToastLayer.test.tsx
@@ -0,0 +1,139 @@
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useI18nStore } from "@/i18n";
+import { useEventStore } from "@/store/events";
+import { ToastLayer } from "./ToastLayer";
+
+beforeEach(() => {
+ useI18nStore.getState().setUi("en", { push: false });
+ useEventStore.setState({ toasts: [] });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+describe("ToastLayer", () => {
+ it("shows a plain toast without a button", () => {
+ render(<ToastLayer />);
+ act(() => useEventStore.getState().pushToast("info", "Saved"));
+
+ expect(screen.getByText("Saved")).toBeTruthy();
+ expect(screen.queryByTestId("toast-action")).toBeNull();
+ });
+
+ it("shows the one button of a toast, runs it, and closes the toast", () => {
+ const onAction = vi.fn();
+ render(<ToastLayer />);
+ act(() =>
+ useEventStore.getState().pushToast("warning", "Personal Jarvis needs microphone access to hear you.", {
+ action: { label: "Open System Settings", onAction },
+ }),
+ );
+
+ const button = screen.getByRole("button", { name: "Open System Settings" });
+ fireEvent.click(button);
+
+ expect(onAction).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText("Personal Jarvis needs microphone access to hear you.")).toBeNull();
+ });
+
+ it("keeps the toast up after a button that asked to stay (a retry)", () => {
+ const onAction = vi.fn();
+ render(<ToastLayer />);
+ act(() =>
+ useEventStore.getState().pushToast("warning", "Needs a restart", {
+ action: { label: "Quit and reopen", onAction, keepOpen: true },
+ }),
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Quit and reopen" }));
+
+ expect(onAction).toHaveBeenCalledTimes(1);
+ expect(screen.getByText("Needs a restart")).toBeTruthy();
+ });
+
+ it("closes with the X like every other toast", () => {
+ render(<ToastLayer />);
+ act(() =>
+ useEventStore.getState().pushToast("info", "Needs access", {
+ action: { label: "Open System Settings", onAction: vi.fn() },
+ }),
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
+
+ expect(screen.queryByText("Needs access")).toBeNull();
+ });
+
+ it("the button sits in the same toast box as the message (one box, not a second layer)", () => {
+ render(<ToastLayer />);
+ act(() =>
+ useEventStore.getState().pushToast("info", "Needs access", {
+ action: { label: "Open System Settings", onAction: vi.fn() },
+ }),
+ );
+
+ const box = screen.getByRole("status");
+ expect(box.contains(screen.getByTestId("toast-action"))).toBe(true);
+ expect(screen.getAllByRole("status")).toHaveLength(1);
+ });
+});
+
+describe("ToastLayer placement", () => {
+ it("renders into <body>, so it can sit above the setup spotlight (also a body-level portal)", () => {
+ const { container } = render(<ToastLayer />);
+ act(() => useEventStore.getState().pushToast("info", "Saved"));
+
+ expect(container.querySelector("[role=status]")).toBeNull();
+ expect(document.body.querySelector(":scope > div.fixed.z-\\[115\\] [role=status]")).not.toBeNull();
+ });
+});
+
+describe("pushToast with an action and a lifetime", () => {
+ it("keeps a toast with a button up for its own ttl, not the 3.5 s default", () => {
+ vi.useFakeTimers();
+ act(() =>
+ useEventStore.getState().pushToast("info", "Needs access", {
+ action: { label: "Go", onAction: vi.fn() },
+ ttlMs: 20_000,
+ }),
+ );
+
+ act(() => void vi.advanceTimersByTime(19_000));
+ expect(useEventStore.getState().toasts).toHaveLength(1);
+ act(() => void vi.advanceTimersByTime(1_500));
+ expect(useEventStore.getState().toasts).toEqual([]);
+ });
+
+ it("a plain toast still goes away after the default lifetime", () => {
+ vi.useFakeTimers();
+ act(() => useEventStore.getState().pushToast("info", "Saved"));
+
+ act(() => void vi.advanceTimersByTime(3_600));
+
+ expect(useEventStore.getState().toasts).toEqual([]);
+ });
+
+ it("collapses a repeat of the same sentence and button into one toast", () => {
+ const action = { label: "Go", onAction: vi.fn() };
+ act(() => {
+ useEventStore.getState().pushToast("info", "Needs access", { action });
+ useEventStore.getState().pushToast("info", "Needs access", { action });
+ });
+
+ expect(useEventStore.getState().toasts).toHaveLength(1);
+ expect(useEventStore.getState().toasts[0].count).toBe(2);
+ });
+
+ it("keeps the same sentence with another button as another toast", () => {
+ act(() => {
+ useEventStore.getState().pushToast("info", "Needs access", { action: { label: "Go", onAction: vi.fn() } });
+ useEventStore.getState().pushToast("info", "Needs access", { action: { label: "Stay", onAction: vi.fn() } });
+ });
+
+ expect(useEventStore.getState().toasts).toHaveLength(2);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ToastLayer.tsx b/jarvis/ui/web/frontend/src/components/ToastLayer.tsx
index 29a4e7ed14..ec9dbf3df4 100644
--- a/jarvis/ui/web/frontend/src/components/ToastLayer.tsx
+++ b/jarvis/ui/web/frontend/src/components/ToastLayer.tsx
@@ -1,3 +1,4 @@
+import { createPortal } from "react-dom";
import {
X,
Info,
@@ -40,13 +41,16 @@ export function ToastLayer() {
const toasts = useEventStore((s) => s.toasts);
const dismiss = useEventStore((s) => s.dismissToast);
- return (
- // z-[60]: the onboarding gate overlays the whole app at z-50 and renders
- // later in the DOM; toasts (e.g. failed permission requests during
- // first-run setup) must stay visible above it.
+ return createPortal(
+ // z-[115]: above the first-run setup spotlight (z-110), whose scrim takes
+ // every click outside its hole: a toast with a button ("Open System
+ // Settings" after the wake-word switch asked for the microphone) must stay
+ // clickable there. Below the caption bar (z-120), which is every window's
+ // title bar. A portal to <body> because the spotlight is one too: inside the
+ // shell root (an isolated stacking context) no z-index could outrank it.
// top-12: below the caption strip — at the top edge a toast covered the
// restart and window buttons whose outcome it reports.
- <div className="pointer-events-none fixed right-4 top-12 z-[60] flex w-[320px] flex-col gap-2">
+ <div className="pointer-events-none fixed right-4 top-12 z-[115] flex w-[320px] flex-col gap-2">
{toasts.map((toast) => {
const Icon = ICON_FOR_KIND[toast.kind];
// A saved-file toast in the desktop shell is a native drag handle: press
@@ -108,6 +112,7 @@ export function ToastLayer() {
{toast.filePath && (
<FileToastActions path={toast.filePath} />
)}
+ {toast.action && <ToastActionButton toast={toast} onDone={() => dismiss(toast.id)} />}
</div>
<button
type="button"
@@ -122,6 +127,32 @@ export function ToastLayer() {
</div>
);
})}
+ </div>,
+ document.body,
+ );
+}
+
+/**
+ * The one button a toast may carry (`pushToast(..., { action })`), in the same
+ * look as the saved-file buttons below. Runs the action, then closes the toast
+ * unless the action asked to stay (a retry).
+ */
+function ToastActionButton({ toast, onDone }: { toast: Toast; onDone: () => void }) {
+ const action = toast.action;
+ if (!action) return null;
+ return (
+ <div className="mt-2 flex flex-wrap gap-1.5" onMouseDown={(e) => e.stopPropagation()}>
+ <button
+ type="button"
+ data-testid="toast-action"
+ onClick={() => {
+ void action.onAction();
+ if (!action.keepOpen) onDone();
+ }}
+ className="inline-flex items-center rounded-md border border-primary/40 bg-primary/10 px-2 py-1 text-xs font-medium text-primary transition-colors hover:bg-primary/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {action.label}
+ </button>
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsx b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsx
deleted file mode 100644
index d9b6b99129..0000000000
--- a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsx
+++ /dev/null
@@ -1,233 +0,0 @@
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import type { PermissionSnapshot } from "@/hooks/usePermissions";
-
-const request = vi.fn();
-const openSettings = vi.fn();
-const reset = vi.fn();
-
-let mockSnapshot: PermissionSnapshot | null = null;
-
-vi.mock("@/i18n", () => ({
- useT: () => (key: string) => key,
-}));
-
-vi.mock("@/store/events", () => ({
- useEventStore: (selector: (state: { pushToast: ReturnType<typeof vi.fn> }) => unknown) =>
- selector({ pushToast: vi.fn() }),
-}));
-
-vi.mock("@/hooks/usePermissions", () => ({
- usePermissions: () => ({
- snapshot: mockSnapshot,
- loading: false,
- error: null,
- pendingId: null,
- refetch: vi.fn(),
- request,
- openSettings,
- reset,
- setupAll: vi.fn().mockResolvedValue("complete"),
- cancelSetup: vi.fn(),
- setupProgress: null,
- setupNeeded: false,
- }),
-}));
-
-import { PermissionsAlertBanner } from "./PermissionsAlertBanner";
-
-function darwinSnapshot(overrides: Partial<PermissionSnapshot> = {}): PermissionSnapshot {
- return {
- platform: "darwin",
- supported: true,
- headless: false,
- app_identity: { stable: true },
- permissions: [
- {
- id: "microphone",
- status: "denied",
- required: ["voice"],
- can_request: false,
- can_open_settings: true,
- can_reset: false,
- restart_required: false,
- },
- ],
- features: { voice: { ready: false, missing: ["microphone"] } },
- restart_required: false,
- ...overrides,
- };
-}
-
-afterEach(() => {
- cleanup();
- vi.clearAllMocks();
- mockSnapshot = null;
-});
-
-describe("PermissionsAlertBanner", () => {
- it("shows a blocked permission with its System Settings deep link", () => {
- mockSnapshot = darwinSnapshot();
- render(<PermissionsAlertBanner />);
-
- expect(screen.getByTestId("permissions-alert-banner")).toBeDefined();
- expect(screen.getByText("permissions.banner.title")).toBeDefined();
- // The broken-feature summary line is rendered from snapshot.features.
- expect(screen.getByText("permissions.banner.impact")).toBeDefined();
-
- fireEvent.click(screen.getByRole("button", { name: "permissions.open_settings" }));
- expect(openSettings).toHaveBeenCalledWith("microphone");
- });
-
- it("offers the native prompt when the backend says a request can run", () => {
- mockSnapshot = darwinSnapshot({
- permissions: [
- {
- id: "microphone",
- status: "not_determined",
- required: ["voice"],
- can_request: true,
- can_open_settings: true,
- can_reset: false,
- restart_required: false,
- },
- ],
- });
- render(<PermissionsAlertBanner />);
-
- fireEvent.click(screen.getByRole("button", { name: "permissions.request" }));
- expect(request).toHaveBeenCalledWith("microphone");
- });
-
- it("collapses to the headline but never disappears while something is missing", () => {
- mockSnapshot = darwinSnapshot();
- render(<PermissionsAlertBanner />);
-
- fireEvent.click(screen.getByRole("button", { name: /permissions.banner.collapse/ }));
-
- expect(screen.getByText("permissions.banner.title")).toBeDefined();
- expect(screen.queryByText("permissions.items.microphone.title")).toBeNull();
- });
-
- it("shows only the restart call-to-action once everything is granted", () => {
- mockSnapshot = darwinSnapshot({
- permissions: [
- {
- id: "screen_recording",
- status: "granted",
- required: ["computer_use"],
- can_request: false,
- can_open_settings: true,
- can_reset: false,
- restart_required: true,
- },
- ],
- features: {
- computer_use: { ready: false, missing: [] },
- },
- restart_required: true,
- });
- render(<PermissionsAlertBanner />);
-
- const banner = screen.getByTestId("permissions-alert-banner");
- expect(banner.getAttribute("data-state")).toBe("restart");
- expect(screen.getByRole("button", { name: "permissions.restart_now" })).toBeDefined();
- });
-
- it("labels a restart-pending screen recording honestly instead of the frozen state", () => {
- // CGPreflightScreenCaptureAccess is frozen per process: after granting in
- // System Settings the probe still reports not_granted until relaunch. The
- // stale label plus a dead Allow button was the live 2026-07-18 Mac finding.
- mockSnapshot = darwinSnapshot({
- permissions: [
- {
- id: "screen_recording",
- status: "not_granted",
- required: ["computer_use"],
- can_request: false,
- can_open_settings: true,
- can_reset: false,
- restart_required: true,
- },
- ],
- features: { computer_use: { ready: false, missing: ["screen_recording"] } },
- restart_required: true,
- });
- render(<PermissionsAlertBanner />);
-
- expect(screen.getByText("permissions.status.restart_pending")).toBeDefined();
- expect(screen.queryByText("permissions.status.not_granted")).toBeNull();
- expect(screen.queryByRole("button", { name: "permissions.request" })).toBeNull();
- });
-
- it("renders nothing on other platforms", () => {
- mockSnapshot = darwinSnapshot({ platform: "win32" });
- render(<PermissionsAlertBanner />);
- expect(screen.queryByTestId("permissions-alert-banner")).toBeNull();
- });
-
- it("renders nothing while the snapshot has not loaded", () => {
- mockSnapshot = null;
- render(<PermissionsAlertBanner />);
- expect(screen.queryByTestId("permissions-alert-banner")).toBeNull();
- });
-
- it("renders nothing when every required permission is settled", () => {
- mockSnapshot = darwinSnapshot({
- permissions: [
- {
- id: "microphone",
- status: "granted",
- required: ["voice"],
- can_request: false,
- can_open_settings: true,
- can_reset: false,
- restart_required: false,
- },
- ],
- features: { voice: { ready: true, missing: [] } },
- });
- render(<PermissionsAlertBanner />);
- expect(screen.queryByTestId("permissions-alert-banner")).toBeNull();
- });
-
- it("renders nothing on a headless install (no desktop session to grant from)", () => {
- mockSnapshot = darwinSnapshot({ headless: true });
- render(<PermissionsAlertBanner />);
- expect(screen.queryByTestId("permissions-alert-banner")).toBeNull();
- });
-
- it("offers the reset for a stranded grant that never reads 'denied' (BUG-159)", () => {
- // Screen Recording's preflight reports an orphaned TCC row as plain
- // "not_granted" while System Settings still shows the checkmark. The
- // banner used to carry no reset at all, so this row was a dead end.
- mockSnapshot = darwinSnapshot({
- permissions: [
- {
- id: "screen_recording",
- status: "not_granted",
- required: ["computer_use"],
- can_request: false,
- can_open_settings: true,
- can_reset: true,
- restart_required: false,
- },
- ],
- features: { computer_use: { ready: false, missing: ["screen_recording"] } },
- });
- render(<PermissionsAlertBanner />);
-
- expect(screen.getByText("permissions.stale_grant_hint")).toBeDefined();
- fireEvent.click(screen.getByRole("button", { name: "permissions.ask_again" }));
- expect(reset).toHaveBeenCalledWith("screen_recording");
- });
-
- it("explains a signature change instead of looking amnesic", () => {
- mockSnapshot = darwinSnapshot({
- identity_reset: { reason: "signature-change", services: ["ScreenCapture"] },
- });
- render(<PermissionsAlertBanner />);
-
- expect(screen.getByText("permissions.identity_reset")).toBeDefined();
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx
deleted file mode 100644
index b216f20356..0000000000
--- a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx
+++ /dev/null
@@ -1,314 +0,0 @@
-import { useState } from "react";
-import {
- Accessibility,
- ChevronDown,
- ChevronUp,
- Keyboard,
- KeyRound,
- Loader2,
- Mic,
- Monitor,
- MousePointer2,
- Music,
- ShieldAlert,
- Wand2,
-} from "lucide-react";
-import { clsx } from "clsx";
-
-import { Button } from "@/components/ui/button";
-import { useT } from "@/i18n";
-import { useEventStore } from "@/store/events";
-import {
- usePermissions,
- type PermissionId,
- type PermissionItem,
-} from "@/hooks/usePermissions";
-import { SetupAllControl } from "@/views/settings/PermissionsPanel";
-
-const ICONS = {
- microphone: Mic,
- screen_recording: Monitor,
- accessibility: Accessibility,
- input_monitoring: Keyboard,
- event_posting: MousePointer2,
- automation: Music,
- credential_store: KeyRound,
-} satisfies Record<PermissionId, typeof Mic>;
-
-// Mirrors the "waiting for System Settings" logic inside usePermissions: a
-// permission only blocks features when some feature requires it AND its state
-// is neither granted, exempt, nor unknowable on this installation.
-const SETTLED_STATES = new Set(["granted", "not_required", "unavailable"]);
-
-function isBlocking(item: PermissionItem): boolean {
- return item.required.length > 0 && !SETTLED_STATES.has(item.status);
-}
-
-/**
- * Fat, app-wide macOS permission alert.
- *
- * macOS TCC permissions cannot be granted at install time — only the user can
- * approve them, in the OS prompt or in System Settings. When a required grant
- * is missing, the affected features (wake word, voice, Computer-Use, …) fail
- * silently and read as "the app is broken" (real field bug: wake word dead
- * because Microphone access was never granted, and only the Settings panel
- * knew). This banner sits above every view, names exactly what is broken, and
- * deep-links each grant to its System Settings pane.
- *
- * Renders nothing on Windows/Linux and on headless installs (no desktop
- * session to grant from), so it is a quiet no-op everywhere but a macOS
- * desktop with work left to do.
- */
-export function PermissionsAlertBanner() {
- const t = useT();
- const pushToast = useEventStore((state) => state.pushToast);
- const [collapsed, setCollapsed] = useState(false);
- const [restarting, setRestarting] = useState(false);
- const {
- snapshot,
- pendingId,
- request,
- openSettings,
- reset,
- setupAll,
- cancelSetup,
- setupProgress,
- setupNeeded,
- } = usePermissions();
-
- if (!snapshot || snapshot.platform !== "darwin" || snapshot.headless) return null;
-
- const missing = snapshot.permissions.filter(isBlocking);
- if (missing.length === 0 && !snapshot.restart_required) return null;
-
- // Everything is granted, the OS just needs a fresh process to hand the new
- // access to. Collapse the whole banner into a single restart call-to-action.
- const restartOnly = missing.length === 0;
-
- const brokenFeatures = Object.entries(snapshot.features)
- .filter(([, feature]) => !feature.ready)
- .map(([key]) => t(`permissions.features.${key}`));
-
- async function run(action: () => Promise<void>) {
- try {
- await action();
- } catch (exc) {
- pushToast("error", exc instanceof Error ? exc.message : String(exc));
- }
- }
-
- async function runSetup() {
- try {
- const outcome = await setupAll({ autoRestart: true });
- if (outcome === "restart") {
- pushToast("info", t("permissions.setup_restarting"));
- } else if (outcome === "timeout") {
- pushToast("warning", t("permissions.setup_timeout"));
- }
- } catch (exc) {
- const message = exc instanceof Error ? exc.message : String(exc);
- pushToast(
- "error",
- message === "restart-missions-running"
- ? t("topbar.restart_missions_running")
- : message,
- );
- }
- }
-
- async function restartApp() {
- if (restarting) return;
- setRestarting(true);
- try {
- const response = await fetch("/api/settings/restart-app", { method: "POST" });
- if (response.status === 409) {
- pushToast("warning", t("topbar.restart_missions_running"));
- setRestarting(false);
- return;
- }
- if (!response.ok) throw new Error(`restart-failed:${response.status}`);
- // A successful response schedules process shutdown; keep the button
- // disabled while the window closes and relaunches.
- } catch {
- pushToast("error", t("permissions.restart_failed"));
- setRestarting(false);
- }
- }
-
- return (
- <div
- data-testid="permissions-alert-banner"
- data-state={restartOnly ? "restart" : "missing"}
- role="alert"
- // Same rule as the other shell banners: a full-width strip does not rise
- // off the page. The alert is carried by the glyph and the hairline.
- className="border-b border-warning"
- >
- <div className="flex items-center gap-3 px-4 py-2.5">
- <ShieldAlert className="h-5 w-5 shrink-0 text-warning" aria-hidden />
- <div className="min-w-0 flex-1">
- <p className="text-body font-semibold text-foreground-strong">
- {restartOnly
- ? t("permissions.restart_required")
- : t("permissions.banner.title")}
- </p>
- {!restartOnly && brokenFeatures.length > 0 && (
- <p className="text-meta text-muted-foreground">
- {t("permissions.banner.impact").replace("{0}", brokenFeatures.join(", "))}
- </p>
- )}
- </div>
- {restartOnly ? (
- <Button size="sm" disabled={restarting} onClick={() => void restartApp()}>
- {restarting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
- {t(restarting ? "permissions.restarting" : "permissions.restart_now")}
- </Button>
- ) : (
- <>
- {/* The whole list in one click; the per-row buttons below stay
- for anyone who wants to pick. Hidden while the app runs
- outside its bundle — a grant would land on the wrong identity. */}
- {setupNeeded && snapshot.app_identity.stable !== false && !setupProgress && (
- <Button size="sm" data-testid="permissions-setup-all" onClick={() => void runSetup()}>
- <Wand2 className="mr-1.5 h-3.5 w-3.5" aria-hidden />
- {t("permissions.setup_all")}
- </Button>
- )}
- <Button
- size="sm"
- variant="outline"
- aria-expanded={!collapsed}
- onClick={() => setCollapsed((value) => !value)}
- >
- {collapsed ? (
- <ChevronDown className="mr-1.5 h-3.5 w-3.5" aria-hidden />
- ) : (
- <ChevronUp className="mr-1.5 h-3.5 w-3.5" aria-hidden />
- )}
- {t(collapsed ? "permissions.banner.expand" : "permissions.banner.collapse")}
- </Button>
- </>
- )}
- </div>
-
- {!restartOnly && setupProgress && (
- <div className="px-4 pb-3">
- <SetupAllControl progress={setupProgress} onStart={() => undefined} onCancel={cancelSetup} />
- </div>
- )}
-
- {!restartOnly && !collapsed && (
- <div className="space-y-stack px-4 pb-3">
- {snapshot.app_identity.stable === false && (
- <p className="text-meta text-muted-foreground">{t("permissions.identity_warning")}</p>
- )}
- {snapshot.identity_reset && (
- <p className="text-meta text-muted-foreground">{t("permissions.identity_reset")}</p>
- )}
- {missing.map((item) => (
- <MissingPermissionRow
- key={item.id}
- item={item}
- busy={pendingId === item.id}
- onRequest={() => void run(() => request(item.id))}
- onOpenSettings={() => void run(() => openSettings(item.id))}
- onReset={() => void run(() => reset(item.id))}
- />
- ))}
- {snapshot.restart_required && (
- // Rim-only, no fill: these rows are as wide as the window, and a
- // surface that wide never rises off the page. When a fill is out,
- // the hairline is what is left to group with.
- <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border p-block">
- <p className="text-body text-foreground">{t("permissions.restart_required")}</p>
- <Button size="sm" disabled={restarting} onClick={() => void restartApp()}>
- {restarting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
- {t(restarting ? "permissions.restarting" : "permissions.restart_now")}
- </Button>
- </div>
- )}
- <p className="text-meta text-muted-foreground">{t("permissions.banner.hint")}</p>
- </div>
- )}
- </div>
- );
-}
-
-function MissingPermissionRow({
- item,
- busy,
- onRequest,
- onOpenSettings,
- onReset,
-}: {
- item: PermissionItem;
- busy: boolean;
- onRequest: () => void;
- onOpenSettings: () => void;
- onReset: () => void;
-}) {
- const t = useT();
- // A newer backend may report a permission id this build does not know yet;
- // fall back to the generic shield instead of rendering `undefined`.
- const Icon = ICONS[item.id] ?? ShieldAlert;
- // Screen Recording's probe is frozen per process (see PermissionsPanel):
- // once a restart is pending, the stale "not granted" would gaslight the
- // user who just granted it — show the honest pending label instead.
- const statusKey =
- item.restart_required && item.id === "screen_recording"
- ? "restart_pending"
- : item.status;
-
- return (
- <div className="flex flex-wrap items-center gap-3 rounded-lg border border-border p-block">
- <Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
- <div className="min-w-[12rem] flex-1">
- <div className="text-title font-semibold text-foreground-strong">
- {t(`permissions.items.${item.id}.title`)}
- </div>
- <p className="mt-0.5 text-meta text-muted-foreground">
- {t(`permissions.items.${item.id}.description`)}
- </p>
- {/* macOS will not prompt again and the grant is missing: the
- checkmark in System Settings belongs to an older signature of
- this app, so toggling it there leads nowhere (BUG-159). */}
- {item.can_reset && !item.can_request && (
- <p className="mt-1 text-meta text-muted-foreground">
- {t("permissions.stale_grant_hint")}
- </p>
- )}
- </div>
- {/* A status is never ink: every row here is a permission the app does
- NOT have, so it reads as a fault — except the one that is only
- waiting for a restart, which is the "degraded" case. */}
- {/* `clsx`, not `cn`: tailwind-merge treats `text-meta` as a colour and
- would drop the size in favour of the status colour beside it. */}
- <span
- className={clsx(
- "shrink-0 text-meta font-medium",
- statusKey === "restart_pending" ? "text-warning" : "text-destructive",
- )}
- >
- {t(`permissions.status.${statusKey}`)}
- </span>
- {item.can_request && (
- <Button size="sm" disabled={busy} onClick={onRequest}>
- {busy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
- {t("permissions.request")}
- </Button>
- )}
- {item.can_open_settings && (
- <Button size="sm" variant="outline" disabled={busy} onClick={onOpenSettings}>
- {busy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
- {t("permissions.open_settings")}
- </Button>
- )}
- {item.can_reset && (
- <Button size="sm" variant="ghost" disabled={busy} onClick={onReset}>
- {busy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
- {t("permissions.ask_again")}
- </Button>
- )}
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/layout/overlay-stacking.test.ts b/jarvis/ui/web/frontend/src/components/layout/overlay-stacking.test.ts
index 2204874fe4..07d499ca96 100644
--- a/jarvis/ui/web/frontend/src/components/layout/overlay-stacking.test.ts
+++ b/jarvis/ui/web/frontend/src/components/layout/overlay-stacking.test.ts
@@ -108,4 +108,23 @@ describe("overlay stacking guard", () => {
"dialog levels.",
).toEqual([]);
});
+
+ it("keeps the toasts between the setup spotlight and the caption bar", () => {
+ // The blocking tour dims the app at z-110 with a pointer-events-auto scrim; a
+ // toast under it would be dimmed and unclickable during the onboarding step
+ // where the wake word asks for the microphone, and its "Open System Settings"
+ // button is the one way on after a denial. The caption bar (z-120) is the
+ // title bar of every window and always wins.
+ const zOf = (path: string, pattern: RegExp): number => {
+ const match = pattern.exec(read(path));
+ expect(match, `${path} no longer carries ${pattern}`).not.toBeNull();
+ return Number(match![1]);
+ };
+ const spotlight = zOf("components/onboarding/tour/Spotlight.tsx", /fixed inset-0 z-\[(\d+)\]/);
+ const caption = zOf("components/layout/TopBar.tsx", /fixed inset-x-0 top-0 z-\[(\d+)\]/);
+ const toasts = zOf("components/ToastLayer.tsx", /fixed right-4 top-12 z-\[(\d+)\]/);
+
+ expect(toasts).toBeGreaterThan(spotlight);
+ expect(toasts).toBeLessThan(caption);
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx
index 49bf2e6999..3347836a22 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx
@@ -29,8 +29,9 @@ function param(name: string): string | null {
* First run, in two acts, both on the real app — there is no setup screen.
*
* 1. Setup: the window dims and a guide walks the user to the app's own
- * places — consent, the API Keys page, the wake word in Settings (and the
- * macOS permissions) — until onboarding is complete. Fails open: while
+ * places — consent, the API Keys page, the wake word in Settings — until
+ * onboarding is complete (macOS permissions are asked later, where a
+ * feature needs them; no step of setup asks for one). Fails open: while
* loading or on a fetch error it renders nothing, so a broken guide never
* traps anyone.
* 2. The tour: after the completion restart, a spotlight explains the app
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.test.tsx
index 6509aacd95..9acf535596 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.test.tsx
@@ -50,7 +50,6 @@ function stubFetch() {
const method = init?.method ?? "GET";
calls.push({ url, method });
const reply = (body: unknown) => Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(body) });
- if (url === "/api/permissions/status") return reply({ platform: "win32" });
if (url === "/api/providers") return reply({ providers });
if (url === "/api/setup/starter-plans") return reply({ plans: [plan], selected: null, custom_id: "custom" });
if (url === "/api/settings/wake-word") return reply(wakeWord);
@@ -169,6 +168,43 @@ it("asks for a wake word before going on, with a way to leave it for later", asy
expect(onb.saveStep).toHaveBeenLastCalledWith("ready", ["voice"]);
});
+const MAC_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)";
+
+function inputMonitoringAsks() {
+ return calls.filter((c) => c.url.startsWith("/api/permissions/input_monitoring/request"));
+}
+
+it("choosing the Call shortcut asks for Input Monitoring once, from that click, in the Mac desktop window", async () => {
+ (window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean }).__JARVIS_EMBEDDED_DESKTOP = true;
+ vi.spyOn(window.navigator, "userAgent", "get").mockReturnValue(MAC_UA);
+ try {
+ const onb = fakeOnb({ ...accepted, current_step: "voice" });
+ render(<SetupTour onb={onb} preview={false} onFinished={vi.fn()} />);
+ await screen.findByTestId("setup-voice-later");
+ // Nothing is asked by arriving on the step.
+ expect(inputMonitoringAsks()).toEqual([]);
+
+ fireEvent.click(screen.getByTestId("setup-voice-later"));
+
+ await waitFor(() => expect(inputMonitoringAsks()).toHaveLength(1));
+ expect(inputMonitoringAsks()[0].method).toBe("POST");
+ await waitFor(() => expect(screen.getByTestId("setup-card").dataset.step).toBe("ready"));
+ } finally {
+ delete (window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean }).__JARVIS_EMBEDDED_DESKTOP;
+ }
+});
+
+it("choosing the Call shortcut asks nothing on Windows, Linux or in a plain browser", async () => {
+ const onb = fakeOnb({ ...accepted, current_step: "voice" });
+ render(<SetupTour onb={onb} preview={false} onFinished={vi.fn()} />);
+ await screen.findByTestId("setup-voice-later");
+
+ fireEvent.click(screen.getByTestId("setup-voice-later"));
+
+ await waitFor(() => expect(screen.getByTestId("setup-card").dataset.step).toBe("ready"));
+ expect(inputMonitoringAsks()).toEqual([]);
+});
+
it("goes on from the wake word once one is saved", async () => {
wakeWord = { phrase: "Hey George", enabled: true };
render(<SetupTour onb={fakeOnb({ ...accepted, current_step: "voice" })} preview={false} onFinished={vi.fn()} />);
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.tsx b/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.tsx
index 9a3cea2df5..ebfb7b9b2e 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/setup/SetupTour.tsx
@@ -7,6 +7,7 @@ import { applyStarterPlan, getStarterPlans, selectStarterPlan, type StarterPlan
import { useWakeWord } from "@/hooks/useWakeWord";
import { fetchAgentConnections } from "@/lib/agentChatApi";
import { clearApiKeysTabRequest, requestApiKeysTab } from "@/lib/apiKeysTab";
+import { isEmbeddedMacWindow } from "@/lib/embeddedDesktop";
import { fill, setUiLanguage, useLocaleChunk, useT, useUiLanguage, type UiLanguage } from "@/i18n";
import type { PetState } from "@/lib/petStates";
import { cn } from "@/lib/utils";
@@ -29,7 +30,6 @@ const PET: Record<SetupStepId, PetState> = {
keys: "thinking",
subscriptions: "thinking",
voice: "listening",
- permissions: "idle",
ready: "success",
};
@@ -41,10 +41,9 @@ const LANGS: UiLanguage[] = ["en", "de", "es"];
* There is no setup screen of its own: the window dims, and the guide walks
* the user to the places where each thing is really set — the API Keys page
* for one key, its Agents tab for a subscription, the wake-word group in
- * Settings, on macOS the permissions —
- * and waits there with a small card. The dim takes clicks, the hole does
- * not: only the part being set up can be used, so nothing else starts before
- * setup is done. Every step has a way on without doing it. There is no
+ * Settings — and waits there with a small card. The dim takes clicks, the hole
+ * does not: only the part being set up can be used, so nothing else starts
+ * before setup is done. Every step has a way on without doing it. There is no
* consent gate: it is an open-source app, the welcome only picks a language.
*
* The last step hands over to the tour of the app straight away; the gate
@@ -68,36 +67,18 @@ export function SetupTour({
}) {
const t = useT();
const ready = useLocaleChunk("onboarding");
- const [platform, setPlatform] = useState<string | null>(null);
- const steps = useMemo(() => stepsFor(platform), [platform]);
+ const steps = useMemo(() => stepsFor(), []);
// A replay shows every step from the start; a real first run resumes where
// it left off (never past the consent).
const [stepId, setStepId] = useState<SetupStepId>(() =>
preview
? (startAt ?? "welcome")
- : resumeStep(stepsFor(null), onb.state?.current_step ?? null),
+ : resumeStep(steps, onb.state?.current_step ?? null),
);
const [skipped, setSkipped] = useState<string[]>(() => onb.state?.skipped_steps ?? []);
const [cue, setCue] = useState(0);
const step = SETUP_STEPS[stepId];
- useEffect(() => {
- let cancelled = false;
- void (async () => {
- try {
- const res = await fetch("/api/permissions/status");
- if (!res.ok) return;
- const data = (await res.json()) as { platform?: string };
- if (!cancelled && typeof data.platform === "string") setPlatform(data.platform);
- } catch {
- // Best-effort: without the probe there is simply no permissions step.
- }
- })();
- return () => {
- cancelled = true;
- };
- }, []);
-
// Open the app's own place for this step before pointing at it — on the
// API Keys page also the right tab.
useEffect(() => {
@@ -201,7 +182,6 @@ export function SetupTour({
{stepId === "keys" && <KeysStep next={next} later={later} cheer={cheer} />}
{stepId === "subscriptions" && <SubscriptionsStep next={next} later={later} />}
{stepId === "voice" && <VoiceStep next={next} later={later} />}
- {stepId === "permissions" && <PermissionsStep next={next} />}
{stepId === "ready" && <ReadyStep preview={preview} onFinished={onFinished} />}
</div>
{footer}
@@ -447,6 +427,30 @@ function useConnectedSubscriptions(pollMs: number): string[] {
return names;
}
+/**
+ * "Skip, I'll use the Call shortcut" is the one moment on first run where the
+ * person picks a global key over the wake word, so on a Mac it is also the moment
+ * that key's permission (Input Monitoring) can be asked: from this click, once,
+ * never at launch. macOS shows its own dialog; a refusal changes nothing here (the
+ * Shortcuts settings save asks again the same way, and a denied one is told by the
+ * permission toast the next time a shortcut fails).
+ */
+function askInputMonitoringForCallShortcut(): void {
+ if (!isEmbeddedMacWindow()) return;
+ void fetch("/api/permissions/input_monitoring/request?dry_run=false", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ feature: "global_shortcuts" }),
+ })
+ .then((res) => {
+ if (!res.ok) console.warn(`Input Monitoring request answered HTTP ${res.status}.`);
+ })
+ .catch((error: unknown) => {
+ // Best-effort: the step moves on either way, the ask is only a courtesy.
+ console.warn("Input Monitoring request failed:", error);
+ });
+}
+
/**
* The wake-word group of Settings is open behind the card. Continue waits
* for a saved wake word; without one the Call shortcut is the way in, so the
@@ -456,6 +460,10 @@ function VoiceStep({ next, later }: { next: () => void; later: () => void }) {
const t = useT();
const { config } = useWakeWord();
const on = Boolean(config?.enabled && config.phrase.trim());
+ const chooseCallShortcut = () => {
+ askInputMonitoringForCallShortcut();
+ later();
+ };
return (
<div className="space-y-3">
<Status tone={on ? "ok" : "muted"} testId="setup-voice-status">
@@ -466,7 +474,7 @@ function VoiceStep({ next, later }: { next: () => void; later: () => void }) {
</PrimaryAction>
{!on && (
<div className="text-center">
- <QuietAction onClick={later} testId="setup-voice-later" className="text-xs">
+ <QuietAction onClick={chooseCallShortcut} testId="setup-voice-later" className="text-xs">
{t("first_run.voice.later")}
</QuietAction>
</div>
@@ -475,17 +483,6 @@ function VoiceStep({ next, later }: { next: () => void; later: () => void }) {
);
}
-/** macOS only: the permission rows of Settings are open behind the card. */
-function PermissionsStep({ next }: { next: () => void }) {
- const t = useT();
- return (
- <div className="space-y-3">
- <p className="text-xs leading-relaxed text-muted-foreground">{t("first_run.permissions.note")}</p>
- <PrimaryAction onClick={next}>{t("first_run.continue")}</PrimaryAction>
- </div>
- );
-}
-
function ReviewRow({ label, value, ok }: { label: string; value: ReactNode; ok: boolean }) {
return (
<div className="flex items-center justify-between gap-3 border-b border-border px-3.5 py-2.5 last:border-b-0">
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/setup/setupSteps.test.ts b/jarvis/ui/web/frontend/src/components/onboarding/setup/setupSteps.test.ts
index 8620ddb985..1789604662 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/setup/setupSteps.test.ts
+++ b/jarvis/ui/web/frontend/src/components/onboarding/setup/setupSteps.test.ts
@@ -24,15 +24,13 @@ describe("setup steps", () => {
expect([...block![1].matchAll(/"([a-z-]+)"/g)].map((m) => m[1])).toEqual([...SETUP_STEP_IDS]);
});
- it("ask for permissions on macOS only", () => {
- expect(stepsFor("darwin")).toContain("permissions");
- expect(stepsFor("win32")).not.toContain("permissions");
- expect(stepsFor("linux")).not.toContain("permissions");
- expect(stepsFor(null)).not.toContain("permissions");
+ it("has no permissions step on any OS (permissions are asked just in time)", () => {
+ expect(stepsFor()).not.toContain("permissions" as never);
+ expect(SETUP_STEPS).not.toHaveProperty("permissions");
});
- it("start with the consent and end with the start", () => {
- const steps = stepsFor("darwin");
+ it("start with the welcome and end with the start", () => {
+ const steps = stepsFor();
expect(steps[0]).toBe("welcome");
expect(steps[steps.length - 1]).toBe("ready");
});
@@ -77,7 +75,7 @@ describe("setup steps", () => {
});
describe("resumeStep", () => {
- const steps = stepsFor("win32");
+ const steps = stepsFor();
it("returns to the saved step", () => {
expect(resumeStep(steps, "voice")).toBe("voice");
@@ -88,4 +86,9 @@ describe("resumeStep", () => {
expect(resumeStep(steps, null)).toBe("welcome");
expect(resumeStep(steps, "api-keys")).toBe("welcome");
});
+
+ it("maps a stored legacy permissions step to the voice step on every OS", () => {
+ // An older build stored "permissions" (macOS only) right before "voice".
+ expect(resumeStep(steps, "permissions")).toBe("voice");
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/setup/setupSteps.ts b/jarvis/ui/web/frontend/src/components/onboarding/setup/setupSteps.ts
index 0e454de337..a84d4e8f7b 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/setup/setupSteps.ts
+++ b/jarvis/ui/web/frontend/src/components/onboarding/setup/setupSteps.ts
@@ -8,10 +8,14 @@
import type { SectionId } from "@/store/events";
import type { TourPlacement } from "../tour/tourSteps";
-/** Must match `ONBOARDING_STEPS` in jarvis/setup/onboarding_meta.py. */
-// Permissions precede voice so the macOS microphone grant exists before the
-// wake-word group's own microphone test.
-export const SETUP_STEP_IDS = ["welcome", "how", "keys", "subscriptions", "permissions", "voice", "ready"] as const;
+/**
+ * Must match `ONBOARDING_STEPS` in jarvis/setup/onboarding_meta.py.
+ *
+ * There is no permissions step: macOS asks at the moment a feature needs its
+ * permission (the wake-word switch on the voice step is one such moment, and
+ * says so inside the spotlight hole), never as a stop of its own on first run.
+ */
+export const SETUP_STEP_IDS = ["welcome", "how", "keys", "subscriptions", "voice", "ready"] as const;
export type SetupStepId = (typeof SETUP_STEP_IDS)[number];
@@ -54,24 +58,12 @@ export const SETUP_STEPS: Record<SetupStepId, SetupStep> = {
placement: "left",
width: 320,
},
- permissions: {
- id: "permissions",
- section: "settings",
- anchor: "settings-permissions",
- scrollTo: true,
- placement: "left",
- width: 320,
- },
ready: { id: "ready", section: "chats", placement: "inside", width: 400 },
};
-/**
- * The steps this machine walks. Only macOS asks for permissions one ability
- * at a time; Windows, Linux and a failed platform probe leave that step out
- * (Settings stays the way to grant them later).
- */
-export function stepsFor(platform: string | null): SetupStepId[] {
- return SETUP_STEP_IDS.filter((id) => id !== "permissions" || platform === "darwin");
+/** The steps this machine walks — every OS walks the same ones. */
+export function stepsFor(): SetupStepId[] {
+ return [...SETUP_STEP_IDS];
}
/**
@@ -80,6 +72,8 @@ export function stepsFor(platform: string | null): SetupStepId[] {
* step id) begins at the welcome.
*/
export function resumeStep(steps: readonly SetupStepId[], saved: string | null): SetupStepId {
- const hit = steps.find((id) => id === saved);
+ // An older build stored "permissions" (macOS only) right before "voice".
+ const wanted = saved === "permissions" ? "voice" : saved;
+ const hit = steps.find((id) => id === wanted);
return hit ?? "welcome";
}
diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
index 6cfd9b874f..5f02916af1 100644
--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
@@ -1,5 +1,5 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useEventStore } from "@/store/events";
import {
@@ -389,6 +389,70 @@ describe("BrowserRealtimeControl", () => {
);
});
+ describe("a refused microphone", () => {
+ const MAC_UA =
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)";
+ let fetchSpy: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ fetchSpy = vi.fn(async () => new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchSpy);
+ fakes.connect.mockRejectedValueOnce(new DOMException("denied", "NotAllowedError"));
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it("reports a Mac desktop denial so the permission toast can show, with a desktop sentence", async () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(MAC_UA);
+ (window as unknown as { pywebview?: unknown }).pywebview = { api: {} };
+ fakes.native = false;
+ render(<BrowserRealtimeControl />);
+ fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));
+
+ expect(await screen.findByText("sidebar.realtime_microphone_denied_desktop")).toBeTruthy();
+ expect(screen.queryByText("sidebar.realtime_microphone_denied")).toBeNull();
+ await waitFor(() => expect(fetchSpy).toHaveBeenCalledTimes(1));
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe("/api/permissions/microphone/request?dry_run=false");
+ expect(init.method).toBe("POST");
+ expect(JSON.parse(String(init.body))).toEqual({ feature: "browser_voice" });
+ });
+
+ it("keeps the browser site-settings sentence, and reports nothing, in a plain browser", async () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(MAC_UA);
+ render(<BrowserRealtimeControl />);
+ fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));
+
+ expect(await screen.findByText("sidebar.realtime_microphone_denied")).toBeTruthy();
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("does not report a denial of a call the wake word started", async () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(MAC_UA);
+ (window as unknown as { pywebview?: unknown }).pywebview = { api: {} };
+ fakes.browserAudio = true;
+ useEventStore.setState({
+ events: [
+ {
+ id: "wake-denied",
+ name: "BrowserVoiceRequested",
+ ts: Date.now(),
+ payload: { action: "start" },
+ },
+ ],
+ });
+ render(<BrowserRealtimeControl controlOnly />);
+
+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+ });
+
it("maps every connection/voice combination onto exactly one look", () => {
expect(waveformPhase("idle", "idle")).toBe("idle");
expect(waveformPhase("connecting", "idle")).toBe("connecting");
diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
index dbc1d4018b..9f61edd2ed 100644
--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
@@ -7,6 +7,7 @@ import { Card } from "@/components/ui/card";
import { useCapabilities } from "@/hooks/useCapabilities";
import { useVoiceMode } from "@/hooks/useVoiceMode";
import { useT } from "@/i18n";
+import { hasEmbeddedDesktopBridge, isEmbeddedMacWindow } from "@/lib/embeddedDesktop";
import {
browserRealtimeSupportIssue,
RealtimeAudioClient,
@@ -29,27 +30,10 @@ import {
type ConnectionState = "idle" | "connecting" | "connected" | "error";
-/** True only inside a pywebview host, never from the backend's machine flag.
- *
- * A normal Chrome window can connect to the same local desktop backend, where
- * `native_file_actions` is also true. Checking the client bridge keeps browser
- * microphone control visible there without enabling a second microphone in the
- * embedded desktop window.
- */
-export function hasEmbeddedDesktopBridge(): boolean {
- const host = window as unknown as {
- __JARVIS_EMBEDDED_DESKTOP?: boolean;
- pywebview?: { api?: unknown };
- chrome?: { webview?: { postMessage?: unknown } };
- webkit?: { messageHandlers?: Record<string, unknown> };
- };
- return Boolean(
- host.__JARVIS_EMBEDDED_DESKTOP ||
- host.pywebview?.api ||
- typeof host.chrome?.webview?.postMessage === "function" ||
- host.webkit?.messageHandlers?.jarvisFileDrag,
- );
-}
+// Defined in lib/embeddedDesktop.ts (a module with no UI imports, so the
+// permission toast can ask it cheaply); re-exported here because this is where
+// the rest of the shell has always imported it from.
+export { hasEmbeddedDesktopBridge };
/** Map the socket state plus the shared voice state onto one visualizer look.
*
@@ -73,6 +57,25 @@ export function waveformPhase(
return "listening";
}
+/**
+ * Tell the backend that the person pressed Start and macOS refused the
+ * microphone, so it opens a user-origin episode and the permission toast is
+ * shown. Best effort: the sentence under the button already says what happened,
+ * so a failure here is logged and nothing else.
+ */
+async function reportHostMicrophoneDenied(): Promise<void> {
+ try {
+ const res = await fetch("/api/permissions/microphone/request?dry_run=false", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ feature: "browser_voice" }),
+ });
+ if (!res.ok) console.warn(`Microphone permission report failed: HTTP ${res.status}`);
+ } catch (error) {
+ console.warn("Microphone permission report failed:", error);
+ }
+}
+
/** Browser-owned microphone control for remote/headless installations.
*
* The desktop shell already owns the physical microphone through
@@ -165,7 +168,7 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:
await client?.disconnect();
}, [setVoice]);
- const start = useCallback(async () => {
+ const start = useCallback(async (options?: { fromGesture?: boolean }) => {
if (!realtimeAvailable || clientRef.current || state === "connecting") return;
const generation = connectionGenerationRef.current + 1;
connectionGenerationRef.current = generation;
@@ -322,12 +325,21 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:
void client.disconnect();
clearVoiceInputLevel("browser");
setState("error");
+ const micDenied = cause instanceof DOMException && cause.name === "NotAllowedError";
+ // In the embedded Mac window a refused microphone is macOS's decision, not a
+ // browser site setting: there is no site settings page to point at. The
+ // person's own press opens a user-origin episode, so the permission toast
+ // ("Open System Settings") takes over; a wake-started call never does.
+ const hostDenied = micDenied && isEmbeddedMacWindow();
+ if (hostDenied && options?.fromGesture) void reportHostMicrophoneDenied();
setError(
cause instanceof RealtimeAudioSupportError
? supportMessage(cause.issue)
- : cause instanceof DOMException && cause.name === "NotAllowedError"
- ? t("sidebar.realtime_microphone_denied")
- : t("sidebar.realtime_error"),
+ : hostDenied
+ ? t("sidebar.realtime_microphone_denied_desktop")
+ : micDenied
+ ? t("sidebar.realtime_microphone_denied")
+ : t("sidebar.realtime_error"),
);
setVoice("error");
}
@@ -468,7 +480,7 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:
disabled={unavailable || connecting}
aria-label={label}
aria-pressed={connected}
- onClick={() => void (connected ? stop() : start())}
+ onClick={() => void (connected ? stop() : start({ fromGesture: true }))}
className="w-full touch-manipulation gap-2"
>
<Icon
diff --git a/jarvis/ui/web/frontend/src/hooks/useMuteMusic.test.tsx b/jarvis/ui/web/frontend/src/hooks/useMuteMusic.test.tsx
new file mode 100644
index 0000000000..cc5a92dbf0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useMuteMusic.test.tsx
@@ -0,0 +1,60 @@
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+import { useMuteMusic } from "./useMuteMusic";
+
+vi.mock("@/lib/bootStagger", () => ({ bootSettled: () => Promise.resolve() }));
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+/** A fake backend: the GET reads the switch, the PUT answers like the real route. */
+function stubBackend(put: { ok: boolean; body: unknown; status?: number }) {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockImplementation((_url: string, init?: RequestInit) => {
+ if (init?.method === "PUT") {
+ return Promise.resolve({
+ ok: put.ok,
+ status: put.status ?? (put.ok ? 200 : 500),
+ json: () => Promise.resolve(put.body),
+ });
+ }
+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ enabled: false }) });
+ }),
+ );
+}
+
+it("saves the switch and reports what the backend answered", async () => {
+ stubBackend({
+ ok: true,
+ body: { ok: true, enabled: true, persisted: true, applied_live: true },
+ });
+
+ const { result } = renderHook(() => useMuteMusic());
+ await waitFor(() => expect(result.current.enabled).toBe(false));
+
+ let saved: unknown;
+ await act(async () => {
+ saved = await result.current.setEnabled(true);
+ });
+
+ expect(result.current.enabled).toBe(true);
+ expect(saved).toMatchObject({ ok: true, enabled: true, persisted: true, applied_live: true });
+});
+
+it("stays quiet when the switch could not be saved", async () => {
+ stubBackend({ ok: false, status: 500, body: { detail: "config is locked" } });
+
+ const { result } = renderHook(() => useMuteMusic());
+ await waitFor(() => expect(result.current.enabled).toBe(false));
+
+ await act(async () => {
+ await expect(result.current.setEnabled(true)).rejects.toThrow("config is locked");
+ });
+
+ expect(result.current.enabled).toBe(false);
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/usePermissionToast.ts b/jarvis/ui/web/frontend/src/hooks/usePermissionToast.ts
new file mode 100644
index 0000000000..afc8e1677f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/usePermissionToast.ts
@@ -0,0 +1,46 @@
+import { useCallback, useEffect, useRef } from "react";
+
+import { useRestartApp } from "@/hooks/useRestartApp";
+import { translate } from "@/i18n";
+import { bootSettled } from "@/lib/bootStagger";
+import { handlePermissionToastEvent, seedPermissionToasts } from "@/lib/permissionToast";
+
+/**
+ * The permission toast's entry points for the WebSocket hook: STABLE functions,
+ * `onEvent` to call with every bus event (it reads only `PermissionNeeded` and
+ * `PermissionResolved`, see `lib/permissionToast.ts`) and `seed` to call once per
+ * (re)connect so an episode that opened while no window listened is not lost.
+ *
+ * It exists because the toast's "Quit and reopen" button is `useRestartApp`,
+ * which is React state, while the socket handler is installed once and lives
+ * outside React. The latest `restart` is kept in a ref so the handler never goes
+ * stale, and the functions returned here never change identity.
+ */
+export function usePermissionToast(): {
+ onEvent: (eventName: string, payload: unknown) => void;
+ seed: () => void;
+} {
+ const { restart } = useRestartApp();
+ const restartRef = useRef(restart);
+ useEffect(() => {
+ restartRef.current = restart;
+ }, [restart]);
+
+ const deps = useCallback(
+ () => ({
+ restart: () => restartRef.current({ failureMessage: translate("permissions.restart_failed") }),
+ }),
+ [],
+ );
+ const onEvent = useCallback(
+ (eventName: string, payload: unknown) => handlePermissionToastEvent(eventName, payload, deps()),
+ [deps],
+ );
+ const seed = useCallback(() => {
+ // Read-only, and behind the boot burst (AP-26): never part of the launch path.
+ bootSettled()
+ .then(() => seedPermissionToasts(deps()))
+ .catch((error) => console.warn("Permission toast seed failed:", error));
+ }, [deps]);
+ return { onEvent, seed };
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/usePermissions.test.tsx b/jarvis/ui/web/frontend/src/hooks/usePermissions.test.tsx
deleted file mode 100644
index 9afc011002..0000000000
--- a/jarvis/ui/web/frontend/src/hooks/usePermissions.test.tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
-import { afterEach, expect, it, vi } from "vitest";
-import { usePermissions, type PermissionSnapshot } from "./usePermissions";
-
-vi.mock("@/lib/bootStagger", () => ({ bootSettled: () => Promise.resolve() }));
-
-afterEach(() => {
- cleanup();
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
-});
-
-function snapshot(status: "not_determined" | "granted"): PermissionSnapshot {
- return {
- platform: "darwin",
- supported: true,
- headless: false,
- app_identity: { stable: true, foreground: true, launched_as_bundle: true },
- permissions: [
- {
- id: "microphone",
- status,
- required: ["voice"],
- can_request: status === "not_determined",
- can_open_settings: true,
- can_reset: status !== "granted",
- restart_required: false,
- },
- ],
- features: {
- voice: { ready: status === "granted", missing: status === "granted" ? [] : ["microphone"] },
- },
- restart_required: false,
- };
-}
-
-it("loads a fresh snapshot and unwraps a request operation", async () => {
- const calls: Array<[string, RequestInit | undefined]> = [];
- vi.stubGlobal(
- "fetch",
- vi.fn().mockImplementation((url: string, init?: RequestInit) => {
- calls.push([url, init]);
- const payload = init?.method === "POST"
- ? { ok: true, snapshot: snapshot("granted") }
- : snapshot("not_determined");
- return Promise.resolve({ ok: true, json: () => Promise.resolve(payload) });
- }),
- );
-
- const { result } = renderHook(() => usePermissions());
- await waitFor(() => expect(result.current.snapshot?.permissions[0].status).toBe("not_determined"));
-
- await act(async () => {
- await result.current.request("microphone");
- });
-
- expect(result.current.snapshot?.features.voice.ready).toBe(true);
- expect(calls).toContainEqual([
- "/api/permissions/microphone/request?dry_run=false",
- { method: "POST" },
- ]);
-});
-
-it("surfaces a failed native request without losing the last snapshot", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(snapshot("not_determined")) })
- .mockResolvedValueOnce({
- ok: false,
- status: 409,
- json: () => Promise.resolve({ message: "Bring Personal Jarvis to the foreground." }),
- });
- vi.stubGlobal("fetch", fetchMock);
-
- const { result } = renderHook(() => usePermissions());
- await waitFor(() => expect(result.current.snapshot).not.toBeNull());
- await act(async () => {
- await expect(result.current.request("microphone")).rejects.toThrow("foreground");
- });
-
- expect(result.current.error).toContain("foreground");
- expect(result.current.snapshot?.permissions[0].status).toBe("not_determined");
-});
-
-function twoRowSnapshot(
- microphone: "not_determined" | "granted",
- accessibility: "not_granted" | "granted",
- restartRequired = false,
-): PermissionSnapshot {
- return {
- platform: "darwin",
- supported: true,
- headless: false,
- app_identity: { stable: true, foreground: true, launched_as_bundle: true },
- permissions: [
- {
- id: "microphone",
- status: microphone,
- required: ["voice"],
- can_request: microphone !== "granted",
- can_open_settings: true,
- can_reset: false,
- restart_required: false,
- },
- {
- // Accessibility has no prompt left here: only the Settings switch.
- id: "accessibility",
- status: accessibility,
- required: ["global_hotkeys"],
- can_request: false,
- can_open_settings: accessibility !== "granted",
- can_reset: false,
- restart_required: restartRequired,
- },
- ],
- features: {
- voice: { ready: microphone === "granted", missing: [] },
- global_hotkeys: { ready: accessibility === "granted", missing: [] },
- },
- restart_required: restartRequired,
- };
-}
-
-it("walks every missing row in order, waits for each grant, then restarts once", async () => {
- // The fake macOS: the microphone dialog is answered on the request; the
- // Accessibility switch flips two polls after System Settings opened, and
- // that grant only applies to a fresh process.
- let microphone: "not_determined" | "granted" = "not_determined";
- let accessibility: "not_granted" | "granted" = "not_granted";
- let pollsSinceSettings = -1;
- const calls: string[] = [];
- vi.stubGlobal(
- "fetch",
- vi.fn().mockImplementation((url: string, init?: RequestInit) => {
- if (init?.method === "POST") calls.push(url);
- if (url === "/api/settings/restart-app") {
- return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({}) });
- }
- if (url.includes("/microphone/request")) microphone = "granted";
- if (url.includes("/accessibility/open-settings")) pollsSinceSettings = 0;
- else if (url === "/api/permissions/status" && pollsSinceSettings >= 0) {
- pollsSinceSettings += 1;
- if (pollsSinceSettings >= 2) accessibility = "granted";
- }
- const restart = accessibility === "granted" && pollsSinceSettings >= 0;
- const body = twoRowSnapshot(microphone, accessibility, restart);
- const payload = init?.method === "POST" ? { ok: true, snapshot: body } : body;
- return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(payload) });
- }),
- );
-
- const { result } = renderHook(() => usePermissions());
- await waitFor(() => expect(result.current.setupNeeded).toBe(true));
-
- let outcome: string | undefined;
- await act(async () => {
- outcome = await result.current.setupAll({ autoRestart: true, pollMs: 1 });
- });
-
- expect(outcome).toBe("restart");
- expect(calls).toEqual([
- "/api/permissions/microphone/request?dry_run=false",
- "/api/permissions/accessibility/open-settings?dry_run=false",
- "/api/settings/restart-app",
- ]);
- expect(result.current.setupProgress).toBeNull();
-});
-
-it("stops when asked and never restarts without being allowed to", async () => {
- const calls: string[] = [];
- vi.stubGlobal(
- "fetch",
- vi.fn().mockImplementation((url: string, init?: RequestInit) => {
- if (init?.method === "POST") calls.push(url);
- const body = twoRowSnapshot("granted", "not_granted");
- const payload = init?.method === "POST" ? { ok: true, snapshot: body } : body;
- return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(payload) });
- }),
- );
-
- const { result } = renderHook(() => usePermissions());
- await waitFor(() => expect(result.current.setupNeeded).toBe(true));
-
- let run: Promise<string> | undefined;
- act(() => {
- run = result.current.setupAll({ pollMs: 1 });
- });
- // The Settings pane is open and the switch never flips: the user gives up.
- await waitFor(() => expect(result.current.setupProgress?.phase).toBe("settings"));
- act(() => {
- result.current.cancelSetup();
- });
- let outcome: string | undefined;
- await act(async () => {
- outcome = await run;
- });
-
- expect(outcome).toBe("cancelled");
- expect(calls).toEqual(["/api/permissions/accessibility/open-settings?dry_run=false"]);
-});
diff --git a/jarvis/ui/web/frontend/src/hooks/usePermissions.ts b/jarvis/ui/web/frontend/src/hooks/usePermissions.ts
deleted file mode 100644
index d6dfc1bb5c..0000000000
--- a/jarvis/ui/web/frontend/src/hooks/usePermissions.ts
+++ /dev/null
@@ -1,332 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-
-import { bootSettled } from "@/lib/bootStagger";
-
-export type PermissionId =
- | "microphone"
- | "screen_recording"
- | "accessibility"
- | "input_monitoring"
- | "event_posting"
- | "automation"
- | "credential_store";
-
-export type PermissionState =
- | "granted"
- | "not_determined"
- | "denied"
- | "restricted"
- | "not_granted"
- | "unavailable"
- | "not_required";
-
-export interface PermissionItem {
- id: PermissionId;
- status: PermissionState;
- required: string[];
- can_request: boolean;
- can_open_settings: boolean;
- /**
- * Whether dropping this app's own TCC record is a sensible next step. Always
- * read this instead of testing `status === "denied"`: the Screen Recording
- * and Accessibility preflights report a grant stranded on an older app
- * signature as plain "not_granted", so the denial test hid the reset from
- * exactly the two rows that need it most (BUG-159).
- */
- can_reset: boolean;
- restart_required: boolean;
- detail?: string | null;
-}
-
-/** Set when a rebuild changed the app signature and macOS discarded the grants. */
-export interface PermissionIdentityReset {
- reason: string;
- services: string[];
-}
-
-export interface PermissionFeature {
- ready: boolean;
- missing: PermissionId[];
-}
-
-export interface PermissionSnapshot {
- platform: string;
- supported: boolean;
- headless: boolean;
- app_identity: {
- app_name?: string;
- expected_bundle_id?: string;
- bundle_id?: string | null;
- bundle_path?: string | null;
- launched_as_bundle?: boolean;
- stable?: boolean;
- foreground?: boolean;
- };
- permissions: PermissionItem[];
- features: Record<string, PermissionFeature>;
- identity_reset?: PermissionIdentityReset | null;
- restart_required: boolean;
-}
-
-/**
- * The guided flow asks in this order: the pure dialogs first (a click each),
- * then the rows that end in a System Settings switch, so the user is never
- * bounced between Settings and the app more than once per row.
- */
-export const SETUP_ORDER: readonly PermissionId[] = [
- "microphone",
- "automation",
- "accessibility",
- "input_monitoring",
- "screen_recording",
- "event_posting",
- "credential_store",
-];
-
-export interface SetupProgress {
- id: PermissionId;
- index: number;
- total: number;
- /** "prompt" while the native dialog is up, "settings" once only a switch in System Settings is left. */
- phase: "prompt" | "settings";
-}
-
-export type SetupOutcome = "complete" | "cancelled" | "timeout" | "restart";
-
-const SETTLED_STATES = new Set(["granted", "not_required"]);
-
-/** A row the guided flow still has to deal with. */
-export function needsSetup(item: PermissionItem): boolean {
- return (
- item.required.length > 0 &&
- !SETTLED_STATES.has(item.status) &&
- !item.restart_required &&
- item.status !== "unavailable" &&
- item.status !== "restricted"
- );
-}
-
-function settled(item: PermissionItem | undefined): boolean {
- return !item || !needsSetup(item);
-}
-
-const EMPTY_SNAPSHOT: PermissionSnapshot = {
- platform: "unknown",
- supported: false,
- headless: false,
- app_identity: {},
- permissions: [],
- features: {},
- identity_reset: null,
- restart_required: false,
-};
-
-async function readJson(res: Response): Promise<unknown> {
- const payload = await res.json().catch(() => null);
- if (!res.ok) {
- const detail = payload && typeof payload === "object"
- ? "detail" in payload
- ? String((payload as { detail: unknown }).detail)
- : "message" in payload
- ? String((payload as { message: unknown }).message)
- : `HTTP ${res.status}`
- : `HTTP ${res.status}`;
- throw new Error(detail);
- }
- return payload;
-}
-
-function normalizeSnapshot(payload: unknown): PermissionSnapshot {
- if (!payload || typeof payload !== "object") return EMPTY_SNAPSHOT;
- const outer = payload as { snapshot?: unknown };
- const raw = outer.snapshot ?? payload;
- if (!raw || typeof raw !== "object") return EMPTY_SNAPSHOT;
- const value = raw as Partial<PermissionSnapshot>;
- return {
- ...EMPTY_SNAPSHOT,
- ...value,
- app_identity: value.app_identity ?? {},
- permissions: Array.isArray(value.permissions) ? value.permissions : [],
- features: value.features ?? {},
- };
-}
-
-export function usePermissions() {
- const [snapshot, setSnapshot] = useState<PermissionSnapshot | null>(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [pendingId, setPendingId] = useState<PermissionId | null>(null);
- const [setupProgress, setSetupProgress] = useState<SetupProgress | null>(null);
- const setupCancelled = useRef(false);
-
- const fetchSnapshot = useCallback(async (): Promise<PermissionSnapshot> => {
- const next = normalizeSnapshot(await readJson(await fetch("/api/permissions/status")));
- setSnapshot(next);
- return next;
- }, []);
-
- const refetch = useCallback(async () => {
- try {
- await fetchSnapshot();
- setError(null);
- } catch (exc) {
- setError(exc instanceof Error ? exc.message : String(exc));
- } finally {
- setLoading(false);
- }
- }, [fetchSnapshot]);
-
- const mutate = useCallback(
- async (
- id: PermissionId,
- action: "request" | "open-settings" | "reset",
- ): Promise<PermissionSnapshot> => {
- setPendingId(id);
- try {
- const payload = await readJson(
- await fetch(`/api/permissions/${id}/${action}?dry_run=false`, {
- method: "POST",
- }),
- );
- const next = normalizeSnapshot(payload);
- setSnapshot(next);
- setError(null);
- return next;
- } catch (exc) {
- setError(exc instanceof Error ? exc.message : String(exc));
- throw exc;
- } finally {
- setPendingId(null);
- }
- },
- [],
- );
-
- /**
- * The one-click flow: walk every missing row, fire its dialog (or open its
- * Settings pane) and wait for macOS to report the grant before moving on.
- * Ends with one automatic restart when a granted row only applies to a
- * fresh process (Screen Recording, Input Monitoring, Accessibility) and
- * `autoRestart` is set — onboarding owns its own final restart instead.
- */
- const setupAll = useCallback(
- async (options: { autoRestart?: boolean; pollMs?: number; rowTimeoutMs?: number } = {}) => {
- const { autoRestart = false, pollMs = 1500, rowTimeoutMs = 180_000 } = options;
- setupCancelled.current = false;
- let latest = await fetchSnapshot();
- const queue = SETUP_ORDER.filter((id) =>
- latest.permissions.some((item) => item.id === id && needsSetup(item)),
- );
- let outcome: SetupOutcome = "complete";
- try {
- for (const [index, id] of queue.entries()) {
- const item = latest.permissions.find((entry) => entry.id === id);
- if (settled(item)) continue;
- setSetupProgress({ id, index: index + 1, total: queue.length, phase: "prompt" });
- if (item?.can_request) {
- latest = await mutate(id, "request");
- } else if (item?.can_open_settings) {
- latest = await mutate(id, "open-settings");
- } else {
- continue;
- }
- const deadline = Date.now() + rowTimeoutMs;
- let current = latest.permissions.find((entry) => entry.id === id);
- while (!settled(current)) {
- if (setupCancelled.current) {
- outcome = "cancelled";
- return outcome;
- }
- if (Date.now() > deadline) {
- outcome = "timeout";
- return outcome;
- }
- setSetupProgress({ id, index: index + 1, total: queue.length, phase: "settings" });
- await new Promise((resolve) => window.setTimeout(resolve, pollMs));
- latest = await fetchSnapshot();
- current = latest.permissions.find((entry) => entry.id === id);
- }
- }
- if (autoRestart && latest.restart_required) {
- outcome = "restart";
- const response = await fetch("/api/settings/restart-app", { method: "POST" });
- if (!response.ok) {
- throw new Error(
- response.status === 409 ? "restart-missions-running" : `restart-failed:${response.status}`,
- );
- }
- }
- return outcome;
- } finally {
- setSetupProgress(null);
- }
- },
- [fetchSnapshot, mutate],
- );
-
- const cancelSetup = useCallback(() => {
- setupCancelled.current = true;
- }, []);
-
- useEffect(() => {
- // Non-critical: the banner can appear a few seconds late; the first-mount
- // burst must not spend a connection on it (see bootStagger).
- void bootSettled().then(refetch);
- }, [refetch]);
-
- useEffect(() => {
- const refreshWhenVisible = () => {
- if (document.visibilityState === "visible") void refetch();
- };
- window.addEventListener("focus", refreshWhenVisible);
- document.addEventListener("visibilitychange", refreshWhenVisible);
- return () => {
- window.removeEventListener("focus", refreshWhenVisible);
- document.removeEventListener("visibilitychange", refreshWhenVisible);
- };
- }, [refetch]);
-
- const waitingForSystemSettings = useMemo(
- () =>
- snapshot?.permissions.some(
- (permission) =>
- permission.required.length > 0 &&
- !["granted", "not_required", "unavailable"].includes(permission.status),
- ) ?? false,
- [snapshot],
- );
-
- useEffect(() => {
- if (!waitingForSystemSettings) return;
- const timer = window.setInterval(() => {
- if (document.visibilityState === "visible") void refetch();
- }, 2500);
- return () => window.clearInterval(timer);
- }, [refetch, waitingForSystemSettings]);
-
- const setupNeeded = useMemo(
- () => snapshot?.permissions.some(needsSetup) ?? false,
- [snapshot],
- );
-
- return {
- snapshot,
- loading,
- error,
- pendingId,
- refetch,
- request: async (id: PermissionId) => {
- await mutate(id, "request");
- },
- openSettings: async (id: PermissionId) => {
- await mutate(id, "open-settings");
- },
- reset: async (id: PermissionId) => {
- await mutate(id, "reset");
- },
- setupAll,
- cancelSetup,
- setupProgress,
- setupNeeded,
- };
-}
diff --git a/jarvis/ui/web/frontend/src/hooks/useRestartApp.test.tsx b/jarvis/ui/web/frontend/src/hooks/useRestartApp.test.tsx
new file mode 100644
index 0000000000..9979570bad
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useRestartApp.test.tsx
@@ -0,0 +1,60 @@
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useRestartApp } from "@/hooks/useRestartApp";
+import { useEventStore } from "@/store/events";
+
+function stubRestart(status: number, body: unknown = {}) {
+ const fetchMock = vi.fn(async () => ({ ok: status < 400, status, json: async () => body }) as Response);
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+const messages = () => useEventStore.getState().toasts.map((toast) => toast.message);
+
+describe("useRestartApp", () => {
+ beforeEach(() => useEventStore.setState({ toasts: [] }));
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ it("says what it was told to when the restart cannot start, instead of the raw error", async () => {
+ stubRestart(500);
+ const { result } = renderHook(() => useRestartApp());
+
+ await act(async () => {
+ await result.current.restart({ failureMessage: "Could not restart. Quit and reopen it manually." });
+ });
+
+ expect(messages()).toEqual(["Could not restart. Quit and reopen it manually."]);
+ expect(result.current.restarting).toBe(false);
+ });
+
+ it("keeps the raw error for callers that give no message", async () => {
+ stubRestart(500);
+ const { result } = renderHook(() => useRestartApp());
+
+ await act(async () => {
+ await result.current.restart();
+ });
+
+ expect(messages()).toEqual(["restart-failed:500"]);
+ });
+
+ it("arms a forced restart when missions are running, and resends with force", async () => {
+ const fetchMock = stubRestart(409, { detail: { missions: [{ id: "a" }, { id: "b" }] } });
+ const { result } = renderHook(() => useRestartApp());
+
+ await act(async () => {
+ await result.current.restart();
+ });
+ expect(messages()[0]).toContain("2 ");
+ expect(result.current.forceArmed).toBe(true);
+
+ await act(async () => {
+ await result.current.restart();
+ });
+ expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/restart-app?force=true", { method: "POST" });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/useRestartApp.ts b/jarvis/ui/web/frontend/src/hooks/useRestartApp.ts
index dbd255f7e0..9ca2f5e7e0 100644
--- a/jarvis/ui/web/frontend/src/hooks/useRestartApp.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useRestartApp.ts
@@ -3,6 +3,12 @@ import { useCallback, useState } from "react";
import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
+/** Options of one `restart()` call. */
+export interface RestartOptions {
+ /** Shown instead of the raw error when the restart could not be started. */
+ failureMessage?: string;
+}
+
/**
* The one-click app restart a setting needs when it cannot apply live (a bar
* <-> orb-window overlay switch, BUG-031). Shared by the display-style picker
@@ -19,7 +25,7 @@ export function useRestartApp() {
const [restarting, setRestarting] = useState(false);
const [forceArmed, setForceArmed] = useState(false);
- const restart = useCallback(async () => {
+ const restart = useCallback(async (options?: RestartOptions) => {
if (restarting) return;
setRestarting(true);
try {
@@ -46,7 +52,7 @@ export function useRestartApp() {
pushToast("info", t("taskbar_view.restarting"));
} catch (e) {
setRestarting(false);
- pushToast("error", (e as Error).message);
+ pushToast("error", options?.failureMessage ?? (e as Error).message);
}
}, [forceArmed, pushToast, restarting, t]);
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.permissions.test.tsx b/jarvis/ui/web/frontend/src/hooks/useWebSocket.permissions.test.tsx
new file mode 100644
index 0000000000..f29a74dec9
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.permissions.test.tsx
@@ -0,0 +1,296 @@
+/**
+ * The permission events and the dictation refusal reach the UI through the real
+ * useWebSocket -> WSClient path (via a MockWebSocket, like useWebSocket.test.tsx):
+ * a user-started feature that a macOS permission stopped becomes ONE toast with
+ * one button in the owner window, and a refused dictation start resets the
+ * recording pill.
+ */
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ToastLayer } from "@/components/ToastLayer";
+import { useWebSocket } from "@/hooks/useWebSocket";
+import { useI18nStore } from "@/i18n";
+import { resetPermissionToastState } from "@/lib/permissionToast";
+import { useEventStore } from "@/store/events";
+
+class MockWebSocket {
+ static OPEN = 1;
+ static CLOSED = 3;
+ readyState = MockWebSocket.OPEN;
+ static last: MockWebSocket | null = null;
+ private listeners: Record<string, Array<(ev: unknown) => void>> = {};
+ url: string;
+
+ constructor(url: string) {
+ this.url = url;
+ MockWebSocket.last = this;
+ queueMicrotask(() => this.fire("open", {}));
+ }
+
+ addEventListener(type: string, fn: (ev: unknown) => void) {
+ (this.listeners[type] ??= []).push(fn);
+ }
+
+ send = vi.fn();
+
+ close = vi.fn(() => {
+ this.readyState = MockWebSocket.CLOSED;
+ this.fire("close", {});
+ });
+
+ fire(type: string, ev: unknown) {
+ (this.listeners[type] ?? []).forEach((fn) => fn(ev));
+ }
+
+ deliver(data: unknown) {
+ this.fire("message", { data: JSON.stringify(data) });
+ }
+}
+
+function envelope(eventName: string, payload: Record<string, unknown>, trace = "trace-1") {
+ return {
+ type: "event",
+ event_name: eventName,
+ source_layer: "platform.permissions",
+ timestamp_ns: Date.now() * 1_000_000,
+ trace_id: trace,
+ payload,
+ };
+}
+
+vi.mock("@/lib/bootStagger", () => ({ bootSettled: () => Promise.resolve() }));
+
+const needed = {
+ permissions: ["microphone"],
+ feature: "dictation",
+ reason: "denied",
+ phase: "blocked",
+ origin: "user",
+ target: "",
+ can_prompt: false,
+ can_open_settings: true,
+ outside_app: false,
+ detail: "Microphone access is off.",
+};
+
+const MAC_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)";
+
+const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+
+function Harness() {
+ return (
+ <QueryClientProvider client={queryClient}>
+ <Inner />
+ <ToastLayer />
+ </QueryClientProvider>
+ );
+}
+function Inner() {
+ useWebSocket();
+ return null;
+}
+
+function embeddedMac() {
+ (window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean }).__JARVIS_EMBEDDED_DESKTOP = true;
+ vi.spyOn(window.navigator, "userAgent", "get").mockReturnValue(MAC_UA);
+}
+
+describe("useWebSocket permission wiring", () => {
+ const OriginalWS = globalThis.WebSocket;
+ let fetchMock: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ (globalThis as unknown as { WebSocket: typeof MockWebSocket }).WebSocket = MockWebSocket;
+ (window as unknown as { location: unknown }).location = { protocol: "http:", host: "localhost:5173" };
+ fetchMock = vi.fn(async () => ({ ok: true, status: 200, json: async () => ({}) }) as Response);
+ vi.stubGlobal("fetch", fetchMock);
+ useI18nStore.getState().setUi("en", { push: false });
+ useEventStore.setState({ dictating: false, toasts: [], solo: false });
+ resetPermissionToastState();
+ queryClient.clear();
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete (window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean }).__JARVIS_EMBEDDED_DESKTOP;
+ (globalThis as unknown as { WebSocket: typeof WebSocket }).WebSocket = OriginalWS;
+ MockWebSocket.last = null;
+ });
+
+ it("a user-started feature stopped by a denied microphone becomes one toast with one action", async () => {
+ embeddedMac();
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(envelope("PermissionNeeded", needed));
+
+ expect(await screen.findByText("Personal Jarvis needs microphone access to hear you.")).toBeTruthy();
+ expect(screen.getAllByTestId("toast-action")).toHaveLength(1);
+ expect(screen.getByTestId("toast-action").textContent).toBe("Open System Settings");
+ });
+
+ it("the same episode is told once, and again after PermissionResolved ends it", async () => {
+ embeddedMac();
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(envelope("PermissionNeeded", needed));
+ MockWebSocket.last!.deliver(envelope("PermissionNeeded", needed));
+ expect(useEventStore.getState().toasts).toHaveLength(1);
+ expect(useEventStore.getState().toasts[0].count).toBe(1);
+
+ // A grant takes the stale sentence down ...
+ MockWebSocket.last!.deliver(
+ envelope("PermissionResolved", { permissions: ["microphone"], feature: "dictation", granted: true }),
+ );
+ expect(useEventStore.getState().toasts).toEqual([]);
+
+ // ... and a later denial of the same episode is news again.
+ MockWebSocket.last!.deliver(envelope("PermissionNeeded", needed));
+ expect(useEventStore.getState().toasts).toHaveLength(1);
+ });
+
+ it("says nothing while macOS is asking, for a background consumer, or outside the owner window", async () => {
+ embeddedMac();
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(envelope("PermissionNeeded", { ...needed, phase: "os_dialog", reason: "not_determined" }));
+ MockWebSocket.last!.deliver(envelope("PermissionNeeded", { ...needed, feature: "screen_context", origin: "background" }));
+ expect(useEventStore.getState().toasts).toEqual([]);
+
+ useEventStore.setState({ solo: true });
+ MockWebSocket.last!.deliver(envelope("PermissionNeeded", needed));
+ expect(useEventStore.getState().toasts).toEqual([]);
+ });
+
+ it("says nothing in a plain browser, even on a Mac (it would open Settings on another computer)", async () => {
+ vi.spyOn(window.navigator, "userAgent", "get").mockReturnValue(MAC_UA);
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(envelope("PermissionNeeded", needed));
+
+ expect(useEventStore.getState().toasts).toEqual([]);
+ });
+
+ it("on connect the owner window only READS the open episodes: nothing is asked at launch", async () => {
+ embeddedMac();
+ fetchMock.mockImplementation(
+ async () =>
+ ({ ok: true, status: 200, json: async () => ({ needed: [] }) }) as Response,
+ );
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver({ type: "welcome", session_id: "s1" });
+ await waitFor(() =>
+ expect(fetchMock.mock.calls.some(([url]) => String(url) === "/api/permissions/status")).toBe(true),
+ );
+
+ const permissionCalls = fetchMock.mock.calls.filter(([url]) => String(url).startsWith("/api/permissions"));
+ expect(permissionCalls.map(([url, init]) => [String(url), (init as RequestInit | undefined)?.method ?? "GET"])).toEqual([
+ ["/api/permissions/status", "GET"],
+ ]);
+ });
+
+ it("does not read the permission API at all in a window that cannot toast", async () => {
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver({ type: "welcome", session_id: "s1" });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(fetchMock.mock.calls.some(([url]) => String(url).startsWith("/api/permissions"))).toBe(false);
+ });
+
+ it("tells an episode that opened while no window was listening, once per page load", async () => {
+ embeddedMac();
+ const wake = { ...needed, feature: "wake_word", origin: "background" };
+ fetchMock.mockImplementation(
+ async (url: unknown) =>
+ ({
+ ok: true,
+ status: 200,
+ json: async () => (String(url) === "/api/permissions/status" ? { needed: [needed, wake] } : {}),
+ }) as Response,
+ );
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver({ type: "welcome", session_id: "s1" });
+ await waitFor(() => expect(useEventStore.getState().toasts.length).toBeGreaterThan(0));
+ expect(await screen.findByText("Personal Jarvis needs microphone access to hear you.")).toBeTruthy();
+ expect(screen.getByText(/The wake word cannot listen/)).toBeTruthy();
+
+ // The person lets them expire; the socket reconnects: nothing is repeated.
+ useEventStore.setState({ toasts: [] });
+ MockWebSocket.last!.deliver({ type: "welcome", session_id: "s1" });
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(useEventStore.getState().toasts).toEqual([]);
+ });
+
+ it("DictationRefused ends a recording the composer started", async () => {
+ useEventStore.setState({ dictating: true });
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(
+ envelope("DictationRefused", { reason: "microphone_unavailable", detail: "Microphone access is off." }),
+ );
+
+ expect(useEventStore.getState().dictating).toBe(false);
+ });
+
+ it.each(["already_running", "nothing_to_paste", "paste_unavailable", "history_disabled"])(
+ "a %s refusal does not end a recording that is live in this window",
+ async (reason) => {
+ useEventStore.setState({ dictating: true });
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(envelope("DictationRefused", { reason, detail: "" }));
+
+ expect(useEventStore.getState().dictating).toBe(true);
+ },
+ );
+
+ it.each(["microphone_unavailable", "no_stt", "handover_failed", "pipeline_not_running", "voice_session_active"])(
+ "a %s refusal means the start failed and resets the pill",
+ async (reason) => {
+ useEventStore.setState({ dictating: true });
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(envelope("DictationRefused", { reason, detail: "" }));
+
+ expect(useEventStore.getState().dictating).toBe(false);
+ },
+ );
+
+ it("ErrorOccurred from ui.web.dictation also stops the recording pill", async () => {
+ useEventStore.setState({ dictating: true });
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(
+ envelope("ErrorOccurred", { layer: "ui.web.dictation", error_type: "DictationBusy", message: "busy", recoverable: true }),
+ );
+
+ expect(useEventStore.getState().dictating).toBe(false);
+ });
+
+ it("an ErrorOccurred from another layer is not a dictation refusal", async () => {
+ useEventStore.setState({ dictating: true });
+ render(<Harness />);
+ await Promise.resolve();
+
+ MockWebSocket.last!.deliver(envelope("ErrorOccurred", { layer: "brain", message: "x", recoverable: true }));
+
+ expect(useEventStore.getState().dictating).toBe(true);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
index a57857cd8a..c361417208 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
@@ -24,6 +24,8 @@ import {
useCommandActivityStore,
COMMAND_ACTIVITY_EVENTS,
} from "@/store/commandActivity";
+import { isDictationStartFailure } from "@/lib/dictationRefusal";
+import { usePermissionToast } from "@/hooks/usePermissionToast";
import { useDeckStore } from "@/store/deck";
import { useHomeStore } from "@/store/home";
import { PANE_ACTIVITY_EVENT } from "@/store/workspacePanes";
@@ -64,6 +66,7 @@ export function useWebSocket(): void {
const setActiveSection = useEventStore((s) => s.setActiveSection);
const setBrainProvider = useEventStore((s) => s.setBrainProvider);
const pushToast = useEventStore((s) => s.pushToast);
+ const { onEvent: onPermissionEvent, seed: seedPermissionToast } = usePermissionToast();
useEffect(() => {
if (mounted.current) return;
@@ -115,6 +118,11 @@ export function useWebSocket(): void {
// authoritative "backend is up" signal — useAssistantNameSeed
// listens for this event and re-fetches the resolved name.
window.dispatchEvent(new CustomEvent("jarvis:assistant-name-changed"));
+ // Re-seed the permission toast on EVERY (re)connect too: a
+ // PermissionNeeded published while no window was connected (autostart
+ // with the window hidden, a wake-word denial before the socket opened)
+ // is a one-shot bus event and would otherwise never be told.
+ seedPermissionToast();
return;
}
@@ -181,6 +189,27 @@ export function useWebSocket(): void {
);
}
+ // A feature a macOS permission stopped: ONE toast with one button, only
+ // in the owner window and only when the person started the feature
+ // (lib/permissionToast). It reads just these two events.
+ if (env.event_name === "PermissionNeeded" || env.event_name === "PermissionResolved") {
+ onPermissionEvent(env.event_name, env.payload);
+ }
+
+ // A dictation that could not start. The composer set `dictating`
+ // optimistically when the person pressed the mic, so without this the
+ // recording pill sticks with a waveform. Only a window that IS
+ // dictating reacts.
+ if (
+ (env.event_name === "DictationRefused" &&
+ isDictationStartFailure((env.payload as { reason?: unknown }).reason)) ||
+ (env.event_name === "ErrorOccurred" &&
+ (env.payload as { layer?: unknown }).layer === "ui.web.dictation")
+ ) {
+ const store = useEventStore.getState();
+ if (store.dictating) store.setDictating(false);
+ }
+
// Mission deck: cost, computer-use, capture, terminals, wiki, words.
// The reducer hands back the same object for every event it does not
// read, so this is one cheap call, not a re-render per event.
@@ -747,6 +776,8 @@ export function useWebSocket(): void {
setActiveSection,
setBrainProvider,
pushToast,
+ onPermissionEvent,
+ seedPermissionToast,
queryClient,
]);
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 1610e9b4b5..9330189df8 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -588,6 +588,7 @@
"realtime_microphone_unavailable": "Dieser Browser kann nicht auf ein Mikrofon zugreifen. Prüfe Browserunterstützung und Geräteeinstellungen.",
"realtime_audio_worklet_unavailable": "Dieser Browser unterstützt den benötigten Audioprozessor nicht. Aktualisiere den Browser.",
"realtime_microphone_denied": "Der Mikrofonzugriff wurde verweigert. Erlaube ihn in den Website-Einstellungen des Browsers und versuche es erneut.",
+ "realtime_microphone_denied_desktop": "Der Mikrofonzugriff wurde verweigert. Erlaube ihn in den Systemeinstellungen deines Computers und versuche es erneut.",
"realtime_browser_tts_unavailable": "Dieser Browser hat keine nutzbare Systemstimme. Die Antwort bleibt als Text verfügbar; verbinde für Audio einen TTS-Anbieter.",
"realtime_pipeline_fallback": "Klassische Pipeline als Fallback",
"realtime_unavailable": "Realtime-Anbieter verbinden oder einrichten",
@@ -2252,87 +2253,33 @@
"vision_note": "Es werden nur Modelle angezeigt, die Bilder verstehen - Computer-Use liest den Bildschirm über Screenshots, ein reines Text-Modell kann es nicht steuern."
},
"permissions": {
- "group_title": "Datenschutz-Berechtigungen",
- "title": "macOS-Berechtigungen",
- "description": "Erteile nur die Systemzugriffe, die für Sprache, Computer-Use, globale Kurzbefehle und Fenstersteuerung nötig sind. Jarvis verändert niemals die macOS-Datenschutzdatenbank.",
- "loading": "Systemberechtigungen werden geprüft…",
- "load_failed": "Der aktuelle Berechtigungsstatus konnte nicht gelesen werden.",
- "refresh": "Erneut prüfen",
- "not_required": "Auf diesem Betriebssystem sind keine zusätzlichen Desktop-Datenschutzberechtigungen nötig.",
- "identity_warning": "Starte Personal Jarvis aus seinem App-Bundle, bevor du Zugriff erlaubst. macOS bindet Berechtigungen an die genaue App-Identität.",
- "restart_required": "Starte Personal Jarvis neu, bevor du den neu erlaubten Zugriff verwendest.",
- "restart_now": "Jetzt neu starten",
- "restarting": "Neustart…",
"restart_failed": "Personal Jarvis konnte nicht neu starten. Beende und öffne es manuell erneut.",
- "request": "Erlauben",
- "open_settings": "Einstellungen öffnen",
- "status": {
- "granted": "Erlaubt",
- "not_determined": "Nicht angefragt",
- "denied": "Abgelehnt",
- "restricted": "Eingeschränkt",
- "not_granted": "Nicht erlaubt",
- "unavailable": "Nicht verfügbar",
- "not_required": "Nicht erforderlich",
- "restart_pending": "Neustart ausstehend"
- },
- "items": {
- "microphone": {
- "title": "Mikrofon",
- "description": "Erforderlich für Aktivierungswort und lokale Spracheingabe."
- },
- "screen_recording": {
- "title": "Bildschirmaufnahme",
- "description": "Erforderlich, damit Computer-Use alle verbundenen Bildschirme sehen kann."
- },
- "accessibility": {
- "title": "Bedienungshilfen",
- "description": "Erforderlich für zuverlässige Klicks, Eingaben, Fokus und Fenstersteuerung."
- },
- "input_monitoring": {
- "title": "Eingabeüberwachung",
- "description": "Erforderlich für globale Tastaturkurzbefehle."
+ "toast": {
+ "microphone": "Personal Jarvis braucht Zugriff auf das Mikrofon, um dich zu hören.",
+ "screen_recording": "Personal Jarvis braucht Zugriff auf die Bildschirmaufnahme, um deinen Bildschirm zu sehen.",
+ "accessibility": "Personal Jarvis braucht Zugriff auf die Bedienungshilfen, um andere Apps für dich zu steuern.",
+ "input_monitoring": "Personal Jarvis braucht Zugriff auf die Eingabeüberwachung, damit deine Kürzel auch in anderen Apps funktionieren.",
+ "automation": "Personal Jarvis braucht deine Erlaubnis, eine andere App zu steuern.",
+ "generic": "Personal Jarvis braucht dafür eine weitere Berechtigung.",
+ "restricted": "Dein Mac erlaubt Personal Jarvis den Zugriff auf {what} nicht. Das kann nur ein Administrator ändern.",
+ "restart": "Der Zugriff auf {what} ist an, wirkt aber erst, wenn Personal Jarvis neu startet.",
+ "outside": "Personal Jarvis braucht Zugriff auf {what}; da es nicht als App installiert ist, gibt macOS den Zugriff an die App, die es gestartet hat.",
+ "wake_word": "Das Wake-Word kann nicht zuhören: Der Mikrofonzugriff ist für Personal Jarvis ausgeschaltet.",
+ "action_failed": "Das hat nicht geklappt. Bitte öffne die Systemeinstellungen selbst.",
+ "name": {
+ "microphone": "das Mikrofon",
+ "screen_recording": "die Bildschirmaufnahme",
+ "accessibility": "die Bedienungshilfen",
+ "input_monitoring": "die Eingabeüberwachung",
+ "automation": "die Automation",
+ "generic": "diese Funktion"
},
- "event_posting": {
- "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."
+ "action": {
+ "open_settings": "Systemeinstellungen öffnen",
+ "ask_now": "macOS jetzt fragen",
+ "restart": "Beenden und neu öffnen"
}
- },
- "banner": {
- "title": "Aktion nötig: macOS-Berechtigungen fehlen",
- "impact": "Funktioniert gerade nicht: {0}",
- "hint": "Erlaube den Zugriff über die Buttons — macOS öffnet für jede Berechtigung direkt die richtige Seite der Systemeinstellungen. {name} prüft automatisch nach.",
- "collapse": "Details ausblenden",
- "expand": "Details anzeigen"
- },
- "features": {
- "voice": "Sprache & Aktivierungswort",
- "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.",
- "setup_all": "Alles einrichten",
- "setup_all_hint": "Ein Klick führt dich durch alle fehlenden Berechtigungen und übernimmt sie am Ende.",
- "setup_running": "Schritt {0} von {1}: {2}",
- "setup_wait_prompt": "Beantworte den macOS-Dialog — es geht automatisch weiter.",
- "setup_wait_settings": "Schalte Personal Jarvis in der gerade geöffneten Systemeinstellungen-Seite ein und komm zurück — es geht automatisch weiter.",
- "setup_cancel": "Abbrechen",
- "setup_restarting": "Fertig — Personal Jarvis startet einmal neu, um den neuen Zugriff zu übernehmen.",
- "setup_timeout": "Einrichtung pausiert: Eine Berechtigung wurde nicht rechtzeitig erteilt. Nutze „Alles einrichten“ jederzeit erneut.",
- "ask_again": "Erneut fragen",
- "stale_grant_hint": "macOS fragt für diesen Zugriff nicht mehr nach. Steht der Haken in den Systemeinstellungen schon, gehört er zu einer älteren Version der App — tippe auf „Erneut fragen“ und erlaube den Zugriff danach neu.",
- "identity_reset": "macOS sieht Personal Jarvis seit dem letzten Neuaufbau der App als neue App an und hat dabei alle erteilten Zugriffe verworfen. Bitte einmal neu erlauben — danach bleiben sie erhalten."
+ }
},
"settings_hub": {
"subtitle": "Alles über dich, deine Schlüssel und diese App — an einem Ort.",
@@ -2400,7 +2347,6 @@
"nav": {
"languages": "Sprachen",
"app": "App",
- "permissions": "Datenschutz-Freigaben",
"screen_context": "Bildschirmkontext",
"realtime_voice": "Realtime-Stimme",
"system_prompt": "Systemprompt",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index c631d3045a..619cb435d4 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -588,6 +588,7 @@
"realtime_microphone_unavailable": "This browser cannot access a microphone. Check browser support and device settings.",
"realtime_audio_worklet_unavailable": "This browser does not support the required audio processor. Update the browser.",
"realtime_microphone_denied": "Microphone access was denied. Allow it in the browser's site settings, then retry.",
+ "realtime_microphone_denied_desktop": "Microphone access was denied. Allow it in your computer's system settings, then retry.",
"realtime_browser_tts_unavailable": "This browser has no usable system voice. The answer is still available as text; connect a TTS provider for audio.",
"realtime_pipeline_fallback": "Classic pipeline fallback",
"realtime_unavailable": "Connect or configure a Realtime provider",
@@ -2252,87 +2253,33 @@
"vision_note": "Only models that can see images are listed - Computer-Use reads the screen from screenshots, so a text-only model cannot run it."
},
"permissions": {
- "group_title": "Privacy permissions",
- "title": "macOS permissions",
- "description": "Grant only the system access needed for voice, Computer-Use, global shortcuts, and window control. Jarvis never edits the macOS privacy database.",
- "loading": "Checking system permissions…",
- "load_failed": "Could not read the current permission status.",
- "refresh": "Check again",
- "not_required": "No extra desktop privacy permissions are required on this operating system.",
- "identity_warning": "Launch Personal Jarvis from its app bundle before granting access. macOS attaches permissions to the exact app identity.",
- "restart_required": "Restart Personal Jarvis before using the newly granted access.",
- "restart_now": "Restart now",
- "restarting": "Restarting…",
"restart_failed": "Personal Jarvis could not restart. Quit and reopen it manually.",
- "request": "Allow",
- "open_settings": "Open Settings",
- "status": {
- "granted": "Allowed",
- "not_determined": "Not requested",
- "denied": "Denied",
- "restricted": "Restricted",
- "not_granted": "Not allowed",
- "unavailable": "Unavailable",
- "not_required": "Not required",
- "restart_pending": "Restart pending"
- },
- "items": {
- "microphone": {
- "title": "Microphone",
- "description": "Required for wake-word and local voice input."
- },
- "screen_recording": {
- "title": "Screen Recording",
- "description": "Required for Computer-Use to see every connected display."
- },
- "accessibility": {
- "title": "Accessibility",
- "description": "Required for reliable clicks, typing, focus, and window control."
- },
- "input_monitoring": {
- "title": "Input Monitoring",
- "description": "Required for global keyboard shortcuts."
+ "toast": {
+ "microphone": "Personal Jarvis needs microphone access to hear you.",
+ "screen_recording": "Personal Jarvis needs screen recording access to see your screen.",
+ "accessibility": "Personal Jarvis needs accessibility access to control other apps for you.",
+ "input_monitoring": "Personal Jarvis needs input monitoring access so your shortcuts work in other apps.",
+ "automation": "Personal Jarvis needs your permission to control another app.",
+ "generic": "Personal Jarvis needs another permission to do that.",
+ "restricted": "Your Mac does not allow Personal Jarvis to use {what}. Only an administrator can change that.",
+ "restart": "Access to {what} is on, but it only works after Personal Jarvis restarts.",
+ "outside": "Personal Jarvis needs access to {what}; as it is not an installed app, macOS gives that access to the app that started it.",
+ "wake_word": "The wake word cannot listen: microphone access is off for Personal Jarvis.",
+ "action_failed": "That did not work. Please open System Settings yourself.",
+ "name": {
+ "microphone": "the microphone",
+ "screen_recording": "screen recording",
+ "accessibility": "accessibility",
+ "input_monitoring": "input monitoring",
+ "automation": "automation",
+ "generic": "this feature"
},
- "event_posting": {
- "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."
+ "action": {
+ "open_settings": "Open System Settings",
+ "ask_now": "Ask macOS now",
+ "restart": "Quit and reopen"
}
- },
- "banner": {
- "title": "Action needed: macOS permissions are missing",
- "impact": "Not working right now: {0}",
- "hint": "Use the buttons to allow access — macOS opens the right System Settings page for each permission. {name} re-checks automatically.",
- "collapse": "Hide details",
- "expand": "Show details"
- },
- "features": {
- "voice": "Voice & wake word",
- "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.",
- "setup_all": "Set up everything",
- "setup_all_hint": "One click walks you through every remaining permission and applies them at the end.",
- "setup_running": "Step {0} of {1}: {2}",
- "setup_wait_prompt": "Answer the macOS dialog — this continues on its own.",
- "setup_wait_settings": "Turn on Personal Jarvis in the System Settings pane that just opened, then come back — this continues on its own.",
- "setup_cancel": "Stop",
- "setup_restarting": "All set — Personal Jarvis restarts once to apply the new access.",
- "setup_timeout": "Setup paused: a permission was not granted in time. Use “Set up everything” again whenever you like.",
- "ask_again": "Ask again",
- "stale_grant_hint": "macOS will not ask for this access again. If System Settings already shows it as enabled, that record belongs to an older version of the app — tap “Ask again” and allow access once more.",
- "identity_reset": "Since the app was last rebuilt, macOS treats Personal Jarvis as a new app and discarded every access you had granted. Please allow them once more — they will stick from then on."
+ }
},
"settings_hub": {
"subtitle": "Everything about you, your keys and this app — in one place.",
@@ -2400,7 +2347,6 @@
"nav": {
"languages": "Languages",
"app": "App",
- "permissions": "Privacy permissions",
"screen_context": "Screen context",
"realtime_voice": "Realtime voice",
"system_prompt": "System prompt",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 5e452cb2dd..99f3e54173 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -588,6 +588,7 @@
"realtime_microphone_unavailable": "Este navegador no puede acceder a un micrófono. Comprueba la compatibilidad del navegador y la configuración del dispositivo.",
"realtime_audio_worklet_unavailable": "Este navegador no admite el procesador de audio necesario. Actualiza el navegador.",
"realtime_microphone_denied": "Se denegó el acceso al micrófono. Permítelo en la configuración del sitio del navegador y vuelve a intentarlo.",
+ "realtime_microphone_denied_desktop": "Se denegó el acceso al micrófono. Permítelo en los ajustes del sistema de tu ordenador y vuelve a intentarlo.",
"realtime_browser_tts_unavailable": "Este navegador no tiene una voz del sistema utilizable. La respuesta sigue disponible como texto; conecta un proveedor de TTS para oírla.",
"realtime_pipeline_fallback": "Sistema de voz clásico como alternativa",
"realtime_unavailable": "Conecta o configura un proveedor de tiempo real",
@@ -2252,87 +2253,33 @@
"vision_note": "Solo se muestran modelos que entienden imágenes: Computer-Use lee la pantalla mediante capturas, un modelo de solo texto no puede controlarlo."
},
"permissions": {
- "group_title": "Permisos de privacidad",
- "title": "Permisos de macOS",
- "description": "Concede solo el acceso del sistema necesario para voz, Computer-Use, atajos globales y control de ventanas. Jarvis nunca modifica la base de datos de privacidad de macOS.",
- "loading": "Comprobando los permisos del sistema…",
- "load_failed": "No se pudo leer el estado actual de los permisos.",
- "refresh": "Comprobar de nuevo",
- "not_required": "Este sistema operativo no requiere permisos de privacidad de escritorio adicionales.",
- "identity_warning": "Inicia Personal Jarvis desde su paquete de aplicación antes de conceder acceso. macOS vincula los permisos a la identidad exacta de la aplicación.",
- "restart_required": "Reinicia Personal Jarvis antes de usar el acceso recién concedido.",
- "restart_now": "Reiniciar ahora",
- "restarting": "Reiniciando…",
"restart_failed": "Personal Jarvis no pudo reiniciarse. Ciérralo y ábrelo de nuevo manualmente.",
- "request": "Permitir",
- "open_settings": "Abrir Ajustes",
- "status": {
- "granted": "Permitido",
- "not_determined": "No solicitado",
- "denied": "Denegado",
- "restricted": "Restringido",
- "not_granted": "No permitido",
- "unavailable": "No disponible",
- "not_required": "No requerido",
- "restart_pending": "Reinicio pendiente"
- },
- "items": {
- "microphone": {
- "title": "Micrófono",
- "description": "Necesario para la palabra de activación y la entrada de voz local."
- },
- "screen_recording": {
- "title": "Grabación de pantalla",
- "description": "Necesario para que Computer-Use vea todas las pantallas conectadas."
- },
- "accessibility": {
- "title": "Accesibilidad",
- "description": "Necesario para clics, escritura, enfoque y control de ventanas fiables."
- },
- "input_monitoring": {
- "title": "Monitorización de entrada",
- "description": "Necesario para los atajos de teclado globales."
+ "toast": {
+ "microphone": "Personal Jarvis necesita acceso al micrófono para oírte.",
+ "screen_recording": "Personal Jarvis necesita acceso a la grabación de pantalla para ver tu pantalla.",
+ "accessibility": "Personal Jarvis necesita acceso a la accesibilidad para controlar otras apps.",
+ "input_monitoring": "Personal Jarvis necesita acceso a la monitorización de entrada para que tus atajos funcionen en otras apps.",
+ "automation": "Personal Jarvis necesita tu permiso para controlar otra app.",
+ "generic": "Personal Jarvis necesita otro permiso para hacer eso.",
+ "restricted": "Tu Mac no permite que Personal Jarvis use {what}. Solo un administrador puede cambiarlo.",
+ "restart": "El acceso a {what} está activado, pero solo funciona cuando Personal Jarvis se reinicia.",
+ "outside": "Personal Jarvis necesita acceso a {what}; como no es una app instalada, macOS da ese acceso a la app que lo inició.",
+ "wake_word": "La palabra de activación no puede escuchar: el acceso al micrófono está desactivado para Personal Jarvis.",
+ "action_failed": "No funcionó. Abre Ajustes del Sistema manualmente.",
+ "name": {
+ "microphone": "el micrófono",
+ "screen_recording": "la grabación de pantalla",
+ "accessibility": "la accesibilidad",
+ "input_monitoring": "la monitorización de entrada",
+ "automation": "la automatización",
+ "generic": "esta función"
},
- "event_posting": {
- "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."
+ "action": {
+ "open_settings": "Abrir Ajustes del Sistema",
+ "ask_now": "Preguntar a macOS ahora",
+ "restart": "Salir y volver a abrir"
}
- },
- "banner": {
- "title": "Acción necesaria: faltan permisos de macOS",
- "impact": "Ahora mismo no funciona: {0}",
- "hint": "Permite el acceso con los botones: macOS abre directamente la página correcta de Ajustes del Sistema para cada permiso. {name} vuelve a comprobarlo automáticamente.",
- "collapse": "Ocultar detalles",
- "expand": "Mostrar detalles"
- },
- "features": {
- "voice": "Voz y palabra de activación",
- "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.",
- "setup_all": "Configurar todo",
- "setup_all_hint": "Un clic te guía por todos los permisos que faltan y los aplica al final.",
- "setup_running": "Paso {0} de {1}: {2}",
- "setup_wait_prompt": "Responde al diálogo de macOS — continúa solo.",
- "setup_wait_settings": "Activa Personal Jarvis en el panel de Ajustes del Sistema que se acaba de abrir y vuelve — continúa solo.",
- "setup_cancel": "Detener",
- "setup_restarting": "Listo — Personal Jarvis se reinicia una vez para aplicar el nuevo acceso.",
- "setup_timeout": "Configuración en pausa: un permiso no se concedió a tiempo. Usa «Configurar todo» de nuevo cuando quieras.",
- "ask_again": "Preguntar de nuevo",
- "stale_grant_hint": "macOS ya no volverá a preguntar por este acceso. Si Ajustes del Sistema ya lo muestra activado, ese registro pertenece a una versión anterior de la app: pulsa «Preguntar de nuevo» y concede el acceso otra vez.",
- "identity_reset": "Desde la última reconstrucción, macOS considera Personal Jarvis una app nueva y descartó todos los accesos concedidos. Vuelve a concederlos una vez; a partir de ahí se mantendrán."
+ }
},
"settings_hub": {
"subtitle": "Todo sobre ti, tus claves y esta aplicación, en un lugar.",
@@ -2400,7 +2347,6 @@
"nav": {
"languages": "Idiomas",
"app": "Aplicación",
- "permissions": "Permisos de privacidad",
"screen_context": "Contexto de pantalla",
"realtime_voice": "Voz en tiempo real",
"system_prompt": "Prompt del sistema",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/de.json b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/de.json
index 0139b46c7e..2427a325dd 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/de.json
@@ -57,14 +57,9 @@
"why": "Ein Abo ist ein fester Monatspreis. Ohne Abo nutzen die Agents deinen API-Schlüssel, und jeder Auftrag wird einzeln abgerechnet.",
"later": "Ich verbinde später eins"
},
- "permissions": {
- "title": "Zugriff auf diesem Mac erlauben",
- "lede": "Das sind die Mac-Berechtigungen. Erlaube die, die du möchtest; jede Zeile aktualisiert sich selbst.",
- "note": "Du kannst jederzeit in den Einstellungen zurückkommen. Der Neustart am Ende wendet sie an."
- },
"voice": {
"title": "Wähle dein Weckwort",
- "lede": "Tippe hier dein Wort nach „Hey“ ein und speichere es. Das Wort wird auch der Name deines Assistenten. Kein Weckwort? Das Anruf-Kürzel funktioniert immer.",
+ "lede": "Tippe hier dein Wort nach „Hey“ ein und speichere es. Das Wort wird auch der Name deines Assistenten. Kein Weckwort? Das Anruf-Kürzel funktioniert jederzeit.",
"on": "„{phrase}“ ist an. Sag es jederzeit.",
"off": "Noch kein Weckwort. Bis dahin funktioniert das Anruf-Kürzel.",
"later": "Überspringen, ich nutze das Anruf-Kürzel"
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/en.json b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/en.json
index dadc8a0dcb..b441c68ded 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/en.json
@@ -57,11 +57,6 @@
"why": "A subscription is a flat monthly price. Without one, agents use your API key and each job is billed per use.",
"later": "I'll connect one later"
},
- "permissions": {
- "title": "Allow access on this Mac",
- "lede": "These are the Mac permissions. Allow the ones you want; each row updates by itself.",
- "note": "You can come back to them anytime in Settings. The restart at the end applies them."
- },
"voice": {
"title": "Choose your wake word",
"lede": "Type your word after \"Hey\" here and save it. The word also becomes the assistant's name. No wake word? The Call shortcut works anytime.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/es.json b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/es.json
index fd6603ebd5..deb88d8b04 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/onboarding/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/onboarding/es.json
@@ -57,14 +57,9 @@
"why": "Una suscripción es un precio mensual fijo. Sin ella, los agentes usan tu clave de API y cada encargo se cobra por uso.",
"later": "Conectaré una más tarde"
},
- "permissions": {
- "title": "Permitir acceso en este Mac",
- "lede": "Estos son los permisos del Mac. Permite los que quieras; cada fila se actualiza sola.",
- "note": "Puedes volver a ellos cuando quieras en Ajustes. El reinicio final los aplica."
- },
"voice": {
"title": "Elige tu palabra de activación",
- "lede": "Escribe aquí tu palabra después de «Hey» y guárdala. La palabra también será el nombre de tu asistente. ¿Sin palabra? El atajo de llamada funciona siempre.",
+ "lede": "Escribe aquí tu palabra después de «Hey» y guárdala. La palabra también será el nombre de tu asistente. ¿Sin palabra? El atajo de llamada funciona en cualquier momento.",
"on": "«{phrase}» está activada. Dila cuando quieras.",
"off": "Aún no hay palabra de activación. Mientras tanto funciona el atajo de llamada.",
"later": "Omitir, usaré el atajo de llamada"
diff --git a/jarvis/ui/web/frontend/src/lib/dictationRefusal.ts b/jarvis/ui/web/frontend/src/lib/dictationRefusal.ts
new file mode 100644
index 0000000000..907119a60a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/dictationRefusal.ts
@@ -0,0 +1,27 @@
+/**
+ * Which `DictationRefused` reasons mean "the start did not happen".
+ *
+ * The composer sets `dictating` optimistically when the person presses the mic,
+ * so a refused start must reset it or the recording pill sticks with a
+ * waveform. Only the tokens below may do that: the others (`already_running`,
+ * and the post-recording `nothing_to_paste`, `paste_unavailable`,
+ * `history_disabled`) come from another trigger or from a recording that is
+ * over, and must not drop a live pill. The composer's own start that hits an
+ * already-running dictation arrives as an `ErrorOccurred` of layer
+ * `ui.web.dictation`, which resets separately (see `useWebSocket`).
+ *
+ * A Python parity test (`tests/unit/ui/web/test_dictation_start_failures_parity.py`)
+ * regex-reads the set below and checks every token is a refusal reason the
+ * backend can send (`DICTATION_REFUSAL_REASONS`, AP-4): keep it a flat literal.
+ */
+export const DICTATION_START_FAILURES: ReadonlySet<string> = new Set([
+ "microphone_unavailable",
+ "no_stt",
+ "handover_failed",
+ "pipeline_not_running",
+ "voice_session_active",
+]);
+
+export function isDictationStartFailure(reason: unknown): boolean {
+ return typeof reason === "string" && DICTATION_START_FAILURES.has(reason);
+}
diff --git a/jarvis/ui/web/frontend/src/lib/embeddedDesktop.ts b/jarvis/ui/web/frontend/src/lib/embeddedDesktop.ts
new file mode 100644
index 0000000000..a1df214c12
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/embeddedDesktop.ts
@@ -0,0 +1,39 @@
+/** True only inside a pywebview host, never from the backend's machine flag.
+ *
+ * A normal Chrome window can connect to the same local desktop backend, where
+ * `native_file_actions` is also true. Checking the client bridge keeps browser
+ * microphone control visible there without enabling a second microphone in the
+ * embedded desktop window.
+ */
+export function hasEmbeddedDesktopBridge(): boolean {
+ const host = window as unknown as {
+ __JARVIS_EMBEDDED_DESKTOP?: boolean;
+ pywebview?: { api?: unknown };
+ chrome?: { webview?: { postMessage?: unknown } };
+ webkit?: { messageHandlers?: Record<string, unknown> };
+ };
+ return Boolean(
+ host.__JARVIS_EMBEDDED_DESKTOP ||
+ host.pywebview?.api ||
+ typeof host.chrome?.webview?.postMessage === "function" ||
+ host.webkit?.messageHandlers?.jarvisFileDrag,
+ );
+}
+
+/** Clients whose user agent says macOS (the embedded WebView and Safari/Chrome on a Mac). */
+export function isMacClient(userAgent: string): boolean {
+ return /Macintosh|Mac OS X/i.test(userAgent);
+}
+
+/**
+ * True in the embedded desktop window of a Mac: the one place where a macOS
+ * permission is the host's own, so asking for it or opening System Settings acts
+ * on the computer in front of the person. A remote browser (another computer) and
+ * Windows or Linux never qualify. Read at call time: the desktop shell injects
+ * the bridge flag AFTER the page loads.
+ */
+export function isEmbeddedMacWindow(): boolean {
+ return (
+ typeof navigator !== "undefined" && isMacClient(navigator.userAgent) && hasEmbeddedDesktopBridge()
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/lib/permissionEvents.ts b/jarvis/ui/web/frontend/src/lib/permissionEvents.ts
new file mode 100644
index 0000000000..b4734442bd
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/permissionEvents.ts
@@ -0,0 +1,70 @@
+/**
+ * Permission event vocabulary — the TypeScript mirror (five-layer pattern L4)
+ * of the tuples in `jarvis/core/events.py` (`PERMISSION_FEATURES`,
+ * `PERMISSION_NEEDED_REASONS`, `PERMISSION_NEEDED_PHASES`,
+ * `PERMISSION_NEEDED_ORIGINS`). A Python parity test
+ * (`tests/unit/core/test_permission_events.py`) regex-extracts the tuples below
+ * and fails when they drift, so a feature or reason cannot be spelled one way
+ * on the bus and another in the UI copy.
+ *
+ * Declarations only, no logic: `permissionToast.ts` reads these events.
+ */
+
+/** Product features that can ask for an OS permission. */
+export const PERMISSION_FEATURES = [
+ "voice",
+ "dictation",
+ "wake_word",
+ "computer_use",
+ "screen_context",
+ "appshot",
+ "window_control",
+ "dictation_insert",
+ "global_shortcuts",
+ "audio_ducking",
+ "browser_voice",
+] as const;
+export type PermissionFeature = (typeof PERMISSION_FEATURES)[number];
+
+/** Why a feature is waiting on a permission. */
+export const PERMISSION_NEEDED_REASONS = [
+ "not_determined",
+ "denied",
+ "restricted",
+ "needs_settings",
+ "restart_hint",
+ "unavailable",
+] as const;
+export type PermissionNeededReason = (typeof PERMISSION_NEEDED_REASONS)[number];
+
+/** Where an episode is in front of the user: macOS is asking, or the user must act. */
+export const PERMISSION_NEEDED_PHASES = ["os_dialog", "blocked"] as const;
+export type PermissionNeededPhase = (typeof PERMISSION_NEEDED_PHASES)[number];
+
+/** What caused the episode: a user gesture, or a background consumer. */
+export const PERMISSION_NEEDED_ORIGINS = ["user", "background"] as const;
+export type PermissionNeededOrigin = (typeof PERMISSION_NEEDED_ORIGINS)[number];
+
+/** Payload of the `PermissionNeeded` WS event (`jarvis.core.events.PermissionNeeded`). */
+export interface PermissionNeededPayload {
+ /** `PermissionId` values of one coalesced episode (`event_posting` is folded into `accessibility`). */
+ permissions: string[];
+ feature: PermissionFeature;
+ reason: PermissionNeededReason;
+ phase: PermissionNeededPhase;
+ origin: PermissionNeededOrigin;
+ /** Automation target bundle id, else "". */
+ target: string;
+ can_prompt: boolean;
+ can_open_settings: boolean;
+ outside_app: boolean;
+ /** English sentence for logs and support; the UI renders i18n copy instead. */
+ detail: string;
+}
+
+/** Payload of the `PermissionResolved` WS event (`jarvis.core.events.PermissionResolved`). */
+export interface PermissionResolvedPayload {
+ permissions: string[];
+ feature: PermissionFeature;
+ granted: boolean;
+}
diff --git a/jarvis/ui/web/frontend/src/lib/permissionToast.test.ts b/jarvis/ui/web/frontend/src/lib/permissionToast.test.ts
new file mode 100644
index 0000000000..9e5b040712
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/permissionToast.test.ts
@@ -0,0 +1,412 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { translate, useI18nStore, type UiLanguage } from "@/i18n";
+import {
+ PERMISSION_TOAST_REPEAT_COOLDOWN_MS,
+ PERMISSION_TOAST_TTL_MS,
+ handlePermissionToastEvent,
+ planPermissionToast,
+ resetPermissionToastState,
+} from "@/lib/permissionToast";
+import { useEventStore } from "@/store/events";
+
+const MAC_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)";
+
+function episode(over: Record<string, unknown> = {}) {
+ return {
+ permissions: ["microphone"],
+ feature: "dictation",
+ reason: "denied",
+ phase: "blocked",
+ origin: "user",
+ target: "",
+ can_prompt: false,
+ can_open_settings: true,
+ outside_app: false,
+ detail: "English support sentence",
+ ...over,
+ };
+}
+
+describe("planPermissionToast", () => {
+ it("tells a denied permission with one sentence and Open System Settings", () => {
+ expect(planPermissionToast(episode())).toMatchObject({
+ variant: "needs",
+ messageKey: "permissions.toast.microphone",
+ action: "open_settings",
+ permission: "microphone",
+ feature: "dictation",
+ });
+ });
+
+ it.each([
+ ["microphone", "permissions.toast.microphone"],
+ ["screen_recording", "permissions.toast.screen_recording"],
+ ["accessibility", "permissions.toast.accessibility"],
+ ["input_monitoring", "permissions.toast.input_monitoring"],
+ ["automation", "permissions.toast.automation"],
+ ["credential_store", "permissions.toast.generic"],
+ ])("has one sentence for %s", (permission, key) => {
+ expect(planPermissionToast(episode({ permissions: [permission] }))?.messageKey).toBe(key);
+ });
+
+ it("folds event_posting into accessibility (one pane)", () => {
+ expect(planPermissionToast(episode({ permissions: ["event_posting"] }))).toMatchObject({
+ messageKey: "permissions.toast.accessibility",
+ permission: "accessibility",
+ });
+ });
+
+ it("names the first missing permission when an episode needs two", () => {
+ const plan = planPermissionToast(episode({ permissions: ["screen_recording", "accessibility"], feature: "computer_use" }));
+ expect(plan?.permission).toBe("screen_recording");
+ });
+
+ it("offers Ask macOS now when macOS can still ask, and says what an outside run means", () => {
+ expect(planPermissionToast(episode({ reason: "not_determined", can_prompt: true }))).toMatchObject({
+ action: "ask_now",
+ messageKey: "permissions.toast.microphone",
+ });
+ expect(
+ planPermissionToast(episode({ reason: "needs_settings", can_prompt: true, outside_app: true })),
+ ).toMatchObject({ action: "ask_outside", messageKey: "permissions.toast.outside" });
+ });
+
+ it("offers a restart for an allowed permission whose use failed", () => {
+ expect(
+ planPermissionToast(episode({ permissions: ["screen_recording"], reason: "restart_hint" })),
+ ).toMatchObject({ variant: "restart", action: "restart", messageKey: "permissions.toast.restart" });
+ });
+
+ it("explains a restriction without a button, and stays quiet when nothing can be asked", () => {
+ expect(planPermissionToast(episode({ reason: "restricted", can_open_settings: false }))).toMatchObject({
+ variant: "restricted",
+ action: null,
+ });
+ expect(planPermissionToast(episode({ reason: "unavailable" }))).toBeNull();
+ });
+
+ it("offers no button when there is no pane to open", () => {
+ expect(planPermissionToast(episode({ can_open_settings: false }))?.action).toBeNull();
+ });
+
+ it("never toasts while macOS is asking itself", () => {
+ expect(planPermissionToast(episode({ phase: "os_dialog", reason: "not_determined" }))).toBeNull();
+ });
+
+ it("never toasts for a background consumer", () => {
+ expect(planPermissionToast(episode({ origin: "background" }))).toBeNull();
+ expect(planPermissionToast(episode({ origin: "background", feature: "screen_context" }))).toBeNull();
+ });
+
+ it("makes ONE exception: a denied microphone for the wake word, once per session", () => {
+ const wake = episode({ origin: "background", feature: "wake_word" });
+ expect(planPermissionToast(wake)).toMatchObject({ variant: "wake_word", action: "open_settings" });
+ expect(planPermissionToast(wake, { wakeWordToldThisSession: true })).toBeNull();
+ // Only "denied": a wake word that merely was not asked yet stays quiet.
+ expect(planPermissionToast({ ...wake, reason: "not_determined", can_prompt: true })).toBeNull();
+ });
+
+ it("ignores payloads it cannot read honestly", () => {
+ expect(planPermissionToast(null)).toBeNull();
+ expect(planPermissionToast({})).toBeNull();
+ expect(planPermissionToast(episode({ permissions: [] }))).toBeNull();
+ expect(planPermissionToast(episode({ reason: "from_the_future" }))).toBeNull();
+ });
+
+ it("keys an episode by feature, permissions and reason", () => {
+ const a = planPermissionToast(episode());
+ const b = planPermissionToast(episode({ reason: "needs_settings" }));
+ expect(a?.key).not.toBe(b?.key);
+ expect(a?.episode).toBe(b?.episode);
+ });
+});
+
+describe("the copy", () => {
+ afterEach(() => useI18nStore.getState().setUi("en", { push: false }));
+
+ const SHAPES = [
+ episode(),
+ episode({ permissions: ["screen_recording"] }),
+ episode({ permissions: ["accessibility"] }),
+ episode({ permissions: ["input_monitoring"] }),
+ episode({ permissions: ["automation"], target: "com.spotify.client" }),
+ episode({ permissions: ["credential_store"] }),
+ episode({ reason: "restricted" }),
+ episode({ reason: "restart_hint", permissions: ["screen_recording"] }),
+ episode({ reason: "needs_settings", can_prompt: true, outside_app: true }),
+ episode({ origin: "background", feature: "wake_word" }),
+ ];
+
+ it.each(["en", "de", "es"] as UiLanguage[])("every sentence, name and button exists in %s", (language) => {
+ useI18nStore.getState().setUi(language, { push: false });
+ for (const shape of SHAPES) {
+ const plan = planPermissionToast(shape)!;
+ expect(translate(plan.messageKey), plan.messageKey).not.toBe(plan.messageKey);
+ if (plan.nameKey) expect(translate(plan.nameKey), plan.nameKey).not.toBe(plan.nameKey);
+ }
+ for (const key of [
+ "permissions.toast.action.open_settings",
+ "permissions.toast.action.ask_now",
+ "permissions.toast.action.restart",
+ "permissions.toast.action_failed",
+ "permissions.restart_failed",
+ ]) {
+ expect(translate(key), key).not.toBe(key);
+ }
+ });
+
+ it("keeps the sentences short, calm and free of pane names and jargon", () => {
+ for (const language of ["en", "de", "es"] as UiLanguage[]) {
+ useI18nStore.getState().setUi(language, { push: false });
+ for (const shape of SHAPES) {
+ const plan = planPermissionToast(shape)!;
+ const text = translate(plan.messageKey);
+ expect(text.length, text).toBeLessThan(170);
+ expect(text).not.toMatch(/Privacy & Security|Privacidad y seguridad|Datenschutz & Sicherheit|TCC|tccutil|[>]/);
+ }
+ }
+ });
+});
+
+describe("handlePermissionToastEvent", () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+ const restart = vi.fn(async () => undefined);
+
+ function onMac(embedded = true) {
+ if (embedded) (window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean }).__JARVIS_EMBEDDED_DESKTOP = true;
+ vi.spyOn(window.navigator, "userAgent", "get").mockReturnValue(MAC_UA);
+ }
+
+ const handle = (name: string, payload: unknown) => handlePermissionToastEvent(name, payload, { restart });
+
+ beforeEach(() => {
+ useI18nStore.getState().setUi("en", { push: false });
+ useEventStore.setState({ toasts: [], solo: false });
+ resetPermissionToastState();
+ restart.mockClear();
+ fetchMock = vi.fn(async () => ({ ok: true, status: 200 }) as Response);
+ vi.stubGlobal("fetch", fetchMock);
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete (window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean }).__JARVIS_EMBEDDED_DESKTOP;
+ });
+
+ function toast() {
+ const toasts = useEventStore.getState().toasts;
+ expect(toasts).toHaveLength(1);
+ return toasts[0];
+ }
+
+ it("pushes the sentence with its button and a lifetime long enough to use it", () => {
+ onMac();
+ const now = Date.now();
+ handle("PermissionNeeded", episode());
+
+ const t = toast();
+ expect(t.message).toBe("Personal Jarvis needs microphone access to hear you.");
+ expect(t.kind).toBe("warning");
+ expect(t.action?.label).toBe("Open System Settings");
+ expect(t.expiresAt - now).toBeGreaterThanOrEqual(PERMISSION_TOAST_TTL_MS - 50);
+ });
+
+ it("Open System Settings posts to the pane's open-settings route", async () => {
+ onMac();
+ handle("PermissionNeeded", episode({ permissions: ["screen_recording"], feature: "screen_context" }));
+
+ await toast().action!.onAction();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe("/api/permissions/screen_recording/open-settings?dry_run=false");
+ expect((init as RequestInit).method).toBe("POST");
+ expect((init as RequestInit).body).toBeUndefined();
+ });
+
+ it("Ask macOS now posts allow_outside_app only for an outside run", async () => {
+ onMac();
+ handle("PermissionNeeded", episode({ reason: "needs_settings", can_prompt: true, outside_app: true }));
+
+ const t = toast();
+ expect(t.action?.label).toBe("Ask macOS now");
+ await t.action!.onAction();
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe("/api/permissions/microphone/request?dry_run=false");
+ expect(JSON.parse((init as RequestInit).body as string)).toEqual({
+ feature: "dictation",
+ allow_outside_app: true,
+ });
+ });
+
+ it("Ask macOS now inside the installed app confirms nothing about another app", async () => {
+ onMac();
+ handle("PermissionNeeded", episode({ reason: "not_determined", can_prompt: true }));
+
+ await toast().action!.onAction();
+
+ const [, init] = fetchMock.mock.calls[0];
+ expect(JSON.parse((init as RequestInit).body as string)).toEqual({ feature: "dictation" });
+ });
+
+ it("an Automation ask names the player the episode is about", async () => {
+ onMac();
+ handle(
+ "PermissionNeeded",
+ episode({
+ permissions: ["automation"],
+ feature: "audio_ducking",
+ reason: "not_determined",
+ can_prompt: true,
+ target: "com.spotify.client",
+ }),
+ );
+
+ await toast().action!.onAction();
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe("/api/permissions/automation/request?dry_run=false");
+ expect(JSON.parse((init as RequestInit).body as string)).toEqual({
+ feature: "audio_ducking",
+ target: "com.spotify.client",
+ });
+ });
+
+ it("the restart variant restarts through the injected restart and stays up for a second press", async () => {
+ onMac();
+ handle("PermissionNeeded", episode({ permissions: ["screen_recording"], reason: "restart_hint" }));
+
+ const t = toast();
+ expect(t.message).toBe("Access to screen recording is on, but it only works after Personal Jarvis restarts.");
+ expect(t.action).toMatchObject({ label: "Quit and reopen", keepOpen: true });
+ await t.action!.onAction();
+ expect(restart).toHaveBeenCalledTimes(1);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("a button that fails says so, in one existing error toast", async () => {
+ onMac();
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ fetchMock.mockResolvedValue({ ok: false, status: 429 } as Response);
+ handle("PermissionNeeded", episode());
+
+ await toast().action!.onAction();
+
+ const messages = useEventStore.getState().toasts.map((t) => t.message);
+ expect(messages).toContain("That did not work. Please open System Settings yourself.");
+ });
+
+ it("is quiet outside the owner window: detached window, plain browser, other OS", () => {
+ onMac();
+ useEventStore.setState({ solo: true });
+ handle("PermissionNeeded", episode());
+ expect(useEventStore.getState().toasts).toEqual([]);
+
+ useEventStore.setState({ solo: false });
+ vi.restoreAllMocks();
+ delete (window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean }).__JARVIS_EMBEDDED_DESKTOP;
+ vi.spyOn(window.navigator, "userAgent", "get").mockReturnValue(MAC_UA);
+ handle("PermissionNeeded", episode());
+ expect(useEventStore.getState().toasts).toEqual([]);
+
+ (window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean }).__JARVIS_EMBEDDED_DESKTOP = true;
+ vi.spyOn(window.navigator, "userAgent", "get").mockReturnValue("Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
+ handle("PermissionNeeded", episode());
+ expect(useEventStore.getState().toasts).toEqual([]);
+ });
+
+ it("tells the wake word's denied microphone once per session, whoever started it", () => {
+ onMac();
+ const wake = episode({ origin: "background", feature: "wake_word" });
+ handle("PermissionNeeded", wake);
+ expect(toast().message).toContain("The wake word cannot listen");
+
+ useEventStore.setState({ toasts: [] });
+ handle("PermissionResolved", { permissions: ["microphone"], feature: "wake_word", granted: false });
+ handle("PermissionNeeded", wake);
+ expect(useEventStore.getState().toasts).toEqual([]);
+ });
+
+ it("does not repeat an episode, but a new reason of the same episode is news", () => {
+ onMac();
+ handle("PermissionNeeded", episode({ reason: "not_determined", can_prompt: true }));
+ handle("PermissionNeeded", episode({ reason: "not_determined", can_prompt: true }));
+ expect(useEventStore.getState().toasts).toHaveLength(1);
+
+ handle("PermissionNeeded", episode());
+ expect(useEventStore.getState().toasts).toHaveLength(2);
+ });
+
+ describe("a toast that is gone", () => {
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2026-01-01T10:00:00Z"));
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("is told again on the next press, once the cooldown has passed", () => {
+ onMac();
+ handle("PermissionNeeded", episode());
+ expect(toast().message).toContain("microphone");
+
+ // Dismissed (or expired) and the person presses the feature again.
+ useEventStore.setState({ toasts: [] });
+ vi.setSystemTime(Date.now() + PERMISSION_TOAST_REPEAT_COOLDOWN_MS + 1);
+ handle("PermissionNeeded", episode());
+ expect(useEventStore.getState().toasts).toHaveLength(1);
+ });
+
+ it("is not told twice in a burst, even though its toast is already gone", () => {
+ onMac();
+ handle("PermissionNeeded", episode());
+ useEventStore.setState({ toasts: [] });
+ vi.setSystemTime(Date.now() + PERMISSION_TOAST_REPEAT_COOLDOWN_MS - 1);
+ handle("PermissionNeeded", episode());
+ expect(useEventStore.getState().toasts).toEqual([]);
+ });
+
+ it("is not told again while its toast is still on screen", () => {
+ onMac();
+ handle("PermissionNeeded", episode());
+ const shown = useEventStore.getState().toasts.map((t) => t.id);
+ vi.setSystemTime(Date.now() + PERMISSION_TOAST_REPEAT_COOLDOWN_MS * 3);
+ handle("PermissionNeeded", episode());
+ expect(useEventStore.getState().toasts.map((t) => t.id)).toEqual(shown);
+ });
+
+ it("never repeats the wake word's toast within a session", () => {
+ onMac();
+ const wake = episode({ origin: "background", feature: "wake_word" });
+ handle("PermissionNeeded", wake);
+ useEventStore.setState({ toasts: [] });
+ vi.setSystemTime(Date.now() + PERMISSION_TOAST_REPEAT_COOLDOWN_MS * 10);
+ handle("PermissionNeeded", wake);
+ expect(useEventStore.getState().toasts).toEqual([]);
+ });
+ });
+
+ it("forgets only the episode a PermissionResolved names", () => {
+ onMac();
+ handle("PermissionNeeded", episode());
+ handle("PermissionNeeded", episode({ feature: "voice" }));
+ expect(useEventStore.getState().toasts).toHaveLength(1); // same sentence collapses into one
+
+ handle("PermissionResolved", { permissions: ["microphone"], feature: "dictation", granted: false });
+ useEventStore.setState({ toasts: [] });
+ handle("PermissionNeeded", episode({ feature: "voice" }));
+ expect(useEventStore.getState().toasts).toEqual([]); // still told
+ handle("PermissionNeeded", episode());
+ expect(useEventStore.getState().toasts).toHaveLength(1); // told again
+ });
+
+ it("ignores every other event", () => {
+ onMac();
+ handle("SystemStateChanged", episode());
+ handle("PermissionResolved", null);
+ expect(useEventStore.getState().toasts).toEqual([]);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/permissionToast.ts b/jarvis/ui/web/frontend/src/lib/permissionToast.ts
new file mode 100644
index 0000000000..69d44ac79c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/permissionToast.ts
@@ -0,0 +1,429 @@
+/**
+ * The one thing Personal Jarvis says when a macOS permission stopped a feature:
+ * a toast, in the app's existing toast layer, with one sentence and at most one
+ * button.
+ *
+ * macOS shows its OWN dialog the first time a feature needs a permission, and
+ * the app draws nothing around it. What macOS does NOT do is say anything after
+ * the person pressed "Don't allow" (it never asks twice) or when a granted
+ * permission still does not work. That silence is all this module fills: it
+ * reads the two bus events `PermissionNeeded` / `PermissionResolved` (typed in
+ * `permissionEvents.ts`) and decides whether a toast is due.
+ *
+ * A toast is due only when ALL of these hold:
+ * - the person caused it (`origin === "user"`), macOS is not asking right now
+ * (`phase === "blocked"`), and this window is the one that owns host-level
+ * prompts (the embedded desktop window on a Mac; never a detached solo
+ * window, a remote browser, or another OS);
+ * - this episode is not already on screen in this window. The key is forgotten
+ * when `PermissionResolved` ends the episode AND as soon as its toast is gone
+ * (dismissed or expired) after a short cooldown, so the next press of the
+ * feature that ends blocked again is told again instead of staying silent
+ * for the rest of the episode;
+ * - there is something the person can do or know. A background consumer never
+ * toasts, with ONE exception: the wake word is the always-listening feature
+ * the person switched on, so a denied microphone for it is told once per app
+ * session.
+ *
+ * Pure planning (`planPermissionToast`) is separate from the state and the I/O
+ * (`handlePermissionToastEvent`) so the table of sentences and buttons is one
+ * readable function with its own test.
+ */
+import { translate, fill } from "@/i18n";
+import { isEmbeddedMacWindow } from "@/lib/embeddedDesktop";
+import {
+ PERMISSION_FEATURES,
+ PERMISSION_NEEDED_ORIGINS,
+ PERMISSION_NEEDED_PHASES,
+ PERMISSION_NEEDED_REASONS,
+} from "@/lib/permissionEvents";
+import { useEventStore, type ToastAction } from "@/store/events";
+
+/** How long the toast stays: long enough to read one sentence and aim at its button. */
+export const PERMISSION_TOAST_TTL_MS = 20_000;
+
+/**
+ * How long a told episode swallows an identical edge even when its toast is already
+ * gone: enough to absorb a burst (two sockets, a double press), short enough that the
+ * person's next deliberate press is answered.
+ */
+export const PERMISSION_TOAST_REPEAT_COOLDOWN_MS = 3_000;
+
+/** The permission families that have their own sentence; anything else gets the generic one. */
+const FAMILIES_WITH_COPY = [
+ "microphone",
+ "screen_recording",
+ "accessibility",
+ "input_monitoring",
+ "automation",
+] as const;
+
+export type PermissionToastVariant = "needs" | "restricted" | "restart" | "wake_word";
+
+/** What the one button does. */
+export type PermissionToastActionKind = "open_settings" | "ask_now" | "ask_outside" | "restart";
+
+/** Everything the toast is made of, before any state or I/O. */
+export interface PermissionToastPlan {
+ /** Dedupe key: one episode in one situation (feature, permissions, reason). */
+ key: string;
+ /** The episode id the key belongs to (feature + permissions); `PermissionResolved` ends it. */
+ episode: string;
+ variant: PermissionToastVariant;
+ /** The `PermissionId` of the pane the button works on (`accessibility` for `event_posting`). */
+ permission: string;
+ /** The `PERMISSION_FEATURES` token the ask is attributed to, or "". */
+ feature: string;
+ /** Automation only: the player's bundle id the episode is about, else "". */
+ target: string;
+ /** i18n key of the sentence. */
+ messageKey: string;
+ /** i18n key of the permission's name, for the sentences that name it. */
+ nameKey: string | null;
+ action: PermissionToastActionKind | null;
+ kind: "info" | "warning";
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === "object";
+}
+
+function oneOf<T extends string>(allowed: readonly T[], value: unknown): T | null {
+ return typeof value === "string" && (allowed as readonly string[]).includes(value)
+ ? (value as T)
+ : null;
+}
+
+/** `event_posting` is an alias of `accessibility`: one pane. */
+function paneFamily(permission: string): string {
+ return permission === "event_posting" ? "accessibility" : permission;
+}
+
+function families(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ const out: string[] = [];
+ for (const entry of value) {
+ if (typeof entry !== "string" || entry === "") continue;
+ const family = paneFamily(entry);
+ if (!out.includes(family)) out.push(family);
+ }
+ return out;
+}
+
+/** The id of one episode, as the backend keys it: the feature and its sorted pane families. */
+function episodeId(feature: string, permissions: readonly string[]): string {
+ return `${feature}:${[...permissions].sort().join("+")}`;
+}
+
+/** The sentence key for one permission family (generic for a family without its own copy). */
+function sentenceKey(family: string): string {
+ return (FAMILIES_WITH_COPY as readonly string[]).includes(family)
+ ? `permissions.toast.${family}`
+ : "permissions.toast.generic";
+}
+
+function nameKey(family: string): string {
+ return (FAMILIES_WITH_COPY as readonly string[]).includes(family)
+ ? `permissions.toast.name.${family}`
+ : "permissions.toast.name.generic";
+}
+
+/**
+ * Decide what a `PermissionNeeded` payload is worth, or null for "say nothing".
+ * Pure: no window, no store, no clock.
+ *
+ * | situation | sentence | button |
+ * |------------------------------------------|----------------------|-------------------|
+ * | denied / needs_settings | one per permission | Open System Settings |
+ * | not yet asked, macOS can still ask | one per permission | Ask macOS now |
+ * | not yet asked, outside the installed app | outside variant | Ask macOS now (allow_outside_app) |
+ * | restart_hint (allowed, but use failed) | restart variant | Quit and reopen |
+ * | restricted (profile / parental control) | restricted variant | none |
+ * | unavailable (no desktop session) | nothing to tell | - |
+ */
+export function planPermissionToast(
+ payload: unknown,
+ options: { wakeWordToldThisSession?: boolean } = {},
+): PermissionToastPlan | null {
+ if (!isRecord(payload)) return null;
+ const feature = typeof payload.feature === "string" ? payload.feature : "";
+ const permissions = families(payload.permissions);
+ const reason = oneOf(PERMISSION_NEEDED_REASONS, payload.reason);
+ const phase = oneOf(PERMISSION_NEEDED_PHASES, payload.phase);
+ const origin = oneOf(PERMISSION_NEEDED_ORIGINS, payload.origin);
+ if (!feature || permissions.length === 0 || !reason || !phase || !origin) return null;
+ // macOS is showing its own dialog: the app adds nothing to it.
+ if (phase !== "blocked") return null;
+
+ const wakeWord = origin !== "user" && feature === "wake_word" && reason === "denied";
+ if (origin !== "user" && !(wakeWord && !options.wakeWordToldThisSession)) return null;
+ // Nothing to tell and nothing to do (no desktop session to ask in).
+ if (reason === "unavailable") return null;
+
+ const canPrompt = payload.can_prompt === true;
+ const canOpenSettings = payload.can_open_settings === true;
+ const outsideApp = payload.outside_app === true;
+ const permission = permissions[0];
+ const knownFeature = (PERMISSION_FEATURES as readonly string[]).includes(feature) ? feature : "";
+ const base = {
+ key: `${episodeId(feature, permissions)}:${reason}`,
+ episode: episodeId(feature, permissions),
+ permission,
+ feature: knownFeature,
+ target: permission === "automation" && typeof payload.target === "string" ? payload.target : "",
+ nameKey: nameKey(permission),
+ };
+
+ if (wakeWord) {
+ return {
+ ...base,
+ variant: "wake_word",
+ messageKey: "permissions.toast.wake_word",
+ nameKey: null,
+ action: canOpenSettings ? "open_settings" : null,
+ kind: "warning",
+ };
+ }
+ if (reason === "restricted") {
+ return {
+ ...base,
+ variant: "restricted",
+ messageKey: "permissions.toast.restricted",
+ action: null,
+ kind: "info",
+ };
+ }
+ if (reason === "restart_hint") {
+ return {
+ ...base,
+ variant: "restart",
+ messageKey: "permissions.toast.restart",
+ action: "restart",
+ kind: "warning",
+ };
+ }
+ // denied / needs_settings / not_determined: the person has to act.
+ if (canPrompt) {
+ return {
+ ...base,
+ variant: "needs",
+ messageKey: outsideApp ? "permissions.toast.outside" : sentenceKey(permission),
+ action: outsideApp ? "ask_outside" : "ask_now",
+ kind: "info",
+ };
+ }
+ return {
+ ...base,
+ variant: "needs",
+ messageKey: sentenceKey(permission),
+ action: canOpenSettings ? "open_settings" : null,
+ kind: "warning",
+ };
+}
+
+// ---------------------------------------------------------------------------
+// State and I/O
+// ---------------------------------------------------------------------------
+
+/**
+ * Whether THIS window owns host-level permission toasts. Every window has its own
+ * socket and the server broadcasts to all of them, so without an owner N windows
+ * would toast N times. The owner is the main window of the embedded desktop app on
+ * macOS; a detached solo window is one section and never is, and a remote browser
+ * must never offer "Open System Settings" for another computer. Read at event time:
+ * the desktop shell injects the bridge flag AFTER the page loads.
+ */
+export function isPermissionToastWindow(): boolean {
+ return !useEventStore.getState().solo && isEmbeddedMacWindow();
+}
+
+/** Episode key -> the message that was shown, so a grant can take the toast down again. */
+const told = new Map<string, { episode: string; message: string; at: number }>();
+/** Episode keys the snapshot seed already handled in this page load. */
+const seeded = new Set<string>();
+let wakeWordTold = false;
+
+/** Tests only: forget what this window already said. */
+export function resetPermissionToastState(): void {
+ told.clear();
+ seeded.clear();
+ wakeWordTold = false;
+}
+
+/** The pieces that need React state (the restart hook), handed in by `usePermissionToast`. */
+export interface PermissionToastDeps {
+ /**
+ * Quit and reopen (`useRestartApp`). Says "missions are running, press again" and
+ * "could not restart" (`permissions.restart_failed`) itself.
+ */
+ restart: () => Promise<void>;
+}
+
+async function post(url: string, body?: Record<string, unknown>): Promise<void> {
+ const res = await fetch(
+ url,
+ body === undefined
+ ? { method: "POST" }
+ : { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) },
+ );
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+}
+
+function failedToast(error: unknown): void {
+ // The person pressed a button and nothing happened: say so, and keep the cause for support.
+ console.warn("Permission toast action failed:", error);
+ useEventStore.getState().pushToast("error", translate("permissions.toast.action_failed"));
+}
+
+function actionFor(plan: PermissionToastPlan, deps: PermissionToastDeps): ToastAction | undefined {
+ switch (plan.action) {
+ case null:
+ return undefined;
+ case "open_settings":
+ return {
+ label: translate("permissions.toast.action.open_settings"),
+ onAction: async () => {
+ try {
+ await post(`/api/permissions/${plan.permission}/open-settings?dry_run=false`);
+ } catch (error) {
+ failedToast(error);
+ }
+ },
+ };
+ case "ask_now":
+ case "ask_outside":
+ return {
+ label: translate("permissions.toast.action.ask_now"),
+ onAction: async () => {
+ const body: Record<string, unknown> = {};
+ if (plan.feature) body.feature = plan.feature;
+ if (plan.target) body.target = plan.target;
+ // Only the person's own click may confirm that macOS records the grant for
+ // the app that started Jarvis; the route refuses it from an agent.
+ if (plan.action === "ask_outside") body.allow_outside_app = true;
+ try {
+ await post(
+ `/api/permissions/${plan.permission}/request?dry_run=false`,
+ Object.keys(body).length > 0 ? body : undefined,
+ );
+ } catch (error) {
+ failedToast(error);
+ }
+ },
+ };
+ case "restart":
+ return {
+ label: translate("permissions.toast.action.restart"),
+ // A restart that answers "missions are running" needs a second press: stay.
+ keepOpen: true,
+ onAction: () => deps.restart(),
+ };
+ }
+}
+
+function messageFor(plan: PermissionToastPlan): string {
+ const template = translate(plan.messageKey);
+ return plan.nameKey ? fill(template, { what: translate(plan.nameKey) }) : template;
+}
+
+/**
+ * Whether this key's toast is still being told: on screen right now, or shown
+ * within the repeat cooldown. A toast that was dismissed or expired is not: the
+ * person is trying the feature again and is owed the sentence again.
+ */
+function isStillTold(key: string): boolean {
+ const entry = told.get(key);
+ if (!entry) return false;
+ if (Date.now() - entry.at < PERMISSION_TOAST_REPEAT_COOLDOWN_MS) return true;
+ return useEventStore.getState().toasts.some((toast) => toast.message === entry.message);
+}
+
+function forgetEpisode(feature: string, permissions: readonly string[], granted: boolean): void {
+ const store = useEventStore.getState();
+ for (const [key, entry] of [...told]) {
+ const [entryFeature, entrySet] = entry.episode.split(":");
+ if (entryFeature !== feature) continue;
+ const overlaps =
+ permissions.length === 0 || entrySet.split("+").some((family) => permissions.includes(family));
+ if (!overlaps) continue;
+ told.delete(key);
+ // The permission was granted: the sentence that said it was missing is stale.
+ if (granted) {
+ for (const toast of store.toasts) {
+ if (toast.message === entry.message) store.dismissToast(toast.id);
+ }
+ }
+ }
+}
+
+/**
+ * Feed one bus event in. Cheap for every event but the two it reads, so the
+ * WebSocket hook can call it for each envelope.
+ */
+export function handlePermissionToastEvent(
+ eventName: string,
+ payload: unknown,
+ deps: PermissionToastDeps,
+): void {
+ if (eventName === "PermissionResolved") {
+ if (!isRecord(payload)) return;
+ // Shape: `PermissionResolvedPayload` (permissionEvents.ts); read defensively.
+ const feature = typeof payload.feature === "string" ? payload.feature : "";
+ if (feature === "") return;
+ forgetEpisode(feature, families(payload.permissions), payload.granted === true);
+ return;
+ }
+ if (eventName !== "PermissionNeeded") return;
+ if (!isPermissionToastWindow()) return;
+ // Shape: `PermissionNeededPayload` (permissionEvents.ts); read defensively.
+ announce(payload, deps);
+}
+
+/** Plan one episode and, when it is due and not already told, put its toast up. */
+function announce(payload: unknown, deps: PermissionToastDeps): void {
+ const plan = planPermissionToast(payload, {
+ wakeWordToldThisSession: wakeWordTold,
+ });
+ if (!plan || isStillTold(plan.key)) return;
+
+ const message = messageFor(plan);
+ told.set(plan.key, { episode: plan.episode, message, at: Date.now() });
+ if (plan.variant === "wake_word") wakeWordTold = true;
+ useEventStore.getState().pushToast(plan.kind, message, {
+ action: actionFor(plan, deps),
+ ttlMs: PERMISSION_TOAST_TTL_MS,
+ });
+}
+
+/**
+ * Catch up on the episodes that opened while no window was listening (autostart
+ * with the window hidden, a wake-word denial at boot before the socket was open):
+ * the bus event was published to nobody and is never repeated. Reads the open
+ * episodes from the read-only status route (it never asks macOS for anything) and
+ * runs each through the same plan as a live event. Owner window only. Each key is
+ * seeded once per page load, so a socket that reconnects does not repeat a toast
+ * the person already saw and let expire.
+ */
+export async function seedPermissionToasts(deps: PermissionToastDeps): Promise<void> {
+ if (!isPermissionToastWindow()) return;
+ let needed: unknown;
+ try {
+ const res = await fetch("/api/permissions/status");
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ needed = ((await res.json()) as { needed?: unknown }).needed;
+ } catch (error) {
+ // Offline or still booting: the live events keep working; the seed is a bonus.
+ console.debug("Permission toast seed skipped:", error);
+ return;
+ }
+ if (!Array.isArray(needed)) return;
+ // The window may have changed owner state while the request was in flight.
+ if (!isPermissionToastWindow()) return;
+ for (const entry of needed) {
+ const plan = planPermissionToast(entry, { wakeWordToldThisSession: wakeWordTold });
+ if (!plan || seeded.has(plan.key)) continue;
+ // Seeded even when it was already told live: a reconnect must not repeat it.
+ seeded.add(plan.key);
+ announce(entry, deps);
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.ts
index 7d6d0b2142..af17e308c1 100644
--- a/jarvis/ui/web/frontend/src/store/events.ts
+++ b/jarvis/ui/web/frontend/src/store/events.ts
@@ -301,6 +301,30 @@ export interface Toast {
filePath?: string;
/** Display name of the saved file (shown next to the actions). */
filename?: string;
+ /**
+ * One optional button under the message ("Open System Settings"). The layer
+ * runs `onAction` and then closes the toast, unless `keepOpen` is set (an
+ * action that can answer "try again", like a restart that needs a second
+ * press while missions run).
+ */
+ action?: ToastAction;
+}
+
+/** The one button a toast may carry. */
+export interface ToastAction {
+ label: string;
+ onAction: () => void | Promise<void>;
+ /** Leave the toast up after the press (default: it closes). */
+ keepOpen?: boolean;
+}
+
+/** Options of {@link EventStore.pushToast}. */
+export interface PushToastOptions {
+ filePath?: string;
+ filename?: string;
+ action?: ToastAction;
+ /** How long the toast stays, in ms. Default: 3.5 s, or 12 s for a saved file. */
+ ttlMs?: number;
}
export interface ChatMessage {
@@ -545,11 +569,7 @@ interface EventStore {
requestWikiPage: (slug: string) => void;
requestIdePane: (name: string) => void;
setTranscription: (text: string, isFinal: boolean) => void;
- pushToast: (
- kind: Toast["kind"],
- message: string,
- opts?: { filePath?: string; filename?: string },
- ) => void;
+ pushToast: (kind: Toast["kind"], message: string, opts?: PushToastOptions) => void;
dismissToast: (id: string) => void;
pushMessage: (m: ChatMessage) => void;
setMessages: (m: ChatMessage[]) => void;
@@ -583,8 +603,9 @@ interface EventStore {
const MAX_EVENTS = 500;
const MAX_MESSAGES = 200;
const TOAST_TTL_MS = 3500;
-// A file toast carries "Show in folder" / "Open" actions the user must have time
-// to aim at and click — keep it up noticeably longer than a plain notification.
+// A file toast carries "Show in folder" / "Open" actions, and any toast with a
+// button is one the user must have time to aim at and click — keep it up
+// noticeably longer than a plain notification.
const TOAST_FILE_TTL_MS = 12000;
// Finished reasoning traces are per-message UI sugar, not history — cap the
// map so a long session cannot grow it unbounded (insertion order = age).
@@ -698,7 +719,8 @@ export const useEventStore = create<EventStore>((set, get) => ({
pushToast: (kind, message, opts) => {
const filePath = opts?.filePath;
- const ttl = filePath ? TOAST_FILE_TTL_MS : TOAST_TTL_MS;
+ const action = opts?.action;
+ const ttl = opts?.ttlMs ?? (filePath || action ? TOAST_FILE_TTL_MS : TOAST_TTL_MS);
const now = Date.now();
const expiresAt = now + ttl;
@@ -707,18 +729,20 @@ export const useEventStore = create<EventStore>((set, get) => ({
// otherwise emit it once per click — and a double click on a card emits it
// twice more — until the stack buries the control the user needs to press.
// File toasts are matched on their path too, so two different saved files
- // stay two separate toasts with their own actions.
+ // stay two separate toasts with their own actions. A repeat that carries a
+ // button also swaps in the newest one (its closure may know more).
const existing = get().toasts.find(
(toast) =>
toast.kind === kind &&
toast.message === message &&
- toast.filePath === filePath,
+ toast.filePath === filePath &&
+ toast.action?.label === action?.label,
);
if (existing) {
set((state) => ({
toasts: state.toasts.map((toast) =>
toast.id === existing.id
- ? { ...toast, count: toast.count + 1, ts: now, expiresAt }
+ ? { ...toast, count: toast.count + 1, ts: now, expiresAt, action: action ?? toast.action }
: toast,
),
}));
@@ -739,6 +763,7 @@ export const useEventStore = create<EventStore>((set, get) => ({
expiresAt,
filePath,
filename: opts?.filename,
+ action,
},
],
}));
diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
index 329eb038ea..bd178f89ae 100644
--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
@@ -14,7 +14,6 @@ import { OverlayTaskbarGroup } from "@/views/settings/OverlayTaskbarGroup";
import { LanguagesGroup } from "@/views/settings/LanguagesGroup";
import { MusicGroup } from "@/views/settings/MusicGroup";
import { AppSettingsGroup } from "@/views/settings/AppSettingsGroup";
-import { PermissionsPanel } from "@/views/settings/PermissionsPanel";
import { RealtimeVoiceGroup } from "@/views/settings/RealtimeVoiceGroup";
import { SilenceWindowGroup } from "@/views/settings/SilenceWindowGroup";
import { VolumeGroup } from "@/views/settings/VolumeGroup";
@@ -157,7 +156,6 @@ export function SettingsView({ searchTarget, onSearchTargetHandled }: {
const SECTIONS: readonly { id: string; labelKey: string; render: () => React.ReactNode }[] = [
{ id: "languages", labelKey: "settings_view.nav.languages", render: () => <LanguagesGroup /> },
{ id: "app", labelKey: "settings_view.nav.app", render: () => <AppSettingsGroup /> },
- { id: "permissions", labelKey: "settings_view.nav.permissions", render: () => <PermissionsPanel /> },
{ id: "realtime-voice", labelKey: "settings_view.nav.realtime_voice", render: () => <RealtimeVoiceGroup /> },
{ id: "system-prompt", labelKey: "settings_view.nav.system_prompt", render: () => <SystemPromptGroup /> },
{ id: "wake-word", labelKey: "settings_view.nav.wake_word", render: () => <WakeWordPanel /> },
diff --git a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.test.tsx b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.test.tsx
deleted file mode 100644
index 9bea225491..0000000000
--- a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.test.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import type { PermissionItem, PermissionSnapshot } from "@/hooks/usePermissions";
-
-const request = vi.fn();
-const openSettings = vi.fn();
-const reset = vi.fn();
-const setupAll = vi.fn().mockResolvedValue("complete");
-const cancelSetup = vi.fn();
-
-let mockSnapshot: PermissionSnapshot | null = null;
-let mockSetupNeeded = false;
-
-vi.mock("@/i18n", () => ({
- useT: () => (key: string) => key,
-}));
-
-vi.mock("@/store/events", () => ({
- useEventStore: (selector: (state: { pushToast: ReturnType<typeof vi.fn> }) => unknown) =>
- selector({ pushToast: vi.fn() }),
-}));
-
-vi.mock("@/hooks/usePermissions", () => ({
- usePermissions: () => ({
- snapshot: mockSnapshot,
- loading: false,
- error: null,
- pendingId: null,
- refetch: vi.fn(),
- request,
- openSettings,
- reset,
- setupAll,
- cancelSetup,
- setupProgress: null,
- setupNeeded: mockSetupNeeded,
- }),
-}));
-
-import { PermissionRows, SetupAllControl } from "./PermissionsPanel";
-
-function snapshotWith(row: Partial<PermissionItem>): PermissionSnapshot {
- return {
- platform: "darwin",
- supported: true,
- headless: false,
- app_identity: { stable: true },
- permissions: [
- {
- id: "screen_recording",
- status: "not_granted",
- required: ["computer_use"],
- can_request: true,
- can_open_settings: true,
- can_reset: false,
- restart_required: false,
- ...row,
- } as PermissionItem,
- ],
- features: { computer_use: { ready: false, missing: ["screen_recording"] } },
- restart_required: false,
- };
-}
-
-afterEach(() => {
- cleanup();
- vi.clearAllMocks();
- mockSnapshot = null;
-});
-
-describe("PermissionRows", () => {
- it("keeps System Settings available when a native request can also run", () => {
- mockSnapshot = snapshotWith({});
- render(<PermissionRows />);
-
- expect(screen.getByRole("button", { name: "permissions.request" })).toBeDefined();
- expect(
- screen.getByRole("button", { name: "permissions.open_settings" }),
- ).toBeDefined();
- });
-
- it("offers the reset on a stranded grant that never reads 'denied' (BUG-159)", () => {
- // The old rule was `status === "denied"`, which the Screen Recording and
- // Accessibility preflights never produce — the recovery button was
- // unreachable on exactly the rows a signature change strands.
- mockSnapshot = snapshotWith({ can_request: false, can_reset: true });
- render(<PermissionRows />);
-
- fireEvent.click(screen.getByRole("button", { name: "permissions.ask_again" }));
- expect(reset).toHaveBeenCalledWith("screen_recording");
- expect(screen.getByText("permissions.stale_grant_hint")).toBeDefined();
- });
-
- it("hides the reset while a grant is in place", () => {
- mockSnapshot = snapshotWith({ status: "granted", can_request: false, can_reset: false });
- render(<PermissionRows />);
-
- expect(screen.queryByRole("button", { name: "permissions.ask_again" })).toBeNull();
- });
-});
-
-describe("Set up everything", () => {
- afterEach(() => {
- mockSetupNeeded = false;
- });
-
- it("offers the one-click flow only while a row still needs setup", () => {
- mockSnapshot = snapshotWith({});
- mockSetupNeeded = true;
- render(<PermissionRows />);
-
- fireEvent.click(screen.getByTestId("permissions-setup-all"));
-
- // Settings/banner mode applies the grants itself; onboarding (deferred
- // restart note) leaves the restart to its own final step.
- expect(setupAll).toHaveBeenCalledWith({ autoRestart: true });
- });
-
- it("leaves the final restart to onboarding", () => {
- mockSnapshot = snapshotWith({});
- mockSetupNeeded = true;
- render(<PermissionRows compact deferRestartNote />);
-
- fireEvent.click(screen.getByTestId("permissions-setup-all"));
-
- expect(setupAll).toHaveBeenCalledWith({ autoRestart: false });
- });
-
- it("hides the flow once everything is granted or the app runs outside its bundle", () => {
- mockSnapshot = snapshotWith({ status: "granted" });
- mockSetupNeeded = false;
- const { unmount } = render(<PermissionRows />);
- expect(screen.queryByTestId("permissions-setup-all")).toBeNull();
- unmount();
-
- mockSnapshot = { ...snapshotWith({}), app_identity: { stable: false } };
- mockSetupNeeded = true;
- render(<PermissionRows />);
- expect(screen.queryByTestId("permissions-setup-all")).toBeNull();
- });
-
- it("names the step and the waiting phase while running, with a way out", () => {
- const onCancel = vi.fn();
- render(
- <SetupAllControl
- progress={{ id: "accessibility", index: 2, total: 5, phase: "settings" }}
- onStart={vi.fn()}
- onCancel={onCancel}
- />,
- );
-
- // The i18n stub echoes keys, so the step line is the bare template key;
- // the phase line tells the user what macOS is waiting for.
- expect(screen.getByTestId("permissions-setup-progress").textContent).toContain(
- "permissions.setup_running",
- );
- expect(screen.getByText("permissions.setup_wait_settings")).toBeDefined();
- expect(screen.queryByTestId("permissions-setup-all")).toBeNull();
- fireEvent.click(screen.getByRole("button", { name: "permissions.setup_cancel" }));
- expect(onCancel).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx
deleted file mode 100644
index 5af835bd05..0000000000
--- a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx
+++ /dev/null
@@ -1,373 +0,0 @@
-import {
- Accessibility,
- CheckCircle2,
- CircleAlert,
- Keyboard,
- KeyRound,
- Loader2,
- Mic,
- Monitor,
- MousePointer2,
- Music,
- RefreshCw,
- ShieldCheck,
- Wand2,
-} from "lucide-react";
-import { useEffect, useState } from "react";
-import { Button } from "@/components/ui/button";
-import { useEventStore } from "@/store/events";
-import { useT } from "@/i18n";
-import {
- usePermissions,
- type PermissionId,
- type PermissionItem,
- type PermissionSnapshot,
- type SetupProgress,
-} from "@/hooks/usePermissions";
-import { SettingsBlock } from "@/views/settings/SettingsBlock";
-
-const ICONS = {
- microphone: Mic,
- screen_recording: Monitor,
- accessibility: Accessibility,
- input_monitoring: Keyboard,
- event_posting: MousePointer2,
- automation: Music,
- credential_store: KeyRound,
-} satisfies Record<PermissionId, typeof Mic>;
-
-const READY_STATES = new Set(["granted", "not_required"]);
-
-export function PermissionRows({
- compact = false,
- deferRestartNote = false,
- onSnapshot,
-}: {
- compact?: boolean;
- /**
- * Onboarding mode: the guide ends with ONE unconditional fresh restart,
- * so a granted-but-stale permission shows a calm "applies after the
- * final restart" note instead of the amber restart-now demand.
- */
- deferRestartNote?: boolean;
- onSnapshot?: (snapshot: PermissionSnapshot | null) => void;
-}) {
- const t = useT();
- const pushToast = useEventStore((state) => state.pushToast);
- const [restarting, setRestarting] = useState(false);
- const {
- snapshot,
- loading,
- error,
- pendingId,
- refetch,
- request,
- openSettings,
- reset,
- setupAll,
- cancelSetup,
- setupProgress,
- setupNeeded,
- } = usePermissions();
-
- useEffect(() => {
- onSnapshot?.(snapshot);
- }, [onSnapshot, snapshot]);
-
- async function run(action: () => Promise<void>) {
- try {
- await action();
- } catch (exc) {
- pushToast("error", exc instanceof Error ? exc.message : String(exc));
- }
- }
-
- async function runSetup() {
- try {
- // Onboarding ends with its own unconditional restart; everywhere else
- // the flow applies the new access itself so nothing is left to click.
- const outcome = await setupAll({ autoRestart: !deferRestartNote });
- if (outcome === "restart") {
- pushToast("info", t("permissions.setup_restarting"));
- } else if (outcome === "timeout") {
- pushToast("warning", t("permissions.setup_timeout"));
- }
- } catch (exc) {
- const message = exc instanceof Error ? exc.message : String(exc);
- pushToast(
- "error",
- message === "restart-missions-running"
- ? t("topbar.restart_missions_running")
- : message,
- );
- }
- }
-
- async function restartApp() {
- if (restarting) return;
- setRestarting(true);
- try {
- const response = await fetch("/api/settings/restart-app", { method: "POST" });
- if (response.status === 409) {
- pushToast("warning", t("topbar.restart_missions_running"));
- setRestarting(false);
- return;
- }
- if (!response.ok) throw new Error(`restart-failed:${response.status}`);
- // A successful response schedules process shutdown, so keep the button
- // disabled while the window closes and returns through LaunchServices.
- } catch {
- pushToast("error", t("permissions.restart_failed"));
- setRestarting(false);
- }
- }
-
- if (loading && !snapshot) {
- return (
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- {t("permissions.loading")}
- </div>
- );
- }
-
- if (error && !snapshot) {
- return (
- <div className="rounded-lg border border-destructive/40 p-3 text-xs text-destructive">
- <p>{t("permissions.load_failed")}</p>
- <Button className="mt-2" size="sm" variant="outline" onClick={() => void refetch()}>
- <RefreshCw className="mr-1.5 h-3.5 w-3.5" />
- {t("permissions.refresh")}
- </Button>
- </div>
- );
- }
-
- const items = snapshot?.permissions ?? [];
- if (items.length === 0 || snapshot?.platform !== "darwin") {
- return (
- <div className="flex items-start gap-2 rounded-lg border border-border bg-background p-3 text-xs text-muted-foreground">
- <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
- {t("permissions.not_required")}
- </div>
- );
- }
-
- return (
- <div className="space-y-2">
- {snapshot?.app_identity.stable === false && (
- <div className="flex items-start gap-2 rounded-lg bg-secondary p-3 text-xs text-foreground">
- <CircleAlert className="mt-0.5 h-4 w-4 shrink-0" />
- {t("permissions.identity_warning")}
- </div>
- )}
- {/* A rebuild changed the app's signature, so macOS discarded every
- recorded grant. Without this the app just looks amnesic. */}
- {snapshot?.identity_reset && (
- <div className="flex items-start gap-2 rounded-lg bg-secondary p-3 text-xs text-foreground">
- <CircleAlert className="mt-0.5 h-4 w-4 shrink-0" />
- {t("permissions.identity_reset")}
- </div>
- )}
- {/* One click for the whole list: every dialog in turn, the Settings
- pane for the rows macOS only grants there, then the restart that
- applies them — instead of six buttons and a restart to find. */}
- {setupNeeded && snapshot?.app_identity.stable !== false && (
- <SetupAllControl
- progress={setupProgress}
- onStart={() => void runSetup()}
- onCancel={cancelSetup}
- />
- )}
- {items.map((permission) => (
- <PermissionRow
- key={permission.id}
- item={permission}
- busy={pendingId === permission.id}
- compact={compact}
- onRequest={() => run(() => request(permission.id))}
- onOpenSettings={() => run(() => openSettings(permission.id))}
- onReset={() => run(() => reset(permission.id))}
- />
- ))}
- {snapshot?.restart_required && deferRestartNote && (
- <p className="text-xs text-muted-foreground">
- {t("permissions.restart_deferred")}
- </p>
- )}
- {snapshot?.restart_required && !deferRestartNote && (
- <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg bg-secondary p-3">
- <p className="text-xs text-foreground">{t("permissions.restart_required")}</p>
- <Button size="sm" disabled={restarting} onClick={() => void restartApp()}>
- {restarting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
- {t(restarting ? "permissions.restarting" : "permissions.restart_now")}
- </Button>
- </div>
- )}
- {error && <p className="text-xs text-destructive">{error}</p>}
- </div>
- );
-}
-
-export function SetupAllControl({
- progress,
- onStart,
- onCancel,
-}: {
- progress: SetupProgress | null;
- onStart: () => void;
- onCancel: () => void;
-}) {
- const t = useT();
- if (!progress) {
- return (
- <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg bg-secondary p-3">
- <p className="text-xs text-foreground">{t("permissions.setup_all_hint")}</p>
- <Button size="sm" data-testid="permissions-setup-all" onClick={onStart}>
- <Wand2 className="mr-1.5 h-3.5 w-3.5" aria-hidden />
- {t("permissions.setup_all")}
- </Button>
- </div>
- );
- }
- const step = t("permissions.setup_running")
- .replace("{0}", String(progress.index))
- .replace("{1}", String(progress.total))
- .replace("{2}", t(`permissions.items.${progress.id}.title`));
- return (
- <div
- className="flex flex-wrap items-center justify-between gap-2 rounded-lg bg-secondary p-3"
- data-testid="permissions-setup-progress"
- aria-live="polite"
- >
- <div className="min-w-0 flex-1">
- <p className="flex items-center gap-2 text-xs font-medium text-foreground">
- <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" aria-hidden />
- {step}
- </p>
- <p className="mt-0.5 text-xs text-muted-foreground">
- {t(
- progress.phase === "settings"
- ? "permissions.setup_wait_settings"
- : "permissions.setup_wait_prompt",
- )}
- </p>
- </div>
- <Button size="sm" variant="outline" onClick={onCancel}>
- {t("permissions.setup_cancel")}
- </Button>
- </div>
- );
-}
-
-function PermissionRow({
- item,
- busy,
- compact,
- onRequest,
- onOpenSettings,
- onReset,
-}: {
- item: PermissionItem;
- busy: boolean;
- compact: boolean;
- onRequest: () => void;
- onOpenSettings: () => void;
- onReset: () => void;
-}) {
- const t = useT();
- const Icon = ICONS[item.id];
- const ready = READY_STATES.has(item.status);
- const showRequest = !ready && item.can_request;
- // The Core Graphics boolean preflights cannot distinguish "not asked" from
- // "asked and denied". Keep the Settings escape hatch visible alongside the
- // first-party request button so a prior denial is always recoverable.
- const showSettings = !ready && item.can_open_settings;
- // macOS auto-denies an app that ever created an input listener before the
- // user was asked, and a signature change orphans recorded grants (BUG-083)
- // — either way macOS never prompts again. "Ask again" drops OUR OWN record
- // (tccutil, scoped to this app's bundle id) so the real system dialog can
- // fire once more. The backend decides when that helps: keying it off a
- // "denied" status hid it from Screen Recording and Accessibility, whose
- // boolean preflights report a stranded grant as "not_granted" (BUG-159).
- const showReset = item.can_reset;
- // No prompt left AND the grant is missing: the checkmark the user sees in
- // System Settings belongs to an older signature of the app. Say so, because
- // toggling it there is exactly what they will otherwise try forever.
- const showStaleHint = item.can_reset && !item.can_request;
- // Screen Recording is the one probe macOS freezes per process: after the
- // user grants it in System Settings, the live value stays stale until the
- // app restarts. Show the honest pending label instead of the stale state;
- // every other permission reads live TCC state and keeps its real status.
- const statusKey =
- !ready && item.restart_required && item.id === "screen_recording"
- ? "restart_pending"
- : item.status;
-
- return (
- <div className={`rounded-lg border border-border bg-background ${compact ? "p-3" : "p-4"}`}>
- <div className="flex flex-wrap items-center gap-3">
- <Icon className="h-4 w-4 shrink-0 text-muted-foreground" />
- <div className="min-w-[12rem] flex-1">
- <div className="text-sm font-medium">{t(`permissions.items.${item.id}.title`)}</div>
- {/* Compact rows drop descriptions to stay scannable — except when
- the grant is missing: a user deciding whether to allow access
- (e.g. the startup Keychain prompt) needs the why right here. */}
- {(!compact || !ready) && (
- <p className="mt-0.5 text-xs text-muted-foreground">
- {t(`permissions.items.${item.id}.description`)}
- </p>
- )}
- </div>
- <span
- className={`rounded-full px-2 py-1 text-micro font-medium ${
- ready
- ? "bg-muted-foreground/10 text-muted-foreground"
- : "bg-secondary text-foreground"
- }`}
- >
- {t(`permissions.status.${statusKey}`)}
- </span>
- {showRequest && (
- <Button size="sm" disabled={busy} onClick={onRequest}>
- {busy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
- {t("permissions.request")}
- </Button>
- )}
- {showSettings && (
- <Button size="sm" variant="outline" disabled={busy} onClick={onOpenSettings}>
- {busy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
- {t("permissions.open_settings")}
- </Button>
- )}
- {showReset && (
- <Button size="sm" variant="ghost" disabled={busy} onClick={onReset}>
- {busy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
- {t("permissions.ask_again")}
- </Button>
- )}
- </div>
- {showStaleHint && (
- <p className="mt-2 text-xs text-foreground">{t("permissions.stale_grant_hint")}</p>
- )}
- </div>
- );
-}
-
-export function PermissionsPanel() {
- const t = useT();
- return (
- <div className="mt-8 space-y-4">
- <h3 className="text-lg font-semibold text-foreground-strong">
- {t("permissions.group_title")}
- </h3>
- <SettingsBlock
- icon={ShieldCheck}
- title={t("permissions.title")}
- description={t("permissions.description")}
- >
- <PermissionRows />
- </SettingsBlock>
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts b/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts
index 5ad1478bea..4bfad32aaa 100644
--- a/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts
+++ b/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts
@@ -11,7 +11,6 @@ const LOCALES: Record<UiLanguage, LocaleTree> = { en, de, es };
const SEARCH_GROUPS = [
{ id: "languages", keys: ["language", "languages_group_title"] },
{ id: "app", keys: ["app_settings_group_title", "autostart", "appearance", "jarvis_api"] },
- { id: "permissions", keys: ["nav.permissions"] },
{ id: "realtime-voice", keys: ["realtime_voice"] },
{ id: "system-prompt", keys: ["system_prompt"] },
{ id: "wake-word", keys: ["wake_word"] },
diff --git a/jarvis/ui/web/permissions_routes.py b/jarvis/ui/web/permissions_routes.py
index 06744364d0..69a66ba1e7 100644
--- a/jarvis/ui/web/permissions_routes.py
+++ b/jarvis/ui/web/permissions_routes.py
@@ -1,19 +1,86 @@
-"""Local-user API for macOS system-permission status and request flows."""
+"""Local-user API for macOS privacy permissions: a passive snapshot and the ask flows.
+
+Nothing here is a wall. ``GET`` routes only READ: they never prompt and never
+block (the Automation probe and the episode refresh run on a bounded daemon
+thread). Asking is a user gesture: ``POST /{id}/request`` hands the permission to
+the just-in-time service (``jarvis.platform.permission_service``), which asks macOS
+at most once per episode, and answers at once with the outcome. A decision made in
+the OS dialog arrives later, through ``PermissionResolved`` on the bus.
+
+Snapshot v2 (``GET /status``)::
+
+ {platform, supported, headless, app_identity{...}, outside_installed_app,
+ permissions: [{id, label, status, used_for, can_request, can_open_settings,
+ can_reset, restart_hint, detail, settings_path}],
+ needed: [open episodes]}
+
+Both GET routes accept ``?activated=1`` (no frontend caller since the UI reset; kept
+for the CLI and the window-focus follow-up in docs/macos-permissions.md 4.9): the route
+then calls ``note_app_activated()`` on the service before it refreshes the episodes,
+so a Screen Recording / Accessibility / Input Monitoring dialog the person left to
+flip a switch in System Settings is promoted to "blocked" at once and the next watcher
+pass reads the grant (the window-title oracle included). Without it the same dialog
+turns "blocked" after about 15 s. It is a hint about what the user just did, never a
+prompt, and only the person at the Jarvis window counts: an agent's ``activated=1`` is
+ignored.
+
+The Automation row is computed only while ``[ducking].enabled`` is on or the caller
+passes ``?include=automation``: reading it asks a running player, which a user who
+never switched the feature on should never meet. A player whose real Apple Event was
+refused (``-1743``) although its probe reads granted has an open ``needs_settings``
+episode (``report_failed_use``); the row keeps the probe's ``status`` (no key is added)
+and its ``detail`` names that player. Reading never asks. Screen Recording is the SHALLOW
+preflight here (no window enumeration); that preflight is frozen per process and can
+only go stale NEGATIVE (BUG-161), so a grant given in System Settings shows up only
+once the service has PROVEN it (an ``ensure`` or the episode watcher runs the
+window-title oracle, rate limited) and then keeps reading granted until a capture
+error invalidates it. Off macOS every row is ``not_required`` and
+``needed`` is empty. ``event_posting`` is an alias of ``accessibility`` and has no
+row of its own.
+
+The key sets of the TypedDicts below are the Python side of an AP-4 parity: a test
+reads them back against the real answer and against the TypeScript twin.
+"""
from __future__ import annotations
-from typing import Any
+import logging
+import math
+import threading
+import time
+from collections import deque
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Annotated, Any, Final, TypedDict, cast
-from fastapi import APIRouter, Depends, Query, Request
+from fastapi import APIRouter, Body, Depends, Query, Request
from fastapi.responses import JSONResponse
+from pydantic import BaseModel, ConfigDict, field_validator
+from jarvis.core.events import PERMISSION_FEATURES
+from jarvis.platform import permissions as _permissions_module
+from jarvis.platform.permission_service import (
+ AppInfo,
+ EnsureResult,
+ PermissionOutcome,
+ PermissionService,
+ agent_detail_for,
+ get_permission_service,
+ user_detail_for,
+)
from jarvis.platform.permissions import (
+ AUTOMATION_TARGETS,
+ PANE_FAMILY,
PermissionId,
- SystemPermissionPort,
- get_system_permission_port,
+ PermissionState,
+ settings_path_text,
)
-from .control_auth import require_control_key_or_session
+from .control_auth import _bearer_token, require_control_key_or_session
+from .missions_auth import validate_token
+from .surface_security import COOKIE_NAME
+
+log = logging.getLogger(__name__)
router = APIRouter(
prefix="/api/permissions",
@@ -21,37 +88,959 @@ router = APIRouter(
dependencies=[Depends(require_control_key_or_session)],
)
-def _port(request: Request) -> SystemPermissionPort:
- injected = getattr(request.app.state, "system_permission_port", None)
- return injected if injected is not None else get_system_permission_port()
+# ----------------------------------------------------------------------
+# Wire shapes (the Python side of the AP-4 parity)
+# ----------------------------------------------------------------------
+
+
+class AppIdentityBlock(TypedDict):
+ app_name: str
+ bundle_id: str | None
+ bundle_path: str | None
+ launched_as_bundle: bool
+ stable: bool
+
+
+class PermissionRow(TypedDict):
+ id: str
+ label: str
+ status: str
+ used_for: list[str]
+ can_request: bool
+ can_open_settings: bool
+ can_reset: bool
+ restart_hint: bool
+ detail: str
+ settings_path: str | None
+
+
+class NeededEpisode(TypedDict):
+ """One open episode: the keys of ``permission_service.Episode.as_dict``."""
+
+ permissions: list[str]
+ feature: str
+ reason: str
+ phase: str
+ origin: str
+ target: str
+ can_prompt: bool
+ can_open_settings: bool
+ outside_app: bool
+ detail: str
+ trace_id: str
+ opened_at_ns: int
+
+
+class PermissionsSnapshot(TypedDict):
+ platform: str
+ supported: bool
+ headless: bool
+ app_identity: AppIdentityBlock
+ outside_installed_app: bool
+ permissions: list[PermissionRow]
+ needed: list[NeededEpisode]
+
+
+class EnsurePayload(TypedDict):
+ """The answer of ``POST /{id}/request``: an ``EnsureResult`` as JSON."""
+
+ permission: str
+ outcome: str
+ granted: bool
+ state: str
+ asked: bool
+ outside_installed_app: bool
+ reason: str
+ can_prompt: bool
+ can_open_settings: bool
+ target: str
+ user_detail: str
+ agent_detail: str
+
+
+class OperationPayload(TypedDict):
+ """The answer of ``/open-settings`` and ``/reset`` (and any dry run)."""
+
+ ok: bool
+ permission_id: str
+ action: str
+ performed: bool
+ dry_run: bool
+ message: str
+ permission: PermissionRow | None
+
+
+class RateLimitedPayload(TypedDict):
+ """The stable body of a 429."""
+
+ error: str
+ scope: str
+ action: str
+ permission_id: str
+ retry_after_s: int
+
+
+# ----------------------------------------------------------------------
+# Row metadata
+# ----------------------------------------------------------------------
+
+# The rows a person sees, in order. EVENT_POSTING is an alias of Accessibility for
+# asking and has no row; the Keychain row stays (it names the storage kind and
+# offers "Try again").
+_ROW_ORDER: Final[tuple[PermissionId, ...]] = (
+ PermissionId.MICROPHONE,
+ PermissionId.SCREEN_RECORDING,
+ PermissionId.ACCESSIBILITY,
+ PermissionId.INPUT_MONITORING,
+ PermissionId.AUTOMATION,
+ PermissionId.CREDENTIAL_STORE,
+)
+
+# English fallback labels; the UI renders its own i18n per row id.
+_ROW_LABELS: Final[dict[PermissionId, str]] = {
+ PermissionId.MICROPHONE: "Microphone",
+ PermissionId.SCREEN_RECORDING: "Screen Recording",
+ PermissionId.ACCESSIBILITY: "Accessibility",
+ PermissionId.INPUT_MONITORING: "Input Monitoring",
+ PermissionId.AUTOMATION: "Automation (Music & Spotify)",
+ PermissionId.CREDENTIAL_STORE: "Keychain (API keys)",
+}
+
+# Which features use a permission, in the vocabulary of ``PERMISSION_FEATURES``. The
+# FIRST one is the feature a request without a ``feature`` is attributed to. The
+# Keychain has no feature in that vocabulary: the UI names the row by its id.
+_USED_FOR: Final[dict[PermissionId, tuple[str, ...]]] = {
+ PermissionId.MICROPHONE: ("voice", "dictation", "wake_word", "browser_voice"),
+ PermissionId.SCREEN_RECORDING: ("computer_use", "screen_context", "appshot"),
+ PermissionId.ACCESSIBILITY: ("computer_use", "window_control", "dictation_insert"),
+ PermissionId.INPUT_MONITORING: ("global_shortcuts",),
+ PermissionId.AUTOMATION: ("audio_ducking",),
+ PermissionId.CREDENTIAL_STORE: (),
+}
+
+_READY: Final = frozenset({PermissionState.GRANTED, PermissionState.NOT_REQUIRED})
+# Nothing is decided yet: macOS can still be asked.
+_UNDECIDED: Final = frozenset({PermissionState.NOT_DETERMINED, PermissionState.NOT_GRANTED})
+# The states "Ask again" (a tccutil reset) can do something about. A restricted or
+# unavailable permission is not stranded, it is out of reach; a granted one must
+# never be reset.
+_RESETTABLE: Final = frozenset(
+ {PermissionState.NOT_DETERMINED, PermissionState.NOT_GRANTED, PermissionState.DENIED}
+)
+_REASON_OF_STATE: Final[dict[PermissionState, str]] = {
+ PermissionState.NOT_DETERMINED: "not_determined",
+ PermissionState.NOT_GRANTED: "needs_settings",
+ PermissionState.DENIED: "denied",
+ PermissionState.RESTRICTED: "restricted",
+ PermissionState.UNAVAILABLE: "unavailable",
+}
+_AUTOMATION_PLAYERS: Final = tuple(bundle_id for _name, bundle_id in AUTOMATION_TARGETS)
+
+_NOT_REQUIRED_DETAIL: Final = "This operating system does not require a macOS privacy permission."
+_AUTOMATION_NOTE: Final = "Checked only while Music or Spotify is running."
+_AUTOMATION_NO_ANSWER: Final = "The Automation check did not answer in time. " + _AUTOMATION_NOTE
+_AUTOMATION_NO_PLAYER: Final = "Music and Spotify are not installed, so there is nothing to allow."
+_KEYCHAIN_DECLINED: Final = (
+ "Keychain access was declined, so API keys are kept in a local file for now. "
+ "Allow access to store them encrypted in the macOS Keychain."
+)
+
+# How long a GET waits for the Automation probe / the episode refresh, and a POST
+# /request for a blocking Automation ask, before it answers without them. The work
+# keeps running on its daemon thread; its late answer is discarded.
+_AUTOMATION_PROBE_TIMEOUT_S: Final = 2.5
+_REFRESH_TIMEOUT_S: Final = 2.5
+_AUTOMATION_ASK_WAIT_S: Final = 2.0
+# How long ONE Automation ask waits for the consent runner before it answers PENDING:
+# long enough to see "the player is not running" (the guarded script ends at once),
+# short enough that two candidates still fit inside the wait above.
+_AUTOMATION_SETTLE_S: Final = 0.75
+
+# Rate limits for the two routes that can make the OS show something: /request and
+# /open-settings. A cooldown per (action, permission) plus a global cap, so a UI bug
+# or another local page cannot turn them into a prompt loop.
+_PERMISSION_COOLDOWN_S: Final = 5.0
+_GLOBAL_MAX_CALLS: Final = 20
+_GLOBAL_WINDOW_S: Final = 60.0
+
+
+# ----------------------------------------------------------------------
+# Rate limiting and bounded calls
+# ----------------------------------------------------------------------
+
+
+@dataclass(frozen=True, slots=True)
+class _Refusal:
+ scope: str
+ retry_after_s: float
+
+
+class _RateLimiter:
+ """A cooldown per (action, permission) and a sliding-window cap over all of them.
+
+ The person at the Jarvis window and every other caller (an agent, a script) have
+ SEPARATE budgets: a loop from a shell must never use up the cooldown or the global
+ cap that the person's own "Allow" / "Open System Settings" click needs.
+ """
+
+ def __init__(
+ self,
+ *,
+ cooldown_s: float = _PERMISSION_COOLDOWN_S,
+ global_max: int = _GLOBAL_MAX_CALLS,
+ global_window_s: float = _GLOBAL_WINDOW_S,
+ clock: Callable[[], float] = time.monotonic,
+ ) -> None:
+ self._cooldown_s = cooldown_s
+ self._global_max = global_max
+ self._global_window_s = global_window_s
+ self._clock = clock
+ self._lock = threading.Lock()
+ self._last: dict[tuple[str, str, bool], float] = {}
+ self._recent: dict[bool, deque[float]] = {True: deque(), False: deque()}
+
+ def admit(self, action: str, permission: PermissionId, *, ui: bool = True) -> _Refusal | None:
+ """``None`` and the call is counted, or why it is refused (nothing is counted)."""
+ now = self._clock()
+ key = (action, permission.value, ui)
+ recent = self._recent[ui]
+ with self._lock:
+ while recent and now - recent[0] >= self._global_window_s:
+ recent.popleft()
+ last = self._last.get(key)
+ if last is not None and now - last < self._cooldown_s:
+ return _Refusal("permission", self._cooldown_s - (now - last))
+ if len(recent) >= self._global_max:
+ return _Refusal("global", self._global_window_s - (now - recent[0]))
+ self._last[key] = now
+ recent.append(now)
+ return None
+
+
+@dataclass(frozen=True, slots=True)
+class _BoundedResult:
+ finished: bool
+ value: Any = None
+ # True: a previous call of this slot is still running, so nothing was started.
+ busy: bool = False
+ # True: the call raised (logged at debug); there is no value.
+ failed: bool = False
+
+ @property
+ def ok(self) -> bool:
+ return self.finished and not self.failed
+
+
+class _Bounded:
+ """Runs ONE call at a time on a daemon thread and waits for it at most ``timeout_s``.
+
+ A native Apple Events probe can hang for a running player that has no window
+ (Apple forums thread 666528) and an Automation ask blocks until the dialog is
+ answered. A route must answer anyway: the call keeps its thread, the route gets
+ ``finished=False``, and while that thread lives no second one is started (a
+ hung probe must not pile up threads). A late answer is discarded.
+ """
+
+ def __init__(self, name: str) -> None:
+ self._name = name
+ self._lock = threading.Lock()
+ self._thread: threading.Thread | None = None
+
+ def run(self, call: Callable[[], Any], timeout_s: float) -> _BoundedResult:
+ box: dict[str, Any] = {}
+
+ def target() -> None:
+ try:
+ box["value"] = call()
+ except Exception: # noqa: BLE001 - the thread must never die loudly, the route reports it
+ log.debug("The bounded %s call failed.", self._name, exc_info=True)
+ box["failed"] = True
+
+ with self._lock:
+ if self._thread is not None and self._thread.is_alive():
+ return _BoundedResult(finished=False, busy=True)
+ thread = threading.Thread(target=target, name=f"permissions-{self._name}", daemon=True)
+ self._thread = thread
+ thread.start()
+ thread.join(timeout_s)
+ if thread.is_alive():
+ log.debug("The bounded %s call did not finish within %.1f s.", self._name, timeout_s)
+ return _BoundedResult(finished=False)
+ return _BoundedResult(finished=True, value=box.get("value"), failed=bool(box.get("failed")))
+
+
+class _Runtime:
+ """The mutable state of the permission routes of ONE app (rate limits, bounded calls)."""
+
+ def __init__(self) -> None:
+ self.limiter = _RateLimiter()
+ self.automation_probe = _Bounded("automation-probe")
+ self.automation_ask = _Bounded("automation-ask")
+ self.refresh = _Bounded("episode-refresh")
+
+
+_RUNTIME_LOCK = threading.Lock()
+
+
+def _runtime(request: Request) -> _Runtime:
+ state = request.app.state
+ runtime = getattr(state, "permissions_runtime", None)
+ if runtime is None:
+ with _RUNTIME_LOCK:
+ runtime = getattr(state, "permissions_runtime", None)
+ if runtime is None:
+ runtime = _Runtime()
+ state.permissions_runtime = runtime
+ return runtime
+
+
+def _service(request: Request) -> PermissionService:
+ """The permission service: ``app.state.permission_service`` when a test injected one."""
+ injected = getattr(request.app.state, "permission_service", None)
+ return injected if injected is not None else get_permission_service()
+
+
+def _ducking_enabled(request: Request) -> bool:
+ """Whether the user switched "Mute music while dictating" on (``[ducking].enabled``)."""
+ state = request.app.state
+ config = getattr(state, "config", None) or getattr(state, "cfg", None)
+ return bool(getattr(getattr(config, "ducking", None), "enabled", False))
+
+
+# ----------------------------------------------------------------------
+# Reading: rows and the snapshot
+# ----------------------------------------------------------------------
+
+
+def _worst_automation(states: list[PermissionState]) -> PermissionState:
+ """One state for every scriptable player: the strictest answer wins.
+
+ A player that is not installed (``NOT_REQUIRED``) takes no part. A running player
+ that was never asked, and a player that is not running at all, both read
+ ``NOT_DETERMINED``: the port cannot tell "unknown" from "not asked" for a player
+ that is closed, which is why the row says it is checked while the player runs.
+ """
+ relevant = [state for state in states if state is not PermissionState.NOT_REQUIRED]
+ if not relevant:
+ return PermissionState.NOT_REQUIRED
+ if PermissionState.DENIED in relevant:
+ return PermissionState.DENIED
+ if any(state in _UNDECIDED for state in relevant):
+ return PermissionState.NOT_DETERMINED
+ for wanted in (PermissionState.RESTRICTED, PermissionState.UNAVAILABLE):
+ if wanted in relevant:
+ return wanted
+ return PermissionState.GRANTED
+
+
+def _read_automation(service: PermissionService) -> list[PermissionState]:
+ """Read-only, per player: never the aggregate read (it rewrites the consent record)."""
+ return [
+ service.check(PermissionId.AUTOMATION, target=bundle_id)
+ for bundle_id in _AUTOMATION_PLAYERS
+ ]
+
+
+def _automation_players(
+ service: PermissionService, runtime: _Runtime
+) -> list[PermissionState] | None:
+ """One state per scriptable player, or ``None`` when the probe did not answer in time."""
+ result = runtime.automation_probe.run(
+ lambda: _read_automation(service), _AUTOMATION_PROBE_TIMEOUT_S
+ )
+ if result.ok and isinstance(result.value, list):
+ return result.value
+ return None
+
+
+def _automation_state(
+ service: PermissionService, runtime: _Runtime
+) -> tuple[PermissionState, bool, list[PermissionState]]:
+ """``(state, answered, per-player states)``; an unanswered probe reads UNAVAILABLE.
+
+ The per-player list follows ``AUTOMATION_TARGETS`` and is empty when the probe did
+ not answer in time.
+ """
+ states = _automation_players(service, runtime)
+ if states is None:
+ return PermissionState.UNAVAILABLE, False, []
+ return _worst_automation(states), True, states
+
+
+def _row_detail(
+ permission: PermissionId,
+ state: PermissionState,
+ *,
+ darwin: bool,
+ restart_hint: bool,
+ answered: bool,
+ refused_targets: tuple[str, ...] = (),
+) -> str:
+ """One English sentence for the row, from fixed templates only (never OS text)."""
+ if state is PermissionState.NOT_REQUIRED:
+ if darwin and permission is PermissionId.AUTOMATION:
+ return _AUTOMATION_NO_PLAYER
+ return _NOT_REQUIRED_DETAIL
+ if restart_hint:
+ # A real failed use while the state reads granted (a wallpaper-only capture,
+ # a deaf event tap): the row stays granted but says what to do.
+ return user_detail_for(permission, "restart_hint")
+ if refused_targets:
+ # A real Apple Event to a player was refused (-1743) although its probe reads
+ # granted: the row keeps the probe's status but names each such player.
+ sentences = " ".join(
+ user_detail_for(permission, "needs_settings", target=bundle_id, refused_use=True)
+ for bundle_id in refused_targets
+ )
+ return f"{sentences} {_AUTOMATION_NOTE}"
+ if state is PermissionState.GRANTED:
+ return ""
+ if permission is PermissionId.AUTOMATION and not answered:
+ return _AUTOMATION_NO_ANSWER
+ if permission is PermissionId.CREDENTIAL_STORE and state is PermissionState.NOT_GRANTED:
+ return _KEYCHAIN_DECLINED
+ sentence = user_detail_for(permission, _REASON_OF_STATE.get(state, "unavailable"))
+ if permission is PermissionId.AUTOMATION:
+ return f"{sentence} {_AUTOMATION_NOTE}"
+ return sentence
+
+
+def _build_row(
+ service: PermissionService,
+ runtime: _Runtime,
+ info: AppInfo,
+ permission: PermissionId,
+ restart_hint_for: frozenset[str],
+ refused_for: frozenset[str] = frozenset(),
+) -> PermissionRow:
+ answered = True
+ refused_targets: tuple[str, ...] = ()
+ if permission is PermissionId.AUTOMATION:
+ state, answered, players = _automation_state(service, runtime)
+ # The signature of a refused send: an open needs_settings episode names a player
+ # whose probe nevertheless reads granted (a plain needs_settings has a probe that
+ # reads undecided, and the episode closes when it turns granted).
+ refused_targets = tuple(
+ bundle_id
+ for bundle_id, player_state in zip(_AUTOMATION_PLAYERS, players, strict=False)
+ if bundle_id in refused_for and player_state is PermissionState.GRANTED
+ )
+ else:
+ state = service.check(permission)
+ darwin = info.platform == "darwin"
+ # A desktop session is needed for anything that opens a dialog or a window.
+ interactive = darwin and not info.headless
+ pane = settings_path_text(permission)
+ if permission is PermissionId.CREDENTIAL_STORE:
+ # The Keychain has no request call; "Try again" replays the failed read.
+ can_request = interactive and state is PermissionState.NOT_GRANTED
+ elif permission is PermissionId.AUTOMATION:
+ can_request = interactive and answered and service.can_request(permission, state)
+ else:
+ can_request = interactive and service.can_request(permission, state)
+ return {
+ "id": permission.value,
+ "label": _ROW_LABELS[permission],
+ "status": state.value,
+ "used_for": list(_USED_FOR[permission]),
+ "can_request": can_request,
+ # Opening a pane is not a prompt and not an action on the permission, so
+ # it does not need the installed-app identity (design P6): it needs a
+ # desktop session and a pane, which is exactly what the route checks.
+ "can_open_settings": interactive and pane is not None,
+ # tccutil is scoped to this app's own bundle id, so only the installed app
+ # may reset (P6); a developer run must not wipe the installed app's rows.
+ "can_reset": (
+ interactive
+ and info.stable
+ and permission is not PermissionId.CREDENTIAL_STORE
+ and state in _RESETTABLE
+ ),
+ # An open restart_hint episode is a REAL failed use, so it shows even when
+ # the state reads granted (that is exactly the case it was reported for).
+ "restart_hint": permission.value in restart_hint_for
+ and state is not PermissionState.NOT_REQUIRED,
+ "detail": _row_detail(
+ permission,
+ state,
+ darwin=darwin,
+ restart_hint=permission.value in restart_hint_for,
+ answered=answered,
+ refused_targets=refused_targets,
+ ),
+ # The textual path of the pane; there is no System Settings off macOS.
+ "settings_path": pane if darwin else None,
+ }
+
+
+def _refresh_edges(service: PermissionService, runtime: _Runtime) -> None:
+ """Re-read the open episodes so a resolve edge is published from this path too.
+
+ The episode watcher does it every two seconds; a status read does it as well,
+ so an edge is emitted whichever path sees it first. Only when something is open,
+ and bounded: an Automation episode reads a running player.
+ """
+ if not service.outstanding():
+ return
+ result = runtime.refresh.run(service.refresh_episodes, _REFRESH_TIMEOUT_S)
+ if not result.finished:
+ log.debug("The episode refresh did not finish in time; the watcher keeps going.")
+
+
+def _note_activated(service: PermissionService, activated: bool) -> None:
+ """The caller says the window just regained focus: tell the service (never raises)."""
+ if not activated:
+ return
+ try:
+ service.note_app_activated()
+ except Exception: # noqa: BLE001 - a focus hint must never turn a GET into a 500
+ log.debug("note_app_activated() failed.", exc_info=True)
[email protected]("/status", summary="Inspect system permission readiness")
-def get_permissions_status(request: Request) -> dict:
- """Return a fresh native permission and feature-readiness snapshot."""
- return _port(request).snapshot()
+def _restart_hints(needed: list[NeededEpisode]) -> frozenset[str]:
+ return frozenset(
+ permission
+ for episode in needed
+ if episode["reason"] == "restart_hint"
+ for permission in episode["permissions"]
+ )
+
+
+def _refused_targets(needed: list[NeededEpisode]) -> frozenset[str]:
+ """The players an open ``needs_settings`` Automation episode names (a refused send, maybe)."""
+ return frozenset(
+ episode["target"]
+ for episode in needed
+ if episode["reason"] == "needs_settings"
+ and "automation" in episode["permissions"]
+ and episode["target"] in _AUTOMATION_PLAYERS
+ )
+
+
+def _needed(service: PermissionService) -> list[NeededEpisode]:
+ return [cast("NeededEpisode", episode.as_dict()) for episode in service.outstanding()]
+
+
+def _build_snapshot(
+ service: PermissionService, runtime: _Runtime, *, include_automation: bool
+) -> PermissionsSnapshot:
+ info = service.app_info()
+ _refresh_edges(service, runtime)
+ needed = _needed(service)
+ hints = _restart_hints(needed)
+ refused = _refused_targets(needed)
+ rows = [
+ _build_row(service, runtime, info, permission, hints, refused)
+ for permission in _ROW_ORDER
+ if include_automation or permission is not PermissionId.AUTOMATION
+ ]
+ return {
+ "platform": info.platform,
+ "supported": info.platform == "darwin",
+ "headless": info.headless,
+ "app_identity": {
+ "app_name": info.app_name,
+ "bundle_id": info.bundle_id,
+ "bundle_path": info.bundle_path,
+ "launched_as_bundle": info.launched_as_bundle,
+ "stable": info.stable,
+ },
+ "outside_installed_app": info.outside_installed_app,
+ "permissions": rows,
+ "needed": needed,
+ }
+
+
+def _single_row(
+ service: PermissionService, runtime: _Runtime, permission: PermissionId
+) -> PermissionRow:
+ """One row without the full snapshot (a cheap poll for a single permission)."""
+ family = PANE_FAMILY[permission]
+ info = service.app_info()
+ needed = _needed(service)
+ return _build_row(
+ service, runtime, info, family, _restart_hints(needed), _refused_targets(needed)
+ )
+
+
[email protected]("/status", summary="Inspect macOS privacy permissions", response_model=None)
+def get_permissions_status(
+ request: Request,
+ include: str | None = Query(
+ default=None,
+ description="Comma-separated extras; 'automation' adds the Automation row.",
+ ),
+ activated: bool = Query(
+ default=False,
+ description="1 on the first refetch after the window regained focus.",
+ ),
+) -> PermissionsSnapshot:
+ """Return the passive permission snapshot. It never prompts and never blocks.
+
+ ``activated=1`` (the first refetch after the window regained focus) first tells
+ the service the app was refocused, see the module docstring.
+ """
+ wanted = {part.strip() for part in (include or "").split(",")}
+ include_automation = "automation" in wanted or _ducking_enabled(request)
+ service = _service(request)
+ _note_activated(service, activated and not _is_agent_caller(request))
+ return _build_snapshot(service, _runtime(request), include_automation=include_automation)
+
+
[email protected]("/{permission_id}", summary="Read one privacy permission row", response_model=None)
+def get_permission(
+ permission_id: PermissionId,
+ request: Request,
+ activated: bool = Query(
+ default=False,
+ description="1 on the first refetch after the window regained focus.",
+ ),
+) -> PermissionRow:
+ """One cheap row; also re-reads open episodes so a resolve edge is published here.
+
+ ``event_posting`` is an alias of ``accessibility`` and answers with that row.
+ ``activated=1`` (the first refetch after the window regained focus) first tells
+ the service the app was refocused, see the module docstring.
+ """
+ service = _service(request)
+ runtime = _runtime(request)
+ _note_activated(service, activated and not _is_agent_caller(request))
+ _refresh_edges(service, runtime)
+ return _single_row(service, runtime, permission_id)
-def _operation_response(payload: dict) -> Any:
+
+# ----------------------------------------------------------------------
+# Acting: request, open settings, reset
+# ----------------------------------------------------------------------
+
+
+class PermissionRequestBody(BaseModel):
+ """Optional body of ``POST /{id}/request``. Unknown keys are refused (a typo must
+ never silently drop a consent flag)."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ # True ONLY after the person confirmed that macOS will record the grant for the
+ # app that started Jarvis (a terminal, an IDE) because Jarvis is not the
+ # installed app. Never a default, never inferred.
+ allow_outside_app: bool = False
+ # The feature the ask is attributed to (``PERMISSION_FEATURES``); defaults to the
+ # first feature that uses the permission.
+ feature: str | None = None
+ # Automation only: the bundle id of ONE player (``AUTOMATION_TARGETS``). Without
+ # it the route picks the first player that can still be asked.
+ target: str | None = None
+
+ @field_validator("feature")
+ @classmethod
+ def _known_feature(cls, value: str | None) -> str | None:
+ if value is not None and value not in PERMISSION_FEATURES:
+ raise ValueError(f"feature must be one of: {', '.join(PERMISSION_FEATURES)}")
+ return value
+
+ @field_validator("target")
+ @classmethod
+ def _known_player(cls, value: str | None) -> str | None:
+ if value is not None and value not in _AUTOMATION_PLAYERS:
+ raise ValueError(f"target must be one of: {', '.join(_AUTOMATION_PLAYERS)}")
+ return value
+
+
+def _is_agent_caller(request: Request) -> bool:
+ """Whether the request is NOT positively the person at the Jarvis window.
+
+ The person is identified by what only the desktop UI carries: its session cookie,
+ or (open local access, the default, has no cookie at all) the browser-set
+ ``Sec-Fetch-Site: same-origin`` header on a request without an ``Authorization``
+ header. Everything else is treated as an agent: a script that presents the control
+ key, and equally a local process that presents NO credential at all (open access
+ lets it reach this router). Two things are for a person at the UI only (P9, P4):
+ confirming that macOS may record a grant for the app that started Jarvis, and an
+ explicit click that skips the re-ask cooldown; neither is open to an agent.
+
+ Honest limit: ``Sec-Fetch-Site`` is a "forbidden header" for page scripts, so a
+ page cannot fake it, but a local process that deliberately forges it is
+ indistinguishable from the WebView; this is a guard against an agent that
+ follows its instructions, not a boundary against malware (the permission dialog
+ itself stays macOS's). Whether the macOS WebView sends the header on every
+ supported release is UNVERIFIED; a WebView without it only loses the two
+ conveniences above and nothing is ever granted by it.
+ """
+ if validate_token(request.cookies.get(COOKIE_NAME, "")):
+ return False
+ if _bearer_token(request) is not None:
+ return True
+ return request.headers.get("sec-fetch-site", "").strip().lower() != "same-origin"
+
+
+def _requires_ui_response(detail: str) -> JSONResponse:
+ """The 403 for something only a person at the Jarvis window may do."""
+ return JSONResponse(
+ status_code=403,
+ content={"error": "confirmation_requires_ui", "detail": detail},
+ )
+
+
+def _operation(
+ permission_id: PermissionId,
+ action: str,
+ *,
+ ok: bool,
+ message: str,
+ performed: bool = False,
+ dry_run: bool = False,
+ row: PermissionRow | None = None,
+) -> OperationPayload:
+ return {
+ "ok": ok,
+ "permission_id": permission_id.value,
+ "action": action,
+ "performed": performed,
+ "dry_run": dry_run,
+ "message": message,
+ "permission": row,
+ }
+
+
+def _operation_response(payload: OperationPayload) -> Any:
if payload["ok"]:
return payload
return JSONResponse(status_code=409, content=payload)
+def _rate_limited(refusal: _Refusal, action: str, permission_id: PermissionId) -> JSONResponse:
+ retry_after = max(1, math.ceil(refusal.retry_after_s))
+ body: RateLimitedPayload = {
+ "error": "rate_limited",
+ "scope": refusal.scope,
+ "action": action,
+ "permission_id": permission_id.value,
+ "retry_after_s": retry_after,
+ }
+ return JSONResponse(status_code=429, content=body, headers={"Retry-After": str(retry_after)})
+
+
+def _ensure_payload(result: EnsureResult) -> EnsurePayload:
+ return {
+ "permission": result.permission.value,
+ "outcome": result.outcome.value,
+ "granted": result.granted,
+ "state": result.state.value,
+ "asked": result.asked,
+ "outside_installed_app": result.outside_installed_app,
+ "reason": result.reason,
+ "can_prompt": result.can_prompt,
+ "can_open_settings": result.can_open_settings,
+ "target": result.target,
+ "user_detail": result.user_detail,
+ "agent_detail": result.agent_detail,
+ }
+
+
+def _asking_result(permission: PermissionId, target: str, *, asked: bool) -> EnsureResult:
+ """PENDING, for an Automation ask whose dialog is still open when the route answers."""
+ family = PANE_FAMILY[permission]
+ return EnsureResult(
+ permission=permission,
+ outcome=PermissionOutcome.PENDING,
+ state=PermissionState.NOT_DETERMINED,
+ asked=asked,
+ outside_installed_app=False,
+ agent_detail=agent_detail_for(family, "not_determined", target=target, asking=True),
+ user_detail=user_detail_for(family, "not_determined", target=target, asking=True),
+ reason="not_determined",
+ can_prompt=False,
+ can_open_settings=settings_path_text(family) is not None,
+ target=target,
+ )
+
+
+def _unavailable_result(permission: PermissionId, target: str) -> EnsureResult:
+ family = PANE_FAMILY[permission]
+ return EnsureResult(
+ permission=permission,
+ outcome=PermissionOutcome.UNAVAILABLE,
+ state=PermissionState.UNAVAILABLE,
+ asked=False,
+ outside_installed_app=False,
+ agent_detail=agent_detail_for(family, "unavailable", target=target),
+ user_detail=user_detail_for(family, "unavailable", target=target),
+ reason="unavailable",
+ target=target,
+ )
+
+
+def _ask_automation(
+ service: PermissionService,
+ permission: PermissionId,
+ *,
+ feature: str,
+ target: str | None,
+ allow_outside_app: bool,
+ force_ask: bool,
+) -> EnsureResult:
+ """Ask for ONE player: the named one, else the first that can still be asked.
+
+ The service runs the consent runner on its own thread and this call waits only
+ :data:`_AUTOMATION_SETTLE_S` for it, so a closed player (the guarded script ends
+ at once) is told from an open dialog. It still runs through :class:`_Bounded`,
+ because the state read before the ask can hang. A player that is not running is
+ not launched and not asked (the runner is guarded), which reads UNAVAILABLE
+ here; the next player is tried.
+ """
+ if target:
+ candidates = [target]
+ else:
+ undecided = [
+ bundle_id
+ for bundle_id in _AUTOMATION_PLAYERS
+ if service.check(PermissionId.AUTOMATION, target=bundle_id) in _UNDECIDED
+ ]
+ candidates = undecided or list(_AUTOMATION_PLAYERS[:1])
+ result = _unavailable_result(permission, "")
+ for bundle_id in candidates:
+ result = service.ensure(
+ permission,
+ feature=feature,
+ interactive=True,
+ wait_s=_AUTOMATION_SETTLE_S,
+ target=bundle_id,
+ allow_outside_app=allow_outside_app,
+ force_ask=force_ask,
+ )
+ # ``asked`` is true even when the guarded script found the player closed and
+ # showed nothing; only the outcome says whether this player is worth stopping at.
+ if result.outcome is not PermissionOutcome.UNAVAILABLE:
+ break
+ return result
+
+
+def _keychain_result(state: PermissionState, *, asked: bool) -> EnsureResult:
+ """The Keychain "Try again" answer, in the shape of every other ask."""
+ permission = PermissionId.CREDENTIAL_STORE
+ if state in _READY:
+ outcome = (
+ PermissionOutcome.NOT_REQUIRED
+ if state is PermissionState.NOT_REQUIRED
+ else PermissionOutcome.GRANTED
+ )
+ return EnsureResult(permission, outcome, state, asked, False, "", "")
+ declined = state is PermissionState.NOT_GRANTED
+ reason = "denied" if declined else "unavailable"
+ return EnsureResult(
+ permission=permission,
+ outcome=PermissionOutcome.DENIED if declined else PermissionOutcome.UNAVAILABLE,
+ state=state,
+ asked=asked,
+ outside_installed_app=False,
+ agent_detail=agent_detail_for(permission, reason),
+ user_detail=_KEYCHAIN_DECLINED if declined else user_detail_for(permission, reason),
+ reason=reason,
+ can_prompt=declined,
+ can_open_settings=False,
+ )
+
+
+def _retry_keychain(service: PermissionService) -> EnsureResult:
+ """Replay the failed Keychain read, the one supported way to make macOS ask again."""
+ state = service.check(PermissionId.CREDENTIAL_STORE)
+ if state is not PermissionState.NOT_GRANTED:
+ return _keychain_result(state, asked=False)
+ port = _permissions_module.get_system_permission_port()
+ try:
+ port.request_native(PermissionId.CREDENTIAL_STORE)
+ except Exception: # noqa: BLE001 - the replay is best-effort, the state read below is the truth
+ log.debug("Replaying the Keychain read failed.", exc_info=True)
+ service.invalidate(PermissionId.CREDENTIAL_STORE)
+ return _keychain_result(service.check(PermissionId.CREDENTIAL_STORE), asked=True)
+
+
@router.post(
"/{permission_id}/request",
- summary="Request a system permission",
+ summary="Ask macOS for a permission",
openapi_extra={"x-jarvis-dangerous": True},
response_model=None,
)
def request_permission(
permission_id: PermissionId,
request: Request,
+ body: Annotated[PermissionRequestBody | None, Body()] = None,
dry_run: bool = Query(default=False),
) -> Any:
- """Trigger an Apple prompt only from the foreground installed app."""
- payload = _port(request).request(permission_id, dry_run=dry_run).to_dict()
- return _operation_response(payload)
+ """Ask for ONE permission from a user gesture and answer with the outcome at once.
+
+ The just-in-time service asks macOS at most once per episode and never refuses
+ an action because its own preflight said "not granted"; the answer is its
+ ``EnsureResult`` (PENDING while a system dialog may be open, NEEDS_SETTINGS when
+ the person has to flip a switch, DENIED once macOS will not ask again). The
+ decision itself arrives later as ``PermissionResolved``. Outside the installed
+ app nothing is asked unless the body says ``allow_outside_app``: the person's
+ one "Ask macOS now" click on a toast that says the app that started Jarvis
+ receives the grant. Rate limited (429).
+ """
+ options = body if body is not None else PermissionRequestBody()
+ agent_caller = _is_agent_caller(request)
+ if options.allow_outside_app and agent_caller:
+ # Confirming "macOS may grant this to the app that started Jarvis" is a
+ # decision for a person at the Jarvis window (the toast says, in one generic
+ # sentence, that the app that started Jarvis receives the grant), never for
+ # an agent that holds the control key (P9).
+ return _requires_ui_response(
+ "Confirming a grant for the app that started Jarvis needs the Jarvis "
+ "window; a script or the control key cannot do it."
+ )
+ label = _ROW_LABELS.get(PANE_FAMILY[permission_id], permission_id.value)
+ if dry_run:
+ return _operation(
+ permission_id,
+ "request",
+ ok=True,
+ dry_run=True,
+ message=f"Would request {label} access.",
+ )
+ runtime = _runtime(request)
+ refusal = runtime.limiter.admit("request", PANE_FAMILY[permission_id], ui=not agent_caller)
+ if refusal is not None:
+ return _rate_limited(refusal, "request", permission_id)
+ service = _service(request)
+ family = PANE_FAMILY[permission_id]
+ if family is PermissionId.CREDENTIAL_STORE:
+ return _ensure_payload(_retry_keychain(service))
+ feature = options.feature or _USED_FOR[family][0]
+ if family is PermissionId.AUTOMATION:
+ asked = runtime.automation_ask.run(
+ lambda: _ask_automation(
+ service,
+ permission_id,
+ feature=feature,
+ target=options.target,
+ allow_outside_app=options.allow_outside_app,
+ force_ask=not agent_caller,
+ ),
+ _AUTOMATION_ASK_WAIT_S,
+ )
+ if asked.ok and isinstance(asked.value, EnsureResult):
+ return _ensure_payload(asked.value)
+ if asked.finished:
+ # The call raised (logged); nothing is known, so nothing is promised.
+ return _ensure_payload(_unavailable_result(permission_id, options.target or ""))
+ # The consent dialog is still open (or the check hung): macOS owns the next
+ # step, the answer arrives as PermissionResolved. Never an HTTP hold.
+ return _ensure_payload(
+ _asking_result(permission_id, options.target or "", asked=not asked.busy)
+ )
+ result = service.ensure(
+ permission_id,
+ feature=feature,
+ interactive=True,
+ wait_s=0.0,
+ allow_outside_app=options.allow_outside_app,
+ # An explicit click on "Allow" is never held back by the re-ask cooldown; a
+ # request that only carries the control key (an agent) is (P4).
+ force_ask=not agent_caller,
+ )
+ return _ensure_payload(result)
@router.post(
@@ -65,9 +1054,42 @@ def open_permission_settings(
request: Request,
dry_run: bool = Query(default=False),
) -> Any:
- """Open the matching pane only for a local foreground app interaction."""
- payload = _port(request).open_settings(permission_id, dry_run=dry_run).to_dict()
- return _operation_response(payload)
+ """Open the matching System Settings pane. Not a prompt; rate limited (429)."""
+ family = PANE_FAMILY[permission_id]
+ label = _ROW_LABELS.get(family, permission_id.value)
+ if settings_path_text(family) is None:
+ return _operation_response(
+ _operation(
+ permission_id,
+ "open_settings",
+ ok=False,
+ message=f"{label} has no System Settings pane; use the request flow instead.",
+ )
+ )
+ if dry_run:
+ return _operation(
+ permission_id,
+ "open_settings",
+ ok=True,
+ dry_run=True,
+ message=f"Would open {label} in System Settings.",
+ )
+ runtime = _runtime(request)
+ refusal = runtime.limiter.admit("open_settings", family, ui=not _is_agent_caller(request))
+ if refusal is not None:
+ return _rate_limited(refusal, "open_settings", permission_id)
+ service = _service(request)
+ opened = service.open_settings(permission_id)
+ return _operation_response(
+ _operation(
+ permission_id,
+ "open_settings",
+ ok=opened,
+ performed=opened,
+ message="System Settings opened." if opened else "System Settings could not be opened.",
+ row=_single_row(service, runtime, permission_id),
+ )
+ )
@router.post(
@@ -81,14 +1103,108 @@ def reset_permission(
request: Request,
dry_run: bool = Query(default=False),
) -> Any:
- """Drop the app's own macOS TCC row so the native prompt can reappear.
+ """Drop the app's own macOS TCC row so the question can be asked again ("Ask again").
- Recovery for the permanently-"Denied" trap: macOS auto-denies an app
- that ever listened before being asked and then never prompts again.
- Scoped strictly to this app's bundle id; other apps stay untouched.
+ Recovery for the stranded decision: macOS auto-denies an app that ever listened
+ before it was asked, or whose signature changed (BUG-083), and then never asks
+ again. Scoped strictly to this app's bundle id by the port, so only the
+ installed app can do it; other apps stay untouched. Refused with 409 while the
+ permission is live GRANTED (a reset would throw a working grant away) and
+ whenever the live state cannot be read. Refused with 403 for an agent (a script, the
+ control key, a caller with no credential): a reset forgets the re-ask cooldown, so
+ "reset, then request" would be a prompt loop; "Ask again" is a click in the window.
"""
- payload = _port(request).reset(permission_id, dry_run=dry_run).to_dict()
- return _operation_response(payload)
+ service = _service(request)
+ runtime = _runtime(request)
+ family = PANE_FAMILY[permission_id]
+ label = _ROW_LABELS.get(family, permission_id.value)
+ agent_caller = _is_agent_caller(request)
+ if agent_caller and not dry_run:
+ # A reset forgets the re-ask cooldown, so "reset, then request" from a script
+ # would make macOS ask over and over and undo a denial the person gave (P4).
+ # "Ask again" is a click in the Jarvis window.
+ return _requires_ui_response(
+ "Resetting a privacy permission needs the Jarvis window; a script or the "
+ "control key cannot do it."
+ )
+ if not dry_run:
+ # "Reset, then request" in a loop would defeat the re-ask limits (P4), so a
+ # reset is rate limited like the other two routes that change what macOS shows.
+ refusal = runtime.limiter.admit("reset", family)
+ if refusal is not None:
+ return _rate_limited(refusal, "reset", permission_id)
+ info = service.app_info()
+ if info.platform != "darwin":
+ return _operation_response(
+ _operation(
+ permission_id,
+ "reset",
+ ok=False,
+ dry_run=dry_run,
+ message="Resetting a privacy permission is only possible on macOS.",
+ )
+ )
+ if family is PermissionId.AUTOMATION:
+ players = _automation_players(service, runtime)
+ # tccutil drops the whole Apple Events row, so ONE working player is enough
+ # to refuse: the strictest-answer aggregate would hide it behind another
+ # player that was never asked.
+ if players is not None and PermissionState.GRANTED in players:
+ live = PermissionState.GRANTED
+ else:
+ live = (
+ _worst_automation(players) if players is not None else PermissionState.UNAVAILABLE
+ )
+ else:
+ live = service.check_deep(permission_id)
+ if live in _READY:
+ return _operation_response(
+ _operation(
+ permission_id,
+ "reset",
+ ok=False,
+ dry_run=dry_run,
+ message=f"{label} is allowed right now, so there is nothing to reset.",
+ )
+ )
+ if live not in _RESETTABLE:
+ return _operation_response(
+ _operation(
+ permission_id,
+ "reset",
+ ok=False,
+ dry_run=dry_run,
+ message=f"{label} cannot be reset from here (it reads {live.value}).",
+ )
+ )
+ port = _permissions_module.get_system_permission_port()
+ # The light entry point: no snapshot, so no Automation probe and no window-title
+ # oracle behind a route that must stay bounded.
+ operation = port.reset_row(permission_id, dry_run=dry_run)
+ if operation.ok and operation.performed:
+ # "Ask again" must really ask: forget this process's request cooldown.
+ service.note_reset(permission_id)
+ return _operation_response(
+ _operation(
+ permission_id,
+ "reset",
+ ok=operation.ok,
+ performed=operation.performed,
+ dry_run=operation.dry_run,
+ message=operation.message,
+ row=None if dry_run else _single_row(service, runtime, permission_id),
+ )
+ )
-__all__ = ["router"]
+__all__ = [
+ "AppIdentityBlock",
+ "EnsurePayload",
+ "NeededEpisode",
+ "OperationPayload",
+ "PermissionRequestBody",
+ "PermissionRow",
+ "PermissionsSnapshot",
+ "RateLimitedPayload",
+ "router",
+]
diff --git a/jarvis/ui/web/screen_context_routes.py b/jarvis/ui/web/screen_context_routes.py
index 0d33f8a4d4..9fc89cdf5e 100644
--- a/jarvis/ui/web/screen_context_routes.py
+++ b/jarvis/ui/web/screen_context_routes.py
@@ -207,9 +207,21 @@ def _resolved_locale(locale: str, text: str) -> str:
)
+def _issue_text(issue: Any) -> str:
+ """The sentence of a permission issue: a structured issue carries ``message``."""
+ if not issue:
+ return ""
+ return str(getattr(issue, "message", issue))
+
+
@router.get("/status")
async def status(request: Request) -> dict[str, Any]:
- """Capability and live state — answers honestly on a machine with no screen."""
+ """Capability and live state — answers honestly on a machine with no screen.
+
+ Never prompts: the permission probes it runs only READ the state. A capture
+ that a person starts is what asks macOS (``POST /capture`` ->
+ ``ScreenContextService.capture``), never a status poll.
+ """
import asyncio # noqa: PLC0415
service = _get_service(request)
@@ -229,7 +241,7 @@ async def status(request: Request) -> dict[str, Any]:
ocr,
) = await asyncio.gather(
asyncio.to_thread(service.displays.monitors),
- asyncio.to_thread(capture_permission_error),
+ asyncio.to_thread(capture_permission_error, deep=False),
asyncio.to_thread(service.cursor.position),
asyncio.to_thread(_capture_backend_capability),
asyncio.to_thread(_indicator_capability),
@@ -251,7 +263,7 @@ async def status(request: Request) -> dict[str, Any]:
for ready, reason in (
(service.settings.enabled, "Screen Context is switched off."),
(display_ready, "No interactive display was found."),
- (permission_ready, str(permission_error or "")),
+ (permission_ready, _issue_text(permission_error)),
(capture_ready, capture_reason),
(indicator_ready, indicator_reason),
(vision_ready, vision_reason),
@@ -272,7 +284,7 @@ async def status(request: Request) -> dict[str, Any]:
"capture": {"ready": capture_ready, "detail": capture_reason},
"permission": {
"ready": permission_ready,
- "detail": str(permission_error or ""),
+ "detail": _issue_text(permission_error),
},
"indicator": {"ready": indicator_ready, "detail": indicator_reason},
"vision": {"ready": vision_ready, "detail": vision_reason},
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 5581948231..08a1950edc 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -2557,6 +2557,15 @@ class WebServer:
callable (the fast-boot bootstrap in launcher.py serves a holding app on
the port and delegates to ``self.app`` once this init chain completes).
"""
+ # Just-in-time permissions: the service publishes PermissionNeeded /
+ # PermissionResolved through this bus, from any thread, onto this loop.
+ # FIRST, so a consumer that asks while the rest of start() runs is heard.
+ # It stores two references and probes nothing (AP-26); the desktop app
+ # already did the same right after the ctor, before the speech task.
+ from jarvis.platform.permission_service import attach_bus as _attach_permission_bus
+
+ _attach_permission_bus(self.bus, asyncio.get_running_loop())
+
import uvicorn
# Boot profiling (opt-in via JARVIS_BOOT_PROFILE=1; zero behavior change
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index dadeff0c3d..4daa5bcfdf 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -53,6 +53,13 @@ log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/settings", tags=["settings"])
+def _is_macos() -> bool:
+ """True on macOS. A seam so tests do not patch ``sys.platform`` for the whole process:
+ a global patch makes a first-time import of a third-party package take the wrong
+ platform branch (numpy calls ``os.uname`` when it sees ``linux``, which Windows lacks)."""
+ return sys.platform == "darwin"
+
+
def _realtime_available_provider(cfg: object) -> str | None:
"""Reachable realtime provider name for ``cfg``, or ``None``.
@@ -1099,27 +1106,98 @@ def _config(request: Request):
)
-def _local_microphone_capture_ready(request: Request) -> bool:
- """Non-prompting runtime gate for local macOS microphone diagnostics."""
- if sys.platform != "darwin":
- return True
+def _microphone_service(request: Request): # noqa: ANN202 - the PermissionGate surface
+ """The permission service: ``app.state.permission_service`` when a test injected one."""
+ injected = getattr(request.app.state, "permission_service", None)
+ if injected is not None:
+ return injected
+ from jarvis.platform.permission_service import get_permission_service
+
+ return get_permission_service()
+
+
+def _microphone_state_value(request: Request) -> str:
+ """The silent microphone state (``PermissionState`` value); never asks, never raises.
+
+ Off macOS there is nothing to ask and the answer is ``"not_required"`` without
+ the service being touched.
+ """
+ if not _is_macos():
+ return "not_required"
try:
- from jarvis.platform.permissions import PermissionId, get_system_permission_port
+ state = _microphone_service(request).check("microphone")
+ except Exception: # noqa: BLE001 - an unreadable state is "not usable", never a 500
+ log.debug("Reading the microphone permission failed.", exc_info=True)
+ return "unavailable"
+ return str(getattr(state, "value", state))
- port = getattr(request.app.state, "system_permission_port", None)
- if port is None:
- port = get_system_permission_port()
- return bool(port.runtime_access_granted(PermissionId.MICROPHONE))
- except Exception: # noqa: BLE001 - protected diagnostics must fail closed
- return False
+
+def _local_microphone_capture_ready(request: Request) -> bool:
+ """Silent gate for local microphone diagnostics: True only for a live grant.
+
+ It reads the permission service with ``check`` (never asks, never opens the
+ device); the routes that are a user gesture ask through ``ensure_async`` first.
+ """
+ return _microphone_state_value(request) in ("granted", "not_required")
+
+
+# state -> the reason vocabulary of the permission layer (PERMISSION_NEEDED_REASONS)
+_MIC_STATE_REASON = {
+ "denied": "denied",
+ "restricted": "restricted",
+ "unavailable": "unavailable",
+}
+
+
+def _microphone_block_fields(
+ request: Request, result: object | None = None
+) -> dict[str, object]:
+ """The permission part of a "microphone is not ready" answer.
+
+ ``permission_required`` / ``permission`` / ``can_open_settings`` are the stable
+ keys; ``message`` is the permission layer's finished sentence and ``hint`` points
+ at the one System Settings pane. ``result`` is the ``EnsureResult`` of a gesture
+ route; a silent GET passes none and the sentence is built from the state alone.
+ """
+ from jarvis.platform.permission_service import user_detail_for
+ from jarvis.platform.permissions import SETTINGS_PATH_TEXT, PermissionId
+
+ path = SETTINGS_PATH_TEXT[PermissionId.MICROPHONE]
+ if result is not None:
+ reason = str(getattr(result, "reason", "") or "not_determined")
+ message = str(getattr(result, "user_detail", "") or "")
+ can_open = bool(getattr(result, "can_open_settings", False))
+ else:
+ reason = _MIC_STATE_REASON.get(_microphone_state_value(request), "not_determined")
+ message = ""
+ can_open = reason not in ("restricted", "unavailable")
+ if not message:
+ message = user_detail_for(PermissionId.MICROPHONE, reason)
+ if reason in ("restricted", "unavailable"):
+ hint = ""
+ elif reason == "not_determined":
+ # An app that has never asked is not listed in that pane yet: the test
+ # button is what makes macOS show its dialog, so point there first.
+ hint = "Press the test button and choose Allow in the macOS dialog."
+ else:
+ hint = f"Allow Microphone access in {path}, then retry."
+ return {
+ "permission_required": True,
+ "permission": "microphone",
+ "can_open_settings": can_open,
+ "message": message,
+ "hint": hint,
+ }
-def _blocked_mic_level_result() -> dict[str, object]:
+def _blocked_mic_level_result(
+ request: Request, result: object | None = None
+) -> dict[str, object]:
return {
"max_dbfs": -120.0,
"no_device": False,
"too_quiet": False,
- "permission_required": True,
+ **_microphone_block_fields(request, result),
}
@@ -1475,6 +1553,33 @@ class WakeActivationBody(BaseModel):
enabled: bool
+def _ask_microphone_for_wake_switch(request: Request, *, enabled: bool) -> dict[str, object]:
+ """The wake switch's permission answer: ``{outcome, reason, can_open_settings}``.
+
+ Only switching ON asks (and only on macOS); switching off, and every other OS,
+ answers ``not_required`` without touching the permission layer. Never raises.
+ """
+ answer: dict[str, object] = {
+ "outcome": "not_required",
+ "reason": "",
+ "can_open_settings": False,
+ }
+ if not enabled or not _is_macos():
+ return answer
+ try:
+ result = _microphone_service(request).ensure(
+ "microphone", feature="wake_word", interactive=True, wait_s=0.0
+ )
+ except Exception: # noqa: BLE001 - the switch itself must still be saved
+ log.debug("Asking for the microphone from the wake switch failed.", exc_info=True)
+ return {"outcome": "unavailable", "reason": "unavailable", "can_open_settings": False}
+ return {
+ "outcome": str(getattr(result.outcome, "value", result.outcome)),
+ "reason": str(result.reason or ""),
+ "can_open_settings": bool(result.can_open_settings),
+ }
+
+
@router.post("/wake-word/activation")
def set_wake_activation(body: WakeActivationBody, request: Request) -> dict[str, object]:
"""Turn the always-on wake word ON/OFF — the "how do you activate Jarvis"
@@ -1488,7 +1593,19 @@ def set_wake_activation(body: WakeActivationBody, request: Request) -> dict[str,
Persisted to ``[trigger] wake_word_enabled`` and applied to the running voice
pipeline when available. Headless/voice-disabled processes keep the setting
for their next voice start.
+
+ Switching ON is the user's gesture, so on macOS it is the just-in-time moment
+ for the microphone: the response gains ``permission`` (``{outcome, reason,
+ can_open_settings}``). The switch is saved and applied either way; without a
+ grant the wake loop waits (nothing is heard until it is allowed); a refused
+ permission reaches the app as one toast through ``PermissionNeeded``, and the
+ answer here is for callers that read it (the CLI, agents). Every existing key
+ is kept.
"""
+ # The ask comes FIRST so the OS dialog appears while the rest of the route
+ # works. This handler is a plain ``def`` (a worker thread), so the blocking
+ # ``ensure`` with ``wait_s=0`` is the right form: it never waits for the answer.
+ permission = _ask_microphone_for_wake_switch(request, enabled=bool(body.enabled))
# Persisting is BEST-EFFORT, exactly like every other settings writer here
# (put_ui_language, put_wake_word, put_appearance, ...). This route used to
# raise a 500 instead, and that one inconsistency locked first-time users
@@ -1536,6 +1653,7 @@ def set_wake_activation(body: WakeActivationBody, request: Request) -> dict[str,
if persisted
else f"The setting could not be saved to jarvis.toml. {LOG_HINT}"
),
+ "permission": permission,
}
@@ -1580,6 +1698,7 @@ async def wake_word_self_test(request: Request) -> dict[str, object]:
the word will wake — the acoustic mismatch that a wrong-language model causes
is exactly what (1) surfaces.
"""
+ from jarvis.audio.capture import MicrophoneAccessError
from jarvis.speech.diagnose import measure_mic_dbfs
from jarvis.speech.wake_constants import resolve_vosk_model_path
from jarvis.speech.wake_model_fetch import resolve_wake_language
@@ -1595,7 +1714,9 @@ async def wake_word_self_test(request: Request) -> dict[str, object]:
language=language,
)
- if not _local_microphone_capture_ready(request):
+ def _blocked(
+ phrase_in_vocab: bool | None, request_result: object | None = None
+ ) -> dict[str, object]:
return {
"ok": False,
"phrase": phrase,
@@ -1603,15 +1724,23 @@ async def wake_word_self_test(request: Request) -> dict[str, object]:
"language": language,
"wake_available": bool(plan.wake_available),
"degraded": bool(plan.degraded),
- "phrase_in_vocab": None,
+ "phrase_in_vocab": phrase_in_vocab,
"max_dbfs": -120.0,
"mic_ok": False,
"no_device": False,
- "permission_required": True,
- "message": "Microphone access is not ready for Personal Jarvis.",
- "hint": "Grant Microphone access in Settings > Permissions, then retry.",
+ **_microphone_block_fields(request, request_result),
}
+ # The test button is the just-in-time moment for the microphone: a first press
+ # on an undecided Mac raises the OS dialog and waits for the answer (up to a
+ # minute) without pinning a worker thread. Only a live grant measures anything.
+ if _is_macos():
+ asked = await _microphone_service(request).ensure_async(
+ "microphone", feature="wake_word", interactive=True, wait_s=60.0
+ )
+ if not asked.granted:
+ return _blocked(None, asked)
+
# Vocabulary check only makes sense for the grammar (vosk_kws) engine.
phrase_in_vocab: bool | None = None
if plan.engine == "vosk_kws":
@@ -1630,24 +1759,14 @@ async def wake_word_self_test(request: Request) -> dict[str, object]:
try:
max_dbfs = await measure_mic_dbfs(duration_s=2.0)
+ except MicrophoneAccessError as exc:
+ # The grant was lost between the ask and the capture: a permission answer,
+ # not "no microphone".
+ return _blocked(phrase_in_vocab, getattr(exc, "result", None))
except Exception: # noqa: BLE001 — treat a failed measurement as no device
max_dbfs = -120.0
if not _local_microphone_capture_ready(request):
- return {
- "ok": False,
- "phrase": phrase,
- "engine": plan.engine,
- "language": language,
- "wake_available": bool(plan.wake_available),
- "degraded": bool(plan.degraded),
- "phrase_in_vocab": phrase_in_vocab,
- "max_dbfs": -120.0,
- "mic_ok": False,
- "no_device": False,
- "permission_required": True,
- "message": "Microphone access changed during the self-test.",
- "hint": "Review Microphone access in Settings > Permissions, then retry.",
- }
+ return _blocked(phrase_in_vocab)
mic_ok = max_dbfs > -40.0
no_device = max_dbfs <= -119.9
@@ -1696,16 +1815,22 @@ async def wake_mic_level(request: Request) -> dict[str, object]:
matches ``jarvis.speech.diagnose`` (same measurement helper, so the CLI
diagnostics and this route can never disagree on what "too quiet" means).
"""
+ from jarvis.audio.capture import MicrophoneAccessError
from jarvis.speech.diagnose import measure_mic_dbfs
+ # A GET never asks: it reads the state silently and reports "permission
+ # required" until the gesture routes (the wake switch, the self-test button)
+ # have got the microphone granted.
if not _local_microphone_capture_ready(request):
- return _blocked_mic_level_result()
+ return _blocked_mic_level_result(request)
try:
max_dbfs = await measure_mic_dbfs(duration_s=3.0)
+ except MicrophoneAccessError as exc: # a lost grant is a permission answer, not an error
+ return _blocked_mic_level_result(request, getattr(exc, "result", None))
except Exception: # noqa: BLE001 — defensive guard: if measurement fails, treat as no device
max_dbfs = -120.0
if not _local_microphone_capture_ready(request):
- return _blocked_mic_level_result()
+ return _blocked_mic_level_result(request)
return {
"max_dbfs": max_dbfs,
"no_device": max_dbfs <= -119.9,
@@ -1854,6 +1979,46 @@ def get_keybind_held(request: Request) -> dict[str, object]:
}
+def _ask_input_monitoring_for_saved_shortcut(
+ request: Request, *, hotkey: str, changed: bool = True
+) -> None:
+ """Ask macOS for Input Monitoring because the user just SAVED a global shortcut.
+
+ A global shortcut is a background listener: nothing the user does at the moment
+ they press it could carry a system dialog, so the save is the one gesture that
+ can. macOS only, only for a combo that is actually bound (clearing a shortcut is
+ a no-op for the OS), only when the save CHANGED the combo (re-saving the value
+ already in force is not a new gesture and must not re-open an episode, so a
+ denied permission is not announced again by an identical save), and only while
+ the key tap is not already listening. ``wait_s=0`` returns at once: the route
+ never waits for the dialog, and the outcome reaches the app as
+ ``PermissionNeeded`` / ``PermissionResolved`` (the hotkey trigger re-arms itself
+ on the grant). Never raises and never asks at launch: the save is the only
+ caller.
+
+ Any caller that passes the route's auth counts as the user's gesture, the same
+ as the wake-word activation route: the request is bounded (one ask per episode,
+ never ``allow_outside_app``) and the dialog is macOS's own.
+ """
+ if not hotkey or not changed or not _is_macos():
+ return
+ pipeline = getattr(request.app.state, "speech_pipeline", None)
+ trigger = getattr(pipeline, "_hotkey_trigger", None) if pipeline is not None else None
+ probe = getattr(trigger, "listening", None)
+ if callable(probe):
+ try:
+ if probe() is True:
+ return # the tap is up: Input Monitoring is already working
+ except Exception: # noqa: BLE001 - a failed probe reads "unknown", not "listening"
+ log.debug("The shortcut tap liveness probe failed.", exc_info=True)
+ try:
+ _microphone_service(request).ensure(
+ "input_monitoring", feature="global_shortcuts", interactive=True, wait_s=0.0
+ )
+ except Exception: # noqa: BLE001 - the shortcut itself is saved either way
+ log.debug("Asking for Input Monitoring after a shortcut save failed.", exc_info=True)
+
+
@router.put("/keybinds")
def put_keybind(body: KeybindBody, request: Request) -> dict[str, object]:
from jarvis.core.config_writer import KEYBIND_ACTIONS, KEYBIND_TOML_KEY
@@ -1952,6 +2117,9 @@ def put_keybind(body: KeybindBody, request: Request) -> dict[str, object]:
# (an unbound action cannot collide with anything).
field = KEYBIND_TOML_KEY[action]
+ # Read BEFORE the overwrite below: the Input Monitoring ask only follows a save
+ # that changes the combo.
+ previous = _keybind_values(trig).get(action, "").strip().lower()
if trig is not None:
try:
setattr(trig, field, hotkey)
@@ -1982,6 +2150,10 @@ def put_keybind(body: KeybindBody, request: Request) -> dict[str, object]:
except Exception as exc: # noqa: BLE001 — never fail the save on a live-apply hiccup
log.warning("keybind live-apply failed (persisted; applies on restart): %s", exc)
+ # Last, after the save and the live re-arm: saving a global shortcut is the
+ # just-in-time moment for Input Monitoring (macOS only; see the helper).
+ _ask_input_monitoring_for_saved_shortcut(request, hotkey=hotkey, changed=previous != hotkey)
+
return {
"ok": True,
"action": action,
@@ -2919,8 +3091,36 @@ def get_mute_music(request: Request) -> dict[str, object]:
return {"enabled": bool(getattr(duck, "enabled", False))}
+def _mute_music_permission(report: object) -> dict[str, object] | None:
+ """The per-player permission answer of a switch-on, or ``None`` when there is none.
+
+ The macOS ducker returns a ``DuckPermissionReport``; Windows and a host without a
+ ducking backend return nothing, and then the response has no ``permission`` key.
+ """
+ as_dict = getattr(report, "as_dict", None)
+ if not callable(as_dict):
+ return None
+ try:
+ return dict(as_dict())
+ except Exception as exc: # noqa: BLE001 - a malformed report never fails the toggle
+ log.debug("mute_music permission report skipped: %s", exc)
+ return None
+
+
@router.put("/mute-music")
async def put_mute_music(body: BoolToggleBody, request: Request) -> dict[str, object]:
+ """Switch "Mute music while dictating" on or off: persisted and applied live.
+
+ Switching ON is the user's gesture, so on macOS it may make the OS ask for
+ Automation access to a RUNNING player (Music, Spotify); the call returns once the
+ dialog is answered (at most ~2 minutes per player). The response keeps ``ok``,
+ ``enabled``, ``persisted`` and ``applied_live`` and, on macOS when switching on,
+ adds ``permission``: ``{feature, checked, asked, note, not_running, players}`` with
+ one ``{player, target, outcome, reason, can_open_settings, asked,
+ outside_installed_app, detail}`` per player that was running. Automation is only
+ checked while a player runs: with none open ``checked`` is false, ``players`` is
+ empty and ``note`` says so. Nothing is asked when switching off.
+ """
enabled = bool(body.enabled)
cfg = _config(request)
duck = getattr(cfg, "ducking", None)
@@ -2938,16 +3138,26 @@ async def put_mute_music(body: BoolToggleBody, request: Request) -> dict[str, ob
except Exception as exc: # noqa: BLE001
log.warning("mute_music persist failed (live apply still attempted): %s", exc)
applied_live = False
+ permission: dict[str, object] | None = None
desktop = getattr(request.app.state, "desktop_app", None)
ducker = getattr(desktop, "_ducker", None)
setter = getattr(ducker, "set_enabled", None)
if callable(setter):
try:
- await setter(enabled)
+ report = await setter(enabled)
applied_live = True
+ permission = _mute_music_permission(report)
except Exception as exc: # noqa: BLE001
log.warning("mute_music live-apply failed: %s", exc)
- return {"ok": True, "enabled": enabled, "persisted": persisted, "applied_live": applied_live}
+ response: dict[str, object] = {
+ "ok": True,
+ "enabled": enabled,
+ "persisted": persisted,
+ "applied_live": applied_live,
+ }
+ if permission is not None:
+ response["permission"] = permission
+ return response
@router.get("/sound-effects")
diff --git a/jarvis/vision/ax_tree.py b/jarvis/vision/ax_tree.py
index 50ed78d3d2..78206ea811 100644
--- a/jarvis/vision/ax_tree.py
+++ b/jarvis/vision/ax_tree.py
@@ -71,12 +71,13 @@ _TRAVERSAL_TIME_BUDGET_S = 1.2
#: nodes only spends IPC on data the ladder is guaranteed to throw away.
_MAX_RAW_NODES = 6000
-# Onboarding message surfaced once when the macOS Accessibility permission is
-# missing — English-only, per the Output Language Policy + AD-13.
+# Log line when the macOS Accessibility permission is missing — English-only,
+# per the Output Language Policy + AD-13. An AX read never asks: Jarvis asks the
+# first time it must type or click for the user.
_AX_PERMISSION_MSG = (
- "macOS Accessibility permission is not ready — grant it to Personal "
- "Jarvis in System Settings > Privacy & Security > Accessibility, then "
- "restart Jarvis. Named UI lookup and protected input remain disabled."
+ "macOS Accessibility access is not granted to Personal Jarvis: the UI tree "
+ "is not read and named UI lookup stays off. It is requested the first time "
+ "Jarvis has to click or type for you."
)
@@ -213,22 +214,28 @@ class AXTreeSource:
@staticmethod
def _ax_is_process_trusted() -> bool:
- """Unified live Accessibility + stable-app-identity gate.
-
- The process-wide permission port owns the uncached native TCC probe,
- stable bundle identity check, and pending-restart state. Imports remain
- lazy so this module is clean on Windows and headless Linux.
+ """Silent live Accessibility read: never prompts, never publishes.
+
+ An AX READ is background work: it asks the permission layer's lock-free
+ ``check`` and degrades when the grant is missing, never raising a card or
+ a system dialog (only an action the user started asks, see
+ ``jarvis.cu.actuate.base.get_actuator``). Off macOS the layer answers
+ NOT_REQUIRED. Imports stay lazy so this module is clean on Windows and
+ headless Linux.
"""
try:
+ from jarvis.platform.permission_service import ( # noqa: PLC0415
+ get_permission_service,
+ )
from jarvis.platform.permissions import ( # noqa: PLC0415
PermissionId,
- get_system_permission_port,
- )
- return get_system_permission_port().runtime_access_granted(
- PermissionId.ACCESSIBILITY,
+ PermissionState,
)
+
+ state = get_permission_service().check(PermissionId.ACCESSIBILITY)
+ return state in (PermissionState.GRANTED, PermissionState.NOT_REQUIRED)
except Exception: # noqa: BLE001
- logger.debug("Accessibility permission gate raised", exc_info=True)
+ logger.debug("Accessibility permission read raised", exc_info=True)
return False
def _empty_observation(self) -> Observation:
diff --git a/jarvis/vision/element_at_point.py b/jarvis/vision/element_at_point.py
index 5c7adab62e..7419f299b8 100644
--- a/jarvis/vision/element_at_point.py
+++ b/jarvis/vision/element_at_point.py
@@ -72,24 +72,27 @@ class AXPointerResolver(_BaseResolver):
_native = staticmethod(lambda x, y: _ax_query_element_at_point(x, y))
def at(self, x: int, y: int) -> PointerElement | None:
- """Query AX only for the canonical, currently authorized app process.
+ """Query AX only while Accessibility is currently granted.
- This check deliberately runs for every point lookup: TCC grants can be
- revoked while Jarvis is running, and an ad-hoc Python/Terminal launch
- must never inherit a different executable's Accessibility grant.
+ An element-at-point read is background work: it asks the permission
+ layer's silent ``check`` for every lookup (a grant can be revoked while
+ Jarvis runs) and degrades to ``None`` without a grant. It never prompts
+ and never raises a card.
"""
try:
+ from jarvis.platform.permission_service import ( # noqa: PLC0415
+ get_permission_service,
+ )
from jarvis.platform.permissions import ( # noqa: PLC0415
PermissionId,
- get_system_permission_port,
+ PermissionState,
)
- if not get_system_permission_port().runtime_access_granted(
- PermissionId.ACCESSIBILITY,
- ):
+ state = get_permission_service().check(PermissionId.ACCESSIBILITY)
+ if state not in (PermissionState.GRANTED, PermissionState.NOT_REQUIRED):
return None
except Exception: # noqa: BLE001 - native permission failures fail closed
- log.debug("macOS Accessibility permission gate failed", exc_info=True)
+ log.debug("macOS Accessibility permission read failed", exc_info=True)
return None
return super().at(x, y)
diff --git a/jarvis/vision/screenshot.py b/jarvis/vision/screenshot.py
index 38e3cbfdf8..7a26b9be5e 100644
--- a/jarvis/vision/screenshot.py
+++ b/jarvis/vision/screenshot.py
@@ -47,34 +47,34 @@ _DEFAULT_BLOB_DIR = Path("data") / "flight_recorder" / "blobs"
# H1 (DEEP-DIVE-AUDIT-2026-06-19): on macOS, screen capture is gated behind a
# TCC "Screen Recording" grant. Without it mss returns ONLY the desktop
# wallpaper with no error, so Computer-Use would click blind. Surface a clear
-# onboarding message at the capture site instead of failing silently.
+# message at the capture site instead of failing silently. These helpers only
+# READ the state: they never ask macOS (the gesture entry points do, through
+# ``jarvis.platform.screen_access``).
_SCREEN_RECORDING_MSG = (
- "macOS Screen Recording permission not granted — grant it in Personal "
- "Jarvis > Settings > Permissions or System Settings > Privacy & Security "
- "> Screen Recording; without it screenshots can contain only the desktop "
- "wallpaper and Computer-Use would click blind."
+ "macOS Screen Recording permission not granted — allow Personal Jarvis in "
+ "System Settings > Privacy & Security > Screen & System Audio Recording; "
+ "without it screenshots can contain only the desktop wallpaper and "
+ "Computer-Use would click blind."
)
_screen_recording_warned = False
def warn_if_screen_recording_denied() -> bool:
- """Probe Screen Recording now and log once per blocked-state episode.
-
- The native result is deliberately uncached: macOS can revoke a TCC grant
- while Jarvis is running. The boolean flag suppresses repeated log lines
- only; it never suppresses a permission probe. Unknown/unavailable native
- state fails closed on macOS and non-macOS reports ``NOT_REQUIRED``.
+ """Read the Screen Recording state now; log once per blocked-state episode.
+
+ Silent: it never asks macOS and never raises a permission toast, so a helper, a
+ status probe or a per-frame fast path may call it freely. The native result is
+ deliberately not held beyond the permission service's sub-second cache: macOS
+ can revoke a TCC grant while Jarvis is running. The boolean flag suppresses
+ repeated log lines only; it never suppresses a read. Unknown/unavailable
+ native state fails closed on macOS and non-macOS reports ``NOT_REQUIRED``.
"""
global _screen_recording_warned
- from jarvis.platform.permissions import ( # noqa: PLC0415
- PermissionId,
- get_system_permission_port,
- )
+ from jarvis.platform import screen_access # noqa: PLC0415
- port = get_system_permission_port()
- blocked = not port.runtime_access_granted(PermissionId.SCREEN_RECORDING)
+ state = screen_access.screen_recording_state()
+ blocked = not screen_access.state_allows_capture(state)
if blocked:
- state = port.state(PermissionId.SCREEN_RECORDING)
if not _screen_recording_warned:
logger.warning("%s Native state: %s.", _SCREEN_RECORDING_MSG, state.value)
_screen_recording_warned = True
@@ -85,6 +85,18 @@ def warn_if_screen_recording_denied() -> bool:
return False
+def _refuse_blocked_capture() -> None:
+ """Raise the honest refusal for a helper capture that is not allowed.
+
+ ``ScreenCaptureRefused`` is a ``RuntimeError`` whose text names the
+ permission; the helper's callers (the harness region grab, the AI pointer
+ crop) catch it and degrade. Nothing is asked here.
+ """
+ from jarvis.platform import screen_access # noqa: PLC0415
+
+ raise screen_access.refusal_for_state(screen_access.screen_recording_state())
+
+
# ---------------------------------------------------------------------------
# DPI awareness — extracted to jarvis/core/win32_dpi.py (Phase A1).
# Re-exported here so old code (tests, vision engine) keeps working
@@ -293,7 +305,7 @@ def capture_region(
from PIL import Image # noqa: PLC0415
if warn_if_screen_recording_denied():
- raise RuntimeError(_SCREEN_RECORDING_MSG)
+ _refuse_blocked_capture()
grabber = grab or _mss_grab
size, rgb = grabber(bbox)
img = Image.frombytes("RGB", size, rgb)
@@ -468,9 +480,11 @@ class ScreenshotSource:
ScreenShotError = Exception # type: ignore[assignment,misc]
# H1: macOS can return only wallpaper without an error when Screen
- # Recording is missing. Probe on every capture and fail closed.
+ # Recording is missing. Read the state on every capture (silently) and
+ # refuse honestly instead of handing the wallpaper on; a blank frame
+ # while the state claims granted is checked after the grab.
if warn_if_screen_recording_denied():
- raise RuntimeError(_SCREEN_RECORDING_MSG)
+ _refuse_blocked_capture()
monitor_id: str = "unknown"
try:
@@ -508,6 +522,18 @@ class ScreenshotSource:
"ScreenshotSource: BitBlt recovered for monitor [%s].", monitor_id
)
+ # The vision source is a background observer, never a gesture: a blank
+ # frame the state cannot explain refuses honestly and records a
+ # background-origin episode (status snapshot only, no toast, no native request).
+ from jarvis.platform import screen_access # noqa: PLC0415
+
+ screen_access.verify_frame_is_real(
+ tuple(raw.size),
+ raw.rgb,
+ feature="computer_use",
+ interactive=False,
+ )
+
img = Image.frombytes("RGB", raw.size, raw.rgb)
buf = io.BytesIO()
if self._image_format == "jpeg":
diff --git a/jarvis/voice/action_phrases.py b/jarvis/voice/action_phrases.py
index 7fdedf5255..789f95a75b 100644
--- a/jarvis/voice/action_phrases.py
+++ b/jarvis/voice/action_phrases.py
@@ -163,6 +163,77 @@ _PHRASES: dict[str, dict[str, str]] = {
"en": "I waited for the administrator confirmation, but none came, so I stopped.",
"es": "Esperé la confirmación de administrador, pero no llegó, así que me detuve.",
},
+ # exit 8 + "[cu] blocked_permission": the mission stopped because a macOS
+ # permission or a system dialog needs the person. ``cu_blocked_permission``
+ # forwards the engine's own English sentence (en only; the other languages
+ # name the permission from the table below); the others are fixed, localized.
+ "cu_blocked_permission": {
+ "de": "Ich musste anhalten: Personal Jarvis braucht " # i18n-allow
+ "die Berechtigung {permission}. " # i18n-allow
+ "Erlaube sie unter {pane}. Versuche es danach noch einmal.", # i18n-allow
+ "en": "I had to stop. {sentence}",
+ "es": "Tuve que parar: Personal Jarvis necesita el permiso de {permission}. "
+ "Actívalo en {pane}. Después, vuelve a intentarlo.",
+ },
+ # The grant is on but unusable, a permission this session cannot ask for, and a
+ # macOS dialog that is still open: each one has its own remedy, none is "allow it
+ # in Settings". de/es name the permission; en forwards the engine's sentence and
+ # only needs these as the fixed fallback.
+ "cu_blocked_restart_hint": {
+ "de": "Ich musste anhalten: Die Berechtigung {permission} wirkt " # i18n-allow
+ "womöglich erst, nachdem Personal Jarvis beendet " # i18n-allow
+ "und neu geöffnet wurde. " # i18n-allow
+ "Starte die App neu und versuche es dann noch einmal.", # i18n-allow
+ "en": "I had to stop: the {permission} permission may only take effect after "
+ "Personal Jarvis is quit and reopened. Reopen the app, then try again.",
+ "es": "Tuve que parar: el permiso de {permission} puede que solo surta efecto "
+ "cuando Personal Jarvis se cierre y se vuelva a abrir. "
+ "Reinicia la app y vuelve a intentarlo.",
+ },
+ "cu_blocked_unavailable": {
+ "de": "Ich musste anhalten: Personal Jarvis kann in dieser Sitzung " # i18n-allow
+ "nicht nach der Berechtigung {permission} fragen.", # i18n-allow
+ "en": "I had to stop: Personal Jarvis cannot ask for the {permission} permission "
+ "in this session.",
+ "es": "Tuve que parar: Personal Jarvis no puede pedir el permiso de {permission} "
+ "en esta sesión.",
+ },
+ "cu_blocked_waiting": {
+ "de": "Ich musste anhalten, weil macOS gerade nach der Berechtigung " # i18n-allow
+ "{permission} fragt. Beantworte den Dialog und versuche es dann noch " # i18n-allow
+ "einmal.", # i18n-allow
+ "en": "I had to stop because macOS is asking about the {permission} permission. "
+ "Answer the dialog, then try again.",
+ "es": "Tuve que parar porque macOS está preguntando por el permiso de "
+ "{permission}. Responde al diálogo y vuelve a intentarlo.",
+ },
+ "cu_blocked_dialog": {
+ "de": "Ich musste anhalten, weil auf dem Mac ein Systemdialog offen ist. " # i18n-allow
+ "Beantworte ihn selbst und versuche es dann noch einmal.", # i18n-allow
+ "en": "I had to stop because a macOS system dialog is open. "
+ "Answer it yourself, then try again.",
+ "es": "Tuve que parar porque hay un diálogo del sistema abierto en el Mac. "
+ "Respóndelo tú y vuelve a intentarlo.",
+ },
+ "cu_blocked_restricted": {
+ "de": "Ich musste anhalten: Eine nötige Berechtigung ist auf diesem " # i18n-allow
+ "Mac durch " # i18n-allow
+ "ein Profil oder eine Kindersicherung gesperrt. Das lässt sich in der " # i18n-allow
+ "App nicht ändern.", # i18n-allow
+ "en": "I had to stop: a permission this needs is restricted on this Mac by a "
+ "profile or a parental control. That cannot be changed from the app.",
+ "es": "Tuve que parar: un permiso necesario está restringido en este Mac por un "
+ "perfil o un control parental. No se puede cambiar desde la app.",
+ },
+ "cu_blocked_generic": {
+ "de": "Ich musste anhalten, weil macOS eine Berechtigung für Personal Jarvis " # i18n-allow
+ "braucht. Erlaube sie in den Systemeinstellungen unter Datenschutz & " # i18n-allow
+ "Sicherheit und versuche es dann noch einmal.", # i18n-allow
+ "en": "I had to stop because macOS needs a permission for Personal Jarvis. "
+ "Allow it in System Settings under Privacy & Security, then try again.",
+ "es": "Tuve que parar porque macOS necesita un permiso para Personal Jarvis. "
+ "Actívalo en Ajustes del Sistema, en Privacidad y seguridad, y vuelve a intentarlo.",
+ },
"cu_timeout": {
"de": "Das am Bildschirm hat zu lange gedauert " # i18n-allow
"(ueber {secs} Sekunden) und wurde abgebrochen.", # i18n-allow
@@ -1003,6 +1074,103 @@ _REASON_FAMILIES: tuple[tuple[re.Pattern[str], dict[str, str]], ...] = (
)
+#: The agent-facing refusal of the permission layer ("[permission_needed:<perm>] This
+#: action cannot run: ... You must not ...") is prohibitive text for the LLM, never for
+#: a person. A tool error that carries it is replaced by ONE short, reason-agnostic
+#: cause sentence (it makes no claim about the remedy: that depends on the reason and
+#: the on-screen card says it), which :func:`localize_failure_reason` then speaks in
+#: the turn's language. Pure regex and fixed tables (AP-11).
+_PERMISSION_NEEDED_TOKEN_RE = re.compile(r"\[permission_needed:(?P<token>[a-z_]+)\]")
+_PERMISSION_CAUSE_EN = "Personal Jarvis does not have the {name} permission right now."
+_PERMISSION_CAUSE_RE = re.compile(
+ r"^Personal Jarvis does not have the (?P<name>.+?) permission right now\.$"
+)
+_PERMISSION_CAUSE_TEMPLATES: dict[str, str] = {
+ "de": "Personal Jarvis hat die Berechtigung {name} gerade nicht.", # i18n-allow
+ "en": _PERMISSION_CAUSE_EN,
+ "es": "Personal Jarvis no tiene ahora el permiso de {name}.",
+}
+#: How each language names a permission (the macOS UI labels; unverified on a real Mac).
+_PERMISSION_CAUSE_NAMES: dict[str, dict[str, str]] = {
+ "microphone": {
+ "de": "Mikrofon", # i18n-allow
+ "en": "Microphone",
+ "es": "Micrófono",
+ },
+ "accessibility": {
+ "de": "Bedienungshilfen", # i18n-allow
+ "en": "Accessibility",
+ "es": "Accesibilidad",
+ },
+ "screen_recording": {
+ "de": "Bildschirmaufnahme", # i18n-allow
+ "en": "Screen Recording",
+ "es": "Grabación de pantalla",
+ },
+ "input_monitoring": {
+ "de": "Eingabeüberwachung", # i18n-allow
+ "en": "Input Monitoring",
+ "es": "Monitorización de entrada",
+ },
+ "automation": {
+ "de": "Automatisierung", # i18n-allow
+ "en": "Automation",
+ "es": "Automatización",
+ },
+}
+_PERMISSION_CAUSE_NAMES["event_posting"] = _PERMISSION_CAUSE_NAMES["accessibility"]
+_PERMISSION_TOKEN_BY_EN_NAME: dict[str, str] = {
+ names["en"]: token for token, names in _PERMISSION_CAUSE_NAMES.items()
+}
+#: Causes without a permission name: a macOS system dialog that is open, and a token
+#: this build does not know. English sentence -> its localized wording.
+_PERMISSION_FIXED_CAUSES: dict[str, dict[str, str]] = {
+ "Personal Jarvis paused because a macOS system dialog is open.": {
+ "de": "Personal Jarvis hat angehalten, weil ein Systemdialog offen ist.", # i18n-allow
+ "en": "Personal Jarvis paused because a macOS system dialog is open.",
+ "es": "Personal Jarvis se detuvo porque hay un cuadro de diálogo del sistema abierto.",
+ },
+ "A macOS permission is missing right now.": {
+ "de": "Eine macOS-Berechtigung fehlt gerade.", # i18n-allow
+ "en": "A macOS permission is missing right now.",
+ "es": "Falta un permiso de macOS en este momento.",
+ },
+}
+
+
+def _permission_cause(text: str | None) -> str | None:
+ """The one-sentence English cause of an agent permission refusal, else ``None``.
+
+ Looks for the ``[permission_needed:<token>]`` marker ANYWHERE in ``text`` (a
+ tool may wrap the refusal) and drops the rest of it: the prohibitive agent
+ sentences, wrapped prefixes and anything after the marker never reach a person.
+ """
+ match = _PERMISSION_NEEDED_TOKEN_RE.search(text or "")
+ if match is None:
+ return None
+ permission = match.group("token")
+ if permission == "system_dialog":
+ return "Personal Jarvis paused because a macOS system dialog is open."
+ names = _PERMISSION_CAUSE_NAMES.get(permission)
+ if names is None:
+ return "A macOS permission is missing right now."
+ return _PERMISSION_CAUSE_EN.format(name=names["en"])
+
+
+def _localize_permission_cause(sentence: str, lang: str) -> str | None:
+ """Speak a :func:`_permission_cause` sentence in ``lang``; ``None`` if it is not one."""
+ fixed = _PERMISSION_FIXED_CAUSES.get(sentence)
+ if fixed is not None:
+ return fixed.get(lang) or fixed[_DEFAULT]
+ match = _PERMISSION_CAUSE_RE.match(sentence)
+ token = _PERMISSION_TOKEN_BY_EN_NAME.get(match.group("name")) if match else None
+ if token is None:
+ return None
+ names = _PERMISSION_CAUSE_NAMES[token]
+ template = _PERMISSION_CAUSE_TEMPLATES.get(lang) or _PERMISSION_CAUSE_TEMPLATES[_DEFAULT]
+ return template.format(name=names.get(lang) or names[_DEFAULT])
+
+
def localize_failure_reason(reason: str | None, language: str) -> str:
"""Speak a KNOWN failure cause in the turn's language; pass others through.
@@ -1053,6 +1221,9 @@ def _localize_one_reason(sentence: str, lang: str) -> str | None:
whether an unrecognized sentence is a cause of its own or the machine tail
of the cause before it.
"""
+ permission_cause = _localize_permission_cause(sentence, lang)
+ if permission_cause is not None:
+ return permission_cause
for pattern, templates in _REASON_FAMILIES:
match = pattern.match(sentence)
if match is None:
@@ -1091,14 +1262,175 @@ def extract_speakable_reason(error: str | None, output: object = None) -> str |
raw = str(output.get(field) or "").strip()
if not raw:
continue
+ # The agent text of a permission refusal is never forwarded: one fixed cause.
+ if (cause := _permission_cause(raw)) is not None:
+ return cause
candidate = _CU_REASON_PREFIX_RE.sub("", raw).strip()
if _is_speakable_reason(candidate):
return candidate
+ if (cause := _permission_cause(error)) is not None:
+ return cause
if _is_speakable_reason(error):
return str(error).strip()
return None
+#: The engine's own line for a mission stopped by a macOS permission or a system
+#: dialog: ``"[cu] blocked_permission at step-N: <sentence>"``. It is NOT the
+#: ``[cu] fail`` family: the sentence is a fixed user-facing template, and the
+#: engine always appends a ``[cu] mission profile`` line after it, which is what
+#: used to trip :data:`_CU_DIAGNOSTIC_RE` and degrade the readback to the generic
+#: "an action failed" phrase.
+_CU_BLOCKED_PERMISSION_RE = re.compile(
+ r"^[ \t]*\[cu\][ \t]+blocked_permission\b[^:\n]*:[ \t]*(?P<sentence>[^\n]*)$",
+ re.IGNORECASE | re.MULTILINE,
+)
+#: The engine's exit code for a tool/action failure; ``blocked_permission`` rides it.
+_CU_TOOL_EXIT_CODE = 8
+
+#: How the localized (de/es) phrase names a permission, found by keyword in the
+#: engine's English sentence: ``(keyword, {lang: (permission name, settings pane)})``.
+#: The pane names are the macOS UI labels (UNVERIFIED on a real Mac: they move
+#: between macOS versions).
+_BLOCKED_PERMISSION_NAMES: tuple[tuple[str, dict[str, tuple[str, str]]], ...] = (
+ (
+ "accessibility",
+ {
+ "de": (
+ "Bedienungshilfen", # i18n-allow
+ "Systemeinstellungen > Datenschutz & Sicherheit > Bedienungshilfen", # i18n-allow
+ ),
+ "es": (
+ "Accesibilidad",
+ "Ajustes del Sistema > Privacidad y seguridad > Accesibilidad",
+ ),
+ },
+ ),
+ (
+ "screen recording",
+ {
+ "de": (
+ "Bildschirm- und Systemaudioaufnahme", # i18n-allow
+ "Systemeinstellungen > Datenschutz & Sicherheit > " # i18n-allow
+ "Bildschirm- & Systemaudioaufnahme", # i18n-allow
+ ),
+ "es": (
+ "Grabación de pantalla y audio del sistema",
+ "Ajustes del Sistema > Privacidad y seguridad > "
+ "Grabación de pantalla y audio del sistema",
+ ),
+ },
+ ),
+ (
+ "input monitoring",
+ {
+ "de": (
+ "Eingabeüberwachung", # i18n-allow
+ "Systemeinstellungen > Datenschutz & Sicherheit > Eingabeüberwachung", # i18n-allow
+ ),
+ "es": (
+ "Supervisión de entradas",
+ "Ajustes del Sistema > Privacidad y seguridad > Supervisión de entradas",
+ ),
+ },
+ ),
+ (
+ "microphone",
+ {
+ "de": (
+ "Mikrofon", # i18n-allow
+ "Systemeinstellungen > Datenschutz & Sicherheit > Mikrofon", # i18n-allow
+ ),
+ "es": (
+ "Micrófono",
+ "Ajustes del Sistema > Privacidad y seguridad > Micrófono",
+ ),
+ },
+ ),
+ (
+ "automation",
+ {
+ "de": (
+ "Automation",
+ "Systemeinstellungen > Datenschutz & Sicherheit > Automation", # i18n-allow
+ ),
+ "es": (
+ "Automatización",
+ "Ajustes del Sistema > Privacidad y seguridad > Automatización",
+ ),
+ },
+ ),
+)
+
+
+def cu_blocked_permission_sentence(stderr: str | None) -> str | None:
+ """The engine's user sentence of a ``blocked_permission`` mission, else ``None``.
+
+ Reads the ``"[cu] blocked_permission at step-N: <sentence>"`` line out of the
+ mission's ``stderr`` wherever it sits (the engine appends a ``[cu] mission
+ profile`` line after it). The sentence is a fixed template with no exception
+ text, path or window title; one that nevertheless looks like machine noise
+ (diagnostic marker, telemetry, a path) is dropped, so the caller falls back to
+ a fixed phrase. Pure regex (AP-11).
+ """
+ match = _CU_BLOCKED_PERMISSION_RE.search(stderr or "")
+ if match is None:
+ return None
+ sentence = match.group("sentence").strip()
+ return sentence if _is_speakable_reason(sentence) else ""
+
+
+def _spoken_en(sentence: str) -> str:
+ """The engine's English sentence, made speakable and addressed to the listener.
+
+ The engine writes it about "the user" and with a Settings path joined by ``>``;
+ spoken, that reads as "greater than" and talks about somebody else. Pure regex
+ (AP-11).
+ """
+ spoken = re.sub(r"\bThe user has to\b", "You have to", sentence)
+ spoken = re.sub(r"\bthe user\b", "you", spoken, flags=re.IGNORECASE)
+ return _spoken_pane(spoken, "en")
+
+
+def _spoken_pane(text: str, lang: str) -> str:
+ """Replace the written Settings-path separators with speakable words."""
+ and_word = {"de": "und", "es": "y"}.get(lang, "and")
+ then_word = {"de": "dann", "es": "luego"}.get(lang, "then")
+ return text.replace(" > ", f", {then_word} ").replace(" & ", f" {and_word} ")
+
+
+def _blocked_permission_readback(lang: str, sentence: str) -> str:
+ """The localized readback of a ``blocked_permission`` mission (no LLM, AP-11).
+
+ English forwards the engine's own sentence (second person, speakable). de/es
+ cannot (it is English), so they name the permission by keyword and pick the
+ remedy by REASON: a dialog still open, a restart, an unaskable permission or a
+ restriction each get their own phrase, and only a switch that is off says "allow
+ it in Settings". A sentence they cannot place falls back to the fixed generic
+ phrase.
+ """
+ low = sentence.lower()
+ if lang == "en" and sentence:
+ return action_phrase("cu_blocked_permission", lang, sentence=_spoken_en(sentence))
+ if "system dialog" in low:
+ return action_phrase("cu_blocked_dialog", lang)
+ if "restricted" in low:
+ return action_phrase("cu_blocked_restricted", lang)
+ names = next((n for keyword, n in _BLOCKED_PERMISSION_NAMES if keyword in low), None)
+ if names is None or lang not in names:
+ return action_phrase("cu_blocked_generic", lang)
+ permission, pane = names[lang]
+ if "quit and reopened" in low:
+ return action_phrase("cu_blocked_restart_hint", lang, permission=permission)
+ if "cannot ask" in low:
+ return action_phrase("cu_blocked_unavailable", lang, permission=permission)
+ if "macos dialog" in low or "showing a dialog" in low:
+ return action_phrase("cu_blocked_waiting", lang, permission=permission)
+ return action_phrase(
+ "cu_blocked_permission", lang, permission=permission, pane=_spoken_pane(pane, lang)
+ )
+
+
def cu_failure_readback(
lang: str,
*,
@@ -1122,6 +1454,21 @@ def cu_failure_readback(
``exit_code`` (``cu_exit_*``), falling back to the plain
"didn't work on screen" sentence when the code is unknown.
"""
+ # 0) A mission stopped by a macOS permission or a system dialog says what is
+ # missing and where to allow it. Checked first: the engine always appends a
+ # "[cu] mission profile" line, and the diagnostic gate below would turn the
+ # whole detail into the generic "an action failed" phrase.
+ if exit_code == _CU_TOOL_EXIT_CODE:
+ blocked = cu_blocked_permission_sentence(detail)
+ if blocked is not None:
+ return _blocked_permission_readback(lang, blocked)
+
+ # 0b) The agent text of a permission refusal is never spoken: one fixed cause.
+ for source in (detail, error):
+ if (cause := _permission_cause(source)) is not None:
+ spoken = _localize_permission_cause(cause, lang) or cause
+ return action_phrase("cu_failed_reason", lang, error=spoken)
+
# 1) The harness detail string may carry the model's verified reason.
if detail:
candidate = _CU_REASON_PREFIX_RE.sub("", detail).strip()
@@ -1190,6 +1537,7 @@ __all__ = [
"CU_TOOL_OUTCOME_LAYER",
"OUTPUT_LANGUAGE_ENV_KEY",
"action_phrase",
+ "cu_blocked_permission_sentence",
"cu_failure_readback",
"cu_success_readback",
"extract_speakable_reason",
diff --git a/packaging/macos/README.md b/packaging/macos/README.md
index daa5496767..f10723fd8b 100644
--- a/packaging/macos/README.md
+++ b/packaging/macos/README.md
@@ -19,22 +19,120 @@ from `jarvis.spec`; its icon is `assets/icons/jarvis.icns`, regenerated by
python3 -m pip install -e ".[full]"
python3 -m pip install pyinstaller
bash packaging/macos/build.sh
+python3 scripts/ci/check_frozen_macos_app.py --app "dist/Personal Jarvis.app"
```
`DRY_RUN=1` prints every command it would run without running any of them,
which is how the flow is rehearsed off a Mac.
+The last command reads the finished app (the CI job runs it too) and fails when
+the bundle could not use its macOS permissions, which no headless smoke run can
+see:
+
+* `LSBackgroundOnly` must be `False` in `Info.plist` (`jarvis.spec` sets it
+ explicitly). PyInstaller turns it on whenever the last executable of the bundle
+ is a console one — the `jarvis` CLI is — and LaunchServices then runs the app
+ with no Dock icon and no windows.
+* The frozen archive must contain `AVFoundation` and the other pyobjc modules the
+ permission code loads *by name*, which a freezer cannot discover on its own.
+ They come from the `desktop-macos` extra, so install it on the build machine:
+ `python3 -m pip install -e ".[desktop,desktop-macos]"` (`.[full]` includes it).
+* Every usage-description string in
+ `jarvis/core/macos_privacy_strings.py` must be in `Info.plist` with exactly
+ that text, and the keys that table lists as removed (camera, speech
+ recognition, system administration) must not be.
+* On a **signed** build, `codesign -d --entitlements :-` must report every
+ entitlement of `packaging/macos/entitlements.plist` and none of the removed
+ ones. An unsigned or ad-hoc build embeds no entitlements (`build.sh` passes
+ them only with a Developer ID identity), so that part is skipped with a
+ message saying so — it is not a pass.
+
+The v2.5.0 image had the first two defects (BUG-222). In CI the smoke boot of the
+app also asks it for its permission status and fails when the microphone row
+reads "unavailable", which is what a framework that did not load looks like from
+inside.
+
+### The usage strings have one source
+
+The `NS...UsageDescription` strings macOS shows in its permission dialogs live
+in exactly one file, `jarvis/core/macos_privacy_strings.py` (standard library
+only). `jarvis.spec` (this `.dmg` app) and
+`jarvis/setup/macos_app_bundle.py` (the managed source-install app) both load that
+file **by path**: the spec runs before the `jarvis` package is importable, so
+neither can use an ordinary import, and neither keeps a copy.
+`tests/unit/packaging/test_macos_privacy_strings.py` runs the real spec against
+stand-in PyInstaller classes and asserts that the spec's `info_plist`, the
+managed bundle's plist and the table agree. Add or reword a string in that file
+only. The Apple Events string is target-neutral on purpose (macOS names the app
+under control in the dialog itself; the same string serves Music, Spotify and
+Terminal) and the folder strings are short.
+
+### German and Spanish dialog text
+
+The same file carries the German and Spanish versions. Both bundles declare
+`CFBundleDevelopmentRegion` (`en`) and `CFBundleLocalizations` (`en`, `de`, `es`) in
+`Info.plist` (the spec spreads `localization_plist_keys()` into its dict) and carry
+`Contents/Resources/{de,es}.lproj/InfoPlist.strings`. English stays the base text in
+`Info.plist`, so there is no `en.lproj`. For this `.dmg` app, `build.sh` runs
+`packaging/macos/add_localizations.py --app "dist/Personal Jarvis.app"` on the
+finished bundle BEFORE signing, because the `.lproj` files are part of the code seal:
+one added after `codesign` would invalidate the signature and the notarization. The
+managed bundle writes the same files itself when it lays out the app. The format
+version of the managed bundle is not bumped for this (a bump would rebuild every
+installed bundle and an ad-hoc rebuild re-asks every permission).
+`scripts/ci/check_frozen_macos_app.py` fails the build if a plist key or a `.strings`
+file is missing or differs from the table. **Unverified:** no Mac was available, so
+that macOS shows these strings in its dialogs, and that it accepts the UTF-8 file
+(Apple's own tooling writes UTF-16), is not proven; `plutil -lint` runs on each file in
+`build.sh` where `plutil` exists.
+
+Keys that are deliberately **not** shipped, because Jarvis has no caller for
+them (least privilege; a string would promise access the app never uses):
+`NSCameraUsageDescription` (and the camera entitlement),
+`NSSpeechRecognitionUsageDescription` (speech-to-text is local or a cloud
+provider, never Apple's speech service) and
+`NSSystemAdministrationUsageDescription` (the wrong key for Accessibility and
+Input Monitoring, which have no usage-description key at all).
+`NSScreenCaptureUsageDescription` is kept for parity between the two bundles;
+Apple's documentation index has no page for that key, so whether it changes
+anything on macOS is **unverified**.
+
+Where `plutil` exists (it does on macOS), `build.sh` validates the built
+`Info.plist` with `plutil -lint` and signs with a canonical-XML copy of
+`entitlements.plist` made by `plutil -convert xml1` (written to
+`dist/entitlements.normalized.plist`; the tracked file is never rewritten).
+Anywhere else those steps are skipped, with a log line, and the script stays
+bash 3.2 clean.
+
## Signing and notarization
-All four settings come from the environment, so the same script serves a
+All settings come from the environment, so the same script serves a
maintainer's Mac and both GitHub runners:
| Variable | Meaning |
|---|---|
-| `APPLE_SIGNING_IDENTITY` | `Developer ID Application: NAME (TEAMID)` |
+| `APPLE_SIGNING_IDENTITY` | `Developer ID Application: NAME (TEAMID)` — optional on CI, where it is read from the imported certificate |
| `APPLE_ID` | Apple ID used for notarization |
| `APPLE_TEAM_ID` | 10-character team identifier |
| `APPLE_APP_SPECIFIC_PASSWORD` | app-specific password for that Apple ID |
+| `APPLE_CERTIFICATE_P12_BASE64` | CI only: the exported Developer ID Application certificate (`.p12`, with its chain), base64 encoded |
+| `APPLE_CERTIFICATE_PASSWORD` | CI only: the password chosen when exporting it |
+
+A GitHub runner starts with an empty keychain, so `codesign` cannot find a
+Developer ID identity there until the certificate is imported. With the two
+`APPLE_CERTIFICATE_*` variables set, `build.sh` imports it into a temporary
+keychain (removed again on exit, search list restored, decoded file deleted),
+reads the signing identity back from it when `APPLE_SIGNING_IDENTITY` is not
+given, and never prints a secret. It does this before the long freeze, so a
+certificate that cannot be used fails in seconds. A Mac that already holds the identity in its login keychain
+needs neither variable. Getting the certificate needs an Apple Developer Program
+membership. The steps, as Apple documents them and not yet followed end to end
+for this project: create a *Developer ID Application* certificate in the
+developer portal, export it from Keychain Access as `.p12` together with its
+chain, encode it with `base64 -i certificate.p12 | pbcopy`, and store the five
+required values (`APPLE_ID`, `APPLE_TEAM_ID`, `APPLE_APP_SPECIFIC_PASSWORD` and
+the two `APPLE_CERTIFICATE_*` ones) as GitHub Actions secrets;
+`APPLE_SIGNING_IDENTITY` is optional on CI.
With the identity set, the script signs every nested Mach-O object inside the
bundle before sealing the bundle itself (Apple's guidance is inside-out;
@@ -84,28 +182,90 @@ That build is fine for local testing and must not be published.
Either way, `xattr -dr com.apple.quarantine "/Applications/Personal Jarvis.app"`
does the same thing from a terminal on every version.
+ These steps follow Apple's published behaviour and have not been tried on a
+ Mac for this project. An ad-hoc signature is a hash of the app's bytes, so an
+ update is a new app to macOS and its permissions are asked for again; a
+ downloaded image keeps one identity across versions only when it is signed
+ with a stable certificate, which for a public download means a Developer ID
+ one.
+
## Permission prompts
macOS grants privacy permissions to an *app identity*, not to a folder, and
Apple does not let an installer pre-approve any of them. The app therefore asks
-for each one at the moment it needs it, through Apple's own prompts:
+for a permission at the moment a feature the person starts needs it, never at
+launch, and Apple's own prompt or System Settings pane does the asking:
-* **Microphone** — voice input; the app is usable for text without it.
-* **Speech recognition** — on-device dictation.
-* **Camera** — only the vision features.
+* **Microphone** — dictation, talking to Jarvis, the wake word once it is
+ switched on; typed chat works without it.
* **Screen recording** — screen capture and Computer-Use; granted in
- System Settings > Privacy & Security, and macOS requires a restart of the app
- afterwards.
-* **Accessibility / Input monitoring** — global hotkeys and Computer-Use input.
-* **Automation (Apple events)** — controlling other apps, e.g. the media
- session.
-
-Each of these needs *both* an entitlement in
-`packaging/macos/entitlements.plist` and a usage-description string in the
-bundle's `Info.plist` (built by `jarvis.spec`). Missing entitlement: the app is
-refused before the prompt appears. Missing usage string: macOS kills the app
-the moment it asks. Declining any of them leaves the app working, with that
-feature honestly unavailable.
+ System Settings > Privacy & Security. Whether macOS needs the app reopened
+ afterwards is **unverified** (reports conflict), so the app re-checks the
+ live state and only suggests a restart as a hint.
+* **Accessibility / Input monitoring** — typing and clicking for you
+ (Computer-Use, dictation paste) and global shortcuts. These two have no
+ usage-description key; the dialog text is fixed by macOS.
+* **Automation (Apple events)** — controlling other apps: Music or Spotify while
+ "Mute music while dictating" is on, and Terminal for sign-in and agent windows.
+* **Files and folders, local network** — asked by macOS itself the first time a
+ feature touches Desktop, Documents, Downloads, an external or network drive,
+ or a device on the local network.
+
+There is no camera and no speech-recognition row: Jarvis has no caller for
+either, so the bundle neither declares a string nor an entitlement for them.
+
+The downloaded app is its own app to macOS: bundle id `ai.personaljarvis.desktop`
+(`jarvis.spec`), separate from the managed bundle the source installer builds
+(`com.personal-jarvis.desktop`). Both are accepted as "the installed app" by the
+permission code, and each keeps its own grants.
+
+Each protected API needs *both* halves on a hardened (Developer ID) build: an
+entitlement in `packaging/macos/entitlements.plist` and a usage-description
+string in the bundle's `Info.plist` (the table in
+`jarvis/core/macos_privacy_strings.py`). Missing entitlement: the app is
+refused before the prompt appears. Missing usage string: macOS ends the process
+(microphone) or, as third parties report for other services, silently refuses
+without a prompt; the exact failure mode is unverified, which is why
+`check_frozen_macos_app.py` asserts the whole string table on every built app.
+Declining any permission leaves the app working, with that one feature honestly
+unavailable.
+
+## Entitlements (`entitlements.plist`)
+
+An entitlements file has no comment syntax Apple documents, so
+`entitlements.plist` carries none; this section is where the reasoning lives.
+
+Notarization requires the Hardened Runtime (`codesign --options runtime`), and
+the Hardened Runtime denies by default exactly the things this app needs. Every
+entry below is here because leaving it out breaks a shipped feature or stops the
+app from launching at all. Nothing is requested "just in case", because each one
+weakens a real platform protection. The file is only embedded by the Developer ID
+path of `build.sh`: the ad-hoc images published so far carry no entitlements, so
+every judgement below is **unverified on a hardened build** until the signed path
+has run once (`scripts/ci/check_frozen_macos_app.py` then reads them back with
+`codesign -d --entitlements :-`).
+
+Entitlements grant the app the *right* to ask; the usage strings are what the
+person reads in the prompt. A hardened app missing the entitlement is refused
+before the prompt appears.
+
+| Entitlement | Why |
+|---|---|
+| `com.apple.security.device.audio-input` | Microphone. The whole voice pipeline (wake word, dictation, calls) reads the default input device through PortAudio. Without it a hardened build fails every capture attempt instead of showing the microphone prompt. |
+| `com.apple.security.automation.apple-events` | Apple events. Jarvis drives other applications through AppleScript for the media-session and window-control paths (`jarvis/platform/media_session.py`, `music_player.py`). Sending an Apple event to another process from a hardened app requires this entitlement plus `NSAppleEventsUsageDescription`. |
+| `com.apple.security.cs.allow-unsigned-executable-memory` | Unsigned executable memory. Expected to be needed by a CPython application: ctypes/libffi build closure trampolines in memory they mark executable (sounddevice's PortAudio binding, vosk's libvosk binding, and several numeric wheels all go through ctypes), and the Hardened Runtime is documented to refuse such allocations without it. Whether this app really needs it has not been observed on a hardened build. It is the narrowest of the "allow ... memory" entitlements; `allow-jit` and its broader siblings are deliberately **not** requested. |
+| `com.apple.security.cs.disable-library-validation` | Library validation. A PyInstaller bundle `dlopen()`s dozens of third-party `.so`/`.dylib` files out of `Contents/Frameworks` and `Contents/Resources` at runtime (onnxruntime, PortAudio, libvosk, PyAV's FFmpeg libraries). Library validation demands every loaded library be signed by the same team ID as the main binary; the re-sign pass in `build.sh` does re-sign them, but any library loaded from a path the pass did not walk, or a plugin the user installs later into the same process, is then refused with an opaque "code signature invalid". This is the one entitlement that could be dropped later: it needs a build where every loadable object is provably signed by us, which the plugin system's "install a wheel at runtime" design currently rules out. |
+
+**Removed: `com.apple.security.device.camera`.** The old file requested it for
+"vision/screen-share features", but no code in Jarvis opens a camera (the web
+voice path asks for audio only, and screen capture is Screen Recording, not the
+camera), so it granted the right to ask for something nothing asks for.
+Re-adding it needs a camera feature, `NSCameraUsageDescription` in the string
+table and a caller in the same change.
+
+Screen Recording, Accessibility, Input Monitoring and posting events have no
+entitlement at all; they are gated by the person's decision in System Settings
+alone.
## Reaching the CLI
@@ -138,18 +298,25 @@ The in-app updater downloads the `.dmg` for this Mac's architecture from the
GitHub Release, verifies it against `installers-SHA256SUMS.txt` from the same
release, mounts it with `hdiutil attach`, replaces the running
`Personal Jarvis.app` atomically, detaches the image and relaunches with
-`open`. Because the bundle identifier does not change, the privacy grants the
-user already gave survive the update - that is the entire reason every launch
-path has to enter through one bundle identity.
+`open`. Whether the privacy grants the user already gave survive the update
+depends on the signature, not on the bundle identifier alone: with a Developer
+ID signature the identity (bundle id plus Team ID) is the same in every version
+and the grants stay; with the ad-hoc images published so far each version is a
+new app to macOS and every permission is asked for again. Either way, every
+launch path has to enter through one bundle identity.
## What has NOT been verified
-Nobody has run this script on a Mac yet. What has been checked:
-`bash -n`, ShellCheck 0.11.0 at `-S style` with zero findings, and a full
-`DRY_RUN=1` rehearsal of both the unsigned and the signed/notarized path,
-including a check that the app-specific password never reaches the output.
-
-A real run - PyInstaller on macOS, `codesign`, `notarytool`, `hdiutil`,
-Gatekeeper on a downloaded image, and the permission prompts - needs the macOS
-CI job or a physical Mac and is the last gate before the first public macOS
-release.
+The macOS CI runners build and publish the **ad-hoc** images (PyInstaller,
+`codesign -s -`, `hdiutil`; the v2.5.0 build log shows it). The signed and
+notarized path has never run for real: it needs the Apple secrets above, and with
+them the first real `codesign`, `notarytool` and `stapler` pass, the first
+import into a real keychain, Gatekeeper on a downloaded image, and the permission
+prompts of a signed app are all still to be seen. The certificate export steps
+and the first-launch steps for each macOS version are written from Apple's
+documentation, not from a run. What has been checked off a Mac: `bash -n`,
+ShellCheck 0.11.0 at `-S style` with zero findings, a `DRY_RUN=1` rehearsal of
+the unsigned path, the certificate import and the signed/notarized path, and the
+real import branch run against a stand-in `security` command
+(`tests/unit/packaging/test_macos_build_script.py`), including that no secret
+reaches the output.
diff --git a/packaging/macos/add_localizations.py b/packaging/macos/add_localizations.py
new file mode 100644
index 0000000000..6a49656f7b
--- /dev/null
+++ b/packaging/macos/add_localizations.py
@@ -0,0 +1,66 @@
+"""Write the German and Spanish ``InfoPlist.strings`` into a built ``Personal Jarvis.app``.
+
+PyInstaller's ``BUNDLE`` writes the base (English) ``Info.plist`` and, through
+``jarvis.spec``, the ``CFBundleLocalizations`` key. The per-language strings that
+macOS shows in its permission dialogs live in ``Contents/Resources/<lang>.lproj/
+InfoPlist.strings`` and cannot come from the spec, so ``packaging/macos/build.sh``
+runs this script on the finished ``.app`` BEFORE it signs it: the files are part of
+the code seal, and a file added afterwards would invalidate the signature.
+
+The text comes from the single table in ``jarvis/core/macos_privacy_strings.py``,
+loaded by path exactly like ``jarvis.spec`` does (the package is not necessarily
+importable on the build machine). The managed source-install app writes the same
+files itself (``jarvis.setup.macos_app_bundle``), so both bundles show the same
+sentences.
+
+ python packaging/macos/add_localizations.py --app "dist/Personal Jarvis.app"
+
+Exit codes: 0 = written, 1 = the app bundle is not usable (no ``Contents`` folder).
+"""
+
+from __future__ import annotations
+
+import argparse
+import importlib.util
+import sys
+from pathlib import Path
+from types import ModuleType
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+TABLE_PATH = REPO_ROOT / "jarvis" / "core" / "macos_privacy_strings.py"
+
+
+def _load_table(path: Path = TABLE_PATH) -> ModuleType:
+ """Load the usage-string table by path (it imports nothing from ``jarvis``)."""
+ loader_spec = importlib.util.spec_from_file_location("_jarvis_macos_privacy_strings", path)
+ if loader_spec is None or loader_spec.loader is None:
+ raise RuntimeError(f"cannot load the macOS usage strings from {path}")
+ module = importlib.util.module_from_spec(loader_spec)
+ loader_spec.loader.exec_module(module)
+ return module
+
+
+def add_localizations(app: Path) -> list[Path]:
+ """Write the ``.lproj`` files into ``app``'s ``Contents/Resources``; return them."""
+ contents = app / "Contents"
+ if not (contents / "Info.plist").is_file():
+ raise FileNotFoundError(f"{app} has no Contents/Info.plist - is it a built app bundle?")
+ return _load_table().write_localizations(contents / "Resources")
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--app", required=True, type=Path, help="the built Personal Jarvis.app")
+ args = parser.parse_args(argv)
+ try:
+ written = add_localizations(args.app)
+ except (OSError, RuntimeError) as exc:
+ print(f"add_localizations: {type(exc).__name__}: {exc}", file=sys.stderr)
+ return 1
+ for path in written:
+ print(f"add_localizations: wrote {path.relative_to(args.app)}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/packaging/macos/build.sh b/packaging/macos/build.sh
index 597f2844ab..7d089201a9 100755
--- a/packaging/macos/build.sh
+++ b/packaging/macos/build.sh
@@ -20,6 +20,15 @@
# APPLE_TEAM_ID 10-character team identifier
# APPLE_APP_SPECIFIC_PASSWORD app-specific password for that Apple ID
#
+# A CI runner has no Developer ID certificate in any keychain, so two more
+# optional variables carry it in (a maintainer's own Mac needs neither):
+#
+# APPLE_CERTIFICATE_P12_BASE64 base64 of the exported Developer ID .p12
+# APPLE_CERTIFICATE_PASSWORD the password chosen when exporting it
+#
+# With those set, APPLE_SIGNING_IDENTITY may be left out: the identity is read
+# back from the imported certificate.
+#
# With APPLE_SIGNING_IDENTITY unset the script ad-hoc signs instead and skips
# notarization, printing one clear line about what that means for the person
# who downloads the result. Nothing is silently "signed enough".
@@ -44,6 +53,9 @@ APP_BUNDLE="${DIST_DIR}/${APP_NAME}.app"
OUT_DIR="${DIST_DIR}/installers"
FRONTEND_DIST="${REPO_ROOT}/jarvis/ui/web/dist"
ENTITLEMENTS="${SCRIPT_DIR}/entitlements.plist"
+# The copy of ENTITLEMENTS that codesign embeds; see prepare_entitlements().
+NORMALIZED_ENTITLEMENTS="${DIST_DIR}/entitlements.normalized.plist"
+SIGNING_ENTITLEMENTS="${ENTITLEMENTS}"
ICNS="${REPO_ROOT}/assets/icons/jarvis.icns"
log() { printf '[macos-build] %s\n' "$*"; }
@@ -80,6 +92,114 @@ esac
DMG_PATH="${OUT_DIR}/PersonalJarvis-macOS-${ARCH_TAG}.dmg"
log "host ${MACHINE} -> building ${ARCH_TAG}"
+# A half-configured certificate is a mistake worth hearing about before the
+# long freeze, not after it.
+if [ -n "${APPLE_CERTIFICATE_P12_BASE64:-}" ] && [ -z "${APPLE_CERTIFICATE_PASSWORD:-}" ]; then
+ die "APPLE_CERTIFICATE_P12_BASE64 is set but APPLE_CERTIFICATE_PASSWORD is not"
+fi
+
+# --- 0b. Developer ID certificate (CI runners) -------------------------------
+#
+# codesign can only use an identity that lives in a keychain, and a GitHub
+# runner starts with none: APPLE_SIGNING_IDENTITY alone made every signed build
+# fail with "no identity found" while the workflow passed the certificate
+# secrets along to a script that never read them. The certificate is imported
+# into a throw-away keychain that is removed (and the search list restored) when
+# the script exits, so it never outlives the build. It happens FIRST, before the
+# long freeze: a wrong password or a certificate without a Developer ID identity
+# should cost seconds, not a finished PyInstaller run. No command that carries a
+# secret goes through run(), which echoes its argv.
+
+SIGNING_KEYCHAIN=""
+SIGNING_CERT_FILE=""
+ORIGINAL_KEYCHAINS=()
+
+decode_base64() {
+ # macOS spells the flag --decode on current releases and -D on older ones.
+ if base64 --decode </dev/null >/dev/null 2>&1; then base64 --decode; else base64 -D; fi
+}
+
+# Runs on EVERY exit - success, `die`, `set -e`, a signal - so a failed import
+# cannot leave the decoded certificate (the private key, password-protected) or
+# the temporary keychain behind on a machine that is not thrown away afterwards.
+cleanup_signing_material() {
+ [ -z "${SIGNING_CERT_FILE}" ] || rm -f "${SIGNING_CERT_FILE}"
+ [ -n "${SIGNING_KEYCHAIN}" ] || return 0
+ if [ "${#ORIGINAL_KEYCHAINS[@]}" -gt 0 ]; then
+ security list-keychains -d user -s "${ORIGINAL_KEYCHAINS[@]}" >/dev/null 2>&1 || true
+ fi
+ security delete-keychain "${SIGNING_KEYCHAIN}" >/dev/null 2>&1 || true
+}
+trap cleanup_signing_material EXIT
+
+import_signing_certificate() {
+ [ -n "${APPLE_CERTIFICATE_P12_BASE64:-}" ] || return 0
+
+ local scratch keychain cert_file keychain_password line identities
+ scratch="${RUNNER_TEMP:-${TMPDIR:-/tmp}}"
+ scratch="${scratch%/}"
+ keychain="${scratch}/jarvis-signing.keychain-db"
+ cert_file="${scratch}/jarvis-signing-certificate.p12"
+
+ log "importing the Developer ID certificate into a temporary keychain"
+ if [ "${DRY_RUN}" = "1" ]; then
+ printf '+ security list-keychains -d user # remembered, restored on exit\n'
+ printf '+ security create-keychain -p <redacted> %q\n' "${keychain}"
+ printf '+ security import <redacted .p12> -k %q -P <redacted> -T /usr/bin/codesign\n' "${keychain}"
+ printf '+ security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k <redacted> %q\n' "${keychain}"
+ printf '+ security list-keychains -d user -s %q <the existing keychains>\n' "${keychain}"
+ APPLE_SIGNING_IDENTITY="${APPLE_SIGNING_IDENTITY:-<identity read from the imported certificate>}"
+ return 0
+ fi
+
+ SIGNING_KEYCHAIN="${keychain}"
+ SIGNING_CERT_FILE="${cert_file}"
+ keychain_password="$(uuidgen)"
+
+ # Remember the user's search list BEFORE creating anything: `create-keychain`
+ # adds the new keychain to it. `security` prints each path indented and
+ # quoted; strip both with sed (bash 3.2 treats quotes inside ${var#...}
+ # patterns differently from newer shells).
+ while IFS= read -r line; do
+ [ -z "${line}" ] || ORIGINAL_KEYCHAINS+=("${line}")
+ done < <(security list-keychains -d user | sed 's/^[[:space:]]*"//; s/"[[:space:]]*$//')
+
+ # A keychain left behind by an interrupted earlier run would fail the create.
+ security delete-keychain "${keychain}" >/dev/null 2>&1 || true
+ security create-keychain -p "${keychain_password}" "${keychain}"
+ # Stay unlocked for the whole build (6 h), even across an idle period.
+ security set-keychain-settings -lut 21600 "${keychain}"
+ security unlock-keychain -p "${keychain_password}" "${keychain}"
+
+ # Owner-only: the file holds the (password-protected) private key.
+ (umask 077 && printf '%s' "${APPLE_CERTIFICATE_P12_BASE64}" | decode_base64 > "${cert_file}")
+ security import "${cert_file}" -k "${keychain}" -P "${APPLE_CERTIFICATE_PASSWORD}" \
+ -T /usr/bin/codesign -T /usr/bin/security
+ rm -f "${cert_file}"
+ # Without this macOS asks (via a dialog nobody can answer on a runner) whether
+ # codesign may use the private key.
+ security set-key-partition-list -S apple-tool:,apple:,codesign: -s \
+ -k "${keychain_password}" "${keychain}" >/dev/null
+
+ # codesign looks identities up through the search list: put ours first.
+ security list-keychains -d user -s "${keychain}" \
+ ${ORIGINAL_KEYCHAINS[@]+"${ORIGINAL_KEYCHAINS[@]}"}
+
+ if [ -z "${APPLE_SIGNING_IDENTITY:-}" ]; then
+ identities="$(security find-identity -v -p codesigning "${keychain}")"
+ APPLE_SIGNING_IDENTITY="$(
+ printf '%s\n' "${identities}" \
+ | sed -n 's/.*"\(Developer ID Application:[^"]*\)".*/\1/p' \
+ | head -n 1
+ )"
+ [ -n "${APPLE_SIGNING_IDENTITY}" ] \
+ || die "the imported certificate holds no valid 'Developer ID Application' identity - an Apple Development or App Store certificate cannot sign an app distributed outside the App Store, and the .p12 must be exported together with its certificate chain"
+ log "signing identity read from the certificate: ${APPLE_SIGNING_IDENTITY}"
+ fi
+}
+
+import_signing_certificate
+
# --- 1. Web bundle ----------------------------------------------------------
if [ -d "${FRONTEND_DIST}" ] && [ -f "${FRONTEND_DIST}/index.html" ]; then
@@ -152,16 +272,52 @@ if building; then
[ -x "${APP_BUNDLE}/Contents/MacOS/${BUNDLE_EXECUTABLE}" ] \
|| die "Info.plist names '${BUNDLE_EXECUTABLE}' as CFBundleExecutable, but Contents/MacOS/${BUNDLE_EXECUTABLE} does not exist"
log "bundle executable: ${BUNDLE_EXECUTABLE}"
+ # plutil ships with macOS only. A malformed Info.plist would make Finder call
+ # the app damaged, so say so here, before signing and notarizing it.
+ if command -v plutil >/dev/null 2>&1; then
+ run plutil -lint "${APP_BUNDLE}/Contents/Info.plist"
+ fi
fi
log "app bundle: ${APP_BUNDLE}"
+# German and Spanish permission-dialog text. The languages are declared in the
+# plist by jarvis.spec; the <lang>.lproj/InfoPlist.strings files are written here
+# from the same table, BEFORE signing: they are part of the code seal, so a file
+# added after codesign would break the signature (and the notarization).
+run "${PYTHON}" "${SCRIPT_DIR}/add_localizations.py" --app "${APP_BUNDLE}"
+if building && command -v plutil >/dev/null 2>&1; then
+ for strings_file in "${APP_BUNDLE}"/Contents/Resources/*.lproj/InfoPlist.strings; do
+ run plutil -lint "${strings_file}"
+ done
+fi
+
# --- 3. Code signing --------------------------------------------------------
+# Apple documents no comment syntax for an entitlements file, so
+# entitlements.plist carries none (why each entry exists is written down in
+# packaging/macos/README.md). Where plutil exists - on macOS - the file is
+# validated and rewritten as canonical XML into a copy under dist/, and codesign
+# embeds that copy: a hand edit that is not a valid property list then fails
+# here, in seconds, not as an opaque signing error after the long freeze.
+# Elsewhere (a DRY_RUN rehearsal on another OS) the file is used as it is.
+prepare_entitlements() {
+ SIGNING_ENTITLEMENTS="${ENTITLEMENTS}"
+ if ! command -v plutil >/dev/null 2>&1; then
+ log "plutil not found - signing with ${ENTITLEMENTS} as it is"
+ return 0
+ fi
+ run mkdir -p "${DIST_DIR}"
+ run plutil -lint "${ENTITLEMENTS}"
+ run plutil -convert xml1 -o "${NORMALIZED_ENTITLEMENTS}" "${ENTITLEMENTS}"
+ SIGNING_ENTITLEMENTS="${NORMALIZED_ENTITLEMENTS}"
+}
+
SIGNED_FOR_DISTRIBUTION=0
if [ -n "${APPLE_SIGNING_IDENTITY:-}" ]; then
SIGNED_FOR_DISTRIBUTION=1
log "signing with Developer ID identity: ${APPLE_SIGNING_IDENTITY}"
[ -f "${ENTITLEMENTS}" ] || die "entitlements file missing: ${ENTITLEMENTS}"
+ prepare_entitlements
# Inside-out first: codesign refuses to seal a bundle whose nested Mach-O
# objects are unsigned or stale, and a PyInstaller bundle carries hundreds of
@@ -170,7 +326,7 @@ if [ -n "${APPLE_SIGNING_IDENTITY:-}" ]; then
if building; then
while IFS= read -r -d '' object; do
run codesign --force --timestamp --options runtime \
- --entitlements "${ENTITLEMENTS}" \
+ --entitlements "${SIGNING_ENTITLEMENTS}" \
--sign "${APPLE_SIGNING_IDENTITY}" "${object}"
done < <(
find "${APP_BUNDLE}/Contents" -type f \
@@ -186,7 +342,7 @@ if [ -n "${APPLE_SIGNING_IDENTITY:-}" ]; then
fi
run codesign --force --deep --timestamp --options runtime \
- --entitlements "${ENTITLEMENTS}" \
+ --entitlements "${SIGNING_ENTITLEMENTS}" \
--sign "${APPLE_SIGNING_IDENTITY}" "${APP_BUNDLE}"
run codesign --verify --strict --verbose=2 "${APP_BUNDLE}"
else
diff --git a/packaging/macos/entitlements.plist b/packaging/macos/entitlements.plist
index 87184f3cbc..80f7cf7ac4 100644
--- a/packaging/macos/entitlements.plist
+++ b/packaging/macos/entitlements.plist
@@ -1,74 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<!--
- Hardened Runtime entitlements for the notarized "Personal Jarvis.app".
-
- Notarization requires the Hardened Runtime (codesign --options runtime), and
- the Hardened Runtime denies by default exactly the things this app needs.
- Every entry below is here because leaving it out breaks a shipped feature or
- stops the app from launching at all — nothing is requested "just in case",
- because each one weakens a real platform protection.
-
- The matching user-facing NSxxxUsageDescription strings live in the bundle's
- Info.plist (built by jarvis.spec). Entitlements grant the app the RIGHT to
- ask; the usage strings are what the person reads in the prompt. Both halves
- are required: a hardened app missing the entitlement is refused before the
- prompt appears, and one missing the usage string is killed by the system the
- moment it asks.
--->
<plist version="1.0">
<dict>
- <!--
- Microphone. The whole voice pipeline (wake word, dictation, calls) reads
- the default input device through PortAudio. Without this a hardened build
- fails every capture attempt instead of showing the microphone prompt.
- -->
<key>com.apple.security.device.audio-input</key>
<true/>
-
- <!--
- Camera. Only the vision/screen-share features touch it, and they degrade
- honestly when the user declines - but a hardened app without the
- entitlement cannot even ask, so the decline would not be the user's.
- -->
- <key>com.apple.security.device.camera</key>
- <true/>
-
- <!--
- Apple events. Jarvis drives other applications through AppleScript for the
- media-session and window-control paths (jarvis/platform/media_session.py,
- music_player.py). Sending an Apple event to another process from a hardened
- app requires this entitlement plus the NSAppleEventsUsageDescription string.
- -->
<key>com.apple.security.automation.apple-events</key>
<true/>
-
- <!--
- Unsigned executable memory. Not optional for a CPython application:
- ctypes/libffi build closure trampolines in memory it marks executable
- (sounddevice's PortAudio binding, vosk's libvosk binding, and several
- numeric wheels all go through ctypes). The Hardened Runtime kills the
- process on the first such allocation without this. Justified rather than
- inherited: it is the narrowest of the three "allow ... memory" entitlements
- - allow-jit and allow-unsigned-executable-memory's unrestricted sibling are
- deliberately NOT requested.
- -->
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
-
- <!--
- Library validation. A PyInstaller bundle dlopen()s dozens of third-party
- .so/.dylib files out of Contents/Frameworks and Contents/Resources at
- runtime (onnxruntime, PortAudio, libvosk, PyAV's FFmpeg libraries). Library
- validation demands every loaded library be signed by the SAME team ID as
- the main binary; the re-sign pass in packaging/macos/build.sh does re-sign
- them, but any library loaded from a path the pass did not walk - or a
- plugin the user installs later into the same process - is then refused and
- the feature dies with an opaque "code signature invalid". This is the one
- entitlement here that could be dropped later: it needs a build where every
- loadable object is provably signed by us, which the plugin system's
- "install a wheel at runtime" design currently rules out.
- -->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
diff --git a/pyproject.toml b/pyproject.toml
index 1bbe07ed0d..d59c7e7462 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -327,10 +327,13 @@ desktop = [
"winrt-Windows.Media.Control>=3.2; sys_platform == 'win32'",
"pystray>=0.19",
"pywebview>=5.3",
- # macOS uses pynput for global hotkeys. Linux keeps pyautogui/no-op fallbacks:
- # pynput would otherwise compile evdev against host kernel headers, breaking
- # the advertised [full] install on a stock headless image. ptyprocess is the
- # POSIX terminal backend; Windows keeps pywinpty above.
+ # macOS needs pynput for Computer-Use keyboard actuation and the has_hotkey
+ # capability probe; its global hotkeys run on a listen-only Quartz event tap
+ # instead (jarvis/trigger/backends/quartz.py, BUG-077). Linux keeps
+ # pyautogui/no-op fallbacks: pynput would otherwise compile evdev against
+ # host kernel headers, breaking the advertised [full] install on a stock
+ # headless image. ptyprocess is the POSIX terminal backend; Windows keeps
+ # pywinpty above.
"pynput>=1.7; sys_platform == 'darwin'",
"ptyprocess>=0.7; sys_platform != 'win32'",
# Screen capture (mss) + desktop input automation (pyautogui) — all-platform
diff --git a/scripts/ci/check_frozen_browser.py b/scripts/ci/check_frozen_browser.py
index 3dd59a9ceb..32f062974d 100644
--- a/scripts/ci/check_frozen_browser.py
+++ b/scripts/ci/check_frozen_browser.py
@@ -2,7 +2,9 @@
Run after packaging, with --executable pointing at the built launcher. Two
headless boots share a fresh scratch profile; no source imports, account keys,
-desktop input, or existing user state are passed to the child application.
+desktop input, or existing user state are passed to the child application. On
+macOS each boot also asks the running app for its permission status, which is
+the only way to see whether its pyobjc frameworks loaded (BUG-222).
"""
from __future__ import annotations
@@ -31,6 +33,7 @@ sys.path.insert(0, str(ROOT))
from jarvis.core.config_writer import _WRITE_LOCK, _atomic_write # noqa: E402
from jarvis.core.instance import DEV_PORT_OFFSET # noqa: E402
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS, wait_procs # noqa: E402
+from jarvis.platform.permissions import ACCEPTED_BUNDLE_IDS # noqa: E402
def isolated_env(profile: Path, port: int, key: str) -> dict[str, str]:
@@ -118,6 +121,46 @@ def request_json(port: int, path: str, key: str) -> dict:
connection.close()
+def check_macos_permissions(port: int, key: str) -> dict:
+ """On macOS, prove the running app can read its own microphone permission.
+
+ The permission port loads its pyobjc frameworks by NAME, which a freezer
+ cannot follow, and reports a framework that did not load as "unavailable"
+ without any error: the v2.5.0 .dmg shipped without AVFoundation and could
+ never read its microphone permission (BUG-222). Whether the module is in
+ the archive is checked statically by check_frozen_macos_app.py; this asks
+ the app itself, which also catches a framework whose own dependencies were
+ left out. Elsewhere there is nothing to ask.
+
+ The status route is passive (it never raises a system dialog), and this
+ reads only keys that survive in the snapshot: ``permissions[].id/status``
+ and ``app_identity.bundle_id``.
+ """
+ if sys.platform != "darwin":
+ return {}
+ try:
+ snapshot = request_json(port, "/api/permissions/status", key)
+ except ProbeHTTPError as exc:
+ if exc.code == 404:
+ # Not "still starting": waiting for the deadline would only hide it.
+ raise RuntimeError("Frozen app does not serve /api/permissions/status") from None
+ raise
+ rows = [row for row in snapshot.get("permissions", []) if isinstance(row, dict)]
+ microphone = next((row.get("status") for row in rows if row.get("id") == "microphone"), None)
+ if microphone in (None, "unavailable"):
+ raise RuntimeError(
+ f"Frozen app cannot read its microphone permission (status {microphone!r}): "
+ "the pyobjc AVFoundation framework did not load"
+ )
+ bundle_id = (snapshot.get("app_identity") or {}).get("bundle_id")
+ if bundle_id not in ACCEPTED_BUNDLE_IDS:
+ raise RuntimeError(
+ f"Frozen app runs as {bundle_id!r}, which the permission port does not accept "
+ f"(expected one of {', '.join(ACCEPTED_BUNDLE_IDS)})"
+ )
+ return {"microphone_permission": microphone, "bundle_id": bundle_id}
+
+
def capture_frame(port: int, key: str, output: Path) -> dict:
started = time.monotonic()
with connect(
@@ -176,6 +219,8 @@ def boot(executable: Path, profile: Path, output: Path, key: str, timeout: float
if health.get("instance") != "dev":
raise RuntimeError("Frozen probe reached the wrong app instance")
report["healthy_seconds"] = round(time.monotonic() - started, 3)
+ if "permissions" not in report and "healthy_seconds" in report:
+ report["permissions"] = check_macos_permissions(port, key)
status = request_json(port, "/api/society/browser/status", key)
except ProbeHTTPError as exc:
if exc.code not in {503, 404}:
diff --git a/scripts/ci/check_frozen_macos_app.py b/scripts/ci/check_frozen_macos_app.py
new file mode 100644
index 0000000000..fc1ce9a1f0
--- /dev/null
+++ b/scripts/ci/check_frozen_macos_app.py
@@ -0,0 +1,366 @@
+#!/usr/bin/env python3
+"""Prove a built macOS app can use its privacy permissions, before it ships.
+
+Why this gate exists (BUG-222). The v2.5.0 ``.dmg`` shipped with two defects
+that no headless smoke run can see, because the smoke run starts the executable
+directly instead of the way a user does:
+
+* The pyobjc ``AVFoundation`` module was not in the frozen archive. The
+ permission port loads it by NAME (``SystemPermissionPort._load``), which
+ PyInstaller's static analysis cannot follow, so the app read its microphone
+ permission as "unavailable" for good and the voice gate never opened.
+* ``Info.plist`` said ``LSBackgroundOnly``. PyInstaller sets it whenever the
+ last executable of the COLLECT is a console one (the ``jarvis`` CLI is), and
+ LaunchServices then runs the app as a faceless background process.
+
+This script reads the finished ``.app`` itself: the plist, and the module table
+of the frozen archive embedded in the main executable (the same data
+``pyi-archive_viewer`` prints). It runs on any host that has PyInstaller, and
+fails with the exact thing that is missing.
+
+It also asserts the privacy-permission declarations of the bundle:
+
+* every ``NS...UsageDescription`` string of the single table in
+ ``jarvis/core/macos_privacy_strings.py`` is in ``Info.plist`` with exactly that
+ text, and the keys that table lists as removed (camera, speech recognition,
+ system administration) are not;
+* the bundle is localised for German and Spanish: ``Info.plist`` declares
+ ``CFBundleLocalizations`` and ``CFBundleDevelopmentRegion``, and
+ ``Contents/Resources/<lang>.lproj/InfoPlist.strings`` exists for each language
+ with exactly the text of that table (``packaging/macos/add_localizations.py``
+ writes them before signing; a file missing here means the build step did not run);
+* on a SIGNED build (a certificate identity, i.e. the Developer ID path of
+ ``packaging/macos/build.sh``), ``codesign -d --entitlements :-`` must report
+ every entitlement of ``packaging/macos/entitlements.plist`` and none of the
+ removed ones. An unsigned or ad-hoc build embeds no entitlements, so that
+ half is SKIPPED with a message that says so; a skip is not a pass. It also
+ needs ``codesign``, which exists on macOS only. The behaviour of a hardened
+ signed build on a real Mac is unverified: this reads declarations, it does not
+ run the app.
+
+Usage:
+ python scripts/ci/check_frozen_macos_app.py --app "dist/Personal Jarvis.app"
+
+Exit codes: 0 = fine (skipped parts are printed as NOTE lines), 1 = the app would
+ship broken (problems listed), 2 = could not check (missing file, unreadable
+archive, no PyInstaller, a signature codesign cannot read).
+"""
+
+from __future__ import annotations
+
+import argparse
+import plistlib
+import re
+import subprocess
+import sys
+from collections.abc import Callable, Collection, Mapping, Sequence
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+
+from jarvis.core import macos_privacy_strings # noqa: E402
+from jarvis.core.branding import MACOS_DMG_BUNDLE_ID # noqa: E402
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # noqa: E402
+
+ENTITLEMENTS_FILE = ROOT / "packaging" / "macos" / "entitlements.plist"
+
+# Entitlements that must never be embedded: Jarvis has no caller for them, so
+# they would grant the right to ask for something nothing asks for.
+REMOVED_ENTITLEMENTS: tuple[str, ...] = ("com.apple.security.device.camera",)
+
+# ``codesign`` is invoked as ``codesign <args>``; the seam returns the finished
+# process with BYTES in stdout and stderr (the plist may carry any encoding).
+CodesignRunner = Callable[[Sequence[str]], "subprocess.CompletedProcess[bytes]"]
+
+# Modules the permission port and the macOS input/capture code reach by NAME or
+# through the frameworks' own lazy loaders: all of them must be in the archive.
+REQUIRED_FROZEN_MODULES: tuple[str, ...] = (
+ "AVFoundation",
+ "ApplicationServices",
+ "AppKit",
+ "Foundation",
+ "Quartz",
+ "objc",
+)
+
+
+def check_info_plist(info: dict, macos_dir: Path) -> list[str]:
+ """What is wrong with the bundle's ``Info.plist`` (empty list = fine)."""
+ problems: list[str] = []
+ if info.get("CFBundleIdentifier") != MACOS_DMG_BUNDLE_ID:
+ problems.append(
+ f"CFBundleIdentifier is {info.get('CFBundleIdentifier')!r}, but the permission "
+ f"port accepts {MACOS_DMG_BUNDLE_ID!r} for this app"
+ )
+ if info.get("LSBackgroundOnly"):
+ problems.append(
+ "LSBackgroundOnly is true: LaunchServices would run the app as a faceless "
+ "background process (no Dock icon, no windows). Set it to False in jarvis.spec."
+ )
+ executable = info.get("CFBundleExecutable")
+ if not isinstance(executable, str) or not (macos_dir / executable).is_file():
+ problems.append(f"CFBundleExecutable {executable!r} is not in Contents/MacOS")
+ problems += check_usage_strings(info)
+ problems += check_localization_keys(info)
+ return problems
+
+
+# What a missing string costs, per key. The microphone one is the documented
+# process-ending case; the others are third-party reports (silent refusal, no
+# prompt) and therefore worded as "may".
+_MISSING_STRING_CONSEQUENCE = {
+ "NSMicrophoneUsageDescription": "macOS ends the process the moment it asks for the microphone",
+}
+_DEFAULT_MISSING_STRING_CONSEQUENCE = (
+ "macOS may refuse the request without ever showing a permission prompt"
+)
+
+
+def check_usage_strings(info: Mapping[str, object]) -> list[str]:
+ """What is wrong with the bundle's usage-description strings (empty = fine).
+
+ The reference is ``jarvis/core/macos_privacy_strings.py``, the one table the
+ spec and the managed bundle both load: a missing, blank or different string
+ means this bundle was not built from it, and a key from the removed list
+ claims access the app never uses.
+ """
+ problems: list[str] = []
+ expected = macos_privacy_strings.usage_descriptions()
+ for key in macos_privacy_strings.REQUIRED_USAGE_KEYS:
+ value = info.get(key)
+ if not isinstance(value, str) or not value.strip():
+ consequence = _MISSING_STRING_CONSEQUENCE.get(key, _DEFAULT_MISSING_STRING_CONSEQUENCE)
+ problems.append(f"{key} is missing: {consequence}")
+ elif value != expected[key]:
+ problems.append(
+ f"{key} differs from jarvis/core/macos_privacy_strings.py: the bundle was "
+ "not built from the single usage-string table (jarvis.spec must load it)"
+ )
+ for key in macos_privacy_strings.REMOVED_USAGE_KEYS:
+ if key in info:
+ problems.append(
+ f"{key} is in Info.plist but Jarvis has no caller for that permission: "
+ "remove it from jarvis.spec (least privilege)"
+ )
+ return problems
+
+
+def check_localization_keys(info: Mapping[str, object]) -> list[str]:
+ """What is wrong with the localisation declarations of ``Info.plist`` (empty = fine)."""
+ expected = macos_privacy_strings.localization_plist_keys()
+ problems: list[str] = []
+ for key, value in expected.items():
+ if info.get(key) != value:
+ problems.append(
+ f"{key} is {info.get(key)!r}, expected {value!r}: the bundle declares no "
+ "German/Spanish localisation (jarvis.spec must spread "
+ "localization_plist_keys() into its Info.plist)"
+ )
+ return problems
+
+
+def check_localization_files(resources_dir: Path) -> list[str]:
+ """Which ``<lang>.lproj/InfoPlist.strings`` are missing or differ from the table."""
+ problems: list[str] = []
+ for language in macos_privacy_strings.LOCALIZED_LANGUAGES:
+ target = resources_dir / f"{language}.lproj" / "InfoPlist.strings"
+ if not target.is_file():
+ problems.append(
+ f"{language}.lproj/InfoPlist.strings is missing from Contents/Resources: "
+ "macOS would show the English permission text only (build.sh runs "
+ "packaging/macos/add_localizations.py before signing)"
+ )
+ continue
+ try:
+ text = target.read_text(encoding="utf-8")
+ except UnicodeDecodeError:
+ problems.append(f"{language}.lproj/InfoPlist.strings is not valid UTF-8")
+ continue
+ if text != macos_privacy_strings.info_plist_strings_text(language):
+ problems.append(
+ f"{language}.lproj/InfoPlist.strings differs from "
+ "jarvis/core/macos_privacy_strings.py: it was not written from the "
+ "single usage-string table"
+ )
+ return problems
+
+
+# --- code signature and entitlements ------------------------------------------
+
+
+def _run_codesign(args: Sequence[str]) -> subprocess.CompletedProcess[bytes]:
+ """The real ``codesign``; raises ``FileNotFoundError`` where it does not exist."""
+ return subprocess.run( # noqa: S603 - fixed argv, no shell
+ ["codesign", *args],
+ capture_output=True,
+ timeout=120,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+
+
+def _text(blob: bytes) -> str:
+ return blob.decode("utf-8", errors="replace")
+
+
+def signing_kind(app: Path, run: CodesignRunner) -> str:
+ """``"identity"`` (signed with a certificate), ``"adhoc"`` or ``"unsigned"``.
+
+ Reads ``codesign -dvv`` (its report goes to stderr). Raises ``RuntimeError``
+ for output it cannot classify, because guessing here would either skip a
+ check that should run or demand entitlements an ad-hoc build never has.
+ """
+ result = run(["-dvv", str(app)])
+ report = _text(result.stderr) + "\n" + _text(result.stdout)
+ if "not signed at all" in report:
+ return "unsigned"
+ if re.search(r"^Signature=adhoc\s*$", report, re.MULTILINE):
+ return "adhoc"
+ if re.search(r"^Authority=\S", report, re.MULTILINE):
+ return "identity"
+ first = next((line for line in report.splitlines() if line.strip()), "<no output>")
+ raise RuntimeError(
+ f"codesign -dvv gave no signature kind I recognise (exit {result.returncode}): {first}"
+ )
+
+
+_PLIST_XML = re.compile(rb"<\?xml.*?</plist>", re.DOTALL)
+
+
+def read_entitlements(app: Path, run: CodesignRunner) -> dict[str, object]:
+ """The entitlements embedded in the signed ``app`` (empty = none embedded).
+
+ ``codesign -d --entitlements :-`` writes the entitlements as an XML plist
+ on stdout; older and newer macOS differ in what else surrounds it (an
+ ``Executable=`` line on stderr, sometimes a blob header), so the plist is cut
+ out of the output instead of parsing the whole stream.
+ """
+ result = run(["-d", "--entitlements", ":-", str(app)])
+ for stream in (result.stdout, result.stderr):
+ match = _PLIST_XML.search(stream)
+ if match:
+ parsed = plistlib.loads(match.group(0))
+ if not isinstance(parsed, dict):
+ raise RuntimeError("codesign reported entitlements that are not a dictionary")
+ return parsed
+ return {}
+
+
+def check_entitlements(found: Mapping[str, object], expected: Mapping[str, object]) -> list[str]:
+ """What an embedded entitlement set lacks, or carries that it must not."""
+ problems = [
+ f"the signed app lacks entitlement {key} (packaging/macos/entitlements.plist asks for it)"
+ for key, value in expected.items()
+ if found.get(key) != value
+ ]
+ problems += [
+ f"the signed app carries entitlement {key}, which Jarvis has no caller for "
+ "(least privilege)"
+ for key in REMOVED_ENTITLEMENTS
+ if key in found
+ ]
+ return problems
+
+
+def check_signature(
+ app: Path,
+ *,
+ run: CodesignRunner | None = None,
+ notes: list[str] | None = None,
+ entitlements_file: Path | None = None,
+) -> list[str]:
+ """Entitlement problems of a SIGNED build; a skip is recorded in ``notes``."""
+ notes = notes if notes is not None else []
+ runner = run if run is not None else _run_codesign
+ try:
+ kind = signing_kind(app, runner)
+ except FileNotFoundError:
+ notes.append(
+ "entitlements NOT checked: codesign is not available on this host "
+ "(it ships with macOS; run this on the Mac or macOS runner that built the app)"
+ )
+ return []
+ if kind != "identity":
+ state = "ad-hoc signed" if kind == "adhoc" else "unsigned"
+ notes.append(
+ f"entitlements NOT checked: the app is {state}, and build.sh embeds "
+ "entitlements only with a Developer ID identity (a skip, not a pass)"
+ )
+ return []
+ expected = plistlib.loads((entitlements_file or ENTITLEMENTS_FILE).read_bytes())
+ return check_entitlements(read_entitlements(app, runner), expected)
+
+
+def check_frozen_modules(names: Collection[str]) -> list[str]:
+ """Which required modules the frozen archive lacks (empty list = fine)."""
+ present = set(names)
+ return [
+ f"the frozen archive has no {module!r} module (needs the [desktop-macos] extra "
+ "on the build machine and a hidden import in jarvis.spec)"
+ for module in REQUIRED_FROZEN_MODULES
+ if module not in present
+ ]
+
+
+def frozen_module_names(executable: Path) -> set[str]:
+ """Every module name in the PYZ archives embedded in a frozen executable."""
+ from PyInstaller.archive.readers import CArchiveReader # noqa: PLC0415
+
+ archive = CArchiveReader(str(executable))
+ names: set[str] = set()
+ for entry_name, (*_, typecode) in archive.toc.items():
+ if typecode == "z":
+ names.update(archive.open_embedded_archive(entry_name).toc.keys())
+ return names
+
+
+def check_app(
+ app: Path,
+ *,
+ read_modules: Callable[[Path], Collection[str]] | None = None,
+ run_codesign: CodesignRunner | None = None,
+ notes: list[str] | None = None,
+) -> list[str]:
+ """All problems of the built ``app`` bundle; raises if the bundle cannot be read.
+
+ ``notes`` collects what was SKIPPED (no ``codesign`` on this host, or an
+ unsigned/ad-hoc build that embeds no entitlements) so the caller can print it.
+ """
+ read = read_modules if read_modules is not None else frozen_module_names
+ contents = app / "Contents"
+ with (contents / "Info.plist").open("rb") as stream:
+ info = plistlib.load(stream)
+ macos_dir = contents / "MacOS"
+ problems = check_info_plist(info, macos_dir)
+ problems += check_localization_files(contents / "Resources")
+ executable = info.get("CFBundleExecutable")
+ if isinstance(executable, str) and (macos_dir / executable).is_file():
+ problems += check_frozen_modules(read(macos_dir / executable))
+ problems += check_signature(app, run=run_codesign, notes=notes)
+ return problems
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--app", required=True, type=Path, help="the built Personal Jarvis.app")
+ args = parser.parse_args(argv)
+ notes: list[str] = []
+ try:
+ problems = check_app(args.app, notes=notes)
+ except Exception as exc: # noqa: BLE001 - any unreadable bundle or archive is "cannot check"
+ print(f"check_frozen_macos_app: cannot check {args.app}: {type(exc).__name__}: {exc}")
+ return 2
+ for note in notes:
+ print(f"check_frozen_macos_app: NOTE - {note}")
+ if problems:
+ print(f"check_frozen_macos_app: {args.app} would ship broken:")
+ for problem in problems:
+ print(f" - {problem}")
+ return 1
+ print(f"check_frozen_macos_app: OK - {args.app} can use macOS permissions.")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/ci/classify_changes.py b/scripts/ci/classify_changes.py
index 1039b68cd7..f0161e1a6b 100644
--- a/scripts/ci/classify_changes.py
+++ b/scripts/ci/classify_changes.py
@@ -115,27 +115,70 @@ _BROWSER_FILES = {
# standalone workflow also matched all of tests/** and jarvis/ui/**, which put
# three 45-minute macOS jobs behind nearly every PR; the lane keeps the
# platform code and the exact test files that job runs.
+#
+# The just-in-time permission service is called from many consumers, so the
+# lane also covers every directory that asks for, or acts on, a macOS
+# permission: capture and speech (jarvis/audio/), computer use (jarvis/cu/),
+# screenshots (jarvis/vision/, jarvis/screen_context/), dictation
+# (jarvis/dictation/), global shortcuts (jarvis/trigger/, which includes
+# jarvis/trigger/backends/) and the permission port, the service and window
+# control (jarvis/platform/: permissions.py, permission_service.py,
+# window_state.py). Packaging is covered too: the spec, packaging/macos/ and the
+# single usage-string table both bundles load. The tool plugins that capture or
+# type (screenshot, type_text, verify_localhost), the appshot gesture, the speech
+# diagnosis, the screen-context routes, the CLI relay and the bundle-id constants
+# are consumers too and are listed by file.
_MACOS_PREFIXES = (
"install/",
"jarvis/admin/",
+ "jarvis/appshot/",
"jarvis/audio/",
"jarvis/autostart/",
"jarvis/cu/",
+ "jarvis/dictation/",
"jarvis/platform/",
+ "jarvis/screen_context/",
"jarvis/setup/",
"jarvis/trigger/",
"jarvis/vision/",
"jarvis/ui/desktop",
+ "packaging/macos/",
"tests/unit/platform/",
+ "tests/unit/audio/",
"tests/unit/autostart/",
"tests/unit/cu/",
"tests/unit/setup/",
+ "tests/unit/trigger/",
+ "tests/unit/ui/web/test_permissions_",
"tests/unit/vision/",
)
_MACOS_FILES = {
"pyproject.toml",
"uv.lock",
".githooks/pre-push",
+ "jarvis.spec",
+ "jarvis/core/macos_privacy_strings.py",
+ "jarvis/core/branding.py",
+ "jarvis/core/events.py",
+ "jarvis/core/protocols.py",
+ "jarvis/cli_ctl/commands/permissions.py",
+ "jarvis/plugins/harness/computer_use.py",
+ "jarvis/plugins/tool/screen_snapshot.py",
+ "jarvis/plugins/tool/type_text.py",
+ "jarvis/plugins/tool/verify_localhost.py",
+ "jarvis/speech/diagnose.py",
+ "jarvis/speech/pipeline.py",
+ "jarvis/tasks/event_catalog.py",
+ "jarvis/ui/web/permissions_routes.py",
+ "jarvis/ui/web/screen_context_routes.py",
+ "jarvis/ui/web/settings_routes.py",
+ "tests/contract/test_permission_service_contract.py",
+ "tests/fakes/fake_permission_service.py",
+ "tests/fakes/fake_tcc.py",
+ "tests/unit/ci/test_check_frozen_macos_app.py",
+ "tests/unit/ci/test_macos_desktop_permission_step.py",
+ "tests/unit/ui/web/test_keybinds_input_monitoring_ask.py",
+ "tests/unit/core/test_permission_events.py",
"scripts/measure_boot.py",
"scripts/measure_desktop_boot.py",
}
diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txt
index 0ae4aa27ea..d7b23892ae 100644
--- a/scripts/ci/german-allowlist.txt
+++ b/scripts/ci/german-allowlist.txt
@@ -469,6 +469,12 @@ tests/unit/memory/test_profile_capture.py
# write in agent descriptions (de/en) onto capability ids ---
jarvis/society/focus.py
+# --- macOS permission-dialog localisation (2026-10): the German and Spanish
+# Info.plist usage strings live in the single usage-string table next to
+# the English ones; macOS shows them in its own permission dialogs on a
+# German or Spanish system (closed product surface: InfoPlist
+# localisations). The InfoPlist.strings files are generated from it. ---
+jarvis/core/macos_privacy_strings.py
# --- Local voice engine bench (2026-10-01): the German speech-input corpus the
# P0 bench renders, transcribes and sends to the local LLM (ADR-0037) ---
jarvis/voice_engine/bench/corpus/de.json
diff --git a/scripts/ci/macos_carbon_hotkey_spike.py b/scripts/ci/macos_carbon_hotkey_spike.py
new file mode 100644
index 0000000000..aaf0404a27
--- /dev/null
+++ b/scripts/ci/macos_carbon_hotkey_spike.py
@@ -0,0 +1,2588 @@
+#!/usr/bin/env python3
+"""Runner evidence for a FUTURE Carbon ``RegisterEventHotKey`` hotkey backend.
+
+No Carbon backend ships in this repository. macOS global shortcuts still use the
+listen-only CGEventTap (``QuartzHotkeyBackend``). This script exists so that the
+follow-up that would add a Carbon backend starts from measured facts instead of
+third-party claims: it records what the macOS runner reports, then runs every
+risky ctypes variant in a CHILD process so that a native crash (SIGSEGV, SIGILL,
+SIGTRAP, SIGABRT) becomes a row in a table instead of killing the job.
+
+What it does, in this order:
+
+1. Records the TCC context FIRST of everything that loads native code (only the
+ signal control, which loads nothing, runs earlier), in a CHILD process like all
+ native code here (the ``tcc_context`` experiment): ``CGPreflightListenEventAccess``,
+ ``CGPreflightPostEventAccess``, ``AXIsProcessTrusted``, ``IOHIDCheckAccess``
+ (listen and post), the macOS version/build, the architecture, the Python
+ build and whether a window-server session exists. Every probe is wrapped; a
+ failure is recorded, never raised. It only ever calls non-prompting reads: no
+ ``Request`` API, no event tap. The parent process loads no framework at all.
+2. Runs each experiment of :data:`EXPERIMENTS` in its own child process
+ (``python <this file> --child NAME``) in its own process group under a hard
+ timeout and records the return code, the signal name (a negative return
+ code), the outcome and the stdout/stderr tails. A timeout, an interrupt and a
+ normal exit all end with a ``SIGKILL`` of the whole group, so a hung
+ ``osascript`` cannot outlive its experiment and press keys into the next one.
+ The experiments are: register/unregister under a real NSApplication loop
+ (plus 200 register/unregister cycles and 50 synthetic presses), register with
+ no NSApplication, unregister from a non-main thread, duplicate registration,
+ registration under secure event input, installing the handler twice, the
+ Appshot both-Option read (with the key actually held, through three
+ injection routes), and two controls that tell a harness bug from a Carbon
+ crash.
+3. Writes ONE JSON document (``--out``) after EVERY experiment (atomically, with
+ ``"complete": false`` until the last one), and prints a short summary. With
+ ``--summary-md`` it also writes the same table as Markdown for
+ ``$GITHUB_STEP_SUMMARY``. A killed parent therefore still leaves a report.
+
+What the ctypes code deliberately mirrors from the crash-surface list
+(docs/macos-permissions.md, 4.15), so that the evidence is about the shape a real shim
+would have: ``restype`` is ``c_void_p`` on the event-target getters, ``EventHotKeyID`` is
+passed by value, the callback and the ``EventTypeSpec`` array are module-level singletons, the
+handler is installed on the APPLICATION event target, the callback returns
+``eventNotHandledErr`` on an internal error, and every native call runs on the
+main thread inside a running ``NSApplication`` loop (except where the variant
+exists to test the opposite).
+
+What this can NOT show, and the report says so: runners pre-grant TCC to
+bash/osascript/Terminal; no dialog is shown; no physical keyboard exists; and no
+key-hold semantics (modifier lifted first, auto-repeat) are exercised. A run
+counts as evidence for "Carbon needs no TCC grant" only when the preflights are
+false in the SAME process that received a hot key event
+(:func:`evaluate_evidence`), the registration returned noErr, a Pressed arrived
+while the chord was registered, and the variant ended ``ok``. The synthetic key
+comes from ``osascript``; it is sent only with ``--inject-synthetic-key`` (the
+workflow passes it) because ``osascript`` driving System Events can raise an
+Automation prompt on a developer's own Mac. "No event arrived" is only
+evidence that Carbon did not deliver when an independent control saw the key
+(the system-wide key-down counter moved); without it the verdict is
+``inconclusive`` (a missing Automation/Accessibility grant for ``osascript``
+looks exactly like a silent Carbon). Nothing here is verified on a Mac by its
+author.
+
+NOT covered, and the report says so (:data:`NOT_COVERED`): variant G of the
+crash-surface list (the hop test, ``AppHelper.callAfter`` versus
+``performSelectorOnMainThread:withObject:waitUntilDone:modes:`` under an
+event-tracking run-loop mode; it needs pyobjc and an Objective-C target object,
+which this standard-library script does not build) and the off-main REGISTER
+half of variant C (only the off-main UNREGISTER is measured). Flip criterion 1
+("spike A, D, E, G green") therefore stays OPEN until G exists.
+
+The script never touches the network, needs only the standard library plus
+ctypes, and is import-safe on every OS (no framework is loaded at import).
+It exits 0 even when a variant crashes (a crash is data). It exits non-zero only
+when the harness itself breaks (unwritable output, bad arguments). It needs
+Python 3.11 or newer and says so instead of raising an ImportError.
+
+Usage (macOS, Python 3.11+):
+ python3.11 scripts/ci/macos_carbon_hotkey_spike.py --out spike.json \\
+ --summary-md summary.md --inject-synthetic-key
+"""
+
+from __future__ import annotations
+
+import sys
+
+if sys.version_info < (3, 11): # noqa: UP036 - the repo targets 3.11, an old Mac python does not
+ sys.exit(
+ "macos_carbon_hotkey_spike.py needs Python 3.11 or newer "
+ f"(running {sys.version.split()[0]}): use python3.11 or the CI runner's Python."
+ )
+
+import argparse
+import ctypes
+import ctypes.util
+import faulthandler
+import importlib
+import json
+import os
+import platform
+import signal
+import subprocess
+import sysconfig
+import threading
+import time
+import traceback
+from collections.abc import Callable, Generator, Mapping, Sequence
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, NoReturn
+
+SCHEMA_VERSION = 1
+TOOL_NAME = "macos_carbon_hotkey_spike"
+
+#: The sentence the step summary and the docs must carry next to any number.
+EVIDENCE_DISCLAIMER = (
+ "Runner evidence only: runners pre-grant TCC to bash/osascript/Terminal; no dialog is "
+ "shown, no physical keyboard exists, no key-hold semantics were exercised."
+)
+EVIDENCE_RULE = (
+ "Counts as evidence for 'Carbon needs no TCC grant' only if, in the SAME process that "
+ "received a hot key event, CGPreflightListenEventAccess is false, AXIsProcessTrusted is "
+ "false and IOHIDCheckAccess(listen) is not 'granted', the registration returned noErr, a "
+ "Pressed arrived while the chord was registered and the variant ended ok."
+)
+
+#: What this tool does not measure; copied into the report and the step summary so a
+#: reader never mistakes a green table for the whole flip criterion.
+NOT_COVERED = (
+ "Variant G (hop test: AppHelper.callAfter vs performSelectorOnMainThread:modes: under an "
+ "event-tracking run-loop mode): flip criterion 1 'spike A, D, E, G green' stays open.",
+ "Variant C is only half covered: the off-main UNREGISTER is measured, the off-main "
+ "REGISTER is not.",
+ "Hold semantics (modifier lifted first, auto-repeat), a physical keyboard, a first press "
+ "with clean TCC and the frozen app are not exercised (physical-Mac / built-app items).",
+)
+
+OUTCOME_OK = "ok"
+OUTCOME_ERROR = "error"
+OUTCOME_CRASH = "crash"
+OUTCOME_TIMEOUT = "timeout"
+OUTCOME_SKIPPED = "skipped"
+OUTCOMES = (OUTCOME_OK, OUTCOME_ERROR, OUTCOME_CRASH, OUTCOME_TIMEOUT, OUTCOME_SKIPPED)
+
+RESULT_PREFIX = "SPIKE_RESULT "
+STEP_PREFIX = "STEP "
+TAIL_CHARS = 2000
+
+#: Environment variables copied into the report. A fixed allowlist: nothing else
+#: from the environment is ever recorded.
+CI_ENV_ALLOWLIST = (
+ "GITHUB_ACTIONS",
+ "GITHUB_RUN_ID",
+ "GITHUB_RUN_ATTEMPT",
+ "GITHUB_SHA",
+ "GITHUB_WORKFLOW",
+ "ImageOS",
+ "ImageVersion",
+ "RUNNER_ARCH",
+ "RUNNER_OS",
+)
+
+_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0
+
+# ---------------------------------------------------------------------------
+# Carbon constants and signatures. Values are from the public headers as the
+# author remembers them (Events.h, CarbonEvents.h, MacTypes.h); the child's own
+# results are the only verification. Nothing here loads a framework.
+# ---------------------------------------------------------------------------
+
+
+def fourcc(text: str) -> int:
+ """A four-character code ('keyb') as the big-endian UInt32 Carbon uses."""
+ raw = text.encode("ascii")
+ if len(raw) != 4:
+ raise ValueError(f"a four-character code needs exactly 4 characters: {text!r}")
+ return int.from_bytes(raw, "big")
+
+
+CARBON_FRAMEWORK = "Carbon"
+NO_ERR = 0
+EVENT_NOT_HANDLED_ERR = -9874
+EVENT_HOT_KEY_EXISTS_ERR = -9878
+K_EVENT_CLASS_KEYBOARD = fourcc("keyb")
+K_EVENT_HOT_KEY_PRESSED = 5
+K_EVENT_HOT_KEY_RELEASED = 6
+K_EVENT_PARAM_DIRECT_OBJECT = fourcc("----")
+TYPE_EVENT_HOT_KEY_ID = fourcc("hkid")
+HOT_KEY_SIGNATURE = fourcc("JRVS")
+
+CMD_KEY = 0x100
+SHIFT_KEY = 0x200
+OPTION_KEY = 0x800
+CONTROL_KEY = 0x1000
+
+VK_ANSI_J = 0x26
+VK_OPTION = 0x3A # kVK_Option (58)
+VK_RIGHT_OPTION = 0x3D # kVK_RightOption (61)
+
+#: The chord every variant registers: Control+Option+J. Every shipped Jarvis
+#: default carries Ctrl or Cmd, so this is a representative "modifiers + one key".
+TEST_KEY_CODE = VK_ANSI_J
+TEST_MODIFIERS = CONTROL_KEY | OPTION_KEY
+
+NS_APPLICATION_ACTIVATION_POLICY_ACCESSORY = 1
+
+K_CG_EVENT_SOURCE_STATE_COMBINED_SESSION = 0
+K_CG_EVENT_SOURCE_STATE_HID_SYSTEM = 1
+#: The two source states every Appshot read and the key-down control sample.
+OPTION_SOURCE_STATES = (
+ ("combined_session", K_CG_EVENT_SOURCE_STATE_COMBINED_SESSION),
+ ("hid_system", K_CG_EVENT_SOURCE_STATE_HID_SYSTEM),
+)
+K_CG_EVENT_KEY_DOWN = 10
+K_CG_EVENT_FLAG_MASK_ALTERNATE = 0x00080000
+NX_DEVICE_LEFT_ALT_KEY_MASK = 0x20
+NX_DEVICE_RIGHT_ALT_KEY_MASK = 0x40
+
+IOHID_REQUEST_POST_EVENT = 0
+IOHID_REQUEST_LISTEN_EVENT = 1
+IOHID_ACCESS_GRANTED = 0
+IOHID_ACCESS_LABELS = {0: "granted", 1: "denied", 2: "unknown"}
+
+
+class EventHotKeyID(ctypes.Structure):
+ """``EventHotKeyID`` (8 bytes). Carbon takes it BY VALUE."""
+
+ _fields_ = (("signature", ctypes.c_uint32), ("id", ctypes.c_uint32))
+
+
+class EventTypeSpec(ctypes.Structure):
+ """``EventTypeSpec`` (8 bytes)."""
+
+ _fields_ = (("eventClass", ctypes.c_uint32), ("eventKind", ctypes.c_uint32))
+
+
+#: ``OSStatus (*)(EventHandlerCallRef, EventRef, void *userData)``.
+HANDLER_PROTO = ctypes.CFUNCTYPE(ctypes.c_int32, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p)
+#: ``void (*CFRunLoopTimerCallBack)(CFRunLoopTimerRef, void *info)``.
+TIMER_PROTO = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p)
+
+#: name -> (restype, argtypes). The pinned crash-surface items live here:
+#: ``c_void_p`` restype on the target getters (a default ``c_int`` would truncate
+#: a 64-bit pointer), ``EventHotKeyID`` by value, strict argtypes everywhere.
+CARBON_SIGNATURES: dict[str, tuple[Any, tuple[Any, ...]]] = {
+ "GetApplicationEventTarget": (ctypes.c_void_p, ()),
+ "GetEventDispatcherTarget": (ctypes.c_void_p, ()),
+ "InstallEventHandler": (
+ ctypes.c_int32,
+ (
+ ctypes.c_void_p,
+ HANDLER_PROTO,
+ ctypes.c_uint32,
+ ctypes.POINTER(EventTypeSpec),
+ ctypes.c_void_p,
+ ctypes.POINTER(ctypes.c_void_p),
+ ),
+ ),
+ "RemoveEventHandler": (ctypes.c_int32, (ctypes.c_void_p,)),
+ "RegisterEventHotKey": (
+ ctypes.c_int32,
+ (
+ ctypes.c_uint32,
+ ctypes.c_uint32,
+ EventHotKeyID,
+ ctypes.c_void_p,
+ ctypes.c_uint32,
+ ctypes.POINTER(ctypes.c_void_p),
+ ),
+ ),
+ "UnregisterEventHotKey": (ctypes.c_int32, (ctypes.c_void_p,)),
+ "GetEventClass": (ctypes.c_uint32, (ctypes.c_void_p,)),
+ "GetEventKind": (ctypes.c_uint32, (ctypes.c_void_p,)),
+ "GetEventParameter": (
+ ctypes.c_int32,
+ (
+ ctypes.c_void_p,
+ ctypes.c_uint32,
+ ctypes.c_uint32,
+ ctypes.POINTER(ctypes.c_uint32),
+ ctypes.c_uint32,
+ ctypes.POINTER(ctypes.c_uint32),
+ ctypes.c_void_p,
+ ),
+ ),
+ "IsSecureEventInputEnabled": (ctypes.c_ubyte, ()),
+ # Believed to return OSStatus; the raw value is recorded, the read-back via
+ # IsSecureEventInputEnabled is the actual evidence.
+ "EnableSecureEventInput": (ctypes.c_int32, ()),
+ "DisableSecureEventInput": (ctypes.c_int32, ()),
+}
+
+
+#: Symbols whose exported name might differ from the header name. The author believes
+#: ``InstallEventHandler`` is a plain exported function but could not rule out that the
+#: SDK reaches it through an underscore-prefixed variant. The alias is tried ONLY when the
+#: plain name is missing, and the report records which name bound.
+SYMBOL_ALIASES: dict[str, tuple[str, ...]] = {"InstallEventHandler": ("_InstallEventHandler",)}
+
+
+def bind_carbon(lib: Any) -> tuple[list[str], list[str], dict[str, str]]:
+ """Set ``restype``/``argtypes`` on every function of :data:`CARBON_SIGNATURES`.
+
+ Returns ``(bound, missing, aliases)``. A symbol the library does not export is
+ reported, never raised, so one missing function is a row in the report. When a
+ symbol only exists under an alias of :data:`SYMBOL_ALIASES`, the alias function is
+ also set on ``lib`` under the canonical name (so callers keep one spelling) and
+ ``aliases`` maps canonical name to the name that bound.
+ """
+ bound: list[str] = []
+ missing: list[str] = []
+ aliases: dict[str, str] = {}
+ for name, (restype, argtypes) in CARBON_SIGNATURES.items():
+ function = None
+ for candidate in (name, *SYMBOL_ALIASES.get(name, ())):
+ try:
+ function = getattr(lib, candidate)
+ except AttributeError:
+ continue # not exported under this spelling: the next candidate is tried
+ if candidate != name:
+ aliases[name] = candidate
+ setattr(lib, name, function)
+ break
+ if function is None:
+ missing.append(name)
+ continue
+ function.restype = restype
+ function.argtypes = list(argtypes)
+ bound.append(name)
+ return bound, missing, aliases
+
+
+# ---------------------------------------------------------------------------
+# The experiment catalogue: names and ORDER are part of the report contract.
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Experiment:
+ name: str
+ title: str
+ #: "control" tells a harness bug from a Carbon crash; "variant" is a risky
+ #: Carbon call pattern; "probe" is a plain API read.
+ kind: str
+ question: str
+ timeout_s: float
+ requires_macos: bool = True
+ #: Only controls have an expectation; variants are measurements.
+ expected_outcome: str | None = None
+
+
+EXPERIMENTS: tuple[Experiment, ...] = (
+ Experiment(
+ name="control_signal_capture",
+ title="Harness control: the child kills itself with SIGABRT",
+ kind="control",
+ question="Does the harness record a signal exit as outcome=crash with the signal name?",
+ timeout_s=30.0,
+ requires_macos=False,
+ expected_outcome=OUTCOME_CRASH,
+ ),
+ Experiment(
+ name="tcc_context",
+ title="Record the TCC context (non-prompting preflight reads) in a child process",
+ kind="probe",
+ question=(
+ "What do CGPreflightListenEventAccess, AXIsProcessTrusted and IOHIDCheckAccess "
+ "report, and is there a window-server session? (Runs before every Carbon variant.)"
+ ),
+ timeout_s=60.0,
+ requires_macos=False,
+ ),
+ Experiment(
+ name="carbon_symbols",
+ title="Harness control: load Carbon by explicit path and bind its functions",
+ kind="control",
+ question="Does the explicit-path load resolve every symbol the shim needs?",
+ timeout_s=30.0,
+ expected_outcome=OUTCOME_OK,
+ ),
+ Experiment(
+ name="nsapp_register_unregister",
+ title="Register + unregister on the main thread inside a real NSApplication loop",
+ kind="variant",
+ question=(
+ "Does the registration return noErr and are Pressed/Released delivered "
+ "(with the preflights false), and does unregister free the slot?"
+ ),
+ timeout_s=120.0,
+ ),
+ Experiment(
+ name="register_unregister_cycles",
+ title="200 register/unregister cycles and 50 synthetic presses in a real NSApplication",
+ kind="variant",
+ question=(
+ "Does a re-registration stay noErr across 200 cycles (no leaked slot), and does "
+ "each of 50 presses arrive?"
+ ),
+ timeout_s=300.0,
+ ),
+ Experiment(
+ name="no_nsapp_register",
+ title="Register with NO NSApplication running",
+ kind="variant",
+ question="Does it fail cleanly with an OSStatus or crash (browser-degrade, --headless)?",
+ timeout_s=60.0,
+ ),
+ Experiment(
+ name="unregister_off_main_thread",
+ title="UnregisterEventHotKey from a non-main thread",
+ kind="variant",
+ question="Silent leak (-9878 on re-register), an error, a hang or a crash?",
+ timeout_s=120.0,
+ ),
+ Experiment(
+ name="duplicate_register",
+ title="Register the same key and modifiers twice",
+ kind="variant",
+ question="Which OSStatus does the second registration return; does a press fire twice?",
+ timeout_s=120.0,
+ ),
+ Experiment(
+ name="register_under_secure_input",
+ title="Register while secure event input is enabled in the process",
+ kind="variant",
+ question="Does registration work, and is the chord still delivered under secure input?",
+ timeout_s=120.0,
+ ),
+ Experiment(
+ name="install_handler_twice",
+ title="Install the application event handler twice",
+ kind="variant",
+ question="Do both installs succeed, and is each press delivered once or twice?",
+ timeout_s=120.0,
+ ),
+ Experiment(
+ name="appshot_option_state_read",
+ title="Appshot both-Option read: CGEventSourceKeyState vs CGEventSourceFlagsState",
+ kind="probe",
+ question=(
+ "With an Option key actually held (three injection routes, left and right), what do "
+ "KeyState (kVK_Option, kVK_RightOption) and the alternate-flag and device bits of "
+ "FlagsState return, per source state, with the preflights recorded in this process?"
+ ),
+ timeout_s=150.0,
+ ),
+)
+
+#: Always run, and first among the Carbon-adjacent experiments: every report needs its TCC
+#: context, and ``--only`` must not be able to drop it.
+ALWAYS_RUN = ("tcc_context",)
+
+
+def experiment_names() -> tuple[str, ...]:
+ return tuple(experiment.name for experiment in EXPERIMENTS)
+
+
+def experiment_by_name(name: str) -> Experiment:
+ for experiment in EXPERIMENTS:
+ if experiment.name == name:
+ return experiment
+ raise KeyError(name)
+
+
+def select_experiments(only: str) -> tuple[Experiment, ...]:
+ """The catalogue, or the comma-separated subset ``only`` (catalogue order)."""
+ wanted = [part.strip() for part in only.split(",") if part.strip()]
+ if not wanted:
+ return EXPERIMENTS
+ unknown = [name for name in wanted if name not in experiment_names()]
+ if unknown:
+ raise ValueError(f"unknown experiment(s): {', '.join(unknown)}")
+ return tuple(experiment for experiment in EXPERIMENTS if experiment.name in wanted)
+
+
+def plan_experiments(only: str) -> tuple[Experiment, ...]:
+ """What a run executes: the ``--only`` selection plus :data:`ALWAYS_RUN`, catalogue order."""
+ selected = {experiment.name for experiment in select_experiments(only)}
+ selected.update(ALWAYS_RUN)
+ return tuple(experiment for experiment in EXPERIMENTS if experiment.name in selected)
+
+
+# ---------------------------------------------------------------------------
+# Pure helpers (unit-tested on Linux).
+# ---------------------------------------------------------------------------
+
+
+def signal_name(returncode: int | None) -> str | None:
+ """The signal that ended a child, from a NEGATIVE return code; else ``None``."""
+ if returncode is None or returncode >= 0:
+ return None
+ try:
+ return signal.Signals(-returncode).name
+ except ValueError:
+ return f"SIG{-returncode}"
+
+
+def classify_outcome(*, returncode: int | None, timed_out: bool, child_ok: bool | None) -> str:
+ """Map a finished child to ``ok|error|crash|timeout``.
+
+ * ``timeout``: the hard timeout fired (the child was killed).
+ * ``crash``: the child died from a signal (negative return code).
+ * ``ok``: it exited 0 AND reported ``ok`` (every step it expected to succeed did).
+ * ``error``: anything else (could not start, non-zero exit, exit 0 with a
+ failed expectation or without a result line).
+ """
+ if timed_out:
+ return OUTCOME_TIMEOUT
+ if returncode is None:
+ return OUTCOME_ERROR
+ if returncode < 0:
+ return OUTCOME_CRASH
+ if returncode != 0:
+ return OUTCOME_ERROR
+ return OUTCOME_OK if child_ok is True else OUTCOME_ERROR
+
+
+def tail_text(data: bytes | str | None, limit: int = TAIL_CHARS) -> str:
+ """The last ``limit`` characters of captured output, decoded and NUL-free."""
+ if data is None:
+ return ""
+ text = data.decode("utf-8", errors="replace") if isinstance(data, bytes) else data
+ text = text.replace("\x00", "")
+ return text[-limit:]
+
+
+def summarize_argv(argv: Sequence[str]) -> list[str]:
+ """``argv`` without machine-specific directories (interpreter and script basenames)."""
+ if not argv:
+ return []
+ summary = [Path(argv[0]).name]
+ for index, part in enumerate(argv[1:], start=1):
+ summary.append(Path(part).name if index == 1 and part.endswith(".py") else part)
+ return summary
+
+
+def parse_child_result(stdout: str) -> dict[str, Any] | None:
+ """The child's final ``SPIKE_RESULT {json}`` line, or ``None`` when there is none.
+
+ An unparseable line yields ``{"_parse_error": ...}`` (no ``ok`` key), so the
+ outcome rule reports an error and the report shows why.
+ """
+ for line in reversed(stdout.splitlines()):
+ if not line.startswith(RESULT_PREFIX):
+ continue
+ try:
+ parsed = json.loads(line[len(RESULT_PREFIX) :])
+ except ValueError as exc:
+ return {"_parse_error": f"{type(exc).__name__}: {exc}"}
+ return parsed if isinstance(parsed, dict) else {"_parse_error": "result is not an object"}
+ return None
+
+
+def last_breadcrumb(stdout: str) -> str | None:
+ """The last ``STEP ...`` line the child printed: where a crash happened."""
+ for line in reversed(stdout.splitlines()):
+ if line.startswith(STEP_PREFIX):
+ return line[len(STEP_PREFIX) :].strip()
+ return None
+
+
+def child_environment(base: Mapping[str, str]) -> dict[str, str]:
+ """The environment of a child: unbuffered, UTF-8, faulthandler on."""
+ env = dict(base)
+ env.update(
+ {
+ "PYTHONUNBUFFERED": "1",
+ "PYTHONFAULTHANDLER": "1",
+ "PYTHONUTF8": "1",
+ "PYTHONIOENCODING": "utf-8",
+ }
+ )
+ return env
+
+
+def md_cell(value: object, limit: int | None = 160) -> str:
+ """One Markdown cell: no pipes, no newlines; bounded length unless ``limit`` is ``None``.
+
+ Table cells are bounded. Sentences that DEFINE the evidence (the rule, the notes) are
+ rendered with ``limit=None``: a truncated rule is worse than a long line.
+ """
+ text = str(value).replace("|", "/").replace("\r", " ").replace("\n", " ").strip()
+ if limit is None or len(text) <= limit:
+ return text
+ return text[: limit - 3] + "..."
+
+
+def probe(name: str, sources: Sequence[tuple[str, Callable[[], Any]]]) -> dict[str, Any]:
+ """Run the first source that works; record every failure, never raise.
+
+ ``sources`` is ordered by preference (pyobjc if importable, then ctypes).
+ """
+ attempts: list[dict[str, str]] = []
+ for label, function in sources:
+ try:
+ value = function()
+ except Exception as exc: # recorded in `attempts`; the next source is tried
+ attempts.append({"source": label, "error": f"{type(exc).__name__}: {exc}"})
+ continue
+ return {"name": name, "value": value, "source": label, "error": None, "attempts": attempts}
+ error = "; ".join(f"{a['source']}: {a['error']}" for a in attempts) or "no source available"
+ return {"name": name, "value": None, "source": None, "error": error, "attempts": attempts}
+
+
+def _probe_value(tcc: Mapping[str, Any], key: str) -> Any:
+ probes = tcc.get("probes")
+ entry = probes.get(key) if isinstance(probes, Mapping) else None
+ return entry.get("value") if isinstance(entry, Mapping) else None
+
+
+def preflight_flags(tcc: Mapping[str, Any]) -> dict[str, bool | None]:
+ """Whether each of the three gates reports 'granted' (``None`` = unreadable)."""
+ listen = _probe_value(tcc, "cg_preflight_listen_event")
+ trusted = _probe_value(tcc, "ax_is_process_trusted")
+ iohid = _probe_value(tcc, "iohid_check_access_listen")
+ return {
+ "listen_event_granted": listen if isinstance(listen, bool) else None,
+ "accessibility_trusted": trusted if isinstance(trusted, bool) else None,
+ "iohid_listen_granted": (iohid == IOHID_ACCESS_GRANTED) if isinstance(iohid, int) else None,
+ }
+
+
+def step_value(observations: Mapping[str, Any], name: str) -> Any:
+ """The value of the child's recorded step ``name``; ``None`` when it never ran."""
+ steps = observations.get("steps")
+ if not isinstance(steps, Sequence) or isinstance(steps, str | bytes):
+ return None
+ for step in steps:
+ if isinstance(step, Mapping) and step.get("step") == name:
+ return step.get("value")
+ return None
+
+
+def _is_count(value: Any) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool)
+
+
+def evaluate_evidence(
+ tcc: Mapping[str, Any], experiments: Sequence[Mapping[str, Any]]
+) -> dict[str, Any]:
+ """Decide whether this run can count as evidence (see :data:`EVIDENCE_RULE`).
+
+ The TCC values of the SAME child process that received the event are
+ preferred over the ``tcc_context`` process's; a granted gate anywhere voids the
+ run. Delivery is judged on the ``pressed_while_registered`` step only (a Pressed
+ that arrives after the unregister, or without a successful registration, proves
+ nothing about a registered chord), and the variant must have ended ``ok``.
+ """
+ nsapp = next((e for e in experiments if e.get("name") == "nsapp_register_unregister"), None)
+ observations = (nsapp or {}).get("observations")
+ observations = observations if isinstance(observations, Mapping) else {}
+ child_tcc = observations.get("tcc")
+ use_child = isinstance(child_tcc, Mapping) and bool(child_tcc.get("probes"))
+ flags = preflight_flags(child_tcc if use_child else tcc)
+ values = list(flags.values())
+ if any(value is True for value in values):
+ all_false: bool | None = False
+ elif all(value is False for value in values):
+ all_false = True
+ else:
+ all_false = None
+ register_status = step_value(observations, "register")
+ pressed_registered = step_value(observations, "pressed_while_registered")
+ injection_seen = step_value(observations, "injection_seen_while_registered")
+ variant_ok = (nsapp or {}).get("outcome") == OUTCOME_OK
+ delivered: bool | None = None
+ if (
+ nsapp is not None
+ and observations.get("synthetic_key_requested") is True
+ and _is_count(register_status)
+ and _is_count(pressed_registered)
+ ):
+ delivered = register_status == NO_ERR and pressed_registered >= 1
+ if delivered is True:
+ conclusion = "delivered"
+ elif delivered is False and register_status != NO_ERR:
+ conclusion = "registration_failed"
+ elif delivered is False and injection_seen is True:
+ conclusion = "not_delivered"
+ elif delivered is False:
+ conclusion = "inconclusive"
+ else:
+ conclusion = "unknown"
+ notes: list[str] = []
+ if all_false is False:
+ notes.append("a preflight reports granted in this process: discard the run as evidence")
+ elif all_false is None:
+ notes.append("a preflight could not be read: the run cannot be claimed as evidence")
+ if delivered is None:
+ notes.append("no synthetic key was sent (or the variant did not run): delivery unknown")
+ elif delivered is False and _is_count(register_status) and register_status != NO_ERR:
+ notes.append(
+ f"the registration returned OSStatus {register_status}, not noErr: "
+ "no Pressed can count as delivered by a registered chord"
+ )
+ elif delivered is False and conclusion == "not_delivered":
+ notes.append(
+ "no Pressed arrived while registered although the system-wide key-down counter "
+ "moved: the key reached the session but Carbon did not deliver it"
+ )
+ elif delivered is False:
+ notes.append(
+ "no Pressed arrived while registered and the injection was NOT confirmed "
+ "independently of Carbon (key-down counter / osascript exit status): "
+ "inconclusive, not evidence that Carbon failed; see the osascript step"
+ )
+ if delivered is True and not variant_ok:
+ notes.append(
+ "a Pressed arrived but the variant did not end ok (an unexpected status, e.g. the "
+ "unregister did not take effect): not clean evidence"
+ )
+ return {
+ "rule": EVIDENCE_RULE,
+ "tcc_source": "child" if use_child else "tcc_context",
+ "preflights": flags,
+ "preflights_all_false": all_false,
+ "carbon_event_delivered": delivered,
+ "injection_seen_independently": injection_seen
+ if isinstance(injection_seen, bool)
+ else None,
+ "delivery_conclusion": conclusion,
+ "variant_ok": variant_ok,
+ "usable_as_evidence": all_false is True and delivered is True and variant_ok,
+ "notes": notes,
+ }
+
+
+def injection_seen(
+ before: Mapping[str, int] | None, after: Mapping[str, int] | None
+) -> bool | None:
+ """Did the system-wide key-down counter move? ``None`` when it could not be read.
+
+ The control for 'no Pressed arrived': it is independent of Carbon, so a counter that
+ moved while no Pressed arrived points at Carbon, and a counter that did not move
+ points at the injection (a missing Automation or Accessibility grant for ``osascript``).
+ """
+ if before is None or after is None:
+ return None
+ return any(after.get(label, 0) > before.get(label, 0) for label in after)
+
+
+def compare_option_reads(reads: Mapping[str, Mapping[str, Any]]) -> dict[str, Any]:
+ """Compare ``CGEventSourceKeyState`` with the alternate bits of ``FlagsState``.
+
+ ``reads`` maps a source-state label to ``{"key_left", "key_right", "flags_raw"}``.
+ For the BASELINE read no key is held, so every value is expected to be false and
+ ``as_expected_no_key_held`` is the check; for a HELD phase the same fields say what
+ each API reported (see :func:`option_hold_verdict`). A baseline read alone cannot
+ show whether KeyState needs Input Monitoring.
+ """
+ per_state: dict[str, dict[str, Any]] = {}
+ any_pressed = False
+ for label, read in reads.items():
+ flags = int(read.get("flags_raw", 0))
+ key_left = bool(read.get("key_left"))
+ key_right = bool(read.get("key_right"))
+ alternate = bool(flags & K_CG_EVENT_FLAG_MASK_ALTERNATE)
+ left_bit = bool(flags & NX_DEVICE_LEFT_ALT_KEY_MASK)
+ right_bit = bool(flags & NX_DEVICE_RIGHT_ALT_KEY_MASK)
+ per_state[label] = {
+ "keystate_left": key_left,
+ "keystate_right": key_right,
+ "flags_raw_hex": hex(flags),
+ "flags_alternate": alternate,
+ "flags_left_device_bit": left_bit,
+ "flags_right_device_bit": right_bit,
+ "agree": (key_left or key_right) == alternate,
+ }
+ any_pressed = any_pressed or key_left or key_right or alternate or left_bit or right_bit
+ return {
+ "states": per_state,
+ "any_pressed_reported": any_pressed,
+ "as_expected_no_key_held": not any_pressed,
+ "limitation": (
+ "a read with no key held cannot show whether KeyState needs Input "
+ "Monitoring; it shows only that the calls return and what they return"
+ ),
+ }
+
+
+def merge_option_samples(
+ samples: Sequence[Mapping[str, Mapping[str, Any]]],
+) -> dict[str, dict[str, Any]]:
+ """The PEAK of a sampling window, per source state: any key read true, flag words OR-ed.
+
+ The held key is down for only part of the window (``osascript`` needs time to start), so
+ a single read would depend on timing; the peak does not.
+ """
+ merged: dict[str, dict[str, Any]] = {}
+ for sample in samples:
+ for label, read in sample.items():
+ peak = merged.setdefault(label, {"key_left": False, "key_right": False, "flags_raw": 0})
+ peak["key_left"] = peak["key_left"] or bool(read.get("key_left"))
+ peak["key_right"] = peak["key_right"] or bool(read.get("key_right"))
+ peak["flags_raw"] |= int(read.get("flags_raw", 0))
+ return merged
+
+
+def option_hold_verdict(
+ baseline: Mapping[str, Mapping[str, Any]],
+ phases: Mapping[str, Mapping[str, Any]],
+) -> dict[str, Any]:
+ """What each API reported while an Option key was held, and what that does NOT show.
+
+ ``phases`` maps a phase name to ``{"reads": <peak per source state>, "injection_exit":
+ <osascript exit status or None>}``. The verdict states observations ("KeyState saw the key
+ where FlagsState did not"), never a policy: whether either read needs Input Monitoring is
+ decided from these values together with the preflights recorded in the same process, by a
+ maintainer, and a phase where NO read saw the key is ``inconclusive`` (the injection may
+ simply not have set modifier state).
+ """
+ per_phase: dict[str, dict[str, Any]] = {}
+ notes: list[str] = []
+ injected = 0
+ any_seen = False
+ for name, phase in phases.items():
+ compared = compare_option_reads(phase.get("reads") or {})
+ exit_status = phase.get("injection_exit")
+ states: dict[str, dict[str, Any]] = {}
+ phase_seen = False
+ for label, state in compared["states"].items():
+ keystate = bool(state["keystate_left"] or state["keystate_right"])
+ flags = bool(
+ state["flags_alternate"]
+ or state["flags_left_device_bit"]
+ or state["flags_right_device_bit"]
+ )
+ sides = [
+ side
+ for side, seen in (
+ ("left", state["keystate_left"] or state["flags_left_device_bit"]),
+ ("right", state["keystate_right"] or state["flags_right_device_bit"]),
+ )
+ if seen
+ ]
+ states[label] = {
+ "keystate_saw_option": keystate,
+ "flagsstate_saw_option": flags,
+ "sides_seen": sides,
+ "flags_raw_hex": state["flags_raw_hex"],
+ }
+ phase_seen = phase_seen or keystate or flags
+ if keystate and not flags:
+ notes.append(f"{name}/{label}: KeyState saw the key, FlagsState did not")
+ elif flags and not keystate:
+ notes.append(f"{name}/{label}: FlagsState saw the key, KeyState did not")
+ if exit_status == 0:
+ injected += 1
+ any_seen = any_seen or phase_seen
+ per_phase[name] = {
+ "injection_exit": exit_status,
+ "samples": phase.get("samples"),
+ "any_api_saw_option": phase_seen,
+ "states": states,
+ }
+ if not phases:
+ notes.append("no injection was requested: only the no-key baseline was read")
+ elif injected == 0:
+ notes.append("no injection route exited 0: nothing can be concluded about the held key")
+ elif not any_seen:
+ notes.append(
+ "inconclusive: an injection exited 0 but no read saw an Option key (the injected "
+ "key may not set modifier state, or every read needs a grant)"
+ )
+ return {
+ "baseline": compare_option_reads(baseline),
+ "phases": per_phase,
+ "injected_routes_exit_0": injected,
+ "any_api_saw_option": any_seen,
+ "notes": notes,
+ "limitation": (
+ "observations only: whether KeyState or FlagsState needs Input Monitoring is not "
+ "decided here; the preflights of this same process are in the child's tcc block"
+ ),
+ }
+
+
+def count_events(events: Sequence[Mapping[str, Any]]) -> dict[str, int]:
+ """Count delivered hot key events by kind, and how many came off the main thread."""
+ counts = {"pressed": 0, "released": 0, "other": 0, "off_main_thread": 0}
+ for event in events:
+ kind = event.get("kind")
+ counts[kind if kind in ("pressed", "released") else "other"] += 1
+ if event.get("on_main_thread") is False:
+ counts["off_main_thread"] += 1
+ return counts
+
+
+def child_ok(steps: Sequence[Mapping[str, Any]], errors: Sequence[str]) -> bool:
+ """A child is ok when no recorded error exists and every step with an expectation met it."""
+ return not errors and all(step.get("ok", True) is not False for step in steps)
+
+
+def build_headline(steps: Sequence[Mapping[str, Any]], counts: Mapping[str, int]) -> str:
+ """One line of ``step=value`` pairs plus the event counts, for the summary table."""
+ parts = []
+ for step in steps:
+ value = step.get("value")
+ if isinstance(value, bool | int) or (isinstance(value, str) and len(value) <= 24):
+ parts.append(f"{step.get('step')}={value}")
+ if counts.get("pressed") or counts.get("released"):
+ parts.append(f"pressed={counts.get('pressed', 0)} released={counts.get('released', 0)}")
+ return " ".join(parts)
+
+
+def assemble_child_result(
+ name: str,
+ extra: Mapping[str, Any],
+ *,
+ steps: Sequence[Mapping[str, Any]],
+ events: Sequence[Mapping[str, Any]],
+ errors: Sequence[str],
+ tcc: Mapping[str, Any] | None,
+ inject: bool,
+) -> dict[str, Any]:
+ """The JSON object a child prints on its last line."""
+ counts = count_events(events)
+ result: dict[str, Any] = dict(extra)
+ forced = extra.get("ok")
+ result.update(
+ {
+ "name": name,
+ "ok": child_ok(steps, errors) and forced is not False,
+ "synthetic_key_requested": inject,
+ "tcc": dict(tcc) if tcc is not None else None,
+ "steps": [dict(step) for step in steps],
+ "events": [dict(event) for event in events],
+ "event_counts": counts,
+ "errors": list(errors),
+ }
+ )
+ result["headline"] = build_headline(steps, counts)
+ return result
+
+
+def tcc_from_experiments(experiments: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
+ """The TCC context the ``tcc_context`` CHILD reported (the parent loads no framework).
+
+ A child that crashed, hung or never ran yields an unsupported block that says why, so a
+ probe that kills its process is a row in the report and not a lost job.
+ """
+ row = next((e for e in experiments if e.get("name") == "tcc_context"), None)
+ observations = (row or {}).get("observations")
+ tcc = observations.get("tcc") if isinstance(observations, Mapping) else None
+ if isinstance(tcc, Mapping) and "supported" in tcc:
+ return dict(tcc)
+ if row is None:
+ reason = "the tcc_context experiment did not run"
+ else:
+ reason = (
+ f"the tcc_context child ended with outcome={row.get('outcome')} "
+ f"(signal {row.get('signal')}, last step {row.get('last_step')})"
+ )
+ return {"supported": False, "reason": reason, "probes": {}, "window_server": None}
+
+
+def build_report(
+ *,
+ runner: Mapping[str, Any],
+ tcc: Mapping[str, Any],
+ experiments: Sequence[Mapping[str, Any]],
+ started_at: str,
+ finished_at: str,
+ options: Mapping[str, Any],
+ complete: bool = True,
+) -> dict[str, Any]:
+ """The one JSON document this tool emits (``complete`` is false for a partial write)."""
+ return {
+ "schema_version": SCHEMA_VERSION,
+ "tool": TOOL_NAME,
+ "disclaimer": EVIDENCE_DISCLAIMER,
+ "complete": complete,
+ "started_at": started_at,
+ "finished_at": finished_at,
+ "options": dict(options),
+ "runner": dict(runner),
+ "tcc": dict(tcc),
+ "experiments": [dict(experiment) for experiment in experiments],
+ "evidence": evaluate_evidence(tcc, experiments),
+ "not_covered": list(NOT_COVERED),
+ }
+
+
+def _runner_line(report: Mapping[str, Any]) -> str:
+ runner = report.get("runner", {})
+ if runner.get("mac_ver"):
+ build = f" ({runner['macos_build']})" if runner.get("macos_build") else ""
+ system = f"macOS {runner['mac_ver']}{build}"
+ else:
+ system = f"{runner.get('system', '?')} {runner.get('kernel_release', '')}".strip()
+ return f"{system} {runner.get('machine', '?')}, Python {runner.get('python_version', '?')}"
+
+
+def _tcc_pairs(report: Mapping[str, Any]) -> list[tuple[str, str]]:
+ tcc = report.get("tcc", {})
+ if not tcc.get("supported", False):
+ return [("tcc", str(tcc.get("reason", "not collected")))]
+ pairs: list[tuple[str, str]] = []
+ for key, entry in tcc.get("probes", {}).items():
+ value = entry.get("value")
+ shown = "unreadable" if value is None else str(value)
+ if entry.get("label"):
+ shown = f"{shown} ({entry['label']})"
+ pairs.append((key, shown))
+ server = tcc.get("window_server") or {}
+ pairs.append(("window_server_session", str(server.get("cg_session_dictionary_present"))))
+ pairs.append(("launchctl_managername", str(server.get("launchctl_managername"))))
+ return pairs
+
+
+def _experiment_row(experiment: Mapping[str, Any]) -> list[str]:
+ observations = experiment.get("observations")
+ headline = observations.get("headline", "") if isinstance(observations, Mapping) else ""
+ if experiment.get("skip_reason"):
+ headline = str(experiment["skip_reason"])
+ elif not headline and experiment.get("last_step"):
+ headline = f"last step: {experiment['last_step']}"
+ marker = ""
+ if experiment.get("as_expected") is True:
+ marker = " (control as expected)"
+ elif experiment.get("as_expected") is False:
+ marker = " (CONTROL NOT AS EXPECTED)"
+ if experiment.get("group_killed") and experiment.get("outcome") != OUTCOME_TIMEOUT:
+ marker += " (leftover child processes killed)"
+ returncode = experiment.get("returncode")
+ return [
+ str(experiment.get("name")),
+ f"{experiment.get('outcome')}{marker}",
+ "-" if returncode is None else str(returncode),
+ str(experiment.get("signal") or "-"),
+ f"{experiment.get('duration_s', 0):.1f}",
+ str(headline),
+ ]
+
+
+def render_summary_text(report: Mapping[str, Any]) -> str:
+ """The short human summary printed to the log."""
+ rows = [_experiment_row(e) for e in report.get("experiments", [])]
+ header = ["experiment", "outcome", "exit", "signal", "secs", "observations"]
+ widths = [max([len(header[i]), *(len(row[i]) for row in rows)]) for i in range(5)]
+ lines = [
+ f"macOS Carbon hotkey spike (schema {report.get('schema_version')})",
+ f"runner: {_runner_line(report)}",
+ "tcc: " + " ".join(f"{key}={value}" for key, value in _tcc_pairs(report)),
+ "",
+ " ".join(header[i].ljust(widths[i]) for i in range(5)) + " " + header[5],
+ ]
+ for row in rows:
+ lines.append(" ".join(row[i].ljust(widths[i]) for i in range(5)) + " " + row[5])
+ evidence = report.get("evidence", {})
+ lines += [
+ "",
+ f"evidence: preflights_all_false={evidence.get('preflights_all_false')} "
+ f"event_delivered={evidence.get('carbon_event_delivered')} "
+ f"conclusion={evidence.get('delivery_conclusion')} "
+ f"usable={evidence.get('usable_as_evidence')}",
+ ]
+ lines += [f" note: {note}" for note in evidence.get("notes", [])]
+ if report.get("complete") is False:
+ lines += ["", "PARTIAL REPORT: the run did not finish; later experiments are missing."]
+ lines += ["", "not covered:"]
+ lines += [f" - {item}" for item in report.get("not_covered", [])]
+ lines += ["", EVIDENCE_DISCLAIMER]
+ return "\n".join(lines)
+
+
+def render_summary_markdown(report: Mapping[str, Any]) -> str:
+ """The Markdown for ``$GITHUB_STEP_SUMMARY``: TCC context, experiment table, verdict."""
+ evidence = report.get("evidence", {})
+ lines = [
+ "### macOS Carbon hotkey spike",
+ "",
+ EVIDENCE_DISCLAIMER,
+ "",
+ f"Runner: {md_cell(_runner_line(report))}",
+ "",
+ "| TCC context (recorded first) | Value |",
+ "| --- | --- |",
+ ]
+ lines += [f"| {md_cell(key)} | {md_cell(value)} |" for key, value in _tcc_pairs(report)]
+ lines += [
+ "",
+ "| Experiment | Outcome | Exit | Signal | Secs | Observations |",
+ "| --- | --- | --- | --- | --- | --- |",
+ ]
+ for experiment in report.get("experiments", []):
+ *cells, observations = _experiment_row(experiment)
+ shown = [md_cell(cell) for cell in cells] + [md_cell(observations, limit=300)]
+ lines.append("| " + " | ".join(shown) + " |")
+ lines += [
+ "",
+ f"Evidence gate: preflights all false = `{evidence.get('preflights_all_false')}`, "
+ f"Carbon event delivered = `{evidence.get('carbon_event_delivered')}` "
+ f"(`{evidence.get('delivery_conclusion')}`), "
+ f"usable as evidence = `{evidence.get('usable_as_evidence')}`.",
+ "",
+ # The rule DEFINES what counts as evidence: never truncated.
+ md_cell(evidence.get("rule", EVIDENCE_RULE), limit=None),
+ ]
+ lines += [f"- {md_cell(note, limit=None)}" for note in evidence.get("notes", [])]
+ if report.get("complete") is False:
+ lines += ["", "**Partial report: the run did not finish; later experiments are missing.**"]
+ lines += ["", "Not covered by this run:"]
+ lines += [f"- {md_cell(item, limit=None)}" for item in report.get("not_covered", [])]
+ return "\n".join(lines) + "\n"
+
+
+# ---------------------------------------------------------------------------
+# Framework loading and the TCC context (every call is wrapped and recorded).
+# ---------------------------------------------------------------------------
+
+
+def framework_path(name: str) -> str:
+ return f"/System/Library/Frameworks/{name}.framework/{name}"
+
+
+def load_framework(name: str) -> tuple[ctypes.CDLL, str]:
+ """Load a system framework by explicit path, falling back to ``find_library``.
+
+ Returns the library and which route worked (recorded in the report: the
+ frozen app must load Carbon by explicit path).
+ """
+ explicit = framework_path(name)
+ try:
+ return ctypes.CDLL(explicit), f"explicit:{explicit}"
+ except OSError as explicit_error:
+ found = ctypes.util.find_library(name)
+ if not found:
+ raise OSError(
+ f"{name}: explicit path failed ({explicit_error}); no find_library hit"
+ ) from explicit_error
+ return ctypes.CDLL(found), f"find_library:{found}"
+
+
+def _bind_symbol(frameworks: Sequence[str], symbol: str, restype: Any, argtypes: Sequence[Any]):
+ errors: list[str] = []
+ for name in frameworks:
+ try:
+ library, _route = load_framework(name)
+ function = getattr(library, symbol)
+ except (OSError, AttributeError) as exc:
+ errors.append(f"{name}: {exc}")
+ continue
+ function.restype = restype
+ function.argtypes = list(argtypes)
+ return function
+ raise OSError(f"{symbol} not found ({'; '.join(errors)})")
+
+
+def _ctypes_bool(frameworks: Sequence[str], symbol: str) -> Callable[[], bool]:
+ def call() -> bool:
+ return bool(_bind_symbol(frameworks, symbol, ctypes.c_ubyte, ())())
+
+ return call
+
+
+def _pyobjc_bool(module: str, symbol: str) -> Callable[[], bool]:
+ def call() -> bool:
+ return bool(getattr(importlib.import_module(module), symbol)())
+
+ return call
+
+
+def _iohid_check(request_type: int) -> Callable[[], int]:
+ def call() -> int:
+ function = _bind_symbol(("IOKit",), "IOHIDCheckAccess", ctypes.c_uint32, (ctypes.c_uint32,))
+ return int(function(request_type))
+
+ return call
+
+
+def probe_window_server() -> dict[str, Any]:
+ """Whether a window-server (GUI) session exists, by two independent reads."""
+ result: dict[str, Any] = {
+ "cg_session_dictionary_present": None,
+ "launchctl_managername": None,
+ "errors": [],
+ }
+ try:
+ function = _bind_symbol(
+ ("CoreGraphics", "ApplicationServices"),
+ "CGSessionCopyCurrentDictionary",
+ ctypes.c_void_p,
+ (),
+ )
+ result["cg_session_dictionary_present"] = bool(function())
+ except Exception as exc: # recorded under "errors"
+ result["errors"].append(f"CGSessionCopyCurrentDictionary: {type(exc).__name__}: {exc}")
+ try:
+ done = subprocess.run(
+ ["launchctl", "managername"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ creationflags=_NO_WINDOW,
+ )
+ result["launchctl_managername"] = done.stdout.strip() or None
+ except Exception as exc: # recorded under "errors"
+ result["errors"].append(f"launchctl managername: {type(exc).__name__}: {exc}")
+ return result
+
+
+def collect_tcc_context() -> dict[str, Any]:
+ """The TCC state the process sees, read WITHOUT prompting (preflight reads only)."""
+ if sys.platform != "darwin":
+ return {
+ "supported": False,
+ "reason": f"requires macOS (running on {sys.platform})",
+ "probes": {},
+ "window_server": None,
+ }
+ quartz = ("CoreGraphics", "ApplicationServices")
+ probes = {
+ "cg_preflight_listen_event": probe(
+ "CGPreflightListenEventAccess",
+ [
+ ("pyobjc", _pyobjc_bool("Quartz", "CGPreflightListenEventAccess")),
+ ("ctypes", _ctypes_bool(quartz, "CGPreflightListenEventAccess")),
+ ],
+ ),
+ "cg_preflight_post_event": probe(
+ "CGPreflightPostEventAccess",
+ [
+ ("pyobjc", _pyobjc_bool("Quartz", "CGPreflightPostEventAccess")),
+ ("ctypes", _ctypes_bool(quartz, "CGPreflightPostEventAccess")),
+ ],
+ ),
+ "ax_is_process_trusted": probe(
+ "AXIsProcessTrusted",
+ [
+ ("pyobjc", _pyobjc_bool("ApplicationServices", "AXIsProcessTrusted")),
+ (
+ "ctypes",
+ _ctypes_bool(("ApplicationServices", "HIServices"), "AXIsProcessTrusted"),
+ ),
+ ],
+ ),
+ "iohid_check_access_listen": probe(
+ "IOHIDCheckAccess(listen)", [("ctypes", _iohid_check(IOHID_REQUEST_LISTEN_EVENT))]
+ ),
+ "iohid_check_access_post": probe(
+ "IOHIDCheckAccess(post)", [("ctypes", _iohid_check(IOHID_REQUEST_POST_EVENT))]
+ ),
+ }
+ for key in ("iohid_check_access_listen", "iohid_check_access_post"):
+ probes[key]["label"] = IOHID_ACCESS_LABELS.get(probes[key]["value"], "unreadable")
+ return {
+ "supported": True,
+ "reason": None,
+ "probes": probes,
+ "window_server": probe_window_server(),
+ }
+
+
+def _macos_build() -> tuple[str | None, str | None]:
+ if sys.platform != "darwin":
+ return None, None
+ try:
+ done = subprocess.run(
+ ["sw_vers", "-buildVersion"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ creationflags=_NO_WINDOW,
+ )
+ except Exception as exc: # returned as the error string
+ return None, f"{type(exc).__name__}: {exc}"
+ return done.stdout.strip() or None, None
+
+
+def collect_runner_facts(environ: Mapping[str, str] | None = None) -> dict[str, Any]:
+ """Facts about the machine and interpreter; only allowlisted environment variables."""
+ env = os.environ if environ is None else environ
+ build, build_error = _macos_build()
+ return {
+ "platform": sys.platform,
+ "system": platform.system(),
+ "kernel_release": platform.release(),
+ "machine": platform.machine(),
+ "mac_ver": platform.mac_ver()[0] or None,
+ "macos_build": build,
+ "macos_build_error": build_error,
+ "python_version": platform.python_version(),
+ "python_implementation": platform.python_implementation(),
+ "python_framework_build": sysconfig.get_config_var("PYTHONFRAMEWORK") or "",
+ "ci_env": {key: env[key] for key in CI_ENV_ALLOWLIST if key in env},
+ }
+
+
+# ---------------------------------------------------------------------------
+# Parent side: run every experiment in a child process.
+# ---------------------------------------------------------------------------
+
+#: How long to wait for the pipes to close after the group was killed.
+DRAIN_TIMEOUT_S = 5.0
+#: How often a running child is checked for having exited while a descendant holds the pipes.
+EXIT_POLL_S = 0.5
+
+
+@dataclass(frozen=True)
+class ChildRun:
+ """What :func:`run_in_process_group` returns for a child that was not timed out.
+
+ ``group_killed`` is true when the group still had members after the child's own exit and
+ they were killed (leftover ``osascript``, a descendant that held the stdout pipe).
+ """
+
+ returncode: int | None
+ stdout: bytes
+ stderr: bytes
+ group_killed: bool = False
+ cleanup_error: str | None = None
+
+
+class ChildTimeout(subprocess.TimeoutExpired):
+ """``TimeoutExpired`` that also says whether the group kill reached anything."""
+
+ def __init__(
+ self,
+ cmd: Sequence[str],
+ timeout: float,
+ *,
+ output: bytes | None,
+ stderr: bytes | None,
+ group_killed: bool,
+ cleanup_error: str | None,
+ ) -> None:
+ super().__init__(list(cmd), timeout, output=output, stderr=stderr)
+ self.group_killed = group_killed
+ self.cleanup_error = cleanup_error
+
+
+def kill_process_group(
+ group: int | None, *, leader: subprocess.Popen[bytes]
+) -> tuple[bool, str | None]:
+ """SIGKILL every member of ``group``; returns ``(something_was_killed, error)``.
+
+ POSIX only (elsewhere only the leader is killed: this tool needs macOS anyway). An empty
+ group is the normal case after a clean exit, so ``ProcessLookupError`` is not an error;
+ anything else is returned as text and ends up in the report, never swallowed.
+ """
+ if group is None or os.name != "posix":
+ try:
+ leader.kill()
+ except OSError as exc:
+ return False, f"{type(exc).__name__}: {exc}"
+ return True, None
+ try:
+ os.killpg(group, signal.SIGKILL)
+ except ProcessLookupError:
+ return False, None
+ except OSError as exc: # EPERM (e.g. a zombie-only group on Darwin) is reported, not hidden
+ return False, f"killpg: {type(exc).__name__}: {exc}"
+ return True, None
+
+
+def _drain(proc: subprocess.Popen[bytes]) -> tuple[bytes, bytes, str | None]:
+ """Collect what is left on the pipes after a group kill; never blocks for long."""
+ try:
+ stdout, stderr = proc.communicate(timeout=DRAIN_TIMEOUT_S)
+ except subprocess.TimeoutExpired as exc:
+ # A descendant that left the group (its own setsid) still holds the pipes: take what
+ # arrived and close our ends so the harness cannot hang on it.
+ for stream in (proc.stdout, proc.stderr):
+ if stream is not None:
+ stream.close()
+ return (
+ exc.stdout or b"",
+ exc.stderr or b"",
+ "pipes still held after the group kill (a descendant left the process group)",
+ )
+ return stdout or b"", stderr or b"", None
+
+
+def run_in_process_group(
+ argv: Sequence[str],
+ *,
+ timeout: float,
+ stdin: Any = None,
+ env: Mapping[str, str] | None = None,
+ creationflags: int = 0,
+) -> ChildRun:
+ """``subprocess.run`` with capture, plus a SIGKILL of the child's whole process group.
+
+ The child starts in its OWN process group (``process_group=0``: no ``setsid``, so the
+ session and controlling terminal stay as they were), so ``killpg`` reaches every
+ descendant. Three exits end in a group kill:
+
+ * timeout: raises :class:`ChildTimeout` (output so far attached) after the kill, when the
+ child itself outlived the timeout;
+ * normal exit (or a crash): the group is killed afterwards to reap strays
+ (``group_killed`` says so). A descendant that keeps the pipes open after the child has
+ exited is noticed within :data:`EXIT_POLL_S` and killed (not after the whole timeout), and
+ the child's REAL exit status is returned, not a timeout;
+ * any exception (a KeyboardInterrupt of the parent): the group is killed, then it is re-raised.
+ """
+ extra: dict[str, Any] = {"process_group": 0} if os.name == "posix" else {}
+ proc = subprocess.Popen(
+ list(argv),
+ stdin=stdin,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=dict(env) if env is not None else None,
+ creationflags=creationflags,
+ **extra,
+ )
+ group = proc.pid if os.name == "posix" else None
+ deadline = time.monotonic() + timeout
+ try:
+ while True:
+ try:
+ stdout, stderr = proc.communicate(
+ timeout=max(0.01, min(EXIT_POLL_S, deadline - time.monotonic()))
+ )
+ except subprocess.TimeoutExpired:
+ leader_status = proc.poll() # None: the child itself is still running
+ if leader_status is None and time.monotonic() < deadline:
+ continue
+ # Either the child outlived its timeout, or it exited and only a descendant
+ # still holds the pipes: kill the group and take what was written.
+ killed, error = kill_process_group(group, leader=proc)
+ stdout, stderr, drain_error = _drain(proc)
+ error = error or drain_error
+ if leader_status is None:
+ raise ChildTimeout(
+ argv,
+ timeout,
+ output=stdout,
+ stderr=stderr,
+ group_killed=killed,
+ cleanup_error=error,
+ ) from None
+ return ChildRun(
+ leader_status, stdout, stderr, group_killed=killed, cleanup_error=error
+ )
+ break
+ except ChildTimeout:
+ raise
+ except BaseException:
+ kill_process_group(group, leader=proc)
+ proc.wait()
+ raise
+ killed, error = kill_process_group(group, leader=proc)
+ return ChildRun(proc.returncode, stdout or b"", stderr or b"", killed, error)
+
+
+def run_experiment(
+ experiment: Experiment,
+ *,
+ script_path: Path,
+ python: str | None = None,
+ inject: bool = False,
+ run: Callable[..., Any] = run_in_process_group,
+ clock: Callable[[], float] = time.monotonic,
+ platform_name: str | None = None,
+ environ: Mapping[str, str] | None = None,
+) -> dict[str, Any]:
+ """Run one experiment in a child process and describe what happened."""
+ host = sys.platform if platform_name is None else platform_name
+ base: dict[str, Any] = {
+ "name": experiment.name,
+ "title": experiment.title,
+ "kind": experiment.kind,
+ "question": experiment.question,
+ "expected_outcome": experiment.expected_outcome,
+ "timeout_s": experiment.timeout_s,
+ }
+ if experiment.requires_macos and host != "darwin":
+ return {
+ **base,
+ "argv": [],
+ "returncode": None,
+ "signal": None,
+ "outcome": OUTCOME_SKIPPED,
+ "skip_reason": f"requires macOS (running on {host})",
+ "duration_s": 0.0,
+ "stdout_tail": "",
+ "stderr_tail": "",
+ "last_step": None,
+ "observations": None,
+ "as_expected": None,
+ "group_killed": False,
+ }
+ argv = [python or sys.executable, str(script_path), "--child", experiment.name]
+ if inject:
+ argv.append("--inject-synthetic-key")
+ env = child_environment(os.environ if environ is None else environ)
+ started = clock()
+ returncode: int | None = None
+ stdout: bytes | str | None = None
+ stderr: bytes | str | None = None
+ timed_out = False
+ spawn_error: str | None = None
+ group_killed = False
+ cleanup_error: str | None = None
+ try:
+ done = run(
+ argv,
+ timeout=experiment.timeout_s,
+ stdin=subprocess.DEVNULL,
+ env=env,
+ creationflags=_NO_WINDOW,
+ )
+ returncode, stdout, stderr = done.returncode, done.stdout, done.stderr
+ group_killed = bool(getattr(done, "group_killed", False))
+ cleanup_error = getattr(done, "cleanup_error", None)
+ except subprocess.TimeoutExpired as exc:
+ timed_out = True
+ stdout, stderr = exc.stdout, exc.stderr
+ group_killed = bool(getattr(exc, "group_killed", False))
+ cleanup_error = getattr(exc, "cleanup_error", None)
+ except OSError as exc:
+ spawn_error = f"{type(exc).__name__}: {exc}"
+ duration = clock() - started
+ stdout_text = tail_text(stdout, limit=10_000_000)
+ observations = parse_child_result(stdout_text)
+ child_flag = observations.get("ok") if isinstance(observations, dict) else None
+ outcome = classify_outcome(
+ returncode=returncode,
+ timed_out=timed_out,
+ child_ok=child_flag if isinstance(child_flag, bool) else None,
+ )
+ row: dict[str, Any] = {
+ **base,
+ "argv": summarize_argv(argv),
+ "returncode": returncode,
+ "signal": signal_name(returncode),
+ "outcome": outcome,
+ "duration_s": round(duration, 3),
+ "stdout_tail": tail_text(stdout),
+ "stderr_tail": tail_text(stderr),
+ "last_step": last_breadcrumb(stdout_text),
+ "observations": observations,
+ "as_expected": None
+ if experiment.expected_outcome is None
+ else (outcome == experiment.expected_outcome),
+ "group_killed": group_killed,
+ }
+ if cleanup_error is not None:
+ row["cleanup_error"] = cleanup_error
+ if spawn_error is not None:
+ row["spawn_error"] = spawn_error
+ return row
+
+
+def run_experiments(
+ experiments: Sequence[Experiment],
+ *,
+ script_path: Path,
+ inject: bool,
+ progress: Callable[[str], None] | None = None,
+ on_result: Callable[[list[dict[str, Any]]], None] | None = None,
+ run: Callable[..., Any] = run_in_process_group,
+) -> list[dict[str, Any]]:
+ """Run each experiment in turn; ``on_result`` gets the rows so far after EACH one.
+
+ The caller persists the partial report there, so a parent that is killed (a job timeout,
+ a runner hiccup) still leaves every finished experiment on disk.
+ """
+ results: list[dict[str, Any]] = []
+ for index, experiment in enumerate(experiments, start=1):
+ row = run_experiment(experiment, script_path=script_path, inject=inject, run=run)
+ results.append(row)
+ if progress is not None:
+ progress(
+ f"[{index}/{len(experiments)}] {experiment.name}: {row['outcome']}"
+ f" (exit {row['returncode']}, signal {row['signal']}, {row['duration_s']}s)"
+ )
+ if on_result is not None:
+ on_result(results)
+ return results
+
+
+# ---------------------------------------------------------------------------
+# Child side (macOS only). Everything below runs inside a child process.
+# ---------------------------------------------------------------------------
+
+
+class _ChildState:
+ """The one place the child collects what it observed."""
+
+ def __init__(self) -> None:
+ self.name = ""
+ self.inject = False
+ self.tcc: dict[str, Any] | None = None
+ self.steps: list[dict[str, Any]] = []
+ self.events: list[dict[str, Any]] = []
+ self.errors: list[str] = []
+ self.main_thread_ident: int | None = threading.main_thread().ident
+ self.started = time.monotonic()
+ #: How many events earlier ``_record_counts`` calls already accounted for.
+ self.counted_upto = 0
+
+
+_STATE = _ChildState()
+#: Module-level singletons. The Carbon callback, the EventTypeSpec array and the
+#: timer callback must outlive every registration: a per-object attribute dies with
+#: its owner while Carbon still holds the pointer (a jump into freed memory).
+_SINGLETONS: dict[str, Any] = {}
+
+
+def reset_child_state() -> None:
+ """Forget everything observed (the unit tests call this between cases)."""
+ global _STATE
+ _STATE = _ChildState()
+ _SINGLETONS.clear()
+
+
+def breadcrumb(message: str) -> None:
+ """Print where the child is, flushed at once, so a crash leaves its location."""
+ print(f"{STEP_PREFIX}{message}", flush=True)
+
+
+def record_step(name: str, value: Any = None, *, expect: Any = None, **extra: Any) -> None:
+ """Record one observation; with ``expect`` it also records whether it was met."""
+ row: dict[str, Any] = {"step": name, "value": value}
+ if expect is not None:
+ row["expected"] = expect
+ row["ok"] = value == expect
+ row.update(extra)
+ _STATE.steps.append(row)
+ breadcrumb(f"{name}={value}")
+
+
+def _carbon_handler(call_ref: Any, event: Any, user_data: Any) -> int:
+ """Record the event. Does nothing else, and never raises into Carbon."""
+ try:
+ carbon = _SINGLETONS["carbon_lib"]
+ kind = carbon.GetEventKind(event)
+ hot_key = EventHotKeyID()
+ status = carbon.GetEventParameter(
+ event,
+ K_EVENT_PARAM_DIRECT_OBJECT,
+ TYPE_EVENT_HOT_KEY_ID,
+ None,
+ ctypes.sizeof(hot_key),
+ None,
+ ctypes.byref(hot_key),
+ )
+ _STATE.events.append(
+ {
+ "kind": {
+ K_EVENT_HOT_KEY_PRESSED: "pressed",
+ K_EVENT_HOT_KEY_RELEASED: "released",
+ }.get(kind, f"kind_{kind}"),
+ "hot_key_id": hot_key.id if status == NO_ERR else None,
+ "parameter_status": status,
+ "on_main_thread": threading.get_ident() == _STATE.main_thread_ident,
+ "t": round(time.monotonic() - _STATE.started, 3),
+ }
+ )
+ return NO_ERR
+ except Exception as exc: # the callback must not raise; the error is recorded
+ _STATE.errors.append(f"carbon handler: {type(exc).__name__}: {exc}")
+ return EVENT_NOT_HANDLED_ERR
+
+
+def callback_singleton() -> Any:
+ if "callback" not in _SINGLETONS:
+ _SINGLETONS["callback"] = HANDLER_PROTO(_carbon_handler)
+ return _SINGLETONS["callback"]
+
+
+def spec_array_singleton() -> Any:
+ if "specs" not in _SINGLETONS:
+ _SINGLETONS["specs"] = (EventTypeSpec * 2)(
+ (K_EVENT_CLASS_KEYBOARD, K_EVENT_HOT_KEY_PRESSED),
+ (K_EVENT_CLASS_KEYBOARD, K_EVENT_HOT_KEY_RELEASED),
+ )
+ return _SINGLETONS["specs"]
+
+
+def timer_callback_singleton() -> Any:
+ if "timer_callback" not in _SINGLETONS:
+
+ def _tick(_timer: Any, _info: Any) -> None:
+ loop = _SINGLETONS.get("loop")
+ if loop is not None:
+ loop.tick()
+
+ _SINGLETONS["timer_callback"] = TIMER_PROTO(_tick)
+ return _SINGLETONS["timer_callback"]
+
+
+class CarbonShim:
+ """The thin spike-only wrapper: records OSStatus values, never raises on a status."""
+
+ def __init__(self, lib: Any = None, route: str = "injected") -> None:
+ if lib is None:
+ lib, route = load_framework(CARBON_FRAMEWORK)
+ self.lib = lib
+ self.route = route
+ self.bound, self.missing, self.aliases = bind_carbon(lib)
+ _SINGLETONS["carbon_lib"] = lib
+
+ def target(self) -> int | None:
+ """The APPLICATION event target (``c_void_p`` restype: an int or ``None``)."""
+ return self.lib.GetApplicationEventTarget()
+
+ def install_handler(self) -> tuple[int, int | None]:
+ ref = ctypes.c_void_p()
+ specs = spec_array_singleton()
+ status = self.lib.InstallEventHandler(
+ self.target(), callback_singleton(), len(specs), specs, None, ctypes.byref(ref)
+ )
+ return status, ref.value
+
+ def remove_handler(self, ref: int) -> int:
+ return self.lib.RemoveEventHandler(ctypes.c_void_p(ref))
+
+ def register(self, key_code: int, modifiers: int, hot_key_id: int) -> tuple[int, int | None]:
+ ref = ctypes.c_void_p()
+ identity = EventHotKeyID(HOT_KEY_SIGNATURE, hot_key_id)
+ status = self.lib.RegisterEventHotKey(
+ key_code, modifiers, identity, self.target(), 0, ctypes.byref(ref)
+ )
+ return status, ref.value
+
+ def unregister(self, ref: int) -> int:
+ return self.lib.UnregisterEventHotKey(ctypes.c_void_p(ref))
+
+
+def unregister_if(shim: CarbonShim, ref: int | None, label: str, *, expect: int | None) -> None:
+ """Unregister a non-null reference; a NULL reference must never reach Carbon."""
+ if ref is None:
+ record_step(f"{label}_skipped_null_ref", True)
+ return
+ record_step(label, shim.unregister(ref), expect=expect)
+
+
+class Injector:
+ """Send synthetic Control+Option+J through ``osascript`` from a helper thread.
+
+ ``repeat`` is the number of presses ONE ``osascript`` run sends (a single process, so the
+ cost of starting it is paid once).
+ """
+
+ TIMEOUT_S = 30.0
+ #: Seconds between two presses of a repeated injection.
+ REPEAT_GAP_S = 0.1
+
+ def __init__(
+ self,
+ *,
+ delay_s: float = 0.5,
+ repeat: int = 1,
+ run: Callable[..., Any] = subprocess.run,
+ ) -> None:
+ self.delay_s = delay_s
+ self.repeat = max(1, repeat)
+ #: A repeated injection needs proportionally longer than one press.
+ self.timeout_s = self.TIMEOUT_S + self.repeat * (self.REPEAT_GAP_S + 0.5)
+ self._run = run
+ self.done = threading.Event()
+ self.result: dict[str, Any] = {}
+ self._thread = threading.Thread(target=self._work, name="spike-injector", daemon=True)
+
+ def start(self) -> None:
+ self._thread.start()
+
+ def script(self) -> str:
+ press = f"key code {TEST_KEY_CODE} using {{control down, option down}}"
+ if self.repeat == 1:
+ return f'tell application "System Events" to {press}'
+ return (
+ 'tell application "System Events"\n'
+ f" repeat {self.repeat} times\n"
+ f" {press}\n"
+ f" delay {self.REPEAT_GAP_S}\n"
+ " end repeat\n"
+ "end tell"
+ )
+
+ def argv(self) -> list[str]:
+ return ["osascript", "-e", self.script()]
+
+ def _work(self) -> None:
+ try:
+ time.sleep(self.delay_s)
+ started = time.monotonic()
+ done = self._run(
+ self.argv(),
+ capture_output=True,
+ text=True,
+ timeout=self.timeout_s,
+ check=False,
+ creationflags=_NO_WINDOW,
+ )
+ self.result = {
+ "returncode": done.returncode,
+ "stdout": tail_text(done.stdout, 300),
+ "stderr": tail_text(done.stderr, 600),
+ "duration_s": round(time.monotonic() - started, 3),
+ }
+ except Exception as exc: # recorded as the injection result
+ self.result = {"returncode": None, "error": f"{type(exc).__name__}: {exc}"}
+ finally:
+ self.done.set()
+
+
+@dataclass(frozen=True)
+class OptionHoldPhase:
+ """One way of holding an Option key down while both Appshot APIs are sampled."""
+
+ name: str
+ #: "applescript" (System Events) or "javascript" (JXA, posts a CGEvent for ``key_code``).
+ language: str
+ key_code: int | None
+ description: str
+
+
+#: Three routes, because none of them is known to work: System Events ``key down option`` (the
+#: the crash-surface list's literal form; it cannot choose a side, the side is READ from the bits
+#: that light up), and a CGEvent key-down for kVK_Option (58) and kVK_RightOption (61) posted from
+#: inside ``osascript`` (JXA), which can choose. A route that fails is a recorded exit status, not
+#: an error of the experiment.
+OPTION_HOLD_PHASES = (
+ OptionHoldPhase("system_events_option", "applescript", None, "System Events `key down option`"),
+ OptionHoldPhase(
+ "cgevent_left_option", "javascript", VK_OPTION, "CGEventPost key down, key code 58"
+ ),
+ OptionHoldPhase(
+ "cgevent_right_option", "javascript", VK_RIGHT_OPTION, "CGEventPost key down, key code 61"
+ ),
+)
+#: How long the key stays down, and how often both APIs are sampled meanwhile.
+OPTION_HOLD_S = 2.5
+OPTION_SAMPLE_INTERVAL_S = 0.05
+
+
+def option_hold_script(phase: OptionHoldPhase, hold_s: float = OPTION_HOLD_S) -> str:
+ """The ``osascript`` source that holds the key for ``hold_s`` seconds and always releases it."""
+ if phase.language == "applescript":
+ return (
+ 'tell application "System Events"\n'
+ " try\n"
+ " key down option\n"
+ f" delay {hold_s}\n"
+ " key up option\n"
+ " on error errorMessage number errorNumber\n"
+ " try\n"
+ " key up option\n"
+ " end try\n"
+ " error errorMessage number errorNumber\n"
+ " end try\n"
+ "end tell"
+ )
+ if phase.language == "javascript" and phase.key_code is not None:
+ return (
+ "ObjC.import('ApplicationServices');\n"
+ "ObjC.import('Foundation');\n"
+ "function post(down) {\n"
+ f" var event = $.CGEventCreateKeyboardEvent(null, {phase.key_code}, down);\n"
+ " $.CGEventPost($.kCGHIDEventTap, event);\n"
+ "}\n"
+ "post(true);\n"
+ "try {\n"
+ f" $.NSThread.sleepForTimeInterval({hold_s});\n"
+ "} finally {\n"
+ " post(false);\n"
+ "}\n"
+ )
+ raise ValueError(f"unsupported hold phase: {phase!r}")
+
+
+class OptionHolder(Injector):
+ """Hold an Option key down through ``osascript`` for :data:`OPTION_HOLD_S` seconds."""
+
+ def __init__(
+ self,
+ phase: OptionHoldPhase,
+ *,
+ hold_s: float = OPTION_HOLD_S,
+ delay_s: float = 0.0,
+ run: Callable[..., Any] = subprocess.run,
+ ) -> None:
+ super().__init__(delay_s=delay_s, run=run)
+ self.phase = phase
+ self.hold_s = hold_s
+
+ def script(self) -> str:
+ return option_hold_script(self.phase, self.hold_s)
+
+ def argv(self) -> list[str]:
+ language = ["-l", "JavaScript"] if self.phase.language == "javascript" else []
+ return ["osascript", *language, "-e", self.script()]
+
+
+def hold_and_sample(
+ phase: OptionHoldPhase,
+ read: Callable[[], Mapping[str, Mapping[str, Any]]],
+ *,
+ holder_factory: Callable[[OptionHoldPhase], Injector] | None = None,
+ sleep: Callable[[float], None] = time.sleep,
+ clock: Callable[[], float] = time.monotonic,
+) -> dict[str, Any]:
+ """Hold the key and sample ``read`` until the holder finishes; return the peak per state.
+
+ One more read happens after the holder is done, so a key still reported down AFTER the
+ release shows up in ``reads_after_release`` (a stuck key would void later experiments).
+ """
+ holder = (holder_factory or OptionHolder)(phase)
+ holder.start()
+ samples: list[Mapping[str, Mapping[str, Any]]] = []
+ deadline = clock() + holder.timeout_s + 5.0
+ while not holder.done.is_set() and clock() < deadline:
+ samples.append(read())
+ sleep(OPTION_SAMPLE_INTERVAL_S)
+ after_release = read()
+ return {
+ "reads": merge_option_samples(samples or [after_release]),
+ "reads_after_release": merge_option_samples([after_release]),
+ "samples": len(samples),
+ "injection_exit": holder.result.get("returncode"),
+ "injection": dict(holder.result),
+ "finished": holder.done.is_set(),
+ }
+
+
+@dataclass(frozen=True)
+class Wait:
+ """What a scenario coroutine yields: block (loop keeps running) until ``predicate``."""
+
+ predicate: Callable[[], bool]
+ timeout_s: float
+ settle_s: float = 0.0
+
+
+Scenario = Generator[Wait, None, dict[str, Any] | None]
+
+
+class MainLoop:
+ """Runs a scenario coroutine from timer ticks on the main thread, inside the loop.
+
+ The scenario must run INSIDE ``[NSApp run]`` (so hot key events can be
+ delivered while it waits) and ON the main thread (Carbon's rule), which is
+ why it is a coroutine driven by a repeating run-loop timer instead of a thread.
+ """
+
+ def __init__(
+ self,
+ finish: Callable[[dict[str, Any], int], None],
+ clock: Callable[[], float] = time.monotonic,
+ ) -> None:
+ self._finish = finish
+ self._clock = clock
+ self._jobs: list[tuple[float, Callable[[], None]]] = []
+
+ def call_later(self, delay_s: float, function: Callable[[], None]) -> None:
+ self._jobs.append((self._clock() + delay_s, function))
+
+ def tick(self) -> None:
+ now = self._clock()
+ due = sorted((job for job in self._jobs if job[0] <= now), key=lambda job: job[0])
+ self._jobs = [job for job in self._jobs if job[0] > now]
+ for _when, function in due:
+ try:
+ function()
+ except Exception as exc: # a harness bug is the child's result, then it ends
+ _STATE.errors.append(f"{type(exc).__name__}: {exc}")
+ _STATE.errors.append(traceback.format_exc()[-1200:])
+ self._finish({"ok": False}, 1)
+ return
+
+ def wait_for(
+ self,
+ predicate: Callable[[], bool],
+ then: Callable[[], None],
+ *,
+ timeout_s: float,
+ settle_s: float,
+ ) -> None:
+ deadline = self._clock() + timeout_s
+
+ def poll() -> None:
+ if predicate() or self._clock() >= deadline:
+ self.call_later(settle_s, then)
+ else:
+ self.call_later(0.1, poll)
+
+ self.call_later(0.0, poll)
+
+ def drive(self, scenario: Scenario) -> None:
+ def advance() -> None:
+ try:
+ request = next(scenario)
+ except StopIteration as stop:
+ self._finish(stop.value or {}, 0)
+ return
+ self.wait_for(
+ request.predicate, advance, timeout_s=request.timeout_s, settle_s=request.settle_s
+ )
+
+ self.call_later(0.0, advance)
+
+
+def emit_result(extra: Mapping[str, Any], exit_code: int) -> int:
+ """Print the ``SPIKE_RESULT`` line; return the exit code for the caller."""
+ result = assemble_child_result(
+ _STATE.name,
+ extra,
+ steps=_STATE.steps,
+ events=_STATE.events,
+ errors=_STATE.errors,
+ tcc=_STATE.tcc,
+ inject=_STATE.inject,
+ )
+ print(RESULT_PREFIX + json.dumps(result, sort_keys=True), flush=True)
+ return exit_code
+
+
+def finish_child(extra: dict[str, Any], exit_code: int) -> NoReturn:
+ """End the child from inside the run loop (it never returns to Python's main)."""
+ code = emit_result(extra, exit_code)
+ sys.stdout.flush()
+ sys.stderr.flush()
+ os._exit(code)
+
+
+class ObjC:
+ """Just enough of the Objective-C runtime to start and run ``NSApplication``."""
+
+ def __init__(self) -> None:
+ self.lib = ctypes.CDLL("/usr/lib/libobjc.A.dylib")
+ self.lib.objc_getClass.restype = ctypes.c_void_p
+ self.lib.objc_getClass.argtypes = [ctypes.c_char_p]
+ self.lib.sel_registerName.restype = ctypes.c_void_p
+ self.lib.sel_registerName.argtypes = [ctypes.c_char_p]
+ self.appkit, _route = load_framework("AppKit")
+
+ def cls(self, name: bytes) -> int:
+ return self.lib.objc_getClass(name)
+
+ def send(
+ self,
+ receiver: int,
+ selector: bytes,
+ *,
+ restype: Any = ctypes.c_void_p,
+ argtypes: Sequence[Any] = (),
+ args: Sequence[Any] = (),
+ ) -> Any:
+ prototype = ctypes.CFUNCTYPE(restype, ctypes.c_void_p, ctypes.c_void_p, *argtypes)
+ function = prototype(("objc_msgSend", self.lib))
+ return function(receiver, self.lib.sel_registerName(selector), *args)
+
+
+class CoreFoundation:
+ """The run-loop functions the spike needs."""
+
+ def __init__(self) -> None:
+ self.lib, _route = load_framework("CoreFoundation")
+ lib = self.lib
+ lib.CFRunLoopGetMain.restype = ctypes.c_void_p
+ lib.CFRunLoopGetMain.argtypes = []
+ lib.CFAbsoluteTimeGetCurrent.restype = ctypes.c_double
+ lib.CFAbsoluteTimeGetCurrent.argtypes = []
+ lib.CFRunLoopTimerCreate.restype = ctypes.c_void_p
+ lib.CFRunLoopTimerCreate.argtypes = [
+ ctypes.c_void_p,
+ ctypes.c_double,
+ ctypes.c_double,
+ ctypes.c_ulong,
+ ctypes.c_long,
+ TIMER_PROTO,
+ ctypes.c_void_p,
+ ]
+ lib.CFRunLoopAddTimer.restype = None
+ lib.CFRunLoopAddTimer.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
+ lib.CFRunLoopRunInMode.restype = ctypes.c_int32
+ lib.CFRunLoopRunInMode.argtypes = [ctypes.c_void_p, ctypes.c_double, ctypes.c_ubyte]
+ self.common_modes = ctypes.c_void_p.in_dll(lib, "kCFRunLoopCommonModes").value
+ self.default_mode = ctypes.c_void_p.in_dll(lib, "kCFRunLoopDefaultMode").value
+
+ def add_main_timer(self, callback: Any, interval_s: float) -> None:
+ timer = self.lib.CFRunLoopTimerCreate(
+ None,
+ self.lib.CFAbsoluteTimeGetCurrent() + interval_s,
+ interval_s,
+ 0,
+ 0,
+ callback,
+ None,
+ )
+ self.lib.CFRunLoopAddTimer(self.lib.CFRunLoopGetMain(), timer, self.common_modes)
+
+ def pump(self, seconds: float) -> int:
+ return self.lib.CFRunLoopRunInMode(self.default_mode, seconds, 0)
+
+
+def run_in_nsapp_loop(make_scenario: Callable[[], Scenario]) -> NoReturn:
+ """Create ``NSApplication`` (accessory policy), run it on the main thread, and
+ drive the scenario from inside it. The process ends through :func:`finish_child`."""
+ objc = ObjC()
+ core_foundation = CoreFoundation()
+ application = objc.send(objc.cls(b"NSApplication"), b"sharedApplication")
+ record_step("nsapp_shared_application_created", bool(application))
+ objc.send(
+ application,
+ b"setActivationPolicy:",
+ restype=ctypes.c_byte,
+ argtypes=(ctypes.c_long,),
+ args=(NS_APPLICATION_ACTIVATION_POLICY_ACCESSORY,),
+ )
+ loop = MainLoop(finish_child)
+ _SINGLETONS["loop"] = loop
+ core_foundation.add_main_timer(timer_callback_singleton(), 0.05)
+ loop.call_later(0.3, lambda: loop.drive(make_scenario()))
+ breadcrumb("nsapp_run:begin")
+ objc.send(application, b"run", restype=None)
+ _STATE.errors.append("NSApplication run returned before the scenario finished")
+ finish_child({"ok": False}, 1)
+
+
+def read_keydown_counters(
+ bind: Callable[..., Any] = _bind_symbol,
+) -> dict[str, int] | None:
+ """The system-wide key-down counters (``CGEventSourceCounterForEventType``), or ``None``.
+
+ This is the positive control for a synthetic key: it does not depend on Carbon, creates no
+ event tap and asks for no permission, so a counter that moved shows the key reached the
+ event system whether or not Carbon delivered it. That the call is allowed without a grant
+ is itself an assumption (unverified); an unreadable counter makes the control
+ ``inconclusive``, never ``seen``.
+ """
+ try:
+ counter = bind(
+ ("CoreGraphics", "ApplicationServices"),
+ "CGEventSourceCounterForEventType",
+ ctypes.c_uint32,
+ (ctypes.c_int32, ctypes.c_uint32),
+ )
+ return {
+ label: int(counter(state, K_CG_EVENT_KEY_DOWN)) for label, state in OPTION_SOURCE_STATES
+ }
+ except Exception as exc: # the control reads 'unreadable' and the verdict says inconclusive
+ record_step("keydown_counter_unreadable", f"{type(exc).__name__}: {exc}"[:200])
+ return None
+
+
+def _inject_and_settle(
+ label: str, injector_factory: Callable[[], Injector] | None = None
+) -> Generator[Wait, None, None]:
+ """Send synthetic chord(s) (only with ``--inject-synthetic-key``) and let them arrive.
+
+ Records ``injection_seen_<label>``: whether the key-down counter moved while the chord was
+ sent (the control that separates 'Carbon did not deliver' from 'nothing was injected').
+ """
+ if not _STATE.inject:
+ record_step(f"inject_{label}", "not_requested")
+ return
+ before = read_keydown_counters()
+ injector = (injector_factory or Injector)()
+ injector.start()
+ yield Wait(injector.done.is_set, timeout_s=injector.timeout_s + 10.0, settle_s=1.0)
+ record_step(
+ f"inject_{label}_osascript_exit",
+ injector.result.get("returncode"),
+ detail=injector.result,
+ finished=injector.done.is_set(),
+ )
+ after = read_keydown_counters()
+ record_step(
+ f"injection_seen_{label}",
+ injection_seen(before, after),
+ counters_before=before,
+ counters_after=after,
+ )
+
+
+def _record_counts(label: str) -> dict[str, int]:
+ """Record the Pressed/Released events that arrived SINCE the previous call.
+
+ A window, not a running total: ``pressed_after_unregister`` must mean 'arrived after the
+ unregister', otherwise a press delivered while registered would be counted again there.
+ """
+ window = _STATE.events[_STATE.counted_upto :]
+ _STATE.counted_upto = len(_STATE.events)
+ counts = count_events(window)
+ record_step(f"pressed_{label}", counts["pressed"])
+ record_step(f"released_{label}", counts["released"])
+ return counts
+
+
+# --- scenarios -----------------------------------------------------------------
+
+
+def _scenario_control_signal_capture() -> dict[str, Any] | None:
+ try:
+ import resource # POSIX only; a core file would be noise
+
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
+ except (ImportError, ValueError, OSError) as exc:
+ record_step("core_limit_not_lowered", f"{type(exc).__name__}: {exc}")
+ breadcrumb("about_to_abort")
+ sys.stdout.flush()
+ os.kill(os.getpid(), signal.SIGABRT)
+ time.sleep(5)
+ return {"ok": False, "error": "the process survived its own SIGABRT"}
+
+
+def _scenario_carbon_symbols() -> dict[str, Any]:
+ shim = CarbonShim()
+ record_step("missing_symbols", len(shim.missing), expect=0)
+ return {
+ "carbon_route": shim.route,
+ "bound": shim.bound,
+ "missing": shim.missing,
+ # Canonical name -> the alias that bound, e.g. InstallEventHandler -> _InstallEventHandler.
+ "aliases": shim.aliases,
+ "struct_sizes": {
+ "EventHotKeyID": ctypes.sizeof(EventHotKeyID),
+ "EventTypeSpec": ctypes.sizeof(EventTypeSpec),
+ },
+ }
+
+
+def _co_nsapp_register_unregister(shim: CarbonShim) -> Scenario:
+ status, _handler = shim.install_handler()
+ record_step("install_handler", status, expect=NO_ERR)
+ status, hot_key = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 1)
+ record_step("register", status, expect=NO_ERR)
+ yield from _inject_and_settle("while_registered")
+ _record_counts("while_registered")
+ unregister_if(shim, hot_key, "unregister", expect=NO_ERR)
+ yield from _inject_and_settle("after_unregister")
+ _record_counts("after_unregister")
+ status, again = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 2)
+ record_step("reregister_after_unregister", status, expect=NO_ERR)
+ unregister_if(shim, again, "unregister_second", expect=NO_ERR)
+ return {"carbon_route": shim.route}
+
+
+def _scenario_nsapp_register_unregister() -> NoReturn:
+ shim = CarbonShim()
+ run_in_nsapp_loop(lambda: _co_nsapp_register_unregister(shim))
+
+
+#: Variant A's stress numbers from the crash-surface list (docs/macos-permissions.md, 4.15).
+REGISTER_CYCLES = 200
+PRESS_CYCLES = 50
+#: At most this many failing cycles are described in the report (all are counted).
+CYCLE_FAILURE_DETAILS = 5
+
+
+def _co_register_unregister_cycles(shim: CarbonShim) -> Scenario:
+ status, _handler = shim.install_handler()
+ record_step("install_handler", status, expect=NO_ERR)
+ failures: list[dict[str, Any]] = []
+ for cycle in range(REGISTER_CYCLES):
+ status, ref = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 1000 + cycle)
+ if status != NO_ERR or ref is None:
+ failures.append({"cycle": cycle, "step": "register", "status": status})
+ continue
+ status = shim.unregister(ref)
+ if status != NO_ERR:
+ failures.append({"cycle": cycle, "step": "unregister", "status": status})
+ record_step("register_unregister_cycles", REGISTER_CYCLES)
+ record_step("cycle_failures", len(failures), expect=0, details=failures[:CYCLE_FAILURE_DETAILS])
+ status, hot_key = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 2000)
+ record_step("register_for_presses", status, expect=NO_ERR)
+ record_step("press_cycles_requested", PRESS_CYCLES if _STATE.inject else 0)
+ yield from _inject_and_settle("press_cycles", lambda: Injector(repeat=PRESS_CYCLES))
+ counts = _record_counts("press_cycles")
+ record_step(
+ "every_press_arrived",
+ counts["pressed"] == PRESS_CYCLES if _STATE.inject else None,
+ )
+ unregister_if(shim, hot_key, "unregister_after_presses", expect=NO_ERR)
+ status, again = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 2001)
+ record_step("reregister_after_cycles", status, expect=NO_ERR)
+ unregister_if(shim, again, "unregister_last", expect=NO_ERR)
+ return {"carbon_route": shim.route}
+
+
+def _scenario_register_unregister_cycles() -> NoReturn:
+ shim = CarbonShim()
+ run_in_nsapp_loop(lambda: _co_register_unregister_cycles(shim))
+
+
+def _scenario_no_nsapp_register() -> dict[str, Any]:
+ shim = CarbonShim()
+ core_foundation = CoreFoundation()
+ record_step("nsapp_created", False)
+ status, handler = shim.install_handler()
+ record_step("install_handler", status)
+ status, hot_key = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 1)
+ record_step("register", status)
+ record_step("run_loop_pump_result", core_foundation.pump(0.5))
+ unregister_if(shim, hot_key, "unregister", expect=None)
+ if handler is not None:
+ record_step("remove_handler", shim.remove_handler(handler))
+ return {"carbon_route": shim.route}
+
+
+def _co_unregister_off_main(shim: CarbonShim) -> Scenario:
+ status, _handler = shim.install_handler()
+ record_step("install_handler", status, expect=NO_ERR)
+ status, hot_key = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 1)
+ record_step("register", status, expect=NO_ERR)
+ outcome: dict[str, Any] = {}
+
+ def worker() -> None:
+ try:
+ outcome["status"] = shim.unregister(hot_key) if hot_key is not None else None
+ except Exception as exc: # recorded as the worker's result
+ outcome["error"] = f"{type(exc).__name__}: {exc}"
+
+ thread = threading.Thread(target=worker, name="spike-offmain-unregister")
+ thread.start()
+ thread.join(10.0)
+ record_step(
+ "unregister_off_main",
+ outcome.get("status"),
+ returned=not thread.is_alive(),
+ error=outcome.get("error"),
+ )
+ status, again = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 2)
+ record_step("reregister_after_off_main_unregister", status)
+ yield from _inject_and_settle("after_off_main_unregister")
+ _record_counts("after_off_main_unregister")
+ unregister_if(shim, again, "unregister_second", expect=None)
+ return {"carbon_route": shim.route}
+
+
+def _scenario_unregister_off_main_thread() -> NoReturn:
+ shim = CarbonShim()
+ run_in_nsapp_loop(lambda: _co_unregister_off_main(shim))
+
+
+def _co_duplicate_register(shim: CarbonShim) -> Scenario:
+ status, _handler = shim.install_handler()
+ record_step("install_handler", status, expect=NO_ERR)
+ status, first = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 1)
+ record_step("register_first", status, expect=NO_ERR)
+ status, second = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 2)
+ record_step("register_second", status)
+ record_step("second_returned_hotkey_exists_err", status == EVENT_HOT_KEY_EXISTS_ERR)
+ yield from _inject_and_settle("with_duplicate")
+ _record_counts("with_duplicate")
+ unregister_if(shim, first, "unregister_first", expect=NO_ERR)
+ unregister_if(shim, second, "unregister_second", expect=None)
+ return {"carbon_route": shim.route}
+
+
+def _scenario_duplicate_register() -> NoReturn:
+ shim = CarbonShim()
+ run_in_nsapp_loop(lambda: _co_duplicate_register(shim))
+
+
+def _co_secure_input(shim: CarbonShim) -> Scenario:
+ lib = shim.lib
+ record_step("secure_input_before", lib.IsSecureEventInputEnabled(), expect=0)
+ record_step("enable_secure_input_raw_status", lib.EnableSecureEventInput())
+ try:
+ record_step("secure_input_after_enable", lib.IsSecureEventInputEnabled(), expect=1)
+ status, _handler = shim.install_handler()
+ record_step("install_handler", status, expect=NO_ERR)
+ status, hot_key = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 1)
+ record_step("register_under_secure_input", status, expect=NO_ERR)
+ yield from _inject_and_settle("under_secure_input")
+ _record_counts("under_secure_input")
+ unregister_if(shim, hot_key, "unregister", expect=NO_ERR)
+ finally:
+ record_step("disable_secure_input_raw_status", lib.DisableSecureEventInput())
+ record_step("secure_input_after_disable", lib.IsSecureEventInputEnabled(), expect=0)
+ return {"carbon_route": shim.route}
+
+
+def _scenario_register_under_secure_input() -> NoReturn:
+ shim = CarbonShim()
+ run_in_nsapp_loop(lambda: _co_secure_input(shim))
+
+
+def _co_install_handler_twice(shim: CarbonShim) -> Scenario:
+ first_status, first_ref = shim.install_handler()
+ record_step("install_handler_first", first_status, expect=NO_ERR)
+ second_status, second_ref = shim.install_handler()
+ record_step("install_handler_second", second_status)
+ record_step(
+ "handler_refs_distinct",
+ first_ref is not None and second_ref is not None and first_ref != second_ref,
+ )
+ status, hot_key = shim.register(TEST_KEY_CODE, TEST_MODIFIERS, 1)
+ record_step("register", status, expect=NO_ERR)
+ yield from _inject_and_settle("two_handlers")
+ _record_counts("two_handlers")
+ unregister_if(shim, hot_key, "unregister", expect=NO_ERR)
+ for label, ref in (("remove_handler_first", first_ref), ("remove_handler_second", second_ref)):
+ if ref is None:
+ record_step(f"{label}_skipped_null_ref", True)
+ else:
+ record_step(label, shim.remove_handler(ref))
+ return {"carbon_route": shim.route}
+
+
+def _scenario_install_handler_twice() -> NoReturn:
+ shim = CarbonShim()
+ run_in_nsapp_loop(lambda: _co_install_handler_twice(shim))
+
+
+def _scenario_appshot_option_state_read() -> dict[str, Any]:
+ key_state = _bind_symbol(
+ ("CoreGraphics", "ApplicationServices"),
+ "CGEventSourceKeyState",
+ ctypes.c_ubyte,
+ (ctypes.c_int32, ctypes.c_uint16),
+ )
+ flags_state = _bind_symbol(
+ ("CoreGraphics", "ApplicationServices"),
+ "CGEventSourceFlagsState",
+ ctypes.c_uint64,
+ (ctypes.c_int32,),
+ )
+
+ def read() -> dict[str, dict[str, Any]]:
+ return {
+ label: {
+ "key_left": bool(key_state(state, VK_OPTION)),
+ "key_right": bool(key_state(state, VK_RIGHT_OPTION)),
+ "flags_raw": int(flags_state(state)),
+ }
+ for label, state in OPTION_SOURCE_STATES
+ }
+
+ baseline = read()
+ for label, state_read in baseline.items():
+ record_step(f"{label}_keystate_left", state_read["key_left"])
+ record_step(f"{label}_keystate_right", state_read["key_right"])
+ record_step(
+ f"{label}_flags_alternate",
+ bool(state_read["flags_raw"] & K_CG_EVENT_FLAG_MASK_ALTERNATE),
+ )
+ phases: dict[str, dict[str, Any]] = {}
+ if _STATE.inject:
+ for phase in OPTION_HOLD_PHASES:
+ phases[phase.name] = hold_and_sample(phase, read)
+ record_step(
+ f"{phase.name}_osascript_exit",
+ phases[phase.name]["injection_exit"],
+ detail=phases[phase.name]["injection"],
+ )
+ record_step(
+ f"{phase.name}_stuck_after_release",
+ any(
+ state_read["key_left"] or state_read["key_right"]
+ for state_read in phases[phase.name]["reads_after_release"].values()
+ ),
+ )
+ else:
+ record_step("hold_phases", "not_requested")
+ verdict = option_hold_verdict(baseline, phases)
+ for name, phase_verdict in verdict["phases"].items():
+ record_step(f"{name}_any_api_saw_option", phase_verdict["any_api_saw_option"])
+ return {
+ "reads": baseline,
+ "comparison": compare_option_reads(baseline),
+ "phases": phases,
+ "verdict": verdict,
+ }
+
+
+def _scenario_tcc_context() -> dict[str, Any]:
+ """Nothing to do: ``run_child`` records the TCC context for this scenario, and only that."""
+ return {}
+
+
+#: name -> (function, collect the TCC context BEFORE the scenario). The no-NSApplication
+#: variant reads TCC afterwards so the probes cannot stand in for an application.
+_SCENARIOS: dict[str, tuple[Callable[[], dict[str, Any] | None], bool]] = {
+ "control_signal_capture": (_scenario_control_signal_capture, False),
+ "tcc_context": (_scenario_tcc_context, True),
+ "carbon_symbols": (_scenario_carbon_symbols, True),
+ "nsapp_register_unregister": (_scenario_nsapp_register_unregister, True),
+ "register_unregister_cycles": (_scenario_register_unregister_cycles, True),
+ "no_nsapp_register": (_scenario_no_nsapp_register, False),
+ "unregister_off_main_thread": (_scenario_unregister_off_main_thread, True),
+ "duplicate_register": (_scenario_duplicate_register, True),
+ "register_under_secure_input": (_scenario_register_under_secure_input, True),
+ "install_handler_twice": (_scenario_install_handler_twice, True),
+ "appshot_option_state_read": (_scenario_appshot_option_state_read, True),
+}
+
+
+def run_child(name: str, *, inject: bool) -> int:
+ """Entry point of ``--child NAME``: run one scenario, print its result line."""
+ _STATE.name = name
+ _STATE.inject = inject
+ entry = _SCENARIOS.get(name)
+ if entry is None:
+ return emit_result({"ok": False, "error": f"unknown experiment {name!r}"}, 2)
+ if experiment_by_name(name).requires_macos and sys.platform != "darwin":
+ return emit_result({"ok": False, "error": f"requires macOS (running on {sys.platform})"}, 1)
+ faulthandler.enable()
+ function, tcc_first = entry
+ try:
+ if tcc_first:
+ _STATE.tcc = collect_tcc_context()
+ extra = function()
+ except Exception as exc: # the failure is the child's result, with a traceback
+ _STATE.errors.append(f"{type(exc).__name__}: {exc}")
+ _STATE.errors.append(traceback.format_exc()[-1500:])
+ return emit_result({"ok": False}, 1)
+ if not tcc_first:
+ _STATE.tcc = collect_tcc_context()
+ return emit_result(extra or {}, 0)
+
+
+# ---------------------------------------------------------------------------
+# Command line.
+# ---------------------------------------------------------------------------
+
+
+def _write_text(path: Path, text: str) -> None:
+ """Write atomically (temp file + replace): a parent killed mid-write leaves the old report."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.with_name(path.name + ".tmp")
+ temporary.write_text(text, encoding="utf-8")
+ os.replace(temporary, path)
+
+
+def _utc_now() -> str:
+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--out", type=Path, help="Write the JSON report here.")
+ parser.add_argument("--summary-md", type=Path, help="Also write the summary as Markdown here.")
+ parser.add_argument("--only", default="", help="Comma-separated experiment names to run.")
+ parser.add_argument(
+ "--inject-synthetic-key",
+ action="store_true",
+ help="Send Control+Option+J through osascript (needs System Events automation).",
+ )
+ parser.add_argument("--child", metavar="NAME", help=argparse.SUPPRESS)
+ args = parser.parse_args(argv)
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(encoding="utf-8", errors="replace")
+
+ if args.child:
+ return run_child(args.child, inject=args.inject_synthetic_key)
+ if args.out is None:
+ parser.error("--out is required")
+ try:
+ planned = plan_experiments(args.only)
+ except ValueError as exc:
+ parser.error(str(exc))
+
+ started_at = _utc_now()
+ runner = collect_runner_facts() # pure Python + sw_vers: the parent loads no framework
+
+ def persist(rows: list[dict[str, Any]], *, complete: bool) -> dict[str, Any]:
+ report = build_report(
+ runner=runner,
+ tcc=tcc_from_experiments(rows),
+ experiments=rows,
+ started_at=started_at,
+ finished_at=_utc_now(),
+ options={"inject_synthetic_key": args.inject_synthetic_key, "only": args.only or None},
+ complete=complete,
+ )
+ _write_text(args.out, json.dumps(report, indent=2) + "\n")
+ if args.summary_md is not None:
+ _write_text(args.summary_md, render_summary_markdown(report))
+ return report
+
+ # An empty first write: even a parent killed before the first experiment ends leaves a file.
+ persist([], complete=False)
+ experiments = run_experiments(
+ planned,
+ script_path=Path(__file__).resolve(),
+ inject=args.inject_synthetic_key,
+ progress=lambda line: print(line, flush=True),
+ on_result=lambda rows: persist(rows, complete=False),
+ )
+ report = persist(experiments, complete=True)
+ print()
+ print(render_summary_text(report))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/conftest.py b/tests/conftest.py
index 02ce0677b3..31cf7adf9d 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -190,6 +190,16 @@ def _macos_shell_registration_in_tmp(tmp_path_factory, monkeypatch): # noqa: AN
monkeypatch.setattr(macos_dock, "_DEFAULTS", str(agents / "no-defaults"))
monkeypatch.setattr(macos_dock, "_KILLALL", str(agents / "no-killall"))
monkeypatch.setattr(macos_dock, "_marker_path", lambda: agents / "macos-dock-pinned")
+ # The permission port keeps no state file any more; the one place that still
+ # names the two files an earlier build left behind is the one-time cleanup on
+ # the darwin install path, and a suite that reaches it must not delete the
+ # developer's real copies.
+ import jarvis.platform.permissions as permissions
+
+ monkeypatch.setattr(permissions, "_leftover_state_dir", lambda: agents)
+ # The rebuild fingerprint is written into the data directory whenever a darwin
+ # bundle is (re)built; a suite that does so must not skew a real launch's decision.
+ monkeypatch.setattr(mab, "_rebuild_marker_path", lambda: agents / "macos-bundle-rebuild.json")
yield agents
@@ -337,6 +347,30 @@ def _reset_entry_point_cache():
invalidate()
[email protected](autouse=True)
+def _reset_permission_service():
+ """Start and end every test with a cold permission service.
+
+ ``jarvis.platform.permission_service`` keeps open episodes, listeners and a
+ bus handle for the life of the process. That is right in production and wrong
+ across tests: an episode one test opened would answer the next test's
+ ``ensure()`` with ``asked=False``, and a listener would outlive the loop it
+ was registered on.
+
+ The module is looked up in ``sys.modules`` and never imported here: a test
+ that never touched the service must not pay for it (or load it on a base
+ install), and a module that is not loaded has nothing to reset.
+ """
+ module = sys.modules.get("jarvis.platform.permission_service")
+ if module is not None:
+ module._reset_for_tests()
+ yield
+ # Re-read: the test itself may have been the first to import the module.
+ module = sys.modules.get("jarvis.platform.permission_service")
+ if module is not None:
+ module._reset_for_tests()
+
+
@pytest_asyncio.fixture
async def fresh_bus():
"""Fresh EventBus for each test."""
diff --git a/tests/contract/test_hotkey_backend_protocol.py b/tests/contract/test_hotkey_backend_protocol.py
index 9e410e9048..c2a761febf 100644
--- a/tests/contract/test_hotkey_backend_protocol.py
+++ b/tests/contract/test_hotkey_backend_protocol.py
@@ -61,3 +61,55 @@ def test_held_tokens_is_unknown_before_the_backend_listens(factory):
probe = getattr(backend, "held_tokens", None)
assert callable(probe)
assert probe() is None
+
+
+# --- optional readiness probes (just-in-time permissions) ---------------------
+#
+# A backend MAY expose ``is_listening()``, ``waiting_for_permission`` and
+# ``deaf_tap_suspected()``; ``HotkeyTrigger`` reads the first two through ``getattr`` and the
+# backend's own ``report_if_deaf`` uses the third.
+# Whatever it exposes must never claim a running listener, a missing permission
+# or a deaf tap BEFORE ``start``: the "Esc to cancel" pill and the permission
+# watchers trust these answers.
+
+
[email protected]("factory", _backend_factories())
+def test_optional_probes_never_claim_a_listener_before_start(factory):
+ backend = factory()
+ listening = getattr(backend, "is_listening", None)
+ if callable(listening):
+ assert listening() is False
+ assert getattr(backend, "waiting_for_permission", False) is False
+ deaf = getattr(backend, "deaf_tap_suspected", None)
+ if callable(deaf):
+ assert deaf() is False
+
+
[email protected]("factory", _backend_factories())
+def test_the_trigger_reads_a_backend_without_probes_as_unknown(factory):
+ """``listening()`` is ``None`` for a backend that cannot say, never ``False``."""
+ from jarvis.trigger.hotkey import HotkeyTrigger
+
+ trigger = HotkeyTrigger({"call": ["f3+f4"]})
+ backend = factory()
+ trigger._backend = backend
+ has_probe = callable(getattr(backend, "is_listening", None))
+ assert trigger.listening() is (False if has_probe else None)
+ assert trigger.armed is False
+
+
+def test_only_the_macos_and_the_noop_backends_have_a_listener_probe():
+ """Windows and Linux keep today's pill behaviour; the no-op backend says "never"."""
+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend
+ from jarvis.trigger.backends.noop import NoopBackend
+ from jarvis.trigger.backends.pynput import PynputBackend
+ from jarvis.trigger.backends.quartz import QuartzHotkeyBackend
+
+ assert callable(QuartzHotkeyBackend().is_listening)
+ # Nothing is ever armed by the no-op backend: "not listening", not "cannot say".
+ assert NoopBackend().is_listening() is False
+ for other in (GlobalHotkeysBackend, PynputBackend, NoopBackend):
+ if other is not NoopBackend:
+ assert not hasattr(other(), "is_listening")
+ # Only the macOS tap can WAIT for a permission (the trigger's re-arm hook).
+ assert not hasattr(other(), "waiting_for_permission")
diff --git a/tests/contract/test_live_conversation.py b/tests/contract/test_live_conversation.py
index a30913f630..499f11f534 100644
--- a/tests/contract/test_live_conversation.py
+++ b/tests/contract/test_live_conversation.py
@@ -80,7 +80,6 @@ def test_running_browser_call_blocks_a_competing_native_start(monkeypatch):
pipeline = SpeechPipeline.__new__(SpeechPipeline)
pipeline._state = PipelineState.IDLE
pipeline._dictation_blocks_activation = lambda: False
- pipeline._capture_permission_allowed = lambda: True
monkeypatch.setattr(runtime, "_active", {"browser": object()})
monkeypatch.setattr(runtime, "_opening", set())
assert not pipeline._activation_allowed()
diff --git a/tests/contract/test_permission_service_contract.py b/tests/contract/test_permission_service_contract.py
new file mode 100644
index 0000000000..7a7a601298
--- /dev/null
+++ b/tests/contract/test_permission_service_contract.py
@@ -0,0 +1,382 @@
+"""Cross-OS contract of the just-in-time permission service.
+
+One scenario table runs against a ``darwin`` ``FakeTCC`` and against ``win32`` /
+``linux``, through every entry point (``ensure``, ``ensure_all``,
+``ensure_async``). The contract:
+
+* On macOS each scenario yields the outcome the table says, with the right
+ ``asked`` / ``outside_installed_app`` flags, and a refusal is announced on the
+ bus exactly once.
+* Everywhere else the answer is ALWAYS ``NOT_REQUIRED`` (``granted`` is true),
+ nothing is published, nothing is registered and the FakeTCC call log stays
+ EMPTY: no framework was loaded, no probe ran, no request was made.
+* On every platform ``EnsureResult.granted`` is true only for GRANTED and
+ NOT_REQUIRED, a result that may not proceed carries the fixed-template
+ sentences, and ``agent_detail`` is the prohibitive one (P9).
+
+Every macOS behaviour is a MODEL (``tests/fakes/fake_tcc.py`` lists which parts
+Apple documents); nothing here ran on a real Mac.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+from collections.abc import Callable, Iterator
+from dataclasses import dataclass, field
+from typing import Any
+
+import pytest
+
+from jarvis.core.events import Event, PermissionNeeded, PermissionResolved
+from jarvis.platform.permission_service import (
+ EnsureResult,
+ PermissionOutcome,
+ PermissionService,
+)
+from jarvis.platform.permissions import PermissionId, PermissionState
+from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, install_port
+
+_MUSIC = "com.apple.Music"
+_PROCEED = {PermissionOutcome.GRANTED, PermissionOutcome.NOT_REQUIRED}
+_PLATFORMS = ("darwin", "win32", "linux")
+_ENTRY_POINTS = ("ensure", "ensure_all", "ensure_async")
+
+
+class _RecordingBus:
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._events: list[Event] = []
+
+ async def publish(self, event: Event) -> None:
+ with self._lock:
+ self._events.append(event)
+
+ @property
+ def events(self) -> list[Event]:
+ with self._lock:
+ return list(self._events)
+
+
+def bus_loop() -> Iterator[asyncio.AbstractEventLoop]:
+ loop = asyncio.new_event_loop()
+ thread = threading.Thread(target=lambda: (asyncio.set_event_loop(loop), loop.run_forever()))
+ thread.daemon = True
+ thread.start()
+ yield loop
+ asyncio.run_coroutine_threadsafe(asyncio.sleep(0), loop).result(timeout=5)
+ loop.call_soon_threadsafe(loop.stop)
+ thread.join(timeout=5)
+ loop.close()
+
+
+def _flush(loop: asyncio.AbstractEventLoop) -> None:
+ for _ in range(3):
+ asyncio.run_coroutine_threadsafe(asyncio.sleep(0), loop).result(timeout=5)
+
+
+@dataclass(frozen=True)
+class Scenario:
+ """One row of the table: a world, a call, and what macOS must answer."""
+
+ id: str
+ permission: PermissionId
+ outcome: PermissionOutcome # on macOS; every other OS answers NOT_REQUIRED
+ asked: bool = False
+ outside: bool = False
+ tcc: dict[str, Any] = field(default_factory=dict)
+ prepare: Callable[[FakeTCC], None] = lambda tcc: None
+ call: dict[str, Any] = field(default_factory=dict)
+ # How many PermissionNeeded events a refusal publishes on macOS (exactly once).
+ announced: int = 1
+
+
+def _grant(tcc: FakeTCC) -> None:
+ tcc.grant("microphone")
+
+
+def _deny(tcc: FakeTCC) -> None:
+ tcc.deny("microphone")
+
+
+def _restrict(tcc: FakeTCC) -> None:
+ tcc.restrict("microphone")
+
+
+SCENARIOS = (
+ Scenario(
+ "mic_already_granted",
+ PermissionId.MICROPHONE,
+ PermissionOutcome.GRANTED,
+ prepare=_grant,
+ announced=0,
+ ),
+ Scenario(
+ "mic_asked_and_allowed",
+ PermissionId.MICROPHONE,
+ PermissionOutcome.GRANTED,
+ asked=True,
+ announced=0,
+ ),
+ Scenario(
+ "mic_asked_dialog_open",
+ PermissionId.MICROPHONE,
+ PermissionOutcome.PENDING,
+ asked=True,
+ tcc={"default_policy": DialogPolicy.NEVER_ANSWERED},
+ ),
+ Scenario(
+ "mic_asked_and_denied",
+ PermissionId.MICROPHONE,
+ PermissionOutcome.DENIED,
+ asked=True,
+ tcc={"default_policy": DialogPolicy.DENY},
+ ),
+ Scenario("mic_denied_before", PermissionId.MICROPHONE, PermissionOutcome.DENIED, prepare=_deny),
+ Scenario(
+ "mic_restricted", PermissionId.MICROPHONE, PermissionOutcome.UNAVAILABLE, prepare=_restrict
+ ),
+ Scenario(
+ "mic_background_consumer",
+ PermissionId.MICROPHONE,
+ PermissionOutcome.PENDING,
+ call={"interactive": False},
+ ),
+ Scenario(
+ "mic_missing_usage_string",
+ PermissionId.MICROPHONE,
+ PermissionOutcome.UNAVAILABLE,
+ tcc={"usage_strings": (), "abort_raises": True},
+ ),
+ Scenario(
+ "mic_outside_the_installed_app",
+ PermissionId.MICROPHONE,
+ PermissionOutcome.NEEDS_SETTINGS,
+ outside=True,
+ tcc={"bundle_id": None, "bundle_path": None},
+ ),
+ Scenario(
+ "accessibility_prompt_once",
+ PermissionId.ACCESSIBILITY,
+ PermissionOutcome.PENDING,
+ asked=True,
+ tcc={"default_policy": DialogPolicy.NEVER_ANSWERED},
+ ),
+ Scenario(
+ "screen_recording_prompt_once",
+ PermissionId.SCREEN_RECORDING,
+ PermissionOutcome.PENDING,
+ asked=True,
+ tcc={"default_policy": DialogPolicy.NEVER_ANSWERED},
+ ),
+ Scenario(
+ "input_monitoring_prompt_once",
+ PermissionId.INPUT_MONITORING,
+ PermissionOutcome.PENDING,
+ asked=True,
+ tcc={"default_policy": DialogPolicy.NEVER_ANSWERED},
+ ),
+ Scenario(
+ "event_posting_is_accessibility",
+ PermissionId.EVENT_POSTING,
+ PermissionOutcome.PENDING,
+ asked=True,
+ tcc={"default_policy": DialogPolicy.NEVER_ANSWERED},
+ ),
+ Scenario(
+ "automation_player_not_installed",
+ PermissionId.AUTOMATION,
+ PermissionOutcome.NOT_REQUIRED,
+ call={"target": _MUSIC},
+ announced=0,
+ ),
+ Scenario(
+ "automation_player_running_allowed",
+ PermissionId.AUTOMATION,
+ PermissionOutcome.GRANTED,
+ asked=True,
+ call={"target": _MUSIC},
+ tcc={"installed_players": [_MUSIC], "running_players": [_MUSIC]},
+ announced=0,
+ ),
+ Scenario(
+ "automation_target_outside_the_table",
+ PermissionId.AUTOMATION,
+ PermissionOutcome.UNAVAILABLE,
+ call={"target": "com.evil.app"},
+ ),
+)
+
+
+@dataclass
+class World:
+ service: PermissionService
+ tcc: FakeTCC
+ bus: _RecordingBus
+ loop: asyncio.AbstractEventLoop
+
+ def run(self, entry: str, scenario: Scenario) -> EnsureResult:
+ kwargs = {"feature": "voice", **scenario.call}
+ if entry == "ensure":
+ return self.service.ensure(scenario.permission, **kwargs)
+ if entry == "ensure_all":
+ [result] = self.service.ensure_all([scenario.permission], **kwargs)
+ return result
+ return asyncio.run(self.service.ensure_async(scenario.permission, **kwargs))
+
+ def events(self) -> list[Event]:
+ _flush(self.loop)
+ return self.bus.events
+
+
+def build_world(
+ monkeypatch: pytest.MonkeyPatch, bus_loop: asyncio.AbstractEventLoop
+) -> Iterator[Callable[[str, Scenario], World]]:
+ services: list[PermissionService] = []
+
+ def build(platform: str, scenario: Scenario) -> World:
+ tcc = FakeTCC(**scenario.tcc)
+ scenario.prepare(tcc)
+ install_port(monkeypatch, tcc.port(platform)) # type: ignore[arg-type]
+ bus = _RecordingBus()
+ # The Automation request normally runs on its own daemon thread; the table
+ # asserts the final outcome, so it runs inline here.
+ service = PermissionService(watch_interval_s=3600.0, ask_runner=lambda work: work())
+ service.attach_bus(bus, bus_loop)
+ services.append(service)
+ return World(service, tcc, bus, bus_loop)
+
+ yield build
+ for service in services:
+ service._shutdown()
+
+
+def _assert_result_invariants(result: EnsureResult) -> None:
+ """What holds for every result on every platform."""
+ assert result.granted is (result.outcome in _PROCEED)
+ family = "accessibility" if result.permission is PermissionId.EVENT_POSTING else None
+ tag = f"[permission_needed:{family or result.permission.value}] "
+ if result.granted:
+ assert result.agent_detail == "" and result.user_detail == ""
+ assert result.reason == ""
+ else:
+ assert result.agent_detail.startswith(tag)
+ assert "must not retry" in result.agent_detail # P9: prohibitive, never "click Allow"
+ assert result.user_detail.endswith(".") and "Traceback" not in result.user_detail
+ assert result.reason
+
+
[email protected]("entry", _ENTRY_POINTS)
[email protected]("scenario", SCENARIOS, ids=lambda s: s.id)
+def test_on_macos_each_scenario_has_the_documented_outcome(
+ build_world: Callable[[str, Scenario], World], scenario: Scenario, entry: str
+) -> None:
+ world = build_world("darwin", scenario)
+ result = world.run(entry, scenario)
+ assert result.outcome is scenario.outcome, world.tcc.format_log()
+ assert result.asked is scenario.asked, world.tcc.format_log()
+ assert result.outside_installed_app is scenario.outside
+ _assert_result_invariants(result)
+ # A prompt only ever happens through an explicit request, never behind our back.
+ assert world.tcc.implicit_prompts() == []
+ assert world.tcc.aborts() == []
+ assert (len(world.tcc.requests()) > 0) is scenario.asked
+ needed = [e for e in world.events() if isinstance(e, PermissionNeeded)]
+ if result.granted:
+ assert needed == []
+ else:
+ assert len(needed) >= 1
+ # Asking again never publishes a second event for the same state (a retry loop is quiet).
+ if scenario.announced:
+ before = len(needed)
+ world.run(entry, scenario)
+ again = [e for e in world.events() if isinstance(e, PermissionNeeded)]
+ assert len(again) == before
+
+
[email protected]("entry", _ENTRY_POINTS)
[email protected]("platform", ["win32", "linux"])
[email protected]("scenario", SCENARIOS, ids=lambda s: s.id)
+def test_off_macos_every_scenario_is_not_required_and_silent(
+ build_world: Callable[[str, Scenario], World],
+ scenario: Scenario,
+ platform: str,
+ entry: str,
+) -> None:
+ world = build_world(platform, scenario)
+ result = world.run(entry, scenario)
+ assert result.outcome is PermissionOutcome.NOT_REQUIRED
+ assert result.granted and result.state is PermissionState.NOT_REQUIRED
+ assert not result.asked and not result.outside_installed_app
+ _assert_result_invariants(result)
+ world.tcc.assert_silent() # no framework loaded, no probe, no request
+ assert world.events() == []
+ assert world.service.outstanding() == []
+
+
[email protected]("platform", _PLATFORMS)
+def test_check_is_silent_and_follows_the_platform(
+ build_world: Callable[[str, Scenario], World], platform: str
+) -> None:
+ scenario = SCENARIOS[1] # not determined, would be allowed if asked
+ world = build_world(platform, scenario)
+ for permission in PermissionId:
+ state = world.service.check(permission)
+ if platform == "darwin":
+ assert state is not PermissionState.NOT_REQUIRED or permission in (
+ PermissionId.AUTOMATION,
+ )
+ else:
+ assert state is PermissionState.NOT_REQUIRED
+ world.tcc.assert_no_prompts()
+ if platform != "darwin":
+ world.tcc.assert_silent()
+ assert world.events() == []
+
+
[email protected]("platform", _PLATFORMS)
+def test_a_background_consumer_never_asks_on_any_platform(
+ build_world: Callable[[str, Scenario], World], platform: str
+) -> None:
+ scenario = Scenario("background", PermissionId.MICROPHONE, PermissionOutcome.PENDING)
+ world = build_world(platform, scenario)
+ results = world.service.ensure_all(
+ [
+ PermissionId.MICROPHONE,
+ PermissionId.SCREEN_RECORDING,
+ PermissionId.ACCESSIBILITY,
+ PermissionId.INPUT_MONITORING,
+ ],
+ feature="wake_word",
+ interactive=False,
+ )
+ assert world.tcc.requests() == [] and world.tcc.implicit_prompts() == []
+ if platform == "darwin":
+ assert not any(r.granted or r.asked for r in results)
+ [episode] = world.service.outstanding()
+ assert episode.origin == "background"
+ else:
+ assert all(r.outcome is PermissionOutcome.NOT_REQUIRED for r in results)
+ assert world.service.outstanding() == []
+
+
+def test_a_grant_ends_the_episode_on_the_bus(
+ build_world: Callable[[str, Scenario], World],
+) -> None:
+ scenario = SCENARIOS[2]
+ world = build_world("darwin", scenario)
+ assert world.service.ensure(scenario.permission, feature="voice").outcome is (
+ PermissionOutcome.PENDING
+ )
+ world.tcc.answer("microphone", DialogPolicy.ALLOW)
+ world.service.invalidate()
+ world.service.refresh_episodes()
+ kinds = [type(e) for e in world.events()]
+ assert kinds == [PermissionNeeded, PermissionResolved]
+ assert world.events()[-1].granted is True # type: ignore[union-attr]
+
+
+def test_the_scenario_table_covers_every_outcome_on_macos() -> None:
+ assert {s.outcome for s in SCENARIOS} == set(PermissionOutcome)
diff --git a/tests/fakes/fake_permission_service.py b/tests/fakes/fake_permission_service.py
new file mode 100644
index 0000000000..a3ee772fd5
--- /dev/null
+++ b/tests/fakes/fake_permission_service.py
@@ -0,0 +1,397 @@
+"""FakePermissionService: a scripted ``PermissionGate`` for consumer tests.
+
+Per AGENTS.md the project uses real fakes, never ``unittest.mock``. A consumer
+(audio capture, dictation, the computer-use actuator, a hotkey backend) asks the
+permission layer through the ``jarvis.core.protocols.PermissionGate`` hook; this
+fake answers it with a scripted outcome per permission, no OS, no bus and no
+threads, and records every call so the test can assert what the consumer asked.
+
+Usage::
+
+ gate = FakePermissionService() # everything granted
+ gate.script(PermissionId.MICROPHONE, PermissionOutcome.PENDING) # sticky
+ gate.script(PermissionId.ACCESSIBILITY, "denied", "granted") # one per call,
+ # the last one sticks
+ consumer = Dictation(access_gate=gate)
+ ...
+ assert gate.ensure_calls(PermissionId.MICROPHONE)[0].interactive is False
+ assert gate.native_free() # an ``interactive=False`` consumer never asks
+
+Results are real :class:`EnsureResult` objects whose sentences come from the same
+fixed templates as the real service, so a consumer that renders ``user_detail`` or
+forwards ``agent_detail`` is tested against the production wording. The fake's own
+rule is only the one the real service guarantees: ``result.granted`` is true for
+GRANTED and NOT_REQUIRED and for nothing else. Like the real service it folds
+EVENT_POSTING into ACCESSIBILITY (one script, one answer for both ids) and it says
+``asked`` only for an answer a real request could have produced (PENDING or
+NEEDS_SETTINGS): a denial, an impossibility and a grant never ask.
+
+The two reports a consumer makes about a REAL attempt (``report_failed_use``: a send was
+refused although the probe read granted; ``report_use_ok``: a later send landed) are
+recorded in the same call log (``report_calls()``) and never count as an ask.
+
+Pair it with the real service and ``FakeTCC`` (``tests/fakes/fake_tcc.py``) when the
+test is about macOS behaviour; use this fake when the test is about the consumer.
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import Any
+from uuid import UUID
+
+from jarvis.platform.permission_service import (
+ EnsureResult,
+ PermissionOutcome,
+ agent_detail_for,
+ user_detail_for,
+)
+from jarvis.platform.permissions import PANE_FAMILY, PermissionId, PermissionState
+
+_STATE_OF_OUTCOME: dict[PermissionOutcome, PermissionState] = {
+ PermissionOutcome.GRANTED: PermissionState.GRANTED,
+ PermissionOutcome.PENDING: PermissionState.NOT_DETERMINED,
+ PermissionOutcome.DENIED: PermissionState.DENIED,
+ PermissionOutcome.NEEDS_SETTINGS: PermissionState.NOT_GRANTED,
+ PermissionOutcome.UNAVAILABLE: PermissionState.UNAVAILABLE,
+ PermissionOutcome.NOT_REQUIRED: PermissionState.NOT_REQUIRED,
+}
+_REASON_OF_OUTCOME: dict[PermissionOutcome, str] = {
+ PermissionOutcome.PENDING: "not_determined",
+ PermissionOutcome.DENIED: "denied",
+ PermissionOutcome.NEEDS_SETTINGS: "needs_settings",
+ PermissionOutcome.UNAVAILABLE: "unavailable",
+}
+
+
+@dataclass(frozen=True, slots=True)
+class GateCall:
+ """One call a consumer made, in order."""
+
+ # "check" | "ensure" | "ensure_async" | "open_settings" | "report_failed_use" | "report_use_ok"
+ method: str
+ permission: PermissionId
+ feature: str = ""
+ interactive: bool = True
+ wait_s: float = 0.0
+ target: str | None = None
+ trace_id: UUID | str | None = None
+ allow_outside_app: bool = False
+ force_ask: bool = False
+ # Only a ``report_failed_use`` call carries these (the reason and the episode origin
+ # the consumer asked for); a report never asks, so its ``interactive`` is False.
+ reason: str | None = None
+ origin: str | None = None
+
+
+# Outcomes a native request can have produced: nothing else is ever "asked".
+_ASKING_OUTCOMES = frozenset({PermissionOutcome.PENDING, PermissionOutcome.NEEDS_SETTINGS})
+
+
+def make_result(
+ permission: PermissionId | str,
+ outcome: PermissionOutcome | str,
+ *,
+ asked: bool = False,
+ outside_installed_app: bool = False,
+ target: str = "",
+ state: PermissionState | None = None,
+) -> EnsureResult:
+ """A real ``EnsureResult`` for ``outcome``, with the production sentences."""
+ perm = PermissionId(permission)
+ out = PermissionOutcome(str(outcome))
+ resolved_state = state if state is not None else _STATE_OF_OUTCOME[out]
+ if out in (PermissionOutcome.GRANTED, PermissionOutcome.NOT_REQUIRED):
+ return EnsureResult(
+ permission=perm,
+ outcome=out,
+ state=resolved_state,
+ asked=asked,
+ outside_installed_app=False,
+ agent_detail="",
+ user_detail="",
+ target=target,
+ )
+ reason = (
+ "restricted" if resolved_state is PermissionState.RESTRICTED else _REASON_OF_OUTCOME[out]
+ )
+ family = PANE_FAMILY[perm]
+ return EnsureResult(
+ permission=perm,
+ outcome=out,
+ state=resolved_state,
+ asked=asked,
+ outside_installed_app=outside_installed_app,
+ agent_detail=agent_detail_for(family, reason, target=target),
+ user_detail=user_detail_for(
+ family, reason, target=target, outside_app=outside_installed_app
+ ),
+ reason=reason,
+ can_prompt=out is PermissionOutcome.PENDING,
+ can_open_settings=reason not in ("restricted", "unavailable"),
+ target=target,
+ )
+
+
+class FakePermissionService:
+ """A scripted, OS-free implementation of ``PermissionGate``."""
+
+ def __init__(
+ self,
+ outcomes: Mapping[PermissionId | str, PermissionOutcome | str | EnsureResult] | None = None,
+ *,
+ default: PermissionOutcome | str = PermissionOutcome.GRANTED,
+ settings_opens: bool = True,
+ ) -> None:
+ self._default = PermissionOutcome(str(default))
+ self._sticky: dict[PermissionId, PermissionOutcome | EnsureResult] = {}
+ self._queued: dict[PermissionId, deque[PermissionOutcome | EnsureResult]] = {}
+ self.settings_opens = settings_opens
+ self.calls: list[GateCall] = []
+ # (permission, feature, target) of every failed use reported and not yet
+ # followed by a use that worked: the fake's stand-in for the open episode.
+ self._reported_failures: set[tuple[PermissionId, str, str]] = set()
+ for permission, outcome in (outcomes or {}).items():
+ self.script(permission, outcome)
+
+ # ----------------------------------------------------------- scripting
+
+ def script(
+ self, permission: PermissionId | str, *outcomes: PermissionOutcome | str | EnsureResult
+ ) -> None:
+ """Script the answers for one permission.
+
+ One outcome is sticky. Several are served one per ``ensure`` call, and the
+ last one sticks. A ready-made :class:`EnsureResult` is returned as it is.
+ """
+ perm = PANE_FAMILY[PermissionId(permission)]
+ if not outcomes:
+ raise ValueError("script() needs at least one outcome")
+ resolved = [
+ item if isinstance(item, EnsureResult) else PermissionOutcome(str(item))
+ for item in outcomes
+ ]
+ self._sticky[perm] = resolved[-1]
+ self._queued[perm] = deque(resolved[:-1])
+
+ def grant(self, permission: PermissionId | str) -> None:
+ """The user allowed it: every later answer is GRANTED."""
+ self.script(permission, PermissionOutcome.GRANTED)
+
+ def _head(self, permission: PermissionId) -> PermissionOutcome | EnsureResult:
+ permission = PANE_FAMILY[permission]
+ queue = self._queued.get(permission)
+ if queue:
+ return queue[0]
+ return self._sticky.get(permission, self._default)
+
+ def _next(self, permission: PermissionId) -> PermissionOutcome | EnsureResult:
+ permission = PANE_FAMILY[permission]
+ queue = self._queued.get(permission)
+ if queue:
+ return queue.popleft()
+ return self._sticky.get(permission, self._default)
+
+ # ----------------------------------------------------------- the gate
+
+ def check(
+ self, permission: PermissionId | str, *, target: str | None = None
+ ) -> PermissionState:
+ perm = PermissionId(permission)
+ self.calls.append(GateCall("check", perm, target=target))
+ head = self._head(perm)
+ if isinstance(head, EnsureResult):
+ return head.state
+ return _STATE_OF_OUTCOME[head]
+
+ def ensure(
+ self,
+ permission: PermissionId | str,
+ *,
+ feature: str,
+ interactive: bool = True,
+ wait_s: float = 0.0,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ allow_outside_app: bool = False,
+ force_ask: bool = False,
+ ) -> EnsureResult:
+ return self._answer(
+ "ensure",
+ permission,
+ feature=feature,
+ interactive=interactive,
+ wait_s=wait_s,
+ target=target,
+ trace_id=trace_id,
+ allow_outside_app=allow_outside_app,
+ force_ask=force_ask,
+ )
+
+ async def ensure_async(
+ self,
+ permission: PermissionId | str,
+ *,
+ feature: str,
+ interactive: bool = True,
+ wait_s: float = 0.0,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ allow_outside_app: bool = False,
+ force_ask: bool = False,
+ ) -> EnsureResult:
+ return self._answer(
+ "ensure_async",
+ permission,
+ feature=feature,
+ interactive=interactive,
+ wait_s=wait_s,
+ target=target,
+ trace_id=trace_id,
+ allow_outside_app=allow_outside_app,
+ force_ask=force_ask,
+ )
+
+ def ensure_all(self, permissions: Any, *, feature: str, **kwargs: Any) -> list[EnsureResult]:
+ """One ``ensure`` per permission, in order (the fake has no episodes)."""
+ return [self.ensure(perm, feature=feature, **kwargs) for perm in permissions]
+
+ def open_settings(self, permission: PermissionId | str) -> bool:
+ perm = PermissionId(permission)
+ self.calls.append(GateCall("open_settings", perm))
+ return self.settings_opens
+
+ def report_failed_use(
+ self,
+ permission: PermissionId | str,
+ *,
+ feature: str,
+ target: str | None = None,
+ trace_id: UUID | str | None = None,
+ reason: str | None = None,
+ origin: str | None = None,
+ ) -> EnsureResult:
+ """Record a failed-use report; it never asks, so the call is not ``interactive``.
+
+ The real service describes the Automation case (a send refused with -1743 while
+ the probe reads granted) as NEEDS_SETTINGS with reason ``needs_settings``, and
+ so does this fake. Any other permission answers like a non-interactive
+ ``ensure`` (the real service does the same for a state that does not fit; the
+ Screen Recording and Input Monitoring ``restart_hint`` is not modelled here).
+ """
+ perm = PermissionId(permission)
+ self.calls.append(
+ GateCall(
+ "report_failed_use",
+ perm,
+ feature=feature,
+ interactive=False,
+ target=target,
+ trace_id=trace_id,
+ reason=reason,
+ origin=origin,
+ )
+ )
+ if PANE_FAMILY[perm] is PermissionId.AUTOMATION:
+ self._reported_failures.add((PermissionId.AUTOMATION, feature, target or ""))
+ return make_result(
+ perm,
+ PermissionOutcome.NEEDS_SETTINGS,
+ target=target or "",
+ state=PermissionState.GRANTED,
+ )
+ scripted = self._next(perm)
+ if isinstance(scripted, EnsureResult):
+ return scripted
+ return make_result(perm, scripted, target=target or "")
+
+ def report_use_ok(
+ self, permission: PermissionId | str, *, feature: str, target: str | None = None
+ ) -> bool:
+ """Record a use that worked; ``True`` when it ended a reported failed use."""
+ perm = PermissionId(permission)
+ self.calls.append(
+ GateCall("report_use_ok", perm, feature=feature, interactive=False, target=target)
+ )
+ key = (PANE_FAMILY[perm], feature, target or "")
+ if key in self._reported_failures:
+ self._reported_failures.discard(key)
+ return True
+ return False
+
+ def _answer(
+ self,
+ method: str,
+ permission: PermissionId | str,
+ *,
+ feature: str,
+ interactive: bool,
+ wait_s: float,
+ target: str | None,
+ trace_id: UUID | str | None,
+ allow_outside_app: bool,
+ force_ask: bool,
+ ) -> EnsureResult:
+ perm = PermissionId(permission)
+ self.calls.append(
+ GateCall(
+ method,
+ perm,
+ feature=feature,
+ interactive=interactive,
+ wait_s=wait_s,
+ target=target,
+ trace_id=trace_id,
+ allow_outside_app=allow_outside_app,
+ force_ask=force_ask,
+ )
+ )
+ scripted = self._next(perm)
+ if isinstance(scripted, EnsureResult):
+ return scripted
+ return make_result(
+ perm,
+ scripted,
+ asked=interactive and scripted in _ASKING_OUTCOMES,
+ target=target or "",
+ )
+
+ # ---------------------------------------------------------- inspection
+
+ def ensure_calls(self, permission: PermissionId | str | None = None) -> list[GateCall]:
+ """Every ``ensure`` / ``ensure_async`` call, optionally for one permission."""
+ wanted = PermissionId(permission) if permission is not None else None
+ return [
+ call
+ for call in self.calls
+ if call.method in ("ensure", "ensure_async")
+ and (wanted is None or call.permission is wanted)
+ ]
+
+ def check_calls(self, permission: PermissionId | str | None = None) -> list[GateCall]:
+ wanted = PermissionId(permission) if permission is not None else None
+ return [
+ call
+ for call in self.calls
+ if call.method == "check" and (wanted is None or call.permission is wanted)
+ ]
+
+ def report_calls(self, method: str | None = None) -> list[GateCall]:
+ """Every ``report_failed_use`` / ``report_use_ok`` call, optionally of one kind."""
+ return [
+ call
+ for call in self.calls
+ if call.method in ("report_failed_use", "report_use_ok")
+ and (method is None or call.method == method)
+ ]
+
+ def native_free(self) -> bool:
+ """``True`` when no call could have made macOS ask (``check`` or ``interactive=False``)."""
+ return all(
+ call.method in ("check", "open_settings") or not call.interactive for call in self.calls
+ )
+
+
+__all__ = ["FakePermissionService", "GateCall", "make_result"]
diff --git a/tests/fakes/fake_quartz_tap.py b/tests/fakes/fake_quartz_tap.py
new file mode 100644
index 0000000000..898b14d94f
--- /dev/null
+++ b/tests/fakes/fake_quartz_tap.py
@@ -0,0 +1,131 @@
+"""A ``Quartz`` module stand-in whose event tap is a ``FakeEventTap``.
+
+``QuartzHotkeyBackend.start`` imports ``Quartz`` lazily and calls
+``CGEventTapCreate``. This builds a module with exactly the names the backend
+touches, wired to ``tests/fakes/fake_tcc.FakeEventTap`` so the tap consults the
+stateful ``FakeTCC``: created without the grant it fails or goes deaf, created
+before the user was asked it auto-denies (the BUG-058 class), and every creation
+lands in the ``FakeTCC`` call log. Events are delivered through
+``FakeQuartz.deliver_*``, which only reaches the backend's callback while the
+fake tap is live, like the real one.
+
+Nothing here is macOS behaviour that has been observed on a Mac; the fidelity
+labels of ``fake_tcc`` apply.
+"""
+
+from __future__ import annotations
+
+import sys
+import threading
+import types
+from typing import Any
+
+from tests.fakes.fake_tcc import FakeEventTap, FakeTCC
+
+_KEY_DOWN, _KEY_UP, _FLAGS_CHANGED = 10, 11, 12
+_DISABLED_BY_TIMEOUT, _DISABLED_BY_USER = 13, 14
+
+
+class _Handle:
+ def __init__(self) -> None:
+ self.enabled = False
+ self.invalidated = False
+
+
+class _Loop:
+ def __init__(self) -> None:
+ self.stopped = False
+ self.wake = threading.Event()
+
+
+class FakeQuartz:
+ """The module (``.module``) plus the hooks a test drives it with."""
+
+ def __init__(self, tcc: FakeTCC, *, caller: str = "quartz-backend") -> None:
+ self.tcc = tcc
+ self.tap = FakeEventTap(tcc, caller=caller)
+ self.created: list[_Handle] = []
+ self.callback: Any = None
+ self._local = threading.local()
+ self.module = self._build()
+
+ # -- event delivery ---------------------------------------------------
+
+ def deliver_key(self, keycode: int, *, down: bool = True) -> bool:
+ """A key goes down (or up). ``True`` when the backend's callback ran."""
+ return self._deliver(_KEY_DOWN if down else _KEY_UP, keycode, 0)
+
+ def deliver_flags(self, flags: int) -> bool:
+ """A modifier flags change. ``True`` when the backend's callback ran."""
+ return self._deliver(_FLAGS_CHANGED, 0, flags)
+
+ def _deliver(self, event_type: int, keycode: int, flags: int) -> bool:
+ if self.callback is None or not self.tap.receives_events:
+ return False
+ self.tap.events_received += 1
+ event = types.SimpleNamespace(keycode=keycode, flags=flags)
+ self.callback(None, event_type, event, None)
+ return True
+
+ # -- the module -------------------------------------------------------
+
+ def _build(self) -> types.ModuleType:
+ quartz = types.ModuleType("Quartz")
+ quartz.kCGEventKeyDown = _KEY_DOWN
+ quartz.kCGEventKeyUp = _KEY_UP
+ quartz.kCGEventFlagsChanged = _FLAGS_CHANGED
+ quartz.kCGEventTapDisabledByTimeout = _DISABLED_BY_TIMEOUT
+ quartz.kCGEventTapDisabledByUserInput = _DISABLED_BY_USER
+ quartz.kCGKeyboardEventKeycode = 15
+ quartz.kCGSessionEventTap = 16
+ quartz.kCGHeadInsertEventTap = 17
+ quartz.kCGEventTapOptionListenOnly = 18
+ quartz.kCFRunLoopCommonModes = "common"
+ quartz.CGEventMaskBit = lambda value: 1 << value
+
+ def tap_create(_location, _placement, _options, _mask, callback, _refcon):
+ self.callback = callback
+ if not self.tap.create(None, listen_only=True):
+ return None
+ handle = _Handle()
+ self.created.append(handle)
+ return handle
+
+ def get_loop():
+ loop = _Loop()
+ self._local.loop = loop
+ return loop
+
+ def run_loop():
+ loop = self._local.loop
+ while not loop.stopped:
+ loop.wake.wait()
+ loop.wake.clear()
+
+ def stop_loop(loop):
+ loop.stopped = True
+
+ def wake_loop(loop):
+ loop.wake.set()
+
+ quartz.CGEventTapCreate = tap_create
+ quartz.CFMachPortCreateRunLoopSource = lambda _alloc, tap, _order: ("source", tap)
+ quartz.CFRunLoopGetCurrent = get_loop
+ quartz.CFRunLoopAddSource = lambda _loop, _source, _mode: None
+ quartz.CFRunLoopRun = run_loop
+ quartz.CFRunLoopStop = stop_loop
+ quartz.CFRunLoopWakeUp = wake_loop
+ quartz.CFRunLoopRemoveSource = lambda _loop, _source, _mode: None
+ quartz.CGEventTapEnable = lambda handle, enabled: setattr(handle, "enabled", enabled)
+ quartz.CFMachPortInvalidate = lambda handle: setattr(handle, "invalidated", True)
+ quartz.CGEventGetIntegerValueField = lambda event, _field: event.keycode
+ quartz.CGEventGetFlags = lambda event: event.flags
+ return quartz
+
+ def install(self, monkeypatch: Any) -> FakeQuartz:
+ """Make ``import Quartz`` resolve to this module for the test."""
+ monkeypatch.setitem(sys.modules, "Quartz", self.module)
+ return self
+
+
+__all__ = ["FakeQuartz"]
diff --git a/tests/fakes/fake_screen_pixels.py b/tests/fakes/fake_screen_pixels.py
new file mode 100644
index 0000000000..3cd2c4f525
--- /dev/null
+++ b/tests/fakes/fake_screen_pixels.py
@@ -0,0 +1,91 @@
+"""Pixels for ``FakeScreenGrab``: what a capture consumer actually receives.
+
+``FakeScreenGrab`` (``tests/fakes/fake_tcc.py``) says whether a simulated capture
+saw other apps' windows or only the wallpaper. A consumer receives pixels, so this
+module turns that verdict into RGB bytes: textured content for a real capture and a
+single flat colour for the wallpaper-only frame macOS returns, without an error,
+for a capture it does not allow (unverified; see the fidelity ledger in
+``fake_tcc.py``).
+
+Usage::
+
+ grab = pixels_grabber(FakeScreenGrab(tcc)) # a ``Grabber``: bbox -> ((w, h), rgb)
+ capture_stable_frame(monitor, grab=grab)
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+
+from tests.fakes.fake_tcc import FakeScreenGrab
+
+#: The flat colour of a wallpaper-only frame.
+WALLPAPER_RGB: tuple[int, int, int] = (12, 40, 90)
+
+
+def textured_pixels(size: tuple[int, int]) -> tuple[tuple[int, int], bytes]:
+ """RGB bytes with real contrast everywhere (a diagonal gradient with stripes)."""
+ width, height = size
+ data = bytearray(width * height * 3)
+ for y in range(height):
+ for x in range(width):
+ offset = (y * width + x) * 3
+ data[offset] = (x * 255 // max(1, width - 1)) & 0xFF
+ data[offset + 1] = (y * 255 // max(1, height - 1)) & 0xFF
+ data[offset + 2] = 255 if (x // 8 + y // 8) % 2 else 40
+ return (width, height), bytes(data)
+
+
+def wallpaper_pixels(size: tuple[int, int]) -> tuple[tuple[int, int], bytes]:
+ """RGB bytes of a wallpaper-only frame: one flat colour."""
+ width, height = size
+ return (width, height), bytes(WALLPAPER_RGB) * (width * height)
+
+
+def photo_wallpaper_pixels(size: tuple[int, int]) -> tuple[tuple[int, int], bytes]:
+ """RGB bytes of a photographic wallpaper: smooth gradients, no flat colour.
+
+ macOS ships photographic and dynamic wallpapers by default, so a wallpaper-only
+ capture is usually NOT one flat colour; a sanity check that only looks for
+ blankness would accept it.
+ """
+ width, height = size
+ data = bytearray(width * height * 3)
+ for y in range(height):
+ for x in range(width):
+ offset = (y * width + x) * 3
+ data[offset] = 20 + (x * 120 // max(1, width - 1))
+ data[offset + 1] = 60 + (y * 100 // max(1, height - 1))
+ data[offset + 2] = 140 + ((x + y) * 80 // max(1, width + height - 2))
+ return (width, height), bytes(data)
+
+
+def pixels_grabber(
+ screen: FakeScreenGrab,
+ *,
+ size: tuple[int, int] = (192, 108),
+ photo_wallpaper: bool = False,
+) -> Callable[[dict[str, int]], tuple[tuple[int, int], bytes]]:
+ """A ``Grabber`` whose pixels follow ``screen``: wallpaper unless macOS allows it.
+
+ Every call goes through ``screen.grab()``, so the ``FakeTCC`` call log shows an
+ implicit prompt if the service was still ``not_determined`` at that moment.
+ ``photo_wallpaper`` makes the wallpaper-only frame a smooth gradient instead of
+ one flat colour.
+ """
+ wallpaper = photo_wallpaper_pixels if photo_wallpaper else wallpaper_pixels
+
+ def grab(_bbox: dict[str, int]) -> tuple[tuple[int, int], bytes]:
+ frame = screen.grab()
+ return wallpaper(size) if frame.wallpaper_only else textured_pixels(size)
+
+ return grab
+
+
+__all__ = [
+ "WALLPAPER_RGB",
+ "photo_wallpaper_pixels",
+ "pixels_grabber",
+ "textured_pixels",
+ "wallpaper_pixels",
+]
diff --git a/tests/fakes/fake_tcc.py b/tests/fakes/fake_tcc.py
new file mode 100644
index 0000000000..3ca775a4b2
--- /dev/null
+++ b/tests/fakes/fake_tcc.py
@@ -0,0 +1,1389 @@
+"""FakeTCC: a stateful, framework-level simulator of macOS privacy (TCC).
+
+Per AGENTS.md the project uses real fakes, never ``unittest.mock``. Nobody can
+run macOS in CI-less sandboxes, and a static ``SimpleNamespace`` per test (the
+style of ``tests/unit/platform/test_permissions.py``) cannot model what makes
+macOS permissions hard: a per-service state machine, a dialog that the user
+answers (or never answers), no second question after a decision, a Screen
+Recording preflight that stays frozen until relaunch, and APIs that make macOS
+show a dialog BY THEMSELVES. This module models exactly those, one level below
+the product: it builds the ``module_loader`` dict (Foundation, AppKit,
+AVFoundation, Quartz, ApplicationServices) plus every seam of
+``SystemPermissionPort`` (``iohid_check``, ``screen_capture_live_check``,
+``automation_probe``, the credential-store pair), so the REAL port and, later,
+the REAL permission service run on top of it.
+
+Every framework call lands in one ordered call log (``FakeTCC.calls``):
+
+* ``probe`` - a read of a permission state; macOS never shows a dialog.
+* ``request`` - an explicit prompt API (``requestAccessForMedia...``,
+ ``CGRequest*Access``, ``AXIsProcessTrustedWithOptions``
+ with the prompt option, ``AEDeterminePermission...`` with
+ ``askUserIfNeeded``).
+* ``implicit_prompt`` - a call that makes macOS show a dialog BY ITSELF: opening
+ an input stream or grabbing the screen while the service
+ is ``not_determined``, creating an event tap before the
+ user was asked. Consumer tests assert there is none.
+
+The ``outcome`` of a ``request`` says what macOS did with it. A request after a
+decision is recorded as ``ignored_request`` (macOS does not re-ask), which makes
+a re-prompt loop visible in the log.
+
+Fidelity ledger. Each simulated behaviour carries one of two labels, here and
+in the code. Nobody can run macOS in this sandbox, so nothing below is
+"verified on a real Mac"; a behaviour marked ``documented`` is stated by Apple,
+one marked ``unverified`` is community-observed or inferred from this repo's
+own bug history (docs/BUGS.md) and must not be quoted as fact.
+
+* Microphone: tri-state status, prompt only while ``not_determined``, the
+ completion handler reports the current answer when already decided; missing
+ ``NSMicrophoneUsageDescription`` aborts the process - documented. Denied
+ microphone yields digital silence instead of an error - unverified.
+* Screen Recording: ``CGPreflightScreenCaptureAccess`` /
+ ``CGRequestScreenCaptureAccess`` exist (10.15+) - documented. The preflight
+ value is frozen until relaunch (BUG-161) and a capture without the grant
+ returns wallpaper-only windows instead of an error - unverified. Whether a
+ grant given mid-process works for capture before relaunch is an open
+ conflict, so both worlds are available (``screen_grant_needs_relaunch``).
+* Accessibility: boolean trust, no ``not_determined`` - documented. Whether the
+ prompt API shows again while still untrusted is an open conflict, so both
+ worlds are available (``ax_reprompts_while_untrusted``) - unverified.
+* Input Monitoring: ``CGPreflightListenEventAccess`` / ``CGRequest...`` /
+ ``IOHIDCheckAccess`` (tri-state) - documented. "A listen tap created before
+ the request registers the app as denied" (BUG-058 class) and "an Accessibility
+ grant also lets a listen-only tap work" - unverified.
+* Event posting is modelled as an alias of Accessibility (one switch, one
+ state) - unverified.
+* Automation: ``-600`` (target not running), ``-1743`` (denied), ``-1744``
+ (consent needed), a blocking dialog with ``askUserIfNeeded`` - documented.
+* No re-ask after a decision: documented for the microphone, unverified (but
+ consistent with this repo's own observations) for the other services.
+* A dialog the user dismisses without answering: unverified (a DIALOG-class
+ service stays ``not_determined``; a PROMPT-ONCE service ends ``denied``).
+* ``tccutil reset <Service> <bundle id>`` returns that bundle's row to
+ ``not_determined`` and touches no other app's row - documented (man page).
+* Which APIs raise an implicit prompt (input stream start, screen capture,
+ listen-tap creation) - the first-access prompt is documented, the exact API
+ set is unverified.
+
+Companions ``FakeAudioInput`` / ``FakeEventTap`` / ``FakeScreenGrab`` consult the
+same ``FakeTCC`` when "opened", so a consumer test can assert that nothing made
+macOS prompt behind the feature's back.
+"""
+
+from __future__ import annotations
+
+import threading
+from collections import deque
+from collections.abc import Callable, Iterable, Mapping
+from dataclasses import dataclass
+from enum import StrEnum
+from types import SimpleNamespace
+from typing import Any, Final, Literal
+
+from jarvis.core.branding import MACOS_APP_NAME, MACOS_BUNDLE_ID, MACOS_DMG_BUNDLE_ID
+from jarvis.platform import PlatformName
+from jarvis.platform.permissions import AUTOMATION_TARGETS, SystemPermissionPort
+
+INSTALLED_BUNDLE_ID: Final = MACOS_BUNDLE_ID
+DMG_BUNDLE_ID: Final = MACOS_DMG_BUNDLE_ID
+TERMINAL_BUNDLE_ID: Final = "com.apple.Terminal"
+INSTALLED_BUNDLE_PATH: Final = f"/Applications/{MACOS_APP_NAME}.app"
+
+# Apple Event Manager OSStatus values (AE headers; stable ABI) - documented.
+AE_NO_ERR: Final = 0
+AE_PROC_NOT_FOUND: Final = -600
+AE_EVENT_NOT_PERMITTED: Final = -1743
+AE_EVENT_WOULD_REQUIRE_USER_CONSENT: Final = -1744
+
+# IOHIDCheckAccess tri-state - documented (IOKit/hidsystem/IOHIDLib.h).
+_IOHID_GRANTED: Final = 0
+_IOHID_DENIED: Final = 1
+_IOHID_UNKNOWN: Final = 2
+_IOHID_REQUEST_POST_EVENT: Final = 0
+_IOHID_REQUEST_LISTEN_EVENT: Final = 1
+
+# AVAuthorizationStatus - documented.
+_AV_STATUS: Final = {"not_determined": 0, "restricted": 1, "denied": 2, "granted": 3}
+
+# ``kAXTrustedCheckOptionPrompt`` is the CFString "AXTrustedCheckOptionPrompt".
+_AX_PROMPT_KEY: Final = "AXTrustedCheckOptionPrompt"
+
+# Info.plist purpose strings for the services Jarvis may ask for. The Screen
+# Recording key is shipped for parity; whether macOS reads it is unverified.
+_USAGE_KEYS: Final = {
+ "microphone": "NSMicrophoneUsageDescription",
+ "automation": "NSAppleEventsUsageDescription",
+ "screen_recording": "NSScreenCaptureUsageDescription",
+}
+
+
+class TccService(StrEnum):
+ """The services this fake models; values equal ``PermissionId`` values."""
+
+ MICROPHONE = "microphone"
+ SCREEN_RECORDING = "screen_recording"
+ ACCESSIBILITY = "accessibility"
+ INPUT_MONITORING = "input_monitoring"
+ POST_EVENT = "event_posting"
+ AUTOMATION = "automation"
+
+
+class TccState(StrEnum):
+ """What the TCC database holds for one service (and, for automation, target).
+
+ Accessibility has no ``NOT_DETERMINED`` (boolean trust): an untrusted process
+ reads ``DENIED``. Documented.
+ """
+
+ NOT_DETERMINED = "not_determined"
+ GRANTED = "granted"
+ DENIED = "denied"
+ RESTRICTED = "restricted"
+
+
+class DialogPolicy(StrEnum):
+ """What the simulated user does with the next dialog.
+
+ ``ALLOW`` / ``DENY``: answer it (for a PROMPT-ONCE service ``ALLOW`` means the
+ user opened System Settings and flipped the switch). ``DISMISS``: close it
+ without an answer. ``NEVER_ANSWERED``: it stays on screen until the test
+ calls :meth:`FakeTCC.answer`.
+ """
+
+ ALLOW = "allow"
+ DENY = "deny"
+ DISMISS = "dismiss"
+ NEVER_ANSWERED = "never_answered"
+
+
+class CallKind(StrEnum):
+ PROBE = "probe"
+ REQUEST = "request"
+ IMPLICIT_PROMPT = "implicit_prompt"
+
+
+class CallOutcome(StrEnum):
+ """What macOS did with a logged call."""
+
+ READ = "read" # a probe: state returned, nothing shown
+ DIALOG_SHOWN = "dialog_shown"
+ IGNORED_REQUEST = "ignored_request" # a decision is on file: no dialog
+ DIALOG_ALREADY_OPEN = "dialog_already_open"
+ RESTRICTED = "restricted" # device policy: no dialog, never granted
+ AUTO_DENIED = "auto_denied" # listen tap created before the request
+ TARGET_NOT_RUNNING = "target_not_running" # Automation: -600
+ PROCESS_ABORT = "process_abort" # missing purpose string killed the process
+
+
+# DIALOG class: the OS dialog has an answer button (microphone, automation).
+# PROMPT-ONCE class: the dialog only offers "Open System Settings" (everything
+# else).
+_DIALOG_CLASS: Final = frozenset({TccService.MICROPHONE, TccService.AUTOMATION})
+
+_TCCUTIL_SERVICES: Final = {
+ "Microphone": TccService.MICROPHONE,
+ "ScreenCapture": TccService.SCREEN_RECORDING,
+ "Accessibility": TccService.ACCESSIBILITY,
+ "ListenEvent": TccService.INPUT_MONITORING,
+ "PostEvent": TccService.POST_EVENT,
+ "AppleEvents": TccService.AUTOMATION,
+}
+
+_Key = tuple[TccService, str]
+
+
+class TccProcessAbort(BaseException): # noqa: N818 - models SIGABRT, never an Exception
+ """Raised (only with ``abort_raises=True``) where macOS would kill the process.
+
+ A BaseException on purpose: a real SIGABRT cannot be caught by the
+ ``except Exception`` guards the port wraps around native calls.
+ """
+
+
+@dataclass(frozen=True, slots=True)
+class TccCall:
+ """One framework call, in the order it happened."""
+
+ seq: int
+ kind: CallKind
+ service: TccService
+ api: str
+ outcome: CallOutcome
+ thread: str
+ target: str = ""
+ caller: str = ""
+ state_before: TccState | None = None
+ state_after: TccState | None = None
+ detail: str = "" # the dialog policy that was applied, if a dialog ran
+ grantee: str = "" # the app macOS would name in the dialog
+
+ def describe(self) -> str:
+ target = f"[{self.target}]" if self.target else ""
+ caller = f" caller={self.caller}" if self.caller else ""
+ before = self.state_before.value if self.state_before else "-"
+ after = self.state_after.value if self.state_after else "-"
+ detail = f" ({self.detail})" if self.detail else ""
+ return (
+ f"#{self.seq} {self.kind.value} {self.service.value}{target} "
+ f"{self.api} -> {self.outcome.value}{detail} "
+ f"{before}->{after} thread={self.thread}{caller}"
+ )
+
+
+@dataclass(slots=True)
+class _Pending:
+ """A dialog that is on screen and not answered yet."""
+
+ handlers: list[Callable[[bool], None]]
+
+
+def _service(value: TccService | str) -> TccService:
+ return TccService(str(value))
+
+
+class FakeTCC:
+ """A stateful macOS TCC simulator that plugs into ``SystemPermissionPort``.
+
+ See the module docstring for the call log and the fidelity ledger.
+ """
+
+ def __init__(
+ self,
+ *,
+ bundle_id: str | None = INSTALLED_BUNDLE_ID,
+ bundle_path: str | None = INSTALLED_BUNDLE_PATH,
+ responsible_app_if_unbundled: str = TERMINAL_BUNDLE_ID,
+ granted: Iterable[TccService | str] = (),
+ default_policy: DialogPolicy = DialogPolicy.ALLOW,
+ usage_strings: Iterable[TccService | str] = (
+ TccService.MICROPHONE,
+ TccService.AUTOMATION,
+ TccService.SCREEN_RECORDING,
+ ),
+ foreground: bool = True,
+ headless: bool = False,
+ preflight_frozen: Iterable[TccService | str] = (TccService.SCREEN_RECORDING,),
+ ax_reprompts_while_untrusted: bool = True,
+ screen_grant_needs_relaunch: bool = False,
+ silent_tap_when_denied: bool = False,
+ abort_raises: bool = False,
+ installed_players: Iterable[str] = (),
+ running_players: Iterable[str] = (),
+ credential_backend: str = "platform",
+ missing_frameworks: Iterable[str] = (),
+ ) -> None:
+ self.bundle_id = bundle_id
+ self.bundle_path = bundle_path
+ self.responsible_app_if_unbundled = responsible_app_if_unbundled
+ self.foreground = foreground
+ self.headless = headless
+ self.credential_backend = credential_backend
+ self.keychain_recover_calls = 0
+ self.keychain_recover_result = True
+ self.default_policy = default_policy
+ self._usage_strings = frozenset(_service(item) for item in usage_strings)
+ self._preflight_frozen = frozenset(_service(item) for item in preflight_frozen)
+ self._ax_reprompts = ax_reprompts_while_untrusted
+ self._screen_needs_relaunch = screen_grant_needs_relaunch
+ self._silent_tap_when_denied = silent_tap_when_denied
+ self._abort_raises = abort_raises
+ self._missing_frameworks = set(missing_frameworks)
+ self._lock = threading.RLock()
+ self._calls: list[TccCall] = []
+ self.loaded_modules: list[str] = []
+ self.tccutil_calls: list[list[str]] = []
+ self.launches: list[tuple[str, bool | None, bool | None]] = []
+ self._states: dict[_Key, TccState] = {}
+ self._pending: dict[_Key, _Pending] = {}
+ self._asked: set[_Key] = set()
+ self._policy_default: dict[_Key, DialogPolicy] = {}
+ self._policy_queue: dict[_Key, deque[DialogPolicy]] = {}
+ self._installed = set(installed_players)
+ self._running = set(running_players)
+ self._launch_view: dict[_Key, TccState] = {}
+ self._launch_count = 0
+ # Taps die with the process: a tap remembers the generation it was born in.
+ self._generation = 0
+ self.workspace_opened_urls: list[str] = []
+
+ for service in TccService:
+ if service is TccService.POST_EVENT:
+ continue # alias of Accessibility, no state of its own
+ initial = (
+ TccState.DENIED if service is TccService.ACCESSIBILITY else TccState.NOT_DETERMINED
+ )
+ self._states[(service, "")] = initial
+ for item in granted:
+ service = _service(item)
+ if service is TccService.AUTOMATION:
+ for _name, target in AUTOMATION_TARGETS:
+ self._states[(TccService.AUTOMATION, target)] = TccState.GRANTED
+ else:
+ self._states[self._key(service)] = TccState.GRANTED
+ self.modules: dict[str, Any] = self._build_modules()
+ self._snapshot_launch()
+
+ # ------------------------------------------------------------------ identity
+
+ @property
+ def launched_as_bundle(self) -> bool:
+ return bool(self.bundle_path and ".app/" in f"{self.bundle_path}/")
+
+ @property
+ def grantee(self) -> str:
+ """The app macOS records grants against and names in the dialog.
+
+ An installed bundle is its own client. A process started from a terminal
+ is attributed to the terminal - community-observed, Apple documents no
+ algorithm for child processes - unverified.
+ """
+ if self.launched_as_bundle and self.bundle_id:
+ return self.bundle_id
+ return self.responsible_app_if_unbundled
+
+ @property
+ def launch_count(self) -> int:
+ return self._launch_count
+
+ # ------------------------------------------------------------------ call log
+
+ @property
+ def calls(self) -> tuple[TccCall, ...]:
+ with self._lock:
+ return tuple(self._calls)
+
+ def mark(self) -> int:
+ """A position in the log; pair with :meth:`calls_since`."""
+ with self._lock:
+ return len(self._calls)
+
+ def calls_since(self, mark: int) -> tuple[TccCall, ...]:
+ with self._lock:
+ return tuple(self._calls[mark:])
+
+ def clear_log(self) -> None:
+ with self._lock:
+ self._calls.clear()
+ self.loaded_modules.clear()
+
+ def calls_of(
+ self,
+ kind: CallKind | str | None = None,
+ service: TccService | str | None = None,
+ *,
+ target: str | None = None,
+ since: int = 0,
+ ) -> list[TccCall]:
+ wanted_kind = CallKind(str(kind)) if kind is not None else None
+ wanted_service = _service(service) if service is not None else None
+ return [
+ call
+ for call in self.calls_since(since)
+ if (wanted_kind is None or call.kind is wanted_kind)
+ and (wanted_service is None or call.service is wanted_service)
+ and (target is None or call.target == target)
+ ]
+
+ def kinds(self) -> list[str]:
+ return [call.kind.value for call in self.calls]
+
+ def probes(self, service: TccService | str | None = None) -> list[TccCall]:
+ return self.calls_of(CallKind.PROBE, service)
+
+ def requests(self, service: TccService | str | None = None) -> list[TccCall]:
+ """Every explicit request, ignored ones included."""
+ return self.calls_of(CallKind.REQUEST, service)
+
+ def implicit_prompts(self, service: TccService | str | None = None) -> list[TccCall]:
+ return self.calls_of(CallKind.IMPLICIT_PROMPT, service)
+
+ def ignored_requests(self, service: TccService | str | None = None) -> list[TccCall]:
+ return [
+ call
+ for call in self.calls_of(CallKind.REQUEST, service)
+ if call.outcome is CallOutcome.IGNORED_REQUEST
+ ]
+
+ def dialogs_shown(self, service: TccService | str | None = None) -> list[TccCall]:
+ return [
+ call
+ for call in self.calls
+ if call.outcome is CallOutcome.DIALOG_SHOWN
+ and (service is None or call.service is _service(service))
+ ]
+
+ def aborts(self) -> list[TccCall]:
+ return [call for call in self.calls if call.outcome is CallOutcome.PROCESS_ABORT]
+
+ def format_log(self) -> str:
+ return "\n".join(call.describe() for call in self.calls) or "(no framework call)"
+
+ def assert_silent(self) -> None:
+ """No framework was loaded and no call happened (the non-darwin contract)."""
+ with self._lock:
+ assert not self._calls and not self.loaded_modules, (
+ f"expected a silent TCC; loaded={self.loaded_modules}\n{self.format_log()}"
+ )
+
+ def assert_no_prompts(self, *, since: int = 0) -> None:
+ """No explicit request and no implicit prompt (the boot contract)."""
+ offending = [
+ call
+ for call in self.calls_since(since)
+ if call.kind in (CallKind.REQUEST, CallKind.IMPLICIT_PROMPT)
+ ]
+ assert not offending, "unexpected prompts:\n" + "\n".join(c.describe() for c in offending)
+
+ def _append(
+ self,
+ kind: CallKind,
+ service: TccService,
+ api: str,
+ outcome: CallOutcome,
+ *,
+ target: str = "",
+ caller: str = "",
+ before: TccState | None = None,
+ after: TccState | None = None,
+ detail: str = "",
+ ) -> TccCall:
+ with self._lock:
+ call = TccCall(
+ seq=len(self._calls),
+ kind=kind,
+ service=service,
+ api=api,
+ outcome=outcome,
+ thread=threading.current_thread().name,
+ target=target,
+ caller=caller,
+ state_before=before,
+ state_after=after,
+ detail=detail,
+ grantee=self.grantee,
+ )
+ self._calls.append(call)
+ return call
+
+ def _probe(
+ self,
+ service: TccService,
+ api: str,
+ *,
+ target: str = "",
+ outcome: CallOutcome = CallOutcome.READ,
+ caller: str = "",
+ ) -> None:
+ state = self._read(service, target)
+ self._append(
+ CallKind.PROBE,
+ service,
+ api,
+ outcome,
+ target=target,
+ caller=caller,
+ before=state,
+ after=state,
+ )
+
+ # ------------------------------------------------------------ state machine
+
+ @staticmethod
+ def _key(service: TccService, target: str = "") -> _Key:
+ # Event posting shares the Accessibility switch (unverified alias).
+ if service is TccService.POST_EVENT:
+ return (TccService.ACCESSIBILITY, "")
+ return (service, target if service is TccService.AUTOMATION else "")
+
+ def _read(self, service: TccService, target: str = "") -> TccState:
+ with self._lock:
+ return self._states.setdefault(self._key(service, target), TccState.NOT_DETERMINED)
+
+ def state(self, service: TccService | str, target: str = "") -> TccState:
+ """The TCC row, for assertions. Not a framework call, never logged."""
+ return self._read(_service(service), target)
+
+ def _set(self, service: TccService, state: TccState, target: str = "") -> None:
+ if service is TccService.AUTOMATION and not target:
+ raise ValueError("automation is per target: pass the player's bundle id")
+ handlers: list[Callable[[bool], None]] = []
+ key = self._key(service, target)
+ with self._lock:
+ self._states[key] = state
+ if state is TccState.DENIED:
+ self._asked.add(key)
+ pending = self._pending.pop(key, None)
+ if pending is not None:
+ handlers = pending.handlers
+ self._asked.add(key)
+ for handler in handlers:
+ handler(state is TccState.GRANTED)
+
+ def grant(self, service: TccService | str, target: str = "") -> None:
+ """The user flips the switch on in System Settings (live in TCC).
+
+ Does not touch a frozen preflight: that needs :meth:`relaunch`.
+ """
+ self._set(_service(service), TccState.GRANTED, target)
+
+ def deny(self, service: TccService | str, target: str = "") -> None:
+ """The user answered "Don't Allow" or flipped the switch off."""
+ self._set(_service(service), TccState.DENIED, target)
+
+ def restrict(self, service: TccService | str) -> None:
+ """Device policy (MDM) forbids the service; no dialog can ever grant it."""
+ self._set(_service(service), TccState.RESTRICTED)
+
+ def reset(self, service: TccService | str, target: str | None = None) -> None:
+ """``tccutil reset``: back to the state before the first question.
+
+ Accessibility has no ``not_determined`` and goes back to untrusted.
+ """
+ resolved = _service(service)
+ with self._lock:
+ if resolved is TccService.AUTOMATION and target is None:
+ keys = [key for key in self._states if key[0] is TccService.AUTOMATION]
+ keys.extend((TccService.AUTOMATION, t) for _name, t in AUTOMATION_TARGETS)
+ else:
+ keys = [self._key(resolved, target or "")]
+ for key in set(keys):
+ self._states[key] = (
+ TccState.DENIED
+ if key[0] is TccService.ACCESSIBILITY
+ else TccState.NOT_DETERMINED
+ )
+ self._pending.pop(key, None)
+ self._asked.discard(key)
+
+ def relaunch(self) -> None:
+ """Quit and reopen the app: frozen preflights refresh, taps and dialogs die."""
+ with self._lock:
+ self._launch_count += 1
+ self._generation += 1
+ self._pending.clear()
+ self._snapshot_launch()
+
+ def _snapshot_launch(self) -> None:
+ with self._lock:
+ self._launch_view = dict(self._states)
+ self._launch_count = max(self._launch_count, 1)
+
+ # ------------------------------------------------------------- dialog policy
+
+ def set_policy(
+ self, service: TccService | str, policy: DialogPolicy | str, target: str = ""
+ ) -> None:
+ """Sticky answer for every later dialog of this service (or target)."""
+ self._policy_default[self._key(_service(service), target)] = DialogPolicy(str(policy))
+
+ def script(
+ self, service: TccService | str, *policies: DialogPolicy | str, target: str = ""
+ ) -> None:
+ """Queue one answer per upcoming dialog; the sticky policy applies after."""
+ queue = self._policy_queue.setdefault(self._key(_service(service), target), deque())
+ queue.extend(DialogPolicy(str(policy)) for policy in policies)
+
+ def _next_policy(self, key: _Key) -> DialogPolicy:
+ queue = self._policy_queue.get(key)
+ if queue:
+ return queue.popleft()
+ if key in self._policy_default:
+ return self._policy_default[key]
+ service_wide = (key[0], "")
+ return self._policy_default.get(service_wide, self.default_policy)
+
+ def dialog_open(self, service: TccService | str, target: str = "") -> bool:
+ with self._lock:
+ return self._key(_service(service), target) in self._pending
+
+ def answer(
+ self,
+ service: TccService | str,
+ policy: DialogPolicy | str = DialogPolicy.ALLOW,
+ *,
+ target: str = "",
+ ) -> None:
+ """The user finally answers a ``NEVER_ANSWERED`` dialog."""
+ resolved = _service(service)
+ key = self._key(resolved, target)
+ with self._lock:
+ pending = self._pending.pop(key, None)
+ if pending is None:
+ raise LookupError(f"no open dialog for {resolved.value} {target}".strip())
+ granted = self._apply_policy(key, DialogPolicy(str(policy)))
+ if granted is not None:
+ for handler in pending.handlers:
+ handler(granted)
+
+ def _apply_policy(self, key: _Key, policy: DialogPolicy) -> bool | None:
+ """Apply the user's answer; ``None`` means no answer was given."""
+ service = key[0]
+ self._asked.add(key)
+ if policy is DialogPolicy.ALLOW:
+ self._states[key] = TccState.GRANTED
+ return True
+ if policy is DialogPolicy.DENY:
+ self._states[key] = TccState.DENIED
+ return False
+ # Dismissed (unverified): a DIALOG-class service keeps asking later; a
+ # PROMPT-ONCE service has already registered the app with its switch off.
+ if service not in _DIALOG_CLASS:
+ self._states[key] = TccState.DENIED
+ return None
+
+ def _bundled_without_purpose_string(self, service: TccService) -> bool:
+ # Documented for the microphone: a missing NSMicrophoneUsageDescription
+ # aborts the process (the BUG-058 SIGABRT class). A terminal-started
+ # process is covered by the terminal's own Info.plist.
+ return (
+ service is TccService.MICROPHONE
+ and self.launched_as_bundle
+ and service not in self._usage_strings
+ )
+
+ def _ask(
+ self,
+ service: TccService,
+ *,
+ api: str,
+ kind: CallKind,
+ target: str = "",
+ caller: str = "",
+ on_answer: Callable[[bool], None] | None = None,
+ ) -> CallOutcome:
+ """Run one request or implicit prompt through the state machine."""
+ key = self._key(service, target)
+ answer: bool | None = None
+ abort = False
+ with self._lock:
+ before = self._states.setdefault(key, TccState.NOT_DETERMINED)
+ detail = ""
+ if self._bundled_without_purpose_string(service):
+ outcome = CallOutcome.PROCESS_ABORT
+ abort = True
+ elif before is TccState.RESTRICTED:
+ outcome = CallOutcome.RESTRICTED
+ answer = False
+ elif key in self._pending:
+ outcome = CallOutcome.DIALOG_ALREADY_OPEN
+ if on_answer is not None:
+ self._pending[key].handlers.append(on_answer)
+ on_answer = None
+ elif self._decision_on_file(key, before):
+ # macOS does not re-ask after a decision. For the microphone the
+ # completion handler simply reports the current answer.
+ outcome = CallOutcome.IGNORED_REQUEST
+ answer = before is TccState.GRANTED
+ else:
+ policy = self._next_policy(key)
+ detail = policy.value
+ outcome = CallOutcome.DIALOG_SHOWN
+ if policy is DialogPolicy.NEVER_ANSWERED:
+ handlers = [on_answer] if on_answer is not None else []
+ self._pending[key] = _Pending(handlers=handlers)
+ on_answer = None
+ else:
+ answer = self._apply_policy(key, policy)
+ after = self._states[key]
+ self._append(
+ kind,
+ service,
+ api,
+ outcome,
+ target=target,
+ caller=caller,
+ before=before,
+ after=after,
+ detail=detail,
+ )
+ if abort and self._abort_raises:
+ raise TccProcessAbort(f"missing purpose string for {service.value}")
+ if on_answer is not None and answer is not None:
+ on_answer(answer)
+ return outcome
+
+ def _decision_on_file(self, key: _Key, state: TccState) -> bool:
+ if state is TccState.GRANTED:
+ return True
+ if key[0] is TccService.ACCESSIBILITY:
+ # No not_determined: DENIED means "untrusted". The first prompt always
+ # shows; a later one shows again only in the re-prompt world (unverified).
+ return state is TccState.DENIED and key in self._asked and not self._ax_reprompts
+ return state is TccState.DENIED
+
+ # ------------------------------------------------- effective grants (no log)
+
+ def _preflight_value(self, service: TccService) -> bool:
+ key = self._key(service)
+ if service in self._preflight_frozen:
+ return self._launch_view.get(key, TccState.NOT_DETERMINED) is TccState.GRANTED
+ return self._read(service) is TccState.GRANTED
+
+ def screen_capture_works(self) -> bool:
+ """Whether a capture right now sees other apps' windows. Not logged.
+
+ Without the grant a capture returns the wallpaper and no error
+ (unverified). Whether a mid-process grant already works before a
+ relaunch is an open conflict: ``screen_grant_needs_relaunch`` selects
+ the pessimistic world.
+ """
+ state = self._read(TccService.SCREEN_RECORDING)
+ if state is not TccState.GRANTED:
+ return False
+ if self._screen_needs_relaunch:
+ launch = self._launch_view.get((TccService.SCREEN_RECORDING, ""))
+ return launch is TccState.GRANTED
+ return True
+
+ def audio_input_is_audible(self) -> bool:
+ """Whether an open input stream carries real audio, else digital silence.
+
+ A denied microphone delivering zeros instead of an error is unverified.
+ """
+ return self._read(TccService.MICROPHONE) is TccState.GRANTED
+
+ # ------------------------------------------------------ companion consults
+
+ def consult_audio_input_start(self, caller: str = "") -> bool:
+ """An input stream starts. ``True`` when it will carry real audio.
+
+ While ``not_determined`` the start itself makes macOS ask (documented:
+ first capture prompts) - recorded as an implicit prompt.
+ """
+ if self._read(TccService.MICROPHONE) is TccState.NOT_DETERMINED:
+ self._ask(
+ TccService.MICROPHONE,
+ api="input stream start",
+ kind=CallKind.IMPLICIT_PROMPT,
+ caller=caller,
+ )
+ return self.audio_input_is_audible()
+
+ def consult_screen_grab(self, caller: str = "") -> bool:
+ """A capture starts. ``True`` when it sees other apps' windows."""
+ if self._read(TccService.SCREEN_RECORDING) is TccState.NOT_DETERMINED:
+ self._ask(
+ TccService.SCREEN_RECORDING,
+ api="screen capture",
+ kind=CallKind.IMPLICIT_PROMPT,
+ caller=caller,
+ )
+ return self.screen_capture_works()
+
+ def consult_listen_tap(
+ self, *, listen_only: bool = True, caller: str = ""
+ ) -> Literal["live", "silent", "failed"]:
+ """``CGEventTapCreate``.
+
+ Unverified rules: a listen-only tap works with Input Monitoring OR
+ Accessibility; created while Input Monitoring is ``not_determined`` (and
+ no Accessibility) it registers the app as DENIED with no dialog (BUG-058
+ class); denied, creation fails, or (``silent_tap_when_denied``) "succeeds"
+ and receives nothing. An active tap needs Accessibility.
+ """
+ with self._lock:
+ ax = self._read(TccService.ACCESSIBILITY)
+ monitoring = self._read(TccService.INPUT_MONITORING)
+ if ax is TccState.GRANTED:
+ return "live"
+ if listen_only and monitoring is TccState.GRANTED:
+ return "live"
+ if (
+ listen_only
+ and monitoring is TccState.NOT_DETERMINED
+ and (TccService.INPUT_MONITORING, "") not in self._pending
+ ):
+ self._states[(TccService.INPUT_MONITORING, "")] = TccState.DENIED
+ self._asked.add((TccService.INPUT_MONITORING, ""))
+ self._append(
+ CallKind.IMPLICIT_PROMPT,
+ TccService.INPUT_MONITORING,
+ "CGEventTapCreate",
+ CallOutcome.AUTO_DENIED,
+ caller=caller,
+ before=monitoring,
+ after=TccState.DENIED,
+ )
+ return "failed"
+ return "silent" if self._silent_tap_when_denied else "failed"
+
+ @property
+ def generation(self) -> int:
+ return self._generation
+
+ # ------------------------------------------------------------ framework API
+
+ def _require_audio(self, media_type: Any) -> None:
+ if media_type != "soun":
+ raise NotImplementedError("FakeTCC models the microphone only (AVMediaTypeAudio)")
+
+ def _av_status(self, media_type: Any) -> int:
+ self._require_audio(media_type)
+ self._probe(TccService.MICROPHONE, "authorizationStatusForMediaType:")
+ return _AV_STATUS[self._read(TccService.MICROPHONE).value]
+
+ def _av_request(self, media_type: Any, handler: Callable[[bool], None]) -> None:
+ self._require_audio(media_type)
+ self._ask(
+ TccService.MICROPHONE,
+ api="requestAccessForMediaType:completionHandler:",
+ kind=CallKind.REQUEST,
+ on_answer=handler,
+ )
+
+ def _cg_preflight(self, service: TccService, api: str) -> bool:
+ self._probe(service, api)
+ return self._preflight_value(service)
+
+ def _cg_request(self, service: TccService, api: str) -> bool:
+ # The requesters report the state at the moment of the call; the user
+ # answers later. Documented.
+ before = self._preflight_value(service)
+ self._ask(service, api=api, kind=CallKind.REQUEST)
+ return before
+
+ def _ax_trusted(self) -> bool:
+ self._probe(TccService.ACCESSIBILITY, "AXIsProcessTrusted")
+ return self._read(TccService.ACCESSIBILITY) is TccState.GRANTED
+
+ def _ax_trusted_with_options(self, options: Mapping[str, Any] | None) -> bool:
+ wants_prompt = bool(options and options.get(_AX_PROMPT_KEY))
+ if not wants_prompt:
+ self._probe(TccService.ACCESSIBILITY, "AXIsProcessTrustedWithOptions")
+ return self._read(TccService.ACCESSIBILITY) is TccState.GRANTED
+ before = self._read(TccService.ACCESSIBILITY) is TccState.GRANTED
+ self._ask(
+ TccService.ACCESSIBILITY,
+ api="AXIsProcessTrustedWithOptions(prompt)",
+ kind=CallKind.REQUEST,
+ )
+ return before
+
+ def iohid_check(self, request_type: int) -> int | None:
+ """Seam ``iohid_check``: the live tri-state of ``IOHIDCheckAccess``."""
+ service = (
+ TccService.INPUT_MONITORING
+ if request_type == _IOHID_REQUEST_LISTEN_EVENT
+ else TccService.POST_EVENT
+ )
+ self._probe(service, "IOHIDCheckAccess")
+ state = self._read(service)
+ if state is TccState.GRANTED:
+ return _IOHID_GRANTED
+ if state is TccState.NOT_DETERMINED:
+ return _IOHID_UNKNOWN
+ if service is TccService.POST_EVENT and self._key(service) not in self._asked:
+ # Accessibility has no not_determined, but the HID tri-state still
+ # reads "unknown" until the user was asked once - unverified.
+ return _IOHID_UNKNOWN
+ return _IOHID_DENIED
+
+ def iohid_request(self, request_type: int) -> bool:
+ """``IOHIDRequestAccess``; no port seam uses it yet."""
+ service = (
+ TccService.INPUT_MONITORING
+ if request_type == _IOHID_REQUEST_LISTEN_EVENT
+ else TccService.POST_EVENT
+ )
+ before = self._read(service) is TccState.GRANTED
+ self._ask(service, api="IOHIDRequestAccess", kind=CallKind.REQUEST)
+ return before
+
+ def screen_capture_live_check(self) -> bool | None:
+ """Seam ``screen_capture_live_check``: another app's window title is readable."""
+ self._probe(TccService.SCREEN_RECORDING, "window title oracle")
+ return True if self.screen_capture_works() else None
+
+ def automation_probe(self, bundle_id: str, ask: bool) -> int | None:
+ """Seam ``automation_probe``: ``AEDeterminePermissionToAutomateTarget``.
+
+ A real ``ask`` blocks until the user answers. A ``NEVER_ANSWERED`` dialog
+ would hang a test, so the call returns ``-1744`` at once (documented
+ deviation) and the dialog stays open for :meth:`answer`.
+ """
+ service = TccService.AUTOMATION
+ if bundle_id not in self._running:
+ self._append(
+ CallKind.REQUEST if ask else CallKind.PROBE,
+ service,
+ "AEDeterminePermissionToAutomateTarget",
+ CallOutcome.TARGET_NOT_RUNNING,
+ target=bundle_id,
+ )
+ return AE_PROC_NOT_FOUND
+ if ask:
+ self._ask(
+ service,
+ api="AEDeterminePermissionToAutomateTarget(ask)",
+ kind=CallKind.REQUEST,
+ target=bundle_id,
+ )
+ else:
+ self._probe(service, "AEDeterminePermissionToAutomateTarget", target=bundle_id)
+ state = self._read(service, bundle_id)
+ if state is TccState.GRANTED:
+ return AE_NO_ERR
+ if state in (TccState.DENIED, TccState.RESTRICTED):
+ return AE_EVENT_NOT_PERMITTED
+ return AE_EVENT_WOULD_REQUIRE_USER_CONSENT
+
+ def automation_consent_runner(self, script: str) -> SimpleNamespace:
+ """Seam ``automation_consent_runner``: the killable ``osascript`` child.
+
+ Stands in for ``subprocess.run(["osascript", "-e", script])`` of the
+ port's Automation request. The guarded script only sends its Apple Event
+ when the player RUNS, so a player that is not running is left alone and
+ nothing is asked (the AppleScript answers ``-``). The runner is
+ synchronous like the real child; a ``NEVER_ANSWERED`` dialog stays open
+ for :meth:`answer` exactly as in :meth:`automation_probe`.
+ """
+ for _name, bundle_id in AUTOMATION_TARGETS:
+ if f'"{bundle_id}"' not in script:
+ continue
+ running = bundle_id in self._running
+ if running:
+ self.automation_probe(bundle_id, True)
+ return SimpleNamespace(returncode=0, stdout="+" if running else "-", stderr="")
+ return SimpleNamespace(returncode=1, stdout="", stderr="unknown target")
+
+ # --------------------------------------------------------- credential store
+
+ def credential_store_backend(self) -> str:
+ return self.credential_backend
+
+ def credential_store_recover(self) -> bool:
+ self.keychain_recover_calls += 1
+ if self.keychain_recover_result:
+ self.credential_backend = "platform"
+ return self.keychain_recover_result
+
+ # ----------------------------------------------------------------- tccutil
+
+ def run_tccutil(self, argv: Iterable[str], **_kwargs: Any) -> SimpleNamespace:
+ """A ``subprocess.run`` stand-in for ``/usr/bin/tccutil reset <Service> <id>``.
+
+ Only the row of the NAMED bundle id is reset (documented); naming another
+ app's id leaves this app's rows alone.
+ """
+ command = [str(part) for part in argv]
+ self.tccutil_calls.append(command)
+ if len(command) != 4 or command[1] != "reset" or command[2] not in _TCCUTIL_SERVICES:
+ return SimpleNamespace(returncode=1, stdout="", stderr="tccutil: invalid arguments")
+ if command[3] == self.grantee:
+ self.reset(_TCCUTIL_SERVICES[command[2]])
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ # ------------------------------------------------------------------ players
+
+ def launch_player(self, bundle_id: str) -> None:
+ self._installed.add(bundle_id)
+ self._running.add(bundle_id)
+
+ def quit_player(self, bundle_id: str) -> None:
+ self._running.discard(bundle_id)
+
+ def player_running(self, bundle_id: str) -> bool:
+ return bundle_id in self._running
+
+ # ------------------------------------------------------ module loader / port
+
+ def module_loader(self, name: str) -> Any:
+ """Seam ``module_loader``: a framework the app imports lazily."""
+ with self._lock:
+ self.loaded_modules.append(name)
+ if name in self._missing_frameworks or name not in self.modules:
+ raise ModuleNotFoundError(name)
+ return self.modules[name]
+
+ def drop_framework(self, name: str) -> None:
+ """Make a framework unimportable, as on a build that did not bundle it."""
+ self._missing_frameworks.add(name)
+
+ def port(
+ self, platform_name: PlatformName = "darwin", **overrides: Any
+ ) -> SystemPermissionPort:
+ """A REAL ``SystemPermissionPort`` wired to every seam of this fake.
+
+ ``overrides`` replace single seams. A seam the port gains later and this
+ method does not pass keeps its production default, which on a real Mac
+ reads the machine's real state: extend this method when one is added.
+ """
+ seams: dict[str, Any] = {
+ "platform_name": platform_name,
+ "module_loader": self.module_loader,
+ "iohid_check": self.iohid_check,
+ "screen_capture_live_check": self.screen_capture_live_check,
+ "credential_store_backend": self.credential_store_backend,
+ "credential_store_recover": self.credential_store_recover,
+ "automation_probe": self.automation_probe,
+ "automation_consent_runner": self.automation_consent_runner,
+ "iohid_request": self.iohid_request,
+ }
+ seams.update(overrides)
+ return SystemPermissionPort(**seams)
+
+ def _build_modules(self) -> dict[str, Any]:
+ tcc = self
+ process_id = 4242
+
+ class _Bundle:
+ def bundleIdentifier(self) -> str | None: # noqa: N802 - Cocoa selector
+ return tcc.bundle_id
+
+ def bundlePath(self) -> str | None: # noqa: N802
+ return tcc.bundle_path
+
+ def objectForInfoDictionaryKey_(self, key: str) -> str | None: # noqa: N802
+ for service, plist_key in _USAGE_KEYS.items():
+ if plist_key == key and TccService(service) in tcc._usage_strings:
+ return f"Jarvis needs {service} access."
+ return None
+
+ def infoDictionary(self) -> dict[str, str]: # noqa: N802
+ return {
+ plist_key: f"Jarvis needs {service} access."
+ for service, plist_key in _USAGE_KEYS.items()
+ if TccService(service) in tcc._usage_strings
+ }
+
+ class _RunningApp:
+ def __init__(self, *, active: bool, pid: int) -> None:
+ self._active = active
+ self._pid = pid
+
+ def isActive(self) -> bool: # noqa: N802
+ return self._active
+
+ def processIdentifier(self) -> int: # noqa: N802
+ return self._pid
+
+ class _PlayerApp:
+ def __init__(self, bundle_id: str) -> None:
+ self.bundle_id = bundle_id
+
+ def terminate(self) -> None:
+ tcc.quit_player(self.bundle_id)
+
+ def isTerminated(self) -> bool: # noqa: N802
+ return not tcc.player_running(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: # noqa: N802
+ self.activates = value
+
+ def setHides_(self, value: bool) -> None: # noqa: N802
+ self.hides = value
+
+ _app_url = "file:///Applications/{}.app"
+
+ class _Workspace:
+ def frontmostApplication(self) -> _RunningApp | None: # noqa: N802
+ if tcc.headless:
+ return None
+ if tcc.foreground:
+ return _RunningApp(active=True, pid=process_id)
+ return _RunningApp(active=False, pid=process_id + 1)
+
+ def openURL_(self, url: str) -> bool: # noqa: N802
+ tcc.workspace_opened_urls.append(url)
+ return True
+
+ def URLForApplicationWithBundleIdentifier_( # noqa: N802
+ self, bundle_id: str
+ ) -> str | None:
+ return _app_url.format(bundle_id) if bundle_id in tcc._installed else None
+
+ def openApplicationAtURL_configuration_completionHandler_( # noqa: N802
+ self, url: str, configuration: _OpenConfiguration, handler: Callable[..., None]
+ ) -> None:
+ bundle_id = url.removeprefix("file:///Applications/").removesuffix(".app")
+ tcc.launches.append((bundle_id, configuration.activates, configuration.hides))
+ if bundle_id in tcc._installed:
+ tcc._running.add(bundle_id)
+ handler(_PlayerApp(bundle_id), None)
+
+ workspace = _Workspace()
+
+ def _running_with_bundle_id(bundle_id: str) -> list[_PlayerApp]:
+ return [_PlayerApp(bundle_id)] if bundle_id in tcc._running else []
+
+ return {
+ "Foundation": SimpleNamespace(
+ NSBundle=SimpleNamespace(mainBundle=_Bundle),
+ NSURL=SimpleNamespace(URLWithString_=lambda value: value),
+ ),
+ "AppKit": SimpleNamespace(
+ NSWorkspace=SimpleNamespace(sharedWorkspace=lambda: workspace),
+ NSRunningApplication=SimpleNamespace(
+ currentApplication=lambda: _RunningApp(active=tcc.foreground, pid=process_id),
+ runningApplicationsWithBundleIdentifier_=_running_with_bundle_id,
+ ),
+ NSWorkspaceOpenConfiguration=SimpleNamespace(configuration=_OpenConfiguration),
+ ),
+ "AVFoundation": SimpleNamespace(
+ AVCaptureDevice=SimpleNamespace(
+ authorizationStatusForMediaType_=self._av_status,
+ requestAccessForMediaType_completionHandler_=self._av_request,
+ ),
+ AVMediaTypeAudio="soun",
+ AVAuthorizationStatusNotDetermined=0,
+ AVAuthorizationStatusRestricted=1,
+ AVAuthorizationStatusDenied=2,
+ AVAuthorizationStatusAuthorized=3,
+ ),
+ "Quartz": SimpleNamespace(
+ CGPreflightScreenCaptureAccess=lambda: self._cg_preflight(
+ TccService.SCREEN_RECORDING, "CGPreflightScreenCaptureAccess"
+ ),
+ CGRequestScreenCaptureAccess=lambda: self._cg_request(
+ TccService.SCREEN_RECORDING, "CGRequestScreenCaptureAccess"
+ ),
+ CGPreflightListenEventAccess=lambda: self._cg_preflight(
+ TccService.INPUT_MONITORING, "CGPreflightListenEventAccess"
+ ),
+ CGRequestListenEventAccess=lambda: self._cg_request(
+ TccService.INPUT_MONITORING, "CGRequestListenEventAccess"
+ ),
+ CGPreflightPostEventAccess=lambda: self._cg_preflight(
+ TccService.POST_EVENT, "CGPreflightPostEventAccess"
+ ),
+ CGRequestPostEventAccess=lambda: self._cg_request(
+ TccService.POST_EVENT, "CGRequestPostEventAccess"
+ ),
+ ),
+ "ApplicationServices": SimpleNamespace(
+ AXIsProcessTrusted=self._ax_trusted,
+ AXIsProcessTrustedWithOptions=self._ax_trusted_with_options,
+ kAXTrustedCheckOptionPrompt=_AX_PROMPT_KEY,
+ ),
+ }
+
+ @classmethod
+ def all_granted(cls, **kwargs: Any) -> FakeTCC:
+ """The upgrader whose every grant is already in place at launch."""
+ return cls(granted=tuple(TccService), **kwargs)
+
+
+# --------------------------------------------------------------------------
+# Companions: a consumer "opens" something and the same FakeTCC decides what
+# macOS would have done.
+# --------------------------------------------------------------------------
+
+_AUDIBLE_SAMPLE = b"\x00\x01" # int16 256: not digital silence
+_SILENT_SAMPLE = b"\x00\x00"
+
+
+class FakeAudioStream:
+ """A ``sounddevice.InputStream`` stand-in; see :class:`FakeAudioInput`."""
+
+ def __init__(self, owner: FakeAudioInput, kwargs: dict[str, Any]) -> None:
+ self.owner = owner
+ self.kwargs = kwargs
+ self.callback: Callable[..., None] | None = kwargs.get("callback")
+ self.channels = int(kwargs.get("channels") or 1)
+ self.blocksize = int(kwargs.get("blocksize") or 512)
+ self.started = False
+ self.stopped = False
+ self.closed = False
+ self.silent_blocks = 0
+ self.audible_blocks = 0
+
+ @property
+ def active(self) -> bool:
+ return self.started and not self.stopped and not self.closed
+
+ def start(self) -> None:
+ self.started = True
+ self.owner.starts.append(self)
+ if self.owner.tcc is not None:
+ self.owner.tcc.consult_audio_input_start(self.owner.caller)
+
+ def stop(self) -> None:
+ self.stopped = True
+
+ def close(self) -> None:
+ self.closed = True
+
+ def pump(self, blocks: int = 1) -> int:
+ """Deliver ``blocks`` callback blocks; zeros while macOS withholds the mic."""
+ tcc = self.owner.tcc
+ audible = tcc is None or tcc.audio_input_is_audible()
+ sample = _AUDIBLE_SAMPLE if audible else _SILENT_SAMPLE
+ for _ in range(blocks):
+ if audible:
+ self.audible_blocks += 1
+ else:
+ self.silent_blocks += 1
+ if self.callback is not None:
+ self.callback(sample * self.blocksize * self.channels, self.blocksize, None, None)
+ return blocks
+
+
+class FakeAudioInput:
+ """Callable ``sounddevice.InputStream`` factory that consults a ``FakeTCC``.
+
+ ``tcc=None`` models an OS without TCC (Windows, Linux): nothing is consulted.
+ Install with ``monkeypatch.setattr(capture, "sd", SimpleNamespace(InputStream=fake))``.
+ ``streams`` lists every stream created, ``starts`` every one that was started:
+ a consumer test asserts "no device was opened" with ``fake.starts == []``.
+ """
+
+ def __init__(self, tcc: FakeTCC | None = None, *, caller: str = "audio") -> None:
+ self.tcc = tcc
+ self.caller = caller
+ self.streams: list[FakeAudioStream] = []
+ self.starts: list[FakeAudioStream] = []
+
+ def __call__(self, *_args: Any, **kwargs: Any) -> FakeAudioStream:
+ stream = FakeAudioStream(self, kwargs)
+ self.streams.append(stream)
+ return stream
+
+
+class FakeEventTap:
+ """A ``CGEventTapCreate`` stand-in that consults a ``FakeTCC``."""
+
+ def __init__(self, tcc: FakeTCC, *, caller: str = "event_tap") -> None:
+ self.tcc = tcc
+ self.caller = caller
+ self.attempts: list[str] = []
+ self.events_received = 0
+ self._result: str = "failed"
+ self._generation = -1
+ self._callback: Callable[[int], None] | None = None
+
+ def create(
+ self, callback: Callable[[int], None] | None = None, *, listen_only: bool = True
+ ) -> bool:
+ """Create the tap. ``True`` when macOS handed back a tap object."""
+ result = self.tcc.consult_listen_tap(listen_only=listen_only, caller=self.caller)
+ self.attempts.append(result)
+ self._result = result
+ self._generation = self.tcc.generation
+ self._callback = callback
+ return result in ("live", "silent")
+
+ @property
+ def live(self) -> bool:
+ """A tap object exists in this process (it may still receive nothing)."""
+ return self._result in ("live", "silent") and self._generation == self.tcc.generation
+
+ @property
+ def receives_events(self) -> bool:
+ return self._result == "live" and self._generation == self.tcc.generation
+
+ def deliver_key(self, keycode: int = 0) -> bool:
+ """A key goes down; ``True`` when the tap callback ran."""
+ if not self.receives_events:
+ return False
+ self.events_received += 1
+ if self._callback is not None:
+ self._callback(keycode)
+ return True
+
+
+@dataclass(frozen=True, slots=True)
+class FakeFrame:
+ """One captured frame: other apps' windows, or the wallpaper only."""
+
+ wallpaper_only: bool
+ window_titles: tuple[str, ...]
+
+
+class FakeScreenGrab:
+ """A screen capture stand-in that consults a ``FakeTCC``.
+
+ Without the grant the frame is wallpaper-only and nothing raises: the
+ silent-failure trap the product guards against with a pixel sanity check.
+ """
+
+ def __init__(
+ self,
+ tcc: FakeTCC,
+ *,
+ caller: str = "screen",
+ other_windows: tuple[str, ...] = ("Safari", "Notes"),
+ ) -> None:
+ self.tcc = tcc
+ self.caller = caller
+ self.other_windows = other_windows
+ self.frames: list[FakeFrame] = []
+
+ def grab(self) -> FakeFrame:
+ sees_windows = self.tcc.consult_screen_grab(self.caller)
+ frame = FakeFrame(
+ wallpaper_only=not sees_windows,
+ window_titles=self.other_windows if sees_windows else (),
+ )
+ self.frames.append(frame)
+ return frame
+
+
+# --------------------------------------------------------------------------
+# Convenience constructors.
+# --------------------------------------------------------------------------
+
+
+def make_darwin_port(
+ tcc: FakeTCC | None = None, **tcc_kwargs: Any
+) -> tuple[SystemPermissionPort, FakeTCC]:
+ """A real port for ``darwin`` running as the installed app, plus its fake."""
+ tcc = tcc if tcc is not None else FakeTCC(**tcc_kwargs)
+ return tcc.port("darwin"), tcc
+
+
+def make_non_darwin_port(
+ platform_name: Literal["win32", "linux"] = "linux",
+ tcc: FakeTCC | None = None,
+ **tcc_kwargs: Any,
+) -> tuple[SystemPermissionPort, FakeTCC]:
+ """A real port for Windows/Linux. ``tcc.assert_silent()`` must hold afterwards."""
+ tcc = tcc if tcc is not None else FakeTCC(**tcc_kwargs)
+ return tcc.port(platform_name), tcc
+
+
+def install_port(monkeypatch: Any, port: SystemPermissionPort) -> SystemPermissionPort:
+ """Make ``get_system_permission_port()`` answer with ``port`` for this test.
+
+ ``monkeypatch`` is pytest's fixture. Modules that imported the getter by name
+ at import time keep their own reference; the lazy imports the consumers use
+ resolve it per call and see this one.
+ """
+ import jarvis.platform.permissions as permissions
+
+ monkeypatch.setattr(permissions, "get_system_permission_port", lambda: port)
+ monkeypatch.setattr(permissions, "_DEFAULT_SYSTEM_PERMISSION_PORT", port)
+ return port
+
+
+__all__ = [
+ "AE_EVENT_NOT_PERMITTED",
+ "AE_EVENT_WOULD_REQUIRE_USER_CONSENT",
+ "AE_NO_ERR",
+ "AE_PROC_NOT_FOUND",
+ "DMG_BUNDLE_ID",
+ "INSTALLED_BUNDLE_ID",
+ "INSTALLED_BUNDLE_PATH",
+ "TERMINAL_BUNDLE_ID",
+ "CallKind",
+ "CallOutcome",
+ "DialogPolicy",
+ "FakeAudioInput",
+ "FakeAudioStream",
+ "FakeEventTap",
+ "FakeFrame",
+ "FakeScreenGrab",
+ "FakeTCC",
+ "TccCall",
+ "TccProcessAbort",
+ "TccService",
+ "TccState",
+ "install_port",
+ "make_darwin_port",
+ "make_non_darwin_port",
+]
diff --git a/tests/unit/agent_screen/test_runner_actuator_cache.py b/tests/unit/agent_screen/test_runner_actuator_cache.py
new file mode 100644
index 0000000000..e3c8e3cedf
--- /dev/null
+++ b/tests/unit/agent_screen/test_runner_actuator_cache.py
@@ -0,0 +1,141 @@
+"""The in-session runner must not cache a permission refusal as "no input backend".
+
+``ScreenServer._get_actuator`` used to store ``str(exc)`` of the FIRST failure
+forever, so after one ``PermissionNeededError`` the runner never asked
+``get_actuator()`` again, even once the person had allowed Accessibility. A
+permission refusal is a state that changes, not unavailability: it is retried per
+action. Real unavailability (Wayland, headless) stays cached.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+import jarvis.cu.actuate as actuate
+import jarvis.cu.capture as cu_capture
+from jarvis.cu.actuate import ActuationUnavailable, PermissionNeededError
+
+
+def screen_server_cls(monkeypatch: pytest.MonkeyPatch):
+ """``ScreenServer``, importable even while ``jarvis.agent_screen.port`` is stale.
+
+ ``jarvis/agent_screen/port.py`` imports ``RawCapture`` and ``raw_pixels`` from
+ ``jarvis.cu.capture``, names that module no longer exports (they are private
+ since e982c073c), so importing ANY ``jarvis.agent_screen`` module fails on the
+ base commit. The runner under test never touches them; supplying the names here
+ keeps this test about the actuator cache. Remove the shim once ``port.py`` is
+ fixed.
+ """
+ for name in ("RawCapture", "raw_pixels"):
+ if not hasattr(cu_capture, name):
+ monkeypatch.setattr(cu_capture, name, object, raising=False)
+ from jarvis.agent_screen.runner.server import ScreenServer # noqa: PLC0415
+
+ return ScreenServer
+
+
+class _Result:
+ """The slice of an ``EnsureResult`` the error reads."""
+
+ agent_detail = "[permission_needed:accessibility] Do not answer the dialog; stop."
+
+
+class _StubActuator:
+ def __init__(self) -> None:
+ self.typed: list[str] = []
+
+ def type_text(self, text: str) -> None:
+ self.typed.append(text)
+
+
+class _ScriptedGetActuator:
+ """``get_actuator`` that raises the scripted errors in order, then succeeds."""
+
+ def __init__(self, *errors: Exception) -> None:
+ self._errors = list(errors)
+ self.calls = 0
+ self.actuator = _StubActuator()
+
+ def __call__(self) -> _StubActuator:
+ self.calls += 1
+ if self._errors:
+ raise self._errors.pop(0)
+ return self.actuator
+
+
+def test_permission_refusal_is_retried_on_the_next_action(
+ monkeypatch: pytest.MonkeyPatch, screen_server_cls
+) -> None:
+ scripted = _ScriptedGetActuator(PermissionNeededError(_Result()))
+ monkeypatch.setattr(actuate, "get_actuator", scripted)
+ server = screen_server_cls()
+
+ with pytest.raises(PermissionNeededError):
+ server._get_actuator()
+ assert server._actuator_error == ""
+
+ # The person allowed Accessibility in the meantime: the next action works.
+ assert server._get_actuator() is scripted.actuator
+ assert scripted.calls == 2
+
+
+def test_refused_action_reports_the_agent_text_then_succeeds_after_the_grant(
+ monkeypatch: pytest.MonkeyPatch, screen_server_cls
+) -> None:
+ scripted = _ScriptedGetActuator(PermissionNeededError(_Result()))
+ monkeypatch.setattr(actuate, "get_actuator", scripted)
+ server = screen_server_cls()
+ params = {"action": "type_text", "params": {"text": "hi"}}
+
+ refused, _ = server.act(params)
+ assert refused["ok"] is False
+ assert "[permission_needed:accessibility]" in refused["error"]
+
+ allowed, _ = server.act(params)
+ assert allowed["ok"] is True
+ assert scripted.actuator.typed == ["hi"]
+
+
+def test_real_unavailability_stays_cached(
+ monkeypatch: pytest.MonkeyPatch, screen_server_cls
+) -> None:
+ scripted = _ScriptedGetActuator(ActuationUnavailable("No display server is available."))
+ monkeypatch.setattr(actuate, "get_actuator", scripted)
+ server = screen_server_cls()
+
+ for _ in range(3):
+ with pytest.raises(RuntimeError, match="No display server is available"):
+ server._get_actuator()
+ assert scripted.calls == 1
+
+
+def test_a_failing_import_is_cached_with_the_real_import_error(
+ monkeypatch: pytest.MonkeyPatch, screen_server_cls
+) -> None:
+ # A missing name makes ``from jarvis.cu.actuate import ...`` raise ImportError
+ # before ``PermissionNeededError`` is bound: the error must not turn into an
+ # UnboundLocalError, and it is cached like any other unavailability.
+ monkeypatch.delattr(actuate, "get_actuator")
+ server = screen_server_cls()
+
+ for _ in range(2):
+ with pytest.raises(RuntimeError, match="cannot import name 'get_actuator'") as excinfo:
+ server._get_actuator()
+ assert "UnboundLocalError" not in str(excinfo.value)
+ assert "cannot import name 'get_actuator'" in server._actuator_error
+
+
+def test_a_working_actuator_is_reused(monkeypatch: pytest.MonkeyPatch, screen_server_cls) -> None:
+ scripted = _ScriptedGetActuator()
+ monkeypatch.setattr(actuate, "get_actuator", scripted)
+ server = screen_server_cls()
+
+ assert server._get_actuator() is server._get_actuator()
+ assert scripted.calls == 1
+
+
+def test_permission_needed_error_is_exported_from_the_actuate_package() -> None:
+ assert actuate.PermissionNeededError is PermissionNeededError
+ assert "PermissionNeededError" in actuate.__all__
+ assert issubclass(PermissionNeededError, ActuationUnavailable)
diff --git a/tests/unit/appshot/test_both_option_status.py b/tests/unit/appshot/test_both_option_status.py
new file mode 100644
index 0000000000..dd3ae54700
--- /dev/null
+++ b/tests/unit/appshot/test_both_option_status.py
@@ -0,0 +1,63 @@
+"""The both-Option appshot gesture: status text only, never a permission request.
+
+Whether ``CGEventSourceKeyState`` needs Input Monitoring is UNVERIFIED (the repo
+contradicted itself), so on a Mac the armed status carries a hint sentence and
+nothing asks for a permission. Elsewhere the status text is unchanged.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+import jarvis.platform as platform_mod
+from jarvis.appshot import gesture as gesture_mod
+from jarvis.appshot import hotkey as hotkey_mod
+from jarvis.appshot.hotkey import BOTH_ALT, BOTH_OPTION_MAC_NOTE, AppshotShortcut
+from tests.fakes.fake_tcc import install_port, make_darwin_port
+
+
+class _Watcher:
+ def __init__(self, _on_fire, *, probe) -> None: # noqa: ANN001
+ self.started = False
+
+ def start(self) -> None:
+ self.started = True
+
+ def stop(self) -> None:
+ return None
+
+
+async def _arm(monkeypatch: pytest.MonkeyPatch, host: str):
+ monkeypatch.setattr(platform_mod, "detect_platform", lambda: host)
+ monkeypatch.setattr(gesture_mod, "make_probe", lambda: (lambda: (False, False), ""))
+ monkeypatch.setattr(gesture_mod, "BothAltWatcher", _Watcher)
+ shortcut = AppshotShortcut(bus=object())
+ return await shortcut._arm_both_alt()
+
+
+async def test_a_mac_gets_the_hint_and_no_permission_is_requested(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ port, tcc = make_darwin_port()
+ install_port(monkeypatch, port)
+ status = await _arm(monkeypatch, "darwin")
+ assert (status.hotkey, status.armed) == (BOTH_ALT, True)
+ assert status.detail == BOTH_OPTION_MAC_NOTE
+ # Its permission need is unverified, so the hint sends nobody to grant one.
+ assert "key combination" in status.detail and "Input Monitoring" not in status.detail
+ assert tcc.requests() == [] and tcc.implicit_prompts() == []
+ assert tcc.probes() == [], "the gesture's status text reads no permission at all"
+
+
[email protected]("host", ["win32", "linux"])
+async def test_other_hosts_keep_an_empty_status_text(
+ monkeypatch: pytest.MonkeyPatch, host: str
+) -> None:
+ status = await _arm(monkeypatch, host)
+ assert status.armed is True
+ assert status.detail == ""
+
+
+def test_the_note_never_sends_the_user_to_a_removed_settings_page() -> None:
+ assert "Settings > Permissions" not in BOTH_OPTION_MAC_NOTE
+ assert hotkey_mod.BOTH_ALT == "alt+alt"
diff --git a/tests/unit/audio/test_capture_permission_gate.py b/tests/unit/audio/test_capture_permission_gate.py
index 7b280ae781..f826848c7f 100644
--- a/tests/unit/audio/test_capture_permission_gate.py
+++ b/tests/unit/audio/test_capture_permission_gate.py
@@ -1,16 +1,54 @@
-"""macOS microphone capture never discovers TCC access by opening a device."""
+"""Microphone capture asks the permission layer ONCE, at open, and never per frame.
+
+The old gate probed ``runtime_access_granted`` twice per frame and refused when OUR
+preflight said "not granted", so macOS was never asked from the feature. The
+contract these tests pin (docs/macos-permissions.md, 4.6, row "audio/capture.py"):
+
+* one service ``ensure`` when the stream opens: an interactive (user-started)
+ open may make macOS ask, a background open never does, and CoreAudio is not
+ touched unless the answer is GRANTED / NOT_REQUIRED;
+* no probing per frame; the watchdog's existing 1 s tick makes one cheap
+ ``check``, and a lost grant ends the stream with ``MicrophoneAccessError``
+ carrying the ``EnsureResult`` and publishes the episode through the service;
+* macOS only: 5 s of exact zeros while the OS says granted is reported once and
+ the stream stays open;
+* off macOS nothing changes and the permission port is never touched.
+
+The OS is ``FakeTCC`` (a stateful TCC simulator); no ``unittest.mock``.
+"""
from __future__ import annotations
+import asyncio
+from collections.abc import Callable
from types import SimpleNamespace
import pytest
from jarvis.audio import capture
+from jarvis.core.bus import EventBus, get_default_bus, reset_default_bus
+from jarvis.core.events import PermissionNeeded
from jarvis.core.protocols import AudioChunk
+from jarvis.platform.permission_service import PermissionOutcome, PermissionService
+from jarvis.platform.permissions import PermissionId, PermissionState
+from tests.fakes.fake_permission_service import FakePermissionService, make_result
+from tests.fakes.fake_tcc import (
+ DialogPolicy,
+ FakeAudioInput,
+ FakeTCC,
+ TccService,
+ install_port,
+ make_darwin_port,
+ make_non_darwin_port,
+)
+
+MIC = TccService.MICROPHONE
+_ZERO_FRAME = b"\x00\x00" * capture.BLOCKSIZE
class _Stream:
+ """A minimal ``sounddevice.InputStream`` for the legacy ``access_gate`` seam."""
+
def __init__(self) -> None:
self.started = False
self.stopped = False
@@ -26,24 +64,185 @@ class _Stream:
self.closed = True
-def test_macos_default_gate_uses_process_wide_permission_port(monkeypatch) -> None:
- import jarvis.platform.permissions as permissions
+def _use_audio(monkeypatch: pytest.MonkeyPatch, audio: FakeAudioInput) -> None:
+ monkeypatch.setattr(capture, "sd", SimpleNamespace(InputStream=audio))
- calls: list[permissions.PermissionId] = []
- port = SimpleNamespace(
- runtime_access_granted=lambda permission_id: calls.append(permission_id) or True
- )
- monkeypatch.setattr(capture.sys, "platform", "darwin")
- monkeypatch.setattr(permissions, "get_system_permission_port", lambda: port)
- gate = capture._macos_microphone_access_gate()
+def _darwin(
+ monkeypatch: pytest.MonkeyPatch, **tcc_kwargs
+) -> tuple[FakeTCC, FakeAudioInput]:
+ port, tcc = make_darwin_port(**tcc_kwargs)
+ install_port(monkeypatch, port)
+ audio = FakeAudioInput(tcc)
+ _use_audio(monkeypatch, audio)
+ return tcc, audio
+
+
+async def _wait_for(predicate: Callable[[], bool], *, timeout_s: float = 3.0) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout_s
+ while not predicate():
+ if asyncio.get_running_loop().time() > deadline:
+ raise AssertionError("condition not reached in time")
+ await asyncio.sleep(0.01)
+
+
+async def _pump_zeros(stream, *, frames: int, interval_s: float = 0.01) -> None:
+ """Deliver exact-zero frames through the capture callback (a muted input)."""
+ for _ in range(frames):
+ stream.callback(_ZERO_FRAME, capture.BLOCKSIZE, None, None)
+ await asyncio.sleep(interval_s)
+
+
+def owned_service() -> Callable[..., PermissionService]:
+ """A service the test owns (zero GRANTED cache, so a revoke is seen at once)."""
+ made: list[PermissionService] = []
+
+ def build(**kwargs) -> PermissionService:
+ service = PermissionService(granted_ttl_s=0.0, watch_interval_s=0.05, **kwargs)
+ made.append(service)
+ return service
+
+ yield build
+ for service in made:
+ service._shutdown()
+
+
+# ---------------------------------------------------------------------------
+# The ask: one request at open, then the stream
+# ---------------------------------------------------------------------------
+
+
+async def test_first_interactive_open_makes_one_request_and_opens_only_after_the_grant(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, audio = _darwin(monkeypatch) # not_determined, the dialog answer is Allow
+
+ mic = capture.MicrophoneCapture(device=0, interactive=True)
+ async with mic:
+ assert tcc.state(MIC).value == "granted"
+
+ (request,) = tcc.requests(MIC)
+ assert request.outcome.value == "dialog_shown"
+ assert len(audio.starts) == 1
+ assert tcc.implicit_prompts() == [] # opening the device never made macOS ask
+ assert not mic.revoked
+
+
+async def test_open_waits_for_the_dialog_before_any_device_exists(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, audio = _darwin(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ mic = capture.MicrophoneCapture(device=0, interactive=True, permission_wait_s=5.0)
+ opening = asyncio.create_task(mic.__aenter__())
+ await _wait_for(lambda: tcc.dialog_open(MIC))
+ assert audio.streams == [] # the dialog is on screen: no stream object yet
+ tcc.answer(MIC, DialogPolicy.ALLOW)
+ await asyncio.wait_for(opening, timeout=5.0)
+
+ assert len(tcc.requests(MIC)) == 1
+ assert len(audio.starts) == 1
+ await mic.__aexit__(None, None, None)
+
+
+async def test_edge_gesture_open_with_a_pending_dialog_refuses_and_opens_no_device(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A held key passes wait 0: the dialog is shown, the press is not retroactive."""
+ tcc, audio = _darwin(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ mic = capture.MicrophoneCapture(device=0, interactive=True)
+ with pytest.raises(capture.MicrophoneAccessError) as refused:
+ await mic.__aenter__()
+
+ assert refused.value.result.outcome is PermissionOutcome.PENDING
+ assert len(tcc.requests(MIC)) == 1
+ assert audio.streams == []
+
+
+async def test_denied_open_asks_nothing_opens_no_device_and_carries_the_result(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, audio = _darwin(monkeypatch)
+ tcc.deny(MIC)
+
+ for _ in range(2): # a second press must not ask again either
+ mic = capture.MicrophoneCapture(device=0, interactive=True)
+ with pytest.raises(capture.MicrophoneAccessError) as refused:
+ await mic.__aenter__()
+ result = refused.value.result
+ assert result is not None and not result.granted
+ assert result.outcome is PermissionOutcome.DENIED and result.reason == "denied"
+ assert result.agent_detail.startswith("[permission_needed:microphone] ")
+ assert str(refused.value) == result.user_detail
+
+ assert tcc.requests() == [] # not even an ignored request
+ assert audio.streams == []
+
+
+async def test_background_open_never_asks_and_never_opens_a_device(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, audio = _darwin(monkeypatch)
+
+ mic = capture.MicrophoneCapture(device=0, permission_feature="wake_word") # interactive=False
+ with pytest.raises(capture.MicrophoneAccessError) as refused:
+ await mic.__aenter__()
+
+ tcc.assert_no_prompts()
+ assert audio.streams == []
+ assert refused.value.result.reason == "not_determined"
+ from jarvis.platform.permission_service import get_permission_service
+
+ (episode,) = get_permission_service().outstanding()
+ assert episode.feature == "wake_word" and episode.origin == "background"
- assert gate is not None and gate() is True
- assert calls == [permissions.PermissionId.MICROPHONE]
+
+async def test_a_granted_open_needs_no_request(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc, audio = _darwin(monkeypatch, granted=[MIC])
+
+ async with capture.MicrophoneCapture(device=0):
+ pass
+
+ assert tcc.requests() == [] and len(audio.starts) == 1
+
+
+def test_unknown_permission_feature_is_a_programming_error() -> None:
+ with pytest.raises(ValueError):
+ capture.MicrophoneCapture(device=0, permission_feature="not_a_feature")
+
+
+# ---------------------------------------------------------------------------
+# Injected gates (test seams)
+# ---------------------------------------------------------------------------
+
+
+async def test_open_passes_the_feature_and_the_gesture_flag_to_the_gate(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ gate = FakePermissionService()
+ _use_audio(monkeypatch, FakeAudioInput(None))
+
+ mic = capture.MicrophoneCapture(
+ device=0, permission_feature="dictation", interactive=True, permission_gate=gate
+ )
+ async with mic:
+ pass
+
+ (call,) = gate.ensure_calls(PermissionId.MICROPHONE)
+ assert (call.feature, call.interactive, call.wait_s) == ("dictation", True, 0.0)
@pytest.mark.asyncio
-async def test_denied_gate_fails_before_portaudio_open(monkeypatch) -> None:
+async def test_a_denied_gate_fails_before_portaudio_open(monkeypatch: pytest.MonkeyPatch) -> None:
opens: list[object] = []
def _input_stream(**_kwargs):
@@ -51,40 +250,434 @@ async def test_denied_gate_fails_before_portaudio_open(monkeypatch) -> None:
return _Stream()
monkeypatch.setattr(capture, "sd", SimpleNamespace(InputStream=_input_stream))
- mic = capture.MicrophoneCapture(device=0, access_gate=lambda: False)
+ gate = FakePermissionService({PermissionId.MICROPHONE: PermissionOutcome.DENIED})
+ mic = capture.MicrophoneCapture(device=0, permission_gate=gate)
- with pytest.raises(capture.MicrophoneAccessError):
+ with pytest.raises(capture.MicrophoneAccessError) as refused:
await mic.__aenter__()
assert opens == []
+ assert refused.value.result.outcome is PermissionOutcome.DENIED
+
+
+async def test_the_legacy_access_gate_replaces_the_service(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, audio = _darwin(monkeypatch)
+ mic = capture.MicrophoneCapture(device=0, access_gate=lambda: False)
+
+ with pytest.raises(capture.MicrophoneAccessError) as refused:
+ await mic.__aenter__()
+
+ assert refused.value.result.outcome is PermissionOutcome.DENIED
+ assert audio.streams == [] and tcc.calls == () # the service was never consulted
+
+
+# ---------------------------------------------------------------------------
+# No per-frame probing; the watchdog tick owns the revoke check
+# ---------------------------------------------------------------------------
+
+
+async def test_frames_cost_no_permission_probe(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc, audio = _darwin(monkeypatch, granted=[MIC])
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 3600.0)
+
+ async with capture.MicrophoneCapture(device=0) as mic:
+ (stream,) = audio.starts
+ mark = tcc.mark()
+ frames = mic.stream()
+ for _ in range(60):
+ stream.pump()
+ chunk = await asyncio.wait_for(anext(frames), timeout=2.0)
+ assert isinstance(chunk, AudioChunk) and any(chunk.pcm)
+ await frames.aclose()
+ # Neither a frame nor an idle wait asks the OS anything (the old gate
+ # called ``runtime_access_granted`` twice per frame and every 0.25 s).
+ assert tcc.calls_since(mark) == ()
+
+
+async def test_an_idle_stream_makes_no_probe_between_ticks(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, audio = _darwin(monkeypatch, granted=[MIC])
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 3600.0)
+
+ async with capture.MicrophoneCapture(device=0) as mic:
+ mark = tcc.mark()
+ reader = asyncio.create_task(anext(mic.stream()))
+ await asyncio.sleep(0.6) # more than two of the old 0.25 s idle probes
+ assert tcc.calls_since(mark) == ()
+ reader.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await reader
@pytest.mark.asyncio
-async def test_live_revocation_stops_stream_and_closes_device(monkeypatch) -> None:
+async def test_mid_stream_revoke_ends_the_stream_and_publishes_one_episode(
+ monkeypatch: pytest.MonkeyPatch, owned_service: Callable[..., PermissionService]
+) -> None:
+ tcc, audio = _darwin(monkeypatch, granted=[MIC])
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ bus = EventBus()
+ seen: list[PermissionNeeded] = []
+
+ async def _collect(event: PermissionNeeded) -> None:
+ seen.append(event)
+
+ bus.subscribe(PermissionNeeded, _collect)
+ service = owned_service()
+ service.attach_bus(bus, asyncio.get_running_loop())
+
+ mic = capture.MicrophoneCapture(
+ device=0, permission_feature="dictation", interactive=True, permission_gate=service
+ )
+ with pytest.raises(capture.MicrophoneAccessError) as revoked:
+ async with mic:
+ (stream,) = audio.starts
+ stream.pump()
+ frames = mic.stream()
+ assert any((await asyncio.wait_for(anext(frames), timeout=2.0)).pcm)
+ tcc.deny(MIC) # the user flips the switch off in System Settings
+ await asyncio.wait_for(anext(frames), timeout=3.0)
+
+ assert mic.revoked
+ assert revoked.value.result.outcome is PermissionOutcome.DENIED
+ assert stream.stopped and stream.closed
+ await _wait_for(lambda: len(seen) >= 1)
+ await asyncio.sleep(0.1) # give a (wrong) second publish the chance to show up
+ (event,) = seen
+ assert (event.permissions, event.feature, event.reason) == (
+ ("microphone",),
+ "dictation",
+ "denied",
+ )
+ assert event.origin == "user" # a user-started capture may raise the card
+ assert tcc.requests() == [] # losing the stream never asks again
+
+
+async def test_mid_stream_revoke_of_a_background_capture_is_published_as_background(
+ monkeypatch: pytest.MonkeyPatch, owned_service: Callable[..., PermissionService]
+) -> None:
+ tcc, audio = _darwin(monkeypatch, granted=[MIC])
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ service = owned_service()
+
+ mic = capture.MicrophoneCapture(
+ device=0, permission_feature="wake_word", permission_gate=service
+ )
+ with pytest.raises(capture.MicrophoneAccessError):
+ async with mic:
+ tcc.deny(MIC)
+ await asyncio.wait_for(anext(mic.stream()), timeout=3.0)
+
+ (episode,) = service.outstanding()
+ assert (episode.feature, episode.origin, episode.reason) == (
+ "wake_word",
+ "background",
+ "denied",
+ )
+
+
+async def test_revoke_wakes_a_reader_parked_on_a_silent_stream(
+ monkeypatch: pytest.MonkeyPatch, owned_service: Callable[..., PermissionService]
+) -> None:
+ tcc, _audio = _darwin(monkeypatch, granted=[MIC])
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ mic = capture.MicrophoneCapture(device=0, permission_gate=owned_service())
+
+ with pytest.raises(capture.MicrophoneAccessError):
+ async with mic:
+ reader = asyncio.create_task(anext(mic.stream())) # no frame ever arrives
+ await asyncio.sleep(0.05)
+ tcc.deny(MIC)
+ await asyncio.wait_for(reader, timeout=3.0)
+
+
+async def test_a_regrant_between_check_and_ensure_does_not_end_the_stream(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``check`` says no, the ensure that follows says yes: the capture stays alive."""
+ gate = FakePermissionService()
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ _use_audio(monkeypatch, FakeAudioInput(None))
+ mic = capture.MicrophoneCapture(device=0, permission_gate=gate)
+
+ async with mic:
+ # check() reads "denied", the ensure that follows answers granted.
+ gate.script(
+ PermissionId.MICROPHONE,
+ make_result(
+ PermissionId.MICROPHONE, PermissionOutcome.GRANTED, state=PermissionState.DENIED
+ ),
+ )
+ await asyncio.sleep(0.1)
+ assert not mic.revoked
+ assert gate.check_calls(PermissionId.MICROPHONE) # the tick did look
+
+
+async def test_a_gate_that_raises_in_a_tick_does_not_end_the_watchdog(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The real service never raises, but an injected ``PermissionGate`` may: the tick
+ is treated as "not revoked" and the watchdog task keeps running (it would
+ otherwise die silently and take stall recovery with it)."""
+
+ class _RaisingCheck(FakePermissionService):
+ raised = 0
+
+ def check(self, *args, **kwargs): # noqa: ANN002, ANN003, ANN202
+ type(self).raised += 1
+ raise RuntimeError("custom gate failure")
+
+ gate = _RaisingCheck()
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ _use_audio(monkeypatch, FakeAudioInput(None))
+ mic = capture.MicrophoneCapture(device=0, permission_gate=gate)
+
+ async with mic:
+ await _wait_for(lambda: _RaisingCheck.raised >= 3) # ticked repeatedly after raising
+ assert not mic.revoked
+ assert mic._watchdog_task is not None and not mic._watchdog_task.done()
+
+
+async def test_a_single_unreadable_tick_is_forgiven_but_a_persistent_one_is_not(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ gate = FakePermissionService()
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ _use_audio(monkeypatch, FakeAudioInput(None))
+ mic = capture.MicrophoneCapture(device=0, permission_gate=gate)
+
+ with pytest.raises(capture.MicrophoneAccessError):
+ async with mic:
+ gate.script(PermissionId.MICROPHONE, PermissionOutcome.UNAVAILABLE)
+ await asyncio.wait_for(anext(mic.stream()), timeout=3.0)
+
+ assert mic.revoked
+
+
+async def test_the_legacy_gate_revoke_closes_the_device(monkeypatch: pytest.MonkeyPatch) -> None:
allowed = True
stream = _Stream()
- monkeypatch.setattr(
- capture,
- "sd",
- SimpleNamespace(InputStream=lambda **_kwargs: stream),
- )
+ monkeypatch.setattr(capture, "sd", SimpleNamespace(InputStream=lambda **_kwargs: stream))
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
mic = capture.MicrophoneCapture(device=0, access_gate=lambda: allowed)
- with pytest.raises(capture.MicrophoneAccessError):
+ with pytest.raises(capture.MicrophoneAccessError) as revoked:
async with mic:
iterator = mic.stream()
mic._safe_put(
- AudioChunk(
- pcm=b"\x00\x00",
- sample_rate=16_000,
- timestamp_ns=1,
- channels=1,
- )
+ AudioChunk(pcm=b"\x00\x01", sample_rate=16_000, timestamp_ns=1, channels=1)
)
assert (await anext(iterator)).timestamp_ns == 1
allowed = False
- await anext(iterator)
+ await asyncio.wait_for(anext(iterator), timeout=3.0)
+
+ assert revoked.value.result is not None
+ assert stream.started and stream.stopped and stream.closed
+
+
+# ---------------------------------------------------------------------------
+# Watchdog restarts are never a gesture
+# ---------------------------------------------------------------------------
+
+
+async def test_a_stall_restart_ensures_non_interactively(monkeypatch: pytest.MonkeyPatch) -> None:
+ gate = FakePermissionService()
+ audio = FakeAudioInput(None)
+ _use_audio(monkeypatch, audio)
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ monkeypatch.setattr(capture.MicrophoneCapture, "_STALL_THRESHOLD_S", 0.05)
+
+ mic = capture.MicrophoneCapture(
+ device=0, permission_feature="dictation", interactive=True, permission_gate=gate
+ )
+ async with mic:
+ # Wait for what is asserted (the second, non-interactive ensure), not for the
+ # restart counter: the watchdog bumps the counter BEFORE it asks again, and a
+ # slow runner would otherwise leave the capture mid-restart.
+ await _wait_for(lambda: len(gate.ensure_calls(PermissionId.MICROPHONE)) >= 2)
+
+ first, restart = gate.ensure_calls(PermissionId.MICROPHONE)[:2]
+ assert first.interactive is True
+ assert restart.interactive is False and restart.feature == "dictation"
+
+
+async def test_a_stall_restart_that_loses_the_grant_ends_the_capture(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ gate = FakePermissionService()
+ gate.script(PermissionId.MICROPHONE, PermissionOutcome.GRANTED, PermissionOutcome.DENIED)
+ _use_audio(monkeypatch, FakeAudioInput(None))
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ monkeypatch.setattr(capture.MicrophoneCapture, "_STALL_THRESHOLD_S", 0.05)
+
+ mic = capture.MicrophoneCapture(device=0, permission_gate=gate)
+ with pytest.raises(capture.MicrophoneAccessError):
+ async with mic:
+ await asyncio.wait_for(anext(mic.stream()), timeout=3.0)
+
+ assert mic.revoked
+
+
+# ---------------------------------------------------------------------------
+# Digital-silence guard (macOS only)
+# ---------------------------------------------------------------------------
+
+
+def default_bus_events() -> list[PermissionNeeded]:
+ reset_default_bus()
+ seen: list[PermissionNeeded] = []
+
+ async def _collect(event: PermissionNeeded) -> None:
+ seen.append(event)
+
+ get_default_bus().subscribe(PermissionNeeded, _collect)
+ yield seen
+ reset_default_bus()
+
+
+async def test_five_seconds_of_zeros_while_granted_reports_once_and_keeps_the_stream(
+ monkeypatch: pytest.MonkeyPatch, default_bus_events: list[PermissionNeeded]
+) -> None:
+ _tcc, audio = _darwin(monkeypatch, granted=[MIC])
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ monkeypatch.setattr(capture, "_SILENCE_REPORT_AFTER_S", 0.05)
+
+ mic = capture.MicrophoneCapture(device=0, permission_feature="voice", interactive=True)
+ async with mic:
+ (stream,) = audio.starts
+ await _pump_zeros(stream, frames=40) # ~0.4 s of digital silence, state GRANTED
+ await _wait_for(lambda: len(default_bus_events) >= 1)
+ await _pump_zeros(stream, frames=10) # still silent: no second report
+
+ assert not mic.revoked and not stream.closed # a notice, not a verdict
+ frames = mic.stream()
+ chunk = await asyncio.wait_for(anext(frames), timeout=2.0)
+ assert chunk.pcm.strip(b"\x00") == b"" # the zeros were not dropped or faked
+ await frames.aclose()
+
+ (event,) = default_bus_events
+ assert event.permissions == ("microphone",)
+ # Background even for a user-started capture: the OS says granted, so this is
+ # more likely a muted input than a denial and must not raise a toast.
+ assert event.feature == "voice" and event.reason == "denied" and event.origin == "background"
+ assert "denied or muted" in event.detail
+
+
+def test_the_silence_window_is_five_seconds_of_exact_zeros() -> None:
+ # The guard must not fire on the normal start-up silence of a real microphone, so
+ # the window is part of the contract (a shorter one shows a false "denied or muted"
+ # card on a granted Mac). The other tests shorten it; this one pins the real value.
+ assert capture._SILENCE_REPORT_AFTER_S == 5.0
+
+
+async def test_start_up_silence_inside_the_real_window_reports_nothing(
+ monkeypatch: pytest.MonkeyPatch, default_bus_events: list[PermissionNeeded]
+) -> None:
+ _tcc, audio = _darwin(monkeypatch, granted=[MIC])
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ # NOT shortened: the real constant decides.
+
+ async with capture.MicrophoneCapture(device=0):
+ (stream,) = audio.starts
+ await _pump_zeros(stream, frames=60) # about 0.6 s of zeros, far inside 5 s
+ await asyncio.sleep(0.1)
+
+ assert default_bus_events == []
+
+
+async def test_audible_frames_never_trigger_the_silence_guard(
+ monkeypatch: pytest.MonkeyPatch, default_bus_events: list[PermissionNeeded]
+) -> None:
+ _tcc, audio = _darwin(monkeypatch, granted=[MIC])
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ monkeypatch.setattr(capture, "_SILENCE_REPORT_AFTER_S", 0.05)
+
+ async with capture.MicrophoneCapture(device=0):
+ (stream,) = audio.starts
+ for _ in range(30):
+ stream.pump()
+ await asyncio.sleep(0.01)
+ # One real sample in an otherwise silent block still counts as audio.
+ for _ in range(30):
+ frame = bytearray(_ZERO_FRAME)
+ frame[10] = 1
+ stream.callback(bytes(frame), capture.BLOCKSIZE, None, None)
+ await asyncio.sleep(0.01)
+
+ assert default_bus_events == []
+
+
+async def test_zeros_with_a_grant_that_is_gone_end_as_a_revoke_not_as_a_silence_notice(
+ monkeypatch: pytest.MonkeyPatch,
+ default_bus_events: list[PermissionNeeded],
+ owned_service: Callable[..., PermissionService],
+) -> None:
+ """A denied mic feeds zeros; the re-check sees the denial and the revoke path takes over."""
+ tcc, audio = _darwin(monkeypatch, granted=[MIC])
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ monkeypatch.setattr(capture, "_SILENCE_REPORT_AFTER_S", 0.05)
+
+ mic = capture.MicrophoneCapture(device=0, permission_gate=owned_service())
+ with pytest.raises(capture.MicrophoneAccessError):
+ async with mic:
+ (stream,) = audio.starts
+ tcc.deny(MIC)
+ await _pump_zeros(stream, frames=40)
+ # The revoke is decided by the watchdog's tick (an executor hop): wait for it
+ # instead of relying on how long the zero pump took (timer resolution differs
+ # between hosts, Windows has a 15.6 ms clock).
+ await _wait_for(lambda: mic.revoked)
+ await asyncio.wait_for(anext(mic.stream()), timeout=3.0)
+
+ assert default_bus_events == [] # the service's episode is the notice here
+
+
+# ---------------------------------------------------------------------------
+# Non-darwin: nothing changes, the permission port is never touched
+# ---------------------------------------------------------------------------
+
+
[email protected]("platform_name", ["win32", "linux"])
+async def test_off_macos_the_capture_never_touches_the_permission_port(
+ monkeypatch: pytest.MonkeyPatch,
+ platform_name: str,
+ default_bus_events: list[PermissionNeeded],
+) -> None:
+ port, tcc = make_non_darwin_port(platform_name)
+ install_port(monkeypatch, port)
+ audio = FakeAudioInput(None) # no TCC off macOS: nothing to consult
+ _use_audio(monkeypatch, audio)
+ monkeypatch.setattr(capture.MicrophoneCapture, "_WATCHDOG_TICK_S", 0.01)
+ monkeypatch.setattr(capture, "_SILENCE_REPORT_AFTER_S", 0.02)
+
+ mic = capture.MicrophoneCapture(device=0, interactive=True)
+ async with mic:
+ (stream,) = audio.starts
+ await _pump_zeros(stream, frames=15) # silence off macOS is not a permission signal
+ frames = mic.stream()
+ chunk = await asyncio.wait_for(anext(frames), timeout=2.0)
+ await frames.aclose()
- assert stream.started is True
- assert stream.stopped is True
- assert stream.closed is True
+ assert chunk.sample_rate == capture.SAMPLE_RATE
+ assert stream.closed and not mic.revoked
+ assert default_bus_events == []
+ tcc.assert_silent()
diff --git a/tests/unit/audio/test_duck_controller.py b/tests/unit/audio/test_duck_controller.py
index a287e297ca..d8ad67f5e3 100644
--- a/tests/unit/audio/test_duck_controller.py
+++ b/tests/unit/audio/test_duck_controller.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from types import SimpleNamespace
from jarvis.audio.ducking.controller import AudioDuckController
+from jarvis.audio.ducking.protocol import DuckPermissionReport
class FakeDucker:
@@ -102,3 +103,55 @@ async def test_restore_sync_unmutes_on_shutdown():
assert d.restored == [[111, 222]] and c._muted == []
c.restore_sync() # idempotent
assert d.restored == [[111, 222]]
+
+
+class AskingDucker(FakeDucker):
+ """A backend with an asking path, like the macOS one."""
+
+ def __init__(self):
+ super().__init__()
+ self.prewarms = 0
+
+ def prewarm(self):
+ self.prewarms += 1
+ return DuckPermissionReport(note="a full sentence")
+
+
+async def test_set_enabled_true_returns_the_backend_permission_report():
+ d, bus = AskingDucker(), FakeBus()
+ c = AudioDuckController(bus=bus, cfg=_cfg(enabled=False), ducker=d)
+ report = await c.set_enabled(True)
+ assert d.prewarms == 1 and report.note == "a full sentence"
+ assert c._cfg.ducking.enabled is True
+
+
+async def test_set_enabled_true_without_an_asking_path_returns_none():
+ d = FakeDucker() # no prewarm: Windows, or no backend at all
+ c = AudioDuckController(bus=FakeBus(), cfg=_cfg(enabled=False), ducker=d)
+ assert await c.set_enabled(True) is None
+
+
+async def test_set_enabled_false_never_asks():
+ d = AskingDucker()
+ c = AudioDuckController(bus=FakeBus(), cfg=_cfg(enabled=True), ducker=d)
+ assert await c.set_enabled(False) is None
+ assert d.prewarms == 0
+
+
+async def test_a_failing_prewarm_is_not_a_permission_report():
+ class Broken(AskingDucker):
+ def prewarm(self):
+ raise RuntimeError("native bridge down")
+
+ c = AudioDuckController(bus=FakeBus(), cfg=_cfg(enabled=False), ducker=Broken())
+ assert await c.set_enabled(True) is None # logged by _run; the toggle still applies
+ assert c._cfg.ducking.enabled is True
+
+
+async def test_a_session_never_asks_the_backend_to_prewarm():
+ d, bus = AskingDucker(), FakeBus()
+ c = AudioDuckController(bus=bus, cfg=_cfg(enabled=True), ducker=d)
+ c.attach()
+ await bus.subs["VoiceSessionStarted"](object())
+ await bus.subs["VoiceSessionEnded"](object())
+ assert d.prewarms == 0 and d.muted_calls == 1
diff --git a/tests/unit/audio/test_ducking_macos.py b/tests/unit/audio/test_ducking_macos.py
index a5e9b358bf..b3251077b6 100644
--- a/tests/unit/audio/test_ducking_macos.py
+++ b/tests/unit/audio/test_ducking_macos.py
@@ -1,9 +1,21 @@
-"""MacOSScriptDucker: tiered AppleScript duck/restore with a fake runner."""
+"""MacOSScriptDucker: tiered AppleScript duck/restore with a fake runner.
+
+The permission layer is a ``FakePermissionService`` that reads Automation as GRANTED
+(the duck/restore logic is the subject here); ``test_ducking_permissions.py`` covers
+the permission behaviour against ``FakeTCC``.
+"""
from __future__ import annotations
import subprocess
+import threading
+import time
+
+import pytest
+from jarvis.audio.ducking import macos
from jarvis.audio.ducking.macos import _MASTER_TOKEN, MacOSScriptDucker
+from jarvis.platform.permissions import PermissionId
+from tests.fakes.fake_permission_service import FakePermissionService
_MUSIC = "com.apple.Music"
_SPOTIFY = "com.spotify.client"
@@ -41,6 +53,7 @@ class FakeRunner:
def _ducker(runner: FakeRunner, **kwargs) -> MacOSScriptDucker:
+ kwargs.setdefault("access_gate", FakePermissionService()) # Automation: granted
return MacOSScriptDucker(run=runner, **kwargs)
@@ -292,3 +305,221 @@ def test_denied_master_restore_keeps_the_saved_level():
)
d.restore([_MASTER_TOKEN])
assert d._saved == {_MASTER_TOKEN: 80}
+
+
+# --------------------------------------------------------------------------- #
+# Permission gating (FakePermissionService) #
+# --------------------------------------------------------------------------- #
+
+
+def _music_scripts(run: FakeRunner) -> list[str]:
+ return [s for s in run.scripts if _MUSIC in s]
+
+
+def _music_scripts_with_a_send(run: FakeRunner) -> list[str]:
+ return [s for s in _music_scripts(run) if "tell application" in s]
+
+
+def test_a_player_without_a_live_grant_is_never_scripted_and_never_asked():
+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "40"})
+ gate = FakePermissionService({PermissionId.AUTOMATION: "pending"})
+ d = _ducker(run, access_gate=gate)
+ assert d.mute_others(own_pid=1, never=frozenset()) == []
+ assert d._saved == {}
+ # Only the pure running-state query ever reaches a player that was not granted.
+ assert all("tell application" not in s for s in run.scripts)
+ # The service was only READ, or told non-interactively: nothing could have asked.
+ assert gate.native_free()
+ assert {c.target for c in gate.check_calls()} == {_MUSIC, _SPOTIFY}
+
+
+def test_a_miss_is_recorded_through_a_non_interactive_ensure_only_for_a_running_player():
+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "-"}) # Spotify is not running
+ gate = FakePermissionService({PermissionId.AUTOMATION: "pending"})
+ d = _ducker(run, access_gate=gate)
+ d.mute_others(own_pid=1, never=frozenset())
+ calls = gate.ensure_calls(PermissionId.AUTOMATION)
+ assert [(c.target, c.interactive, c.feature) for c in calls] == [
+ (_MUSIC, False, "audio_ducking")
+ ]
+
+
+def test_a_player_the_service_calls_not_required_is_left_alone():
+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "40"})
+ gate = FakePermissionService({PermissionId.AUTOMATION: "not_required"})
+ d = _ducker(run, access_gate=gate)
+ assert d.mute_others(own_pid=1, never=frozenset()) == []
+ assert run.scripts == [] # not installed (or not macOS): not even a probe
+ assert gate.ensure_calls() == []
+
+
+def test_master_fallback_still_applies_when_a_running_player_has_no_grant():
+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "-", "master": "80"})
+ gate = FakePermissionService({PermissionId.AUTOMATION: "denied"})
+ d = _ducker(run, master_fallback=True, access_gate=gate)
+ assert d.mute_others(own_pid=1, never=frozenset()) == [_MASTER_TOKEN]
+ assert not _music_scripts_with_a_send(run)
+
+
+def test_minus_1743_after_a_granted_read_skips_the_player_and_drops_the_cache():
+ refused = subprocess.CompletedProcess(
+ ["osascript"], 1, stdout="", stderr="Not authorized to send Apple events (-1743)"
+ )
+
+ class Gate(FakePermissionService):
+ invalidated: list[object]
+
+ def invalidate(self, permission=None):
+ self.invalidated.append(permission)
+
+ gate = Gate()
+ gate.invalidated = []
+ run = FakeRunner({_MUSIC: refused, _SPOTIFY: "70"})
+ d = _ducker(run, access_gate=gate)
+ assert d.mute_others(own_pid=1, never=frozenset()) == [2] # Spotify still ducks
+ assert gate.invalidated == [PermissionId.AUTOMATION]
+ # The service is told ONCE, through the failed-use report: a background episode that
+ # names the player, never an ask (and no longer a non-interactive ensure).
+ (report,) = gate.report_calls("report_failed_use")
+ assert (report.permission, report.feature, report.target) == (
+ PermissionId.AUTOMATION,
+ "audio_ducking",
+ _MUSIC,
+ )
+ assert (report.reason, report.origin, report.interactive) == (
+ "needs_settings",
+ "background",
+ False,
+ )
+ assert gate.ensure_calls(PermissionId.AUTOMATION) == [] and gate.native_free()
+
+
+def test_a_send_that_lands_after_a_refusal_reports_the_success_once():
+ refused = subprocess.CompletedProcess(
+ ["osascript"], 1, stdout="", stderr="Not authorized to send Apple events (-1743)"
+ )
+ gate = FakePermissionService()
+ run = FakeRunner({_MUSIC: refused, _SPOTIFY: "-"})
+ d = _ducker(run, access_gate=gate)
+ assert d.mute_others(own_pid=1, never=frozenset()) == []
+ assert gate.report_calls("report_use_ok") == [] # nothing landed yet
+
+ run._results[_MUSIC] = "65" # fixed in System Settings: the next duck lands
+ assert d.mute_others(own_pid=1, never=frozenset()) == [1]
+ (ok,) = gate.report_calls("report_use_ok")
+ assert (ok.permission, ok.feature, ok.target) == (
+ PermissionId.AUTOMATION,
+ "audio_ducking",
+ _MUSIC,
+ )
+ d.restore([1])
+ assert d.mute_others(own_pid=1, never=frozenset()) == [1]
+ assert len(gate.report_calls("report_use_ok")) == 1 # a healthy session never reports again
+ assert gate.native_free()
+
+
+def test_a_healthy_session_never_calls_the_failed_use_reports():
+ gate = FakePermissionService()
+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "40"})
+ d = _ducker(run, access_gate=gate)
+ tokens = d.mute_others(own_pid=1, never=frozenset())
+ d.restore(tokens)
+ assert d.mute_others(own_pid=1, never=frozenset()) == [1, 2]
+ assert gate.report_calls() == []
+
+
+def test_a_player_that_is_not_running_is_no_evidence_that_a_send_landed():
+ """The ``is running`` guard answers ``-`` before any Apple event is sent."""
+ refused = subprocess.CompletedProcess(
+ ["osascript"], 1, stdout="", stderr="Not authorized to send Apple events (-1743)"
+ )
+ gate = FakePermissionService()
+ run = FakeRunner({_MUSIC: refused, _SPOTIFY: "-"})
+ d = _ducker(run, access_gate=gate)
+ d.mute_others(own_pid=1, never=frozenset())
+
+ run._results[_MUSIC] = "-" # Music quit: nothing was sent, so nothing was proven
+ d.mute_others(own_pid=1, never=frozenset())
+
+ assert gate.report_calls("report_use_ok") == []
+
+
+def test_a_gate_without_the_report_calls_still_gets_the_older_background_episode():
+ """A scripted stub has no ``report_failed_use``: the miss goes through a plain ensure."""
+ refused = subprocess.CompletedProcess(
+ ["osascript"], 1, stdout="", stderr="Not authorized to send Apple events (-1743)"
+ )
+ inner = FakePermissionService()
+
+ class BareGate:
+ def check(self, permission, *, target=None):
+ return inner.check(permission, target=target)
+
+ def ensure(self, permission, **kwargs):
+ return inner.ensure(permission, **kwargs)
+
+ run = FakeRunner({_MUSIC: refused, _SPOTIFY: "70"})
+ d = _ducker(run, access_gate=BareGate())
+ assert d.mute_others(own_pid=1, never=frozenset()) == [2]
+ assert [c.interactive for c in inner.ensure_calls(PermissionId.AUTOMATION)] == [False]
+
+ run._results[_MUSIC] = "65" # and a landed send is simply not reported
+ assert d.mute_others(own_pid=1, never=frozenset()) == [1, 2]
+
+
+def test_a_report_that_hangs_never_stalls_the_session_and_the_other_player_still_ducks(
+ monkeypatch,
+):
+ release = threading.Event()
+ entered = threading.Event()
+
+ class HungReportGate(FakePermissionService):
+ def report_failed_use(self, permission, **kwargs):
+ entered.set()
+ release.wait(10)
+ return super().report_failed_use(permission, **kwargs)
+
+ refused = subprocess.CompletedProcess(
+ ["osascript"], 1, stdout="", stderr="Not authorized to send Apple events (-1743)"
+ )
+ monkeypatch.setattr(macos, "_PROBE_TIMEOUT_S", 0.05)
+ d = _ducker(FakeRunner({_MUSIC: refused, _SPOTIFY: "70"}), access_gate=HungReportGate())
+ started = time.monotonic()
+ try:
+ assert d.mute_others(own_pid=1, never=frozenset()) == [2]
+ assert entered.is_set() # the report really was out
+ finally:
+ release.set()
+ assert time.monotonic() - started < 2.0
+
+
+def test_a_report_that_raises_is_logged_and_never_breaks_the_session(caplog):
+ """AP-30: the failure is contained, the session carries on, and it leaves a trace."""
+
+ class BrokenGate(FakePermissionService):
+ def report_failed_use(self, permission, **kwargs):
+ raise RuntimeError("the permission service is broken")
+
+ refused = subprocess.CompletedProcess(
+ ["osascript"], 1, stdout="", stderr="Not authorized to send Apple events (-1743)"
+ )
+ d = _ducker(FakeRunner({_MUSIC: refused, _SPOTIFY: "70"}), access_gate=BrokenGate())
+ with caplog.at_level("DEBUG", logger="jarvis.audio.ducking"):
+ assert d.mute_others(own_pid=1, never=frozenset()) == [2]
+ messages = [record.getMessage() for record in caplog.records]
+ assert any("bounded" in m and "failed" in m for m in messages)
+ assert any("was not delivered to the permission service" in m for m in messages)
+
+
+def test_prewarm_asks_through_the_gate_for_running_players_only():
+ run = FakeRunner({_MUSIC: "+", _SPOTIFY: "-"})
+ gate = FakePermissionService({PermissionId.AUTOMATION: "granted"})
+ report = _ducker(run, access_gate=gate).prewarm()
+ calls = gate.ensure_calls(PermissionId.AUTOMATION)
+ # The ask runs on a worker thread, so it waits for the dialog (budget minus a margin).
+ (call,) = calls
+ assert (call.target, call.interactive) == (_MUSIC, True)
+ assert call.wait_s == pytest.approx(macos._ASK_BUDGET_S - macos._ASK_WAIT_MARGIN_S)
+ assert [p.player for p in report.players] == ["Music"]
+ assert report.not_running == ("Spotify",)
+ assert all("is running" in s and "tell application" not in s for s in run.scripts)
diff --git a/tests/unit/audio/test_ducking_permissions.py b/tests/unit/audio/test_ducking_permissions.py
new file mode 100644
index 0000000000..2c1e7dbef4
--- /dev/null
+++ b/tests/unit/audio/test_ducking_permissions.py
@@ -0,0 +1,624 @@
+"""Mute music while dictating: the Automation permission, asked just in time.
+
+The REAL permission service runs on a REAL ``SystemPermissionPort`` that sits on
+``FakeTCC`` (``tests/fakes/fake_tcc.py``), a stateful model of macOS privacy, and the
+ducker's ``osascript`` is a stand-in that answers like macOS for the scripts the
+ducker sends. The FakeTCC call log is the proof of what was (not) asked. Nothing here
+ran on a real Mac: every behaviour is a MODEL (see the fidelity ledger in fake_tcc.py).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import subprocess
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.audio.ducking import macos
+from jarvis.audio.ducking.controller import AudioDuckController
+from jarvis.audio.ducking.macos import MacOSScriptDucker
+from jarvis.audio.ducking.windows import WindowsPycawDucker
+from jarvis.platform import permission_service as service_module
+from jarvis.platform.permission_service import get_permission_service
+from jarvis.platform.permissions import AUTOMATION_TARGETS, PermissionId
+from tests.fakes.fake_permission_service import FakePermissionService
+from tests.fakes.fake_tcc import (
+ AE_EVENT_NOT_PERMITTED,
+ CallKind,
+ DialogPolicy,
+ FakeTCC,
+ TccService,
+ install_port,
+ make_non_darwin_port,
+)
+from tests.unit.platform.test_permission_service import LoopThread, RecordingBus
+
+_MUSIC = "com.apple.Music"
+_SPOTIFY = "com.spotify.client"
+_AUTOMATION = PermissionId.AUTOMATION
+_DENIED_STDERR = "execution error: Not authorized to send Apple events to Music. (-1743)"
+
+
+class TccAppleScript:
+ """An ``osascript`` stand-in that answers like macOS for the ducker's scripts.
+
+ A pure running-state query is answered from ``FakeTCC``. A script that SENDS an
+ Apple event to a player succeeds only with the grant, fails with ``-1743`` when it
+ was denied, and is recorded in ``sends_without_decision`` when macOS would have
+ shown its consent dialog in the middle of the call: a test that asserts the list
+ stays empty proves nothing was scripted behind the user's back.
+ """
+
+ def __init__(self, tcc: FakeTCC, *, volume: int = 65) -> None:
+ self.tcc = tcc
+ self.volume = volume
+ self.scripts: list[str] = []
+ self.sends: list[str] = []
+ self.sends_without_decision: list[str] = []
+ self.refuse_with_1743: set[str] = set()
+
+ @staticmethod
+ def _bundle(script: str) -> str | None:
+ return next(
+ (bundle for _name, bundle in AUTOMATION_TARGETS if f'"{bundle}"' in script), None
+ )
+
+ def __call__(self, script: str) -> subprocess.CompletedProcess:
+ self.scripts.append(script)
+ bundle = self._bundle(script)
+ if bundle is None: # the master-volume tier
+ return subprocess.CompletedProcess(["osascript"], 0, stdout="50\n", stderr="")
+ running = self.tcc.player_running(bundle)
+ if "tell application" not in script: # the pure "is it running" query
+ return subprocess.CompletedProcess(
+ ["osascript"], 0, stdout="+\n" if running else "-\n", stderr=""
+ )
+ if not running:
+ return subprocess.CompletedProcess(["osascript"], 0, stdout="-\n", stderr="")
+ self.sends.append(bundle)
+ state = self.tcc.state(TccService.AUTOMATION, bundle).value
+ if state == "not_determined":
+ self.sends_without_decision.append(bundle)
+ if state != "granted" or bundle in self.refuse_with_1743:
+ return subprocess.CompletedProcess(["osascript"], 1, stdout="", stderr=_DENIED_STDERR)
+ return subprocess.CompletedProcess(["osascript"], 0, stdout=f"{self.volume}\n", stderr="")
+
+
+def _world(monkeypatch: pytest.MonkeyPatch, **tcc_kwargs):
+ """A Mac with Music installed and running; returns (tcc, osascript, ducker)."""
+ tcc_kwargs.setdefault("installed_players", [_MUSIC])
+ tcc_kwargs.setdefault("running_players", [_MUSIC])
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ osa = TccAppleScript(tcc)
+ return tcc, osa, MacOSScriptDucker(run=osa)
+
+
+def _requests(tcc: FakeTCC) -> list[str]:
+ return [call.target for call in tcc.requests("automation")]
+
+
+# ----------------------------------------------------------------------
+# Switching on: prewarm() is the one asking path
+# ----------------------------------------------------------------------
+
+
+def test_switching_on_with_music_running_asks_exactly_once_and_names_the_player(monkeypatch):
+ tcc, osa, ducker = _world(monkeypatch)
+ report = ducker.prewarm()
+ assert _requests(tcc) == [_MUSIC] # one ask, for the running player only
+ assert len(tcc.dialogs_shown("automation")) == 1
+ (music,) = report.players
+ assert (music.player, music.target) == ("Music", _MUSIC)
+ assert music.outcome == "granted" and music.asked and music.reason == ""
+ assert report.not_running == ("Spotify",) and report.note == ""
+ assert tcc.implicit_prompts() == []
+ # The ducker never scripts the player itself to provoke a dialog, and carries no
+ # private copy of the consent script any more (the port owns it).
+ assert not osa.sends and not any("get player state" in s for s in osa.scripts)
+ assert not hasattr(macos, "_prewarm_script")
+ assert "consent_run" not in inspect.signature(MacOSScriptDucker).parameters
+
+
+def test_every_player_ask_gets_the_full_budget_not_the_leftover(monkeypatch):
+ """A slow first dialog must not starve the second ask into a late, lost dialog."""
+ import time
+
+ tcc = FakeTCC(installed_players=[_MUSIC, _SPOTIFY], running_players=[_MUSIC, _SPOTIFY])
+ runs: list[str] = []
+
+ def slow_consent_runner(script: str):
+ runs.append(_MUSIC if _MUSIC in script else _SPOTIFY)
+ time.sleep(0.6) # the person takes a while to answer each dialog
+ return tcc.automation_consent_runner(script)
+
+ install_port(monkeypatch, tcc.port("darwin", automation_consent_runner=slow_consent_runner))
+ # One ask fits the budget, two do not: a shared deadline would leave the second
+ # ask 0.4 s, report "unavailable" and still leave its dialog open on the screen.
+ monkeypatch.setattr(macos, "_ASK_BUDGET_S", 1.0)
+ report = MacOSScriptDucker(run=TccAppleScript(tcc)).prewarm()
+ assert runs == [_MUSIC, _SPOTIFY]
+ assert [(p.player, p.outcome, p.asked) for p in report.players] == [
+ ("Music", "granted", True),
+ ("Spotify", "granted", True),
+ ]
+
+
+def test_a_dialog_still_open_at_the_end_of_the_wait_is_pending_and_never_granted(monkeypatch):
+ """The consent runner blocks until the person answers: the service answers PENDING at
+ the end of the wait (budget minus a margin) instead of the ducker blocking forever."""
+ import time
+
+ tcc = FakeTCC(installed_players=[_MUSIC], running_players=[_MUSIC])
+ release = threading.Event()
+
+ def stuck_consent_runner(script: str):
+ release.wait(5)
+ return tcc.automation_consent_runner(script)
+
+ install_port(monkeypatch, tcc.port("darwin", automation_consent_runner=stuck_consent_runner))
+ # The wait must end well BEFORE the hung-call backstop. With a 0.5 s budget the real
+ # margin (10 % of it) is 50 ms, which a loaded macOS runner can eat: the backstop then
+ # wins and the expected "pending" comes back as "unavailable".
+ monkeypatch.setattr(macos, "_ASK_BUDGET_S", 3.0)
+ monkeypatch.setattr(macos, "_ask_wait_s", lambda: 0.3)
+ started = time.monotonic()
+ try:
+ (music,) = MacOSScriptDucker(run=TccAppleScript(tcc)).prewarm().players
+ finally:
+ release.set()
+ assert time.monotonic() - started < 2.0
+ assert music.outcome == "pending" and music.asked # asked once, no answer yet
+ assert music.outcome != "granted"
+
+
+def test_an_ask_that_hangs_inside_the_gate_is_unavailable_and_never_granted(monkeypatch):
+ """The budget stays the backstop for a native call that never returns."""
+ import time
+
+ release = threading.Event()
+
+ class HungGate(FakePermissionService):
+ def ensure(self, permission, **kwargs):
+ release.wait(5)
+ return super().ensure(permission, **kwargs)
+
+ tcc = FakeTCC(installed_players=[_MUSIC], running_players=[_MUSIC])
+ monkeypatch.setattr(macos, "_ASK_BUDGET_S", 0.1)
+ ducker = MacOSScriptDucker(run=TccAppleScript(tcc), access_gate=HungGate())
+ started = time.monotonic()
+ try:
+ (music,) = ducker.prewarm().players
+ finally:
+ release.set()
+ assert time.monotonic() - started < 2.0
+ assert music.outcome == "unavailable" and not music.asked
+
+
+def test_the_ask_waits_on_the_request_thread_for_the_budget_minus_a_margin(monkeypatch):
+ """prewarm() is a worker-thread caller: it must pass wait_s, never rely on wait_s=0."""
+ seen: list[float] = []
+
+ class RecordingGate(FakePermissionService):
+ def ensure(self, permission, **kwargs):
+ seen.append(kwargs["wait_s"])
+ return super().ensure(permission, **kwargs)
+
+ tcc = FakeTCC(installed_players=[_MUSIC], running_players=[_MUSIC])
+ ducker = MacOSScriptDucker(run=TccAppleScript(tcc), access_gate=RecordingGate())
+ ducker.prewarm()
+ assert seen == [pytest.approx(macos._ASK_BUDGET_S - macos._ASK_WAIT_MARGIN_S)]
+ assert 0 < seen[0] < macos._ASK_BUDGET_S
+
+
+def test_switching_on_again_does_not_ask_a_second_time(monkeypatch):
+ tcc, _osa, ducker = _world(monkeypatch)
+ ducker.prewarm()
+ again = ducker.prewarm()
+ assert _requests(tcc) == [_MUSIC]
+ assert again.players[0].outcome == "granted" and not again.players[0].asked
+
+
+def test_switching_on_with_no_player_running_asks_nothing_and_says_so(monkeypatch):
+ tcc, osa, ducker = _world(monkeypatch, installed_players=[_MUSIC, _SPOTIFY], running_players=[])
+ report = ducker.prewarm()
+ assert tcc.calls_of(CallKind.REQUEST) == [] and tcc.implicit_prompts() == []
+ assert not osa.sends # a player is never launched or scripted to find out
+ assert report.players == () and set(report.not_running) == {"Music", "Spotify"}
+ assert "checked while the player is running" in report.note
+ body = report.as_dict()
+ assert body["checked"] is False and body["asked"] is False and body["players"] == []
+
+
+def test_a_player_that_is_not_running_is_not_asked_even_when_another_one_is(monkeypatch):
+ tcc, _osa, ducker = _world(
+ monkeypatch, installed_players=[_MUSIC, _SPOTIFY], running_players=[_SPOTIFY]
+ )
+ report = ducker.prewarm()
+ assert _requests(tcc) == [_SPOTIFY]
+ assert [p.player for p in report.players] == ["Spotify"] and report.not_running == ("Music",)
+
+
+def test_a_denied_player_is_reported_skipped_and_never_asked_again(monkeypatch):
+ tcc, osa, ducker = _world(monkeypatch, default_policy=DialogPolicy.DENY)
+ first = ducker.prewarm().players[0]
+ assert first.outcome == "denied" and first.reason == "denied" and first.asked
+ assert first.can_open_settings and "Automation access for Music" in first.detail
+ assert _requests(tcc) == [_MUSIC]
+
+ # A voice session (non-interactive) and a second switch-on: no new question.
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == []
+ second = ducker.prewarm().players[0]
+ assert second.outcome == "denied" and not second.asked
+ assert _requests(tcc) == [_MUSIC]
+ assert tcc.ignored_requests() == [] # macOS was not even bothered with a repeat
+ assert not osa.sends # a denied player is never scripted
+
+
+def test_outside_the_installed_app_the_ask_is_withheld_and_reported(monkeypatch):
+ tcc, _osa, ducker = _world(
+ monkeypatch, bundle_id=None, bundle_path="/usr/bin/python3", granted=()
+ )
+ player = ducker.prewarm().players[0]
+ assert tcc.requests() == [] # no native request without an explicit confirmation
+ assert player.outcome == "needs_settings" and player.outside_installed_app
+ assert player.asked is False
+
+
+# ----------------------------------------------------------------------
+# A voice session never asks
+# ----------------------------------------------------------------------
+
+
+def test_mute_others_never_asks_and_never_scripts_an_unasked_player(monkeypatch):
+ tcc, osa, ducker = _world(monkeypatch)
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == []
+ assert tcc.calls_of(CallKind.REQUEST) == [] and tcc.implicit_prompts() == []
+ assert not osa.sends and osa.sends_without_decision == []
+ # The miss is recorded for the status snapshot: a background episode, never a toast.
+ (episode,) = get_permission_service().outstanding()
+ assert (episode.feature, episode.origin, episode.target) == (
+ "audio_ducking",
+ "background",
+ _MUSIC,
+ )
+ assert episode.reason == "not_determined" and episode.permissions == ("automation",)
+
+
+def test_a_player_that_is_not_running_leaves_no_episode(monkeypatch):
+ tcc, _osa, ducker = _world(monkeypatch, running_players=[])
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == []
+ assert get_permission_service().outstanding() == []
+ assert tcc.calls_of(CallKind.REQUEST) == []
+
+
+def test_mute_others_ducks_a_player_with_a_live_grant_and_asks_nothing(monkeypatch):
+ tcc, osa, ducker = _world(monkeypatch, granted=[TccService.AUTOMATION])
+ tokens = ducker.mute_others(own_pid=1, never=frozenset())
+ assert tokens == [1] and osa.sends == [_MUSIC]
+ assert tcc.calls_of(CallKind.REQUEST) == []
+ ducker.restore(tokens)
+ assert get_permission_service().outstanding() == []
+
+
+def test_a_grant_given_in_system_settings_is_used_by_the_next_session(monkeypatch):
+ tcc, osa, ducker = _world(monkeypatch)
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == []
+ tcc.grant(TccService.AUTOMATION, _MUSIC) # the user flipped the switch
+ get_permission_service().invalidate() # the ~250 ms negative window has passed
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == [1]
+ assert osa.sends == [_MUSIC] and tcc.calls_of(CallKind.REQUEST) == []
+
+
+def test_minus_1743_after_granted_skips_the_player_and_reports_needs_settings(monkeypatch):
+ tcc, osa, ducker = _world(monkeypatch, granted=[TccService.AUTOMATION])
+ osa.refuse_with_1743.add(_MUSIC) # the probe says granted, the real sender is refused
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == []
+ assert osa.sends == [_MUSIC]
+ assert tcc.calls_of(CallKind.REQUEST) == [] # nothing is asked because of it
+
+ player = ducker.prewarm().players[0]
+ assert (player.outcome, player.reason) == ("needs_settings", "needs_settings")
+ assert player.can_open_settings and not player.asked
+ assert "Automation access for Music" in player.detail
+ assert tcc.calls_of(CallKind.REQUEST) == []
+
+ osa.refuse_with_1743.clear() # fixed in System Settings: the next duck lands
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == [1]
+ assert ducker.prewarm().players[0].outcome == "granted"
+
+
+def events():
+ """The real service with a bus attached, so a test can read what it published."""
+ loop = LoopThread()
+ bus = RecordingBus()
+ get_permission_service().attach_bus(bus, loop.loop)
+ yield SimpleNamespace(bus=bus, flush=loop.flush)
+ # The watcher task lives on this loop: stop the service before the loop.
+ service_module._reset_for_tests()
+ loop.stop()
+
+
+def _two_players_one_refused(monkeypatch):
+ """Music and Spotify both read GRANTED; the real sender is refused for Music only."""
+ tcc, osa, ducker = _world(
+ monkeypatch,
+ installed_players=[_MUSIC, _SPOTIFY],
+ running_players=[_MUSIC, _SPOTIFY],
+ granted=[TccService.AUTOMATION],
+ )
+ osa.refuse_with_1743.add(_MUSIC)
+ return tcc, osa, ducker
+
+
+def test_minus_1743_after_granted_at_mute_time_opens_one_background_episode(monkeypatch, events):
+ tcc, osa, ducker = _two_players_one_refused(monkeypatch)
+
+ # Music (token 1) is skipped, Spotify (token 2) still ducks.
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == [2]
+ events.flush()
+
+ assert osa.sends == [_MUSIC, _SPOTIFY]
+ tcc.assert_no_prompts() # nothing is asked because of a refusal
+ assert tcc.requests() == [] and tcc.dialogs_shown() == []
+ (episode,) = get_permission_service().outstanding()
+ assert (
+ episode.feature,
+ episode.permissions,
+ episode.reason,
+ episode.phase,
+ episode.origin,
+ episode.target,
+ ) == ("audio_ducking", ("automation",), "needs_settings", "blocked", "background", _MUSIC)
+ assert episode.can_open_settings and not episode.can_prompt
+ assert "Automation access for Music" in episode.detail
+ # ONE event, background origin: only the status snapshot shows it,
+ # never a toast (that opens for the user origin only).
+ needed = events.bus.needed()
+ assert [(e.origin, e.reason, e.target) for e in needed] == [
+ ("background", "needs_settings", _MUSIC)
+ ]
+
+
+def test_the_refusal_persists_across_sessions_without_a_second_event_or_a_request(
+ monkeypatch, events
+):
+ tcc, osa, ducker = _two_players_one_refused(monkeypatch)
+
+ first = ducker.mute_others(own_pid=1, never=frozenset())
+ ducker.restore(first)
+ second = ducker.mute_others(own_pid=1, never=frozenset())
+ events.flush()
+
+ assert first == second == [2] # the ducker keeps skipping Music and keeps ducking Spotify
+ assert osa.sends.count(_MUSIC) == 2 # it retries every session: that is how a fix is noticed
+ assert len(get_permission_service().outstanding()) == 1
+ assert len(events.bus.needed()) == 1 and events.bus.resolved() == []
+ assert tcc.requests() == []
+
+
+def test_a_later_successful_send_clears_the_episode(monkeypatch, events):
+ tcc, osa, ducker = _two_players_one_refused(monkeypatch)
+ ducker.restore(ducker.mute_others(own_pid=1, never=frozenset()))
+ assert len(get_permission_service().outstanding()) == 1
+
+ osa.refuse_with_1743.clear() # fixed in System Settings: the next duck lands
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == [1, 2]
+ events.flush()
+
+ assert get_permission_service().outstanding() == []
+ [resolved] = events.bus.resolved()
+ assert (resolved.feature, resolved.permissions, resolved.granted) == (
+ "audio_ducking",
+ ("automation",),
+ True,
+ )
+ assert tcc.requests() == []
+
+
+def test_a_probe_that_still_reads_granted_does_not_resolve_it(monkeypatch, events):
+ """The probe is exactly what lied: only a send that landed may end the episode."""
+ tcc, osa, ducker = _two_players_one_refused(monkeypatch)
+ ducker.mute_others(own_pid=1, never=frozenset())
+ service = get_permission_service()
+
+ for _ in range(3): # what the 2 s watcher and every status read do
+ service.invalidate()
+ assert service.check(PermissionId.AUTOMATION, target=_MUSIC).value == "granted"
+ service.refresh_episodes()
+ events.flush()
+
+ assert [e.reason for e in service.outstanding()] == ["needs_settings"]
+ assert events.bus.resolved() == []
+ assert tcc.requests() == []
+
+
+def test_switching_on_again_after_a_refusal_that_is_then_allowed_for_real_clears_it(
+ monkeypatch, events
+):
+ """A fresh ask that was allowed went through the real sender: the refusal is over."""
+ tcc, osa, ducker = _two_players_one_refused(monkeypatch)
+ ducker.mute_others(own_pid=1, never=frozenset())
+ assert len(get_permission_service().outstanding()) == 1
+
+ tcc.reset(TccService.AUTOMATION, _MUSIC) # the decision is gone: macOS will ask again
+ get_permission_service().invalidate()
+ report = ducker.prewarm()
+ events.flush()
+
+ music = next(p for p in report.players if p.player == "Music")
+ assert music.outcome == "granted" and music.asked
+ assert [call.target for call in tcc.requests("automation")] == [_MUSIC] # ONE ask, by prewarm
+ assert get_permission_service().outstanding() == []
+ assert [r.granted for r in events.bus.resolved()] == [True]
+
+
+async def test_a_report_that_hangs_never_holds_the_controller_session_start_up(monkeypatch):
+ """The controller holds its lock around mute_others: a service call must be bounded."""
+ release, entered = threading.Event(), threading.Event()
+
+ class HungReportGate(FakePermissionService):
+ def report_failed_use(self, permission, **kwargs):
+ entered.set()
+ release.wait(10)
+ return super().report_failed_use(permission, **kwargs)
+
+ monkeypatch.setattr(macos, "_PROBE_TIMEOUT_S", 0.05)
+ tcc = FakeTCC(installed_players=[_MUSIC, _SPOTIFY], running_players=[_MUSIC, _SPOTIFY])
+ tcc.grant(TccService.AUTOMATION, _SPOTIFY) # Music is refused by the real sender
+ ducker = MacOSScriptDucker(run=TccAppleScript(tcc), access_gate=HungReportGate())
+ controller = AudioDuckController(bus=_Bus(), cfg=_cfg(enabled=True), ducker=ducker)
+
+ try:
+ await asyncio.wait_for(controller._on_start(object()), 5)
+ assert entered.is_set() # the report really was out while the session started
+ assert controller._muted == [2] # the other player still ducked
+ assert not controller._lock.locked()
+ finally:
+ release.set()
+
+
+def test_ae_denial_constant_matches_the_script_shape_the_ducker_detects():
+ assert str(AE_EVENT_NOT_PERMITTED) in _DENIED_STDERR
+
+
+def test_a_hung_automation_read_never_stalls_the_session(monkeypatch):
+ release = threading.Event()
+ reads: list[str] = []
+
+ class HungGate(FakePermissionService):
+ def check(self, permission, *, target=None):
+ reads.append(str(target))
+ release.wait(10)
+ return super().check(permission, target=target)
+
+ monkeypatch.setattr(macos, "_PROBE_TIMEOUT_S", 0.05)
+ tcc = FakeTCC(installed_players=[_MUSIC], running_players=[_MUSIC])
+ ducker = MacOSScriptDucker(run=TccAppleScript(tcc), access_gate=HungGate())
+ try:
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == [] # returns, skipped
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == []
+ # A hung read still owns its slot: no second thread piles up behind it.
+ assert reads.count(_MUSIC) == 1 and reads.count(_SPOTIFY) == 1
+ finally:
+ release.set()
+
+
+# ----------------------------------------------------------------------
+# The controller: the ask never holds its lock
+# ----------------------------------------------------------------------
+
+
+class _Bus:
+ def __init__(self) -> None:
+ self.subs: dict[str, object] = {}
+
+ def subscribe(self, event, handler) -> None:
+ self.subs[event.__name__] = handler
+
+
+def _cfg(enabled: bool) -> SimpleNamespace:
+ return SimpleNamespace(
+ ducking=SimpleNamespace(enabled=enabled, restore_delay_ms=0, never_mute=[])
+ )
+
+
+async def test_the_controller_lock_is_free_while_the_dialog_is_open(monkeypatch):
+ release, entered = threading.Event(), threading.Event()
+ asking_thread: list[str] = []
+ tcc = FakeTCC(installed_players=[_MUSIC], running_players=[_MUSIC])
+
+ def blocking_consent_runner(script: str):
+ asking_thread.append(threading.current_thread().name)
+ entered.set()
+ assert release.wait(10), "the test never answered the dialog"
+ return tcc.automation_consent_runner(script)
+
+ install_port(monkeypatch, tcc.port("darwin", automation_consent_runner=blocking_consent_runner))
+ bus = _Bus()
+ controller = AudioDuckController(
+ bus=bus, cfg=_cfg(enabled=False), ducker=MacOSScriptDucker(run=TccAppleScript(tcc))
+ )
+ controller.attach()
+
+ ask = asyncio.create_task(controller.set_enabled(True))
+ try:
+ assert await asyncio.to_thread(entered.wait, 5), "the ask never reached macOS"
+ assert asking_thread[0] != threading.current_thread().name # a worker, not the loop
+ assert not controller._lock.locked() # nobody holds it across the ask
+ # The user starts and ends a voice session while the dialog is still open:
+ # neither handler waits for it, and neither asks anything.
+ await asyncio.wait_for(bus.subs["VoiceSessionStarted"](object()), 5)
+ assert controller._muted == [] # no grant yet: nothing was scripted
+ await asyncio.wait_for(bus.subs["VoiceSessionEnded"](object()), 5)
+ assert not ask.done() and tcc.requests("automation") == []
+ finally:
+ release.set()
+ report = await asyncio.wait_for(ask, 10)
+ assert [call.target for call in tcc.requests("automation")] == [_MUSIC]
+ assert report.players[0].outcome == "granted"
+ # The ducker's own state lock-free too: a later session ducks with the new grant.
+ get_permission_service().invalidate()
+ await asyncio.wait_for(bus.subs["VoiceSessionStarted"](object()), 5)
+ assert controller._muted == [1]
+
+
+# ----------------------------------------------------------------------
+# Boot: a configured-on feature asks nothing until the person switches it on
+# ----------------------------------------------------------------------
+
+
+async def test_boot_with_ducking_enabled_and_players_open_asks_and_reads_nothing(monkeypatch):
+ """Config ``enabled = true`` is not a gesture: building and attaching the controller
+ performs no OS dialog, no request, no probe, and opens no episode."""
+ from jarvis.audio.ducking import factory
+
+ tcc = FakeTCC(installed_players=[_MUSIC, _SPOTIFY], running_players=[_MUSIC, _SPOTIFY])
+ install_port(monkeypatch, tcc.port("darwin"))
+ monkeypatch.setattr(factory, "sys", SimpleNamespace(platform="darwin"))
+ monkeypatch.setattr(factory, "_osascript_available", lambda: True)
+ cfg = _cfg(enabled=True)
+ bus = _Bus()
+
+ ducker = factory.make_audio_ducker(cfg)
+ assert isinstance(ducker, MacOSScriptDucker)
+ controller = AudioDuckController(bus=bus, cfg=cfg, ducker=ducker)
+ controller.attach()
+ await asyncio.sleep(0.05) # nothing may be scheduled behind attach() either
+
+ assert set(bus.subs) == {"VoiceSessionStarted", "VoiceSessionEnded"}
+ tcc.assert_silent() # no framework loaded, no native call of any kind
+ assert get_permission_service().outstanding() == []
+
+
+# ----------------------------------------------------------------------
+# Off macOS nothing changes
+# ----------------------------------------------------------------------
+
+
[email protected]("platform", ["win32", "linux"])
+def test_off_macos_the_ducker_asks_nothing_and_publishes_nothing(monkeypatch, platform):
+ port, tcc = make_non_darwin_port(platform, installed_players=[_MUSIC], running_players=[_MUSIC])
+ install_port(monkeypatch, port)
+ osa = TccAppleScript(tcc)
+ ducker = MacOSScriptDucker(run=osa) # never built off macOS; inert if it were
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == []
+ assert not osa.sends
+ assert get_permission_service().outstanding() == []
+ tcc.assert_silent()
+
+
+async def test_windows_ducking_is_untouched_by_the_permission_work(monkeypatch):
+ port, tcc = make_non_darwin_port("win32")
+ install_port(monkeypatch, port)
+ ducker = WindowsPycawDucker()
+ assert not hasattr(ducker, "prewarm") # no asking path, no permission concept
+ controller = AudioDuckController(bus=_Bus(), cfg=_cfg(enabled=False), ducker=ducker)
+ assert await controller.set_enabled(True) is None # no report: the route adds no key
+ assert await controller.set_enabled(False) is None
+ tcc.assert_silent()
+ assert get_permission_service().outstanding() == []
diff --git a/tests/unit/ci/test_check_frozen_macos_app.py b/tests/unit/ci/test_check_frozen_macos_app.py
new file mode 100644
index 0000000000..707fa886aa
--- /dev/null
+++ b/tests/unit/ci/test_check_frozen_macos_app.py
@@ -0,0 +1,522 @@
+"""``scripts/ci/check_frozen_macos_app.py`` — the gate that stops a broken .dmg.
+
+The v2.5.0 image shipped without the pyobjc ``AVFoundation`` module (the
+microphone permission then reads "unavailable" for good) and with
+``LSBackgroundOnly`` in its ``Info.plist`` (LaunchServices runs it as a faceless
+background process). The probe was run against that very image by hand and
+reports exactly those two problems; these tests pin its decisions.
+
+It also asserts the privacy declarations of the bundle: the single table of
+usage-description strings (``jarvis/core/macos_privacy_strings.py``) and, on a
+signed build, the entitlements ``codesign`` reports. No test here runs
+``codesign`` (it exists on macOS only): a stand-in runner returns recorded
+output shapes, and what a real ``codesign`` prints on a real Mac is unverified.
+"""
+
+from __future__ import annotations
+
+import plistlib
+import subprocess
+import sys
+import types
+from collections.abc import Sequence
+from pathlib import Path
+
+import pytest
+
+from jarvis.core import macos_privacy_strings
+from jarvis.core.branding import MACOS_DMG_BUNDLE_ID
+from scripts.ci import check_frozen_macos_app as probe
+
+ALL_MODULES = set(probe.REQUIRED_FROZEN_MODULES) | {"jarvis", "jarvis.platform.permissions"}
+
+
+def _info(**overrides: object) -> dict:
+ info: dict = {
+ "CFBundleIdentifier": MACOS_DMG_BUNDLE_ID,
+ "CFBundleExecutable": "PersonalJarvis",
+ "LSBackgroundOnly": False,
+ **macos_privacy_strings.usage_descriptions(),
+ **macos_privacy_strings.localization_plist_keys(),
+ }
+ info.update(overrides)
+ return info
+
+
+def _bundle(tmp_path: Path, **overrides: object) -> Path:
+ app = tmp_path / "Personal Jarvis.app"
+ (app / "Contents" / "MacOS").mkdir(parents=True)
+ (app / "Contents" / "MacOS" / "PersonalJarvis").write_bytes(b"\xcf\xfa\xed\xfe")
+ with (app / "Contents" / "Info.plist").open("wb") as stream:
+ plistlib.dump(_info(**overrides), stream)
+ macos_privacy_strings.write_localizations(app / "Contents" / "Resources")
+ return app
+
+
+# What `codesign -dvv <app>` prints (to stderr) for the three kinds of build. The
+# shapes follow Apple's tool as documented and as seen in public logs; none was
+# captured from this project's app on a Mac (unverified).
+ADHOC_REPORT = (
+ "Executable=/Applications/Personal Jarvis.app/Contents/MacOS/PersonalJarvis\n"
+ "Identifier=ai.personaljarvis.desktop\n"
+ "Format=app bundle with Mach-O thin (arm64)\n"
+ "CodeDirectory v=20400 size=1234 flags=0x2(adhoc) hashes=30+7 location=embedded\n"
+ "Signature=adhoc\n"
+ "TeamIdentifier=not set\n"
+)
+IDENTITY_REPORT = (
+ "Executable=/Applications/Personal Jarvis.app/Contents/MacOS/PersonalJarvis\n"
+ "Identifier=ai.personaljarvis.desktop\n"
+ "CodeDirectory v=20500 size=1234 flags=0x10000(runtime) hashes=30+7 location=embedded\n"
+ "Authority=Developer ID Application: Example GmbH (ABCDE12345)\n"
+ "Authority=Developer ID Certification Authority\n"
+ "Authority=Apple Root CA\n"
+ "TeamIdentifier=ABCDE12345\n"
+)
+UNSIGNED_REPORT = "/Applications/Personal Jarvis.app: code object is not signed at all\n"
+
+
+def _entitlements_xml(entitlements: dict) -> bytes:
+ return plistlib.dumps(entitlements)
+
+
+def _codesign(report: str, *, entitlements: bytes = b"", header: bytes = b"", returncode: int = 0):
+ """A stand-in ``codesign``: ``-dvv`` answers ``report``; ``--entitlements`` the blob."""
+
+ def run(args: Sequence[str]) -> subprocess.CompletedProcess[bytes]:
+ if "--entitlements" in args:
+ return subprocess.CompletedProcess(
+ ["codesign", *args],
+ returncode,
+ stdout=header + entitlements,
+ stderr=b"Executable=/Applications/Personal Jarvis.app/Contents/MacOS/X\n",
+ )
+ return subprocess.CompletedProcess(
+ ["codesign", *args], returncode, stdout=b"", stderr=report.encode("utf-8")
+ )
+
+ return run
+
+
+def _shipped_entitlements() -> dict:
+ return plistlib.loads(probe.ENTITLEMENTS_FILE.read_bytes())
+
+
+def test_a_good_plist_has_no_problems(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+
+ assert probe.check_info_plist(_info(), app / "Contents" / "MacOS") == []
+
+
+def test_a_background_only_app_is_refused(tmp_path: Path) -> None:
+ app = _bundle(tmp_path, LSBackgroundOnly=True)
+
+ problems = probe.check_info_plist(_info(LSBackgroundOnly=True), app / "Contents" / "MacOS")
+
+ assert len(problems) == 1
+ assert "LSBackgroundOnly" in problems[0]
+
+
+def test_a_bundle_id_the_permission_port_does_not_accept_is_refused(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+
+ problems = probe.check_info_plist(
+ _info(CFBundleIdentifier="com.example.other"), app / "Contents" / "MacOS"
+ )
+
+ assert len(problems) == 1
+ assert MACOS_DMG_BUNDLE_ID in problems[0]
+
+
+def test_a_missing_microphone_usage_string_is_refused(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+
+ problems = probe.check_info_plist(
+ _info(NSMicrophoneUsageDescription=" "), app / "Contents" / "MacOS"
+ )
+
+ assert len(problems) == 1
+ assert "NSMicrophoneUsageDescription" in problems[0]
+ assert "ends the process" in problems[0]
+
+
+def test_a_declared_executable_that_is_not_there_is_refused(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+
+ problems = probe.check_info_plist(
+ _info(CFBundleExecutable="Missing"), app / "Contents" / "MacOS"
+ )
+
+ assert len(problems) == 1
+ assert "Missing" in problems[0]
+
+
+def test_every_required_module_present_is_fine() -> None:
+ assert probe.check_frozen_modules(ALL_MODULES) == []
+
+
+def test_the_v250_archive_without_avfoundation_is_refused() -> None:
+ """The exact defect of the published image."""
+ problems = probe.check_frozen_modules(ALL_MODULES - {"AVFoundation"})
+
+ assert len(problems) == 1
+ assert "AVFoundation" in problems[0]
+ assert "desktop-macos" in problems[0]
+
+
+def test_check_app_reports_both_defects_of_the_published_image(tmp_path: Path) -> None:
+ app = _bundle(tmp_path, LSBackgroundOnly=True)
+
+ problems = probe.check_app(
+ app,
+ read_modules=lambda _exe: ALL_MODULES - {"AVFoundation"},
+ run_codesign=_codesign(ADHOC_REPORT),
+ )
+
+ assert len(problems) == 2
+ assert any("LSBackgroundOnly" in problem for problem in problems)
+ assert any("AVFoundation" in problem for problem in problems)
+
+
+def test_check_app_does_not_read_an_archive_that_cannot_exist(tmp_path: Path) -> None:
+ app = _bundle(tmp_path, CFBundleExecutable="Missing")
+
+ def explode(_exe: Path):
+ raise AssertionError("the archive of a missing executable must not be read")
+
+ assert probe.check_app(app, read_modules=explode, run_codesign=_codesign(ADHOC_REPORT))
+
+
+def test_main_exit_codes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys) -> None:
+ good = _bundle(tmp_path / "good")
+ broken = _bundle(tmp_path / "broken", LSBackgroundOnly=True)
+ monkeypatch.setattr(probe, "frozen_module_names", lambda _exe: ALL_MODULES)
+ monkeypatch.setattr(probe, "_run_codesign", _codesign(ADHOC_REPORT))
+
+ assert probe.main(["--app", str(good)]) == 0
+ out = capsys.readouterr().out
+ assert "OK" in out
+ assert "NOTE" in out and "ad-hoc" in out # the skipped half is said out loud
+ assert probe.main(["--app", str(broken)]) == 1
+ assert "LSBackgroundOnly" in capsys.readouterr().out
+ assert probe.main(["--app", str(tmp_path / "nowhere.app")]) == 2
+ assert "cannot check" in capsys.readouterr().out
+
+
+def test_frozen_module_names_unions_every_embedded_pyz(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The reader walks the executable's table and opens each PYZ it finds."""
+
+ class _Pyz:
+ def __init__(self, names: list[str]) -> None:
+ self.toc = dict.fromkeys(names, (0, 0, 0))
+
+ class _CArchive:
+ def __init__(self, _path: str) -> None:
+ self.toc = {
+ "PYZ-00.pyz": (0, 0, 0, False, "z"),
+ "base_library.zip": (0, 0, 0, False, "b"),
+ "PYZ-01.pyz": (0, 0, 0, False, "z"),
+ }
+
+ def open_embedded_archive(self, name: str) -> _Pyz:
+ return _Pyz(["AVFoundation"] if name == "PYZ-00.pyz" else ["Quartz"])
+
+ readers = types.ModuleType("PyInstaller.archive.readers")
+ readers.CArchiveReader = _CArchive # type: ignore[attr-defined]
+ for name, module in (
+ ("PyInstaller", types.ModuleType("PyInstaller")),
+ ("PyInstaller.archive", types.ModuleType("PyInstaller.archive")),
+ ("PyInstaller.archive.readers", readers),
+ ):
+ monkeypatch.setitem(sys.modules, name, module)
+
+ assert probe.frozen_module_names(Path("anything")) == {"AVFoundation", "Quartz"}
+
+
+# --- the usage-description table ---------------------------------------------
+
+
+def test_every_key_of_the_table_is_asserted_on_the_built_bundle() -> None:
+ assert probe.check_usage_strings(_info()) == []
+ for key in macos_privacy_strings.REQUIRED_USAGE_KEYS:
+ info = _info()
+ del info[key]
+
+ problems = probe.check_usage_strings(info)
+
+ assert len(problems) == 1, key
+ assert key in problems[0] and "missing" in problems[0]
+
+
+def test_a_non_microphone_string_that_is_missing_is_not_called_process_ending() -> None:
+ """Only the microphone case is documented as fatal; the rest is a third-party report."""
+ problems = probe.check_usage_strings(_info(NSScreenCaptureUsageDescription=""))
+
+ assert len(problems) == 1
+ assert "ends the process" not in problems[0]
+ assert "without ever showing a permission prompt" in problems[0]
+
+
+def test_a_string_that_differs_from_the_table_means_the_spec_kept_its_own_copy() -> None:
+ problems = probe.check_usage_strings(_info(NSDesktopFolderUsageDescription="Old wording."))
+
+ assert len(problems) == 1
+ assert "NSDesktopFolderUsageDescription" in problems[0]
+ assert "macos_privacy_strings.py" in problems[0]
+
+
[email protected]("key", macos_privacy_strings.REMOVED_USAGE_KEYS)
+def test_a_removed_key_that_comes_back_is_refused(key: str) -> None:
+ problems = probe.check_usage_strings(_info(**{key: "A string for an API Jarvis never calls."}))
+
+ assert len(problems) == 1
+ assert key in problems[0] and "least privilege" in problems[0]
+
+
+def test_the_plist_check_includes_the_usage_table(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+ info = _info()
+ del info["NSLocalNetworkUsageDescription"]
+
+ problems = probe.check_info_plist(info, app / "Contents" / "MacOS")
+
+ assert len(problems) == 1
+ assert "NSLocalNetworkUsageDescription" in problems[0]
+
+
+# --- German and Spanish localisation --------------------------------------------
+
+
+def test_a_bundle_that_declares_no_localisation_is_refused(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+ info = _info()
+ del info["CFBundleLocalizations"]
+
+ problems = probe.check_info_plist(info, app / "Contents" / "MacOS")
+
+ assert len(problems) == 1
+ assert "CFBundleLocalizations" in problems[0] and "localization_plist_keys" in problems[0]
+
+
+def test_a_wrong_development_region_is_refused(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+
+ problems = probe.check_info_plist(
+ _info(CFBundleDevelopmentRegion="de"), app / "Contents" / "MacOS"
+ )
+
+ assert len(problems) == 1
+ assert "CFBundleDevelopmentRegion" in problems[0]
+
+
+def test_a_localisation_list_without_spanish_is_refused(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+
+ problems = probe.check_info_plist(
+ _info(CFBundleLocalizations=["en", "de"]), app / "Contents" / "MacOS"
+ )
+
+ assert len(problems) == 1 and "CFBundleLocalizations" in problems[0]
+
+
+def test_the_shipped_lproj_files_pass(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+
+ assert probe.check_localization_files(app / "Contents" / "Resources") == []
+
+
[email protected]("language", macos_privacy_strings.LOCALIZED_LANGUAGES)
+def test_a_missing_strings_file_names_the_build_step(tmp_path: Path, language: str) -> None:
+ app = _bundle(tmp_path)
+ (app / "Contents" / "Resources" / f"{language}.lproj" / "InfoPlist.strings").unlink()
+
+ problems = probe.check_localization_files(app / "Contents" / "Resources")
+
+ assert len(problems) == 1
+ assert f"{language}.lproj/InfoPlist.strings is missing" in problems[0]
+ assert "add_localizations.py" in problems[0]
+
+
+def test_a_strings_file_that_is_not_the_table_is_refused(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+ target = app / "Contents" / "Resources" / "de.lproj" / "InfoPlist.strings"
+ target.write_text('"NSMicrophoneUsageDescription" = "Alter Text.";\n', encoding="utf-8")
+
+ problems = probe.check_localization_files(app / "Contents" / "Resources")
+
+ assert len(problems) == 1
+ assert "de.lproj" in problems[0] and "single usage-string table" in problems[0]
+
+
+def test_a_strings_file_that_is_not_utf8_is_refused(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+ target = app / "Contents" / "Resources" / "es.lproj" / "InfoPlist.strings"
+ target.write_bytes("\ufeff".encode("utf-16-le") + b"\xff\xfe\x00")
+
+ problems = probe.check_localization_files(app / "Contents" / "Resources")
+
+ assert len(problems) == 1 and "es.lproj" in problems[0] and "UTF-8" in problems[0]
+
+
+def test_check_app_reports_a_bundle_built_without_the_localisation_step(tmp_path: Path) -> None:
+ app = _bundle(tmp_path)
+ for language in macos_privacy_strings.LOCALIZED_LANGUAGES:
+ (app / "Contents" / "Resources" / f"{language}.lproj" / "InfoPlist.strings").unlink()
+
+ problems = probe.check_app(
+ app, read_modules=lambda _exe: ALL_MODULES, run_codesign=_codesign(ADHOC_REPORT)
+ )
+
+ assert len(problems) == 2
+ assert all("InfoPlist.strings is missing" in problem for problem in problems)
+
+
+# --- entitlements of a signed build ---------------------------------------------
+
+
+def test_an_adhoc_build_skips_the_entitlement_check_and_says_so(tmp_path: Path) -> None:
+ notes: list[str] = []
+
+ problems = probe.check_signature(tmp_path / "A.app", run=_codesign(ADHOC_REPORT), notes=notes)
+
+ assert problems == []
+ assert len(notes) == 1
+ assert "NOT checked" in notes[0] and "ad-hoc" in notes[0]
+ assert "not a pass" in notes[0]
+
+
+def test_an_unsigned_build_skips_the_entitlement_check_and_says_so(tmp_path: Path) -> None:
+ notes: list[str] = []
+
+ problems = probe.check_signature(
+ tmp_path / "A.app", run=_codesign(UNSIGNED_REPORT, returncode=1), notes=notes
+ )
+
+ assert problems == []
+ assert "unsigned" in notes[0] and "NOT checked" in notes[0]
+
+
+def test_a_host_without_codesign_skips_with_a_clear_message(tmp_path: Path) -> None:
+ def no_codesign(_args: Sequence[str]) -> subprocess.CompletedProcess[bytes]:
+ raise FileNotFoundError("codesign")
+
+ notes: list[str] = []
+
+ assert probe.check_signature(tmp_path / "A.app", run=no_codesign, notes=notes) == []
+ assert "codesign is not available on this host" in notes[0]
+
+
+def test_a_signed_build_with_the_shipped_entitlements_passes(tmp_path: Path) -> None:
+ notes: list[str] = []
+ runner = _codesign(IDENTITY_REPORT, entitlements=_entitlements_xml(_shipped_entitlements()))
+
+ assert probe.check_signature(tmp_path / "A.app", run=runner, notes=notes) == []
+ assert notes == []
+
+
+def test_the_entitlement_plist_is_cut_out_of_surrounding_codesign_noise(tmp_path: Path) -> None:
+ """A blob header before the XML, and trailing text after it, must not break parsing."""
+ xml = _entitlements_xml(_shipped_entitlements())
+ runner = _codesign(
+ IDENTITY_REPORT,
+ entitlements=xml + b"\n[trailing tool chatter]\n",
+ header=b"\xfa\xde\x71\x71\x00\x00\x01\x00",
+ )
+
+ assert probe.check_signature(tmp_path / "A.app", run=runner, notes=[]) == []
+
+
+def test_a_signed_build_that_embedded_no_entitlements_is_refused(tmp_path: Path) -> None:
+ runner = _codesign(IDENTITY_REPORT, entitlements=b"")
+
+ problems = probe.check_signature(tmp_path / "A.app", run=runner, notes=[])
+
+ expected = _shipped_entitlements()
+ assert len(problems) == len(expected)
+ for key in expected:
+ assert any(key in problem for problem in problems)
+
+
+def test_a_signed_build_missing_one_entitlement_names_it(tmp_path: Path) -> None:
+ entitlements = _shipped_entitlements()
+ del entitlements["com.apple.security.device.audio-input"]
+ runner = _codesign(IDENTITY_REPORT, entitlements=_entitlements_xml(entitlements))
+
+ problems = probe.check_signature(tmp_path / "A.app", run=runner, notes=[])
+
+ assert len(problems) == 1
+ assert "com.apple.security.device.audio-input" in problems[0]
+
+
+def test_an_entitlement_set_to_false_counts_as_missing(tmp_path: Path) -> None:
+ entitlements = _shipped_entitlements()
+ entitlements["com.apple.security.automation.apple-events"] = False
+ runner = _codesign(IDENTITY_REPORT, entitlements=_entitlements_xml(entitlements))
+
+ problems = probe.check_signature(tmp_path / "A.app", run=runner, notes=[])
+
+ assert len(problems) == 1
+ assert "apple-events" in problems[0]
+
+
+def test_the_camera_entitlement_coming_back_on_a_signed_build_is_refused(tmp_path: Path) -> None:
+ entitlements = {**_shipped_entitlements(), "com.apple.security.device.camera": True}
+ runner = _codesign(IDENTITY_REPORT, entitlements=_entitlements_xml(entitlements))
+
+ problems = probe.check_signature(tmp_path / "A.app", run=runner, notes=[])
+
+ assert len(problems) == 1
+ assert "device.camera" in problems[0] and "least privilege" in problems[0]
+
+
+def test_a_signature_codesign_output_i_cannot_classify_is_cannot_check(tmp_path: Path) -> None:
+ runner = _codesign("something unexpected\n", returncode=1)
+
+ with pytest.raises(RuntimeError, match="no signature kind"):
+ probe.check_signature(tmp_path / "A.app", run=runner, notes=[])
+
+
+def test_the_shipped_entitlements_file_has_nothing_the_gate_forbids() -> None:
+ shipped = _shipped_entitlements()
+
+ assert not set(shipped) & set(probe.REMOVED_ENTITLEMENTS)
+ assert probe.check_entitlements(shipped, shipped) == []
+
+
+def test_main_reports_a_signed_build_with_a_missing_entitlement_as_broken(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys
+) -> None:
+ entitlements = _shipped_entitlements()
+ del entitlements["com.apple.security.cs.disable-library-validation"]
+ monkeypatch.setattr(probe, "frozen_module_names", lambda _exe: ALL_MODULES)
+ monkeypatch.setattr(
+ probe,
+ "_run_codesign",
+ _codesign(IDENTITY_REPORT, entitlements=_entitlements_xml(entitlements)),
+ )
+
+ assert probe.main(["--app", str(_bundle(tmp_path))]) == 1
+ out = capsys.readouterr().out
+ assert "disable-library-validation" in out
+ assert "NOTE" not in out
+
+
+def test_main_on_a_host_without_codesign_passes_with_a_note(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys
+) -> None:
+ def no_codesign(_args: Sequence[str]) -> subprocess.CompletedProcess[bytes]:
+ raise FileNotFoundError("codesign")
+
+ monkeypatch.setattr(probe, "frozen_module_names", lambda _exe: ALL_MODULES)
+ monkeypatch.setattr(probe, "_run_codesign", no_codesign)
+
+ assert probe.main(["--app", str(_bundle(tmp_path))]) == 0
+ assert "NOTE - entitlements NOT checked" in capsys.readouterr().out
+
+
+def test_help_lists_the_one_required_argument(capsys) -> None:
+ with pytest.raises(SystemExit) as raised:
+ probe.main(["--help"])
+
+ assert raised.value.code == 0
+ assert "--app" in capsys.readouterr().out
diff --git a/tests/unit/ci/test_macos_carbon_hotkey_spike.py b/tests/unit/ci/test_macos_carbon_hotkey_spike.py
new file mode 100644
index 0000000000..6572401c98
--- /dev/null
+++ b/tests/unit/ci/test_macos_carbon_hotkey_spike.py
@@ -0,0 +1,2274 @@
+"""``scripts/ci/macos_carbon_hotkey_spike.py`` - the evidence tool for a future Carbon backend.
+
+Nothing here runs Carbon, AppKit or a macOS runner, and nothing here is evidence
+about macOS behaviour. These tests pin the parts that CAN be checked on Linux:
+
+* the experiment catalogue (names and order are the report contract),
+* signal / outcome classification, tails, JSON assembly and the summary tables,
+* the evidence rule (a granted preflight voids a run),
+* the shape of the ctypes surface (``restype``/``argtypes`` of every function,
+ struct sizes, four-character codes) against an in-memory fake Carbon, and the
+ sequencing of every scenario against that same fake,
+* the REAL ctypes marshalling against a tiny C library that exports the Carbon
+ prototypes (skipped without a C compiler): a truncated 64-bit pointer or a
+ by-pointer ``EventHotKeyID`` makes the C side return an error,
+* the process-group handling of the parent against real subprocesses with a
+ sleeping grandchild,
+* the workflow file (dispatch-only, read-only token, pinned actions, summary text).
+
+What a fake or a Linux C library cannot show is whether the real Carbon calls
+behave the same on a real Mac; that stays unverified until the workflow has run there.
+"""
+
+from __future__ import annotations
+
+import ast
+import ctypes
+import json
+import os
+import re
+import shutil
+import signal
+import subprocess
+import sys
+import textwrap
+import threading
+import time
+from pathlib import Path
+from typing import Any
+
+import pytest
+import yaml
+
+from scripts.ci import macos_carbon_hotkey_spike as spike
+
+REPO = Path(__file__).resolve().parents[3]
+WORKFLOW = REPO / ".github" / "workflows" / "macos-hotkey-spike.yml"
+
+EXPECTED_NAMES = (
+ "control_signal_capture",
+ "tcc_context",
+ "carbon_symbols",
+ "nsapp_register_unregister",
+ "register_unregister_cycles",
+ "no_nsapp_register",
+ "unregister_off_main_thread",
+ "duplicate_register",
+ "register_under_secure_input",
+ "install_handler_twice",
+ "appshot_option_state_read",
+)
+
+
[email protected](autouse=True)
+def _fresh_child_state():
+ spike.reset_child_state()
+ yield
+ spike.reset_child_state()
+
+
+# --- catalogue --------------------------------------------------------------------
+
+
+def test_catalogue_names_and_order_are_pinned() -> None:
+ assert spike.experiment_names() == EXPECTED_NAMES
+
+
+def test_catalogue_entries_are_well_formed() -> None:
+ names = spike.experiment_names()
+ assert len(set(names)) == len(names)
+ for experiment in spike.EXPERIMENTS:
+ assert experiment.kind in ("control", "variant", "probe")
+ assert experiment.timeout_s > 0
+ assert experiment.title and experiment.question
+ # Only the signal control and the TCC context (which reports "unsupported" off macOS) run
+ # everywhere; every Carbon experiment needs macOS.
+ assert [e.name for e in spike.EXPERIMENTS if not e.requires_macos] == [
+ "control_signal_capture",
+ "tcc_context",
+ ]
+ # Only controls carry an expectation; variants are measurements.
+ assert {e.name: e.expected_outcome for e in spike.EXPERIMENTS if e.expected_outcome} == {
+ "control_signal_capture": "crash",
+ "carbon_symbols": "ok",
+ }
+
+
+def test_every_catalogued_experiment_has_a_child_scenario() -> None:
+ assert set(spike._SCENARIOS) == set(spike.experiment_names())
+
+
+def test_select_experiments() -> None:
+ assert spike.select_experiments("") == spike.EXPERIMENTS
+ picked = spike.select_experiments("duplicate_register, carbon_symbols")
+ assert [e.name for e in picked] == ["carbon_symbols", "duplicate_register"]
+ with pytest.raises(ValueError, match="bogus"):
+ spike.select_experiments("carbon_symbols,bogus")
+
+
+def test_the_tcc_context_always_runs_first_whatever_only_selects() -> None:
+ # The report's TCC block comes from this child: `--only` must not be able to drop it.
+ planned = spike.plan_experiments("duplicate_register")
+ assert [e.name for e in planned] == ["tcc_context", "duplicate_register"]
+ assert spike.plan_experiments("") == spike.EXPERIMENTS
+ assert [e.name for e in spike.plan_experiments("tcc_context")] == ["tcc_context"]
+ with pytest.raises(ValueError, match="bogus"):
+ spike.plan_experiments("bogus")
+ # It runs before every Carbon variant (the signal control, which loads nothing, is earlier).
+ names = list(spike.experiment_names())
+ assert names.index("tcc_context") < names.index("carbon_symbols")
+
+
+# --- classification ----------------------------------------------------------------
+
+
+ ("returncode", "expected"),
+ [
+ (-int(signal.SIGSEGV), "SIGSEGV"),
+ (-int(signal.SIGABRT), "SIGABRT"),
+ (-int(signal.SIGILL), "SIGILL"),
+ (-999, "SIG999"),
+ (0, None),
+ (1, None),
+ (None, None),
+ ],
+)
+def test_signal_name(returncode: int | None, expected: str | None) -> None:
+ assert spike.signal_name(returncode) == expected
+
+
+ ("kwargs", "expected"),
+ [
+ ({"returncode": None, "timed_out": True, "child_ok": None}, "timeout"),
+ ({"returncode": -11, "timed_out": True, "child_ok": None}, "timeout"),
+ ({"returncode": -11, "timed_out": False, "child_ok": None}, "crash"),
+ ({"returncode": -6, "timed_out": False, "child_ok": True}, "crash"),
+ ({"returncode": 0, "timed_out": False, "child_ok": True}, "ok"),
+ ({"returncode": 0, "timed_out": False, "child_ok": False}, "error"),
+ ({"returncode": 0, "timed_out": False, "child_ok": None}, "error"),
+ ({"returncode": 1, "timed_out": False, "child_ok": True}, "error"),
+ ({"returncode": None, "timed_out": False, "child_ok": None}, "error"),
+ ],
+)
+def test_classify_outcome(kwargs: dict[str, Any], expected: str) -> None:
+ assert spike.classify_outcome(**kwargs) == expected
+ assert expected in spike.OUTCOMES
+
+
+def test_tail_text() -> None:
+ assert spike.tail_text(None) == ""
+ assert spike.tail_text(b"abc\x00def") == "abcdef"
+ assert spike.tail_text("x" * 5000, limit=10) == "x" * 10
+ assert spike.tail_text(b"\xff\xfeok").endswith("ok") # undecodable bytes never raise
+
+
+def test_summarize_argv_drops_machine_specific_directories() -> None:
+ argv = ["/opt/hostedtoolcache/Python/3.12/bin/python3", "/Users/runner/w/s.py", "--child", "x"]
+ assert spike.summarize_argv(argv) == ["python3", "s.py", "--child", "x"]
+ assert spike.summarize_argv([]) == []
+
+
+def test_parse_child_result_takes_the_last_result_line() -> None:
+ out = "STEP a=1\n" + spike.RESULT_PREFIX + '{"ok": false}\nnoise\n'
+ out += spike.RESULT_PREFIX + '{"ok": true, "n": 2}\n'
+ assert spike.parse_child_result(out) == {"ok": True, "n": 2}
+ assert spike.parse_child_result("no result here\n") is None
+ broken = spike.parse_child_result(spike.RESULT_PREFIX + "{nope\n")
+ assert broken is not None and "ok" not in broken and "_parse_error" in broken
+ assert "_parse_error" in (spike.parse_child_result(spike.RESULT_PREFIX + "[1]\n") or {})
+
+
+def test_last_breadcrumb_locates_a_crash() -> None:
+ out = "STEP install_handler=0\nSTEP register=0\nFatal Python error: Segmentation fault\n"
+ assert spike.last_breadcrumb(out) == "register=0"
+ assert spike.last_breadcrumb("nothing") is None
+
+
+def test_child_environment_sets_utf8_and_faulthandler_without_dropping_the_base() -> None:
+ env = spike.child_environment({"PATH": "/bin", "HOME": "/h"})
+ assert env["PATH"] == "/bin" and env["HOME"] == "/h"
+ assert env["PYTHONFAULTHANDLER"] == "1" and env["PYTHONUTF8"] == "1"
+ assert env["PYTHONUNBUFFERED"] == "1"
+
+
+def test_probe_records_failures_and_prefers_the_first_working_source() -> None:
+ def broken() -> bool:
+ raise ImportError("no pyobjc")
+
+ result = spike.probe("x", [("pyobjc", broken), ("ctypes", lambda: True)])
+ assert result["value"] is True and result["source"] == "ctypes" and result["error"] is None
+ assert result["attempts"] == [{"source": "pyobjc", "error": "ImportError: no pyobjc"}]
+
+ failed = spike.probe("x", [("pyobjc", broken), ("ctypes", broken)])
+ assert failed["value"] is None and failed["source"] is None
+ assert "pyobjc: ImportError" in failed["error"] and len(failed["attempts"]) == 2
+
+ assert spike.probe("x", [])["error"] == "no source available"
+
+
+# --- evidence rule -----------------------------------------------------------------
+
+
+def _tcc(listen: Any = False, trusted: Any = False, iohid: Any = 1) -> dict[str, Any]:
+ def entry(value: Any) -> dict[str, Any]:
+ return {"value": value, "error": None if value is not None else "unreadable"}
+
+ return {
+ "supported": True,
+ "probes": {
+ "cg_preflight_listen_event": entry(listen),
+ "ax_is_process_trusted": entry(trusted),
+ "iohid_check_access_listen": entry(iohid),
+ },
+ }
+
+
+def _nsapp_row(
+ *,
+ pressed: int,
+ requested: bool = True,
+ tcc: Any = None,
+ register: int = 0,
+ pressed_after_unregister: int = 0,
+ injection_seen: bool | None = True,
+ outcome: str = "ok",
+) -> dict[str, Any]:
+ """A ``nsapp_register_unregister`` row as the parent assembles it (steps + counts)."""
+ steps = [
+ {"step": "register", "value": register},
+ {"step": "pressed_while_registered", "value": pressed},
+ {"step": "injection_seen_while_registered", "value": injection_seen},
+ {"step": "pressed_after_unregister", "value": pressed_after_unregister},
+ ]
+ total = pressed + pressed_after_unregister
+ return {
+ "name": "nsapp_register_unregister",
+ "outcome": outcome,
+ "observations": {
+ "tcc": tcc,
+ "steps": steps,
+ "event_counts": {"pressed": total, "released": total},
+ "synthetic_key_requested": requested,
+ },
+ }
+
+
+def test_evidence_is_usable_only_with_false_preflights_and_a_delivered_event() -> None:
+ verdict = spike.evaluate_evidence(_tcc(), [_nsapp_row(pressed=1, tcc=_tcc())])
+ assert verdict["preflights_all_false"] is True
+ assert verdict["carbon_event_delivered"] is True
+ assert verdict["delivery_conclusion"] == "delivered"
+ assert verdict["usable_as_evidence"] is True
+ assert verdict["tcc_source"] == "child"
+ assert spike.EVIDENCE_RULE == verdict["rule"]
+
+
+ "tcc",
+ [_tcc(listen=True), _tcc(trusted=True), _tcc(iohid=0)],
+ ids=["listen-granted", "ax-trusted", "iohid-granted"],
+)
+def test_a_granted_preflight_voids_the_run(tcc: dict[str, Any]) -> None:
+ verdict = spike.evaluate_evidence(tcc, [_nsapp_row(pressed=1)])
+ assert verdict["preflights_all_false"] is False
+ assert verdict["usable_as_evidence"] is False
+ assert any("discard" in note for note in verdict["notes"])
+
+
+def test_the_childs_own_tcc_beats_the_parents() -> None:
+ verdict = spike.evaluate_evidence(_tcc(), [_nsapp_row(pressed=1, tcc=_tcc(listen=True))])
+ assert verdict["tcc_source"] == "child"
+ assert verdict["preflights_all_false"] is False
+
+
+def test_unreadable_preflight_is_not_claimable() -> None:
+ verdict = spike.evaluate_evidence(_tcc(trusted=None), [_nsapp_row(pressed=1)])
+ assert verdict["preflights_all_false"] is None
+ assert verdict["usable_as_evidence"] is False
+
+
+def test_delivery_unknown_without_a_synthetic_key_and_false_without_an_event() -> None:
+ off = spike.evaluate_evidence(_tcc(), [_nsapp_row(pressed=0, requested=False)])
+ assert off["carbon_event_delivered"] is None and off["usable_as_evidence"] is False
+ none_arrived = spike.evaluate_evidence(_tcc(), [_nsapp_row(pressed=0)])
+ assert none_arrived["carbon_event_delivered"] is False
+ assert spike.evaluate_evidence(_tcc(), [])["carbon_event_delivered"] is None
+ unsupported = spike.evaluate_evidence({"supported": False, "probes": {}}, [])
+ assert unsupported["preflights_all_false"] is None
+ assert unsupported["tcc_source"] == "tcc_context" # the separate tcc_context child
+ assert unsupported["delivery_conclusion"] == "unknown"
+
+
+def test_a_press_after_the_unregister_is_not_a_delivery_while_registered() -> None:
+ # The regression: nothing arrived while registered, but one Pressed arrived in the
+ # 'after_unregister' window. The whole-scenario total (1) used to make this usable evidence
+ # that Carbon needs no grant; the delivery is judged on the registered window alone.
+ row = _nsapp_row(pressed=0, pressed_after_unregister=1)
+ assert row["observations"]["event_counts"]["pressed"] == 1
+ verdict = spike.evaluate_evidence(_tcc(), [row])
+ assert verdict["preflights_all_false"] is True
+ assert verdict["carbon_event_delivered"] is False
+ assert verdict["usable_as_evidence"] is False
+
+
+def test_a_failed_registration_never_counts_as_a_delivery() -> None:
+ row = _nsapp_row(pressed=1, register=spike.EVENT_HOT_KEY_EXISTS_ERR, outcome="error")
+ verdict = spike.evaluate_evidence(_tcc(), [row])
+ assert verdict["carbon_event_delivered"] is False
+ assert verdict["delivery_conclusion"] == "registration_failed"
+ assert verdict["usable_as_evidence"] is False
+ assert any(f"OSStatus {spike.EVENT_HOT_KEY_EXISTS_ERR}" in note for note in verdict["notes"])
+
+
[email protected]("outcome", ["error", "crash", "timeout"])
+def test_a_variant_that_did_not_end_ok_is_not_clean_evidence(outcome: str) -> None:
+ # A delivered Pressed with an unexpected status elsewhere (e.g. the unregister did not
+ # take effect) is a real observation but not usable evidence.
+ verdict = spike.evaluate_evidence(_tcc(), [_nsapp_row(pressed=1, outcome=outcome)])
+ assert verdict["carbon_event_delivered"] is True and verdict["variant_ok"] is False
+ assert verdict["usable_as_evidence"] is False
+ assert any("not clean evidence" in note for note in verdict["notes"])
+
+
+ ("injection_seen", "conclusion"),
+ [(True, "not_delivered"), (False, "inconclusive"), (None, "inconclusive")],
+)
+def test_no_event_is_only_a_carbon_failure_when_the_injection_was_seen_independently(
+ injection_seen: bool | None, conclusion: str
+) -> None:
+ # Zero delivered events looks the same whether Carbon is silent or osascript never sent a
+ # key (no Automation/Accessibility grant). The key-down counter is the control.
+ row = _nsapp_row(pressed=0, injection_seen=injection_seen)
+ verdict = spike.evaluate_evidence(_tcc(), [row])
+ assert verdict["carbon_event_delivered"] is False
+ assert verdict["delivery_conclusion"] == conclusion
+ assert verdict["injection_seen_independently"] is injection_seen
+ assert verdict["usable_as_evidence"] is False
+ if conclusion == "inconclusive":
+ assert any("inconclusive" in note for note in verdict["notes"])
+
+
+def test_injection_seen_compares_the_key_down_counters() -> None:
+ assert spike.injection_seen(
+ {"combined_session": 3, "hid_system": 0}, {"combined_session": 4, "hid_system": 0}
+ )
+ assert spike.injection_seen({"a": 1}, {"a": 1}) is False
+ assert spike.injection_seen(None, {"a": 1}) is None
+ assert spike.injection_seen({"a": 1}, None) is None
+
+
+def test_step_value_reads_the_recorded_step_or_none() -> None:
+ observations = {"steps": [{"step": "register", "value": 0}, {"step": "x", "value": None}]}
+ assert spike.step_value(observations, "register") == 0
+ assert spike.step_value(observations, "missing") is None
+ assert spike.step_value({}, "register") is None
+ assert spike.step_value({"steps": "register"}, "register") is None
+
+
+# --- appshot read ------------------------------------------------------------------
+
+
+def test_compare_option_reads_with_no_key_held() -> None:
+ reads = {
+ "combined_session": {"key_left": False, "key_right": False, "flags_raw": 0x100},
+ "hid_system": {"key_left": False, "key_right": False, "flags_raw": 0},
+ }
+ result = spike.compare_option_reads(reads)
+ assert result["as_expected_no_key_held"] is True and not result["any_pressed_reported"]
+ assert result["states"]["combined_session"]["flags_raw_hex"] == "0x100"
+ assert all(state["agree"] for state in result["states"].values())
+ assert "cannot show whether KeyState needs Input Monitoring" in result["limitation"]
+
+
+def test_compare_option_reads_flags_a_disagreement_between_the_two_apis() -> None:
+ alt = spike.K_CG_EVENT_FLAG_MASK_ALTERNATE | spike.NX_DEVICE_RIGHT_ALT_KEY_MASK
+ reads = {"combined_session": {"key_left": False, "key_right": False, "flags_raw": alt}}
+ state = spike.compare_option_reads(reads)["states"]["combined_session"]
+ assert state["flags_alternate"] is True and state["flags_right_device_bit"] is True
+ assert state["flags_left_device_bit"] is False and state["agree"] is False
+ assert spike.compare_option_reads(reads)["as_expected_no_key_held"] is False
+
+
+def _read(left: bool = False, right: bool = False, flags: int = 0) -> dict[str, Any]:
+ return {"key_left": left, "key_right": right, "flags_raw": flags}
+
+
+def test_merge_option_samples_keeps_the_peak_of_the_window() -> None:
+ # The key is down for only part of the window: the peak must not depend on timing.
+ samples = [
+ {"hid_system": _read(), "combined_session": _read(flags=0x100)},
+ {"hid_system": _read(left=True), "combined_session": _read(flags=0x80000 | 0x20)},
+ {"hid_system": _read(), "combined_session": _read(flags=0x100)},
+ ]
+ merged = spike.merge_option_samples(samples)
+ assert merged["hid_system"] == {"key_left": True, "key_right": False, "flags_raw": 0}
+ assert merged["combined_session"]["flags_raw"] == 0x100 | 0x80000 | 0x20
+ assert spike.merge_option_samples([]) == {}
+
+
+def _phase(reads: dict[str, Any], exit_status: int | None = 0) -> dict[str, Any]:
+ return {"reads": reads, "injection_exit": exit_status, "samples": 7}
+
+
+def test_option_hold_verdict_without_an_injection_says_only_the_baseline_was_read() -> None:
+ baseline = {"hid_system": _read(), "combined_session": _read()}
+ verdict = spike.option_hold_verdict(baseline, {})
+ assert verdict["phases"] == {} and verdict["any_api_saw_option"] is False
+ assert verdict["baseline"]["as_expected_no_key_held"] is True
+ assert any("only the no-key baseline" in note for note in verdict["notes"])
+ assert "not decided here" in verdict["limitation"]
+
+
+def test_option_hold_verdict_separates_keystate_from_flagsstate_per_source_state() -> None:
+ baseline = {"hid_system": _read(), "combined_session": _read()}
+ alt = spike.K_CG_EVENT_FLAG_MASK_ALTERNATE | spike.NX_DEVICE_RIGHT_ALT_KEY_MASK
+ phases = {
+ # FlagsState (combined) saw the right Option; KeyState saw nothing anywhere.
+ "cgevent_right_option": _phase(
+ {"hid_system": _read(), "combined_session": _read(flags=alt)}
+ ),
+ # KeyState (HID) saw the left Option; FlagsState saw nothing.
+ "cgevent_left_option": _phase(
+ {"hid_system": _read(left=True), "combined_session": _read()}
+ ),
+ }
+ verdict = spike.option_hold_verdict(baseline, phases)
+ right = verdict["phases"]["cgevent_right_option"]["states"]["combined_session"]
+ assert right["flagsstate_saw_option"] is True and right["keystate_saw_option"] is False
+ assert right["sides_seen"] == ["right"]
+ left = verdict["phases"]["cgevent_left_option"]["states"]["hid_system"]
+ assert left["keystate_saw_option"] is True and left["flagsstate_saw_option"] is False
+ assert left["sides_seen"] == ["left"]
+ assert verdict["any_api_saw_option"] is True and verdict["injected_routes_exit_0"] == 2
+ assert any("FlagsState saw the key, KeyState did not" in n for n in verdict["notes"])
+ assert any("KeyState saw the key, FlagsState did not" in n for n in verdict["notes"])
+
+
+def test_option_hold_verdict_is_inconclusive_when_no_api_saw_a_held_key() -> None:
+ # The exact failure the old no-key read could not tell apart: everything false.
+ baseline = {"hid_system": _read(), "combined_session": _read()}
+ nothing = {"hid_system": _read(), "combined_session": _read(flags=0x100)}
+ verdict = spike.option_hold_verdict(baseline, {"system_events_option": _phase(nothing)})
+ assert verdict["any_api_saw_option"] is False
+ assert any("inconclusive" in note for note in verdict["notes"])
+ # A failed injection route is its own conclusion: nothing can be said about the key.
+ failed = spike.option_hold_verdict(baseline, {"system_events_option": _phase(nothing, 1)})
+ assert failed["injected_routes_exit_0"] == 0
+ assert any("no injection route exited 0" in note for note in failed["notes"])
+
+
+def test_option_hold_script_holds_then_always_releases() -> None:
+ by_name = {phase.name: phase for phase in spike.OPTION_HOLD_PHASES}
+ assert list(by_name) == ["system_events_option", "cgevent_left_option", "cgevent_right_option"]
+ events = spike.option_hold_script(by_name["system_events_option"], 2.5)
+ assert (
+ events.index("key down option") < events.index("delay 2.5") < events.index("key up option")
+ )
+ assert events.count("key up option") == 2 # normal path and the error path
+ assert "error errorMessage number errorNumber" in events # a failure is re-raised, not hidden
+ left = spike.option_hold_script(by_name["cgevent_left_option"], 2.5)
+ right = spike.option_hold_script(by_name["cgevent_right_option"], 2.5)
+ assert "CGEventCreateKeyboardEvent(null, 58, down)" in left
+ assert "CGEventCreateKeyboardEvent(null, 61, down)" in right
+ assert "finally" in left and "post(false)" in left.split("finally")[1]
+ with pytest.raises(ValueError, match="unsupported"):
+ spike.option_hold_script(spike.OptionHoldPhase("x", "javascript", None, "no key code"))
+
+
+def test_option_holder_builds_the_osascript_command_line_per_language() -> None:
+ by_name = {phase.name: phase for phase in spike.OPTION_HOLD_PHASES}
+ apple = spike.OptionHolder(by_name["system_events_option"], run=lambda *a, **k: None)
+ assert apple.argv()[:2] == ["osascript", "-e"] and "key down option" in apple.argv()[2]
+ js = spike.OptionHolder(by_name["cgevent_right_option"], run=lambda *a, **k: None)
+ assert js.argv()[:3] == ["osascript", "-l", "JavaScript"] and js.argv()[3] == "-e"
+
+
+class _FakeHolder:
+ """A holder that finishes after a fixed number of samples, like osascript does."""
+
+ def __init__(self, phase: Any, *, exit_status: int | None = 0, samples_needed: int = 3) -> None:
+ self.phase = phase
+ self.timeout_s = 1.0
+ self.done = threading.Event()
+ self.result: dict[str, Any] = {"returncode": exit_status}
+ self.samples_needed = samples_needed
+
+ def start(self) -> None:
+ pass
+
+
+def test_hold_and_sample_takes_the_peak_and_one_read_after_the_release() -> None:
+ phase = spike.OPTION_HOLD_PHASES[1]
+ reads = iter(
+ [
+ {"hid_system": _read()},
+ {"hid_system": _read(left=True)}, # the key is down for the middle sample only
+ {"hid_system": _read()},
+ {"hid_system": _read(right=True)}, # a stuck key after the release
+ ]
+ )
+ holder = _FakeHolder(phase)
+
+ def read() -> Any:
+ value = next(reads)
+ if len(holder_samples) >= 2:
+ holder.done.set()
+ holder_samples.append(value)
+ return value
+
+ holder_samples: list[Any] = []
+ result = spike.hold_and_sample(
+ phase, read, holder_factory=lambda _phase: holder, sleep=lambda _s: None
+ )
+ assert result["samples"] == 3 and result["finished"] is True
+ assert result["reads"]["hid_system"]["key_left"] is True
+ assert result["reads_after_release"]["hid_system"]["key_right"] is True
+ assert result["injection_exit"] == 0
+
+
+def test_hold_and_sample_gives_up_at_the_deadline_when_osascript_never_finishes() -> None:
+ clock_values = iter([0.0, 1.0, 2.0, 3.0, 100.0, 101.0])
+ holder = _FakeHolder(spike.OPTION_HOLD_PHASES[0], exit_status=None)
+ result = spike.hold_and_sample(
+ spike.OPTION_HOLD_PHASES[0],
+ lambda: {"hid_system": _read()},
+ holder_factory=lambda _phase: holder,
+ sleep=lambda _s: None,
+ clock=lambda: next(clock_values),
+ )
+ assert result["finished"] is False and result["injection_exit"] is None
+ assert result["samples"] >= 1
+
+
+class _FakeCoreGraphics:
+ """CGEventSource*State stand-ins: the Option key reads down while ``held`` is set."""
+
+ def __init__(self) -> None:
+ self.held: set[int] = set()
+
+ def bind(self, _frameworks: Any, symbol: str, _restype: Any, _argtypes: Any) -> Any:
+ if symbol == "CGEventSourceKeyState":
+ return lambda _state, key: int(key in self.held)
+ if symbol == "CGEventSourceFlagsState":
+ return lambda _state: spike.K_CG_EVENT_FLAG_MASK_ALTERNATE if self.held else 0
+ raise OSError(symbol)
+
+
+def test_the_appshot_scenario_reads_a_held_key_and_reports_a_verdict(monkeypatch) -> None:
+ graphics = _FakeCoreGraphics()
+ monkeypatch.setattr(spike, "_bind_symbol", graphics.bind)
+
+ class Holder(_FakeHolder):
+ """Only the left-Option route 'works': it holds key 58 down, then releases it."""
+
+ def start(self) -> None:
+ graphics.held = {spike.VK_OPTION} if self.phase.key_code == spike.VK_OPTION else set()
+
+ def release() -> None:
+ graphics.held = set()
+ self.done.set()
+
+ threading.Timer(0.15, release).start()
+
+ monkeypatch.setattr(spike, "OptionHolder", Holder)
+ spike._STATE.inject = True
+ result = spike._scenario_appshot_option_state_read()
+ steps = _steps()
+ assert steps["combined_session_keystate_left"] is False # the no-key baseline
+ assert steps["cgevent_left_option_osascript_exit"] == 0
+ assert steps["cgevent_left_option_any_api_saw_option"] is True
+ assert steps["cgevent_right_option_any_api_saw_option"] is False
+ assert steps["system_events_option_any_api_saw_option"] is False
+ assert steps["cgevent_left_option_stuck_after_release"] is False
+ assert result["verdict"]["injected_routes_exit_0"] == 3
+ json.dumps(result)
+
+
+def test_the_appshot_scenario_without_injection_records_that_no_key_was_held(monkeypatch) -> None:
+ monkeypatch.setattr(spike, "_bind_symbol", _FakeCoreGraphics().bind)
+ result = spike._scenario_appshot_option_state_read()
+ assert _steps()["hold_phases"] == "not_requested"
+ assert result["phases"] == {} and result["comparison"]["as_expected_no_key_held"] is True
+
+
+# --- child result assembly ---------------------------------------------------------
+
+
+def test_count_events_and_child_ok_and_headline() -> None:
+ events = [
+ {"kind": "pressed", "on_main_thread": True},
+ {"kind": "released", "on_main_thread": False},
+ {"kind": "kind_9", "on_main_thread": True},
+ ]
+ counts = spike.count_events(events)
+ assert counts == {"pressed": 1, "released": 1, "other": 1, "off_main_thread": 1}
+ steps = [
+ {"step": "register", "value": 0, "expected": 0, "ok": True},
+ {"step": "unregister", "value": -9879, "expected": 0, "ok": False},
+ {"step": "note", "value": "short"},
+ {"step": "long", "value": "x" * 40},
+ {"step": "detail", "value": None},
+ ]
+ assert spike.child_ok(steps[:1], []) is True
+ assert spike.child_ok(steps, []) is False
+ assert spike.child_ok(steps[:1], ["boom"]) is False
+ headline = spike.build_headline(steps, counts)
+ assert headline == "register=0 unregister=-9879 note=short pressed=1 released=1"
+
+
+def test_assemble_child_result_forces_ok_false_and_is_json_serialisable() -> None:
+ steps = [{"step": "register", "value": 0, "expected": 0, "ok": True}]
+ result = spike.assemble_child_result(
+ "x", {"ok": False, "k": 1}, steps=steps, events=[], errors=[], tcc=None, inject=True
+ )
+ assert result["ok"] is False and result["k"] == 1 and result["synthetic_key_requested"] is True
+ json.dumps(result)
+ fine = spike.assemble_child_result(
+ "x", {}, steps=steps, events=[], errors=[], tcc={"supported": True}, inject=False
+ )
+ assert fine["ok"] is True and fine["tcc"] == {"supported": True}
+
+
+# --- run_experiment (the subprocess is a recording fake) ---------------------------
+
+
+class _Done:
+ def __init__(self, returncode: int, stdout: bytes = b"", stderr: bytes = b"") -> None:
+ self.returncode = returncode
+ self.stdout = stdout
+ self.stderr = stderr
+
+
+class _Runner:
+ def __init__(self, outcome: Any) -> None:
+ self.outcome = outcome
+ self.calls: list[tuple[list[str], dict[str, Any]]] = []
+
+ def __call__(self, argv: list[str], **kwargs: Any) -> Any:
+ self.calls.append((argv, kwargs))
+ if isinstance(self.outcome, BaseException):
+ raise self.outcome
+ return self.outcome
+
+
+def _experiment(name: str = "duplicate_register") -> spike.Experiment:
+ return spike.experiment_by_name(name)
+
+
+def _run(outcome: Any, name: str = "duplicate_register", **kwargs: Any):
+ runner = _Runner(outcome)
+ row = spike.run_experiment(
+ _experiment(name),
+ script_path=Path("/x/spike.py"),
+ python="/py/python3",
+ run=runner,
+ clock=iter([10.0, 12.5]).__next__,
+ platform_name="darwin",
+ environ={"PATH": "/bin"},
+ **kwargs,
+ )
+ return row, runner
+
+
+def test_run_experiment_records_a_signal_death_as_a_crash_with_the_last_step() -> None:
+ stdout = b"STEP install_handler=0\nSTEP register=0\n"
+ segv = -int(signal.SIGSEGV) # the host signal table decides the name
+ row, runner = _run(_Done(segv, stdout, b"Fatal Python error: Segmentation fault\n"))
+ assert row["outcome"] == "crash" and row["signal"] == "SIGSEGV" and row["returncode"] == segv
+ assert row["last_step"] == "register=0"
+ assert "Segmentation fault" in row["stderr_tail"]
+ assert row["duration_s"] == 2.5
+ argv, kwargs = runner.calls[0]
+ assert argv == ["/py/python3", str(Path("/x/spike.py")), "--child", "duplicate_register"]
+ assert kwargs["timeout"] == _experiment().timeout_s
+ assert kwargs["stdin"] == subprocess.DEVNULL
+ assert kwargs["env"]["PYTHONFAULTHANDLER"] == "1"
+ # The runner captures and kills the group itself: no subprocess.run-only options leak in.
+ assert set(kwargs) == {"timeout", "stdin", "env", "creationflags"}
+ assert row["argv"] == ["python3", "spike.py", "--child", "duplicate_register"]
+ assert row["group_killed"] is False and "cleanup_error" not in row
+
+
+def test_run_experiment_passes_the_injection_flag_only_when_asked() -> None:
+ _row, plain = _run(_Done(0))
+ assert "--inject-synthetic-key" not in plain.calls[0][0]
+ _row, injected = _run(_Done(0), inject=True)
+ assert injected.calls[0][0][-1] == "--inject-synthetic-key"
+
+
+def test_run_experiment_records_a_timeout_with_partial_output() -> None:
+ timeout = subprocess.TimeoutExpired(["x"], 1.0, output=b"STEP unregister_off_main=\n")
+ row, _runner = _run(timeout)
+ assert row["outcome"] == "timeout" and row["returncode"] is None and row["signal"] is None
+ assert row["last_step"] == "unregister_off_main="
+
+
+def test_run_experiment_ok_error_and_protocol_violation() -> None:
+ ok = spike.RESULT_PREFIX + json.dumps({"ok": True, "headline": "register=0"})
+ row, _ = _run(_Done(0, ok.encode()))
+ assert row["outcome"] == "ok" and row["observations"]["headline"] == "register=0"
+ assert row["as_expected"] is None # a variant has no expectation
+
+ failed = spike.RESULT_PREFIX + json.dumps({"ok": False})
+ assert _run(_Done(0, failed.encode()))[0]["outcome"] == "error"
+ assert _run(_Done(0, b"no result line"))[0]["outcome"] == "error"
+ assert _run(_Done(3, ok.encode()))[0]["outcome"] == "error"
+
+
+def test_run_experiment_records_the_group_kill_and_a_cleanup_error() -> None:
+ ok = spike.RESULT_PREFIX + json.dumps({"ok": True})
+ leftover = spike.ChildRun(0, ok.encode(), b"", group_killed=True, cleanup_error="boom")
+ row, _ = _run(leftover)
+ assert row["outcome"] == "ok" and row["group_killed"] is True
+ assert row["cleanup_error"] == "boom"
+ table = spike._experiment_row(row)
+ assert "leftover child processes killed" in table[1]
+ timeout = spike.ChildTimeout(
+ ["x"], 1.0, output=b"STEP a=1\n", stderr=b"", group_killed=True, cleanup_error=None
+ )
+ row, _ = _run(timeout)
+ assert row["outcome"] == "timeout" and row["group_killed"] is True
+ assert "leftover" not in spike._experiment_row(row)[1] # a timeout says timeout, once
+
+
+def test_run_experiment_records_a_spawn_failure_as_an_error() -> None:
+ row, _ = _run(FileNotFoundError("no python"))
+ assert row["outcome"] == "error" and "FileNotFoundError" in row["spawn_error"]
+
+
+# --- process-group handling (REAL subprocesses; POSIX only) ------------------------
+
+posix_only = pytest.mark.skipif(os.name != "posix", reason="process groups are POSIX")
+
+#: A child that starts a grandchild sleeping 300 s (it inherits the stdout pipe), prints the
+#: grandchild's pid, then does what ``MODE`` says. Written to a temp file by the tests.
+_GROUP_CHILD = textwrap.dedent(
+ """
+ import json, subprocess, sys, time
+ mode = sys.argv[sys.argv.index("--child") + 1] if "--child" in sys.argv else sys.argv[1]
+ grandchild = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(300)"])
+ print("GRANDCHILD", grandchild.pid, flush=True)
+ if mode == "hang":
+ time.sleep(300)
+ elif mode == "ok_with_stray":
+ print("SPIKE_RESULT " + json.dumps({"ok": True, "name": "x"}), flush=True)
+ sys.exit(0)
+ elif mode == "crash":
+ import os, signal
+ os.kill(os.getpid(), signal.SIGABRT)
+ else:
+ sys.exit(0)
+ """
+)
+
+
+def _grandchild_pid(stdout: bytes | str) -> int:
+ text = stdout.decode() if isinstance(stdout, bytes) else stdout
+ line = next(line for line in text.splitlines() if line.startswith("GRANDCHILD"))
+ return int(line.split()[1])
+
+
+def _process_is_gone(pid: int, timeout_s: float = 5.0) -> bool:
+ """True when ``pid`` no longer runs (a zombie nobody reaped counts as gone)."""
+ has_proc = Path("/proc/self/stat").exists()
+ deadline = time.monotonic() + timeout_s
+ while time.monotonic() < deadline:
+ if has_proc:
+ try:
+ stat = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8")
+ except (FileNotFoundError, ProcessLookupError):
+ # ESRCH (not ENOENT) is raised while the killed task is still exiting.
+ return True
+ if stat.rsplit(") ", 1)[1].split()[0] == "Z":
+ return True
+ else:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return True
+ time.sleep(0.05)
+ return False
+
+
+def _real_run(tmp_path: Path, mode: str, timeout_s: float) -> spike.ChildRun:
+ script = tmp_path / "child.py"
+ script.write_text(_GROUP_CHILD, encoding="utf-8")
+ return spike.run_in_process_group(
+ [sys.executable, str(script), mode],
+ timeout=timeout_s,
+ stdin=subprocess.DEVNULL,
+ env=dict(os.environ),
+ )
+
+
+@posix_only
+def test_a_timeout_kills_the_whole_process_group_not_just_the_child(tmp_path: Path) -> None:
+ # The finding: only the direct child was SIGKILLed, so its descendants (the injector's
+ # osascript) lived on and could press keys into the next experiment.
+ with pytest.raises(spike.ChildTimeout) as raised:
+ _real_run(tmp_path, "hang", timeout_s=2.0)
+ assert raised.value.group_killed is True and raised.value.cleanup_error is None
+ grandchild = _grandchild_pid(raised.value.stdout)
+ assert _process_is_gone(grandchild), "the grandchild survived the timeout"
+
+
+@posix_only
+def test_a_child_that_exited_ok_keeps_its_real_exit_status_when_a_stray_holds_the_pipe(
+ tmp_path: Path,
+) -> None:
+ # The finding's second probe: the child printed its ok result and exited 0, but a grandchild
+ # inherited the stdout pipe, so it was reported as timeout with returncode None. The leader's
+ # exit is noticed within EXIT_POLL_S: the 20 s timeout must NOT be waited out.
+ started = time.monotonic()
+ result = _real_run(tmp_path, "ok_with_stray", timeout_s=20.0)
+ assert result.returncode == 0 and result.group_killed is True
+ assert b"SPIKE_RESULT" in result.stdout
+ assert time.monotonic() - started < 10, "waited for the timeout instead of noticing the exit"
+ assert _process_is_gone(_grandchild_pid(result.stdout))
+
+
+@posix_only
+def test_a_normal_exit_with_no_leftovers_kills_nothing(tmp_path: Path) -> None:
+ script = tmp_path / "quiet.py"
+ script.write_text("print('hi')\n", encoding="utf-8")
+ result = spike.run_in_process_group(
+ [sys.executable, str(script)], timeout=30.0, stdin=subprocess.DEVNULL, env=dict(os.environ)
+ )
+ assert result.returncode == 0 and result.stdout == b"hi\n"
+ assert result.group_killed is False and result.cleanup_error is None
+
+
+@posix_only
+def test_a_crashing_child_is_reported_as_its_signal_and_its_group_is_reaped(
+ tmp_path: Path,
+) -> None:
+ started = time.monotonic()
+ result = _real_run(tmp_path, "crash", timeout_s=20.0)
+ assert result.returncode == -int(signal.SIGABRT) and result.group_killed is True
+ assert time.monotonic() - started < 10, "waited for the timeout instead of noticing the crash"
+ assert _process_is_gone(_grandchild_pid(result.stdout))
+
+
+@posix_only
+def test_an_interrupt_of_the_parent_kills_the_group_and_is_not_swallowed(
+ tmp_path: Path, monkeypatch
+) -> None:
+ script = tmp_path / "child.py"
+ script.write_text(_GROUP_CHILD, encoding="utf-8")
+ captured: dict[str, Any] = {}
+ original_popen = subprocess.Popen
+
+ class InterruptedPopen(original_popen):
+ def communicate(self, input=None, timeout=None): # noqa: A002
+ # Wait until the child has started its grandchild, then interrupt like Ctrl-C would.
+ captured["grandchild"] = _grandchild_pid(self.stdout.readline())
+ captured["leader"] = self
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr(subprocess, "Popen", InterruptedPopen)
+ with pytest.raises(KeyboardInterrupt):
+ spike.run_in_process_group(
+ [sys.executable, str(script), "hang"],
+ timeout=60.0,
+ stdin=subprocess.DEVNULL,
+ env=dict(os.environ),
+ )
+ assert _process_is_gone(captured["grandchild"]), "the grandchild survived the interrupt"
+ assert captured["leader"].returncode == -int(signal.SIGKILL) # killed AND reaped (no zombie)
+
+
+def test_kill_process_group_reports_an_empty_group_as_nothing_killed_and_an_error_as_text() -> None:
+ class Leader:
+ def kill(self) -> None:
+ raise PermissionError("no")
+
+ killed, error = spike.kill_process_group(None, leader=Leader())
+ assert killed is False and error == "PermissionError: no"
+ if os.name == "posix":
+ # A pid that cannot be a group: reported as an empty group, not an exception.
+ assert spike.kill_process_group(2**22 + 12345, leader=Leader()) == (False, None)
+
+
+@posix_only
+def test_the_real_runner_drives_run_experiment_end_to_end_with_a_timeout(tmp_path: Path) -> None:
+ script = tmp_path / "child.py"
+ script.write_text(_GROUP_CHILD, encoding="utf-8")
+ hanging = spike.Experiment(
+ name="hang", title="t", kind="variant", question="q", timeout_s=2.0, requires_macos=False
+ )
+ row = spike.run_experiment(
+ hanging, script_path=script, python=sys.executable, platform_name="darwin"
+ )
+ assert row["outcome"] == "timeout" and row["returncode"] is None
+ assert row["group_killed"] is True
+ assert _process_is_gone(_grandchild_pid(row["stdout_tail"]))
+
+
+def test_run_experiment_control_expectation() -> None:
+ row, _ = _run(_Done(-int(signal.SIGABRT)), name="control_signal_capture")
+ assert row["outcome"] == "crash" and row["signal"] == "SIGABRT"
+ assert row["as_expected"] is True
+ row, _ = _run(_Done(0, b""), name="control_signal_capture")
+ assert row["as_expected"] is False
+
+
+def test_run_experiment_skips_macos_experiments_elsewhere_without_spawning() -> None:
+ runner = _Runner(_Done(0))
+ row = spike.run_experiment(
+ _experiment("carbon_symbols"),
+ script_path=Path("/x/spike.py"),
+ run=runner,
+ platform_name="linux",
+ )
+ assert row["outcome"] == "skipped" and "requires macOS" in row["skip_reason"]
+ assert runner.calls == []
+
+
+# --- report assembly and rendering -------------------------------------------------
+
+
+def _report(experiments: list[dict[str, Any]] | None = None) -> dict[str, Any]:
+ runner = {
+ "system": "Darwin",
+ "mac_ver": "15.5",
+ "macos_build": "24F74",
+ "machine": "arm64",
+ "python_version": "3.12.9",
+ }
+ tcc = {
+ "supported": True,
+ "probes": {
+ "cg_preflight_listen_event": {"value": False},
+ "iohid_check_access_listen": {"value": 1, "label": "denied"},
+ },
+ "window_server": {"cg_session_dictionary_present": True, "launchctl_managername": "Aqua"},
+ }
+ rows = experiments or [
+ {
+ "name": "control_signal_capture",
+ "outcome": "crash",
+ "returncode": -6,
+ "signal": "SIGABRT",
+ "duration_s": 0.2,
+ "as_expected": True,
+ "observations": None,
+ },
+ {
+ "name": "duplicate_register",
+ "outcome": "error",
+ "returncode": 0,
+ "signal": None,
+ "duration_s": 3.14159,
+ "observations": {"headline": "register_second=-9878 | pipe\nnewline"},
+ },
+ {
+ "name": "no_nsapp_register",
+ "outcome": "skipped",
+ "returncode": None,
+ "signal": None,
+ "duration_s": 0.0,
+ "skip_reason": "requires macOS (running on linux)",
+ "observations": None,
+ },
+ ]
+ return spike.build_report(
+ runner=runner,
+ tcc=tcc,
+ experiments=rows,
+ started_at="2026-10-01T00:00:00Z",
+ finished_at="2026-10-01T00:01:00Z",
+ options={"inject_synthetic_key": True},
+ )
+
+
+def test_build_report_shape_and_json_round_trip() -> None:
+ report = _report()
+ assert set(report) == {
+ "schema_version",
+ "tool",
+ "disclaimer",
+ "complete",
+ "started_at",
+ "finished_at",
+ "options",
+ "runner",
+ "tcc",
+ "experiments",
+ "evidence",
+ "not_covered",
+ }
+ assert report["complete"] is True
+ assert report["schema_version"] == spike.SCHEMA_VERSION == 1
+ assert report["tool"] == "macos_carbon_hotkey_spike"
+ assert report["disclaimer"] == spike.EVIDENCE_DISCLAIMER
+ assert json.loads(json.dumps(report)) == report
+ assert set(report["evidence"]) >= {
+ "rule",
+ "tcc_source",
+ "preflights",
+ "preflights_all_false",
+ "carbon_event_delivered",
+ "delivery_conclusion",
+ "variant_ok",
+ "usable_as_evidence",
+ "notes",
+ }
+ assert report["not_covered"] == list(spike.NOT_COVERED)
+
+
+def test_the_report_says_what_it_does_not_cover() -> None:
+ covered = " ".join(spike.NOT_COVERED)
+ assert "Variant G" in covered and "flip criterion 1" in covered
+ assert "off-main REGISTER" in covered
+ markdown = spike.render_summary_markdown(_report())
+ text = spike.render_summary_text(_report())
+ for item in spike.NOT_COVERED:
+ assert item in markdown and item in text
+
+
+def test_the_disclaimer_is_the_required_sentence() -> None:
+ assert spike.EVIDENCE_DISCLAIMER.startswith(
+ "Runner evidence only: runners pre-grant TCC to bash/osascript/Terminal; "
+ "no dialog is shown, no physical keyboard exists, "
+ "no key-hold semantics were exercised"
+ )
+
+
+def test_markdown_summary_has_the_tables_the_sentence_and_clean_cells() -> None:
+ markdown = spike.render_summary_markdown(_report())
+ assert spike.EVIDENCE_DISCLAIMER in markdown
+ assert "| Experiment | Outcome | Exit | Signal | Secs | Observations |" in markdown
+ assert "| TCC context (recorded first) | Value |" in markdown
+ assert (
+ "| control_signal_capture | crash (control as expected) | -6 | SIGABRT | 0.2 |" in markdown
+ )
+ assert "requires macOS (running on linux)" in markdown
+ assert "iohid_check_access_listen | 1 (denied)" in markdown
+ # A pipe or newline in an observation must not break the table.
+ row = next(line for line in markdown.splitlines() if line.startswith("| duplicate_register"))
+ assert row.count("|") == 7 and "\n" not in row
+ assert "Evidence gate:" in markdown and markdown.endswith("\n")
+
+
+def test_markdown_carries_the_whole_evidence_rule_not_a_truncated_one() -> None:
+ # The rule defines what counts as evidence; md_cell's 160-character cap used to cut it off
+ # in 'AXIsPro...' so a reader of the step summary never saw the IOHIDCheckAccess condition.
+ assert len(spike.EVIDENCE_RULE) > 160
+ markdown = spike.render_summary_markdown(_report())
+ assert spike.EVIDENCE_RULE in markdown
+ assert (
+ "IOHIDCheckAccess(listen)" in markdown and "..." not in markdown.split("Evidence gate")[1]
+ )
+
+
+def test_a_partial_report_is_marked_in_both_summaries() -> None:
+ partial = spike.build_report(
+ runner={},
+ tcc={"supported": False, "reason": "x", "probes": {}},
+ experiments=[],
+ started_at="a",
+ finished_at="b",
+ options={},
+ complete=False,
+ )
+ assert partial["complete"] is False
+ assert "Partial report" in spike.render_summary_markdown(partial)
+ assert "PARTIAL REPORT" in spike.render_summary_text(partial)
+ assert "Partial" not in spike.render_summary_markdown(_report())
+
+
+def test_text_summary_lists_every_experiment_and_the_sentence() -> None:
+ text = spike.render_summary_text(_report())
+ for name in ("control_signal_capture", "duplicate_register", "no_nsapp_register"):
+ assert name in text
+ assert "evidence: preflights_all_false=" in text
+ assert text.rstrip().endswith(spike.EVIDENCE_DISCLAIMER)
+ assert "macOS 15.5 (24F74) arm64" in text
+
+
+def test_summaries_render_an_empty_experiment_list() -> None:
+ report = _report([])
+ assert "evidence:" in spike.render_summary_text(report)
+ assert "Evidence gate" in spike.render_summary_markdown(report)
+
+
+def test_md_cell() -> None:
+ assert spike.md_cell("a|b\nc") == "a/b c"
+ assert len(spike.md_cell("x" * 500)) == 160
+ assert len(spike.md_cell("x" * 500, limit=300)) == 300
+ assert spike.md_cell("x|y\n" * 500, limit=None) == ("x/y " * 500).strip() # never cut
+
+
+# --- the ctypes surface (shape only; no framework is loaded) -----------------------
+
+
+def test_four_character_codes_and_struct_sizes() -> None:
+ assert spike.fourcc("keyb") == 0x6B657962 == spike.K_EVENT_CLASS_KEYBOARD
+ assert spike.fourcc("----") == 0x2D2D2D2D == spike.K_EVENT_PARAM_DIRECT_OBJECT
+ assert spike.fourcc("hkid") == 0x686B6964 == spike.TYPE_EVENT_HOT_KEY_ID
+ assert spike.fourcc("JRVS") == 0x4A525653 == spike.HOT_KEY_SIGNATURE
+ with pytest.raises(ValueError, match="exactly 4"):
+ spike.fourcc("abc")
+ assert ctypes.sizeof(spike.EventHotKeyID) == 8
+ assert ctypes.sizeof(spike.EventTypeSpec) == 8
+ assert spike.TEST_MODIFIERS == 0x1800 and spike.TEST_KEY_CODE == 0x26
+ assert (spike.VK_OPTION, spike.VK_RIGHT_OPTION) == (58, 61)
+
+
+def test_signature_table_pins_the_red_team_crash_surface() -> None:
+ table = spike.CARBON_SIGNATURES
+ assert set(table) == {
+ "GetApplicationEventTarget",
+ "GetEventDispatcherTarget",
+ "InstallEventHandler",
+ "RemoveEventHandler",
+ "RegisterEventHotKey",
+ "UnregisterEventHotKey",
+ "GetEventClass",
+ "GetEventKind",
+ "GetEventParameter",
+ "IsSecureEventInputEnabled",
+ "EnableSecureEventInput",
+ "DisableSecureEventInput",
+ }
+ # A default c_int restype would truncate a 64-bit pointer.
+ assert table["GetApplicationEventTarget"][0] is ctypes.c_void_p
+ assert table["GetEventDispatcherTarget"][0] is ctypes.c_void_p
+ # EventHotKeyID is passed BY VALUE (argument 3), never as a pointer.
+ assert table["RegisterEventHotKey"][1][2] is spike.EventHotKeyID
+ assert len(table["RegisterEventHotKey"][1]) == 6
+ assert table["InstallEventHandler"][1][1] is spike.HANDLER_PROTO
+ assert len(table["InstallEventHandler"][1]) == 6
+ for restype, argtypes in table.values():
+ assert restype is not None and isinstance(argtypes, tuple)
+
+
+class _FakeFunction:
+ def __init__(self, implementation: Any) -> None:
+ self.implementation = implementation
+ self.restype: Any = None
+ self.argtypes: Any = None
+ self.calls: list[tuple[Any, ...]] = []
+
+ def __call__(self, *args: Any) -> Any:
+ self.calls.append(args)
+ return self.implementation(*args)
+
+
+class FakeCarbon:
+ """An in-memory Carbon. It models only what the spike reads back; nothing more."""
+
+ #: Needs more than 32 bits: a c_int restype or argument would truncate it.
+ APP_TARGET = 0x1000_0000_0000_1234
+
+ def __init__(
+ self,
+ *,
+ missing: tuple[str, ...] = (),
+ leak_off_main: bool = False,
+ alias_install: bool = False,
+ leak_always: bool = False,
+ ) -> None:
+ self.missing = set(missing)
+ self.leak_off_main = leak_off_main
+ #: Unregister claims success on EVERY thread but keeps the registration.
+ self.leak_always = leak_always
+ #: Export InstallEventHandler only as ``_InstallEventHandler`` (the doubt in the SDK).
+ self.alias_install = alias_install
+ self.chords: dict[int, tuple[int, int, int]] = {}
+ self.handlers: dict[int, Any] = {}
+ self.secure = 0
+ self.fail_install = False
+ self.events: dict[int, tuple[int, int]] = {}
+ self._next = 0xA000
+ self._functions: dict[str, _FakeFunction] = {}
+
+ def _ref(self) -> int:
+ self._next += 1
+ return self._next
+
+ def _function(self, name: str) -> _FakeFunction:
+ if name not in self._functions:
+ self._functions[name] = _FakeFunction(getattr(self, f"_impl_{name}"))
+ return self._functions[name]
+
+ def __getattr__(self, name: str) -> _FakeFunction:
+ if name == "_InstallEventHandler" and self.alias_install:
+ return self._function("InstallEventHandler")
+ if name.startswith("_") or name in self.missing or name not in spike.CARBON_SIGNATURES:
+ raise AttributeError(name)
+ return self._function(name)
+
+ def _impl_GetApplicationEventTarget(self) -> int:
+ return self.APP_TARGET
+
+ def _impl_GetEventDispatcherTarget(self) -> int:
+ return 0x2000
+
+ def _impl_InstallEventHandler(self, target, handler, count, specs, user_data, out_ref) -> int:
+ if self.fail_install:
+ raise RuntimeError("install exploded")
+ assert target == self.APP_TARGET and count == 2 and user_data is None
+ assert [(s.eventClass, s.eventKind) for s in specs] == [
+ (spike.K_EVENT_CLASS_KEYBOARD, 5),
+ (spike.K_EVENT_CLASS_KEYBOARD, 6),
+ ]
+ ref = self._ref()
+ self.handlers[ref] = handler
+ out_ref._obj.value = ref
+ return 0
+
+ def _impl_RemoveEventHandler(self, ref) -> int:
+ return 0 if self.handlers.pop(getattr(ref, "value", ref), None) else -50
+
+ def _impl_RegisterEventHotKey(self, key, modifiers, identity, target, options, out_ref) -> int:
+ assert isinstance(identity, spike.EventHotKeyID)
+ assert target == self.APP_TARGET and options == 0
+ if any((k, m) == (key, modifiers) for k, m, _ in self.chords.values()):
+ return spike.EVENT_HOT_KEY_EXISTS_ERR
+ ref = self._ref()
+ self.chords[ref] = (key, modifiers, identity.id)
+ out_ref._obj.value = ref
+ return 0
+
+ def _impl_UnregisterEventHotKey(self, ref) -> int:
+ value = getattr(ref, "value", ref)
+ assert value is not None, "a NULL reference must never reach Carbon"
+ off_main = threading.current_thread() is not threading.main_thread()
+ if self.leak_always or (self.leak_off_main and off_main):
+ return 0 # reports success but keeps the registration (a silent leak)
+ return 0 if self.chords.pop(value, None) else -9879
+
+ def _impl_GetEventClass(self, event) -> int:
+ return spike.K_EVENT_CLASS_KEYBOARD
+
+ def _impl_GetEventKind(self, event) -> int:
+ return self.events[event][0]
+
+ def _impl_GetEventParameter(self, event, name, desired, actual_type, size, actual, data) -> int:
+ assert name == spike.K_EVENT_PARAM_DIRECT_OBJECT and desired == spike.TYPE_EVENT_HOT_KEY_ID
+ assert size == 8
+ data._obj.signature = spike.HOT_KEY_SIGNATURE
+ data._obj.id = self.events[event][1]
+ return 0
+
+ def _impl_IsSecureEventInputEnabled(self) -> int:
+ return self.secure
+
+ def _impl_EnableSecureEventInput(self) -> int:
+ self.secure = 1
+ return 0
+
+ def _impl_DisableSecureEventInput(self) -> int:
+ self.secure = 0
+ return 0
+
+ def press(self, key: int = spike.TEST_KEY_CODE, modifiers: int = spike.TEST_MODIFIERS) -> None:
+ """Deliver Pressed then Released through the REAL ctypes callback."""
+ for _ref, (k, m, ident) in list(self.chords.items()):
+ if (k, m) != (key, modifiers):
+ continue
+ for handler in list(self.handlers.values()):
+ for kind in (spike.K_EVENT_HOT_KEY_PRESSED, spike.K_EVENT_HOT_KEY_RELEASED):
+ event = self._ref()
+ self.events[event] = (kind, ident)
+ assert handler(0, event, 0) == spike.NO_ERR
+
+
+def test_bind_carbon_sets_restype_and_argtypes_on_every_function() -> None:
+ fake = FakeCarbon()
+ bound, missing, aliases = spike.bind_carbon(fake)
+ assert missing == [] and bound == list(spike.CARBON_SIGNATURES) and aliases == {}
+ for name, (restype, argtypes) in spike.CARBON_SIGNATURES.items():
+ function = getattr(fake, name)
+ assert function.restype is restype and function.argtypes == list(argtypes)
+
+
+def test_bind_carbon_reports_a_missing_symbol_instead_of_raising() -> None:
+ bound, missing, aliases = spike.bind_carbon(FakeCarbon(missing=("EnableSecureEventInput",)))
+ assert missing == ["EnableSecureEventInput"] and aliases == {}
+ assert "EnableSecureEventInput" not in bound and "RegisterEventHotKey" in bound
+
+
+def test_bind_carbon_falls_back_to_the_underscore_install_symbol_and_records_it() -> None:
+ # The doubt: the SDK might export InstallEventHandler only as _InstallEventHandler. One
+ # missing symbol must not turn every Carbon scenario into a harness error.
+ fake = FakeCarbon(missing=("InstallEventHandler",), alias_install=True)
+ bound, missing, aliases = spike.bind_carbon(fake)
+ assert missing == [] and "InstallEventHandler" in bound
+ assert aliases == {"InstallEventHandler": "_InstallEventHandler"}
+ shim = spike.CarbonShim(lib=FakeCarbon(missing=("InstallEventHandler",), alias_install=True))
+ assert shim.aliases == {"InstallEventHandler": "_InstallEventHandler"}
+ status, handler = shim.install_handler() # callers keep the one canonical spelling
+ assert status == 0 and handler is not None
+ # The plain name wins when both exist, and no alias is recorded.
+ assert spike.CarbonShim(lib=FakeCarbon(alias_install=True)).aliases == {}
+ # Neither spelling: reported as missing, never raised.
+ _bound, gone, none = spike.bind_carbon(FakeCarbon(missing=("InstallEventHandler",)))
+ assert gone == ["InstallEventHandler"] and none == {}
+
+
+def test_shim_passes_arguments_in_the_order_carbon_expects() -> None:
+ fake = FakeCarbon()
+ shim = spike.CarbonShim(lib=fake)
+ status, handler = shim.install_handler()
+ assert status == 0 and handler is not None
+ status, ref = shim.register(spike.TEST_KEY_CODE, spike.TEST_MODIFIERS, 7)
+ assert status == 0 and fake.chords[ref] == (0x26, 0x1800, 7)
+ call = fake.RegisterEventHotKey.calls[0]
+ assert call[:2] == (0x26, 0x1800) and call[2].signature == spike.HOT_KEY_SIGNATURE
+ assert call[3] == FakeCarbon.APP_TARGET # the full 64-bit target, not truncated
+ assert shim.unregister(ref) == 0 and fake.chords == {}
+ assert shim.remove_handler(handler) == 0
+
+
+def test_a_duplicate_registration_returns_the_status_and_a_null_reference() -> None:
+ shim = spike.CarbonShim(lib=FakeCarbon())
+ shim.install_handler()
+ assert shim.register(0x26, 0x1800, 1)[0] == 0
+ status, ref = shim.register(0x26, 0x1800, 2)
+ assert status == spike.EVENT_HOT_KEY_EXISTS_ERR and ref is None
+
+
+def test_the_ctypes_callback_records_events_and_never_raises_into_carbon() -> None:
+ fake = FakeCarbon()
+ shim = spike.CarbonShim(lib=fake)
+ shim.install_handler()
+ shim.register(0x26, 0x1800, 5)
+ fake.press()
+ assert [e["kind"] for e in spike._STATE.events] == ["pressed", "released"]
+ assert {e["hot_key_id"] for e in spike._STATE.events} == {5}
+ assert all(e["on_main_thread"] for e in spike._STATE.events)
+ # The same module-level singleton is handed to every install.
+ assert spike.callback_singleton() is spike.callback_singleton()
+ assert spike.spec_array_singleton() is spike.spec_array_singleton()
+ # An internal error returns eventNotHandledErr and is recorded, not swallowed.
+ handler = spike.callback_singleton()
+ assert handler(0, 987654, 0) == spike.EVENT_NOT_HANDLED_ERR
+ assert spike._STATE.errors and "carbon handler" in spike._STATE.errors[0]
+
+
+def test_the_callback_notices_an_off_main_thread_delivery() -> None:
+ fake = FakeCarbon()
+ shim = spike.CarbonShim(lib=fake)
+ shim.install_handler()
+ shim.register(0x26, 0x1800, 5)
+ worker = threading.Thread(target=fake.press)
+ worker.start()
+ worker.join()
+ assert spike.count_events(spike._STATE.events)["off_main_thread"] == 2
+
+
+# --- scenarios against the fake (sequencing only) ----------------------------------
+
+
+def _drive(scenario: Any, *, settle: bool = True) -> dict[str, Any] | None:
+ """Run a scenario coroutine to its end, waiting for each ``Wait`` like the loop does."""
+ try:
+ while True:
+ wait = next(scenario)
+ assert isinstance(wait, spike.Wait) and wait.timeout_s > 0
+ deadline = threading.Event()
+ for _ in range(400):
+ if wait.predicate():
+ break
+ deadline.wait(0.01)
+ assert wait.predicate(), "the injector never finished"
+ except StopIteration as stop:
+ return stop.value
+
+
+def _steps() -> dict[str, Any]:
+ return {row["step"]: row["value"] for row in spike._STATE.steps}
+
+
+class _PressingInjector(spike.Injector):
+ """Stands in for osascript: presses the fake chord from the injector thread."""
+
+ lib: FakeCarbon
+
+ def __init__(self, repeat: int = 1) -> None:
+ super().__init__(delay_s=0.0, repeat=repeat, run=lambda *a, **k: None)
+
+ def _work(self) -> None:
+ try:
+ for _ in range(self.repeat):
+ type(self).lib.press()
+ self.result = {"returncode": 0}
+ finally:
+ self.done.set()
+
+
+def test_scenario_register_unregister_without_a_synthetic_key() -> None:
+ fake = FakeCarbon()
+ shim = spike.CarbonShim(lib=fake)
+ result = _drive(spike._co_nsapp_register_unregister(shim))
+ steps = _steps()
+ assert steps["install_handler"] == 0 and steps["register"] == 0 and steps["unregister"] == 0
+ assert steps["inject_while_registered"] == "not_requested"
+ assert steps["reregister_after_unregister"] == 0 and steps["unregister_second"] == 0
+ assert fake.chords == {} and result == {"carbon_route": "injected"}
+ assert spike.child_ok(spike._STATE.steps, spike._STATE.errors)
+
+
+def test_scenario_register_unregister_with_a_delivered_synthetic_key(monkeypatch) -> None:
+ fake = FakeCarbon()
+ shim = spike.CarbonShim(lib=fake)
+ _PressingInjector.lib = fake
+ monkeypatch.setattr(spike, "Injector", _PressingInjector)
+ spike._STATE.inject = True
+ _drive(spike._co_nsapp_register_unregister(shim))
+ steps = _steps()
+ # Delivered while registered; after the unregister the second press goes nowhere. Each
+ # count is a WINDOW (events since the previous count), so 'after' is 0, not a running total.
+ assert steps["pressed_while_registered"] == 1 and steps["released_while_registered"] == 1
+ assert steps["pressed_after_unregister"] == 0 and steps["released_after_unregister"] == 0
+ assert steps["inject_while_registered_osascript_exit"] == 0
+ assert spike.count_events(spike._STATE.events)["pressed"] == 1 # the total is still 1
+
+
+def _counters(monkeypatch, before: Any, after: Any) -> None:
+ """Make the key-down control read ``before`` then ``after`` (None = unreadable)."""
+ values = iter([before, after] * 4)
+ monkeypatch.setattr(spike, "read_keydown_counters", lambda *a, **k: next(values))
+
+
+def test_scenario_records_whether_the_injection_was_seen_independently_of_carbon(
+ monkeypatch,
+) -> None:
+ fake = FakeCarbon()
+ _PressingInjector.lib = fake
+ monkeypatch.setattr(spike, "Injector", _PressingInjector)
+ spike._STATE.inject = True
+ _counters(
+ monkeypatch,
+ {"combined_session": 5, "hid_system": 5},
+ {"combined_session": 6, "hid_system": 5},
+ )
+ _drive(spike._co_nsapp_register_unregister(spike.CarbonShim(lib=fake)))
+ step = next(r for r in spike._STATE.steps if r["step"] == "injection_seen_while_registered")
+ assert step["value"] is True
+ assert (
+ step["counters_before"]["combined_session"] == 5
+ and step["counters_after"]["combined_session"] == 6
+ )
+
+ spike.reset_child_state()
+ spike._STATE.inject = True
+ fake = FakeCarbon()
+ _PressingInjector.lib = fake
+ _counters(monkeypatch, {"combined_session": 5}, None) # the counter became unreadable
+ _drive(spike._co_nsapp_register_unregister(spike.CarbonShim(lib=fake)))
+ assert _steps()["injection_seen_while_registered"] is None
+
+
+def test_read_keydown_counters_reads_both_source_states_or_reports_unreadable() -> None:
+ seen: list[tuple[int, int]] = []
+
+ def bind(_frameworks: Any, symbol: str, _restype: Any, _argtypes: Any) -> Any:
+ assert symbol == "CGEventSourceCounterForEventType"
+
+ def counter(state: int, event_type: int) -> int:
+ seen.append((state, event_type))
+ return 7 + state
+
+ return counter
+
+ assert spike.read_keydown_counters(bind) == {"combined_session": 7, "hid_system": 8}
+ assert seen == [(0, spike.K_CG_EVENT_KEY_DOWN), (1, spike.K_CG_EVENT_KEY_DOWN)]
+ assert spike.K_CG_EVENT_KEY_DOWN == 10
+
+ def missing(*_args: Any) -> Any:
+ raise OSError("CGEventSourceCounterForEventType not found")
+
+ assert spike.read_keydown_counters(missing) is None
+ assert "keydown_counter_unreadable" in _steps()
+
+
+def test_a_leaking_unregister_is_not_clean_evidence_even_though_a_press_arrived(
+ monkeypatch,
+) -> None:
+ # The whole chain of the finding: a Pressed arrived while registered, but the unregister did
+ # not take effect (the second press still arrives, the re-register fails with -9878).
+ fake = FakeCarbon(leak_always=True)
+ _PressingInjector.lib = fake
+ monkeypatch.setattr(spike, "Injector", _PressingInjector)
+ spike._STATE.inject = True
+ _counters(monkeypatch, {"a": 1}, {"a": 2})
+ _drive(spike._co_nsapp_register_unregister(spike.CarbonShim(lib=fake)))
+ steps = _steps()
+ assert steps["pressed_while_registered"] == 1 and steps["pressed_after_unregister"] == 1
+ assert steps["reregister_after_unregister"] == spike.EVENT_HOT_KEY_EXISTS_ERR
+ result = spike.assemble_child_result(
+ "nsapp_register_unregister",
+ {},
+ steps=spike._STATE.steps,
+ events=spike._STATE.events,
+ errors=spike._STATE.errors,
+ tcc=_tcc(),
+ inject=True,
+ )
+ assert result["ok"] is False
+ row = {
+ "name": "nsapp_register_unregister",
+ "outcome": spike.classify_outcome(returncode=0, timed_out=False, child_ok=result["ok"]),
+ "observations": result,
+ }
+ verdict = spike.evaluate_evidence(_tcc(), [row])
+ assert verdict["carbon_event_delivered"] is True and verdict["variant_ok"] is False
+ assert verdict["usable_as_evidence"] is False
+
+
+def test_scenario_cycles_register_and_unregister_without_a_synthetic_key() -> None:
+ fake = FakeCarbon()
+ result = _drive(spike._co_register_unregister_cycles(spike.CarbonShim(lib=fake)))
+ steps = _steps()
+ assert steps["register_unregister_cycles"] == spike.REGISTER_CYCLES == 200
+ assert steps["cycle_failures"] == 0 and steps["reregister_after_cycles"] == 0
+ assert steps["press_cycles_requested"] == 0 and steps["every_press_arrived"] is None
+ assert fake.chords == {} and result == {"carbon_route": "injected"}
+ assert len(fake.RegisterEventHotKey.calls) == 200 + 2
+ assert spike.child_ok(spike._STATE.steps, spike._STATE.errors)
+
+
+def test_scenario_cycles_count_every_press_of_one_repeated_injection(monkeypatch) -> None:
+ fake = FakeCarbon()
+ _PressingInjector.lib = fake
+ monkeypatch.setattr(spike, "Injector", _PressingInjector)
+ spike._STATE.inject = True
+ _drive(spike._co_register_unregister_cycles(spike.CarbonShim(lib=fake)))
+ steps = _steps()
+ assert spike.PRESS_CYCLES == 50 and steps["press_cycles_requested"] == 50
+ assert steps["pressed_press_cycles"] == 50 and steps["released_press_cycles"] == 50
+ assert steps["every_press_arrived"] is True
+ assert steps["inject_press_cycles_osascript_exit"] == 0
+ assert spike.child_ok(spike._STATE.steps, spike._STATE.errors)
+
+
+def test_scenario_cycles_detect_a_leaked_slot_and_cap_the_failure_details() -> None:
+ fake = FakeCarbon(leak_always=True) # the unregister never frees the slot
+ _drive(spike._co_register_unregister_cycles(spike.CarbonShim(lib=fake)))
+ steps = _steps()
+ assert steps["cycle_failures"] == 199 # cycle 0 registers; every later one hits -9878
+ details = next(r for r in spike._STATE.steps if r["step"] == "cycle_failures")["details"]
+ assert len(details) == spike.CYCLE_FAILURE_DETAILS == 5
+ assert details[0] == {"cycle": 1, "step": "register", "status": spike.EVENT_HOT_KEY_EXISTS_ERR}
+ assert spike.child_ok(spike._STATE.steps, spike._STATE.errors) is False
+
+
+def test_scenario_duplicate_register_records_the_status_and_skips_the_null_ref() -> None:
+ fake = FakeCarbon()
+ _drive(spike._co_duplicate_register(spike.CarbonShim(lib=fake)))
+ steps = _steps()
+ assert steps["register_first"] == 0
+ assert steps["register_second"] == spike.EVENT_HOT_KEY_EXISTS_ERR
+ assert steps["second_returned_hotkey_exists_err"] is True
+ assert steps["unregister_first"] == 0 and steps["unregister_second_skipped_null_ref"] is True
+ assert spike.child_ok(spike._STATE.steps, spike._STATE.errors)
+ assert fake.chords == {}
+
+
+def test_scenario_off_main_unregister_detects_a_silent_leak() -> None:
+ clean = FakeCarbon()
+ _drive(spike._co_unregister_off_main(spike.CarbonShim(lib=clean)))
+ steps = _steps()
+ assert steps["unregister_off_main"] == 0 and steps["reregister_after_off_main_unregister"] == 0
+
+ spike.reset_child_state()
+ leaky = FakeCarbon(leak_off_main=True)
+ _drive(spike._co_unregister_off_main(spike.CarbonShim(lib=leaky)))
+ steps = _steps()
+ # The off-main call claims success, yet the slot is still taken.
+ assert steps["unregister_off_main"] == 0
+ assert steps["reregister_after_off_main_unregister"] == spike.EVENT_HOT_KEY_EXISTS_ERR
+ returned = next(r for r in spike._STATE.steps if r["step"] == "unregister_off_main")
+ assert returned["returned"] is True and returned["error"] is None
+
+
+def test_scenario_secure_input_is_always_disabled_again() -> None:
+ fake = FakeCarbon()
+ _drive(spike._co_secure_input(spike.CarbonShim(lib=fake)))
+ steps = _steps()
+ assert steps["secure_input_before"] == 0 and steps["secure_input_after_enable"] == 1
+ assert steps["register_under_secure_input"] == 0 and steps["secure_input_after_disable"] == 0
+ assert fake.secure == 0
+
+ spike.reset_child_state()
+ broken = FakeCarbon()
+ broken.fail_install = True
+ with pytest.raises(RuntimeError, match="install exploded"):
+ _drive(spike._co_secure_input(spike.CarbonShim(lib=broken)))
+ assert broken.secure == 0 # the finally block ran
+
+
+def test_scenario_install_handler_twice_counts_both_deliveries(monkeypatch) -> None:
+ fake = FakeCarbon()
+ _PressingInjector.lib = fake
+ monkeypatch.setattr(spike, "Injector", _PressingInjector)
+ spike._STATE.inject = True
+ _drive(spike._co_install_handler_twice(spike.CarbonShim(lib=fake)))
+ steps = _steps()
+ assert steps["install_handler_first"] == 0 and steps["install_handler_second"] == 0
+ assert steps["handler_refs_distinct"] is True
+ # Two handlers on one target: every press arrives twice.
+ assert steps["pressed_two_handlers"] == 2 and steps["released_two_handlers"] == 2
+ assert steps["remove_handler_first"] == 0 and steps["remove_handler_second"] == 0
+ assert fake.handlers == {} and fake.chords == {}
+
+
+def test_a_repeated_injection_is_one_osascript_run_with_a_longer_timeout() -> None:
+ many = spike.Injector(delay_s=0.0, repeat=50, run=lambda *a, **k: None)
+ script = many.script()
+ assert script.startswith('tell application "System Events"\n')
+ assert "repeat 50 times" in script and "key code 38 using {control down, option down}" in script
+ assert f"delay {spike.Injector.REPEAT_GAP_S}" in script and script.endswith("end tell")
+ assert many.timeout_s > spike.Injector(run=lambda *a, **k: None).timeout_s
+ assert spike.Injector(repeat=0, run=lambda *a, **k: None).repeat == 1
+
+
+def test_injector_records_an_osascript_failure_and_always_finishes() -> None:
+ def failing(*_a: Any, **_k: Any) -> Any:
+ raise FileNotFoundError("osascript")
+
+ injector = spike.Injector(delay_s=0.0, run=failing)
+ injector.start()
+ assert injector.done.wait(5)
+ assert injector.result["returncode"] is None and "FileNotFoundError" in injector.result["error"]
+ assert "key code 38" in injector.script() and "control down, option down" in injector.script()
+ assert "repeat" not in injector.script() # one press stays a one-liner
+ assert injector.argv() == ["osascript", "-e", injector.script()]
+
+ done = spike.Injector(delay_s=0.0, run=lambda *a, **k: _Done(0, b"out", b"err"))
+ done.start()
+ assert done.done.wait(5) and done.result["returncode"] == 0
+ assert done.result["stderr"] == "err"
+
+
+# --- the REAL ctypes marshalling, against a C library with the Carbon prototypes ---------
+#
+# FakeCarbon above is a Python object: it accepts any argument, so it can never notice a wrong
+# ``argtypes`` or ``restype``. This library is compiled C with the real prototypes, so it only
+# answers noErr when the arguments really arrive as Carbon would see them: the event target is a
+# full 64-bit pointer (a default ``c_int`` restype truncates it) and ``EventHotKeyID`` arrives
+# BY VALUE (an instance passed by pointer makes the signature field garbage).
+
+_C_CARBON = r"""
+#include <stdint.h>
+#include <string.h>
+
+typedef int32_t OSStatus;
+typedef struct { uint32_t signature; uint32_t id; } EventHotKeyID;
+typedef struct { uint32_t eventClass; uint32_t eventKind; } EventTypeSpec;
+typedef OSStatus (*Handler)(void *call_ref, void *event, void *user_data);
+
+#define APP_TARGET ((void *)0x1000000000001234ULL)
+#define DISPATCHER_TARGET ((void *)0x2000ULL)
+#define HANDLER_REF ((void *)0x7000000000000001ULL)
+#define KEY_REF_BASE 0x7000000000000100ULL
+
+static Handler g_handler;
+static void *g_handler_user;
+static int g_handler_installed;
+static struct { int used; uint32_t key; uint32_t mods; EventHotKeyID id; } g_keys[16];
+static struct { uint32_t kind; EventHotKeyID id; } g_events[256];
+static int g_event_count;
+static unsigned char g_secure;
+
+void *GetApplicationEventTarget(void) { return APP_TARGET; }
+void *GetEventDispatcherTarget(void) { return DISPATCHER_TARGET; }
+
+OSStatus InstallEventHandler(void *target, Handler handler, uint32_t count,
+ const EventTypeSpec *specs, void *user_data, void **out_ref) {
+ if (target != APP_TARGET) return -50; /* paramErr: a truncated pointer lands here */
+ if (count != 2 || specs == 0 || out_ref == 0) return -50;
+ if (specs[0].eventClass != 0x6B657962u || specs[0].eventKind != 5u) return -50;
+ if (specs[1].eventClass != 0x6B657962u || specs[1].eventKind != 6u) return -50;
+ g_handler = handler; g_handler_user = user_data; g_handler_installed = 1;
+ *out_ref = HANDLER_REF;
+ return 0;
+}
+
+OSStatus RemoveEventHandler(void *ref) {
+ if (ref != HANDLER_REF || !g_handler_installed) return -50;
+ g_handler_installed = 0;
+ return 0;
+}
+
+OSStatus RegisterEventHotKey(uint32_t key, uint32_t mods, EventHotKeyID id, void *target,
+ uint32_t options, void **out_ref) {
+ int i;
+ if (target != APP_TARGET || options != 0 || out_ref == 0) return -50;
+ if (id.signature != 0x4A525653u) return -50; /* 'JRVS': the struct arrived BY VALUE */
+ for (i = 0; i < 16; i++)
+ if (g_keys[i].used && g_keys[i].key == key && g_keys[i].mods == mods) return -9878;
+ for (i = 0; i < 16; i++) {
+ if (g_keys[i].used) continue;
+ g_keys[i].used = 1; g_keys[i].key = key; g_keys[i].mods = mods; g_keys[i].id = id;
+ *out_ref = (void *)(KEY_REF_BASE + (uint64_t)i);
+ return 0;
+ }
+ return -50;
+}
+
+OSStatus UnregisterEventHotKey(void *ref) {
+ uint64_t index = (uint64_t)ref - KEY_REF_BASE;
+ if ((uint64_t)ref < KEY_REF_BASE || index >= 16 || !g_keys[index].used) return -9879;
+ g_keys[index].used = 0;
+ return 0;
+}
+
+uint32_t GetEventClass(void *event) { (void)event; return 0x6B657962u; }
+
+uint32_t GetEventKind(void *event) {
+ uint64_t index = (uint64_t)event - 1;
+ return index < 256 ? g_events[index].kind : 0;
+}
+
+OSStatus GetEventParameter(void *event, uint32_t name, uint32_t type, uint32_t *actual_type,
+ uint32_t size, uint32_t *actual_size, void *data) {
+ uint64_t index = (uint64_t)event - 1;
+ (void)actual_type; (void)actual_size;
+ if (name != 0x2D2D2D2Du || type != 0x686B6964u || size != 8u || data == 0 || index >= 256)
+ return -9870;
+ memcpy(data, &g_events[index].id, 8);
+ return 0;
+}
+
+unsigned char IsSecureEventInputEnabled(void) { return g_secure; }
+OSStatus EnableSecureEventInput(void) { g_secure = 1; return 0; }
+OSStatus DisableSecureEventInput(void) { g_secure = 0; return 0; }
+
+/* Test helper, NOT a Carbon symbol: deliver Pressed then Released for a registered chord. */
+int fake_press(uint32_t key, uint32_t mods) {
+ int i, k, delivered = 0;
+ uint32_t kinds[2] = {5u, 6u};
+ if (!g_handler_installed) return -1;
+ for (i = 0; i < 16; i++) {
+ if (!g_keys[i].used || g_keys[i].key != key || g_keys[i].mods != mods) continue;
+ for (k = 0; k < 2; k++) {
+ if (g_event_count >= 256) return -2;
+ g_events[g_event_count].kind = kinds[k];
+ g_events[g_event_count].id = g_keys[i].id;
+ g_event_count++;
+ if (g_handler((void *)0, (void *)(uintptr_t)g_event_count, g_handler_user) != 0)
+ return -3;
+ delivered++;
+ }
+ }
+ return delivered;
+}
+"""
+
+C_APP_TARGET = 0x1000_0000_0000_1234
+C_HANDLER_REF = 0x7000_0000_0000_0001
+C_KEY_REF_BASE = 0x7000_0000_0000_0100
+C_PARAM_ERR = -50
+
+
[email protected](scope="module")
+def c_carbon_path(tmp_path_factory: pytest.TempPathFactory) -> Path:
+ compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
+ if compiler is None or os.name == "nt":
+ pytest.skip("no C compiler: the real-marshalling tests need one")
+ directory = tmp_path_factory.mktemp("fake_carbon")
+ source = directory / "fake_carbon.c"
+ source.write_text(_C_CARBON, encoding="utf-8")
+ library = directory / (
+ "libfake_carbon.dylib" if sys.platform == "darwin" else "libfake_carbon.so"
+ )
+ flags = ["-dynamiclib"] if sys.platform == "darwin" else ["-shared", "-fPIC"]
+ done = subprocess.run(
+ [compiler, *flags, "-o", str(library), str(source)],
+ capture_output=True,
+ text=True,
+ timeout=120,
+ check=False,
+ )
+ # A compile error is a bug in THIS test source, so it fails instead of skipping.
+ assert done.returncode == 0, done.stderr
+ return library
+
+
+def c_carbon(c_carbon_path: Path, tmp_path: Path) -> Any:
+ """A FRESH instance of the library per test (a copy at a new path has its own statics)."""
+ private = tmp_path / c_carbon_path.name
+ shutil.copy(c_carbon_path, private)
+ lib = ctypes.CDLL(str(private))
+ lib.fake_press.restype = ctypes.c_int
+ lib.fake_press.argtypes = [ctypes.c_uint32, ctypes.c_uint32]
+ return lib
+
+
+def test_real_ctypes_calls_marshal_pointers_and_the_by_value_struct_correctly(c_carbon) -> None:
+ shim = spike.CarbonShim(lib=c_carbon, route="c-library")
+ assert shim.bound == list(spike.CARBON_SIGNATURES) and shim.missing == [] and shim.aliases == {}
+ assert shim.target() == C_APP_TARGET # all 64 bits: the c_void_p restype works
+ status, handler = shim.install_handler()
+ assert status == 0 and handler == C_HANDLER_REF
+ status, ref = shim.register(spike.TEST_KEY_CODE, spike.TEST_MODIFIERS, 7)
+ assert status == 0 and ref == C_KEY_REF_BASE # EventHotKeyID arrived by value (signature ok)
+ duplicate_status, duplicate = shim.register(spike.TEST_KEY_CODE, spike.TEST_MODIFIERS, 8)
+ assert duplicate_status == spike.EVENT_HOT_KEY_EXISTS_ERR and duplicate is None
+
+ # The callback is invoked FROM C through the module-level ctypes trampoline and reads the id
+ # back through GetEventParameter's by-reference out parameter.
+ assert c_carbon.fake_press(spike.TEST_KEY_CODE, spike.TEST_MODIFIERS) == 2
+ events = spike._STATE.events
+ assert [event["kind"] for event in events] == ["pressed", "released"]
+ assert {event["hot_key_id"] for event in events} == {7}
+ assert {event["parameter_status"] for event in events} == {0}
+ assert all(event["on_main_thread"] for event in events) and spike._STATE.errors == []
+
+ assert shim.unregister(ref) == 0
+ assert c_carbon.fake_press(spike.TEST_KEY_CODE, spike.TEST_MODIFIERS) == 0 # slot is free
+ assert shim.remove_handler(handler) == 0
+ assert shim.remove_handler(handler) == C_PARAM_ERR # the C side really tracks the handler
+
+
+def test_real_ctypes_secure_input_functions_round_trip(c_carbon) -> None:
+ shim = spike.CarbonShim(lib=c_carbon)
+ assert shim.lib.IsSecureEventInputEnabled() == 0
+ assert shim.lib.EnableSecureEventInput() == 0 and shim.lib.IsSecureEventInputEnabled() == 1
+ assert shim.lib.DisableSecureEventInput() == 0 and shim.lib.IsSecureEventInputEnabled() == 0
+
+
+def test_the_c_library_catches_a_truncated_event_target(c_carbon, monkeypatch) -> None:
+ # The classic crash: no restype on a pointer getter, so ctypes reads a 32-bit int.
+ table = dict(spike.CARBON_SIGNATURES)
+ table["GetApplicationEventTarget"] = (ctypes.c_int, ())
+ monkeypatch.setattr(spike, "CARBON_SIGNATURES", table)
+ shim = spike.CarbonShim(lib=c_carbon)
+ assert shim.target() != C_APP_TARGET
+ status, handler = shim.install_handler()
+ assert status == C_PARAM_ERR and handler is None
+
+
+def test_the_c_library_catches_a_hot_key_id_passed_by_pointer(c_carbon, monkeypatch) -> None:
+ table = dict(spike.CARBON_SIGNATURES)
+ restype, argtypes = table["RegisterEventHotKey"]
+ by_pointer = (*argtypes[:2], ctypes.POINTER(spike.EventHotKeyID), *argtypes[3:])
+ table["RegisterEventHotKey"] = (restype, by_pointer)
+ monkeypatch.setattr(spike, "CARBON_SIGNATURES", table)
+ shim = spike.CarbonShim(lib=c_carbon)
+ assert shim.install_handler()[0] == 0
+ status, ref = shim.register(spike.TEST_KEY_CODE, spike.TEST_MODIFIERS, 1)
+ assert status == C_PARAM_ERR and ref is None
+
+
+class _CPressingInjector(spike.Injector):
+ """osascript stand-in that delivers through the compiled library, ``repeat`` times."""
+
+ lib: Any
+
+ def __init__(self, repeat: int = 1) -> None:
+ super().__init__(delay_s=0.0, repeat=repeat, run=lambda *a, **k: None)
+
+ def _work(self) -> None:
+ try:
+ for _ in range(self.repeat):
+ type(self).lib.fake_press(spike.TEST_KEY_CODE, spike.TEST_MODIFIERS)
+ self.result = {"returncode": 0}
+ finally:
+ self.done.set()
+
+
+def test_the_scenarios_run_through_real_ctypes_against_the_c_library(c_carbon, monkeypatch) -> None:
+ _CPressingInjector.lib = c_carbon
+ monkeypatch.setattr(spike, "Injector", _CPressingInjector)
+ monkeypatch.setattr(spike, "read_keydown_counters", lambda *a, **k: None)
+ spike._STATE.inject = True
+ shim = spike.CarbonShim(lib=c_carbon)
+ _drive(spike._co_nsapp_register_unregister(shim))
+ steps = _steps()
+ assert steps["register"] == 0 and steps["pressed_while_registered"] == 1
+ assert steps["pressed_after_unregister"] == 0 and steps["reregister_after_unregister"] == 0
+ assert spike.child_ok(spike._STATE.steps, spike._STATE.errors)
+
+ spike.reset_child_state()
+ spike._STATE.inject = True
+ _drive(spike._co_register_unregister_cycles(spike.CarbonShim(lib=c_carbon)))
+ steps = _steps()
+ assert steps["cycle_failures"] == 0 and steps["pressed_press_cycles"] == spike.PRESS_CYCLES
+ assert steps["every_press_arrived"] is True and spike._STATE.errors == []
+
+
+def test_the_scenario_reports_a_leak_through_real_ctypes_as_a_duplicate_registration(
+ c_carbon,
+) -> None:
+ shim = spike.CarbonShim(lib=c_carbon)
+ _drive(spike._co_duplicate_register(shim))
+ steps = _steps()
+ assert steps["register_first"] == 0 and steps["second_returned_hotkey_exists_err"] is True
+ assert steps["unregister_first"] == 0 and steps["unregister_second_skipped_null_ref"] is True
+
+
+# --- the version guard --------------------------------------------------------------
+
+
+def _module_source() -> str:
+ return Path(spike.__file__).read_text(encoding="utf-8")
+
+
+def test_the_version_guard_runs_before_the_first_3_11_only_import() -> None:
+ tree = ast.parse(_module_source())
+ guard_index = next(
+ index
+ for index, node in enumerate(tree.body)
+ if isinstance(node, ast.If) and "version_info" in ast.unparse(node.test)
+ )
+ utc_index = next(
+ index
+ for index, node in enumerate(tree.body)
+ if isinstance(node, ast.ImportFrom)
+ and node.module == "datetime"
+ and any(alias.name == "UTC" for alias in node.names)
+ )
+ assert guard_index < utc_index
+ # The guard can only run on an old interpreter if the file still PARSES there.
+ ast.parse(_module_source(), feature_version=(3, 9))
+
+
+def test_the_version_guard_exits_with_a_clear_message_on_an_old_python() -> None:
+ tree = ast.parse(_module_source())
+ guard = next(
+ node
+ for node in tree.body
+ if isinstance(node, ast.If) and "version_info" in ast.unparse(node.test)
+ )
+
+ class OldSys:
+ version_info = (3, 9, 18, "final", 0)
+ version = "3.9.18 (default, Aug 2024)"
+
+ @staticmethod
+ def exit(message: str) -> None:
+ raise SystemExit(message)
+
+ with pytest.raises(SystemExit) as raised:
+ exec(compile(ast.unparse(guard), "<guard>", "exec"), {"sys": OldSys}) # noqa: S102
+ message = str(raised.value)
+ assert "needs Python 3.11 or newer" in message and "3.9.18" in message
+
+ class NewSys(OldSys):
+ version_info = (3, 12, 1, "final", 0)
+
+ exec(compile(ast.unparse(guard), "<guard>", "exec"), {"sys": NewSys}) # noqa: S102 - no exit
+
+
[email protected](shutil.which("python3.10") is None, reason="no python3.10 on this host")
+def test_a_real_python_3_10_gets_the_message_not_an_import_error(tmp_path: Path) -> None:
+ done = subprocess.run(
+ [str(shutil.which("python3.10")), spike.__file__, "--out", str(tmp_path / "x.json")],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ check=False,
+ )
+ assert done.returncode != 0
+ assert "needs Python 3.11 or newer" in done.stderr and "ImportError" not in done.stderr
+ assert not (tmp_path / "x.json").exists()
+
+
+# --- the main-thread driver ---------------------------------------------------------
+
+
+class _Clock:
+ def __init__(self) -> None:
+ self.now = 0.0
+
+ def __call__(self) -> float:
+ return self.now
+
+
+def test_main_loop_drives_a_scenario_through_waits_without_blocking() -> None:
+ clock = _Clock()
+ finished: list[tuple[dict[str, Any], int]] = []
+ loop = spike.MainLoop(lambda extra, code: finished.append((extra, code)), clock)
+ flag = {"go": False}
+ order: list[str] = []
+
+ def scenario() -> Any:
+ order.append("start")
+ yield spike.Wait(lambda: flag["go"], timeout_s=5.0, settle_s=0.5)
+ order.append("resumed")
+ return {"done": True}
+
+ loop.drive(scenario())
+ loop.tick() # advance -> first yield
+ loop.tick() # poll: predicate false
+ assert order == ["start"] and finished == []
+ clock.now = 0.2
+ flag["go"] = True
+ loop.tick() # poll sees it, schedules the settle
+ loop.tick()
+ assert order == ["start"], "the settle delay has not passed"
+ clock.now = 0.8
+ loop.tick() # then -> advance (adds a job for the next tick)
+ loop.tick()
+ assert order == ["start", "resumed"] and finished == [({"done": True}, 0)]
+
+
+def test_main_loop_gives_up_waiting_at_the_deadline() -> None:
+ clock = _Clock()
+ finished: list[tuple[dict[str, Any], int]] = []
+ loop = spike.MainLoop(lambda extra, code: finished.append((extra, code)), clock)
+
+ def scenario() -> Any:
+ yield spike.Wait(lambda: False, timeout_s=2.0)
+ return {"waited": True}
+
+ loop.drive(scenario())
+ for _ in range(60):
+ loop.tick()
+ clock.now += 0.1
+ if finished:
+ break
+ assert finished == [({"waited": True}, 0)] and clock.now >= 2.0
+
+
+def test_main_loop_turns_a_scenario_exception_into_a_recorded_error_and_exit_1() -> None:
+ clock = _Clock()
+ finished: list[tuple[dict[str, Any], int]] = []
+ loop = spike.MainLoop(lambda extra, code: finished.append((extra, code)), clock)
+
+ def scenario() -> Any:
+ raise ValueError("harness bug")
+ yield # pragma: no cover - makes this a generator
+
+ loop.drive(scenario())
+ loop.tick()
+ assert finished == [({"ok": False}, 1)]
+ assert any("ValueError: harness bug" in error for error in spike._STATE.errors)
+
+
+# --- child entry point and the real harness on a non-macOS host --------------------
+
+
+def test_run_child_reports_an_unknown_experiment(capsys: pytest.CaptureFixture[str]) -> None:
+ assert spike.run_child("nope", inject=False) == 2
+ result = spike.parse_child_result(capsys.readouterr().out)
+ assert result is not None and result["ok"] is False and "unknown experiment" in result["error"]
+
+
[email protected](sys.platform == "darwin", reason="would load Carbon for real")
+def test_run_child_refuses_macos_experiments_elsewhere(capsys: pytest.CaptureFixture[str]) -> None:
+ assert spike.run_child("carbon_symbols", inject=True) == 1
+ result = spike.parse_child_result(capsys.readouterr().out)
+ assert result is not None and result["ok"] is False
+ assert "requires macOS" in result["error"] and result["synthetic_key_requested"] is True
+
+
[email protected](sys.platform == "darwin", reason="would probe the real frameworks")
+def test_tcc_context_is_unsupported_off_macos_and_never_raises() -> None:
+ tcc = spike.collect_tcc_context()
+ assert tcc["supported"] is False and tcc["probes"] == {} and "requires macOS" in tcc["reason"]
+ facts = spike.collect_runner_facts({"RUNNER_OS": "macOS", "AWS_SECRET_ACCESS_KEY": "x"})
+ assert facts["ci_env"] == {"RUNNER_OS": "macOS"} # an allowlist, nothing else
+ assert facts["platform"] == sys.platform and facts["python_version"]
+
+
[email protected](sys.platform in ("win32", "darwin"), reason="real POSIX child; no Carbon")
+def test_the_real_harness_end_to_end_records_a_real_crash_and_exits_zero(tmp_path: Path) -> None:
+ out = tmp_path / "nested" / "spike.json"
+ md = tmp_path / "summary.md"
+ done = subprocess.run(
+ [sys.executable, str(spike.__file__), "--out", str(out), "--summary-md", str(md)],
+ capture_output=True,
+ text=True,
+ timeout=120,
+ check=False,
+ )
+ assert done.returncode == 0, done.stderr
+ report = json.loads(out.read_text(encoding="utf-8"))
+ assert [e["name"] for e in report["experiments"]] == list(EXPECTED_NAMES)
+ control = report["experiments"][0]
+ assert control["outcome"] == "crash" and control["signal"] == "SIGABRT"
+ assert control["returncode"] == -int(signal.SIGABRT) and control["as_expected"] is True
+ assert control["last_step"] == "about_to_abort"
+ # The TCC context is collected by a CHILD (the parent loads no framework): on a non-macOS
+ # host that child runs, reports "unsupported" and ends ok; every Carbon experiment is skipped.
+ by_name = {e["name"]: e for e in report["experiments"]}
+ assert by_name["tcc_context"]["outcome"] == "ok" and by_name["tcc_context"]["returncode"] == 0
+ assert all(
+ e["outcome"] == "skipped"
+ for e in report["experiments"]
+ if e["name"] not in ("control_signal_capture", "tcc_context")
+ )
+ assert report["tcc"]["supported"] is False and "requires macOS" in report["tcc"]["reason"]
+ assert report["evidence"]["usable_as_evidence"] is False
+ assert report["evidence"]["tcc_source"] == "tcc_context"
+ assert report["complete"] is True and report["not_covered"] == list(spike.NOT_COVERED)
+ assert not any(row["group_killed"] for row in report["experiments"])
+ markdown = md.read_text(encoding="utf-8")
+ assert spike.EVIDENCE_DISCLAIMER in markdown and spike.EVIDENCE_RULE in markdown
+ assert spike.EVIDENCE_DISCLAIMER in done.stdout
+ assert sorted(path.name for path in tmp_path.rglob("*.tmp")) == [] # atomic writes tidy up
+
+
[email protected](sys.platform in ("win32", "darwin"), reason="real POSIX child; no Carbon")
+def test_only_still_runs_the_tcc_context_child(tmp_path: Path) -> None:
+ out = tmp_path / "spike.json"
+ assert spike.main(["--out", str(out), "--only", "duplicate_register"]) == 0
+ report = json.loads(out.read_text(encoding="utf-8"))
+ assert [e["name"] for e in report["experiments"]] == ["tcc_context", "duplicate_register"]
+ assert report["options"]["only"] == "duplicate_register"
+
+
+def test_a_killed_parent_still_leaves_every_finished_experiment_on_disk(
+ tmp_path: Path, monkeypatch
+) -> None:
+ finished = {
+ "name": "tcc_context",
+ "outcome": "ok",
+ "returncode": 0,
+ "signal": None,
+ "duration_s": 0.1,
+ "observations": {"tcc": {"supported": False, "reason": "x", "probes": {}}},
+ }
+
+ def interrupted_after_one(planned, *, on_result, **_kwargs):
+ on_result([finished]) # one experiment finished and was persisted ...
+ raise KeyboardInterrupt # ... then the job is cancelled
+
+ out, md = tmp_path / "r.json", tmp_path / "r.md"
+ monkeypatch.setattr(spike, "run_experiments", interrupted_after_one)
+ with pytest.raises(KeyboardInterrupt):
+ spike.main(["--out", str(out), "--summary-md", str(md)])
+ report = json.loads(out.read_text(encoding="utf-8"))
+ assert report["complete"] is False
+ assert [e["name"] for e in report["experiments"]] == ["tcc_context"]
+ assert report["tcc"]["reason"] == "x"
+ assert "Partial report" in md.read_text(encoding="utf-8")
+
+ # Even a parent killed before the first experiment ends leaves a (empty, partial) file.
+ out2 = tmp_path / "r2.json"
+ monkeypatch.setattr(
+ spike, "run_experiments", lambda *a, **k: (_ for _ in ()).throw(KeyboardInterrupt())
+ )
+ with pytest.raises(KeyboardInterrupt):
+ spike.main(["--out", str(out2)])
+ first = json.loads(out2.read_text(encoding="utf-8"))
+ assert first["complete"] is False and first["experiments"] == []
+ assert "did not run" in first["tcc"]["reason"]
+
+
+def test_run_experiments_hands_the_rows_so_far_to_the_callback_after_each_one() -> None:
+ ok = spike.RESULT_PREFIX + json.dumps({"ok": True})
+ runner = _Runner(_Done(0, ok.encode()))
+ seen: list[list[str]] = []
+ rows = spike.run_experiments(
+ [
+ spike.experiment_by_name("tcc_context"),
+ spike.experiment_by_name("control_signal_capture"),
+ ],
+ script_path=Path("/x/spike.py"),
+ inject=False,
+ on_result=lambda rows: seen.append([row["name"] for row in rows]),
+ run=runner,
+ )
+ assert seen == [["tcc_context"], ["tcc_context", "control_signal_capture"]]
+ assert [row["name"] for row in rows] == seen[-1] and len(runner.calls) == 2
+
+
+def test_tcc_comes_from_the_tcc_context_child_or_says_why_it_is_missing() -> None:
+ good = {"supported": True, "probes": {}, "window_server": None}
+ rows = [{"name": "tcc_context", "outcome": "ok", "observations": {"tcc": good}}]
+ assert spike.tcc_from_experiments(rows) == good
+ crashed = [
+ {"name": "tcc_context", "outcome": "crash", "signal": "SIGSEGV", "last_step": "probe=1"}
+ ]
+ tcc = spike.tcc_from_experiments(crashed)
+ assert tcc["supported"] is False and tcc["probes"] == {}
+ assert "outcome=crash" in tcc["reason"] and "SIGSEGV" in tcc["reason"]
+ assert "did not run" in spike.tcc_from_experiments([])["reason"]
+
+
+def test_write_text_is_atomic_and_creates_parents(tmp_path: Path) -> None:
+ target = tmp_path / "a" / "b" / "report.json"
+ spike._write_text(target, "one")
+ spike._write_text(target, "two")
+ assert target.read_text(encoding="utf-8") == "two"
+ assert [path.name for path in target.parent.iterdir()] == ["report.json"]
+
+
+def test_main_validates_its_arguments(tmp_path: Path) -> None:
+ with pytest.raises(SystemExit) as no_out:
+ spike.main([])
+ assert no_out.value.code == 2
+ with pytest.raises(SystemExit) as bad_only:
+ spike.main(["--out", str(tmp_path / "x.json"), "--only", "bogus"])
+ assert bad_only.value.code == 2
+
+
+# --- the script's own promises -----------------------------------------------------
+
+
+def test_the_script_never_imports_a_network_module() -> None:
+ tree = ast.parse(Path(spike.__file__).read_text(encoding="utf-8"))
+ imported: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ imported.update(alias.name.split(".")[0] for alias in node.names)
+ elif isinstance(node, ast.ImportFrom) and node.module:
+ imported.add(node.module.split(".")[0])
+ network = {"socket", "ssl", "urllib", "http", "requests", "httpx", "aiohttp", "ftplib"}
+ assert not imported & network
+ assert "jarvis" not in imported # stdlib + ctypes only
+
+
+# --- the workflow ------------------------------------------------------------------
+
+
+def _workflow() -> dict[str, Any]:
+ return yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))
+
+
+def _steps_of(doc: dict[str, Any]) -> list[dict[str, Any]]:
+ return [step for job in doc["jobs"].values() for step in job["steps"]]
+
+
+def test_workflow_is_dispatch_only_with_a_read_only_token() -> None:
+ doc = _workflow()
+ triggers = doc.get("on", doc.get(True)) # PyYAML reads the bare key `on` as True
+ assert set(triggers) == {"workflow_dispatch"}
+ assert doc["permissions"] == {"contents": "read"}
+ assert "secrets." not in WORKFLOW.read_text(encoding="utf-8")
+
+
+def test_workflow_pins_every_action_to_a_commit() -> None:
+ uses = [step["uses"] for step in _steps_of(_workflow()) if "uses" in step]
+ assert uses, "the workflow uses no action at all"
+ for reference in uses:
+ assert re.search(r"@[0-9a-f]{40}$", reference), reference
+
+
+def test_workflow_matrix_has_one_intel_and_one_arm64_runner_by_default() -> None:
+ doc = _workflow()
+ plan = doc["jobs"]["plan"]["steps"][0]["run"]
+ assert '"runner":"macos-15-intel","arch":"x86_64"' in plan
+ assert '"runner":"macos-15","arch":"arm64"' in plan
+ assert doc["jobs"]["spike"]["runs-on"] == "${{ matrix.runner }}"
+ assert doc["jobs"]["spike"]["strategy"]["fail-fast"] is False
+ # The optional macOS 26 row is opt-in: a missing label would queue forever.
+ inputs = (doc.get("on", doc.get(True)))["workflow_dispatch"]["inputs"]
+ assert inputs["include_macos_26"]["default"] is False
+ assert "macos-26" in plan and 'INCLUDE_MACOS_26" = "true"' in plan
+
+
+def test_workflow_runs_the_script_uploads_the_json_and_appends_the_summary() -> None:
+ steps = _steps_of(_workflow())
+ run = next(s for s in steps if s.get("name") == "Run the Carbon hotkey spike")["run"]
+ assert "scripts/ci/macos_carbon_hotkey_spike.py" in run
+ assert "--out" in run and "--summary-md" in run and "--inject-synthetic-key" in run
+ summary = next(s for s in steps if s.get("name") == "Publish the step summary")
+ assert summary["if"] == "always()"
+ assert "GITHUB_STEP_SUMMARY" in summary["run"]
+ # The fallback text must not drift from the script's sentence.
+ assert spike.EVIDENCE_DISCLAIMER in summary["run"]
+ upload = next(s for s in steps if s.get("uses", "").startswith("actions/upload-artifact@"))
+ assert upload["if"] == "always()" and upload["with"]["path"] == "spike-out/"
+ assert "carbon-hotkey-spike-" in upload["with"]["name"]
diff --git a/tests/unit/ci/test_macos_desktop_permission_step.py b/tests/unit/ci/test_macos_desktop_permission_step.py
new file mode 100644
index 0000000000..21cbb89af3
--- /dev/null
+++ b/tests/unit/ci/test_macos_desktop_permission_step.py
@@ -0,0 +1,248 @@
+"""The macOS lane's permission steps, run against FakeTCC.
+
+``.github/workflows/macos-desktop.yml`` carries small scripts that assert a bare
+Python process (which is not the installed app) is never allowed to start a native
+permission request of its own, that the native symbols the port binds resolve, and
+that the service never asks without a gesture. The scripts only really run on a
+macOS runner, so this test extracts them from the workflow and runs the very same
+text against the stateful FakeTCC: a step cannot rot into something that always
+passes, every state a runner can report is proven to pass, and each assertion is
+proven to bite before a runner ever sees it.
+"""
+
+from __future__ import annotations
+
+import importlib
+import re
+from pathlib import Path
+
+import pytest
+import yaml
+
+from jarvis.platform.permission_service import PermissionService
+from tests.fakes.fake_tcc import TccService, install_port, make_darwin_port
+
+_WORKFLOW = Path(__file__).resolve().parents[3] / ".github" / "workflows" / "macos-desktop.yml"
+_STEP_NAME = "Verify headless permission asks fail closed"
+_SYMBOL_STEP = "Probe the native permission symbols"
+_SMOKE_STEP = "Smoke the permission service without asking"
+
+
+def _step_script(name: str = _STEP_NAME) -> str:
+ document = yaml.safe_load(_WORKFLOW.read_text(encoding="utf-8"))
+ steps = document["jobs"]["desktop"]["steps"]
+ run = next(step["run"] for step in steps if step.get("name") == name)
+ match = re.search(r"python - <<'PY'\n(?P<code>.*?)\nPY\s*$", run, flags=re.DOTALL)
+ assert match is not None, "the step must be a quoted-heredoc python script"
+ return match.group("code")
+
+
+def _run_step(name: str = _STEP_NAME) -> None:
+ exec(compile(_step_script(name), str(_WORKFLOW), "exec"), {"__name__": "__ci_step__"}) # noqa: S102
+
+
+def test_the_step_replaces_the_deleted_port_request_and_snapshot_calls() -> None:
+ text = _step_script() + _WORKFLOW.read_text(encoding="utf-8")
+
+ assert "ensure(PermissionId.MICROPHONE, feature=" in text
+ assert "SystemPermissionPort()" not in text
+ assert ".snapshot(" not in text
+ assert "p.request(" not in text
+
+
+def test_a_bare_python_is_refused_and_asks_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ port, tcc = make_darwin_port(bundle_id="org.python.python")
+ install_port(monkeypatch, port)
+
+ _run_step()
+
+ assert tcc.requests() == []
+ tcc.assert_no_prompts()
+
+
+def test_a_runner_that_already_holds_the_grant_is_read_as_it_is(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ port, tcc = make_darwin_port(bundle_id="org.python.python", granted=[TccService.MICROPHONE])
+ install_port(monkeypatch, port)
+
+ _run_step()
+
+ assert tcc.requests() == []
+
+
+ "state",
+ ["not_determined", "granted", "denied", "restricted"],
+)
[email protected]("headless", [False, True])
+def test_every_state_a_runner_can_report_passes_the_step(
+ monkeypatch: pytest.MonkeyPatch, state: str, headless: bool
+) -> None:
+ """A denied or restricted microphone, or no desktop session, is not a failure."""
+ port, tcc = make_darwin_port(bundle_id="org.python.python", headless=headless)
+ if state == "granted":
+ tcc.grant(TccService.MICROPHONE)
+ elif state == "denied":
+ tcc.deny(TccService.MICROPHONE)
+ elif state == "restricted":
+ tcc.restrict(TccService.MICROPHONE)
+ install_port(monkeypatch, port)
+
+ _run_step()
+
+ assert tcc.requests() == []
+ tcc.assert_no_prompts()
+
+
+def test_the_step_replaces_the_native_request_seams_with_tripwires() -> None:
+ script = _step_script()
+
+ for seam in ("port.request_native", "port._iohid_request", "port._automation_consent_runner"):
+ assert f"{seam} = forbidden" in script
+
+
+def test_the_step_bites_when_the_installed_app_could_ask(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Run as the installed app the step's own precondition fails: it is not a no-op."""
+ port, _tcc = make_darwin_port()
+ install_port(monkeypatch, port)
+
+ with pytest.raises(AssertionError):
+ _run_step()
+
+
+def test_the_step_bites_when_the_service_asks_outside_the_installed_app(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The precondition holds (a bare Python), yet the service asks anyway: the step must fail.
+
+ The ask is forced through ``allow_outside_app``, the one switch that lifts the
+ refusal. The failure must come from the tripwire or the ``asked`` assertion, not
+ from the precondition.
+ """
+ port, tcc = make_darwin_port(bundle_id="org.python.python")
+ install_port(monkeypatch, port)
+ assert port.outside_installed_app is True
+ real_ensure = PermissionService.ensure
+
+ def asking_ensure(self, permission, **kwargs):
+ return real_ensure(self, permission, **{**kwargs, "allow_outside_app": True})
+
+ monkeypatch.setattr(PermissionService, "ensure", asking_ensure)
+
+ with pytest.raises(AssertionError, match="native"):
+ _run_step()
+
+ # The tripwire sat in front of the fake: nothing reached it.
+ assert tcc.requests() == []
+
+
+# --- Native symbol binding
+
+
+class _Framework:
+ """A framework stand-in that has every symbol except the ones listed."""
+
+ def __init__(self, missing: frozenset[str] = frozenset()) -> None:
+ self._missing = missing
+
+ def __getattr__(self, name: str) -> object:
+ if name in self._missing:
+ raise AttributeError(name)
+ return object()
+
+
+def test_the_symbol_probe_passes_when_every_required_symbol_binds(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(importlib, "import_module", lambda _name: _Framework())
+
+ _run_step(_SYMBOL_STEP)
+
+
+def test_the_symbol_probe_names_a_missing_required_symbol(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ importlib,
+ "import_module",
+ lambda _name: _Framework(frozenset({"CGPreflightListenEventAccess"})),
+ )
+
+ with pytest.raises(AssertionError, match="CGPreflightListenEventAccess"):
+ _run_step(_SYMBOL_STEP)
+
+
+def test_the_symbol_probe_only_reports_a_missing_optional_symbol(
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ monkeypatch.setattr(
+ importlib,
+ "import_module",
+ lambda _name: _Framework(frozenset({"CGPreflightPostEventAccess"})),
+ )
+
+ _run_step(_SYMBOL_STEP)
+
+ assert "optional symbol absent: Quartz.CGPreflightPostEventAccess" in capsys.readouterr().out
+
+
+# --- Service smoke without a gesture
+
+
[email protected]("bundle_id", ["org.python.python", None])
+def test_the_service_smoke_reads_every_permission_and_asks_nothing(
+ monkeypatch: pytest.MonkeyPatch, bundle_id: str | None
+) -> None:
+ kwargs = {"bundle_id": bundle_id} if bundle_id else {}
+ port, tcc = make_darwin_port(**kwargs)
+ install_port(monkeypatch, port)
+
+ _run_step(_SMOKE_STEP)
+
+ assert tcc.requests() == []
+ tcc.assert_no_prompts()
+
+
+def test_the_service_smoke_bites_when_a_background_ensure_asks(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ port, _tcc = make_darwin_port()
+ install_port(monkeypatch, port)
+ real_ensure = PermissionService.ensure
+
+ def asking_ensure(self, permission, **kwargs):
+ return real_ensure(self, permission, **{**kwargs, "interactive": True})
+
+ monkeypatch.setattr(PermissionService, "ensure", asking_ensure)
+
+ with pytest.raises(AssertionError):
+ _run_step(_SMOKE_STEP)
+
+
+def test_the_service_smoke_bites_on_a_state_that_is_not_a_permission_state(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ port, _tcc = make_darwin_port()
+ install_port(monkeypatch, port)
+ monkeypatch.setattr(PermissionService, "check", lambda self, permission, **_kw: "granted")
+
+ with pytest.raises(AssertionError):
+ _run_step(_SMOKE_STEP)
+
+
+def test_the_service_smoke_bites_on_a_hung_probe(monkeypatch: pytest.MonkeyPatch) -> None:
+ import threading
+
+ port, _tcc = make_darwin_port()
+ install_port(monkeypatch, port)
+ release = threading.Event()
+ port._automation_probe = lambda _bundle, _ask: release.wait(60)
+ # A short deadline so the failing case does not wait the real 30 seconds.
+ real_join = threading.Thread.join
+ monkeypatch.setattr(threading.Thread, "join", lambda self, timeout=None: real_join(self, 0.2))
+ try:
+ with pytest.raises(AssertionError, match="did not return"):
+ _run_step(_SMOKE_STEP)
+ finally:
+ release.set()
diff --git a/tests/unit/ci/test_pipeline_scripts.py b/tests/unit/ci/test_pipeline_scripts.py
index a49e1543b7..68f6ca5126 100644
--- a/tests/unit/ci/test_pipeline_scripts.py
+++ b/tests/unit/ci/test_pipeline_scripts.py
@@ -70,6 +70,101 @@ def test_unrelated_python_change_leaves_the_updater_lane_off():
assert result["updater"] is False
+ "path",
+ [
+ # Packaging: the spec, the build script, the entitlements and the single
+ # usage-string table both macOS bundles load.
+ "jarvis.spec",
+ "packaging/macos/build.sh",
+ "packaging/macos/entitlements.plist",
+ "packaging/macos/README.md",
+ "jarvis/core/macos_privacy_strings.py",
+ # The just-in-time permission service, its port and its HTTP surface.
+ "jarvis/platform/permission_service.py",
+ "jarvis/platform/permissions.py",
+ "jarvis/ui/web/permissions_routes.py",
+ # Every directory whose code asks for, or acts on, a macOS permission.
+ "jarvis/audio/capture.py",
+ "jarvis/cu/engine.py",
+ "jarvis/vision/screenshot.py",
+ "jarvis/screen_context/capture.py",
+ "jarvis/dictation/insert.py",
+ "jarvis/trigger/backends/quartz.py",
+ "jarvis/platform/window_state.py",
+ # The voice gates, the wake/mic routes, the shared events and protocols, and
+ # the fakes and contract tests the macOS lane runs.
+ "jarvis/speech/pipeline.py",
+ "jarvis/speech/diagnose.py",
+ "jarvis/ui/web/settings_routes.py",
+ "jarvis/core/events.py",
+ # Consumers that capture, type or relay: tools, appshot, routes, CLI, bundle ids.
+ "jarvis/plugins/tool/screen_snapshot.py",
+ "jarvis/plugins/tool/type_text.py",
+ "jarvis/plugins/tool/verify_localhost.py",
+ "jarvis/plugins/harness/computer_use.py",
+ "jarvis/appshot/gesture.py",
+ "jarvis/ui/web/screen_context_routes.py",
+ "jarvis/cli_ctl/commands/permissions.py",
+ "jarvis/core/branding.py",
+ "jarvis/tasks/event_catalog.py",
+ "jarvis/core/protocols.py",
+ "tests/fakes/fake_tcc.py",
+ "tests/fakes/fake_permission_service.py",
+ "tests/contract/test_permission_service_contract.py",
+ "tests/unit/core/test_permission_events.py",
+ "tests/unit/ci/test_macos_desktop_permission_step.py",
+ "tests/unit/ui/web/test_permissions_routes.py",
+ "tests/unit/trigger/test_quartz_backend.py",
+ # The windows spelling of a path must classify the same way.
+ "jarvis\\core\\macos_privacy_strings.py",
+ ],
+)
+def test_macos_permission_and_packaging_paths_turn_on_the_macos_lane(path):
+ result = classify_changes.classify([path])
+
+ assert result["macos_desktop"] is True, path
+ assert result["full"] is False, path
+
+
+ "path",
+ [
+ "jarvis/society/roster.py",
+ "jarvis/ui/web/society_browser_routes.py",
+ "packaging/windows/PersonalJarvis.iss",
+ "packaging/linux/build.sh",
+ "docs/macos-permissions.md",
+ ],
+)
+def test_unrelated_paths_leave_the_macos_lane_off(path):
+ assert classify_changes.classify([path])["macos_desktop"] is False, path
+
+
+def test_the_macos_lane_gate_names_the_new_paths_it_adds_to_the_prefix_tables():
+ """Guard the data, not just the outcome: a refactor must not drop an entry."""
+ assert {"jarvis.spec", "jarvis/core/macos_privacy_strings.py"} <= classify_changes._MACOS_FILES
+ assert "jarvis/ui/web/permissions_routes.py" in classify_changes._MACOS_FILES
+ assert {
+ "jarvis/plugins/tool/screen_snapshot.py",
+ "jarvis/plugins/tool/type_text.py",
+ "jarvis/plugins/tool/verify_localhost.py",
+ "jarvis/speech/diagnose.py",
+ "jarvis/ui/web/screen_context_routes.py",
+ "jarvis/cli_ctl/commands/permissions.py",
+ "jarvis/core/branding.py",
+ "jarvis/tasks/event_catalog.py",
+ } <= classify_changes._MACOS_FILES
+ assert {
+ "packaging/macos/",
+ "jarvis/screen_context/",
+ "jarvis/dictation/",
+ "jarvis/appshot/",
+ } <= set(
+ classify_changes._MACOS_PREFIXES
+ )
+
+
def test_lockfile_change_reaches_deps_realtime_and_installer():
result = classify_changes.classify(["requirements.txt"])
assert result["deps"] and result["realtime"] and result["installer"]
diff --git a/tests/unit/cli_ctl/test_commands_permissions.py b/tests/unit/cli_ctl/test_commands_permissions.py
index 65dae50fb8..6dbce43c72 100644
--- a/tests/unit/cli_ctl/test_commands_permissions.py
+++ b/tests/unit/cli_ctl/test_commands_permissions.py
@@ -1,10 +1,17 @@
from __future__ import annotations
+import json
+import plistlib
+import subprocess
+import sys
from types import SimpleNamespace
+import pytest
+import typer
from typer.testing import CliRunner
from jarvis.cli_ctl.__main__ import app
+from jarvis.platform.permissions import ACCEPTED_BUNDLE_IDS
runner = CliRunner()
@@ -40,6 +47,60 @@ def test_request_with_yes_uses_permission_path(monkeypatch, capture_api):
assert call["path"] == "/api/permissions/screen_recording/request"
+def test_status_reads_the_automation_row_only_on_request(capture_api):
+ plain = runner.invoke(app, ["permissions", "status"])
+ with_automation = runner.invoke(app, ["permissions", "status", "--include-automation"])
+
+ assert plain.exit_code == 0 and with_automation.exit_code == 0
+ first, second = capture_api["calls"][-2:]
+ assert first["path"] == second["path"] == "/api/permissions/status"
+ assert first["query"] == {}
+ assert second["query"] == {"include": "automation"}
+
+
+def test_request_sends_no_body_because_the_installed_app_is_the_only_grantee(
+ monkeypatch, capture_api
+):
+ monkeypatch.setattr(
+ "jarvis.cli_ctl.commands.permissions._activate_macos_app_for_tcc", lambda: None
+ )
+
+ result = runner.invoke(app, ["permissions", "request", "microphone", "--yes"])
+
+ assert result.exit_code == 0
+ assert capture_api["calls"][-1]["body"] is None
+
+
+def test_request_has_no_outside_app_option(capture_api):
+ # The route answers 403 confirmation_requires_ui to a Bearer-only caller, so the
+ # flag could only fail and would invite an agent to try: it does not exist.
+ result = runner.invoke(
+ app, ["permissions", "request", "microphone", "--allow-outside-app", "--yes"]
+ )
+
+ assert result.exit_code == 2
+ assert capture_api["calls"] == []
+ help_text = runner.invoke(app, ["permissions", "request", "--help"]).output
+ assert "allow-outside-app" not in help_text
+
+
+def test_request_refuses_clearly_without_the_installed_app_and_sends_nothing(
+ monkeypatch, tmp_path, capture_api
+):
+ from jarvis.cli_ctl.commands import permissions as module
+
+ monkeypatch.setattr(module, "detect_platform", lambda: "darwin")
+ monkeypatch.setattr(module, "_installed_macos_app", lambda: tmp_path / "Missing.app")
+
+ result = runner.invoke(app, ["permissions", "request", "microphone", "--yes"])
+
+ assert result.exit_code == 1
+ assert capture_api["calls"] == []
+ message = " ".join(result.output.split())
+ assert "installed Personal Jarvis app was not found" in message
+ assert "nothing was requested" in message
+
+
def test_request_activates_app_after_confirmation(monkeypatch, capture_api):
calls: list[str] = []
monkeypatch.setattr(
@@ -95,15 +156,14 @@ def test_request_dry_run_does_not_activate_app(monkeypatch, capture_api):
assert capture_api["calls"] == []
-def test_macos_activation_targets_canonical_bundle_and_waits_for_identity(
- monkeypatch, tmp_path
-):
+def _activate_with_frontmost(monkeypatch, tmp_path, frontmost_id: str):
+ """Run the macOS activation helper against a fake frontmost app."""
from jarvis.cli_ctl.commands import permissions as module
bundle = tmp_path / "Personal Jarvis.app"
bundle.mkdir()
commands: list[list[str]] = []
- frontmost = SimpleNamespace(bundleIdentifier=lambda: module.EXPECTED_BUNDLE_ID)
+ frontmost = SimpleNamespace(bundleIdentifier=lambda: frontmost_id)
workspace = SimpleNamespace(frontmostApplication=lambda: frontmost)
appkit = SimpleNamespace(
NSWorkspace=SimpleNamespace(sharedWorkspace=lambda: workspace)
@@ -118,7 +178,374 @@ def test_macos_activation_targets_canonical_bundle_and_waits_for_identity(
),
)
monkeypatch.setattr(module.importlib, "import_module", lambda _name: appkit)
+ # A fake clock keeps the "never became the foreground app" case instant.
+ ticks = iter(range(1000))
+ monkeypatch.setattr(
+ module,
+ "time",
+ SimpleNamespace(monotonic=lambda: float(next(ticks)), sleep=lambda _s: None),
+ )
+ return module, bundle, commands
+
+
[email protected]("bundle_id", ACCEPTED_BUNDLE_IDS)
+def test_macos_activation_targets_canonical_bundle_and_waits_for_identity(
+ monkeypatch, tmp_path, bundle_id
+):
+ # Both the managed bundle and the downloaded .dmg app are the installed app;
+ # the .dmg one used to be refused here, so `jarvis permissions request`
+ # failed on a Mac that only has the downloaded app.
+ module, bundle, commands = _activate_with_frontmost(monkeypatch, tmp_path, bundle_id)
module._activate_macos_app_for_tcc()
assert commands == [["open", str(bundle)]]
+
+
+def test_macos_activation_refuses_when_another_app_stays_in_front(monkeypatch, tmp_path):
+ module, _bundle, _commands = _activate_with_frontmost(
+ monkeypatch, tmp_path, "com.apple.Terminal"
+ )
+
+ with pytest.raises(typer.Exit) as excinfo:
+ module._activate_macos_app_for_tcc()
+
+ assert excinfo.value.exit_code == 1
+
+
+# --- permissions reset: the local tccutil command ------------------------------
+
+_RESET_SERVICES = {
+ "microphone": "Microphone",
+ "screen_recording": "ScreenCapture",
+ "accessibility": "Accessibility",
+ "input_monitoring": "ListenEvent",
+ "event_posting": "PostEvent",
+ "automation": "AppleEvents",
+}
+
+
+class _TccutilRecorder:
+ """A hand-written stand-in for ``/usr/bin/tccutil`` that records every argv."""
+
+ def __init__(self, returncode: int = 0, stderr: str = "") -> None:
+ self.calls: list[list[str]] = []
+ self.returncode = returncode
+ self.stderr = stderr
+
+ def __call__(self, argv: list[str]) -> SimpleNamespace:
+ self.calls.append(list(argv))
+ return SimpleNamespace(returncode=self.returncode, stdout="", stderr=self.stderr)
+
+
+def _macos_with_app(monkeypatch, tmp_path, bundle_id: str | None):
+ """Pretend to be macOS with an installed app carrying ``bundle_id`` (None: no app)."""
+ from jarvis.cli_ctl.commands import permissions as module
+
+ app_dir = tmp_path / "Personal Jarvis.app"
+ if bundle_id is not None:
+ (app_dir / "Contents").mkdir(parents=True)
+ (app_dir / "Contents" / "Info.plist").write_bytes(
+ plistlib.dumps({"CFBundleIdentifier": bundle_id})
+ )
+ recorder = _TccutilRecorder()
+ monkeypatch.setattr(module, "detect_platform", lambda: "darwin")
+ monkeypatch.setattr(module, "_installed_macos_app", lambda: app_dir)
+ monkeypatch.setattr(module, "_run_tccutil", recorder)
+ return module, recorder
+
+
+def test_reset_is_registered_in_the_command_index() -> None:
+ from jarvis.cli_ctl.command_index import COMMAND_INDEX
+
+ assert COMMAND_INDEX["permissions"] == ("status", "request", "open-settings", "reset")
+
+
+def test_reset_off_macos_says_so_in_one_line_and_exits_non_zero(monkeypatch, capture_api):
+ from jarvis.cli_ctl.commands import permissions as module
+
+ recorder = _TccutilRecorder()
+ monkeypatch.setattr(module, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(module, "_run_tccutil", recorder)
+
+ result = runner.invoke(app, ["permissions", "reset", "microphone", "--yes"])
+
+ assert result.exit_code == 1
+ message = " ".join(result.output.split())
+ assert "only works on macOS" in message
+ assert len(result.output.strip().splitlines()) <= 3 # the one sentence (it may wrap)
+ assert recorder.calls == []
+ assert capture_api["calls"] == []
+
+
+def test_reset_off_macos_refuses_even_a_dry_run(monkeypatch, capture_api):
+ from jarvis.cli_ctl.commands import permissions as module
+
+ monkeypatch.setattr(module, "detect_platform", lambda: "win32")
+
+ result = runner.invoke(app, ["permissions", "reset", "microphone", "--dry-run"])
+
+ assert result.exit_code == 1
+ assert "only works on macOS" in " ".join(result.output.split())
+
+
[email protected]("bundle_id", ACCEPTED_BUNDLE_IDS)
[email protected](("permission", "service"), sorted(_RESET_SERVICES.items()))
+def test_reset_builds_exactly_the_tccutil_command_for_each_permission_and_bundle(
+ monkeypatch, tmp_path, capture_api, permission, service, bundle_id
+):
+ module, recorder = _macos_with_app(monkeypatch, tmp_path, bundle_id)
+
+ result = runner.invoke(app, ["--json", "permissions", "reset", permission, "--yes"])
+
+ assert result.exit_code == 0, result.output
+ assert recorder.calls == [["/usr/bin/tccutil", "reset", service, bundle_id]]
+ payload = json.loads(result.stdout)
+ assert payload["ok"] is True and payload["performed"] is True
+ assert payload["bundle_id"] == bundle_id and payload["service"] == service
+ assert "Quit and reopen" in payload["message"]
+ # It is a local command: nothing goes to the app's REST API (its /reset route
+ # refuses scripts on purpose).
+ assert capture_api["calls"] == []
+
+
[email protected]("bundle_id", ACCEPTED_BUNDLE_IDS)
+def test_reset_bundle_id_option_wins_over_the_installed_app(monkeypatch, tmp_path, bundle_id):
+ other = next(candidate for candidate in ACCEPTED_BUNDLE_IDS if candidate != bundle_id)
+ _module, recorder = _macos_with_app(monkeypatch, tmp_path, other)
+
+ result = runner.invoke(
+ app, ["permissions", "reset", "microphone", "--bundle-id", bundle_id, "--yes"]
+ )
+
+ assert result.exit_code == 0, result.output
+ assert recorder.calls == [["/usr/bin/tccutil", "reset", "Microphone", bundle_id]]
+
+
+def test_reset_refuses_a_bundle_id_that_is_not_ours(monkeypatch, tmp_path):
+ _module, recorder = _macos_with_app(monkeypatch, tmp_path, ACCEPTED_BUNDLE_IDS[0])
+
+ result = runner.invoke(
+ app,
+ ["permissions", "reset", "microphone", "--bundle-id", "com.apple.Safari", "--yes"],
+ )
+
+ assert result.exit_code == 2
+ assert "--bundle-id must be one of" in " ".join(result.output.split())
+ assert recorder.calls == []
+
+
+def test_reset_needs_yes_and_runs_nothing_without_it(monkeypatch, tmp_path):
+ _module, recorder = _macos_with_app(monkeypatch, tmp_path, ACCEPTED_BUNDLE_IDS[0])
+ monkeypatch.delenv("JARVIS_CLI_ASSUME_YES", raising=False)
+
+ result = runner.invoke(app, ["permissions", "reset", "screen_recording"])
+
+ assert result.exit_code == 1
+ assert "--yes" in result.output
+ assert recorder.calls == []
+
+
+def test_reset_accepts_the_assume_yes_environment(monkeypatch, tmp_path):
+ _module, recorder = _macos_with_app(monkeypatch, tmp_path, ACCEPTED_BUNDLE_IDS[0])
+ monkeypatch.setenv("JARVIS_CLI_ASSUME_YES", "1")
+
+ result = runner.invoke(app, ["permissions", "reset", "screen_recording"])
+
+ assert result.exit_code == 0, result.output
+ assert len(recorder.calls) == 1
+
+
+def test_reset_dry_run_prints_the_command_and_runs_nothing(monkeypatch, tmp_path):
+ _module, recorder = _macos_with_app(monkeypatch, tmp_path, ACCEPTED_BUNDLE_IDS[1])
+
+ result = runner.invoke(app, ["--json", "permissions", "reset", "accessibility", "--dry-run"])
+
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.stdout)
+ assert payload["dry_run"] is True
+ assert payload["argv"] == ["/usr/bin/tccutil", "reset", "Accessibility", ACCEPTED_BUNDLE_IDS[1]]
+ assert recorder.calls == []
+
+
+def test_reset_refuses_a_permission_without_a_privacy_record(monkeypatch, tmp_path):
+ _module, recorder = _macos_with_app(monkeypatch, tmp_path, ACCEPTED_BUNDLE_IDS[0])
+
+ result = runner.invoke(app, ["permissions", "reset", "credential_store", "--yes"])
+
+ assert result.exit_code == 1
+ assert "no macOS privacy record" in " ".join(result.output.split())
+ assert recorder.calls == []
+
+
+def test_reset_without_an_installed_app_says_what_to_do(monkeypatch, tmp_path):
+ _module, recorder = _macos_with_app(monkeypatch, tmp_path, None)
+
+ result = runner.invoke(app, ["permissions", "reset", "microphone", "--yes"])
+
+ assert result.exit_code == 1
+ message = " ".join(result.output.split())
+ assert "installed Personal Jarvis app was not found" in message
+ assert "--bundle-id" in message and "nothing was reset" in message
+ assert recorder.calls == []
+
+
+def test_reset_refuses_an_installed_app_with_a_foreign_bundle_id(monkeypatch, tmp_path):
+ _module, recorder = _macos_with_app(monkeypatch, tmp_path, "com.example.other")
+
+ result = runner.invoke(app, ["permissions", "reset", "microphone", "--yes"])
+
+ assert result.exit_code == 1
+ assert "not one of Personal Jarvis's" in " ".join(result.output.split())
+ assert recorder.calls == []
+
+
+def test_reset_refuses_an_unreadable_info_plist(monkeypatch, tmp_path):
+ module, recorder = _macos_with_app(monkeypatch, tmp_path, ACCEPTED_BUNDLE_IDS[0])
+ (tmp_path / "Personal Jarvis.app" / "Contents" / "Info.plist").write_bytes(b"not a plist")
+
+ result = runner.invoke(app, ["permissions", "reset", "microphone", "--yes"])
+
+ assert result.exit_code == 1
+ message = " ".join(result.output.split())
+ assert "Info.plist could not be read" in message and "nothing was reset" in message
+ assert recorder.calls == []
+
+
+def test_reset_reports_a_failing_tccutil_with_its_status(monkeypatch, tmp_path):
+ module, _recorder = _macos_with_app(monkeypatch, tmp_path, ACCEPTED_BUNDLE_IDS[0])
+ failing = _TccutilRecorder(returncode=70, stderr="tccutil: Failed to reset Microphone\n")
+ monkeypatch.setattr(module, "_run_tccutil", failing)
+
+ result = runner.invoke(app, ["permissions", "reset", "microphone", "--yes"])
+
+ assert result.exit_code == 1
+ message = " ".join(result.output.split())
+ assert "status 70" in message and "Failed to reset Microphone" in message
+ assert len(failing.calls) == 1
+
+
[email protected]("failure", [OSError("no such file"), subprocess.TimeoutExpired("x", 30)])
+def test_reset_survives_tccutil_that_cannot_run(monkeypatch, tmp_path, failure):
+ module, _recorder = _macos_with_app(monkeypatch, tmp_path, ACCEPTED_BUNDLE_IDS[0])
+
+ def explode(_argv):
+ raise failure
+
+ monkeypatch.setattr(module, "_run_tccutil", explode)
+
+ result = runner.invoke(app, ["permissions", "reset", "microphone", "--yes"])
+
+ assert result.exit_code == 1
+ assert "tccutil could not run" in " ".join(result.output.split())
+
+
+def test_run_tccutil_is_utf8_and_windowless(monkeypatch):
+ """AP-1: every subprocess passes NO_WINDOW_CREATIONFLAGS and decodes UTF-8."""
+ from jarvis.cli_ctl.commands import permissions as module
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ seen: dict[str, object] = {}
+
+ def fake_run(argv, **kwargs):
+ seen["argv"] = argv
+ seen.update(kwargs)
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(module.subprocess, "run", fake_run)
+
+ module._run_tccutil(["/usr/bin/tccutil", "reset", "Microphone", "x"])
+
+ assert seen["creationflags"] == NO_WINDOW_CREATIONFLAGS
+ assert seen["encoding"] == "utf-8" and seen["errors"] == "replace"
+ assert seen["text"] is True and seen["check"] is False
+ assert seen["timeout"] == module._TCCUTIL_TIMEOUT_S
+ assert "shell" not in seen
+
+
[email protected](sys.platform == "win32", reason="the fake tccutil is a POSIX shell script")
+def test_reset_end_to_end_with_a_fake_tccutil_executable(monkeypatch, tmp_path):
+ """The real ``_run_tccutil`` path: a fake executable stands in for /usr/bin/tccutil."""
+ from jarvis.cli_ctl.commands import permissions as module
+
+ log = tmp_path / "argv.log"
+ fake = tmp_path / "tccutil"
+ fake.write_text(f'#!/bin/sh\nprintf \'%s\\n\' "$@" > "{log}"\nexit 0\n', encoding="utf-8")
+ fake.chmod(0o755)
+ app_dir = tmp_path / "Personal Jarvis.app"
+ (app_dir / "Contents").mkdir(parents=True)
+ (app_dir / "Contents" / "Info.plist").write_bytes(
+ plistlib.dumps({"CFBundleIdentifier": ACCEPTED_BUNDLE_IDS[0]})
+ )
+ monkeypatch.setattr(module, "detect_platform", lambda: "darwin")
+ monkeypatch.setattr(module, "_installed_macos_app", lambda: app_dir)
+ monkeypatch.setattr(module, "_TCCUTIL", str(fake))
+
+ result = runner.invoke(app, ["--json", "permissions", "reset", "input_monitoring", "--yes"])
+
+ assert result.exit_code == 0, result.output
+ assert log.read_text(encoding="utf-8").split() == [
+ "reset",
+ "ListenEvent",
+ ACCEPTED_BUNDLE_IDS[0],
+ ]
+
+
+ ("permission", "target"),
+ [
+ ("microphone", ""),
+ ("screen_recording", ""),
+ ("input_monitoring", ""),
+ ("automation", "com.apple.Music"),
+ ],
+)
[email protected]("bundle_id", ACCEPTED_BUNDLE_IDS)
+def test_reset_returns_the_apps_own_row_to_not_determined_in_fake_tcc(
+ monkeypatch, tmp_path, permission, target, bundle_id
+):
+ """FakeTCC models ``tccutil reset``: the named bundle's row goes back to "not asked yet"."""
+ from tests.fakes.fake_tcc import FakeTCC, TccState
+
+ tcc = FakeTCC(bundle_id=bundle_id, granted=(permission,))
+ module, _recorder = _macos_with_app(monkeypatch, tmp_path, bundle_id)
+ monkeypatch.setattr(module, "_run_tccutil", tcc.run_tccutil)
+ assert tcc.state(permission, target) is TccState.GRANTED
+
+ result = runner.invoke(app, ["permissions", "reset", permission, "--yes"])
+
+ assert result.exit_code == 0, result.output
+ assert len(tcc.tccutil_calls) == 1
+ assert tcc.state(permission, target) is TccState.NOT_DETERMINED
+
+
[email protected]("permission", ["accessibility", "event_posting"])
+def test_reset_of_the_accessibility_family_is_accepted_by_fake_tcc(
+ monkeypatch, tmp_path, permission
+):
+ """Accessibility has no "not determined" (boolean trust): it reads denied afterwards."""
+ from tests.fakes.fake_tcc import FakeTCC, TccState
+
+ tcc = FakeTCC(bundle_id=ACCEPTED_BUNDLE_IDS[0], granted=("accessibility",))
+ module, _recorder = _macos_with_app(monkeypatch, tmp_path, ACCEPTED_BUNDLE_IDS[0])
+ monkeypatch.setattr(module, "_run_tccutil", tcc.run_tccutil)
+
+ result = runner.invoke(app, ["permissions", "reset", permission, "--yes"])
+
+ assert result.exit_code == 0, result.output
+ assert tcc.state("accessibility") is TccState.DENIED
+
+
+def test_reset_leaves_the_other_apps_row_alone_in_fake_tcc(monkeypatch, tmp_path):
+ from tests.fakes.fake_tcc import FakeTCC, TccState
+
+ ours, other = ACCEPTED_BUNDLE_IDS
+ tcc = FakeTCC(bundle_id=other, granted=("microphone",))
+ module, _recorder = _macos_with_app(monkeypatch, tmp_path, ours)
+ monkeypatch.setattr(module, "_run_tccutil", tcc.run_tccutil)
+
+ result = runner.invoke(app, ["permissions", "reset", "microphone", "--yes"])
+
+ assert result.exit_code == 0, result.output
+ assert tcc.tccutil_calls == [["/usr/bin/tccutil", "reset", "Microphone", ours]]
+ assert tcc.state("microphone") is TccState.GRANTED
diff --git a/tests/unit/core/test_branding.py b/tests/unit/core/test_branding.py
index 4a9a199560..1a64135b44 100644
--- a/tests/unit/core/test_branding.py
+++ b/tests/unit/core/test_branding.py
@@ -37,6 +37,7 @@ _CURRENT_IDENTITY = {
"MACOS_APP_DIR_NAME": "Personal Jarvis.app",
"MACOS_EXECUTABLE_NAME": "PersonalJarvis",
"MACOS_BUNDLE_ID": "com.personal-jarvis.desktop",
+ "MACOS_DMG_BUNDLE_ID": "ai.personaljarvis.desktop",
"MACOS_AUTOSTART_LABEL": "com.personal-jarvis.autostart",
"LINUX_APP_NAME": "Personal Jarvis",
"LINUX_DESKTOP_ENTRY_FILE_NAME": "personal-jarvis.desktop",
diff --git a/tests/unit/core/test_permission_events.py b/tests/unit/core/test_permission_events.py
new file mode 100644
index 0000000000..e2f60ce717
--- /dev/null
+++ b/tests/unit/core/test_permission_events.py
@@ -0,0 +1,460 @@
+"""The just-in-time permission events: vocabulary parity, wire shape, bus safety.
+
+``PermissionNeeded`` / ``PermissionResolved`` carry values that cross Python
+(the permission service), the bus, the ``/ws`` forwarder and the UI copy keyed
+per (feature, reason) — the five-layer shape AP-4 / BUG-008 guards. A drift
+shows up here as one failing test instead of an unknown-reason blank card.
+
+1. ``jarvis/core/events.py`` — the tuples + dataclasses (source of truth)
+2. ``jarvis/ui/web/schema.py`` — ``event_to_ws_envelope`` (the /ws wire shape)
+3. ``jarvis/ui/web/frontend/src/lib/permissionEvents.ts`` — the TS const tuples + payload interfaces
+4. ``jarvis/tasks/event_catalog.py`` — routines must NOT be able to trigger on them
+"""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import json
+import re
+from dataclasses import FrozenInstanceError, fields, is_dataclass
+from pathlib import Path
+from uuid import UUID, uuid4
+
+import pytest
+
+from jarvis.core import events as events_mod
+from jarvis.core.bus import EventBus
+from jarvis.core.events import (
+ PERMISSION_FEATURES,
+ PERMISSION_NEEDED_ORIGINS,
+ PERMISSION_NEEDED_PHASES,
+ PERMISSION_NEEDED_REASONS,
+ DictationRefused,
+ Event,
+ PermissionNeeded,
+ PermissionResolved,
+)
+from jarvis.ui.web.schema import event_to_ws_envelope
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+TS_FILE = REPO_ROOT / "jarvis/ui/web/frontend/src/lib/permissionEvents.ts"
+
+_ENVELOPE_FIELDS = {"trace_id", "timestamp_ns", "source_layer"}
+
+# Python tuple -> (TS const tuple name, TS union type name)
+_VOCABULARIES: dict[str, tuple[tuple[str, ...], str, str]] = {
+ "features": (PERMISSION_FEATURES, "PERMISSION_FEATURES", "PermissionFeature"),
+ "reasons": (
+ PERMISSION_NEEDED_REASONS,
+ "PERMISSION_NEEDED_REASONS",
+ "PermissionNeededReason",
+ ),
+ "phases": (PERMISSION_NEEDED_PHASES, "PERMISSION_NEEDED_PHASES", "PermissionNeededPhase"),
+ "origins": (PERMISSION_NEEDED_ORIGINS, "PERMISSION_NEEDED_ORIGINS", "PermissionNeededOrigin"),
+}
+
+# Event field -> the TS union its payload interface must use for it.
+_ENUMERATED_FIELDS: dict[str, str] = {
+ "feature": "PermissionFeature",
+ "reason": "PermissionNeededReason",
+ "phase": "PermissionNeededPhase",
+ "origin": "PermissionNeededOrigin",
+}
+
+# Python annotation (a string: events.py uses `from __future__ import annotations`)
+# -> the TS type the twin must declare. An unmapped annotation fails loudly so a
+# new field type forces this table to be extended instead of passing unchecked.
+_TS_TYPES: dict[str, str] = {
+ "str": "string",
+ "bool": "boolean",
+ "tuple[str, ...]": "string[]",
+}
+
+
+def _ts_source() -> str:
+ return TS_FILE.read_text(encoding="utf-8")
+
+
+def _ts_tuple(name: str) -> list[str]:
+ match = re.search(rf"export const {name} = \[([^\]]*)\] as const;", _ts_source())
+ assert match, f"{name} const tuple missing from {TS_FILE.name}"
+ return re.findall(r'"([a-z_]+)"', match.group(1))
+
+
+def _ts_interface(name: str) -> dict[str, str]:
+ """Field name -> declared TS type of one exported interface (declarations only)."""
+ match = re.search(rf"export interface {name} \{{(.*?)\n\}}", _ts_source(), re.S)
+ assert match, f"interface {name} missing from {TS_FILE.name}"
+ return dict(re.findall(r"^\s{2}([a-z_]+): ([^;\n]+);", match.group(1), re.M))
+
+
+def _payload_fields(event_cls: type[Event]) -> dict[str, str]:
+ return {f.name: str(f.type) for f in fields(event_cls) if f.name not in _ENVELOPE_FIELDS}
+
+
+def _needed(**overrides: object) -> PermissionNeeded:
+ values: dict[str, object] = {
+ "permissions": ("accessibility",),
+ "feature": "computer_use",
+ "reason": "needs_settings",
+ "phase": "blocked",
+ "origin": "user",
+ "can_prompt": True,
+ "can_open_settings": True,
+ "detail": "Accessibility is off, so Jarvis cannot click or type for you yet.",
+ "source_layer": "platform.permissions",
+ }
+ values.update(overrides)
+ return PermissionNeeded(**values) # type: ignore[arg-type]
+
+
+# ----------------------------------------------------------------------
+# Vocabulary: Python tuples <-> TypeScript twin (AP-4)
+# ----------------------------------------------------------------------
+
+
[email protected]("key", list(_VOCABULARIES))
+def test_python_vocabulary_is_unique_snake_case(key: str) -> None:
+ values = _VOCABULARIES[key][0]
+ assert values, key
+ assert len(values) == len(set(values)), f"duplicate value in the {key} tuple"
+ assert all(re.fullmatch(r"[a-z]+(_[a-z]+)*", v) for v in values), key
+
+
[email protected]("key", list(_VOCABULARIES))
+def test_typescript_tuple_matches_python(key: str) -> None:
+ py_values, ts_name, _ = _VOCABULARIES[key]
+ ts_values = _ts_tuple(ts_name)
+ assert len(ts_values) == len(set(ts_values)), f"duplicate value in {ts_name}"
+ assert set(ts_values) == set(py_values), (
+ f"{ts_name} drift: extra={set(ts_values) - set(py_values)}, "
+ f"missing={set(py_values) - set(ts_values)}"
+ )
+
+
[email protected]("key", list(_VOCABULARIES))
+def test_typescript_union_is_derived_from_the_tuple(key: str) -> None:
+ _, ts_name, union_name = _VOCABULARIES[key]
+ assert f"export type {union_name} = (typeof {ts_name})[number];" in _ts_source()
+
+
+ ("event_cls", "interface"),
+ [
+ (PermissionNeeded, "PermissionNeededPayload"),
+ (PermissionResolved, "PermissionResolvedPayload"),
+ ],
+)
+def test_typescript_payload_interface_matches_the_event(
+ event_cls: type[Event], interface: str
+) -> None:
+ py_fields = _payload_fields(event_cls)
+ ts_fields = _ts_interface(interface)
+ assert set(ts_fields) == set(py_fields), (
+ f"{interface} drift: extra={set(ts_fields) - set(py_fields)}, "
+ f"missing={set(py_fields) - set(ts_fields)}"
+ )
+ for name, annotation in py_fields.items():
+ expected = _ENUMERATED_FIELDS.get(name) or _TS_TYPES.get(annotation)
+ assert expected is not None, (
+ f"no TS type mapped for {event_cls.__name__}.{name}: {annotation}"
+ )
+ assert ts_fields[name] == expected, (
+ f"{interface}.{name} is {ts_fields[name]!r}, expected {expected!r}"
+ )
+
+
+# ----------------------------------------------------------------------
+# Event shape: frozen, slotted, conventions of the neighbouring events
+# ----------------------------------------------------------------------
+
+
[email protected]("event_cls", [PermissionNeeded, PermissionResolved])
+def test_permission_events_follow_the_event_conventions(event_cls: type[Event]) -> None:
+ assert issubclass(event_cls, Event)
+ assert is_dataclass(event_cls)
+ event = event_cls()
+ # Base-class envelope fields come from Event's own default factories.
+ assert isinstance(event.trace_id, UUID)
+ assert event.timestamp_ns > 0
+ assert event.source_layer == ""
+ assert event_cls().trace_id != event.trace_id
+ # slots=True: no per-instance dict to grow state on.
+ assert not hasattr(event, "__dict__")
+ # An explicit trace id is carried as given.
+ trace = uuid4()
+ assert event_cls(trace_id=trace).trace_id == trace
+
+
+def test_permission_needed_defaults_are_the_inert_values() -> None:
+ event = PermissionNeeded()
+ assert event.permissions == ()
+ assert (event.feature, event.reason, event.phase, event.origin) == ("", "", "", "")
+ assert event.target == ""
+ assert (event.can_prompt, event.can_open_settings, event.outside_app) == (False, False, False)
+ assert event.detail == ""
+
+
+def test_permission_resolved_defaults_are_the_inert_values() -> None:
+ event = PermissionResolved()
+ assert event.permissions == ()
+ assert event.feature == ""
+ assert event.granted is False
+
+
+ ("event", "attribute", "value"),
+ [
+ (_needed(), "reason", "denied"),
+ (_needed(), "permissions", ()),
+ (_needed(), "can_prompt", False),
+ (PermissionResolved(feature="voice", granted=False), "granted", True),
+ ],
+)
+def test_permission_events_are_frozen(event: Event, attribute: str, value: object) -> None:
+ with pytest.raises(FrozenInstanceError):
+ setattr(event, attribute, value)
+
+
+def test_permissions_are_a_tuple_so_the_event_stays_immutable_and_hashable() -> None:
+ needed = _needed(permissions=("accessibility", "screen_recording"))
+ resolved = PermissionResolved(permissions=("microphone",), feature="voice", granted=True)
+ assert isinstance(needed.permissions, tuple)
+ assert isinstance(resolved.permissions, tuple)
+ # A list field would make the frozen event unhashable (and mutable in place).
+ assert isinstance(hash(needed), int)
+ assert isinstance(hash(resolved), int)
+
+
+def test_dictation_refused_keeps_its_shape() -> None:
+ """The microphone case publishes BOTH events; the old one is not reshaped."""
+ assert [f.name for f in fields(DictationRefused)] == [
+ "trace_id",
+ "timestamp_ns",
+ "source_layer",
+ "reason",
+ "detail",
+ ]
+ assert not issubclass(PermissionNeeded, DictationRefused)
+
+
+# ----------------------------------------------------------------------
+# Wire shape: the /ws forwarder
+# ----------------------------------------------------------------------
+
+
+def test_permission_needed_round_trips_through_the_ws_serialisation() -> None:
+ trace = uuid4()
+ event = _needed(
+ permissions=("accessibility", "screen_recording"),
+ trace_id=trace,
+ target="com.apple.Music",
+ outside_app=True,
+ )
+
+ envelope = event_to_ws_envelope(event)
+ # Starlette's WebSocket.send_json encodes exactly like this.
+ wire = json.loads(json.dumps(envelope, separators=(",", ":"), ensure_ascii=False))
+
+ assert wire["type"] == "event"
+ assert wire["event_name"] == "PermissionNeeded"
+ assert wire["trace_id"] == str(trace)
+ assert wire["source_layer"] == "platform.permissions"
+ assert isinstance(wire["timestamp_ns"], int)
+ # Envelope-level fields are lifted out of the payload, not repeated in it.
+ assert not _ENVELOPE_FIELDS & set(wire["payload"])
+ assert wire["payload"] == {
+ "permissions": ["accessibility", "screen_recording"],
+ "feature": "computer_use",
+ "reason": "needs_settings",
+ "phase": "blocked",
+ "origin": "user",
+ "target": "com.apple.Music",
+ "can_prompt": True,
+ "can_open_settings": True,
+ "outside_app": True,
+ "detail": "Accessibility is off, so Jarvis cannot click or type for you yet.",
+ }
+ # Tuples arrive as JSON arrays, and the order of the episode is kept.
+ assert isinstance(wire["payload"]["permissions"], list)
+
+
+def test_permission_resolved_round_trips_through_the_ws_serialisation() -> None:
+ event = PermissionResolved(permissions=("microphone",), feature="voice", granted=True)
+
+ wire = json.loads(json.dumps(event_to_ws_envelope(event), ensure_ascii=False))
+
+ assert wire["event_name"] == "PermissionResolved"
+ assert wire["payload"] == {"permissions": ["microphone"], "feature": "voice", "granted": True}
+
+
+def test_every_ws_payload_field_is_declared_by_the_typescript_twin() -> None:
+ """The envelope payload keys are exactly what the TS interface declares."""
+ for event, interface in (
+ (_needed(), "PermissionNeededPayload"),
+ (PermissionResolved(), "PermissionResolvedPayload"),
+ ):
+ payload = event_to_ws_envelope(event)["payload"]
+ assert set(payload) == set(_ts_interface(interface)), interface
+
+
+def test_permission_events_reach_a_ws_client_through_the_real_forwarder() -> None:
+ """Published on the bus, the events arrive as envelopes — no per-event wiring.
+
+ Uses the real ``WebServer`` ``/ws`` route and its wildcard forwarder, the
+ same way ``tests/integration/test_websocket_echo.py`` does.
+ """
+ from fastapi.testclient import TestClient
+
+ from jarvis.core.config import JarvisConfig
+ from jarvis.ui.web.server import WebServer
+
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ server = WebServer(cfg, bus=EventBus())
+
+ async def _publish() -> None:
+ await server.bus.publish(_needed(permissions=("microphone",), feature="voice"))
+ await server.bus.publish(
+ PermissionResolved(permissions=("microphone",), feature="voice", granted=True)
+ )
+
+ with TestClient(server.app) as client, client.websocket_connect("/ws") as ws:
+ assert ws.receive_json()["type"] == "welcome"
+
+ loop = asyncio.new_event_loop()
+ try:
+ loop.run_until_complete(_publish())
+ finally:
+ loop.close()
+
+ needed = ws.receive_json()
+ resolved = ws.receive_json()
+
+ assert needed["type"] == "event"
+ assert needed["event_name"] == "PermissionNeeded"
+ assert needed["payload"]["permissions"] == ["microphone"]
+ assert needed["payload"]["phase"] == "blocked"
+ assert resolved["event_name"] == "PermissionResolved"
+ assert resolved["payload"]["granted"] is True
+
+
+# ----------------------------------------------------------------------
+# Bus safety (AP-18)
+# ----------------------------------------------------------------------
+
+
+async def test_raising_resolved_subscriber_does_not_stop_later_subscribers() -> None:
+ from loguru import logger
+
+ bus = EventBus()
+ calls: list[str] = []
+
+ async def before(event: Event) -> None:
+ calls.append("before")
+
+ async def boom(event: Event) -> None:
+ calls.append("boom")
+ raise RuntimeError("subscriber blew up")
+
+ async def after(event: Event) -> None:
+ calls.append("after")
+
+ bus.subscribe(PermissionResolved, before)
+ bus.subscribe(PermissionResolved, boom)
+ bus.subscribe(PermissionResolved, after)
+
+ failures: list[str] = []
+ sink = logger.add(
+ lambda message: failures.append(message.record["extra"].get("event", "")),
+ level="WARNING",
+ )
+ try:
+ # The exception must never leave EventBus._safe_dispatch.
+ await bus.publish(PermissionResolved(permissions=("microphone",), feature="voice"))
+ finally:
+ logger.remove(sink)
+
+ assert sorted(calls) == ["after", "before", "boom"]
+ assert "PermissionResolved" in failures, "the failing subscriber was not logged"
+
+
+async def test_raising_wildcard_subscriber_does_not_stop_permission_delivery() -> None:
+ bus = EventBus()
+ seen: list[str] = []
+
+ async def boom(event: Event) -> None:
+ raise RuntimeError("observer blew up")
+
+ async def typed(event: PermissionNeeded) -> None:
+ seen.append(f"typed:{event.feature}")
+
+ async def observer(event: Event) -> None:
+ seen.append(f"observer:{type(event).__name__}")
+
+ bus.subscribe_all(boom)
+ bus.subscribe(PermissionNeeded, typed)
+ bus.subscribe_all(observer)
+
+ await bus.publish(_needed(feature="dictation"))
+ await bus.publish(_needed(feature="voice")) # the bus is still usable afterwards
+
+ assert sorted(seen) == [
+ "observer:PermissionNeeded",
+ "observer:PermissionNeeded",
+ "typed:dictation",
+ "typed:voice",
+ ]
+
+
+# ----------------------------------------------------------------------
+# Routine triggers: the permission events are excluded from the catalog
+# ----------------------------------------------------------------------
+
+
+def _core_event_names() -> set[str]:
+ return {
+ name
+ for name, obj in inspect.getmembers(events_mod, inspect.isclass)
+ if obj is not Event and issubclass(obj, Event)
+ }
+
+
+def test_the_catalog_exclusion_is_exactly_the_two_permission_events() -> None:
+ from jarvis.tasks.event_catalog import EXCLUDED_EVENT_NAMES
+
+ assert frozenset({"PermissionNeeded", "PermissionResolved"}) == EXCLUDED_EVENT_NAMES
+ # The exclusion names real events: a rename must not leave it inert.
+ assert EXCLUDED_EVENT_NAMES <= _core_event_names()
+
+
+def test_event_catalog_omits_the_permission_events_and_nothing_else() -> None:
+ from jarvis.tasks.event_catalog import EXCLUDED_EVENT_NAMES, event_catalog
+
+ catalog = event_catalog()
+
+ assert not EXCLUDED_EVENT_NAMES & set(catalog)
+ # Every other event of jarvis.core.events is still offered to routines.
+ assert _core_event_names() - EXCLUDED_EVENT_NAMES <= set(catalog)
+ assert "DictationRefused" in catalog
+
+
[email protected]("name", ["PermissionNeeded", "PermissionResolved"])
[email protected]("filter_expr", [None, "feature == 'voice'"])
+def test_routines_cannot_be_scheduled_on_the_permission_events(
+ name: str, filter_expr: str | None
+) -> None:
+ from jarvis.tasks.event_catalog import validate_event_schedule
+
+ schedule: dict[str, object] = {"event_name": name}
+ if filter_expr:
+ schedule["filter_expr"] = filter_expr
+ with pytest.raises(ValueError, match="cannot trigger a routine"):
+ validate_event_schedule(schedule)
+
+
+def test_a_neighbouring_event_stays_schedulable() -> None:
+ from jarvis.tasks.event_catalog import validate_event_schedule
+
+ validate_event_schedule({"event_name": "DictationRefused", "filter_expr": "reason == 'no_stt'"})
diff --git a/tests/unit/cu/conftest.py b/tests/unit/cu/conftest.py
index e40804f22b..6ab9decd37 100644
--- a/tests/unit/cu/conftest.py
+++ b/tests/unit/cu/conftest.py
@@ -1,13 +1,21 @@
"""Computer-Use unit-test fixtures.
-The capture path probes the LIVE macOS Screen-Recording TCC state before
-every grab (``_require_macos_screen_recording_permission``). These unit tests
+The capture path reads the LIVE macOS Screen-Recording TCC state: the perception
+entry asks for a missing grant (``_ensure_screen_recording_for_perception``),
+the helpers read it silently (``_helper_capture_blocked``), the engine's per-action
+gate raises without asking (``_require_macos_screen_recording_permission``) and a
+blank frame is sanity-checked (``_verify_perception_frame``). These unit tests
drive capture/engine logic through injected fake grabbers — the real TCC
state of the host must not decide their outcome (CI runners and dev shells
have no grant, so every capture-touching test would fail on real darwin
-hosts while passing everywhere else). The gate's own behavior is covered by
-``tests/unit/cu/test_capture_permission_gate``-style tests that patch the
-permission port explicitly.
+hosts while passing everywhere else). The permission behavior itself is covered
+by the ``real_tcc_gate`` tests, which run the real permission service on a
+``FakeTCC`` and so stay deterministic on every host.
+
+The engine's per-action guard (``engine._blocked_before_dispatch``: a deep Screen
+Recording read plus the system-consent window list) is neutralised by the
+``patched`` fixture of ``test_engine_loop.py``, not here: the tests of the guard
+call ``_dispatch_tool`` directly through a ``FakeTCC`` world and need it live.
"""
from __future__ import annotations
@@ -19,9 +27,9 @@ import pytest
def _screen_recording_gate_open(
request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch
) -> None:
- """Neutralize the live TCC probe; a no-op off darwin by design.
+ """Neutralize the live TCC reads; a no-op off darwin by design.
- Tests that exercise the gate itself opt back in with
+ Tests that exercise the permission behavior itself opt back in with
``@pytest.mark.real_tcc_gate`` (they fake the permission port and the
platform explicitly, so they stay deterministic on every host).
"""
@@ -32,6 +40,11 @@ def _screen_recording_gate_open(
monkeypatch.setattr(
capture, "_require_macos_screen_recording_permission", lambda: None
)
+ monkeypatch.setattr(
+ capture, "_ensure_screen_recording_for_perception", lambda: None
+ )
+ monkeypatch.setattr(capture, "_verify_perception_frame", lambda _raw: None)
+ monkeypatch.setattr(capture, "_helper_capture_blocked", lambda: False)
@pytest.fixture(autouse=True)
diff --git a/tests/unit/cu/indicator/test_controller_esc_honesty.py b/tests/unit/cu/indicator/test_controller_esc_honesty.py
new file mode 100644
index 0000000000..94a96e2d1b
--- /dev/null
+++ b/tests/unit/cu/indicator/test_controller_esc_honesty.py
@@ -0,0 +1,159 @@
+"""The "Esc to cancel" pill claims the key only when the key listener really runs.
+
+On macOS the global key listener is a listen-only event tap that exists only
+while Input Monitoring is granted; without it the tap is never created and a pill
+promising Esc would be a lie. These tests drive the REAL ``CUIndicatorController``
+with the REAL ``HotkeyTrigger`` over the REAL ``QuartzHotkeyBackend`` on top of
+``FakeTCC`` (fidelity labels of ``tests/fakes/fake_tcc.py`` apply; nothing here
+ran on a Mac), and with hand-written triggers for the three-way answer.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+import jarvis.trigger.hotkey as hotkey_mod
+from jarvis.core.bus import EventBus
+from jarvis.cu.indicator import controller as controller_mod
+from jarvis.cu.indicator.controller import _ESC_HINTS, CUIndicatorController
+from jarvis.platform import probes
+from jarvis.trigger.backends.quartz import QuartzHotkeyBackend
+from tests.fakes.fake_quartz_tap import FakeQuartz
+from tests.fakes.fake_tcc import TccService, install_port, make_darwin_port
+
+_PILL = _ESC_HINTS["en"]
+
+
+def _controller(monkeypatch: pytest.MonkeyPatch) -> tuple[CUIndicatorController, list[str]]:
+ """A controller whose border shows are recorded: the hint IS the observable."""
+ ctl = CUIndicatorController(EventBus())
+ hints: list[str] = []
+
+ async def record_show(*, hint: str, required: bool) -> bool:
+ hints.append(hint)
+ return True
+
+ monkeypatch.setattr(ctl, "_show_border", record_show)
+ monkeypatch.setattr(controller_mod, "_resolve_hint_language", lambda: "en")
+ monkeypatch.setattr(probes, "has_hotkey", lambda: True)
+ return ctl, hints
+
+
+class _StubTrigger:
+ """A hand-written ``HotkeyTrigger``: ``listening`` answers True / False / None."""
+
+ answer: bool | None = True
+
+ def __init__(self, _bindings: dict[str, list[str]]) -> None:
+ self.entered = False
+
+ async def __aenter__(self) -> _StubTrigger:
+ self.entered = True
+ return self
+
+ async def __aexit__(self, *_exc: object) -> None:
+ return None
+
+ def listening(self) -> bool | None:
+ return type(self).answer
+
+ async def events(self): # noqa: ANN201
+ await asyncio.Event().wait()
+ yield "" # pragma: no cover - never reached
+
+
+async def _activate(ctl: CUIndicatorController) -> None:
+ try:
+ await ctl._activate()
+ finally:
+ ctl._disarm_escape()
+ await asyncio.sleep(0)
+
+
+ ("answer", "shows_pill"),
+ [(True, True), (None, True), (False, False)],
+ ids=["listening", "backend-cannot-say-as-before", "not-listening"],
+)
+async def test_the_pill_follows_the_listener_answer(
+ monkeypatch: pytest.MonkeyPatch, answer: bool | None, shows_pill: bool
+) -> None:
+ ctl, hints = _controller(monkeypatch)
+ monkeypatch.setattr(hotkey_mod, "HotkeyTrigger", type("T", (_StubTrigger,), {"answer": answer}))
+ await _activate(ctl)
+ assert hints == [_PILL if shows_pill else ""]
+
+
+async def test_a_listener_that_never_reports_earns_no_pill(monkeypatch: pytest.MonkeyPatch) -> None:
+ ctl, hints = _controller(monkeypatch)
+ monkeypatch.setattr(controller_mod, "_ESC_READY_TIMEOUT_S", 0.05)
+
+ class _Hangs(_StubTrigger):
+ async def __aenter__(self) -> _Hangs:
+ await asyncio.Event().wait()
+ return self
+
+ monkeypatch.setattr(hotkey_mod, "HotkeyTrigger", _Hangs)
+ await _activate(ctl)
+ assert hints == [""]
+
+
+async def test_a_listener_that_fails_to_start_earns_no_pill(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctl, hints = _controller(monkeypatch)
+
+ class _Fails(_StubTrigger):
+ async def __aenter__(self) -> _Fails:
+ raise RuntimeError("backend exploded")
+
+ monkeypatch.setattr(hotkey_mod, "HotkeyTrigger", _Fails)
+ await _activate(ctl)
+ assert hints == [""]
+
+
+async def test_a_mac_without_input_monitoring_shows_no_pill_and_forces_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ port, tcc = make_darwin_port()
+ install_port(monkeypatch, port)
+ fake = FakeQuartz(tcc).install(monkeypatch)
+ ctl, hints = _controller(monkeypatch)
+ monkeypatch.setattr(hotkey_mod, "make_hotkey_backend", lambda: QuartzHotkeyBackend())
+
+ await _activate(ctl)
+
+ assert hints == [""], "the pill must not promise a key that cannot work"
+ assert fake.tap.attempts == [], "no tap was created to provoke a prompt"
+ assert tcc.requests() == [] and tcc.implicit_prompts() == [] and tcc.dialogs_shown() == []
+
+
+async def test_a_mac_with_input_monitoring_shows_the_pill(monkeypatch: pytest.MonkeyPatch) -> None:
+ port, tcc = make_darwin_port()
+ install_port(monkeypatch, port)
+ tcc.grant(TccService.INPUT_MONITORING)
+ fake = FakeQuartz(tcc).install(monkeypatch)
+ ctl, hints = _controller(monkeypatch)
+ monkeypatch.setattr(hotkey_mod, "make_hotkey_backend", lambda: QuartzHotkeyBackend())
+
+ await _activate(ctl)
+
+ assert hints == [_PILL]
+ assert fake.tap.attempts == ["live"]
+ assert tcc.requests() == []
+
+
+async def test_a_second_mission_reuses_the_answer_of_the_running_listener(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctl, hints = _controller(monkeypatch)
+ monkeypatch.setattr(hotkey_mod, "HotkeyTrigger", type("T", (_StubTrigger,), {"answer": False}))
+ try:
+ await ctl._activate()
+ await ctl._activate()
+ assert hints == ["", ""]
+ finally:
+ ctl._disarm_escape()
+ await asyncio.sleep(0)
diff --git a/tests/unit/cu/test_actuate.py b/tests/unit/cu/test_actuate.py
index 811c571736..e66c9edb6e 100644
--- a/tests/unit/cu/test_actuate.py
+++ b/tests/unit/cu/test_actuate.py
@@ -492,57 +492,143 @@ def test_get_actuator_on_this_host():
assert actuator.name.startswith("posix-")
-def test_macos_input_permissions_fail_closed_before_backend_init(monkeypatch):
- from jarvis.platform.permissions import PermissionId, PermissionState
+class _Clock:
+ """A monotonic clock a test advances (the service's cooldown and grant cache)."""
- probes: list[PermissionId] = []
+ def __init__(self) -> None:
+ self.now = 1000.0
- class _PermissionPort:
- def state(self, permission_id):
- return {
- PermissionId.ACCESSIBILITY: PermissionState.GRANTED,
- PermissionId.EVENT_POSTING: PermissionState.NOT_GRANTED,
- }[permission_id]
+ def __call__(self) -> float:
+ return self.now
- def runtime_access_granted(self, permission_id):
- probes.append(permission_id)
- return permission_id is PermissionId.ACCESSIBILITY
- monkeypatch.setattr(base_mod.sys, "platform", "darwin")
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: _PermissionPort(),
- )
+def macos_ax(monkeypatch):
+ """The REAL permission service on a REAL port that sits on FakeTCC.
+
+ Builds a darwin world per call. ``sys.platform`` is switched to ``darwin``
+ because the actuator only consults the permission layer on macOS; nothing
+ here ran on a real Mac, FakeTCC models the OS.
+ """
+ from jarvis.platform import permission_service as service_module
+ from jarvis.platform.permission_service import PermissionService
+ from tests.fakes.fake_tcc import FakeTCC, install_port
+
+ created: list[PermissionService] = []
+
+ def build(platform: str = "darwin", **tcc_kwargs):
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port(platform))
+ clock = _Clock()
+ service = PermissionService(clock=clock, watch_interval_s=3600.0)
+ monkeypatch.setattr(service_module, "_SERVICE", service)
+ created.append(service)
+ if platform == "darwin":
+ monkeypatch.setattr(base_mod.sys, "platform", "darwin")
+ return types.SimpleNamespace(tcc=tcc, service=service, clock=clock)
+
+ yield build
+ for service in created:
+ service._shutdown()
+
- with pytest.raises(ActuationUnavailable, match="Input Control"):
+def test_macos_first_input_asks_once_and_refuses_with_the_agent_prefix(macos_ax):
+ from tests.fakes.fake_tcc import DialogPolicy
+
+ world = macos_ax(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ with pytest.raises(base_mod.PermissionNeededError) as first:
base_mod.get_actuator()
- assert probes == [PermissionId.ACCESSIBILITY, PermissionId.EVENT_POSTING]
+ # The text for an LLM tool error: the prefix the engine maps, prohibitive.
+ assert str(first.value).startswith("[permission_needed:accessibility] ")
+ assert "must not retry" in str(first.value)
+ assert isinstance(first.value, ActuationUnavailable) # flat tools keep their handler
+ assert first.value.result.granted is False
+ assert len(world.tcc.requests("accessibility")) == 1
+ assert world.tcc.implicit_prompts() == []
+
+ # A second action inside the cooldown asks nothing more (the dialog is open).
+ world.clock.now += 5
+ with pytest.raises(base_mod.PermissionNeededError):
+ base_mod.get_actuator()
+ assert len(world.tcc.requests("accessibility")) == 1
+
+
+def test_macos_input_never_proceeds_on_a_denied_accessibility_grant(macos_ax):
+ from tests.fakes.fake_tcc import DialogPolicy
+
+ world = macos_ax(default_policy=DialogPolicy.DENY)
+
+ with pytest.raises(base_mod.PermissionNeededError):
+ base_mod.get_actuator()
+ world.clock.now += 5
+ with pytest.raises(base_mod.PermissionNeededError):
+ base_mod.get_actuator()
+ # A decision is on file: macOS is not asked again and nothing acts.
+ assert len(world.tcc.requests("accessibility")) == 1
+ assert world.tcc.ignored_requests("accessibility") == []
-def test_macos_input_permissions_are_rechecked_after_revocation(monkeypatch):
- from jarvis.platform.permissions import PermissionState
- states = [True, True, False, True]
+def test_macos_input_with_the_grant_present_asks_nothing(macos_ax):
+ world = macos_ax(granted=("accessibility",))
- class _PermissionPort:
- def runtime_access_granted(self, _permission_id):
- return states.pop(0)
+ base_mod._ensure_macos_input_permission("computer_use")
- def state(self, _permission_id):
- return PermissionState.NOT_GRANTED
+ assert world.tcc.requests() == []
+ assert world.tcc.implicit_prompts() == []
+
+def test_macos_input_is_rechecked_after_revocation(macos_ax):
+ from tests.fakes.fake_tcc import DialogPolicy
+
+ world = macos_ax(granted=("accessibility",), default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ base_mod._ensure_macos_input_permission("computer_use")
+ world.tcc.deny("accessibility")
+ world.clock.now += 5 # the service caches a grant for about a second
+ with pytest.raises(base_mod.PermissionNeededError, match="permission_needed"):
+ base_mod._ensure_macos_input_permission("computer_use")
+
+
+def test_macos_input_names_the_feature_that_wanted_it(monkeypatch):
+ from tests.fakes.fake_permission_service import FakePermissionService
+
+ gate = FakePermissionService(default="needs_settings")
+ monkeypatch.setattr(base_mod, "_permission_gate", lambda: gate)
monkeypatch.setattr(base_mod.sys, "platform", "darwin")
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: _PermissionPort(),
- )
- base_mod._require_macos_input_permissions()
- with pytest.raises(ActuationUnavailable, match="Accessibility"):
- base_mod._require_macos_input_permissions()
+ with pytest.raises(base_mod.PermissionNeededError):
+ base_mod.get_actuator()
+
+ (call,) = gate.ensure_calls()
+ assert call.permission.value == "accessibility" # event_posting is an alias: one ask
+ assert call.feature == "computer_use"
+ assert call.interactive is True
+ assert call.wait_s == 0.0 # a tool body never blocks on a person
+
+
+def test_an_empty_gate_answer_is_not_a_grant(monkeypatch):
+ class _Gate:
+ def ensure_all(self, permissions, **_kwargs):
+ return []
+
+ monkeypatch.setattr(base_mod, "_permission_gate", lambda: _Gate())
+ monkeypatch.setattr(base_mod.sys, "platform", "darwin")
+
+ with pytest.raises(base_mod.PermissionNeededError) as refusal:
+ base_mod._ensure_macos_input_permission("computer_use")
+ assert str(refusal.value).startswith("[permission_needed:accessibility] ")
+
+
[email protected]("platform", ["linux", "win32"])
+def test_off_macos_the_actuator_never_touches_the_permission_layer(macos_ax, platform):
+ world = macos_ax(platform=platform)
+
+ base_mod._ensure_macos_input_permission("computer_use")
- assert states == []
+ world.tcc.assert_silent()
def test_pynput_key_table_maps_core_vocabulary():
diff --git a/tests/unit/cu/test_capture.py b/tests/unit/cu/test_capture.py
index 83448fde04..ac4ce54720 100644
--- a/tests/unit/cu/test_capture.py
+++ b/tests/unit/cu/test_capture.py
@@ -290,99 +290,8 @@ def test_visual_probe_local_ignores_bgrx_padding(monkeypatch):
assert regions_equal(first.local, second.local) is True
-def test_macos_screen_recording_denial_stops_before_grab(monkeypatch):
- from jarvis.platform.permissions import PermissionState
-
- calls = {"grab": 0, "probe": 0}
-
- class _DeniedPort:
- def runtime_access_granted(self, _permission_id):
- calls["probe"] += 1
- return False
-
- def state(self, _permission_id):
- return PermissionState.NOT_GRANTED
-
- monkeypatch.setattr("jarvis.platform.detect_platform", lambda: "darwin")
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: _DeniedPort(),
- )
-
- def grab(_bbox):
- calls["grab"] += 1
- return _solid((192, 108), (10, 20, 30))
-
- with pytest.raises(RuntimeError, match="Screen Recording"):
- capture_stable_frame(_monitor(), grab=grab, sleep=lambda _s: None)
-
- assert calls == {"grab": 0, "probe": 1}
-
-
-def test_macos_screen_recording_revoked_fails_before_any_grab(monkeypatch):
- from jarvis.platform.permissions import PermissionState
-
- calls = {"grab": 0, "probe": 0}
-
- class _RevokedPort:
- def runtime_access_granted(self, _permission_id):
- calls["probe"] += 1
- return False
-
- def state(self, _permission_id):
- return PermissionState.NOT_GRANTED
-
- monkeypatch.setattr("jarvis.platform.detect_platform", lambda: "darwin")
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: _RevokedPort(),
- )
-
- def grab(_bbox):
- calls["grab"] += 1
- return _solid((192, 108), (10, 20, 30))
-
- with pytest.raises(RuntimeError, match="Screen Recording"):
- capture_stable_frame(_monitor(), grab=grab, sleep=lambda _s: None)
-
- assert calls["grab"] == 0
- assert calls["probe"] == 1
-
-
-def test_macos_screen_recording_is_probed_once_per_frame(monkeypatch):
- # The stability loop can re-grab many times inside one frame; the
- # permission probe must run once per FRAME, not per re-grab — the engine
- # re-probes before every dispatched action, which is the revocation gate.
- from jarvis.platform.permissions import PermissionState
-
- calls = {"grab": 0, "probe": 0}
-
- class _GrantedPort:
- def runtime_access_granted(self, _permission_id):
- calls["probe"] += 1
- return True
-
- def state(self, _permission_id):
- return PermissionState.GRANTED
-
- monkeypatch.setattr("jarvis.platform.detect_platform", lambda: "darwin")
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: _GrantedPort(),
- )
-
- def grab(_bbox):
- calls["grab"] += 1
- return _solid((192, 108), (10, 20, 30))
-
- frame = capture_stable_frame(_monitor(), grab=grab, sleep=lambda _s: None)
-
- assert frame.stable is True
- assert calls["grab"] == 2
- assert calls["probe"] == 1
+# The macOS Screen Recording behaviour of capture (ask once on a gesture, never from
+# a helper, honest refusal, wallpaper check) lives in test_capture_permissions.py.
def test_capture_guard_rechecks_window_identity_around_each_grab():
diff --git a/tests/unit/cu/test_capture_permissions.py b/tests/unit/cu/test_capture_permissions.py
new file mode 100644
index 0000000000..7cb1b98064
--- /dev/null
+++ b/tests/unit/cu/test_capture_permissions.py
@@ -0,0 +1,512 @@
+"""Screen Recording behaviour of Computer-Use capture (just-in-time permissions).
+
+Every test runs the REAL permission service on a REAL ``SystemPermissionPort`` that
+sits on ``FakeTCC`` (a stateful model of macOS privacy), with ``FakeScreenGrab``
+producing the pixels. Nothing here ran on a real Mac: the call log of the fake is
+the proof of what was (not) asked, and each simulated macOS behaviour is labelled
+documented or unverified in ``tests/fakes/fake_tcc.py``.
+
+The rules under test: the perception entry (``capture_stable_frame``) may ASK, once;
+a helper (``grab_region``, ``grab_visual_probe``) never asks and degrades; a denial
+is a stable state (no second request); a frame that is wallpaper-only while the state
+claims GRANTED is never a success; off macOS nothing is read or requested.
+"""
+
+from __future__ import annotations
+
+import contextlib
+
+import pytest
+
+pytest.importorskip("PIL", reason="pillow required for capture tests")
+
+import jarvis.cu.capture as capture_mod
+from jarvis.cu.capture import (
+ capture_stable_frame,
+ grab_region,
+ grab_visual_probe,
+ grabber_for,
+)
+from jarvis.cu.geometry import MonitorInfo
+from jarvis.platform import screen_access, window_capture
+from jarvis.platform.permission_service import PermissionService, get_permission_service
+from jarvis.platform.permissions import PermissionId, PermissionState
+from jarvis.platform.screen_access import ScreenCaptureRefused
+from tests.fakes.fake_permission_service import FakePermissionService
+from tests.fakes.fake_screen_pixels import (
+ pixels_grabber,
+ textured_pixels,
+ wallpaper_pixels,
+)
+from tests.fakes.fake_tcc import (
+ DialogPolicy,
+ FakeScreenGrab,
+ FakeTCC,
+ TccService,
+ install_port,
+ make_non_darwin_port,
+)
+
+pytestmark = pytest.mark.real_tcc_gate
+
+_SR = PermissionId.SCREEN_RECORDING
+_SIZE = (192, 108)
+
+
+def _monitor(**kw) -> MonitorInfo:
+ defaults = dict(left=0, top=0, width=_SIZE[0], height=_SIZE[1])
+ defaults.update(kw)
+ return MonitorInfo(**defaults)
+
+
+def _darwin(monkeypatch, **tcc_kwargs) -> FakeTCC:
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
+
+
+def _capture(grab, **kw):
+ return capture_stable_frame(_monitor(), grab=grab, sleep=lambda _s: None, **kw)
+
+
[email protected](autouse=True)
+def _fresh_evidence_cache():
+ screen_access.reset_window_evidence_cache()
+ yield
+ screen_access.reset_window_evidence_cache()
+
+
+# ---------------------------------------------------------------------------
+# The perception entry asks (once); a decision is a stable state
+# ---------------------------------------------------------------------------
+
+
+def test_first_frame_asks_once_and_the_answer_is_not_a_grant(monkeypatch):
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ screen = FakeScreenGrab(tcc)
+
+ with pytest.raises(ScreenCaptureRefused) as first:
+ _capture(pixels_grabber(screen))
+ with pytest.raises(ScreenCaptureRefused):
+ _capture(pixels_grabber(screen))
+
+ # Exactly one native request across two attempts, and the capture itself never
+ # touched the screen (no implicit prompt, no frame): the dialog is still open.
+ assert len(tcc.requests(TccService.SCREEN_RECORDING)) == 1
+ assert tcc.implicit_prompts() == []
+ assert screen.frames == []
+ assert str(first.value).startswith("[permission_needed:screen_recording] ")
+ assert first.value.agent_detail == str(first.value)
+ assert first.value.user_detail
+ assert first.value.permission == "screen_recording"
+
+
+def test_the_frame_after_the_ask_proceeds_once_the_user_allowed(monkeypatch):
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.ALLOW)
+ screen = FakeScreenGrab(tcc)
+
+ # The preflight is frozen per process (BUG-161), so the very first frame may still
+ # be refused while the grant is only visible to the window-title oracle; the next
+ # one must go through, with no second request.
+ with contextlib.suppress(ScreenCaptureRefused):
+ _capture(pixels_grabber(screen))
+ frame = _capture(pixels_grabber(screen))
+
+ assert frame.stable is True
+ assert len(tcc.requests(TccService.SCREEN_RECORDING)) == 1
+ assert tcc.implicit_prompts() == []
+ assert screen.frames and not any(item.wallpaper_only for item in screen.frames)
+ # The request's return value is never the evidence: the grant was READ back.
+ assert get_permission_service().check_deep(_SR) is PermissionState.GRANTED
+
+
+def test_denied_is_a_stable_state_with_no_second_request(monkeypatch):
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.DENY)
+ screen = FakeScreenGrab(tcc)
+
+ with pytest.raises(ScreenCaptureRefused):
+ _capture(pixels_grabber(screen))
+ with pytest.raises(ScreenCaptureRefused) as second:
+ _capture(pixels_grabber(screen))
+
+ assert len(tcc.requests(TccService.SCREEN_RECORDING)) == 1
+ assert tcc.ignored_requests() == []
+ assert screen.frames == []
+ # Screen Recording has no tri-state: a decline reads "off", and the refusal
+ # says where to turn it on.
+ assert second.value.reason == "needs_settings"
+ assert "turn Personal Jarvis on" in second.value.user_detail
+
+
+def test_a_grant_given_mid_session_is_seen_without_a_restart(monkeypatch):
+ # The preflight is frozen per process (BUG-161): the window-title oracle is what
+ # sees the grant the user just gave in System Settings.
+ tcc = _darwin(monkeypatch)
+ screen = FakeScreenGrab(tcc)
+ tcc.deny(TccService.SCREEN_RECORDING)
+ tcc.grant(TccService.SCREEN_RECORDING)
+
+ frame = _capture(pixels_grabber(screen))
+
+ assert frame.stable is True
+ assert tcc.requests() == []
+
+
+def test_a_granted_frame_never_asks_and_reads_the_state_once_per_frame(monkeypatch):
+ gate = FakePermissionService()
+ monkeypatch.setattr(screen_access, "permission_gate", lambda: gate)
+ grabs = {"n": 0}
+
+ def grab(_bbox):
+ grabs["n"] += 1
+ return textured_pixels(_SIZE)
+
+ frame = _capture(grab)
+
+ assert frame.stable is True
+ assert grabs["n"] == 2 # the stability loop re-grabbed
+ assert gate.ensure_calls() == []
+ # One read for the entry and one after the final grab (the revoke check of the
+ # pixel sanity check). Not one per stability re-grab.
+ assert len(gate.check_calls(_SR)) == 2
+
+
+# ---------------------------------------------------------------------------
+# Helpers never ask
+# ---------------------------------------------------------------------------
+
+
+def test_region_helper_degrades_silently_when_not_determined(monkeypatch):
+ tcc = _darwin(monkeypatch)
+ calls = {"grab": 0}
+
+ def grab(_bbox):
+ calls["grab"] += 1
+ return textured_pixels((4, 4))
+
+ got = grab_region({"left": 0, "top": 0, "width": 4, "height": 4}, grab=grab)
+
+ assert got is None
+ assert calls["grab"] == 0
+ tcc.assert_no_prompts()
+
+
+def test_visual_probe_helper_degrades_silently_when_not_determined(monkeypatch):
+ tcc = _darwin(monkeypatch)
+
+ got = grab_visual_probe({"left": 0, "top": 0, "width": 8, "height": 8}, point=(2, 2))
+
+ assert got is None
+ tcc.assert_no_prompts()
+
+
+def test_helpers_do_not_ask_after_a_denial_either(monkeypatch):
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.DENY)
+ with pytest.raises(ScreenCaptureRefused):
+ _capture(pixels_grabber(FakeScreenGrab(tcc)))
+ before = len(tcc.requests())
+
+ assert grab_region({"left": 0, "top": 0, "width": 4, "height": 4}) is None
+ assert grab_visual_probe({"left": 0, "top": 0, "width": 8, "height": 8}) is None
+
+ assert len(tcc.requests()) == before
+
+
+def test_region_helper_grabs_when_the_grant_is_live(monkeypatch):
+ _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING])
+ region = textured_pixels((4, 4))
+
+ got = grab_region({"left": 0, "top": 0, "width": 4, "height": 4}, grab=lambda _b: region)
+
+ assert got == region
+
+
+def test_the_engine_gate_is_silent_and_sees_a_mid_session_grant(monkeypatch):
+ tcc = _darwin(monkeypatch)
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ capture_mod._require_macos_screen_recording_permission()
+ assert str(refused.value).startswith("[permission_needed:screen_recording] ")
+ tcc.assert_no_prompts()
+
+ tcc.grant(TccService.SCREEN_RECORDING)
+ capture_mod._require_macos_screen_recording_permission() # no raise
+ tcc.assert_no_prompts()
+
+
+# ---------------------------------------------------------------------------
+# Wallpaper-only frames are never a success
+# ---------------------------------------------------------------------------
+
+
+def test_wallpaper_frame_after_a_revoke_opens_an_episode_and_is_no_success(monkeypatch):
+ # The state read says GRANTED (cached), then the user revokes in System Settings
+ # while the grab runs: macOS hands back the wallpaper and no error.
+ tcc = _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING], preflight_frozen=())
+ screen = FakeScreenGrab(tcc)
+ assert get_permission_service().check(_SR) is PermissionState.GRANTED
+ grabs = {"n": 0}
+
+ def grab(bbox):
+ grabs["n"] += 1
+ if grabs["n"] == 1:
+ tcc.deny(TccService.SCREEN_RECORDING)
+ return pixels_grabber(screen)(bbox)
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ _capture(grab)
+
+ assert refused.value.reason == "needs_settings"
+ assert screen.frames and all(item.wallpaper_only for item in screen.frames)
+ episodes = get_permission_service().outstanding()
+ assert [(e.permissions, e.feature, e.origin) for e in episodes] == [
+ (("screen_recording",), "computer_use", "user")
+ ]
+ # macOS does not re-ask after a decision: no dialog was shown for the revoked grant.
+ assert tcc.dialogs_shown() == []
+
+
+def test_a_revoke_that_lands_after_the_cached_grant_expired_is_no_success(monkeypatch):
+ # The grab itself takes longer than the 1 s granted cache (the stability loop
+ # runs up to 1.2 s, a native capture timeout 3 s): the user revokes meanwhile.
+ tcc = _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING], preflight_frozen=())
+ clock = {"now": 0.0}
+ service = PermissionService(clock=lambda: clock["now"])
+ monkeypatch.setattr(screen_access, "permission_gate", lambda: service)
+ screen = FakeScreenGrab(tcc)
+ grabs = {"n": 0}
+
+ def grab(bbox):
+ grabs["n"] += 1
+ if grabs["n"] == 1:
+ tcc.deny(TccService.SCREEN_RECORDING)
+ clock["now"] += 1.5 # the cached GRANTED is long expired
+ return pixels_grabber(screen)(bbox)
+
+ try:
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ _capture(grab)
+ assert refused.value.agent_detail.startswith("[permission_needed:screen_recording] ")
+ assert screen.frames and all(item.wallpaper_only for item in screen.frames)
+ assert [e.feature for e in service.outstanding()] == ["computer_use"]
+ finally:
+ service._shutdown()
+
+
[email protected]("photo", [False, True], ids=["flat", "photographic"])
+def test_wallpaper_with_an_unusable_grant_refuses_and_names_the_permission(monkeypatch, photo):
+ # State GRANTED everywhere, yet the capture is the wallpaper and other apps'
+ # windows are on screen without a readable title: the grant is not usable. The
+ # macOS default wallpaper is a photograph, so a flat-colour check alone misses it.
+ tcc = _darwin(monkeypatch, preflight_frozen=(), screen_grant_needs_relaunch=True)
+ tcc.grant(TccService.SCREEN_RECORDING)
+ screen = FakeScreenGrab(tcc)
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (2, 0))
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ _capture(pixels_grabber(screen, photo_wallpaper=photo))
+
+ assert refused.value.agent_detail.startswith("[permission_needed:screen_recording] ")
+ assert all(item.wallpaper_only for item in screen.frames)
+
+
+def test_an_unusable_grant_opens_one_restart_hint_episode_and_a_real_frame_ends_it(monkeypatch):
+ # A REAL failed attempt while the state reads granted: the honest advice is "quit
+ # and reopen", offered through a user-origin episode. Nothing restarts, nothing is
+ # asked, and the capture itself is still refused.
+ tcc = _darwin(monkeypatch, preflight_frozen=(), screen_grant_needs_relaunch=True)
+ tcc.grant(TccService.SCREEN_RECORDING)
+ screen = FakeScreenGrab(tcc)
+ evidence = {"value": (2, 0)}
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: evidence["value"])
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ _capture(pixels_grabber(screen))
+ with pytest.raises(ScreenCaptureRefused):
+ _capture(pixels_grabber(screen)) # the same failure again: still one episode
+
+ assert refused.value.reason == "restart_hint"
+ assert "quit and reopened" in refused.value.user_detail
+ assert refused.value.agent_detail.startswith("[permission_needed:screen_recording] ")
+ (episode,) = get_permission_service().outstanding()
+ assert (episode.permissions, episode.feature, episode.reason, episode.origin) == (
+ ("screen_recording",),
+ "computer_use",
+ "restart_hint",
+ "user",
+ )
+ assert tcc.requests() == [] and tcc.dialogs_shown() == [] # a hint never asks
+
+ # The grant works now (the user restarted, or the entry caught up): a frame that
+ # shows readable titles of other apps' windows ends the episode, no more nagging.
+ evidence["value"] = (3, 2)
+ _capture(lambda _b: textured_pixels(_SIZE))
+ get_permission_service().refresh_episodes()
+ assert get_permission_service().outstanding() == []
+
+
+def test_a_background_capture_with_an_unusable_grant_opens_no_user_card(monkeypatch):
+ tcc = _darwin(monkeypatch, preflight_frozen=(), screen_grant_needs_relaunch=True)
+ tcc.grant(TccService.SCREEN_RECORDING)
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (2, 0))
+ size, pixels = wallpaper_pixels(_SIZE)
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ screen_access.verify_frame_is_real(
+ size, pixels, feature="screen_context", interactive=False
+ )
+
+ assert refused.value.reason == "needs_settings"
+ assert get_permission_service().outstanding() == []
+ assert tcc.requests() == []
+
+
+def test_the_window_list_is_not_read_again_for_every_frame(monkeypatch):
+ _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING], preflight_frozen=())
+ reads: list[int] = []
+
+ def evidence():
+ reads.append(1)
+ return (3, 2)
+
+ monkeypatch.setattr(screen_access, "_window_evidence", evidence)
+
+ for _ in range(3):
+ _capture(lambda _b: textured_pixels(_SIZE))
+
+ assert len(reads) == 1
+
+
+ "evidence", [(3, 1), (0, 0), None], ids=["titles", "no_windows", "unknown"]
+)
+def test_a_genuinely_blank_screen_is_accepted_while_the_grant_works(monkeypatch, evidence):
+ tcc = _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING], preflight_frozen=())
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: evidence)
+
+ frame = _capture(lambda _b: wallpaper_pixels(_SIZE))
+
+ assert frame.stable is True
+ tcc.assert_no_prompts()
+
+
+def test_pixel_check_samples_bgrx_frames_like_rgb(monkeypatch):
+ # mss hands out BGRX (4 bytes per pixel); a textured frame must not read as blank.
+ assert screen_access.frame_is_blank(_SIZE, b"\x10\x20\x30\x00" * (192 * 108), bytes_per_pixel=4)
+ rgb = textured_pixels(_SIZE)[1]
+ bgrx = bytearray()
+ for i in range(0, len(rgb), 3):
+ bgrx += bytes((rgb[i + 2], rgb[i + 1], rgb[i], 0))
+ assert not screen_access.frame_is_blank(_SIZE, bgrx, bytes_per_pixel=4)
+
+
+# ---------------------------------------------------------------------------
+# A native window capture that times out while macOS may be asking
+# ---------------------------------------------------------------------------
+
+
+def _window_target() -> MonitorInfo:
+ return _monitor(name="window:x", window_handle=9)
+
+
+def _pending_native(monkeypatch):
+ def native(_handle, _bbox):
+ window_capture._failure.reason = "pending_confirmation"
+ return None
+
+ monkeypatch.setattr(window_capture, "grab_window", native)
+
+
+def test_pending_native_capture_is_not_a_denial_while_the_grant_is_live(monkeypatch):
+ _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING])
+ _pending_native(monkeypatch)
+ fallback = textured_pixels((80, 60))
+ monkeypatch.setattr(capture_mod, "mss_grab", lambda _bbox: fallback)
+ bbox = {"left": 0, "top": 0, "width": 80, "height": 60}
+
+ assert grabber_for(_window_target())(bbox) == fallback
+
+
+def test_pending_native_capture_while_a_request_is_open_says_macos_may_be_asking(monkeypatch):
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ get_permission_service().ensure(_SR, feature="computer_use", wait_s=0)
+ assert tcc.dialog_open(TccService.SCREEN_RECORDING)
+ _pending_native(monkeypatch)
+ monkeypatch.setattr(
+ capture_mod,
+ "mss_grab",
+ lambda _bbox: (_ for _ in ()).throw(AssertionError("no wallpaper grab while pending")),
+ )
+ bbox = {"left": 0, "top": 0, "width": 80, "height": 60}
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ grabber_for(_window_target())(bbox)
+
+ assert refused.value.reason == "pending"
+ # The Screen Recording dialog has no Allow button: the text sends the user to
+ # System Settings and never tells them to "choose Allow".
+ assert "macOS may be showing a dialog" in refused.value.user_detail
+ assert "turn Personal Jarvis on" in refused.value.user_detail
+ assert "Allow" not in refused.value.user_detail
+ assert len(tcc.requests()) == 1 # nothing new was asked
+
+
+def _native_fails_with(monkeypatch, reason):
+ def native(_handle, _bbox):
+ window_capture._failure.reason = reason
+ return None
+
+ monkeypatch.setattr(window_capture, "grab_window", native)
+
+
+def test_a_plain_timeout_the_state_does_not_explain_refuses_instead_of_grabbing_wallpaper(
+ monkeypatch,
+):
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.DENY)
+ get_permission_service().ensure(_SR, feature="computer_use", wait_s=0)
+ _native_fails_with(monkeypatch, "timeout")
+ monkeypatch.setattr(
+ capture_mod,
+ "mss_grab",
+ lambda _bbox: (_ for _ in ()).throw(AssertionError("no wallpaper grab after a denial")),
+ )
+ before = len(tcc.requests())
+ bbox = {"left": 0, "top": 0, "width": 80, "height": 60}
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ grabber_for(_window_target())(bbox)
+
+ assert refused.value.reason == "needs_settings"
+ assert len(tcc.requests()) == before
+
+
+def test_a_timeout_with_a_live_grant_is_logged_and_carries_on(monkeypatch, caplog):
+ _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING])
+ _native_fails_with(monkeypatch, "pending_confirmation")
+ fallback = textured_pixels((80, 60))
+ monkeypatch.setattr(capture_mod, "mss_grab", lambda _bbox: fallback)
+ bbox = {"left": 0, "top": 0, "width": 80, "height": 60}
+
+ with caplog.at_level("WARNING", logger=capture_mod.logger.name):
+ assert grabber_for(_window_target())(bbox) == fallback
+
+ assert any("macOS may be waiting for a confirmation" in r.getMessage() for r in caplog.records)
+
+
+# ---------------------------------------------------------------------------
+# Off macOS nothing changes
+# ---------------------------------------------------------------------------
+
+
+def test_non_darwin_capture_reads_and_requests_nothing(monkeypatch):
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ # A flat frame is fine here: the wallpaper check is a macOS-only trap.
+ frame = _capture(lambda _b: wallpaper_pixels(_SIZE))
+
+ assert frame.stable is True
+ region = wallpaper_pixels((4, 4))
+ assert grab_region({"left": 0, "top": 0, "width": 4, "height": 4}, grab=lambda _b: region)
+ capture_mod._require_macos_screen_recording_permission()
+ tcc.assert_silent()
+ assert get_permission_service().outstanding() == []
diff --git a/tests/unit/cu/test_engine_loop.py b/tests/unit/cu/test_engine_loop.py
index fc7a49d6d0..f99f5c9616 100644
--- a/tests/unit/cu/test_engine_loop.py
+++ b/tests/unit/cu/test_engine_loop.py
@@ -175,6 +175,10 @@ def patched(monkeypatch, tmp_path):
fake_verify_click_focus_point,
)
monkeypatch.setattr(engine_mod, "_foreground_title", lambda: "Test Window")
+ # The per-action permission guard reads the LIVE TCC state and the window list: on
+ # a macOS dev machine without a grant it would refuse every dispatched action.
+ # The guard's own tests drive ``_dispatch_tool`` through a FakeTCC world instead.
+ monkeypatch.setattr(engine_mod, "_blocked_before_dispatch", lambda: None)
# The engine normalizes the target window via jarvis.platform.window_state;
# tests must never maximize a real window on the dev machine.
from jarvis.platform import window_state as ws
@@ -358,17 +362,25 @@ async def test_recent_missions_reach_the_decide_prompt_but_not_the_judge(patched
cu_run_registry.clear_runs()
-async def test_dispatch_refuses_action_after_screen_permission_revocation(
- monkeypatch,
-):
+def _darwin_world(monkeypatch, **tcc_kwargs):
+ """A darwin FakeTCC behind the REAL port; the process-wide service reads it.
+
+ The engine itself never asks macOS: an unanswered dialog makes any unexpected
+ prompt visible as a ``request`` in the call log. Nothing here ran on a real
+ Mac; FakeTCC models the OS.
+ """
+ from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, install_port
+
+ tcc_kwargs.setdefault("default_policy", DialogPolicy.NEVER_ANSWERED)
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
+
+
+async def test_dispatch_refuses_action_after_screen_permission_revocation(monkeypatch):
+ tcc = _darwin_world(monkeypatch, granted=("accessibility",)) # Screen Recording is off
executor = FakeExecutor()
ctx = _ctx(FakeBrain([]), executor)
- monkeypatch.setattr(
- "jarvis.cu.capture._require_macos_screen_recording_permission",
- lambda: (_ for _ in ()).throw(
- RuntimeError("Screen Recording permission was revoked"),
- ),
- )
ok, detail = await engine_mod._dispatch_tool(
ctx,
@@ -378,10 +390,135 @@ async def test_dispatch_refuses_action_after_screen_permission_revocation(
)
assert ok is False
- assert "Screen Recording" in detail
+ # The agent-facing refusal: the prefix the loop maps, prohibitive, no paths.
+ assert detail.startswith("[permission_needed:screen_recording] ")
+ assert "must not retry" in detail
+ assert executor.calls == []
+ # The gate is silent: it never asks macOS (no dialog, no implicit prompt).
+ assert tcc.requests() == []
+ assert tcc.implicit_prompts() == []
+
+
+async def test_dispatch_sees_a_screen_recording_grant_given_mid_session(monkeypatch):
+ # The per-process preflight is frozen (BUG-161); the deep read's window-title
+ # oracle must still see the grant the user flipped on while Jarvis runs.
+ tcc = _darwin_world(monkeypatch)
+ executor = FakeExecutor()
+ ctx = _ctx(FakeBrain([]), executor)
+ first, _detail = await engine_mod._dispatch_tool(ctx, "click", {"x": 1, "y": 1}, None)
+ assert first is False
+
+ tcc.grant("screen_recording")
+ second, _detail = await engine_mod._dispatch_tool(ctx, "click", {"x": 1, "y": 1}, None)
+
+ assert second is True
+ assert [name for name, _args in executor.calls] == ["click"]
+ assert tcc.requests() == []
+
+
+async def test_dispatch_refuses_after_a_proven_screen_recording_grant_is_revoked(monkeypatch):
+ # The remembered proof of a grant must not defeat the blind-input guard: the gate
+ # reads deep, so a revoke that lands between two actions is seen on the next one.
+ tcc = _darwin_world(monkeypatch)
+ executor = FakeExecutor()
+ ctx = _ctx(FakeBrain([]), executor)
+ tcc.grant("screen_recording") # the preflight stays frozen negative; the oracle proves it
+ ok, _detail = await engine_mod._dispatch_tool(ctx, "click", {"x": 1, "y": 1}, None)
+ assert ok is True
+
+ tcc.deny("screen_recording")
+ ok, detail = await engine_mod._dispatch_tool(ctx, "click", {"x": 1, "y": 1}, None)
+
+ assert ok is False
+ assert detail.startswith("[permission_needed:screen_recording] ")
+ assert [name for name, _args in executor.calls] == ["click"] # only the first one ran
+ assert tcc.requests() == []
+
+
+async def test_dispatch_pauses_while_a_system_consent_dialog_is_frontmost(monkeypatch):
+ tcc = _darwin_world(monkeypatch, granted=("screen_recording", "accessibility"))
+ monkeypatch.setattr(engine_mod, "_frontmost_system_consent_owner", lambda: "SecurityAgent")
+ executor = FakeExecutor()
+ ctx = _ctx(FakeBrain([]), executor)
+
+ ok, detail = await engine_mod._dispatch_tool(ctx, "key", {}, None)
+ ok_click, _detail_click = await engine_mod._dispatch_tool(ctx, "click", {"x": 5, "y": 5}, None)
+
+ assert ok is False and ok_click is False
+ assert detail.startswith("[permission_needed:system_dialog] ")
+ assert "must not try to answer" in detail
+ assert "SecurityAgent" not in detail # no window or owner names in agent text
+ assert executor.calls == [] # an AI agent never answers a system dialog
+ assert tcc.requests() == []
+
+
+async def test_dispatch_gate_is_read_only_through_an_injected_gate(monkeypatch):
+ # The engine gate only READS (``check_deep`` or ``check``) and records a
+ # background episode: it never makes an interactive request.
+ from tests.fakes.fake_permission_service import FakePermissionService
+
+ gate = FakePermissionService({"screen_recording": "needs_settings"})
+ monkeypatch.setattr(engine_mod, "_permission_gate", lambda: gate)
+ executor = FakeExecutor()
+
+ ok, detail = await engine_mod._dispatch_tool(
+ _ctx(FakeBrain([]), executor), "click", {"x": 5, "y": 5}, None
+ )
+
+ assert ok is False and detail.startswith("[permission_needed:screen_recording] ")
+ assert executor.calls == []
+ assert gate.native_free() # nothing interactive: no call could have made macOS ask
+ assert all(not call.interactive for call in gate.ensure_calls())
+
+
+async def test_dispatch_proceeds_when_no_system_dialog_is_frontmost(monkeypatch):
+ _darwin_world(monkeypatch, granted=("screen_recording", "accessibility"))
+ monkeypatch.setattr(engine_mod, "_frontmost_system_consent_owner", lambda: "")
+ executor = FakeExecutor()
+
+ ok, _detail = await engine_mod._dispatch_tool(
+ _ctx(FakeBrain([]), executor), "click", {"x": 5, "y": 5}, None
+ )
+
+ assert ok is True
+ assert [name for name, _args in executor.calls] == ["click"]
+
+
+async def test_dispatch_refuses_on_macos_when_the_guard_itself_fails(monkeypatch):
+ _darwin_world(monkeypatch, granted=("screen_recording",))
+ monkeypatch.setattr(engine_mod.sys, "platform", "darwin")
+
+ def _boom() -> str:
+ raise RuntimeError("window list exploded")
+
+ monkeypatch.setattr(engine_mod, "_frontmost_system_consent_owner", _boom)
+ executor = FakeExecutor()
+
+ ok, detail = await engine_mod._dispatch_tool(
+ _ctx(FakeBrain([]), executor), "click", {"x": 5, "y": 5}, None
+ )
+
+ assert ok is False and detail.startswith("[permission_needed:")
+ assert "exploded" not in detail # no exception text in agent-facing text
assert executor.calls == []
[email protected]("platform", ["linux", "win32"])
+async def test_dispatch_off_macos_asks_nothing_and_changes_nothing(monkeypatch, platform):
+ from tests.fakes.fake_tcc import FakeTCC, install_port
+
+ tcc = FakeTCC()
+ install_port(monkeypatch, tcc.port(platform))
+ executor = FakeExecutor()
+
+ ok, _detail = await engine_mod._dispatch_tool(
+ _ctx(FakeBrain([]), executor), "click", {"x": 5, "y": 5}, None
+ )
+
+ assert ok is True and [name for name, _args in executor.calls] == ["click"]
+ tcc.assert_silent()
+
+
async def test_rejected_done_feeds_history_and_eventually_fails(patched):
brain = FakeBrain(
[
@@ -1099,3 +1236,205 @@ async def test_a_screen_that_stays_unreadable_still_fails(patched, monkeypatch):
final = _final(chunks)
assert final.exit_code == 1
assert "cannot see the screen" in final.stderr
+
+
[email protected]("refusal", ["pending", "denied"])
+async def test_a_screen_recording_refusal_during_perception_is_terminal(
+ patched, monkeypatch, refusal
+):
+ # The first perception frame of a mission is where Screen Recording is asked
+ # for. The refusal is not flaky capture: no retries, a blocked_permission
+ # ending with the people sentence and a single capture attempt.
+ from jarvis.platform import screen_access
+ from jarvis.platform.permissions import PermissionState
+
+ attempts: list[int] = []
+
+ def refused_capture(monitor, **kw):
+ attempts.append(1)
+ if refusal == "pending":
+ raise screen_access.refusal_pending()
+ raise screen_access.refusal_for_state(PermissionState.DENIED)
+
+ monkeypatch.setattr(engine_mod, "capture_stable_frame", refused_capture)
+
+ chunks = await _run(_ctx(FakeBrain([]), FakeExecutor()))
+
+ final = _final(chunks)
+ assert final.exit_code == 8
+ assert "blocked_permission" in final.stderr
+ assert "Screen Recording" in final.stderr
+ assert "You must not" not in final.stderr
+ assert "[permission_needed:" not in final.stderr
+ assert "cannot see the screen" not in final.stderr
+ assert len(attempts) == 1
+
+
+# ---- a permission refusal is TERMINAL (blocked_permission), never a model retry loop ----
+
+
+class _RefusingExecutor(FakeExecutor):
+ """A tool layer whose input tools answer with the permission layer's agent text."""
+
+ def __init__(self, error: str, tool_names: set[str] | None = None) -> None:
+ super().__init__()
+ self.error = error
+ self.tool_names = tool_names
+
+ async def execute(self, tool, args, *, user_utterance, trace_id):
+ name = tool["name"]
+ self.calls.append((name, dict(args)))
+ if self.tool_names is None or name in self.tool_names:
+ return SimpleNamespace(success=False, output=None, error=self.error)
+ return SimpleNamespace(success=True, output=f"{name} ok")
+
+
+def _agent_refusal(permission: str = "accessibility") -> str:
+ from jarvis.platform.permission_service import agent_detail_for
+ from jarvis.platform.permissions import PermissionId
+
+ return agent_detail_for(PermissionId(permission), "needs_settings")
+
+
+async def test_a_permission_refusal_ends_the_mission_as_blocked_permission(patched):
+ brain = FakeBrain(['{"action": "click", "x": 500, "y": 500, "target": "ok"}'] * 8)
+ executor = _RefusingExecutor(_agent_refusal())
+
+ chunks = await _run(_ctx(brain, executor))
+
+ final = _final(chunks)
+ # An existing terminal status carries a stable reason code (no new status value).
+ assert final.exit_code == 8
+ assert "blocked_permission" in final.stderr
+ assert engine_mod.CU_REASON_BLOCKED_PERMISSION == "blocked_permission"
+ # No model retry loop: one dispatch, one decide call, then the mission is over.
+ assert [name for name, _args in executor.calls] == ["click"]
+ assert len(brain.calls) == 1
+ # People get a sentence from a fixed template, not the prohibitive agent text.
+ assert "Accessibility" in final.stderr
+ assert "You must not" not in final.stderr
+ assert "[permission_needed:" not in final.stderr
+
+
+async def test_a_wrapped_permission_refusal_is_still_terminal(patched):
+ # clear_first wraps the hotkey error: "could not select ... : <detail>; refusing ...".
+ brain = FakeBrain(
+ ['{"action": "type", "text": "hello", "clear_first": true}'] * 8,
+ )
+ executor = _RefusingExecutor(_agent_refusal(), tool_names={"hotkey"})
+
+ chunks = await _run(_ctx(brain, executor))
+
+ final = _final(chunks)
+ assert final.exit_code == 8 and "blocked_permission" in final.stderr
+ assert [name for name, _args in executor.calls] == ["hotkey"] # nothing was typed
+
+
+async def test_a_system_dialog_refusal_is_terminal_and_names_no_permission(patched):
+ from jarvis.cu import system_dialogs
+
+ brain = FakeBrain(['{"action": "key", "keys": ["enter"]}'] * 8)
+ executor = _RefusingExecutor(system_dialogs.agent_detail())
+
+ chunks = await _run(_ctx(brain, executor))
+
+ final = _final(chunks)
+ assert final.exit_code == 8 and "blocked_permission" in final.stderr
+ assert "system dialog" in final.stderr
+ assert "You must not" not in final.stderr
+
+
+class _ClickThenRefuseExecutor(FakeExecutor):
+ """The first click lands (and misses); every later click is refused with ``error``."""
+
+ def __init__(self, error: str) -> None:
+ super().__init__()
+ self.error = error
+
+ async def execute(self, tool, args, *, user_utterance, trace_id):
+ name = tool["name"]
+ self.calls.append((name, dict(args)))
+ clicks = [n for n, _a in self.calls if n == "click"]
+ if name == "click" and len(clicks) > 1:
+ return SimpleNamespace(success=False, output=None, error=self.error)
+ return SimpleNamespace(success=True, output=f"{name} ok")
+
+
+async def test_a_refused_zoom_refined_retry_ends_the_mission_without_another_model_call(patched):
+ from jarvis.cu import system_dialogs
+
+ patched.region_changes_after_click = False # the first click misses
+ brain = FakeBrain(
+ [
+ '{"action": "click", "x": 500, "y": 500, "target": "tiny icon"}',
+ '{"found": true, "x": 900, "y": 900}',
+ '{"action": "fail", "reason": "must never be asked"}',
+ ]
+ )
+ executor = _ClickThenRefuseExecutor(system_dialogs.agent_detail())
+
+ final = _final(await _run(_ctx(brain, executor)))
+
+ # A dialog opened after the first click: the refine click is refused by the guard
+ # and the mission is over, not a failure the model is asked about again.
+ assert final.exit_code == 8 and "blocked_permission" in final.stderr
+ assert "system dialog" in final.stderr
+ assert [n for n, _a in executor.calls].count("click") == 2
+ assert len(brain.calls) == 2 # decide + zoom-refine; no third (re-perceive) call
+
+
+ ("reason", "asking"),
+ [
+ ("needs_settings", False),
+ ("denied", False),
+ ("not_determined", True),
+ ("restart_hint", False),
+ ("restricted", False),
+ ("unavailable", False),
+ ],
+)
+def test_the_user_sentence_follows_the_reason_the_refusal_carries(reason, asking):
+ from jarvis.platform.permission_service import agent_detail_for, user_detail_for
+ from jarvis.platform.permissions import PermissionId
+
+ family = PermissionId.SCREEN_RECORDING
+ sentence = engine_mod._permission_block(agent_detail_for(family, reason, asking=asking))
+
+ assert sentence is not None
+ assert "[permission_needed:" not in sentence and "You must not" not in sentence
+ if reason in ("restricted", "unavailable"):
+ # Nothing the user can switch on: an explanation, not "turn it on in Settings".
+ assert sentence == user_detail_for(family, reason)
+ assert "Then try the task again" not in sentence
+ else:
+ # not_determined shares its agent sentence with needs_settings: that wording wins.
+ expected = "needs_settings" if reason == "not_determined" else reason
+ assert sentence.startswith(user_detail_for(family, expected, asking=asking))
+ if reason == "denied":
+ assert "turned off" in sentence and sentence.endswith("Then try the task again.")
+
+
+def test_the_guard_failure_refusal_is_explained_not_blamed_on_a_switch(monkeypatch):
+ monkeypatch.setattr(engine_mod.sys, "platform", "darwin")
+
+ sentence = engine_mod._permission_block(engine_mod._guard_failure_refusal() or "")
+
+ assert sentence is not None
+ assert "cannot ask for Screen Recording" in sentence
+ assert "turn" not in sentence.lower() and "try the task again" not in sentence.lower()
+
+
+def test_an_unknown_permission_token_gets_a_neutral_sentence():
+ sentence = engine_mod._permission_block("[permission_needed:something_new] stop")
+
+ assert sentence is not None and "System Settings" not in sentence
+
+
+async def test_an_ordinary_tool_failure_is_not_a_permission_block(patched):
+ brain = FakeBrain(['{"action":"open_app","name":"spotify"}'] * 8)
+ executor = FakeExecutor(failures={"open_app"})
+
+ final = _final(await _run(_ctx(brain, executor)))
+
+ assert "blocked_permission" not in final.stderr
diff --git a/tests/unit/cu/test_permission_not_agent_exposed.py b/tests/unit/cu/test_permission_not_agent_exposed.py
new file mode 100644
index 0000000000..b8a3a8e4e2
--- /dev/null
+++ b/tests/unit/cu/test_permission_not_agent_exposed.py
@@ -0,0 +1,108 @@
+"""No agent-reachable tool may ask, reset or open settings for a macOS permission (P9).
+
+The permission service's asking surface (``open_settings``, ``request_native``,
+``note_reset``, a ``tccutil`` reset) belongs to people: a user gesture, a route behind
+the dangerous-action header, or a dedicated consumer entry point. A tool an LLM can
+call must never reach it, or an agent could answer a system dialog's question for the
+user by itself. This is an AST contract over the tool modules, so a later tool or
+plugin that imports the service and calls one of these fails here.
+
+* Tool modules (``jarvis/plugins/tool``, ``jarvis/brain/tools``) never import the
+ service. They reach permissions only through a consumer seam (``get_actuator``,
+ ``screen_access``, the ``window_state`` helpers) that has its own gesture rules.
+* The actuator seam (``jarvis/cu/actuate``) may import it in ``base.py`` only, and
+ only to ``ensure_all`` / ``check`` Accessibility.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import pytest
+
+_ROOT = Path(__file__).resolve().parents[3] / "jarvis"
+_FORBIDDEN_NAMES = frozenset(
+ {"open_settings", "request_native", "note_reset", "refresh_episodes", "attach_bus"}
+)
+_SERVICE_MODULE = "jarvis.platform.permission_service"
+_TOOL_DIRS = ("plugins/tool", "brain/tools")
+
+
+def _modules(subdir: str) -> list[Path]:
+ return sorted(p for p in (_ROOT / subdir).rglob("*.py") if "__pycache__" not in p.parts)
+
+
+def _imports_service(tree: ast.AST) -> bool:
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.module == _SERVICE_MODULE:
+ return True
+ if isinstance(node, ast.ImportFrom) and node.module == "jarvis.platform":
+ if any(alias.name == "permission_service" for alias in node.names):
+ return True
+ if isinstance(node, ast.Import) and any(a.name == _SERVICE_MODULE for a in node.names):
+ return True
+ return False
+
+
+def _forbidden_uses(tree: ast.AST) -> list[str]:
+ found: list[str] = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Attribute) and node.attr in _FORBIDDEN_NAMES:
+ found.append(f"line {node.lineno}: .{node.attr}")
+ elif isinstance(node, ast.Name) and node.id in _FORBIDDEN_NAMES:
+ found.append(f"line {node.lineno}: {node.id}")
+ elif isinstance(node, ast.Constant) and isinstance(node.value, str):
+ if "tccutil" in node.value:
+ found.append(f"line {node.lineno}: a tccutil reset")
+ return found
+
+
+def _rel(path: Path) -> str:
+ return path.relative_to(_ROOT).as_posix()
+
+
+def test_the_scan_covers_real_tool_modules():
+ # A guard that scans an empty directory proves nothing.
+ assert len(_modules("plugins/tool")) > 10
+ assert (_ROOT / "cu" / "actuate" / "base.py").is_file()
+
+
[email protected]("subdir", _TOOL_DIRS)
+def test_tool_modules_never_import_the_permission_service(subdir):
+ offenders = [
+ _rel(path)
+ for path in _modules(subdir)
+ if _imports_service(ast.parse(path.read_text(encoding="utf-8")))
+ ]
+
+ assert offenders == [], f"an agent-reachable tool imports the permission service: {offenders}"
+
+
[email protected]("subdir", [*_TOOL_DIRS, "cu/actuate"])
+def test_no_tool_or_actuator_module_asks_resets_or_opens_settings(subdir):
+ offenders = {}
+ for path in _modules(subdir):
+ uses = _forbidden_uses(ast.parse(path.read_text(encoding="utf-8")))
+ if uses:
+ offenders[_rel(path)] = uses
+
+ assert offenders == {}
+
+
+def test_only_the_actuator_base_imports_the_service_there_and_asks_for_accessibility_only():
+ importers = [
+ _rel(path)
+ for path in _modules("cu/actuate")
+ if _imports_service(ast.parse(path.read_text(encoding="utf-8")))
+ ]
+ assert importers == ["cu/actuate/base.py"]
+
+ tree = ast.parse((_ROOT / "cu" / "actuate" / "base.py").read_text(encoding="utf-8"))
+ called = {
+ node.func.attr
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
+ }
+ assert {"ensure_all"} <= called
+ assert not called & (_FORBIDDEN_NAMES | {"ensure_async"})
diff --git a/tests/unit/cu/test_system_dialogs.py b/tests/unit/cu/test_system_dialogs.py
new file mode 100644
index 0000000000..646d99db59
--- /dev/null
+++ b/tests/unit/cu/test_system_dialogs.py
@@ -0,0 +1,198 @@
+"""The macOS system-consent guard data and matcher (P9: an agent never answers a system dialog).
+
+Pure data plus one matcher driven by an injected window list. The owner names are
+UNVERIFIED (nobody can run macOS in the test sandbox); these tests pin the matching
+rules, not what a real Mac names its dialogs.
+"""
+
+from __future__ import annotations
+
+import os
+
+import pytest
+
+from jarvis.cu import system_dialogs as sd
+
+
+def _window(
+ owner: str,
+ title: str = "",
+ *,
+ alpha: float = 1.0,
+ size: tuple[int, int] = (400, 300),
+ layer: int | None = None,
+ pid: int | None = None,
+):
+ entry = {
+ "kCGWindowOwnerName": owner,
+ "kCGWindowName": title,
+ "kCGWindowAlpha": alpha,
+ "kCGWindowBounds": {"Width": size[0], "Height": size[1]},
+ }
+ if layer is not None:
+ entry["kCGWindowLayer"] = layer
+ if pid is not None:
+ entry["kCGWindowOwnerPID"] = pid
+ return entry
+
+
+ "owner",
+ [
+ "UserNotificationCenter",
+ "universalaccessd",
+ "SecurityAgent",
+ "coreautha",
+ "authorizationhost",
+ ],
+)
+def test_known_consent_owners_match_case_insensitively(owner):
+ assert sd.is_system_consent_window(owner)
+ assert sd.is_system_consent_window(owner.upper())
+
+
[email protected]("owner", ["Safari", "Finder", "Terminal", "", "Personal Jarvis"])
+def test_ordinary_apps_are_never_a_consent_surface(owner):
+ assert not sd.is_system_consent_window(owner, "Privacy")
+
+
+def test_system_settings_is_a_consent_surface_only_on_a_privacy_pane():
+ assert sd.is_system_consent_window("System Settings", "Privacy & Security")
+ assert sd.is_system_consent_window("System Settings", "Accessibility")
+ # A mission that changes the wallpaper must still work.
+ assert not sd.is_system_consent_window("System Settings", "Wallpaper")
+ assert not sd.is_system_consent_window("System Settings", "")
+
+
+ ("owner", "title"),
+ [
+ ("Systemeinstellungen", "Datenschutz & Sicherheit"), # i18n-allow
+ ("Ajustes del Sistema", "Privacidad y seguridad"),
+ ("System Settings", "Camera"),
+ ("System Settings", "Files & Folders"),
+ ("System Settings", "Developer Tools"),
+ ],
+)
+def test_a_localized_system_settings_owner_is_recognised_by_its_bundle_id(owner, title):
+ # The owner name alone does not decide on a de/es Mac (UNVERIFIED that it is localized).
+ if owner != "System Settings":
+ assert not sd.is_system_consent_window(owner, title)
+ assert sd.is_system_consent_window(owner, title, "com.apple.systempreferences")
+ assert not sd.is_system_consent_window(owner, "Wallpaper", "com.apple.systempreferences")
+ assert not sd.is_system_consent_window("Safari", title, "com.apple.Safari")
+
+
+def test_the_scan_looks_a_privacy_titled_window_up_by_its_owner_bundle_id():
+ settings = _window("Systemeinstellungen", "Datenschutz & Sicherheit", pid=4242) # i18n-allow
+ windows = [settings, _window("Safari")]
+ looked_up: list[int] = []
+
+ def lookup(pid: int) -> str:
+ looked_up.append(pid)
+ return "com.apple.systempreferences"
+
+ assert sd.frontmost_consent_owner(lambda: windows, lookup) == "Systemeinstellungen"
+ assert looked_up == [4242]
+ # A window that does not name a privacy pane is never looked up (no AppKit round trip).
+ wallpaper = _window("Systemeinstellungen", "Hintergrundbild", pid=4242) # i18n-allow
+ plain = [wallpaper, _window("Safari")]
+ looked_up.clear()
+ assert sd.frontmost_consent_owner(lambda: plain, lookup) == ""
+ assert looked_up == []
+
+
+def test_a_failing_bundle_lookup_leaves_the_owner_name_to_decide():
+ def broken(_pid: int) -> str:
+ raise RuntimeError("no AppKit")
+
+ windows = [_window("System Settings", "Privacy & Security", pid=1), _window("Safari")]
+ assert sd.frontmost_consent_owner(lambda: windows, broken) == "System Settings"
+ localized = _window("Systemeinstellungen", "Datenschutz & Sicherheit", pid=1) # i18n-allow
+ other = [localized, _window("Safari")]
+ assert sd.frontmost_consent_owner(lambda: other, broken) == "" # fail open, never raises
+
+
+def test_the_frontmost_consent_window_is_reported():
+ windows = [_window("UserNotificationCenter", "Jarvis would like to..."), _window("Safari")]
+ assert sd.frontmost_consent_owner(lambda: windows) == "UserNotificationCenter"
+
+
+def test_chrome_and_invisible_windows_do_not_hide_a_dialog_behind_them():
+ windows = [
+ _window("Window Server", "Menubar"),
+ _window("Dock", "Dock"),
+ _window("Notification Center", "banner"),
+ _window("Some Overlay", alpha=0.0),
+ _window("Tiny Helper", size=(1, 1)),
+ _window("SecurityAgent", "Authentication"),
+ _window("Safari"),
+ ]
+ assert sd.frontmost_consent_owner(lambda: windows) == "SecurityAgent"
+
+
+def test_an_ordinary_frontmost_window_decides_even_with_a_dialog_behind_it():
+ # The dialog is not frontmost: the person already moved on, nothing to pause for.
+ windows = [_window("Safari"), _window("SecurityAgent", "Authentication")]
+ assert sd.frontmost_consent_owner(lambda: windows) == ""
+
+
+def test_a_floating_overlay_of_another_app_does_not_mask_a_dialog_behind_it():
+ # Front to back: a floating overlay (layer 3), the consent dialog (layer 8), Safari.
+ windows = [
+ _window("Python", layer=3, pid=999_999),
+ _window("UserNotificationCenter", "Jarvis would like to...", layer=8),
+ _window("Safari", layer=0),
+ ]
+ assert sd.frontmost_consent_owner(lambda: windows) == "UserNotificationCenter"
+
+
+def test_jarvis_own_always_on_top_windows_do_not_mask_a_dialog_behind_them():
+ own = os.getpid()
+ windows = [
+ _window("Personal Jarvis", "orb overlay", layer=3, pid=own),
+ _window("Personal Jarvis", "virtual cursor", layer=3, pid=own),
+ _window("Personal Jarvis", "Esc pill", layer=0, pid=own), # even on layer 0
+ _window("SecurityAgent", "Authentication", layer=8),
+ _window("Safari", layer=0),
+ ]
+ assert sd.frontmost_consent_owner(lambda: windows) == "SecurityAgent"
+
+
+def test_a_normal_window_of_another_app_in_front_ends_the_scan_even_with_overlays_above_it():
+ windows = [
+ _window("Python", layer=3, pid=999_999),
+ _window("Safari", layer=0),
+ _window("SecurityAgent", "Authentication", layer=8),
+ ]
+ assert sd.frontmost_consent_owner(lambda: windows) == ""
+
+
+def test_a_malformed_layer_or_pid_fails_open_without_raising():
+ windows = [
+ _window("Safari", layer="not a number", pid="x"), # type: ignore[arg-type]
+ _window("SecurityAgent", "Authentication"),
+ ]
+ # An unreadable layer reads as a normal window: the scan stops there (fail open).
+ assert sd.frontmost_consent_owner(lambda: windows) == ""
+ windows = [
+ _window("Python", pid="x"), # type: ignore[arg-type]
+ _window("SecurityAgent", "Authentication", layer=8),
+ ]
+ assert sd.frontmost_consent_owner(lambda: windows) == ""
+
+
+def test_an_unreadable_window_list_fails_open_without_raising():
+ def boom():
+ raise RuntimeError("no window server")
+
+ assert sd.frontmost_consent_owner(boom) == ""
+ assert sd.frontmost_consent_owner(lambda: []) == ""
+
+
+def test_the_texts_are_fixed_templates_with_the_stable_prefix():
+ agent = sd.agent_detail()
+ assert agent.startswith(f"[permission_needed:{sd.SYSTEM_DIALOG_BLOCK}] ")
+ assert "must not try to answer" in agent and "must not retry" in agent
+ assert "[permission_needed" not in sd.user_detail()
+ assert "never answers system dialogs" in sd.user_detail()
diff --git a/tests/unit/dictation/test_insert_permission.py b/tests/unit/dictation/test_insert_permission.py
new file mode 100644
index 0000000000..3f4e804251
--- /dev/null
+++ b/tests/unit/dictation/test_insert_permission.py
@@ -0,0 +1,238 @@
+"""Dictation auto-paste asks for Accessibility when it first needs it, and degrades honestly.
+
+The paste keystroke needs macOS's Accessibility grant. These tests run the REAL
+permission service on a REAL port that sits on ``FakeTCC`` (a model of macOS
+privacy, nothing here ran on a real Mac) and pin four promises: the first paste
+asks once (no loop), a refusal leaves the transcript on the clipboard and tells
+the PERSON why (``user_detail``, never the agent text), the first paste after an
+in-process grant reports ``paste_sent`` instead of claiming delivery, and no key
+is ever sent while a system dialog could be frontmost.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.dictation import insert as insert_mod
+from jarvis.dictation.insert import TargetReport, insert_text
+from jarvis.platform.permission_service import get_permission_service
+from tests.fakes.fake_permission_service import make_result
+from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, install_port
+
+
+class FakeClipboard:
+ def __init__(self, initial: str | None = "previous contents") -> None:
+ self.content = initial
+ self.writes: list[str] = []
+
+ def read_text(self) -> str | None:
+ return self.content
+
+ def write_text(self, text: str) -> bool:
+ self.writes.append(text)
+ self.content = text
+ return True
+
+
+class FakeActuator:
+ def __init__(self) -> None:
+ self.combos: list[list[str]] = []
+ self.typed: list[str] = []
+
+ def key_combo(self, keys: list[str]) -> None:
+ self.combos.append(list(keys))
+
+ def type_text(self, text: str, *, delay_s: float = 0.02) -> None:
+ self.typed.append(text)
+
+
+def paste(monkeypatch: pytest.MonkeyPatch):
+ """insert_text on macOS with fakes: no sleeping, no real clipboard, no real keys."""
+ import jarvis.platform.clipboard as real_clipboard
+
+ clipboard = FakeClipboard()
+ actuator = FakeActuator()
+ monkeypatch.setattr(real_clipboard, "read_text", clipboard.read_text)
+ monkeypatch.setattr(real_clipboard, "write_text", clipboard.write_text)
+ monkeypatch.setattr(insert_mod, "describe_target", lambda: TargetReport(True, "", ""))
+ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", lambda: actuator)
+ monkeypatch.setattr(insert_mod.time, "sleep", lambda _s: None)
+ monkeypatch.setattr(insert_mod, "_clipboard_offer_factory", lambda: None)
+ monkeypatch.setattr(insert_mod, "os", SimpleNamespace(name="posix"))
+ monkeypatch.setattr(insert_mod.sys, "platform", "darwin")
+ # No system dialog on screen unless a test says so.
+ monkeypatch.setattr("jarvis.cu.system_dialogs.frontmost_consent_owner", lambda *a, **k: "")
+ # Module state of the first-paste flag must not leak between tests.
+ insert_mod._FIRST_PASTE_AFTER_GRANT.clear()
+ monkeypatch.setattr(insert_mod, "_grant_listener_gate", None)
+
+ def world(**tcc_kwargs: object) -> FakeTCC:
+ tcc_kwargs.setdefault("default_policy", DialogPolicy.NEVER_ANSWERED)
+ tcc = FakeTCC(**tcc_kwargs) # type: ignore[arg-type]
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
+
+ yield SimpleNamespace(clipboard=clipboard, actuator=actuator, world=world)
+ insert_mod._FIRST_PASTE_AFTER_GRANT.clear()
+
+
+def test_the_first_paste_asks_once_and_degrades_to_the_clipboard(paste) -> None:
+ tcc = paste.world()
+
+ first = insert_text("dictated text")
+ second = insert_text("more text")
+
+ assert first.status == "clipboard_only" and second.status == "clipboard_only"
+ assert first.clipboard_holds_text is True
+ assert paste.clipboard.content == "more text" # the honest fallback: one Cmd+V away
+ assert paste.actuator.combos == [] # no keystroke without a live grant
+ assert len(tcc.requests("accessibility")) == 1 # no re-prompt loop on the second paste
+ assert tcc.implicit_prompts() == []
+
+
+def test_a_refusal_tells_the_person_in_the_users_words_never_the_agent_text(paste) -> None:
+ paste.world()
+
+ result = insert_text("dictated text")
+
+ assert "Accessibility" in result.detail
+ assert "on your clipboard" in result.detail
+ assert "[permission_needed" not in result.detail
+ assert "must not" not in result.detail # the prohibitive agent text is for tool errors
+ assert "Settings > Permissions" not in result.detail
+
+
+def test_a_denied_accessibility_grant_is_not_asked_again(paste) -> None:
+ tcc = paste.world(default_policy=DialogPolicy.DENY)
+
+ results = [insert_text(f"text {n}") for n in range(3)]
+
+ assert [r.status for r in results] == ["clipboard_only"] * 3
+ assert len(tcc.requests("accessibility")) == 1
+ assert paste.actuator.combos == []
+
+
+def test_with_the_grant_present_the_paste_goes_out_and_nothing_is_asked(paste) -> None:
+ tcc = paste.world(granted=("accessibility",))
+
+ result = insert_text("dictated text")
+
+ assert result.status == "inserted" and result.method == "clipboard+cmd_v"
+ assert paste.actuator.combos == [["cmd", "v"]]
+ assert tcc.requests() == []
+
+
+def test_the_first_paste_after_an_in_process_grant_reports_paste_sent(paste) -> None:
+ tcc = paste.world()
+ assert insert_text("first").status == "clipboard_only"
+
+ tcc.answer("accessibility") # the user flips the switch while Jarvis runs
+ get_permission_service().invalidate()
+ after = insert_text("second")
+ later = insert_text("third")
+
+ # Whether an in-process grant already reaches event posting is unverified and
+ # macOS never reports delivery: the first paste does not claim "inserted" and
+ # does not restore the clipboard over the transcript.
+ assert after.status == "paste_sent"
+ assert after.clipboard_holds_text is True and after.clipboard_restored is False
+ assert paste.actuator.combos[0] == ["cmd", "v"]
+ assert "clipboard" in after.detail
+ # Only the first one: the next paste is an ordinary, restoring paste.
+ assert later.status == "inserted"
+
+
+def test_a_grant_present_from_the_start_is_not_downgraded(paste) -> None:
+ paste.world(granted=("accessibility",))
+
+ assert [insert_text(f"text {n}").status for n in range(2)] == ["inserted", "inserted"]
+
+
+def test_the_type_route_asks_too_and_never_types_without_the_grant(paste) -> None:
+ tcc = paste.world()
+
+ result = insert_text("dictated text", method="type")
+
+ assert result.status == "clipboard_only"
+ assert paste.actuator.typed == []
+ assert len(tcc.requests("accessibility")) == 1
+
+
[email protected]("method", ["clipboard", "type"])
+def test_no_key_is_sent_while_a_system_dialog_is_frontmost(paste, monkeypatch, method) -> None:
+ paste.world(granted=("accessibility",))
+ monkeypatch.setattr(
+ "jarvis.cu.system_dialogs.frontmost_consent_owner",
+ lambda *a, **k: "UserNotificationCenter",
+ )
+
+ # A recorded custom chord may contain Return: it must not answer a dialog.
+ result = insert_text("dictated text", method=method, paste_chord="cmd+enter")
+
+ assert result.status == "clipboard_only"
+ assert paste.actuator.combos == [] and paste.actuator.typed == []
+ assert "system dialog" in result.detail
+ assert "UserNotificationCenter" not in result.detail # no owner names for people
+ assert paste.clipboard.content == "dictated text" # not restored over the transcript
+
+
+def test_a_permission_refusal_raised_by_the_actuator_shows_the_users_sentence(
+ paste, monkeypatch
+) -> None:
+ from jarvis.cu.actuate.base import PermissionNeededError
+ from jarvis.platform.permissions import PermissionId
+
+ paste.world(granted=("accessibility",)) # the up-front ask passes, then it is revoked
+
+ def revoked():
+ raise PermissionNeededError(make_result(PermissionId.ACCESSIBILITY, "needs_settings"))
+
+ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", revoked)
+
+ result = insert_text("dictated text")
+
+ assert result.status == "clipboard_only"
+ assert "Accessibility" in result.detail and "[permission_needed" not in result.detail
+
+
+def test_the_grant_watcher_is_registered_once_per_gate_and_flags_the_first_paste(paste) -> None:
+ class _Gate:
+ def __init__(self) -> None:
+ self.listeners: list[tuple[str, object]] = []
+
+ def add_listener(self, permission, callback):
+ self.listeners.append((str(permission), callback))
+ return lambda: None
+
+ gate = _Gate()
+ insert_mod._watch_for_grant(gate)
+ insert_mod._watch_for_grant(gate)
+
+ assert [name for name, _cb in gate.listeners] == ["accessibility"]
+ assert not insert_mod._FIRST_PASTE_AFTER_GRANT.is_set()
+ gate.listeners[0][1]() # the permission layer reports the grant (zero-argument callback)
+ assert insert_mod._FIRST_PASTE_AFTER_GRANT.is_set()
+
+
+def test_a_gate_without_listeners_never_breaks_the_paste(paste) -> None:
+ insert_mod._watch_for_grant(object()) # must not raise
+
+ assert insert_mod._grant_listener_gate is None # nothing registered, nothing remembered
+
+
[email protected]("platform", ["linux", "win32"])
+def test_off_macos_the_paste_never_touches_the_permission_layer(
+ paste, monkeypatch, platform
+) -> None:
+ tcc = FakeTCC()
+ install_port(monkeypatch, tcc.port(platform)) # type: ignore[arg-type]
+ monkeypatch.setattr(insert_mod.sys, "platform", platform)
+
+ result = insert_text("dictated text", paste_chord="ctrl_v")
+
+ assert result.status in ("inserted", "paste_sent")
+ assert paste.actuator.combos == [["ctrl", "v"]]
+ tcc.assert_silent()
diff --git a/tests/unit/harness/test_cu_control_events.py b/tests/unit/harness/test_cu_control_events.py
index 221443fff9..99aebacdb0 100644
--- a/tests/unit/harness/test_cu_control_events.py
+++ b/tests/unit/harness/test_cu_control_events.py
@@ -222,3 +222,63 @@ async def test_concurrent_missions_pair_up(
assert len(rec.ended) == 2
assert {e.mission_id for e in rec.started} == {e.mission_id for e in rec.ended}
assert len({e.mission_id for e in rec.started}) == 2
+
+
+async def test_blocked_permission_sentence_reaches_the_run_registry(
+ bus: EventBus, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The mission result run control reads carries the engine's permission sentence.
+
+ The sentence sits in stderr (a failed mission has no stdout), which the registry
+ does not store; without this the run list shows an empty result for a mission
+ that is waiting for the person to allow something.
+ """
+ from jarvis.harness import cu_run_registry
+
+ cu_run_registry.clear_runs()
+ sentence = "Accessibility is off for Personal Jarvis. Then try the task again."
+ monkeypatch.setattr(
+ cu_mod,
+ "_resolve_run_cu_loop",
+ lambda: _stub_loop(
+ HarnessResult(
+ stderr=(
+ f"[cu] blocked_permission at step-2: {sentence}\n"
+ "[cu] mission profile: steps=2 total=1.0s\n"
+ ),
+ exit_code=8,
+ is_final=True,
+ )
+ ),
+ )
+ harness = ComputerUseHarness(context=_ctx(bus))
+ await _invoke_all(harness, HarnessTask(prompt="open Safari", timeout_s=5))
+
+ run = cu_run_registry.list_runs(limit=1)[0]
+ assert run["status"] == "error"
+ assert run["exit_code"] == 8
+ assert run["result_text"] == sentence
+ cu_run_registry.clear_runs()
+
+
+async def test_plain_failure_keeps_an_empty_registry_result(
+ bus: EventBus, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.harness import cu_run_registry
+
+ cu_run_registry.clear_runs()
+ monkeypatch.setattr(
+ cu_mod,
+ "_resolve_run_cu_loop",
+ lambda: _stub_loop(
+ HarnessResult(
+ stderr="[cu] fail at step-2: no news\n[cu] mission profile: steps=2\n",
+ exit_code=8,
+ is_final=True,
+ )
+ ),
+ )
+ harness = ComputerUseHarness(context=_ctx(bus))
+ await _invoke_all(harness, HarnessTask(prompt="x", timeout_s=5))
+ assert cu_run_registry.list_runs(limit=1)[0]["result_text"] == ""
+ cu_run_registry.clear_runs()
diff --git a/tests/unit/harness/test_cu_screenshot_fastpath.py b/tests/unit/harness/test_cu_screenshot_fastpath.py
index 161596328d..e42ae725a3 100644
--- a/tests/unit/harness/test_cu_screenshot_fastpath.py
+++ b/tests/unit/harness/test_cu_screenshot_fastpath.py
@@ -297,16 +297,23 @@ async def test_compound_screenshot_goal_uses_the_loop_not_the_fast_path(
"jarvis.harness.screenshot_only_loop_stable",
),
)
-def test_legacy_save_screenshot_fails_closed_when_recording_is_denied(
+def test_legacy_save_screenshot_degrades_without_asking_when_recording_is_not_granted(
monkeypatch: pytest.MonkeyPatch,
module_name: str,
) -> None:
+ """The frozen loops only READ the Screen Recording state: the fast path returns
+ None (the loop falls through, honestly) and never makes macOS ask. The REAL
+ permission service runs on ``FakeTCC``, a model of macOS privacy (nothing here ran
+ on a real Mac); its call log proves nothing was requested."""
import importlib
+ from tests.fakes.fake_tcc import FakeTCC, install_port
+
module = importlib.import_module(module_name)
- monkeypatch.setattr(
- "jarvis.vision.screenshot.warn_if_screen_recording_denied",
- lambda: True,
- )
+ tcc = FakeTCC()
+ install_port(monkeypatch, tcc.port("darwin"))
assert module._save_user_screenshot() is None
+ assert module._save_user_screenshot() is None
+
+ tcc.assert_no_prompts()
diff --git a/tests/unit/packaging/test_frozen_browser_smoke.py b/tests/unit/packaging/test_frozen_browser_smoke.py
index 5802c1c819..eb68548e8c 100644
--- a/tests/unit/packaging/test_frozen_browser_smoke.py
+++ b/tests/unit/packaging/test_frozen_browser_smoke.py
@@ -1,10 +1,13 @@
"""Failure and isolation guarantees for the native-package acceptance probe."""
+import stat
+import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
+from jarvis.core.instance import DEV_PORT_OFFSET
from scripts.ci import check_frozen_browser as probe
@@ -69,3 +72,174 @@ def test_first_install_requires_a_fresh_profile(tmp_path, monkeypatch):
)
with pytest.raises(FileExistsError):
probe.main()
+
+
+def _snapshot(microphone: str | None, bundle_id: str | None) -> dict:
+ rows = [] if microphone is None else [{"id": "microphone", "status": microphone}]
+ return {"permissions": rows, "app_identity": {"bundle_id": bundle_id}}
+
+
+def test_permission_check_asks_nothing_off_macos(monkeypatch):
+ """Windows and Linux have no permission port to ask."""
+ monkeypatch.setattr(probe.sys, "platform", "linux")
+
+ def explode(*_args, **_kwargs):
+ raise AssertionError("no request may be made off macOS")
+
+ monkeypatch.setattr(probe, "request_json", explode)
+
+ assert probe.check_macos_permissions(50000, "test-key") == {}
+
+
+def test_a_frozen_mac_app_that_can_read_its_microphone_passes(monkeypatch):
+ monkeypatch.setattr(probe.sys, "platform", "darwin")
+ monkeypatch.setattr(
+ probe,
+ "request_json",
+ lambda *_args: _snapshot("not_determined", probe.ACCEPTED_BUNDLE_IDS[-1]),
+ )
+
+ assert probe.check_macos_permissions(50000, "test-key") == {
+ "microphone_permission": "not_determined",
+ "bundle_id": probe.ACCEPTED_BUNDLE_IDS[-1],
+ }
+
+
[email protected]("microphone", ["unavailable", None])
+def test_a_frozen_mac_app_without_its_microphone_framework_fails(monkeypatch, microphone):
+ """The v2.5.0 image: AVFoundation missing, so the row reads 'unavailable' for good."""
+ monkeypatch.setattr(probe.sys, "platform", "darwin")
+ monkeypatch.setattr(
+ probe,
+ "request_json",
+ lambda *_args: _snapshot(microphone, probe.ACCEPTED_BUNDLE_IDS[0]),
+ )
+
+ with pytest.raises(RuntimeError, match="AVFoundation"):
+ probe.check_macos_permissions(50000, "test-key")
+
+
+def test_a_frozen_mac_app_with_a_foreign_bundle_id_fails(monkeypatch):
+ monkeypatch.setattr(probe.sys, "platform", "darwin")
+ monkeypatch.setattr(
+ probe,
+ "request_json",
+ lambda *_args: _snapshot("denied", "com.example.other"),
+ )
+
+ with pytest.raises(RuntimeError, match="com.example.other"):
+ probe.check_macos_permissions(50000, "test-key")
+
+
+def test_a_missing_permission_route_fails_at_once_but_a_starting_app_is_retried(monkeypatch):
+ monkeypatch.setattr(probe.sys, "platform", "darwin")
+
+ def respond(code):
+ def request(*_args):
+ raise probe.ProbeHTTPError(code)
+
+ return request
+
+ monkeypatch.setattr(probe, "request_json", respond(404))
+ with pytest.raises(RuntimeError, match="does not serve"):
+ probe.check_macos_permissions(50000, "test-key")
+
+ # 503 is "still starting": the boot loop retries it, so it must pass through.
+ monkeypatch.setattr(probe, "request_json", respond(503))
+ with pytest.raises(probe.ProbeHTTPError) as starting:
+ probe.check_macos_permissions(50000, "test-key")
+ assert starting.value.code == 503
+
+
+# A stand-in for the frozen app: `<exe> serve` answers the three requests the
+# smoke makes, with the permission status a given build would report.
+_FAKE_APP = """#!{python}
+import json, os, re
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+config = open(os.environ["JARVIS_CONFIG"], encoding="utf-8").read()
+port = int(re.search(r"admin_api_port\\s*=\\s*(\\d+)", config).group(1)) + {offset}
+mode = "{mode}"
+
+
+class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ if self.headers.get("Authorization") != "Bearer " + os.environ["JARVIS_CONTROL_API_KEY"]:
+ return self.reply(401, {{}})
+ if self.path == "/api/health":
+ return self.reply(200, {{"ok": True, "instance": "dev"}})
+ if self.path == "/api/society/browser/status":
+ return self.reply(200, {{"phase": "ready", "installed": True}})
+ if self.path == "/api/permissions/status" and mode != "missing-route":
+ microphone = "unavailable" if mode == "no-avfoundation" else "not_determined"
+ return self.reply(200, {{
+ "permissions": [{{"id": "microphone", "status": microphone}}],
+ "app_identity": {{"bundle_id": "ai.personaljarvis.desktop"}},
+ }})
+ return self.reply(404, {{}})
+
+ def reply(self, code, body):
+ data = json.dumps(body).encode()
+ self.send_response(code)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def log_message(self, *_args):
+ pass
+
+
+ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
+"""
+
+
+def _boot_fake_app(tmp_path, monkeypatch, *, platform, mode):
+ app = tmp_path / "fake-app"
+ app.write_text(
+ _FAKE_APP.format(python=sys.executable, offset=DEV_PORT_OFFSET, mode=mode),
+ encoding="utf-8",
+ )
+ app.chmod(app.stat().st_mode | stat.S_IXUSR)
+ profile = tmp_path / "profile"
+ profile.mkdir()
+ monkeypatch.setattr(probe.sys, "platform", platform)
+ monkeypatch.setattr(probe, "capture_frame", lambda *_args, **_kwargs: {})
+ return probe.boot(app, profile, tmp_path / "first-install", "test-key", timeout=60)
+
+
+posix_only = pytest.mark.skipif(
+ sys.platform == "win32", reason="the stand-in app is a POSIX shebang script"
+)
+
+
+@posix_only
+def test_a_mac_boot_records_the_permission_check(tmp_path, monkeypatch):
+ report = _boot_fake_app(tmp_path, monkeypatch, platform="darwin", mode="ok")
+
+ assert report["permissions"] == {
+ "microphone_permission": "not_determined",
+ "bundle_id": "ai.personaljarvis.desktop",
+ }
+ assert "healthy_seconds" in report
+
+
+@posix_only
+def test_a_mac_boot_without_the_microphone_framework_fails_instead_of_passing(
+ tmp_path, monkeypatch
+):
+ with pytest.raises(RuntimeError, match="AVFoundation"):
+ _boot_fake_app(tmp_path, monkeypatch, platform="darwin", mode="no-avfoundation")
+
+
+@posix_only
+def test_a_mac_boot_without_the_permission_route_fails_instead_of_waiting(tmp_path, monkeypatch):
+ with pytest.raises(RuntimeError, match="does not serve"):
+ _boot_fake_app(tmp_path, monkeypatch, platform="darwin", mode="missing-route")
+
+
+@posix_only
+def test_a_boot_off_macos_never_asks_for_permissions(tmp_path, monkeypatch):
+ report = _boot_fake_app(tmp_path, monkeypatch, platform="linux", mode="no-avfoundation")
+
+ assert report["permissions"] == {}
diff --git a/tests/unit/packaging/test_macos_build_script.py b/tests/unit/packaging/test_macos_build_script.py
new file mode 100644
index 0000000000..d619c71693
--- /dev/null
+++ b/tests/unit/packaging/test_macos_build_script.py
@@ -0,0 +1,528 @@
+"""``packaging/macos/build.sh`` — the rehearsed (``DRY_RUN=1``) signing flow.
+
+A GitHub runner starts with an empty keychain, so ``codesign --sign "Developer
+ID Application: ..."`` can only work once the certificate secrets have been
+imported. The workflow passed ``APPLE_CERTIFICATE_P12_BASE64`` to a script that
+never read it, which is why every public .dmg was ad-hoc signed and
+unnotarized: macOS then refuses the first launch and forgets every privacy
+grant on every update. These tests rehearse the script on any host (DRY_RUN
+prints each command instead of running it) in a throw-away copy of the layout,
+and pin the three things that must stay true:
+
+* without secrets the script behaves exactly as before (ad-hoc, no keychain);
+* with the certificate secrets it imports them and signs, and no secret ever
+ reaches the output;
+* a certificate without its password is refused before the long freeze;
+* the REAL import branch (not just its DRY_RUN printout) runs the right
+ ``security`` calls in the right order, reads the identity back from the
+ certificate, and always restores the keychain search list and deletes the
+ temporary keychain. That branch is cut out of the script and run against a
+ stand-in ``security`` command, because a runner's keychain cannot be used on
+ every host these tests run on. On a Mac runner the same test runs under the
+ shell macOS ships (bash 3.2).
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+BUILD_SH = REPO_ROOT / "packaging" / "macos" / "build.sh"
+
+pytestmark = pytest.mark.skipif(
+ sys.platform == "win32" or shutil.which("bash") is None,
+ reason="a POSIX shell is needed to rehearse the macOS build script",
+)
+
+# Strings that must never appear in the rehearsal output.
+_SECRETS = {
+ "APPLE_CERTIFICATE_P12_BASE64": "TOPSECRET-P12-PAYLOAD",
+ "APPLE_CERTIFICATE_PASSWORD": "TOPSECRET-P12-PASSWORD",
+ "APPLE_APP_SPECIFIC_PASSWORD": "TOPSECRET-APP-PASSWORD",
+}
+
+
+def layout(tmp_path: Path) -> Path:
+ """A minimal copy of the repo layout the script resolves its paths from."""
+ root = tmp_path / "repo"
+ (root / "packaging" / "macos").mkdir(parents=True)
+ shutil.copy2(BUILD_SH, root / "packaging" / "macos" / "build.sh")
+ shutil.copy2(
+ REPO_ROOT / "packaging" / "macos" / "entitlements.plist",
+ root / "packaging" / "macos" / "entitlements.plist",
+ )
+ (root / "jarvis" / "ui" / "web" / "dist").mkdir(parents=True)
+ (root / "jarvis" / "ui" / "web" / "dist" / "index.html").write_text("<html></html>")
+ (root / "jarvis.toml.example").write_text("# defaults\n", encoding="utf-8")
+ (root / "jarvis.toml").write_text("# defaults\n", encoding="utf-8")
+ (root / "assets" / "icons").mkdir(parents=True)
+ (root / "assets" / "icons" / "jarvis.icns").write_bytes(b"icns")
+ return root
+
+
+def _rehearse(layout: Path, **env: str) -> subprocess.CompletedProcess[str]:
+ clean = {
+ "PATH": os.environ.get("PATH", ""),
+ "HOME": str(layout),
+ "DRY_RUN": "1",
+ "SKIP_FRONTEND": "1",
+ "PYTHON": sys.executable,
+ }
+ clean.update(env)
+ return subprocess.run(
+ ["bash", str(layout / "packaging" / "macos" / "build.sh")],
+ capture_output=True,
+ text=True,
+ timeout=120,
+ env=clean,
+ check=False,
+ )
+
+
+def test_without_secrets_the_build_is_ad_hoc_and_touches_no_keychain(layout: Path) -> None:
+ result = _rehearse(layout)
+
+ assert result.returncode == 0, result.stderr
+ assert "ad-hoc signing this build" in result.stdout
+ assert "codesign --force --deep -s -" in result.stdout
+ assert "keychain" not in result.stdout.lower()
+ assert "notarytool" not in result.stdout
+
+
+def test_the_certificate_secrets_are_imported_and_the_app_is_signed_with_it(
+ layout: Path,
+) -> None:
+ result = _rehearse(
+ layout,
+ APPLE_ID="[email protected]",
+ APPLE_TEAM_ID="ABCDE12345",
+ **_SECRETS,
+ )
+
+ assert result.returncode == 0, result.stderr
+ out = result.stdout
+ # The identity does not have to be given: it comes out of the certificate.
+ assert "signing with Developer ID identity" in out
+ assert "--options runtime" in out
+ # Import, key access for codesign, and the search list — in that order.
+ markers = [
+ "security create-keychain",
+ "security import",
+ "security set-key-partition-list",
+ "security list-keychains -d user -s",
+ "codesign --force --deep --timestamp --options runtime",
+ ]
+ positions = [out.index(marker) for marker in markers]
+ assert positions == sorted(positions)
+ assert "notarytool submit" in out
+ assert "ad-hoc" not in out
+
+
+def test_the_localised_permission_text_is_written_before_anything_is_signed(
+ layout: Path,
+) -> None:
+ """The .lproj files are part of the code seal: written after codesign they break it."""
+ ad_hoc = _rehearse(layout)
+ signed = _rehearse(
+ layout,
+ APPLE_ID="[email protected]",
+ APPLE_TEAM_ID="ABCDE12345",
+ **_SECRETS,
+ )
+
+ for result, first_signing in (
+ (ad_hoc, "codesign --force --deep -s -"),
+ (signed, "codesign --force --deep --timestamp --options runtime"),
+ ):
+ assert result.returncode == 0, result.stderr
+ out = result.stdout
+ assert "add_localizations.py --app" in out
+ assert out.index("add_localizations.py") < out.index(first_signing)
+ if "notarytool submit" in out:
+ assert out.index("add_localizations.py") < out.index("notarytool submit")
+
+
+def test_no_secret_ever_reaches_the_output(layout: Path) -> None:
+ result = _rehearse(
+ layout,
+ APPLE_ID="[email protected]",
+ APPLE_TEAM_ID="ABCDE12345",
+ **_SECRETS,
+ )
+
+ assert result.returncode == 0, result.stderr
+ combined = result.stdout + result.stderr
+ for secret in _SECRETS.values():
+ assert secret not in combined
+ assert "<redacted>" in combined
+
+
+def test_an_identity_that_is_given_wins_over_reading_one_from_the_certificate(
+ layout: Path,
+) -> None:
+ result = _rehearse(
+ layout,
+ APPLE_SIGNING_IDENTITY="Developer ID Application: Example (ABCDE12345)",
+ **_SECRETS,
+ )
+
+ assert result.returncode == 0, result.stderr
+ assert "Developer ID Application: Example (ABCDE12345)" in result.stdout
+
+
+def test_a_certificate_without_its_password_is_refused_before_the_freeze(layout: Path) -> None:
+ result = _rehearse(layout, APPLE_CERTIFICATE_P12_BASE64="TOPSECRET-P12-PAYLOAD")
+
+ assert result.returncode != 0
+ assert "APPLE_CERTIFICATE_PASSWORD" in result.stderr
+ assert "TOPSECRET-P12-PAYLOAD" not in result.stdout + result.stderr
+ # Refused up front: the long PyInstaller step never started.
+ assert "running PyInstaller" not in result.stdout
+
+
+def test_an_identity_alone_keeps_working_on_a_mac_that_already_holds_it(layout: Path) -> None:
+ """A maintainer's own Mac has the identity in its login keychain: no import."""
+ result = _rehearse(
+ layout,
+ APPLE_SIGNING_IDENTITY="Developer ID Application: Example (ABCDE12345)",
+ )
+
+ assert result.returncode == 0, result.stderr
+ assert "security create-keychain" not in result.stdout
+ assert "signing with Developer ID identity" in result.stdout
+
+
+# --- The real import branch, against a stand-in `security` command -----------
+
+_FAKE_SECURITY = """#!/usr/bin/env bash
+# Stand-in for macOS `security`: log every call, answer the two queries.
+printf '%s\\n' "$*" >> "${FAKE_SECURITY_LOG}"
+case "$1" in
+ list-keychains)
+ case " $* " in
+ *" -s "*) ;;
+ *) printf ' "/Users/runner/Library/Keychains/login.keychain-db"\\n'
+ printf ' "/Library/Keychains/System.keychain"\\n' ;;
+ esac ;;
+ find-identity) cat "${FAKE_IDENTITIES_FILE}" ;;
+ import) [ -z "${FAKE_IMPORT_FAILS:-}" ] || exit 1 ;;
+esac
+exit 0
+"""
+
+_FAKE_UUIDGEN = """#!/usr/bin/env bash
+echo "11111111-2222-3333-4444-555555555555"
+"""
+
+_DEVELOPER_ID_IDENTITIES = (
+ " 1) 0123456789ABCDEF0123456789ABCDEF01234567 "
+ '"Developer ID Application: Example GmbH (ABCDE12345)"\n'
+ " 1 valid identities found\n"
+)
+_APPLE_DEVELOPMENT_IDENTITIES = (
+ ' 1) 0123456789ABCDEF0123456789ABCDEF01234567 "Apple Development: Someone (ZZZZZ99999)"\n'
+ " 1 valid identities found\n"
+)
+
+
+def _import_section() -> str:
+ """The certificate-import part of build.sh, cut out by its own markers."""
+ script = BUILD_SH.read_text(encoding="utf-8")
+ start_marker = 'SIGNING_KEYCHAIN=""'
+ end_marker = "import_signing_certificate\n\n# --- 1. Web bundle"
+ assert start_marker in script and end_marker in script, (
+ "build.sh was restructured: update the markers that cut out the certificate import"
+ )
+ return script[script.index(start_marker) : script.index(end_marker)]
+
+
+def stand_in(tmp_path: Path):
+ """A PATH whose `security` and `uuidgen` are logging stand-ins."""
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ for name, body in (("security", _FAKE_SECURITY), ("uuidgen", _FAKE_UUIDGEN)):
+ tool = bin_dir / name
+ tool.write_text(body, encoding="utf-8")
+ tool.chmod(0o755)
+ harness = tmp_path / "harness.sh"
+ harness.write_text(
+ "#!/usr/bin/env bash\n"
+ "set -euo pipefail\n"
+ "DRY_RUN=0\n"
+ "log() { printf '[macos-build] %s\\n' \"$*\"; }\n"
+ "die() { printf '[macos-build] ERROR: %s\\n' \"$*\" >&2; exit 1; }\n"
+ + _import_section()
+ + '\nimport_signing_certificate\necho "IDENTITY=${APPLE_SIGNING_IDENTITY:-}"\n',
+ encoding="utf-8",
+ )
+ scratch = tmp_path / "scratch"
+ scratch.mkdir()
+ return bin_dir, harness, scratch
+
+
+def _run_import(stand_in, tmp_path: Path, identities: str, **env: str):
+ bin_dir, harness, scratch = stand_in
+ log_file = tmp_path / "security.log"
+ log_file.write_text("", encoding="utf-8")
+ identities_file = tmp_path / "identities.txt"
+ identities_file.write_text(identities, encoding="utf-8")
+ clean = {
+ "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}",
+ "HOME": str(tmp_path),
+ "RUNNER_TEMP": str(scratch),
+ "FAKE_SECURITY_LOG": str(log_file),
+ "FAKE_IDENTITIES_FILE": str(identities_file),
+ "APPLE_CERTIFICATE_P12_BASE64": "VE9QU0VDUkVULVAxMi1QQVlMT0FE", # TOPSECRET-P12-PAYLOAD
+ "APPLE_CERTIFICATE_PASSWORD": "TOPSECRET-P12-PASSWORD",
+ }
+ clean.update(env)
+ result = subprocess.run(
+ ["bash", str(harness)],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ env=clean,
+ check=False,
+ )
+ calls = [line for line in log_file.read_text(encoding="utf-8").splitlines() if line]
+ return result, calls
+
+
+def test_the_real_import_runs_the_right_calls_in_order_and_cleans_up(
+ stand_in, tmp_path: Path
+) -> None:
+ result, calls = _run_import(stand_in, tmp_path, _DEVELOPER_ID_IDENTITIES)
+
+ assert result.returncode == 0, result.stderr
+ assert [call.split()[0] for call in calls] == [
+ "list-keychains", # remember the search list BEFORE creating anything
+ "delete-keychain", # a leftover of an interrupted earlier run
+ "create-keychain",
+ "set-keychain-settings",
+ "unlock-keychain",
+ "import",
+ "set-key-partition-list",
+ "list-keychains", # put ours first
+ "find-identity",
+ "list-keychains", # on exit: restore the search list ...
+ "delete-keychain", # ... and drop the temporary keychain
+ ]
+ keychain = str(tmp_path / "scratch" / "jarvis-signing.keychain-db")
+ originals = [
+ "/Users/runner/Library/Keychains/login.keychain-db",
+ "/Library/Keychains/System.keychain",
+ ]
+ assert calls[7] == f"list-keychains -d user -s {keychain} {' '.join(originals)}"
+ assert calls[9] == f"list-keychains -d user -s {' '.join(originals)}"
+ assert calls[-1] == f"delete-keychain {keychain}"
+ assert "-T /usr/bin/codesign" in calls[5]
+
+
+def test_the_real_import_reads_the_identity_back_from_the_certificate(
+ stand_in, tmp_path: Path
+) -> None:
+ result, _calls = _run_import(stand_in, tmp_path, _DEVELOPER_ID_IDENTITIES)
+
+ assert result.returncode == 0, result.stderr
+ assert "IDENTITY=Developer ID Application: Example GmbH (ABCDE12345)" in result.stdout
+
+
+def test_a_given_identity_is_not_looked_up_again(stand_in, tmp_path: Path) -> None:
+ result, calls = _run_import(
+ stand_in,
+ tmp_path,
+ _APPLE_DEVELOPMENT_IDENTITIES,
+ APPLE_SIGNING_IDENTITY="Developer ID Application: Given (QQQQQ11111)",
+ )
+
+ assert result.returncode == 0, result.stderr
+ assert "IDENTITY=Developer ID Application: Given (QQQQQ11111)" in result.stdout
+ assert "find-identity" not in [call.split()[0] for call in calls]
+
+
+def test_a_certificate_without_a_developer_id_identity_fails_and_still_cleans_up(
+ stand_in, tmp_path: Path
+) -> None:
+ result, calls = _run_import(stand_in, tmp_path, _APPLE_DEVELOPMENT_IDENTITIES)
+
+ assert result.returncode != 0
+ assert "Developer ID Application" in result.stderr
+ # The trap still ran: search list restored, temporary keychain dropped.
+ assert calls[-2].startswith("list-keychains -d user -s /Users/runner/")
+ assert calls[-1].startswith("delete-keychain ")
+
+
+def test_the_real_import_never_prints_a_secret_and_leaves_no_certificate_behind(
+ stand_in, tmp_path: Path
+) -> None:
+ result, _calls = _run_import(stand_in, tmp_path, _DEVELOPER_ID_IDENTITIES)
+
+ assert result.returncode == 0, result.stderr
+ for secret in ("TOPSECRET-P12-PAYLOAD", "TOPSECRET-P12-PASSWORD"):
+ assert secret not in result.stdout + result.stderr
+ assert list((tmp_path / "scratch").iterdir()) == []
+
+
+def test_a_failed_import_leaves_neither_the_certificate_nor_the_keychain_behind(
+ stand_in, tmp_path: Path
+) -> None:
+ """A wrong password aborts at `security import`; the trap must still clean up.
+
+ On a runner the machine is thrown away; on a maintainer's Mac it is not, and
+ the decoded certificate is the private key.
+ """
+ result, calls = _run_import(stand_in, tmp_path, _DEVELOPER_ID_IDENTITIES, FAKE_IMPORT_FAILS="1")
+
+ assert result.returncode != 0
+ assert list((tmp_path / "scratch").iterdir()) == []
+ assert calls[-2].startswith("list-keychains -d user -s /Users/runner/")
+ assert calls[-1].startswith("delete-keychain ")
+ assert "find-identity" not in [call.split()[0] for call in calls]
+
+
+# --- entitlements: validated and normalised before codesign embeds them -------
+
+_FAKE_PLUTIL = """#!/usr/bin/env bash
+# Stand-in for macOS `plutil`: log every call; `-convert xml1 -o OUT IN` copies.
+printf '%s\\n' "$*" >> "${FAKE_PLUTIL_LOG}"
+case "$1" in
+ -lint) [ -z "${FAKE_PLUTIL_LINT_FAILS:-}" ] || { echo "not a property list" >&2; exit 1; } ;;
+ -convert) cp "$5" "$4" ;;
+esac
+exit 0
+"""
+
+
+def _with_fake_plutil(tmp_path: Path) -> dict[str, str]:
+ bin_dir = tmp_path / "plutil-bin"
+ bin_dir.mkdir()
+ tool = bin_dir / "plutil"
+ tool.write_text(_FAKE_PLUTIL, encoding="utf-8")
+ tool.chmod(0o755)
+ log_file = tmp_path / "plutil.log"
+ log_file.write_text("", encoding="utf-8")
+ return {
+ "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}",
+ "FAKE_PLUTIL_LOG": str(log_file),
+ }
+
+
+def test_with_plutil_the_entitlements_are_linted_and_normalised_before_signing(
+ layout: Path, tmp_path: Path
+) -> None:
+ env = _with_fake_plutil(tmp_path)
+
+ result = _rehearse(
+ layout,
+ APPLE_SIGNING_IDENTITY="Developer ID Application: Example (ABCDE12345)",
+ **env,
+ )
+
+ assert result.returncode == 0, result.stderr
+ out = result.stdout
+ source = str(layout / "packaging" / "macos" / "entitlements.plist")
+ normalized = str(layout / "dist" / "entitlements.normalized.plist")
+ lint = f"plutil -lint {source}"
+ convert = f"plutil -convert xml1 -o {normalized} {source}"
+ sign = "codesign --force --deep --timestamp --options runtime"
+ assert lint in out and convert in out
+ assert out.index(lint) < out.index(convert) < out.index(sign)
+ # codesign embeds the normalised copy, never the tracked file directly.
+ signing_line = next(line for line in out.splitlines() if line.startswith(f"+ {sign}"))
+ assert f"--entitlements {normalized}" in out[out.index(sign) :]
+ assert source not in signing_line
+
+
+def test_an_ad_hoc_build_embeds_no_entitlements_so_plutil_is_never_asked(
+ layout: Path, tmp_path: Path
+) -> None:
+ result = _rehearse(layout, **_with_fake_plutil(tmp_path))
+
+ assert result.returncode == 0, result.stderr
+ assert "entitlements" not in result.stdout.lower()
+ assert "plutil" not in result.stdout
+
+
[email protected](shutil.which("plutil") is not None, reason="this host has a real plutil")
+def test_without_plutil_the_entitlements_file_is_used_as_it_is(layout: Path) -> None:
+ result = _rehearse(
+ layout,
+ APPLE_SIGNING_IDENTITY="Developer ID Application: Example (ABCDE12345)",
+ )
+
+ assert result.returncode == 0, result.stderr
+ source = str(layout / "packaging" / "macos" / "entitlements.plist")
+ assert "plutil not found" in result.stdout
+ assert f"--entitlements {source}" in result.stdout
+ assert "entitlements.normalized.plist" not in result.stdout
+
+
+def _function_text(name: str) -> str:
+ """One function of build.sh, cut out by its own opening line and closing brace."""
+ script = BUILD_SH.read_text(encoding="utf-8")
+ start = script.index(f"\n{name}() {{\n") + 1
+ end = script.index("\n}\n", start) + 3
+ return script[start:end]
+
+
+def _run_prepare(tmp_path: Path, **env: str) -> tuple[subprocess.CompletedProcess[str], Path, Path]:
+ """Run build.sh's own prepare_entitlements() for real against a stand-in plutil."""
+ source = tmp_path / "entitlements.plist"
+ source.write_text("<plist><dict/></plist>\n", encoding="utf-8")
+ normalized = tmp_path / "dist" / "entitlements.normalized.plist"
+ harness = tmp_path / "prepare.sh"
+ harness.write_text(
+ "#!/usr/bin/env bash\n"
+ "set -euo pipefail\n"
+ "DRY_RUN=0\n"
+ f"DIST_DIR={tmp_path / 'dist'}\n"
+ f"ENTITLEMENTS={source}\n"
+ f"NORMALIZED_ENTITLEMENTS={normalized}\n"
+ 'SIGNING_ENTITLEMENTS="${ENTITLEMENTS}"\n'
+ "log() { printf '[macos-build] %s\\n' \"$*\"; }\n"
+ + _function_text("run")
+ + _function_text("prepare_entitlements")
+ + 'prepare_entitlements\necho "SIGNING_ENTITLEMENTS=${SIGNING_ENTITLEMENTS}"\n',
+ encoding="utf-8",
+ )
+ clean = {"HOME": str(tmp_path), **_with_fake_plutil(tmp_path), **env}
+ result = subprocess.run(
+ ["bash", str(harness)],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ env=clean,
+ check=False,
+ )
+ return result, source, normalized
+
+
+def test_the_real_prepare_step_signs_with_a_normalised_copy_and_leaves_the_source_alone(
+ tmp_path: Path,
+) -> None:
+ result, source, normalized = _run_prepare(tmp_path)
+
+ assert result.returncode == 0, result.stderr
+ assert f"SIGNING_ENTITLEMENTS={normalized}" in result.stdout
+ assert normalized.is_file()
+ assert source.read_text(encoding="utf-8") == "<plist><dict/></plist>\n"
+ calls = (tmp_path / "plutil.log").read_text(encoding="utf-8").splitlines()
+ assert calls == [f"-lint {source}", f"-convert xml1 -o {normalized} {source}"]
+
+
+def test_a_malformed_entitlements_file_fails_before_any_signing(tmp_path: Path) -> None:
+ result, _source, normalized = _run_prepare(tmp_path, FAKE_PLUTIL_LINT_FAILS="1")
+
+ assert result.returncode != 0
+ assert "SIGNING_ENTITLEMENTS=" not in result.stdout
+ assert not normalized.exists()
+ calls = (tmp_path / "plutil.log").read_text(encoding="utf-8").splitlines()
+ assert [call.split()[0] for call in calls] == ["-lint"] # never reached -convert
diff --git a/tests/unit/packaging/test_macos_privacy_strings.py b/tests/unit/packaging/test_macos_privacy_strings.py
new file mode 100644
index 0000000000..4b4bd4b9c2
--- /dev/null
+++ b/tests/unit/packaging/test_macos_privacy_strings.py
@@ -0,0 +1,502 @@
+"""The macOS usage-description strings have exactly one source, and both bundles read it.
+
+``jarvis/core/macos_privacy_strings.py`` holds the single table of
+``NS...UsageDescription`` strings. The downloadable ``.dmg`` app (``jarvis.spec``,
+evaluated by PyInstaller before the package is importable) and the managed
+source-install app (``macos_app_bundle._bundle_plist``) both load THAT FILE BY
+PATH. These tests pin the table's shape and prove that the spec's plist dict, the
+managed bundle's plist and the table agree - including that neither carries a
+private copy - and that ``entitlements.plist`` stays comment-free and
+camera-free.
+
+Everything here runs off macOS: the real ``jarvis.spec`` is executed against
+stand-in PyInstaller names (it needs no Mac to describe its own ``Info.plist``).
+What a real Mac does with these strings is not checked and stays unverified.
+"""
+
+from __future__ import annotations
+
+import ast
+import importlib.util
+import plistlib
+import re
+import shutil
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+import jarvis.setup.macos_app_bundle as mab
+from jarvis.core import macos_privacy_strings as table_module
+from jarvis.core.branding import PRODUCT_NAME
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+SPEC_PATH = REPO_ROOT / "jarvis.spec"
+TABLE_PATH = REPO_ROOT / "jarvis" / "core" / "macos_privacy_strings.py"
+ENTITLEMENTS_PATH = REPO_ROOT / "packaging" / "macos" / "entitlements.plist"
+
+EXPECTED_KEYS = (
+ "NSMicrophoneUsageDescription",
+ "NSScreenCaptureUsageDescription",
+ "NSAppleEventsUsageDescription",
+ "NSDesktopFolderUsageDescription",
+ "NSDocumentsFolderUsageDescription",
+ "NSDownloadsFolderUsageDescription",
+ "NSRemovableVolumesUsageDescription",
+ "NSNetworkVolumesUsageDescription",
+ "NSLocalNetworkUsageDescription",
+)
+REMOVED_KEYS = (
+ "NSCameraUsageDescription",
+ "NSSpeechRecognitionUsageDescription",
+ "NSSystemAdministrationUsageDescription",
+)
+SENTINEL = "SENTINEL usage string that only the edited table carries."
+
+
+def _load_by_path(path: Path) -> types.ModuleType:
+ """Exactly what ``jarvis.spec`` and ``macos_app_bundle`` do to read the table."""
+ loader_spec = importlib.util.spec_from_file_location("_table_under_test", path)
+ assert loader_spec is not None and loader_spec.loader is not None
+ module = importlib.util.module_from_spec(loader_spec)
+ loader_spec.loader.exec_module(module)
+ return module
+
+
+# --- the table itself ----------------------------------------------------------
+
+
+def test_the_table_holds_exactly_the_keys_jarvis_has_a_caller_for() -> None:
+ assert table_module.REQUIRED_USAGE_KEYS == EXPECTED_KEYS
+ assert tuple(table_module.usage_descriptions()) == EXPECTED_KEYS
+ assert table_module.REMOVED_USAGE_KEYS == REMOVED_KEYS
+ assert not set(table_module.usage_descriptions()) & set(REMOVED_KEYS)
+
+
+def test_every_string_is_one_plain_english_sentence_that_names_the_product() -> None:
+ for key, text in table_module.usage_descriptions().items():
+ assert text == text.strip(), key
+ assert text.isascii(), f"{key} must stay plain ASCII"
+ assert "\n" not in text, key
+ assert text.startswith(PRODUCT_NAME), key
+ assert text.endswith("."), f"{key} needs a closing period"
+ assert text.count(". ") == 0 and text.count(".") == 1, f"{key} must be ONE sentence"
+ assert 20 <= len(text.encode("utf-8")) < 4000, key
+
+
+def test_the_product_name_equals_the_branding_constant() -> None:
+ """The table may not import the package, so a test keeps its literal honest."""
+ assert table_module.PRODUCT_NAME == PRODUCT_NAME
+
+
+def test_each_string_names_the_feature_that_triggers_the_request() -> None:
+ texts = table_module.usage_descriptions()
+ assert "dictate" in texts["NSMicrophoneUsageDescription"]
+ assert "wake word" in texts["NSMicrophoneUsageDescription"]
+ assert "screen" in texts["NSScreenCaptureUsageDescription"]
+ # Target-neutral: macOS names the controlled app in the dialog itself, and the
+ # same string serves Music, Spotify and Terminal, so it names none of them.
+ apple_events = texts["NSAppleEventsUsageDescription"]
+ assert "other apps" in apple_events
+ for target in ("Music", "Spotify", "Terminal"):
+ assert target not in apple_events
+ assert "Desktop" in texts["NSDesktopFolderUsageDescription"]
+ assert "Documents" in texts["NSDocumentsFolderUsageDescription"]
+ assert "Downloads" in texts["NSDownloadsFolderUsageDescription"]
+ assert "external drive" in texts["NSRemovableVolumesUsageDescription"]
+ assert "network drive" in texts["NSNetworkVolumesUsageDescription"]
+ # The old text claimed the app "serves its own interface to your browser";
+ # the local-network prompt is about the hosts the person configures.
+ assert "local network" in texts["NSLocalNetworkUsageDescription"]
+ assert "serves" not in texts["NSLocalNetworkUsageDescription"]
+
+
+def test_usage_descriptions_returns_a_fresh_dict_each_call() -> None:
+ first = table_module.usage_descriptions()
+ first["NSMicrophoneUsageDescription"] = "changed"
+ first["NSCameraUsageDescription"] = "added"
+
+ assert table_module.usage_descriptions()["NSMicrophoneUsageDescription"] != "changed"
+ assert "NSCameraUsageDescription" not in table_module.usage_descriptions()
+
+
+def test_the_module_is_standard_library_only_and_does_nothing_at_import() -> None:
+ """Loadable by path before the package exists (AP-26: no import-time work)."""
+ tree = ast.parse(TABLE_PATH.read_text(encoding="utf-8"))
+ imported = {
+ alias.name.split(".")[0]
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Import)
+ for alias in node.names
+ } | {
+ (node.module or "").split(".")[0]
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ImportFrom)
+ }
+ assert imported <= {"__future__", "pathlib"}, imported
+ top_level_calls = [
+ node
+ for node in tree.body
+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call)
+ ]
+ assert top_level_calls == []
+
+
+def test_loading_by_path_and_importing_give_the_same_table() -> None:
+ by_path = _load_by_path(TABLE_PATH)
+
+ assert by_path.usage_descriptions() == table_module.usage_descriptions()
+ assert by_path.REQUIRED_USAGE_KEYS == table_module.REQUIRED_USAGE_KEYS
+ assert Path(table_module.__file__).resolve() == TABLE_PATH.resolve()
+
+
+# --- the .dmg app: jarvis.spec -------------------------------------------------
+
+
+def _exec_spec(monkeypatch: pytest.MonkeyPatch, root: Path) -> dict:
+ """Run the real ``jarvis.spec`` with stand-in PyInstaller names; return BUNDLE's kwargs."""
+ calls: dict[str, dict] = {}
+
+ def recorder(name: str):
+ def _call(*args: object, **kwargs: object) -> types.SimpleNamespace:
+ calls[name] = kwargs
+ return types.SimpleNamespace(
+ pure=[], zipped_data=[], scripts=[], binaries=[], zipfiles=[], datas=[]
+ )
+
+ return _call
+
+ hooks = types.ModuleType("PyInstaller.utils.hooks")
+ hooks.collect_data_files = lambda *a, **k: [] # type: ignore[attr-defined]
+ hooks.collect_submodules = lambda *a, **k: [] # type: ignore[attr-defined]
+ hooks.copy_metadata = lambda *a, **k: [] # type: ignore[attr-defined]
+ for name, module in (
+ ("PyInstaller", types.ModuleType("PyInstaller")),
+ ("PyInstaller.utils", types.ModuleType("PyInstaller.utils")),
+ ("PyInstaller.utils.hooks", hooks),
+ # The spec probes these optional packages with __import__; stand-ins keep
+ # a real (possibly platform-specific) import from running under a fake OS.
+ ("webview", types.ModuleType("webview")),
+ ("pystray", types.ModuleType("pystray")),
+ ("PIL", types.ModuleType("PIL")),
+ ):
+ monkeypatch.setitem(sys.modules, name, module)
+ monkeypatch.setattr(sys, "platform", "darwin")
+
+ namespace: dict[str, object] = {
+ "SPECPATH": str(root),
+ "__file__": str(root / "jarvis.spec"),
+ }
+ for builtin in ("Analysis", "PYZ", "EXE", "COLLECT", "BUNDLE"):
+ namespace[builtin] = recorder(builtin)
+ source = (root / "jarvis.spec").read_text(encoding="utf-8")
+ exec(compile(source, str(root / "jarvis.spec"), "exec"), namespace) # noqa: S102
+ assert "BUNDLE" in calls, "the spec must build a BUNDLE on darwin"
+ return calls["BUNDLE"]
+
+
+def spec_root(tmp_path: Path) -> Path:
+ """A minimal checkout: the real spec, the real table, a version file."""
+ root = tmp_path / "checkout"
+ (root / "jarvis" / "core").mkdir(parents=True)
+ (root / "jarvis" / "__init__.py").write_text('__version__ = "9.9.9"\n', encoding="utf-8")
+ shutil.copy2(TABLE_PATH, root / "jarvis" / "core" / "macos_privacy_strings.py")
+ shutil.copy2(SPEC_PATH, root / "jarvis.spec")
+ return root
+
+
+def test_the_spec_plist_carries_every_string_of_the_table_and_no_removed_key(
+ monkeypatch: pytest.MonkeyPatch, spec_root: Path
+) -> None:
+ bundle = _exec_spec(monkeypatch, spec_root)
+ info = bundle["info_plist"]
+
+ expected = table_module.usage_descriptions()
+ assert {key: info[key] for key in EXPECTED_KEYS} == expected
+ for key in REMOVED_KEYS:
+ assert key not in info, f"{key} has no caller and must not ship"
+ assert {
+ key for key in info if key.startswith("NS") and key.endswith("UsageDescription")
+ } == set(EXPECTED_KEYS)
+ # The rest of the plist is the app's identity and is unchanged by the move.
+ assert info["CFBundleIdentifier"] == "ai.personaljarvis.desktop"
+ assert info["LSBackgroundOnly"] is False
+ assert info["CFBundleVersion"] == "9.9.9"
+ # PyInstaller writes the dict with plistlib, so it must serialise.
+ assert plistlib.loads(plistlib.dumps(info)) == info
+
+
+def test_the_spec_reads_the_table_by_path_and_keeps_no_copy(
+ monkeypatch: pytest.MonkeyPatch, spec_root: Path
+) -> None:
+ """Edit the table beside the spec: the spec's plist follows, so it is not a copy."""
+ table = spec_root / "jarvis" / "core" / "macos_privacy_strings.py"
+ text = table.read_text(encoding="utf-8")
+ table.write_text(
+ text + f'\n_USAGE_DESCRIPTIONS["NSMicrophoneUsageDescription"] = "{SENTINEL}"\n',
+ encoding="utf-8",
+ )
+
+ info = _exec_spec(monkeypatch, spec_root)["info_plist"]
+
+ assert info["NSMicrophoneUsageDescription"] == SENTINEL
+
+
+def test_neither_the_spec_nor_the_managed_bundle_spells_a_usage_key_itself() -> None:
+ """A quoted ``"NS...UsageDescription"`` literal outside the table is a private copy."""
+ literal = re.compile(r"""["']NS\w+UsageDescription["']""")
+ for path in (SPEC_PATH, Path(mab.__file__)):
+ found = literal.findall(path.read_text(encoding="utf-8"))
+ assert found == [], f"{path.name} carries its own usage keys: {found}"
+
+
+# --- the managed app: macos_app_bundle ----------------------------------------
+
+
+def test_the_managed_bundle_plist_carries_the_same_table() -> None:
+ info = mab._bundle_plist()
+
+ assert {key: info[key] for key in EXPECTED_KEYS} == table_module.usage_descriptions()
+ for key in REMOVED_KEYS:
+ assert key not in info
+ assert info["CFBundleIdentifier"] == "com.personal-jarvis.desktop"
+
+
+def test_the_managed_bundle_reads_the_table_by_path(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ edited = tmp_path / "macos_privacy_strings.py"
+ edited.write_text(
+ TABLE_PATH.read_text(encoding="utf-8")
+ + f'\n_USAGE_DESCRIPTIONS["NSNetworkVolumesUsageDescription"] = "{SENTINEL}"\n',
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(mab, "_PRIVACY_STRINGS_PATH", edited)
+
+ assert mab._bundle_plist()["NSNetworkVolumesUsageDescription"] == SENTINEL
+
+
+def test_a_missing_table_file_is_loud_not_an_empty_plist(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr(mab, "_PRIVACY_STRINGS_PATH", tmp_path / "nowhere.py")
+
+ with pytest.raises(FileNotFoundError):
+ mab._bundle_plist()
+
+
+def test_both_bundles_agree_on_every_usage_string(
+ monkeypatch: pytest.MonkeyPatch, spec_root: Path
+) -> None:
+ """The headline parity: the .dmg app and the managed app show the same dialogs."""
+ dmg = _exec_spec(monkeypatch, spec_root)["info_plist"]
+ managed = mab._bundle_plist()
+
+ def usage(info: dict) -> dict:
+ return {k: v for k, v in info.items() if k.endswith("UsageDescription")}
+
+ assert usage(dmg) == usage(managed) == table_module.usage_descriptions()
+
+
+# --- entitlements.plist --------------------------------------------------------
+
+
+def test_entitlements_plist_has_no_xml_comments() -> None:
+ """Apple documents no comment syntax for entitlements; the reasoning is in the README."""
+ assert "<!--" not in ENTITLEMENTS_PATH.read_text(encoding="utf-8")
+
+
+def test_entitlements_plist_parses_and_requests_exactly_the_four_justified_rights() -> None:
+ entitlements = plistlib.loads(ENTITLEMENTS_PATH.read_bytes())
+
+ assert entitlements == {
+ "com.apple.security.device.audio-input": True,
+ "com.apple.security.automation.apple-events": True,
+ "com.apple.security.cs.allow-unsigned-executable-memory": True,
+ "com.apple.security.cs.disable-library-validation": True,
+ }
+
+
+def test_the_camera_entitlement_is_gone_and_the_readme_says_why() -> None:
+ assert "device.camera" not in ENTITLEMENTS_PATH.read_text(encoding="utf-8")
+ readme = (REPO_ROOT / "packaging" / "macos" / "README.md").read_text(encoding="utf-8")
+ assert "com.apple.security.device.camera" in readme # the "Removed:" paragraph
+ for entitlement in plistlib.loads(ENTITLEMENTS_PATH.read_bytes()):
+ assert f"`{entitlement}`" in readme, f"README must keep the reasoning for {entitlement}"
+
+
+# --- the English folder sentences stay short -----------------------------------
+
+
+def test_the_folder_strings_do_not_promise_saving_or_creating() -> None:
+ """The system dialog already names the folder; the sentence only says "works with"."""
+ texts = table_module.usage_descriptions()
+ for key in (
+ "NSDesktopFolderUsageDescription",
+ "NSDocumentsFolderUsageDescription",
+ "NSDownloadsFolderUsageDescription",
+ "NSRemovableVolumesUsageDescription",
+ "NSNetworkVolumesUsageDescription",
+ ):
+ lowered = texts[key].lower()
+ assert "saves" not in lowered and "creates" not in lowered, key
+ assert "works with files" in lowered, key
+
+
+# --- German and Spanish: both bundles ship the same InfoPlist.strings -----------
+
+
+def _parse_strings(text: str) -> dict[str, str]:
+ """Read back an ``InfoPlist.strings`` file (``"key" = "value";`` lines, escapes undone)."""
+ parsed: dict[str, str] = {}
+ for line in text.splitlines():
+ if not line.strip() or line.startswith("/*"):
+ continue
+ match = re.fullmatch(r'"(?P<key>[A-Za-z]+)" = "(?P<value>(?:[^"\\]|\\.)*)";', line)
+ assert match is not None, f"not a .strings line: {line!r}"
+ parsed[match["key"]] = (
+ match["value"].replace('\\"', '"').replace("\\n", "\n").replace("\\\\", "\\")
+ )
+ return parsed
+
+
+def test_the_localised_tables_cover_exactly_the_required_keys() -> None:
+ assert table_module.LOCALIZATIONS == ("en", "de", "es")
+ assert table_module.DEVELOPMENT_REGION == "en"
+ assert table_module.LOCALIZED_LANGUAGES == ("de", "es")
+ english = table_module.usage_descriptions()
+ for language in table_module.LOCALIZED_LANGUAGES:
+ localised = table_module.localized_usage_descriptions(language)
+ assert tuple(localised) == table_module.REQUIRED_USAGE_KEYS, language
+ for key, text in localised.items():
+ assert text == text.strip() and "\n" not in text, (language, key)
+ assert text.startswith(PRODUCT_NAME), (language, key)
+ assert text.endswith("."), (language, key)
+ assert text.count(".") == 1, f"{language} {key} must be ONE sentence"
+ assert text != english[key], f"{language} {key} is still English"
+
+
+def test_the_apple_events_string_is_target_neutral_in_every_language() -> None:
+ for language in table_module.LOCALIZED_LANGUAGES:
+ text = table_module.localized_usage_descriptions(language)["NSAppleEventsUsageDescription"]
+ for target in ("Music", "Spotify", "Terminal"):
+ assert target not in text, (language, target)
+
+
+def test_localised_dicts_are_fresh_copies() -> None:
+ first = table_module.localized_usage_descriptions("de")
+ first["NSMicrophoneUsageDescription"] = "changed"
+ assert table_module.localized_usage_descriptions("de")["NSMicrophoneUsageDescription"] != (
+ "changed"
+ )
+ keys = table_module.localization_plist_keys()
+ keys["CFBundleLocalizations"].append("fr")
+ assert table_module.localization_plist_keys()["CFBundleLocalizations"] == ["en", "de", "es"]
+
+
[email protected]("language", ["de", "es"])
+def test_the_strings_file_round_trips_the_table(language: str) -> None:
+ text = table_module.info_plist_strings_text(language)
+
+ assert text.endswith("\n") and "\r" not in text
+ assert _parse_strings(text) == table_module.localized_usage_descriptions(language)
+
+
+def test_the_strings_file_escapes_quotes_backslashes_and_newlines(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tricky = 'Say "hi" \\ there\nnext'
+ monkeypatch.setitem(
+ table_module._LOCALIZED_USAGE_DESCRIPTIONS["de"], "NSMicrophoneUsageDescription", tricky
+ )
+
+ parsed = _parse_strings(table_module.info_plist_strings_text("de"))
+
+ assert parsed["NSMicrophoneUsageDescription"] == tricky
+
+
+def test_write_localizations_creates_one_lproj_per_language(tmp_path: Path) -> None:
+ resources = tmp_path / "Contents" / "Resources"
+
+ written = table_module.write_localizations(resources)
+
+ assert sorted(path.relative_to(resources).as_posix() for path in written) == [
+ "de.lproj/InfoPlist.strings",
+ "es.lproj/InfoPlist.strings",
+ ]
+ for language in table_module.LOCALIZED_LANGUAGES:
+ raw = (resources / f"{language}.lproj" / "InfoPlist.strings").read_bytes()
+ assert raw.decode("utf-8") == table_module.info_plist_strings_text(language)
+ # English is the base Info.plist text: there is deliberately no en.lproj.
+ assert not (resources / "en.lproj").exists()
+
+
+def test_write_localizations_is_repeatable(tmp_path: Path) -> None:
+ table_module.write_localizations(tmp_path)
+ table_module.write_localizations(tmp_path)
+
+ assert sorted(path.name for path in tmp_path.iterdir()) == ["de.lproj", "es.lproj"]
+
+
+def test_the_spec_declares_the_localisations(
+ monkeypatch: pytest.MonkeyPatch, spec_root: Path
+) -> None:
+ info = _exec_spec(monkeypatch, spec_root)["info_plist"]
+
+ assert info["CFBundleLocalizations"] == ["en", "de", "es"]
+ assert info["CFBundleDevelopmentRegion"] == "en"
+ assert plistlib.loads(plistlib.dumps(info)) == info
+
+
+def test_the_managed_bundle_declares_the_same_localisations() -> None:
+ info = mab._bundle_plist()
+
+ assert info["CFBundleLocalizations"] == ["en", "de", "es"]
+ assert info["CFBundleDevelopmentRegion"] == "en"
+ # No format bump: a bump would rebuild every installed bundle and re-ask every
+ # permission after an ad-hoc rebuild (see the comment above _BUNDLE_FORMAT_VERSION).
+ assert info["JarvisBundleFormatVersion"] == 3
+
+
+def test_the_managed_bundle_layout_carries_the_lproj_files(tmp_path: Path) -> None:
+ bundle = mab._write_cross_platform_fixture_bundle(tmp_path / mab.APP_DIR_NAME)
+
+ for language in table_module.LOCALIZED_LANGUAGES:
+ strings = bundle / "Contents" / "Resources" / f"{language}.lproj" / "InfoPlist.strings"
+ assert _parse_strings(strings.read_text(encoding="utf-8")) == (
+ table_module.localized_usage_descriptions(language)
+ )
+
+
+def test_both_bundles_write_the_same_strings_files(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """The .dmg build step and the managed layout read ONE table, so the files agree."""
+ helper_path = REPO_ROOT / "packaging" / "macos" / "add_localizations.py"
+ loader_spec = importlib.util.spec_from_file_location("_add_localizations", helper_path)
+ assert loader_spec is not None and loader_spec.loader is not None
+ helper = importlib.util.module_from_spec(loader_spec)
+ loader_spec.loader.exec_module(helper)
+
+ dmg_app = tmp_path / "dmg" / "Personal Jarvis.app"
+ (dmg_app / "Contents").mkdir(parents=True)
+ (dmg_app / "Contents" / "Info.plist").write_bytes(plistlib.dumps({}))
+ helper.add_localizations(dmg_app)
+ managed = mab._write_cross_platform_fixture_bundle(tmp_path / "managed" / mab.APP_DIR_NAME)
+
+ for language in table_module.LOCALIZED_LANGUAGES:
+ relative = Path("Contents") / "Resources" / f"{language}.lproj" / "InfoPlist.strings"
+ assert (dmg_app / relative).read_bytes() == (managed / relative).read_bytes()
+
+
+def test_the_build_helper_refuses_a_directory_that_is_not_an_app(tmp_path: Path) -> None:
+ helper_path = REPO_ROOT / "packaging" / "macos" / "add_localizations.py"
+ loader_spec = importlib.util.spec_from_file_location("_add_localizations2", helper_path)
+ assert loader_spec is not None and loader_spec.loader is not None
+ helper = importlib.util.module_from_spec(loader_spec)
+ loader_spec.loader.exec_module(helper)
+
+ assert helper.main(["--app", str(tmp_path / "Nothing.app")]) == 1
+ assert not (tmp_path / "Nothing.app").exists()
diff --git a/tests/unit/platform/test_fake_tcc.py b/tests/unit/platform/test_fake_tcc.py
new file mode 100644
index 0000000000..31ad4f330a
--- /dev/null
+++ b/tests/unit/platform/test_fake_tcc.py
@@ -0,0 +1,899 @@
+"""Self-tests of ``tests/fakes/fake_tcc.py``.
+
+A fake that consumer tests lean on must itself be pinned: if the simulator
+drifts, every test built on it proves nothing. These tests cover the state
+machine, the scripted dialog policy, "macOS does not re-ask", the frozen Screen
+Recording preflight, Accessibility without ``not_determined``, the tap-before-
+request auto-deny, the Automation OSStatus values, the implicit-prompt
+companions and the ordered call log. A last group runs the REAL
+``SystemPermissionPort`` on top of the fake.
+
+What these tests pin is the MODEL. Where the model encodes behaviour that Apple
+does not document, the fake's module docstring says so; nothing here is a claim
+about a real Mac.
+"""
+
+from __future__ import annotations
+
+import threading
+from typing import Any
+
+import pytest
+
+from jarvis.platform.permissions import AUTOMATION_TARGETS, PermissionId, PermissionState
+from tests.fakes.fake_tcc import (
+ AE_EVENT_NOT_PERMITTED,
+ AE_EVENT_WOULD_REQUIRE_USER_CONSENT,
+ AE_NO_ERR,
+ AE_PROC_NOT_FOUND,
+ DMG_BUNDLE_ID,
+ TERMINAL_BUNDLE_ID,
+ CallKind,
+ CallOutcome,
+ DialogPolicy,
+ FakeAudioInput,
+ FakeEventTap,
+ FakeScreenGrab,
+ FakeTCC,
+ TccProcessAbort,
+ TccService,
+ TccState,
+ install_port,
+ make_darwin_port,
+ make_non_darwin_port,
+)
+
+MIC = TccService.MICROPHONE
+SCREEN = TccService.SCREEN_RECORDING
+AX = TccService.ACCESSIBILITY
+INPUT = TccService.INPUT_MONITORING
+POST = TccService.POST_EVENT
+AUTOMATION = TccService.AUTOMATION
+MUSIC = "com.apple.Music"
+SPOTIFY = "com.spotify.client"
+
+
+def _av(tcc: FakeTCC) -> Any:
+ return tcc.modules["AVFoundation"].AVCaptureDevice
+
+
+def _request_mic(tcc: FakeTCC) -> list[bool]:
+ """Fire the microphone request; the list collects what the handler reported."""
+ answers: list[bool] = []
+ _av(tcc).requestAccessForMediaType_completionHandler_("soun", answers.append)
+ return answers
+
+
+def _mic_status(tcc: FakeTCC) -> int:
+ return _av(tcc).authorizationStatusForMediaType_("soun")
+
+
+def _prompt_ax(tcc: FakeTCC) -> bool:
+ services = tcc.modules["ApplicationServices"]
+ return services.AXIsProcessTrustedWithOptions({services.kAXTrustedCheckOptionPrompt: True})
+
+
+# --- state machine -----------------------------------------------------------
+
+
+def test_every_service_starts_before_its_first_question() -> None:
+ tcc = FakeTCC()
+
+ assert tcc.state(MIC) is TccState.NOT_DETERMINED
+ assert tcc.state(SCREEN) is TccState.NOT_DETERMINED
+ assert tcc.state(INPUT) is TccState.NOT_DETERMINED
+ assert tcc.state(AUTOMATION, MUSIC) is TccState.NOT_DETERMINED
+ # Accessibility has no not_determined: untrusted reads as denied. Event
+ # posting is an alias and follows it.
+ assert tcc.state(AX) is TccState.DENIED
+ assert tcc.state(POST) is TccState.DENIED
+ tcc.assert_silent() # inspecting the model is not a framework call
+
+
+ ("policy", "final", "reported"),
+ [
+ (DialogPolicy.ALLOW, TccState.GRANTED, [True]),
+ (DialogPolicy.DENY, TccState.DENIED, [False]),
+ # A dialog closed without an answer: the DIALOG class stays unanswered
+ # and the completion handler never runs (unverified model).
+ (DialogPolicy.DISMISS, TccState.NOT_DETERMINED, []),
+ ],
+)
+def test_microphone_dialog_policies(
+ policy: DialogPolicy, final: TccState, reported: list[bool]
+) -> None:
+ tcc = FakeTCC(default_policy=policy)
+
+ answers = _request_mic(tcc)
+
+ assert tcc.state(MIC) is final
+ assert answers == reported
+ (request,) = tcc.requests(MIC)
+ assert request.outcome is CallOutcome.DIALOG_SHOWN
+ assert request.detail == policy.value
+ assert (request.state_before, request.state_after) == (TccState.NOT_DETERMINED, final)
+
+
+def test_the_status_api_reports_the_av_authorization_values() -> None:
+ tcc = FakeTCC()
+ assert _mic_status(tcc) == 0
+ tcc.grant(MIC)
+ assert _mic_status(tcc) == 3
+ tcc.deny(MIC)
+ assert _mic_status(tcc) == 2
+ tcc.restrict(MIC)
+ assert _mic_status(tcc) == 1
+
+
+def test_a_prompt_once_service_dismissed_ends_denied() -> None:
+ """Closing the Screen Recording dialog leaves the app registered, switch off."""
+ tcc = FakeTCC(default_policy=DialogPolicy.DISMISS)
+
+ tcc.modules["Quartz"].CGRequestScreenCaptureAccess()
+
+ assert tcc.state(SCREEN) is TccState.DENIED
+
+
+def test_a_never_answered_dialog_stays_open_until_the_test_answers() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ first = _request_mic(tcc)
+ second = _request_mic(tcc)
+
+ assert tcc.dialog_open(MIC) is True
+ assert tcc.state(MIC) is TccState.NOT_DETERMINED
+ assert first == [] and second == []
+ # A second request does not stack a second dialog.
+ assert [call.outcome for call in tcc.requests(MIC)] == [
+ CallOutcome.DIALOG_SHOWN,
+ CallOutcome.DIALOG_ALREADY_OPEN,
+ ]
+ assert len(tcc.dialogs_shown(MIC)) == 1
+
+ tcc.answer(MIC, DialogPolicy.ALLOW)
+
+ assert tcc.dialog_open(MIC) is False
+ assert tcc.state(MIC) is TccState.GRANTED
+ assert first == [True] and second == [True]
+
+
+def test_answering_a_dialog_that_is_not_open_is_an_error() -> None:
+ with pytest.raises(LookupError):
+ FakeTCC().answer(MIC)
+
+
+def test_scripted_policies_apply_per_dialog_then_the_default_takes_over() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.ALLOW)
+ tcc.script(MIC, DialogPolicy.DENY)
+
+ _request_mic(tcc)
+ assert tcc.state(MIC) is TccState.DENIED
+
+ tcc.reset(MIC)
+ _request_mic(tcc)
+ assert tcc.state(MIC) is TccState.GRANTED
+
+
+def test_a_sticky_policy_is_per_service() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.ALLOW)
+ tcc.set_policy(SCREEN, DialogPolicy.DENY)
+
+ _request_mic(tcc)
+ tcc.modules["Quartz"].CGRequestScreenCaptureAccess()
+
+ assert tcc.state(MIC) is TccState.GRANTED
+ assert tcc.state(SCREEN) is TccState.DENIED
+
+
+def test_a_grant_in_settings_closes_an_open_dialog() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ answers = _request_mic(tcc)
+
+ tcc.grant(MIC)
+
+ assert tcc.dialog_open(MIC) is False
+ assert answers == [True]
+
+
+# --- macOS does not re-ask ----------------------------------------------------
+
+
+def test_a_request_after_a_denial_is_ignored_and_recorded() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.DENY)
+ _request_mic(tcc)
+ tcc.default_policy = DialogPolicy.ALLOW # the user would say yes - but is never asked
+
+ answers = _request_mic(tcc)
+
+ assert tcc.state(MIC) is TccState.DENIED
+ assert answers == [False] # the handler reports the answer on file
+ assert len(tcc.dialogs_shown(MIC)) == 1
+ (ignored,) = tcc.ignored_requests(MIC)
+ assert ignored.state_before is TccState.DENIED
+
+
+def test_a_request_while_granted_shows_nothing() -> None:
+ tcc = FakeTCC(granted=[MIC])
+
+ answers = _request_mic(tcc)
+
+ assert answers == [True]
+ assert tcc.dialogs_shown() == []
+ assert len(tcc.ignored_requests(MIC)) == 1
+
+
+def test_a_restricted_service_never_asks_and_never_grants() -> None:
+ tcc = FakeTCC()
+ tcc.restrict(MIC)
+
+ answers = _request_mic(tcc)
+
+ assert answers == [False]
+ assert tcc.state(MIC) is TccState.RESTRICTED
+ assert [call.outcome for call in tcc.requests(MIC)] == [CallOutcome.RESTRICTED]
+ assert tcc.dialogs_shown() == []
+
+
+# --- Screen Recording ---------------------------------------------------------
+
+
+def test_the_screen_recording_preflight_is_frozen_until_relaunch() -> None:
+ tcc = FakeTCC()
+ quartz = tcc.modules["Quartz"]
+ assert quartz.CGPreflightScreenCaptureAccess() is False
+
+ # The request returns the state at the call; the user then allows.
+ assert quartz.CGRequestScreenCaptureAccess() is False
+ assert tcc.state(SCREEN) is TccState.GRANTED
+ assert quartz.CGPreflightScreenCaptureAccess() is False # frozen
+
+ tcc.relaunch()
+
+ assert quartz.CGPreflightScreenCaptureAccess() is True
+ assert tcc.launch_count == 2
+
+
+def test_a_grant_that_exists_at_launch_is_visible_to_the_preflight() -> None:
+ tcc = FakeTCC(granted=[SCREEN])
+
+ assert tcc.modules["Quartz"].CGPreflightScreenCaptureAccess() is True
+
+
+def test_input_monitoring_preflight_is_live_unless_configured_frozen() -> None:
+ live = FakeTCC()
+ live.grant(INPUT)
+ frozen = FakeTCC(preflight_frozen=[SCREEN, INPUT])
+ frozen.grant(INPUT)
+
+ assert live.modules["Quartz"].CGPreflightListenEventAccess() is True
+ assert frozen.modules["Quartz"].CGPreflightListenEventAccess() is False
+ frozen.relaunch()
+ assert frozen.modules["Quartz"].CGPreflightListenEventAccess() is True
+
+
+def test_a_capture_without_the_grant_returns_the_wallpaper_and_no_error() -> None:
+ tcc = FakeTCC()
+ tcc.deny(SCREEN)
+ grab = FakeScreenGrab(tcc)
+
+ frame = grab.grab()
+
+ assert frame.wallpaper_only is True
+ assert frame.window_titles == ()
+ assert tcc.implicit_prompts() == [] # a decision is on file: nothing to ask
+ tcc.grant(SCREEN)
+ assert grab.grab().window_titles == ("Safari", "Notes")
+
+
+def test_a_first_capture_makes_macos_ask_by_itself() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ frame = FakeScreenGrab(tcc, caller="screen_snapshot").grab()
+
+ assert frame.wallpaper_only is True
+ (prompt,) = tcc.implicit_prompts(SCREEN)
+ assert prompt.outcome is CallOutcome.DIALOG_SHOWN
+ assert prompt.caller == "screen_snapshot"
+ assert tcc.requests() == [] # nothing the code asked for explicitly
+
+
+def test_both_worlds_for_a_screen_grant_given_while_the_app_runs() -> None:
+ """Whether capture works before relaunch is an open conflict: model both."""
+ optimistic = FakeTCC()
+ optimistic.grant(SCREEN)
+ pessimistic = FakeTCC(screen_grant_needs_relaunch=True)
+ pessimistic.grant(SCREEN)
+
+ assert FakeScreenGrab(optimistic).grab().wallpaper_only is False
+ assert FakeScreenGrab(pessimistic).grab().wallpaper_only is True
+ pessimistic.relaunch()
+ assert FakeScreenGrab(pessimistic).grab().wallpaper_only is False
+
+
+def test_the_window_title_oracle_is_a_silent_probe() -> None:
+ tcc = FakeTCC()
+ assert tcc.screen_capture_live_check() is None # unknowable, never False
+ tcc.grant(SCREEN)
+ assert tcc.screen_capture_live_check() is True
+ tcc.assert_no_prompts()
+ assert len(tcc.probes(SCREEN)) == 2
+
+
+# --- Accessibility and event posting -----------------------------------------
+
+
+def test_accessibility_is_a_boolean_and_its_prompt_can_be_called_again() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.DENY)
+ services = tcc.modules["ApplicationServices"]
+ assert services.AXIsProcessTrusted() is False
+
+ assert _prompt_ax(tcc) is False
+ assert _prompt_ax(tcc) is False
+
+ # Re-prompt world (unverified): each call while untrusted shows a dialog.
+ assert len(tcc.dialogs_shown(AX)) == 2
+ assert tcc.ignored_requests(AX) == []
+
+
+def test_in_the_no_reprompt_world_the_second_accessibility_prompt_is_ignored() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.DENY, ax_reprompts_while_untrusted=False)
+
+ _prompt_ax(tcc)
+ _prompt_ax(tcc)
+
+ assert len(tcc.dialogs_shown(AX)) == 1
+ assert len(tcc.ignored_requests(AX)) == 1
+
+
+def test_an_accessibility_prompt_without_the_option_is_only_a_read() -> None:
+ tcc = FakeTCC()
+
+ assert tcc.modules["ApplicationServices"].AXIsProcessTrustedWithOptions({}) is False
+
+ assert tcc.requests() == []
+ assert len(tcc.probes(AX)) == 1
+
+
+def test_an_allowed_accessibility_prompt_makes_the_process_trusted() -> None:
+ tcc = FakeTCC()
+
+ assert _prompt_ax(tcc) is False # the state at the call; the user acts afterwards
+ assert tcc.modules["ApplicationServices"].AXIsProcessTrusted() is True
+ assert tcc.modules["Quartz"].CGPreflightPostEventAccess() is True # alias
+
+
+def test_event_posting_asks_through_the_accessibility_switch() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.DENY)
+
+ tcc.modules["Quartz"].CGRequestPostEventAccess()
+
+ assert tcc.state(AX) is TccState.DENIED
+ (request,) = tcc.requests(POST)
+ assert request.service is POST
+ tcc.default_policy = DialogPolicy.ALLOW
+ tcc.reset(AX)
+ tcc.modules["Quartz"].CGRequestPostEventAccess()
+ assert tcc.state(AX) is TccState.GRANTED
+
+
+def test_the_hid_post_event_tristate_reads_unknown_until_the_user_was_asked() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.DENY)
+ assert tcc.iohid_check(0) == 2
+
+ _prompt_ax(tcc)
+
+ assert tcc.iohid_check(0) == 1
+
+
+# --- Input Monitoring and event taps -----------------------------------------
+
+
+def test_a_tap_created_before_the_request_registers_the_app_as_denied() -> None:
+ """The BUG-058 class: creating a tap is not a way to ask."""
+ tcc = FakeTCC()
+ tap = FakeEventTap(tcc, caller="hotkeys")
+
+ assert tap.create() is False
+
+ (prompt,) = tcc.implicit_prompts(INPUT)
+ assert prompt.outcome is CallOutcome.AUTO_DENIED
+ assert prompt.caller == "hotkeys"
+ assert tcc.state(INPUT) is TccState.DENIED
+ assert tcc.iohid_check(1) == 1
+
+ # The request that should have come first is now ignored: no dialog, ever.
+ assert tcc.modules["Quartz"].CGRequestListenEventAccess() is False
+ assert len(tcc.ignored_requests(INPUT)) == 1
+ assert tcc.dialogs_shown() == []
+
+
+def test_a_tap_created_after_the_grant_receives_keys() -> None:
+ tcc = FakeTCC()
+ tcc.modules["Quartz"].CGRequestListenEventAccess()
+ keys: list[int] = []
+ tap = FakeEventTap(tcc)
+
+ assert tap.create(keys.append) is True
+ assert tap.deliver_key(7) is True
+
+ assert keys == [7]
+ assert tcc.implicit_prompts() == []
+
+
+def test_an_accessibility_grant_also_lets_a_listen_tap_work() -> None:
+ tcc = FakeTCC(granted=[AX])
+ tap = FakeEventTap(tcc)
+
+ assert tap.create() is True
+
+ assert tcc.state(INPUT) is TccState.NOT_DETERMINED # untouched
+ assert tcc.implicit_prompts() == []
+
+
+def test_an_active_tap_needs_accessibility_not_input_monitoring() -> None:
+ tcc = FakeTCC(granted=[INPUT])
+
+ assert FakeEventTap(tcc).create(listen_only=False) is False
+ tcc.grant(AX)
+ assert FakeEventTap(tcc).create(listen_only=False) is True
+
+
+def test_a_denied_tap_can_be_created_and_receive_nothing() -> None:
+ tcc = FakeTCC(silent_tap_when_denied=True)
+ tcc.deny(INPUT)
+ tap = FakeEventTap(tcc)
+
+ assert tap.create() is True
+ assert tap.live is True
+ assert tap.receives_events is False
+ assert tap.deliver_key() is False
+
+
+def test_a_tap_dies_with_the_process() -> None:
+ tcc = FakeTCC(granted=[INPUT])
+ tap = FakeEventTap(tcc)
+ tap.create()
+
+ tcc.relaunch()
+
+ assert tap.live is False
+ assert tap.deliver_key() is False
+
+
+# --- Automation ---------------------------------------------------------------
+
+
+def test_automation_reports_the_apple_event_status_values() -> None:
+ tcc = FakeTCC(running_players=[MUSIC])
+
+ assert tcc.automation_probe(SPOTIFY, False) == AE_PROC_NOT_FOUND
+ assert tcc.automation_probe(MUSIC, False) == AE_EVENT_WOULD_REQUIRE_USER_CONSENT
+ tcc.grant(AUTOMATION, MUSIC)
+ assert tcc.automation_probe(MUSIC, False) == AE_NO_ERR
+ tcc.deny(AUTOMATION, MUSIC)
+ assert tcc.automation_probe(MUSIC, False) == AE_EVENT_NOT_PERMITTED
+ assert tcc.requests() == [] # asking=False never raises the dialog
+
+
+def test_automation_asks_only_for_a_running_target_and_only_once() -> None:
+ tcc = FakeTCC(running_players=[MUSIC], default_policy=DialogPolicy.DENY)
+
+ assert tcc.automation_probe(SPOTIFY, True) == AE_PROC_NOT_FOUND
+ assert tcc.automation_probe(MUSIC, True) == AE_EVENT_NOT_PERMITTED
+ assert tcc.automation_probe(MUSIC, True) == AE_EVENT_NOT_PERMITTED
+
+ outcomes = [(call.target, call.outcome) for call in tcc.requests(AUTOMATION)]
+ assert outcomes == [
+ (SPOTIFY, CallOutcome.TARGET_NOT_RUNNING),
+ (MUSIC, CallOutcome.DIALOG_SHOWN),
+ (MUSIC, CallOutcome.IGNORED_REQUEST),
+ ]
+
+
+def test_automation_decisions_are_per_target() -> None:
+ tcc = FakeTCC(running_players=[MUSIC, SPOTIFY])
+ tcc.script(AUTOMATION, DialogPolicy.ALLOW, target=MUSIC)
+ tcc.script(AUTOMATION, DialogPolicy.DENY, target=SPOTIFY)
+
+ assert tcc.automation_probe(MUSIC, True) == AE_NO_ERR
+ assert tcc.automation_probe(SPOTIFY, True) == AE_EVENT_NOT_PERMITTED
+ assert tcc.state(AUTOMATION, MUSIC) is TccState.GRANTED
+ assert tcc.state(AUTOMATION, SPOTIFY) is TccState.DENIED
+
+
+def test_an_unanswered_automation_dialog_does_not_hang_the_caller() -> None:
+ tcc = FakeTCC(running_players=[MUSIC], default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ assert tcc.automation_probe(MUSIC, True) == AE_EVENT_WOULD_REQUIRE_USER_CONSENT
+
+ assert tcc.dialog_open(AUTOMATION, MUSIC) is True
+
+
+def test_automation_state_changes_need_a_target() -> None:
+ with pytest.raises(ValueError):
+ FakeTCC().grant(AUTOMATION)
+
+
+# --- the audio companion ------------------------------------------------------
+
+
+def test_opening_the_microphone_while_not_determined_prompts_by_itself() -> None:
+ tcc = FakeTCC()
+ audio = FakeAudioInput(tcc, caller="wake_loop")
+
+ stream = audio(device=0, channels=1, blocksize=4)
+ stream.start()
+
+ (prompt,) = tcc.implicit_prompts(MIC)
+ assert prompt.caller == "wake_loop"
+ assert tcc.requests() == []
+ assert tcc.state(MIC) is TccState.GRANTED # the default simulated user allows
+
+
+def test_a_denied_microphone_delivers_digital_silence_not_an_error() -> None:
+ tcc = FakeTCC()
+ tcc.deny(MIC)
+ audio = FakeAudioInput(tcc)
+ received: list[bytes] = []
+ stream = audio(
+ channels=1, blocksize=4, callback=lambda data, _f, _t, _s: received.append(bytes(data))
+ )
+
+ stream.start()
+ stream.pump(2)
+
+ assert received == [b"\x00" * 8] * 2
+ assert (stream.silent_blocks, stream.audible_blocks) == (2, 0)
+ assert tcc.implicit_prompts() == []
+
+
+def test_a_granted_microphone_delivers_audio() -> None:
+ tcc = FakeTCC(granted=[MIC])
+ received: list[bytes] = []
+ stream = FakeAudioInput(tcc)(
+ channels=1, blocksize=4, callback=lambda data, _f, _t, _s: received.append(bytes(data))
+ )
+
+ stream.start()
+ stream.pump()
+
+ assert received and any(received[0])
+ assert stream.audible_blocks == 1
+
+
+def test_the_microphone_stays_silent_until_the_open_dialog_is_answered() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ stream = FakeAudioInput(tcc)(channels=1, blocksize=2)
+ stream.start()
+
+ stream.pump()
+ tcc.answer(MIC)
+ stream.pump()
+
+ assert (stream.silent_blocks, stream.audible_blocks) == (1, 1)
+
+
+def test_without_tcc_a_stream_opens_without_a_question() -> None:
+ audio = FakeAudioInput(None)
+ stream = audio(channels=1, blocksize=2)
+
+ stream.start()
+
+ assert audio.starts == [stream]
+ assert stream.active is True
+ stream.stop()
+ stream.close()
+ assert stream.active is False
+
+
+def test_a_stream_that_was_never_started_opened_no_device() -> None:
+ tcc = FakeTCC()
+ audio = FakeAudioInput(tcc)
+
+ audio(channels=1) # constructed, not started: consumers assert audio.starts == []
+
+ assert audio.starts == []
+ tcc.assert_no_prompts()
+
+
+# --- purpose strings ----------------------------------------------------------
+
+
+def test_a_missing_microphone_purpose_string_aborts_the_process() -> None:
+ tcc = FakeTCC(usage_strings=())
+
+ answers = _request_mic(tcc)
+
+ assert answers == []
+ assert tcc.state(MIC) is TccState.NOT_DETERMINED
+ assert tcc.dialogs_shown() == []
+ (abort,) = tcc.aborts()
+ assert abort.outcome is CallOutcome.PROCESS_ABORT
+
+
+def test_an_abort_can_be_raised_as_a_base_exception() -> None:
+ tcc = FakeTCC(usage_strings=(), abort_raises=True)
+
+ with pytest.raises(TccProcessAbort):
+ FakeAudioInput(tcc)(channels=1).start()
+
+ # An ``except Exception`` guard cannot hide it, as with a real SIGABRT.
+ assert not issubclass(TccProcessAbort, Exception)
+
+
+def test_a_terminal_started_process_is_covered_by_the_terminals_strings() -> None:
+ tcc = FakeTCC(bundle_id=None, bundle_path="/usr/bin/python3", usage_strings=())
+
+ _request_mic(tcc)
+
+ assert tcc.aborts() == []
+ assert tcc.grantee == TERMINAL_BUNDLE_ID
+ assert tcc.requests(MIC)[0].grantee == TERMINAL_BUNDLE_ID
+
+
+def test_the_bundle_reports_its_purpose_strings() -> None:
+ bundle = FakeTCC().modules["Foundation"].NSBundle.mainBundle()
+ bare = FakeTCC(usage_strings=()).modules["Foundation"].NSBundle.mainBundle()
+
+ assert bundle.objectForInfoDictionaryKey_("NSMicrophoneUsageDescription")
+ assert bundle.objectForInfoDictionaryKey_("NSAppleEventsUsageDescription")
+ assert "NSMicrophoneUsageDescription" in bundle.infoDictionary()
+ assert bundle.objectForInfoDictionaryKey_("NSCameraUsageDescription") is None
+ assert bare.objectForInfoDictionaryKey_("NSMicrophoneUsageDescription") is None
+
+
+# --- the call log -------------------------------------------------------------
+
+
+def test_the_log_is_ordered_and_records_the_calling_thread() -> None:
+ tcc = FakeTCC()
+ tcc.modules["Quartz"].CGPreflightScreenCaptureAccess()
+
+ worker = threading.Thread(target=_request_mic, args=(tcc,), name="worker-1")
+ worker.start()
+ worker.join()
+
+ assert [call.seq for call in tcc.calls] == [0, 1]
+ assert tcc.kinds() == ["probe", "request"]
+ assert [call.thread for call in tcc.calls][1] == "worker-1"
+ assert tcc.calls[0].thread == threading.current_thread().name
+
+
+def test_the_log_filters_accept_a_permission_id_or_a_plain_string() -> None:
+ tcc = FakeTCC()
+ _request_mic(tcc)
+
+ assert tcc.requests("microphone") == tcc.requests(PermissionId.MICROPHONE) == tcc.requests(MIC)
+ assert tcc.requests("screen_recording") == []
+ assert tcc.implicit_prompts("microphone") == []
+
+
+def test_log_filters_marks_and_clear() -> None:
+ tcc = FakeTCC()
+ _mic_status(tcc)
+ mark = tcc.mark()
+ _request_mic(tcc)
+ tcc.modules["Quartz"].CGRequestScreenCaptureAccess()
+
+ assert len(tcc.probes()) == 1
+ assert len(tcc.requests()) == 2
+ assert len(tcc.requests(MIC)) == 1
+ assert [call.service for call in tcc.calls_since(mark)] == [MIC, SCREEN]
+ assert tcc.calls_of("request", "screen_recording") == tcc.requests(SCREEN)
+ assert tcc.calls_of(CallKind.PROBE, target="") == tcc.probes()
+
+ tcc.clear_log()
+
+ assert tcc.calls == ()
+ tcc.assert_silent()
+
+
+def test_assert_no_prompts_names_the_offending_call() -> None:
+ tcc = FakeTCC()
+ _mic_status(tcc)
+ tcc.assert_no_prompts() # a probe is not a prompt
+ mark = tcc.mark()
+ _request_mic(tcc)
+
+ with pytest.raises(AssertionError, match="requestAccessForMediaType"):
+ tcc.assert_no_prompts()
+ tcc.assert_no_prompts(since=tcc.mark()) # nothing after the last call
+ assert mark == 1
+
+
+def test_assert_silent_fails_when_a_framework_was_loaded() -> None:
+ tcc = FakeTCC()
+ tcc.module_loader("Quartz")
+
+ with pytest.raises(AssertionError, match="Quartz"):
+ tcc.assert_silent()
+
+
+def test_a_missing_framework_cannot_be_imported() -> None:
+ tcc = FakeTCC(missing_frameworks=["Quartz"])
+ tcc.drop_framework("AppKit")
+
+ for name in ("Quartz", "AppKit", "Nonexistent"):
+ with pytest.raises(ModuleNotFoundError):
+ tcc.module_loader(name)
+ assert tcc.module_loader("Foundation") is tcc.modules["Foundation"]
+
+
+# --- reset, relaunch, tccutil -------------------------------------------------
+
+
+def test_relaunch_closes_dialogs_and_counts_launches() -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ _request_mic(tcc)
+ assert tcc.launch_count == 1
+
+ tcc.relaunch()
+
+ assert tcc.dialog_open(MIC) is False
+ assert tcc.state(MIC) is TccState.NOT_DETERMINED
+ assert tcc.launch_count == 2
+
+
+def test_tccutil_resets_only_the_named_bundles_row() -> None:
+ tcc = FakeTCC(granted=[MIC, AX])
+
+ other = tcc.run_tccutil(["/usr/bin/tccutil", "reset", "Microphone", "com.example.other"])
+ own = tcc.run_tccutil(["/usr/bin/tccutil", "reset", "Microphone", tcc.grantee])
+ bad = tcc.run_tccutil(["/usr/bin/tccutil", "reset", "NoSuchService", tcc.grantee])
+ ax = tcc.run_tccutil(["/usr/bin/tccutil", "reset", "Accessibility", tcc.grantee])
+
+ assert (other.returncode, own.returncode, bad.returncode, ax.returncode) == (0, 0, 1, 0)
+ assert tcc.state(MIC) is TccState.NOT_DETERMINED
+ assert tcc.state(AX) is TccState.DENIED # no not_determined: untrusted again
+ assert len(tcc.tccutil_calls) == 4
+
+
+def test_reset_without_a_target_forgets_every_automation_target() -> None:
+ tcc = FakeTCC(granted=[AUTOMATION])
+ assert all(
+ tcc.state(AUTOMATION, bundle) is TccState.GRANTED for _n, bundle in AUTOMATION_TARGETS
+ )
+
+ tcc.reset(AUTOMATION)
+
+ assert all(
+ tcc.state(AUTOMATION, bundle) is TccState.NOT_DETERMINED
+ for _n, bundle in AUTOMATION_TARGETS
+ )
+
+
+def test_the_upgrader_whose_grants_are_all_in_place() -> None:
+ tcc = FakeTCC.all_granted()
+
+ assert all(
+ tcc.state(service, MUSIC if service is AUTOMATION else "") is TccState.GRANTED
+ for service in TccService
+ )
+ assert tcc.modules["Quartz"].CGPreflightScreenCaptureAccess() is True
+
+
+# --- players and identity -----------------------------------------------------
+
+
+def test_a_closed_player_can_be_launched_hidden_and_closed_again() -> None:
+ tcc = FakeTCC(installed_players=[MUSIC])
+ appkit = tcc.modules["AppKit"]
+ workspace = appkit.NSWorkspace.sharedWorkspace()
+ config = appkit.NSWorkspaceOpenConfiguration.configuration()
+ config.setActivates_(False)
+ config.setHides_(True)
+ url = workspace.URLForApplicationWithBundleIdentifier_(MUSIC)
+ assert workspace.URLForApplicationWithBundleIdentifier_(SPOTIFY) is None
+ assert appkit.NSRunningApplication.runningApplicationsWithBundleIdentifier_(MUSIC) == []
+
+ workspace.openApplicationAtURL_configuration_completionHandler_(url, config, lambda *_a: None)
+
+ (player,) = appkit.NSRunningApplication.runningApplicationsWithBundleIdentifier_(MUSIC)
+ assert tcc.launches == [(MUSIC, False, True)]
+ player.terminate()
+ assert player.isTerminated() is True
+ assert tcc.player_running(MUSIC) is False
+
+
+def test_the_frontmost_application_follows_the_foreground_and_headless_switches() -> None:
+ tcc = FakeTCC()
+ appkit = tcc.modules["AppKit"]
+ workspace = appkit.NSWorkspace.sharedWorkspace()
+
+ assert workspace.frontmostApplication().isActive() is True
+ tcc.foreground = False
+ assert workspace.frontmostApplication().isActive() is False
+ assert appkit.NSRunningApplication.currentApplication().isActive() is False
+ tcc.headless = True
+ assert workspace.frontmostApplication() is None
+
+
+def test_the_dmg_build_is_an_installed_identity_too() -> None:
+ tcc = FakeTCC(bundle_id=DMG_BUNDLE_ID)
+
+ assert tcc.launched_as_bundle is True
+ assert tcc.grantee == DMG_BUNDLE_ID
+
+
+# --- the real port on top of the fake ----------------------------------------
+
+
+def test_the_real_port_reads_the_fake_without_ever_prompting() -> None:
+ port, tcc = make_darwin_port()
+
+ states = {permission_id.value: port.state(permission_id) for permission_id in PermissionId}
+
+ assert states["microphone"] is PermissionState.NOT_DETERMINED
+ assert states["screen_recording"] is PermissionState.NOT_GRANTED
+ assert states["accessibility"] is PermissionState.NOT_GRANTED
+ assert states["input_monitoring"] is PermissionState.NOT_DETERMINED
+ assert states["automation"] is PermissionState.NOT_REQUIRED # no scriptable player installed
+ assert port._app_identity()[0].stable is True
+ assert tcc.probes() and tcc.kinds().count("probe") == len(tcc.calls)
+ tcc.assert_no_prompts()
+
+
+def test_the_real_port_requests_through_the_fake_and_macos_never_asks_twice() -> None:
+ port, tcc = make_darwin_port(default_policy=DialogPolicy.DENY)
+
+ first = port.request_native(PermissionId.MICROPHONE)
+ second = port.request_native(PermissionId.MICROPHONE)
+
+ assert first == "dialog_shown"
+ assert second == "no_dialog" # the decision is on file: no second dialog
+ assert len(tcc.dialogs_shown(MIC)) == 1
+ assert len(tcc.ignored_requests(MIC)) == 1
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.DENIED
+
+
+def test_the_real_port_reads_a_state_change_on_the_very_next_call() -> None:
+ port, tcc = make_darwin_port(granted=[MIC])
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.GRANTED
+
+ tcc.deny(MIC)
+
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.DENIED
+
+
+def test_the_real_port_sees_a_screen_grant_through_the_live_oracle() -> None:
+ port, tcc = make_darwin_port()
+ tcc.grant(SCREEN)
+
+ assert tcc.modules["Quartz"].CGPreflightScreenCaptureAccess() is False
+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.GRANTED
+
+
+def test_the_real_port_needs_a_relaunch_in_the_pessimistic_screen_world() -> None:
+ port, tcc = make_darwin_port(screen_grant_needs_relaunch=True)
+ tcc.grant(SCREEN)
+
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.NOT_GRANTED
+ tcc.relaunch()
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.GRANTED
+
+
[email protected]("platform_name", ["win32", "linux"])
+def test_a_non_darwin_port_never_touches_the_fake(platform_name: str) -> None:
+ port, tcc = make_non_darwin_port(platform_name) # type: ignore[arg-type]
+
+ port.state(PermissionId.MICROPHONE)
+ port.request_native(PermissionId.MICROPHONE)
+ port.open_pane(PermissionId.MICROPHONE)
+ port.reset_row(PermissionId.MICROPHONE)
+
+ tcc.assert_silent()
+ assert port.platform == platform_name
+
+
+def test_install_port_replaces_the_process_wide_port(monkeypatch: pytest.MonkeyPatch) -> None:
+ import jarvis.platform.permissions as permissions
+
+ before = permissions.get_system_permission_port()
+ port, _tcc = make_darwin_port()
+
+ assert install_port(monkeypatch, port) is port
+ assert permissions.get_system_permission_port() is port
+ monkeypatch.undo()
+ assert permissions.get_system_permission_port() is before
diff --git a/tests/unit/platform/test_no_legacy_permission_api.py b/tests/unit/platform/test_no_legacy_permission_api.py
new file mode 100644
index 0000000000..a0b3ec57e6
--- /dev/null
+++ b/tests/unit/platform/test_no_legacy_permission_api.py
@@ -0,0 +1,200 @@
+"""Ratchet: the legacy macOS permission wall must not come back.
+
+The rebuild deleted the readiness aggregation, the stable-identity-gates-acting
+path, the legacy ``snapshot()``/``request()``, the identity-reset marker file and
+the Automation consent file. This module fails when any of them is reintroduced,
+by name in the product code, the CI scripts and the workflows, and by shape on the
+port itself. The only place allowed to name the two state files an earlier build
+left behind is the one-time cleanup in ``jarvis/platform/permissions.py``.
+"""
+
+from __future__ import annotations
+
+import inspect
+import os
+import re
+from pathlib import Path
+
+import pytest
+
+from jarvis.platform import permissions
+from jarvis.platform.permissions import SystemPermissionPort
+
+_ROOT = Path(__file__).resolve().parents[3]
+_SCANNED_DIRS = ("jarvis", "scripts", ".github")
+_SCANNED_SUFFIXES = {".py", ".yml", ".yaml", ".sh", ".ps1", ".toml", ".spec"}
+_SKIPPED_PARTS = {"node_modules", "dist", "__pycache__", ".venv", "wheels"}
+
+# Names of deleted behaviour. Each is a whole identifier (``\b``), so ``reset_row`` and
+# ``automation_consent_runner`` (the killable consent seam that stays) never match.
+_REMOVED_NAMES = (
+ "runtime_access_granted",
+ "runtime_feature_ready",
+ "FEATURE_REQUIREMENTS",
+ "active_features",
+ "identity_reset_marker_path",
+ "identity_reset_pending",
+ "record_identity_reset",
+ "_clear_identity_reset",
+ "_read_identity_reset",
+ "automation_consent_path",
+ "_read_automation_consent",
+ "_write_automation_consent",
+ "_clear_automation_consent",
+ "screen_recording_granted",
+ "PermissionStatus",
+)
+# Chained calls on the process-wide port or a fresh one: the legacy v1 entry points.
+_REMOVED_CALLS = re.compile(
+ r"(?:SystemPermissionPort\(\)|get_system_permission_port\(\))"
+ r"\s*\.\s*(?:snapshot|request|open_settings|reset)\s*\("
+)
+_LEFTOVER_FILES = ("macos-tcc-reset.json", "macos-automation-consent.json")
+_CLEANUP_HOME = "jarvis/platform/permissions.py"
+
+
+def _scanned_files() -> list[Path]:
+ files: list[Path] = []
+ for directory in _SCANNED_DIRS:
+ for current, subdirs, names in os.walk(_ROOT / directory):
+ # Prune before descending: the frontend's node_modules is enormous.
+ subdirs[:] = [name for name in subdirs if name not in _SKIPPED_PARTS]
+ files.extend(
+ Path(current) / name for name in names if Path(name).suffix in _SCANNED_SUFFIXES
+ )
+ return files
+
+
+def _read(path: Path) -> str:
+ return path.read_text(encoding="utf-8", errors="replace")
+
+
[email protected](scope="module")
+def sources() -> dict[str, str]:
+ return {path.relative_to(_ROOT).as_posix(): _read(path) for path in _scanned_files()}
+
+
+def test_the_scan_sees_the_product_the_ci_scripts_and_the_workflows(
+ sources: dict[str, str],
+) -> None:
+ assert _CLEANUP_HOME in sources
+ assert "scripts/ci/check_frozen_browser.py" in sources
+ assert ".github/workflows/macos-desktop.yml" in sources
+
+
[email protected]("name", _REMOVED_NAMES)
+def test_a_removed_name_does_not_appear_in_the_product_the_scripts_or_the_workflows(
+ name: str, sources: dict[str, str]
+) -> None:
+ pattern = re.compile(rf"\b{re.escape(name)}\b")
+
+ offenders = sorted(rel for rel, text in sources.items() if pattern.search(text))
+
+ assert offenders == [], f"{name} was deleted with the legacy permission wall: {offenders}"
+
+
+def test_no_chained_call_reaches_a_legacy_port_entry_point(sources: dict[str, str]) -> None:
+ offenders = sorted(rel for rel, text in sources.items() if _REMOVED_CALLS.search(text))
+
+ assert offenders == []
+
+
+def test_only_the_one_time_cleanup_names_the_two_leftover_state_files(
+ sources: dict[str, str],
+) -> None:
+ for name in _LEFTOVER_FILES:
+ offenders = sorted(rel for rel, text in sources.items() if name in text)
+ assert offenders == [_CLEANUP_HOME], (name, offenders)
+
+
+def test_the_leftover_cleanup_is_called_only_on_the_darwin_install_path(
+ sources: dict[str, str],
+) -> None:
+ callers = sorted(
+ rel
+ for rel, text in sources.items()
+ if re.search(r"\bremove_leftover_state_files\s*\(", text) and rel != _CLEANUP_HOME
+ )
+
+ # Nothing initialises at import time or on the boot critical path (AP-26).
+ assert callers == ["jarvis/setup/macos_app_bundle.py"]
+ assert not re.search(r"^remove_leftover_state_files\(", sources[_CLEANUP_HOME], re.M)
+
+
+def test_the_port_exposes_only_the_primitives_the_service_composes() -> None:
+ public = {
+ name
+ for name, _member in inspect.getmembers(SystemPermissionPort)
+ if not name.startswith("_")
+ }
+
+ assert public == {
+ "has_desktop_session",
+ "launched_as_bundle",
+ "open_pane",
+ "outside_installed_app",
+ "platform",
+ "request_native",
+ "reset_row",
+ "state",
+ "usage_string_present",
+ }
+
+
+def test_the_port_keeps_no_restart_flag_and_no_recorded_answers() -> None:
+ attributes = set(vars(SystemPermissionPort(platform_name="linux")))
+
+ assert not [name for name in attributes if "restart" in name]
+ # Injected seams, the static bundle identity and the last opened pane: nothing recorded.
+ assert attributes == {
+ "_platform_name",
+ "_module_loader",
+ "_iohid_check",
+ "_screen_capture_live_check",
+ "_credential_store_backend",
+ "_credential_store_recover",
+ "_automation_probe",
+ "_iohid_request",
+ "_automation_consent_runner",
+ "_bundle_identity_cache",
+ "_last_opened_url",
+ }
+
+
+def test_the_module_no_longer_exports_the_readiness_aggregation() -> None:
+ for name in ("FEATURE_REQUIREMENTS", "active_features", "PermissionStatus"):
+ assert not hasattr(permissions, name), name
+ assert name not in permissions.__all__
+
+
+def test_a_state_read_is_shallow_unless_a_deep_read_is_asked_for() -> None:
+ parameters = inspect.signature(SystemPermissionPort.state).parameters
+
+ assert parameters["deep"].default is False
+ assert parameters["deep"].kind is inspect.Parameter.KEYWORD_ONLY
+ assert parameters["target"].kind is inspect.Parameter.KEYWORD_ONLY
+
+
+def test_the_app_identity_keeps_no_foreground_and_no_expected_id() -> None:
+ fields = set(permissions.AppIdentity.__dataclass_fields__)
+
+ assert fields == {"app_name", "bundle_id", "bundle_path", "launched_as_bundle", "stable"}
+
+
+ "relative",
+ [
+ "scripts/ci/check_frozen_browser.py",
+ "scripts/ci/check_frozen_macos_app.py",
+ ".github/workflows/macos-desktop.yml",
+ ".github/workflows/desktop-installers.yml",
+ ],
+)
+def test_the_ci_probes_read_only_status_keys_that_survive(
+ relative: str, sources: dict[str, str]
+) -> None:
+ """``/api/permissions/status`` lost its v1 keys; a probe that reads one would go blind."""
+ text = sources[relative]
+
+ for key in ("features", "wanted", "identity_reset", "restart_required", "expected_bundle_id"):
+ assert not re.search(rf"""["']{key}["']""", text), (relative, key)
diff --git a/tests/unit/platform/test_permission_agent_boundary.py b/tests/unit/platform/test_permission_agent_boundary.py
new file mode 100644
index 0000000000..c4b6d0ce4e
--- /dev/null
+++ b/tests/unit/platform/test_permission_agent_boundary.py
@@ -0,0 +1,335 @@
+"""Boundaries of the permission layer that only a ratchet can hold.
+
+* P9, "an AI agent never answers a system dialog": no tool and no agent-reachable
+ package may trigger or answer a permission request, open a pane, reset a row or
+ talk to the permission routes. A later tool or MCP wrapper that forwards to
+ ``POST /api/permissions/*`` would otherwise go unnoticed.
+* Nothing inbound on ``/ws`` can publish ``PermissionNeeded`` or ``PermissionResolved``:
+ only a short list of backend modules constructs them, and the socket accepts only
+ two frame types.
+* Boot: the service gets the bus before anything can ask, and a fresh Mac with every
+ permission undecided boots with no request and no implicit prompt.
+* The module-level functions are thin wrappers; each one is pinned so that a dropped
+ or swapped argument cannot go unnoticed.
+
+The AST scans are static on purpose: they hold for code paths no test can execute.
+"""
+
+from __future__ import annotations
+
+import ast
+import asyncio
+import re
+import threading
+import tomllib
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.core.events import ErrorOccurred, Event, PermissionNeeded, PermissionResolved
+from jarvis.platform import permission_service as service_module
+from jarvis.platform.permissions import PermissionId, PermissionState
+from jarvis.ui.web.server import WebServer
+from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, install_port
+
+_ROOT = Path(__file__).resolve().parents[3]
+_JARVIS = _ROOT / "jarvis"
+
+# Packages an agent (the router, a worker, an MCP client, a tool) can reach.
+_AGENT_REACHABLE = (
+ "plugins/tool",
+ "brain",
+ "mcp",
+ "agent_chat",
+ "harness",
+ "agents",
+ "tools",
+ "missions",
+ "society",
+)
+# Entry points that trigger or answer a system dialog, open a pane or reset a row.
+_FORBIDDEN_ATTRIBUTES = frozenset(
+ {"open_settings", "note_reset", "reset_row", "request_native", "open_pane"}
+)
+_FORBIDDEN_TEXT = ("/api/permissions", "permissions_routes")
+# The only backend modules that build the two permission events: the service, the
+# event definitions, and the microphone capture (design 3.5: its watchdog and the
+# digital-silence guard report a revoked or muted microphone). A new producer is a
+# conscious decision: add it here, in the same change.
+_EVENT_CONSTRUCTORS = frozenset(
+ {
+ "jarvis/platform/permission_service.py",
+ "jarvis/core/events.py",
+ "jarvis/audio/capture.py",
+ }
+)
+_PERMISSION_TOOL_NAME = re.compile(r"permission|privacy|tcc|consent", re.IGNORECASE)
+
+
+def _python_files(*relative: str) -> Iterator[Path]:
+ for directory in relative:
+ base = _JARVIS / directory
+ if base.is_dir():
+ yield from sorted(base.rglob("*.py"))
+
+
+def _tool_entry_point_names() -> list[str]:
+ pyproject = tomllib.loads((_ROOT / "pyproject.toml").read_text(encoding="utf-8"))
+ return sorted(pyproject["project"]["entry-points"]["jarvis.tool"])
+
+
+# ----------------------------------------------------------------------
+# P9: an agent never answers a system dialog
+# ----------------------------------------------------------------------
+
+
+def test_no_registered_tool_is_named_after_a_permission_operation() -> None:
+ from jarvis.brain.factory import ROUTER_TOOLS
+
+ names = [*_tool_entry_point_names(), *ROUTER_TOOLS]
+
+ assert names, "the tool entry points could not be read"
+ assert [name for name in names if _PERMISSION_TOOL_NAME.search(name)] == []
+
+
+def test_no_agent_reachable_package_triggers_or_answers_a_permission_request() -> None:
+ offenders: list[str] = []
+ for path in _python_files(*_AGENT_REACHABLE):
+ text = path.read_text(encoding="utf-8")
+ if not (
+ any(token in text for token in _FORBIDDEN_TEXT)
+ or any(name in text for name in _FORBIDDEN_ATTRIBUTES)
+ ):
+ continue
+ relative = path.relative_to(_ROOT).as_posix()
+ for token in _FORBIDDEN_TEXT:
+ if token in text:
+ offenders.append(f"{relative}: mentions {token}")
+ for node in ast.walk(ast.parse(text)):
+ if isinstance(node, ast.Attribute) and node.attr in _FORBIDDEN_ATTRIBUTES:
+ offenders.append(f"{relative}:{node.lineno}: .{node.attr}")
+ if isinstance(node, ast.ImportFrom) and any(
+ alias.name in _FORBIDDEN_ATTRIBUTES for alias in node.names
+ ):
+ offenders.append(f"{relative}:{node.lineno}: imports a permission operation")
+
+ assert offenders == [], "\n".join(offenders)
+
+
+# ----------------------------------------------------------------------
+# Nothing inbound can publish a permission event
+# ----------------------------------------------------------------------
+
+
+def test_only_the_known_backend_modules_construct_the_permission_events() -> None:
+ offenders: list[str] = []
+ for path in _JARVIS.rglob("*.py"):
+ text = path.read_text(encoding="utf-8")
+ if "PermissionNeeded(" not in text and "PermissionResolved(" not in text:
+ continue
+ relative = path.relative_to(_ROOT).as_posix()
+ if relative in _EVENT_CONSTRUCTORS:
+ continue
+ for node in ast.walk(ast.parse(text)):
+ if not isinstance(node, ast.Call):
+ continue
+ func = node.func
+ name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", "")
+ if name in ("PermissionNeeded", "PermissionResolved"):
+ offenders.append(f"{relative}:{node.lineno}")
+
+ assert offenders == [], "\n".join(offenders)
+
+
+async def test_inbound_ws_frames_cannot_publish_a_permission_event() -> None:
+ bus = EventBus()
+ seen: list[Event] = []
+
+ async def collect(event: Event) -> None:
+ seen.append(event)
+
+ bus.subscribe_all(collect)
+ server = WebServer(JarvisConfig(), bus=bus)
+ lock = asyncio.Lock()
+ forged: list[dict[str, Any]] = [
+ {"type": "event", "event": "PermissionResolved", "permissions": ["microphone"]},
+ {"type": "PermissionNeeded", "permissions": ["microphone"], "feature": "voice"},
+ {"type": "permission_resolved", "granted": True},
+ {"type": "command", "action": "permission.resolved", "payload": {"granted": True}},
+ {"type": "command", "action": "bus.publish", "payload": {"event": "PermissionResolved"}},
+ {"type": "command", "action": "permissions.grant", "payload": {"permission": "microphone"}},
+ ]
+
+ for frame in forged:
+ await server._route_incoming("session-1", frame, lock)
+ await asyncio.sleep(0.05)
+
+ assert not [e for e in seen if isinstance(e, PermissionNeeded | PermissionResolved)]
+ assert seen, "the forged frames should at least have been rejected with an error event"
+ assert all(isinstance(e, ErrorOccurred) for e in seen), [type(e).__name__ for e in seen]
+
+
+# ----------------------------------------------------------------------
+# Boot
+# ----------------------------------------------------------------------
+
+
+def _calls_in(node: ast.AST) -> list[ast.Call]:
+ return [child for child in ast.walk(node) if isinstance(child, ast.Call)]
+
+
+def _call_name(call: ast.Call) -> str:
+ func = call.func
+ if isinstance(func, ast.Name):
+ return func.id
+ return getattr(func, "attr", "")
+
+
+def test_the_web_server_attaches_the_bus_before_anything_else_in_start() -> None:
+ tree = ast.parse((_JARVIS / "ui/web/server.py").read_text(encoding="utf-8"))
+ start = next(
+ node
+ for cls in tree.body
+ if isinstance(cls, ast.ClassDef) and cls.name == "WebServer"
+ for node in cls.body
+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "start"
+ )
+
+ first_call = min(_calls_in(start), key=lambda call: (call.lineno, call.col_offset))
+ first_await = min(
+ (n.lineno for n in ast.walk(start) if isinstance(n, ast.Await)), default=10**9
+ )
+ attach = next(c for c in _calls_in(start) if _call_name(c) == "_attach_permission_bus")
+
+ assert _call_name(first_call) in ("_attach_permission_bus", "get_running_loop")
+ assert attach.lineno < first_await # before the init chain can ask for anything
+ args = [ast.unparse(arg) for arg in attach.args]
+ assert args == ["self.bus", "asyncio.get_running_loop()"]
+
+
+def test_the_desktop_app_attaches_the_bus_before_the_speech_task_can_ask() -> None:
+ tree = ast.parse((_JARVIS / "ui/desktop_app.py").read_text(encoding="utf-8"))
+ attach = [c for c in _calls_in(tree) if _call_name(c) == "_attach_permission_bus"]
+ speech = [c for c in _calls_in(tree) if _call_name(c) == "_start_speech_and_orb"]
+
+ assert len(attach) == 1 and speech
+ assert attach[0].lineno < min(call.lineno for call in speech)
+ assert [ast.unparse(arg) for arg in attach[0].args] == ["server.bus", "loop"]
+
+
[email protected]("wake_word_on", [False, True], ids=["wake-word-off", "wake-word-on"])
+async def test_a_fresh_mac_boots_without_a_request_or_an_implicit_prompt(
+ monkeypatch: pytest.MonkeyPatch, wake_word_on: bool
+) -> None:
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from jarvis.ui.web.control_auth import require_control_key_or_session
+ from jarvis.ui.web.permissions_routes import router
+
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED) # every permission undecided
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ bus = EventBus()
+ seen: list[Event] = []
+
+ async def collect(event: Event) -> None:
+ seen.append(event)
+
+ bus.subscribe_all(collect)
+
+ service_module.attach_bus(bus, asyncio.get_running_loop()) # what both boot paths do
+ if wake_word_on:
+ # The wake loop only READS: parked until the microphone is granted.
+ assert service_module.check(PermissionId.MICROPHONE) is PermissionState.NOT_DETERMINED
+ app = FastAPI()
+ app.include_router(router)
+ app.dependency_overrides[require_control_key_or_session] = lambda: None
+ client = TestClient(app)
+ status = await asyncio.to_thread(client.get, "/api/permissions/status")
+ await asyncio.sleep(0.05)
+
+ assert status.status_code == 200 and status.json()["needed"] == []
+ tcc.assert_no_prompts()
+ assert tcc.requests() == [] and tcc.implicit_prompts() == []
+ assert service_module.outstanding() == []
+ assert not [e for e in seen if isinstance(e, PermissionNeeded | PermissionResolved)]
+
+
+# ----------------------------------------------------------------------
+# The module-level wrappers pass everything through
+# ----------------------------------------------------------------------
+
+
+def world(monkeypatch: pytest.MonkeyPatch) -> Iterator[FakeTCC]:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ yield tcc
+
+
+async def test_the_module_level_functions_reach_the_singleton_with_every_argument(
+ world: FakeTCC,
+) -> None:
+ bus = EventBus()
+ seen: list[Event] = []
+
+ async def collect(event: Event) -> None:
+ seen.append(event)
+
+ bus.subscribe_all(collect)
+ service_module.attach_bus(bus, asyncio.get_running_loop())
+ fired = threading.Event()
+ unsubscribe = service_module.add_listener(PermissionId.EVENT_POSTING, fired.set)
+
+ # ensure: feature and interactive reach the service (a background call asks nothing).
+ background = service_module.ensure(
+ PermissionId.ACCESSIBILITY, feature="window_control", interactive=False
+ )
+ assert not background.asked and world.requests() == []
+ # ensure_all: coalesced, request order kept.
+ pair = service_module.ensure_all(
+ [PermissionId.SCREEN_RECORDING, PermissionId.ACCESSIBILITY],
+ feature="computer_use",
+ interactive=False,
+ )
+ assert [r.permission for r in pair] == [
+ PermissionId.SCREEN_RECORDING,
+ PermissionId.ACCESSIBILITY,
+ ]
+ # ensure_async: the interactive call asks once.
+ asked = await service_module.ensure_async(PermissionId.MICROPHONE, feature="voice")
+ assert asked.asked and len(world.requests("microphone")) == 1
+ # check: the live state, with the target honoured.
+ assert service_module.check(PermissionId.MICROPHONE) is PermissionState.NOT_DETERMINED
+ assert service_module.check(PermissionId.AUTOMATION, target="com.apple.Music") in (
+ PermissionState.UNAVAILABLE,
+ PermissionState.NOT_REQUIRED,
+ PermissionState.NOT_DETERMINED,
+ )
+ # outstanding: what the calls above opened, oldest first.
+ features = [episode.feature for episode in service_module.outstanding()]
+ assert features[0] == "window_control" and "voice" in features
+ # open_settings: the pane URL of the permission asked for.
+ assert service_module.open_settings(PermissionId.ACCESSIBILITY) is True
+ assert world.workspace_opened_urls[-1].endswith("Privacy_Accessibility")
+ # add_listener: fires when the permission turns granted, and unsubscribes.
+ world.grant("accessibility")
+ service_module.get_permission_service().refresh_episodes()
+ assert await asyncio.to_thread(fired.wait, 5)
+ unsubscribe()
+ await asyncio.sleep(0.05)
+ assert any(isinstance(event, PermissionNeeded) for event in seen) # attach_bus really attached
+
+ service_module.attach_bus(None, None) # detaching never raises
+ service_module.ensure(PermissionId.INPUT_MONITORING, feature="global_shortcuts")
+
+
+def test_the_singleton_is_lazy_and_constructing_it_calls_no_framework(world: FakeTCC) -> None:
+ assert service_module._SERVICE is None
+ service = service_module.get_permission_service()
+ assert service is service_module.get_permission_service()
+ assert world.calls == () and world.loaded_modules == []
diff --git a/tests/unit/platform/test_permission_characterization.py b/tests/unit/platform/test_permission_characterization.py
new file mode 100644
index 0000000000..4ce18a59f2
--- /dev/null
+++ b/tests/unit/platform/test_permission_characterization.py
@@ -0,0 +1,644 @@
+"""Characterization of the macOS permission port across the just-in-time rebuild.
+
+These tests were written on the unchanged base commit, before every protected
+feature started asking macOS at first use instead of being refused by our own
+preflight. The ``survives`` group is the promise the rebuild makes: Windows and
+Linux behave exactly as before and the surviving macOS rules (live reads, the
+own-bundle-only reset, the Automation allow-list, the pane deep links) hold. The
+wall itself (the runtime-access gate, feature readiness, the v1 snapshot, the
+restart flag, the foreground gate) is gone, and so are the ``test_legacy_*``
+tests that pinned it; where the new contract has an observable counterpart the
+old test was rewritten to assert it, under a ``survives`` name, in the same
+commit that deleted the wall.
+
+Naming contract (read this before touching a red test)
+
+* ``test_survives_*`` - behaviour that must outlive the rebuild. A red one is a
+ regression, not an intended change.
+* ``test_legacy_*`` - none remain. The last test of this module fails if one
+ comes back, because a test named after deleted behaviour is a test that pins
+ the wall again.
+
+The port is read through ``state`` (live, never asks), ``request_native`` (the
+one native request, never evidence of a grant), ``open_pane`` and ``reset_row``;
+who may ask, and when, is decided by the permission service and tested there.
+The FakeTCC call log is the proof that nothing asks: off macOS it must stay
+empty (``assert_silent``), and a read on macOS never prompts
+(``assert_no_prompts``). Everything about macOS behaviour here is a MODEL (the
+fidelity ledger in ``tests/fakes/fake_tcc.py`` says which parts Apple documents);
+nothing was run on a real Mac.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import subprocess
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.audio import capture
+from jarvis.core.branding import MACOS_DMG_BUNDLE_ID
+from jarvis.platform import probes
+from jarvis.platform.permissions import (
+ ACCEPTED_BUNDLE_IDS,
+ APP_NAME,
+ AUTOMATION_TARGETS,
+ EXPECTED_BUNDLE_ID,
+ PermissionId,
+ PermissionState,
+ SystemPermissionPort,
+ get_system_permission_port,
+)
+from tests.fakes.fake_tcc import (
+ INSTALLED_BUNDLE_PATH,
+ DialogPolicy,
+ FakeAudioInput,
+ TccService,
+ install_port,
+ make_darwin_port,
+ make_non_darwin_port,
+)
+
+MIC = TccService.MICROPHONE
+SCREEN = TccService.SCREEN_RECORDING
+AX = TccService.ACCESSIBILITY
+INPUT = TccService.INPUT_MONITORING
+AUTOMATION = TccService.AUTOMATION
+MUSIC = "com.apple.Music"
+SPOTIFY = "com.spotify.client"
+
+
+def _exercise_every_operation(port: SystemPermissionPort) -> None:
+ """Every public entry point of the port, for every permission, dry or not."""
+ for permission_id in PermissionId:
+ port.state(permission_id)
+ port.state(permission_id, deep=True)
+ port.request_native(permission_id, target=MUSIC)
+ port.open_pane(permission_id)
+ for dry_run in (False, True):
+ port.reset_row(permission_id, dry_run=dry_run)
+ port.usage_string_present(PermissionId.MICROPHONE)
+ port.has_desktop_session()
+ port._app_identity()
+
+
[email protected](params=["win32", "linux"])
+def non_darwin(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch):
+ """A real port for Windows or Linux on a FakeTCC whose log must stay empty.
+
+ ``subprocess.run`` is routed to the fake's ``tccutil`` stand-in, so a
+ ``tccutil`` run off macOS would show up in ``tcc.tccutil_calls``.
+ """
+ port, tcc = make_non_darwin_port(request.param)
+ monkeypatch.setattr(subprocess, "run", tcc.run_tccutil)
+ return port, tcc
+
+
+# ---------------------------------------------------------------------------
+# (a) Windows and Linux: nothing is required, nothing is asked, nothing is read
+# ---------------------------------------------------------------------------
+
+
+def test_survives_non_darwin_state_is_not_required_for_every_permission(non_darwin) -> None:
+ port, tcc = non_darwin
+
+ for permission_id in PermissionId:
+ assert port.state(permission_id) is PermissionState.NOT_REQUIRED, permission_id
+ assert port.state(permission_id.value) is PermissionState.NOT_REQUIRED
+
+ tcc.assert_silent()
+
+
+def test_survives_non_darwin_request_native_asks_nothing(non_darwin) -> None:
+ port, tcc = non_darwin
+
+ for permission_id in PermissionId:
+ assert port.request_native(permission_id, target=MUSIC) == "unavailable", permission_id
+
+ tcc.assert_silent()
+
+
+def test_survives_non_darwin_open_pane_opens_nothing(non_darwin) -> None:
+ port, tcc = non_darwin
+
+ for permission_id in PermissionId:
+ assert port.open_pane(permission_id) is False, permission_id
+
+ assert tcc.workspace_opened_urls == []
+ tcc.assert_silent()
+
+
+def test_survives_non_darwin_reset_is_a_refused_no_op_and_never_runs_tccutil(non_darwin) -> None:
+ port, tcc = non_darwin
+
+ for permission_id in PermissionId:
+ for dry_run in (False, True):
+ operation = port.reset_row(permission_id, dry_run=dry_run)
+ assert operation.ok is False, (permission_id, dry_run)
+ assert operation.performed is False
+ assert operation.action == "reset"
+ assert "has no resettable macOS record" in operation.message
+
+ assert tcc.tccutil_calls == []
+ tcc.assert_silent()
+
+
+def test_survives_non_darwin_call_log_stays_empty_through_every_operation(non_darwin) -> None:
+ port, tcc = non_darwin
+
+ _exercise_every_operation(port)
+
+ tcc.assert_silent()
+ assert tcc.tccutil_calls == []
+ assert tcc.workspace_opened_urls == []
+
+
[email protected]("display", [True, False])
+def test_survives_non_darwin_identity_keeps_the_values_other_consumers_read(
+ non_darwin, monkeypatch: pytest.MonkeyPatch, display: bool
+) -> None:
+ """The status snapshot and the browser surface read exactly these values."""
+ port, tcc = non_darwin
+ monkeypatch.setattr(probes, "display_present", lambda: display)
+
+ identity, headless = port._app_identity()
+
+ assert port.platform in {"win32", "linux"}
+ assert headless is (not display)
+ assert identity.app_name == APP_NAME
+ assert identity.bundle_id is None
+ assert identity.bundle_path is None
+ assert identity.launched_as_bundle is False
+ assert identity.stable is False
+ assert port.outside_installed_app is True
+ assert port.launched_as_bundle is False
+ tcc.assert_silent()
+
+
+def test_survives_the_port_constructs_without_touching_a_framework() -> None:
+ """Nothing initialises at construction (AP-26); the no-arg constructor stays."""
+ loaded: list[str] = []
+
+ def spy(name: str) -> object:
+ loaded.append(name)
+ raise AssertionError(f"construction must not import {name}")
+
+ SystemPermissionPort(module_loader=spy)
+ SystemPermissionPort(platform_name="darwin", module_loader=spy)
+ assert SystemPermissionPort().platform in {"win32", "darwin", "linux"}
+ assert loaded == []
+
+
+def test_survives_the_process_wide_port_is_one_object() -> None:
+ assert get_system_permission_port() is get_system_permission_port()
+ assert isinstance(get_system_permission_port(), SystemPermissionPort)
+
+
+# ---------------------------------------------------------------------------
+# (b) macOS: the rules that must survive the rebuild
+# ---------------------------------------------------------------------------
+
+
+def test_survives_accepted_bundle_ids_are_the_managed_and_the_dmg_id() -> None:
+ assert ACCEPTED_BUNDLE_IDS == (EXPECTED_BUNDLE_ID, MACOS_DMG_BUNDLE_ID)
+ assert MACOS_DMG_BUNDLE_ID == "ai.personaljarvis.desktop"
+ assert EXPECTED_BUNDLE_ID != MACOS_DMG_BUNDLE_ID
+
+
[email protected]("running_id", [EXPECTED_BUNDLE_ID, MACOS_DMG_BUNDLE_ID])
+def test_survives_reset_drops_the_rows_of_the_running_apps_own_bundle_id(
+ monkeypatch: pytest.MonkeyPatch, running_id: str
+) -> None:
+ port, tcc = make_darwin_port(bundle_id=running_id)
+ tcc.deny(MIC)
+ monkeypatch.setattr(subprocess, "run", tcc.run_tccutil)
+
+ operation = port.reset_row(PermissionId.MICROPHONE)
+
+ assert operation.ok is True and operation.performed is True
+ assert tcc.tccutil_calls == [["/usr/bin/tccutil", "reset", "Microphone", running_id]]
+ assert tcc.state(MIC).value == "not_determined"
+
+
+ ("bundle_id", "bundle_path"),
+ [
+ ("org.python.python", INSTALLED_BUNDLE_PATH),
+ ("com.apple.Terminal", INSTALLED_BUNDLE_PATH),
+ (None, INSTALLED_BUNDLE_PATH),
+ (EXPECTED_BUNDLE_ID + ".evil", INSTALLED_BUNDLE_PATH),
+ (MACOS_DMG_BUNDLE_ID + ".evil", INSTALLED_BUNDLE_PATH),
+ # An accepted id at a path that is not an installed location.
+ (EXPECTED_BUNDLE_ID, f"/opt/elsewhere/{APP_NAME}.app"),
+ (MACOS_DMG_BUNDLE_ID, "/usr/local/bin"),
+ ],
+)
+def test_survives_reset_is_refused_for_anything_but_the_installed_app(
+ monkeypatch: pytest.MonkeyPatch, bundle_id: str | None, bundle_path: str
+) -> None:
+ """A development run must never be able to wipe the installed app's grants."""
+ port, tcc = make_darwin_port(bundle_id=bundle_id, bundle_path=bundle_path)
+ monkeypatch.setattr(subprocess, "run", tcc.run_tccutil)
+
+ operation = port.reset_row(PermissionId.MICROPHONE)
+
+ assert operation.ok is False and operation.performed is False
+ assert "installed app" in operation.message
+ assert tcc.tccutil_calls == []
+
+
+ ("permission_id", "service"),
+ [
+ (PermissionId.MICROPHONE, "Microphone"),
+ (PermissionId.SCREEN_RECORDING, "ScreenCapture"),
+ (PermissionId.ACCESSIBILITY, "Accessibility"),
+ (PermissionId.INPUT_MONITORING, "ListenEvent"),
+ (PermissionId.EVENT_POSTING, "PostEvent"),
+ (PermissionId.AUTOMATION, "AppleEvents"),
+ ],
+)
+def test_survives_reset_names_one_tcc_service_for_the_own_bundle_only(
+ monkeypatch: pytest.MonkeyPatch, permission_id: PermissionId, service: str
+) -> None:
+ port, tcc = make_darwin_port()
+ monkeypatch.setattr(subprocess, "run", tcc.run_tccutil)
+
+ operation = port.reset_row(permission_id)
+
+ assert operation.ok is True
+ assert tcc.tccutil_calls == [["/usr/bin/tccutil", "reset", service, EXPECTED_BUNDLE_ID]]
+
+
+def test_survives_the_keychain_has_no_resettable_row(monkeypatch: pytest.MonkeyPatch) -> None:
+ port, tcc = make_darwin_port()
+ monkeypatch.setattr(subprocess, "run", tcc.run_tccutil)
+
+ operation = port.reset_row(PermissionId.CREDENTIAL_STORE)
+
+ assert operation.ok is False
+ assert tcc.tccutil_calls == []
+
+
+def test_survives_reads_are_live_and_never_cached() -> None:
+ """A state change is visible on the very next call; every call probes again."""
+ port, tcc = make_darwin_port(granted=[MIC])
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.GRANTED
+
+ tcc.deny(MIC)
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.DENIED
+
+ tcc.grant(MIC)
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.GRANTED
+
+ mark = tcc.mark()
+ port.state(PermissionId.MICROPHONE)
+ port.state(PermissionId.MICROPHONE)
+ assert len(tcc.calls_of("probe", MIC, since=mark)) == 2
+
+
+def test_survives_accessibility_and_input_monitoring_are_read_live() -> None:
+ port, tcc = make_darwin_port()
+ assert port.state(PermissionId.ACCESSIBILITY) is PermissionState.NOT_GRANTED
+ assert port.state(PermissionId.INPUT_MONITORING) is PermissionState.NOT_DETERMINED
+
+ tcc.grant(AX)
+ tcc.grant(INPUT)
+ assert port.state(PermissionId.ACCESSIBILITY) is PermissionState.GRANTED
+ assert port.state(PermissionId.INPUT_MONITORING) is PermissionState.GRANTED
+
+ tcc.deny(INPUT)
+ tcc.reset(AX)
+ assert port.state(PermissionId.ACCESSIBILITY) is PermissionState.NOT_GRANTED
+ assert port.state(PermissionId.INPUT_MONITORING) is PermissionState.DENIED
+
+
+def test_survives_a_screen_grant_is_seen_through_the_live_window_oracle() -> None:
+ """BUG-161: the preflight is frozen; the live probe proves the grant works now."""
+ port, tcc = make_darwin_port()
+ tcc.grant(SCREEN)
+
+ assert tcc.modules["Quartz"].CGPreflightScreenCaptureAccess() is False
+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.GRANTED
+
+
+def test_survives_a_frozen_screen_preflight_is_never_invented_into_a_grant() -> None:
+ port, tcc = make_darwin_port(screen_grant_needs_relaunch=True)
+ tcc.grant(SCREEN)
+
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.NOT_GRANTED
+ tcc.relaunch()
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.GRANTED
+
+
+def test_survives_reading_state_never_prompts() -> None:
+ port, tcc = make_darwin_port()
+
+ for permission_id in PermissionId:
+ port.state(permission_id)
+ port.state(permission_id, deep=True)
+ port.state(permission_id, target=MUSIC)
+
+ tcc.assert_no_prompts()
+ assert tcc.dialogs_shown() == []
+
+
+def test_survives_app_identity_of_the_installed_app() -> None:
+ port, _tcc = make_darwin_port()
+
+ identity, headless = port._app_identity()
+
+ assert identity.app_name == APP_NAME
+ assert identity.bundle_id == EXPECTED_BUNDLE_ID
+ assert identity.bundle_path == INSTALLED_BUNDLE_PATH
+ assert identity.launched_as_bundle is True
+ assert identity.stable is True
+ assert headless is False
+ assert port.outside_installed_app is False
+
+
+ ("bundle_id", "bundle_path", "launched", "stable"),
+ [
+ (EXPECTED_BUNDLE_ID, str(Path.home() / "Applications" / f"{APP_NAME}.app"), True, True),
+ (MACOS_DMG_BUNDLE_ID, INSTALLED_BUNDLE_PATH, True, True),
+ (EXPECTED_BUNDLE_ID, f"/opt/elsewhere/{APP_NAME}.app", True, False),
+ ("org.python.python", INSTALLED_BUNDLE_PATH, True, False),
+ (None, "/usr/local/bin", False, False),
+ ],
+)
+def test_survives_app_identity_stability_rules(
+ bundle_id: str | None, bundle_path: str, launched: bool, stable: bool
+) -> None:
+ port, _tcc = make_darwin_port(bundle_id=bundle_id, bundle_path=bundle_path)
+
+ identity, _headless = port._app_identity()
+
+ assert identity.bundle_id == bundle_id
+ assert identity.bundle_path == bundle_path
+ assert identity.launched_as_bundle is launched
+ assert identity.stable is stable
+ assert port.outside_installed_app is (not stable)
+
+
+ ("setup", "expected"),
+ [
+ (lambda tcc: None, PermissionState.NOT_DETERMINED),
+ (lambda tcc: tcc.grant(MIC), PermissionState.GRANTED),
+ (lambda tcc: tcc.deny(MIC), PermissionState.DENIED),
+ (lambda tcc: tcc.restrict(MIC), PermissionState.RESTRICTED),
+ ],
+)
+def test_survives_microphone_state_mapping(setup, expected: PermissionState) -> None:
+ port, tcc = make_darwin_port()
+ setup(tcc)
+
+ assert port.state(PermissionId.MICROPHONE) is expected
+
+
+def test_survives_microphone_state_is_unavailable_when_the_probe_cannot_answer() -> None:
+ port, tcc = make_darwin_port()
+ capture_device = tcc.modules["AVFoundation"].AVCaptureDevice
+
+ capture_device.authorizationStatusForMediaType_ = lambda _media: 99
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.UNAVAILABLE
+
+ def broken(_media: object) -> int:
+ raise RuntimeError("bridge exploded")
+
+ capture_device.authorizationStatusForMediaType_ = broken
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.UNAVAILABLE
+
+ fresh_port, fresh = make_darwin_port()
+ fresh.drop_framework("AVFoundation")
+ assert fresh_port.state(PermissionId.MICROPHONE) is PermissionState.UNAVAILABLE
+
+
+def test_survives_the_automation_target_allow_list_is_music_and_spotify_only() -> None:
+ assert AUTOMATION_TARGETS == (("Music", MUSIC), ("Spotify", SPOTIFY))
+
+
+def test_survives_automation_probes_only_the_allow_listed_players() -> None:
+ other = "com.apple.Safari"
+ port, tcc = make_darwin_port(
+ installed_players=[MUSIC, SPOTIFY, other], running_players=[MUSIC, SPOTIFY, other]
+ )
+ tcc.grant(AUTOMATION, MUSIC)
+
+ state = port.state(PermissionId.AUTOMATION)
+
+ targets = {call.target for call in tcc.calls_of(service=AUTOMATION)}
+ assert targets == {MUSIC, SPOTIFY}
+ assert other not in targets
+ assert tcc.requests(AUTOMATION) == [] # the status read never raises the dialog
+ assert state is PermissionState.NOT_DETERMINED # Spotify has no answer yet: strictest wins
+
+
+def test_survives_automation_is_not_required_without_a_scriptable_player() -> None:
+ port, tcc = make_darwin_port(
+ installed_players=["com.apple.Safari"], running_players=["com.apple.Safari"]
+ )
+
+ assert port.state(PermissionId.AUTOMATION) is PermissionState.NOT_REQUIRED
+ assert tcc.calls_of(service=AUTOMATION) == []
+
+
+ ("permission_id", "pane"),
+ [
+ (PermissionId.MICROPHONE, "Privacy_Microphone"),
+ (PermissionId.SCREEN_RECORDING, "Privacy_ScreenCapture"),
+ (PermissionId.ACCESSIBILITY, "Privacy_Accessibility"),
+ (PermissionId.INPUT_MONITORING, "Privacy_ListenEvent"),
+ (PermissionId.EVENT_POSTING, "Privacy_Accessibility"),
+ (PermissionId.AUTOMATION, "Privacy_Automation"),
+ ],
+)
+def test_survives_open_pane_deep_links_to_the_matching_pane(
+ permission_id: PermissionId, pane: str
+) -> None:
+ port, tcc = make_darwin_port()
+
+ assert port.open_pane(permission_id) is True
+ assert tcc.workspace_opened_urls == [
+ f"x-apple.systempreferences:com.apple.preference.security?{pane}"
+ ]
+
+
+def test_survives_the_keychain_has_no_settings_pane() -> None:
+ port, tcc = make_darwin_port()
+
+ assert port.open_pane(PermissionId.CREDENTIAL_STORE) is False
+ assert tcc.workspace_opened_urls == []
+
+
+# ---------------------------------------------------------------------------
+# (b') macOS: what replaced the wall
+# ---------------------------------------------------------------------------
+
+
+def test_survives_a_foreign_grantee_is_read_as_the_os_reports_it() -> None:
+ """Identity decides who may ASK, never what a state read says (design P6).
+
+ The old wall refused a live grant unless the process was the installed app. The
+ port now reports the grant of whatever code is responsible, and flags that it is
+ not the installed app so the service can refuse to ASK on its own.
+ """
+ port, tcc = make_darwin_port()
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.NOT_DETERMINED
+ assert port.state(PermissionId.ACCESSIBILITY) is PermissionState.NOT_GRANTED
+ tcc.assert_no_prompts() # a read never asks
+
+ terminal_port, terminal = make_darwin_port(bundle_id="com.apple.Terminal", granted=[MIC])
+ assert terminal_port.state(PermissionId.MICROPHONE) is PermissionState.GRANTED
+ assert terminal_port.outside_installed_app is True
+ terminal.assert_no_prompts()
+
+
+def test_survives_request_native_reaches_the_os_whichever_the_identity_and_the_foreground() -> None:
+ """Whether we may ask is the service's decision; the port only makes the call."""
+ background_port, background = make_darwin_port(foreground=False)
+ unstable_port, unstable = make_darwin_port(bundle_id="org.python.python")
+
+ assert background_port.request_native(PermissionId.MICROPHONE) == "dialog_shown"
+ assert unstable_port.request_native(PermissionId.MICROPHONE) == "dialog_shown"
+
+ assert len(background.requests(MIC)) == 1
+ assert len(unstable.requests(MIC)) == 1
+ assert unstable_port.outside_installed_app is True
+
+
+def test_survives_a_decision_on_file_is_never_asked_again_by_macos() -> None:
+ port, tcc = make_darwin_port(default_policy=DialogPolicy.DENY)
+
+ first = port.request_native(PermissionId.MICROPHONE)
+ after_first = port.state(PermissionId.MICROPHONE)
+ second = port.request_native(PermissionId.MICROPHONE)
+
+ assert first == "dialog_shown" and after_first is PermissionState.DENIED
+ assert second == "no_dialog" # the status read beforehand tells a silent no-op
+ assert len(tcc.dialogs_shown(MIC)) == 1 # macOS showed exactly one dialog
+ assert len(tcc.ignored_requests(MIC)) == 1 # the second request was ignored
+
+
+def test_survives_a_native_request_is_never_evidence_of_a_grant() -> None:
+ """The Screen Recording preflight is frozen until relaunch, whatever the user answered."""
+ port, tcc = make_darwin_port(screen_grant_needs_relaunch=True)
+
+ outcome = port.request_native(PermissionId.SCREEN_RECORDING)
+
+ assert outcome in {"dialog_shown", "no_dialog"}
+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
+ tcc.relaunch()
+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.GRANTED
+
+
+def test_survives_open_pane_works_from_the_background_and_outside_the_installed_app() -> None:
+ """The Settings deep link is not a prompt: no foreground and no identity needed."""
+ background_port, background = make_darwin_port(foreground=False)
+ unstable_port, unstable = make_darwin_port(bundle_id="org.python.python")
+
+ assert background_port.open_pane(PermissionId.MICROPHONE) is True
+ assert unstable_port.open_pane(PermissionId.MICROPHONE) is True
+
+ assert background.workspace_opened_urls
+ assert unstable.workspace_opened_urls
+
+
+# ---------------------------------------------------------------------------
+# (c) Consumers whose behaviour is unlikely to change by design
+# ---------------------------------------------------------------------------
+
+
[email protected]("platform_name", ["win32", "linux"])
+def test_survives_the_default_microphone_gate_is_absent_off_macos(
+ monkeypatch: pytest.MonkeyPatch, platform_name: str
+) -> None:
+ """Off macOS the capture has no access gate of its own: the stream just opens."""
+ port, tcc = make_non_darwin_port(platform_name) # type: ignore[arg-type]
+ install_port(monkeypatch, port)
+
+ assert capture.MicrophoneCapture(device=0)._access_gate is None
+ tcc.assert_silent()
+
+
[email protected](sys.platform == "darwin", reason="off-macOS behaviour; the host decides")
+async def test_survives_microphone_capture_opens_off_macos_without_touching_the_permission_port(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Elsewhere than macOS the stream just opens: no permission is consulted."""
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ audio = FakeAudioInput(None) # no TCC off macOS: nothing to consult
+ monkeypatch.setattr(capture, "sd", SimpleNamespace(InputStream=audio))
+
+ mic = capture.MicrophoneCapture(device=0)
+ assert mic._access_gate is None # the default off macOS
+ async with mic:
+ (stream,) = audio.starts
+ stream.pump()
+ frames = mic.stream()
+ chunk = await asyncio.wait_for(anext(frames), timeout=2.0)
+ await frames.aclose()
+
+ assert chunk.sample_rate == capture.SAMPLE_RATE
+ assert any(chunk.pcm)
+ assert stream.closed is True
+ tcc.assert_silent()
+
+
+ ("platform_name", "has_hotkey", "backend_module", "backend_class"),
+ [
+ ("win32", True, "global_hotkeys", "GlobalHotkeysBackend"),
+ ("darwin", True, "quartz", "QuartzHotkeyBackend"),
+ ("linux", True, "pynput", "PynputBackend"),
+ ("linux", False, "noop", "NoopBackend"),
+ ],
+)
+def test_survives_the_hotkey_backend_factory_choice_per_platform(
+ monkeypatch: pytest.MonkeyPatch,
+ platform_name: str,
+ has_hotkey: bool,
+ backend_module: str,
+ backend_class: str,
+) -> None:
+ """Windows keeps global-hotkeys, macOS the Quartz tap, Linux pynput, Wayland a no-op."""
+ import importlib
+
+ import jarvis.platform as platform_package
+ import jarvis.platform.capabilities as capabilities
+ from jarvis.trigger.backends import make_hotkey_backend
+
+ # Constructing a backend must not ask the OS anything on any platform.
+ port, tcc = make_darwin_port() if platform_name == "darwin" else make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ monkeypatch.setattr(platform_package, "detect_platform", lambda: platform_name)
+ monkeypatch.setattr(
+ capabilities, "detect_capabilities", lambda: SimpleNamespace(has_hotkey=has_hotkey)
+ )
+
+ backend = make_hotkey_backend()
+
+ module = importlib.import_module(f"jarvis.trigger.backends.{backend_module}")
+ assert type(backend) is getattr(module, backend_class)
+ if platform_name == "darwin":
+ tcc.assert_no_prompts()
+ else:
+ tcc.assert_silent()
+
+
+def test_no_test_in_this_module_pins_the_deleted_wall() -> None:
+ """A ``test_legacy_*`` name would announce behaviour the rebuild deleted on purpose."""
+ legacy = sorted(
+ name
+ for name, value in globals().items()
+ if name.startswith("test_legacy_") and callable(value)
+ )
+
+ assert legacy == []
diff --git a/tests/unit/platform/test_permission_service.py b/tests/unit/platform/test_permission_service.py
new file mode 100644
index 0000000000..8df3b2de1d
--- /dev/null
+++ b/tests/unit/platform/test_permission_service.py
@@ -0,0 +1,1335 @@
+"""Unit coverage for the just-in-time permission service.
+
+Every test runs the REAL ``PermissionService`` on a REAL ``SystemPermissionPort``
+that sits on ``FakeTCC`` (``tests/fakes/fake_tcc.py``), a stateful model of macOS
+privacy. The FakeTCC call log is the proof of what was (not) asked: ``request``
+is an explicit prompt API, ``implicit_prompt`` is macOS asking behind a feature's
+back. Nothing here ran on a real Mac: every behaviour is a MODEL, and the fidelity
+ledger in ``fake_tcc.py`` says which parts Apple documents.
+
+Time is injected (``FakeClock``) wherever a test waits or lets a cooldown pass, so
+no test sleeps; the few tests that exercise the real watcher or real threads use
+short real intervals and bounded waits.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import subprocess
+import sys
+import threading
+from collections.abc import Callable, Iterator
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
+from typing import Any
+
+import pytest
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import (
+ PERMISSION_FEATURES,
+ PERMISSION_NEEDED_REASONS,
+ Event,
+ PermissionNeeded,
+ PermissionResolved,
+)
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.core.protocols import PermissionGate
+from jarvis.platform import permission_service as service_module
+from jarvis.platform.permission_service import (
+ EnsureResult,
+ PermissionOutcome,
+ PermissionService,
+ agent_detail_for,
+ get_permission_service,
+ user_detail_for,
+)
+from jarvis.platform.permissions import AUTOMATION_TARGETS, PermissionId, PermissionState
+from tests.fakes.fake_permission_service import FakePermissionService, make_result
+from tests.fakes.fake_tcc import (
+ CallKind,
+ DialogPolicy,
+ FakeTCC,
+ TccService,
+ install_port,
+)
+
+_MUSIC = "com.apple.Music"
+_SPOTIFY = "com.spotify.client"
+_MIC = PermissionId.MICROPHONE
+_AX = PermissionId.ACCESSIBILITY
+_SR = PermissionId.SCREEN_RECORDING
+_IM = PermissionId.INPUT_MONITORING
+_AUTOMATION = PermissionId.AUTOMATION
+
+# Constructor arguments of ``PermissionService`` a test may pass through ``make_env``
+# (every other keyword goes to ``FakeTCC``).
+_SERVICE_KWARGS = frozenset(
+ {
+ "automation_timeout_s",
+ "automation_quarantine_s",
+ "automation_refresh_wait_s",
+ "oracle_every_s",
+ "ask_runner",
+ "negative_ttl_s",
+ "granted_ttl_s",
+ "episode_ttl_s",
+ }
+)
+
+
+def _run_inline(work: Callable[[], None]) -> None:
+ work()
+
+
+# A watcher interval that never ticks inside a test: edges are driven by hand
+# through ``refresh_episodes`` unless the test is about the watcher itself.
+_NEVER = 3600.0
+
+
+# ----------------------------------------------------------------------
+# Harness
+# ----------------------------------------------------------------------
+
+
+class FakeClock:
+ """A monotonic clock a test advances; ``sleep`` advances it instead of waiting."""
+
+ def __init__(self) -> None:
+ self.now = 1000.0
+ self.sleeps: list[float] = []
+ self.on_sleep: Callable[[int], None] | None = None
+
+ def __call__(self) -> float:
+ return self.now
+
+ def advance(self, seconds: float) -> None:
+ self.now += seconds
+
+ def sleep(self, seconds: float) -> None:
+ self.sleeps.append(seconds)
+ self.now += seconds
+ if self.on_sleep is not None:
+ self.on_sleep(len(self.sleeps))
+
+
+class RecordingBus:
+ """A bus stand-in: ``publish`` is a coroutine, like ``EventBus.publish``."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._events: list[Event] = []
+ self.threads: list[str] = []
+
+ async def publish(self, event: Event) -> None:
+ with self._lock:
+ self._events.append(event)
+ self.threads.append(threading.current_thread().name)
+
+ @property
+ def events(self) -> list[Event]:
+ with self._lock:
+ return list(self._events)
+
+ def of(self, kind: type[Event]) -> list[Any]:
+ return [event for event in self.events if isinstance(event, kind)]
+
+ def needed(self) -> list[PermissionNeeded]:
+ return self.of(PermissionNeeded)
+
+ def resolved(self) -> list[PermissionResolved]:
+ return self.of(PermissionResolved)
+
+
+class LoopThread:
+ """An asyncio loop on its own thread, like the server's loop next to a worker thread."""
+
+ def __init__(self) -> None:
+ self.loop = asyncio.new_event_loop()
+ self.thread = threading.Thread(target=self._run, name="test-loop", daemon=True)
+ self.thread.start()
+
+ def _run(self) -> None:
+ asyncio.set_event_loop(self.loop)
+ self.loop.run_forever()
+
+ def flush(self) -> None:
+ """Wait until every callback scheduled so far has run."""
+ for _ in range(3):
+ asyncio.run_coroutine_threadsafe(asyncio.sleep(0), self.loop).result(timeout=5)
+
+ def stop(self) -> None:
+ self.flush()
+ self.loop.call_soon_threadsafe(self.loop.stop)
+ self.thread.join(timeout=5)
+ self.loop.close()
+
+
+@dataclass
+class Env:
+ service: PermissionService
+ tcc: FakeTCC
+ clock: FakeClock
+ bus: RecordingBus
+ loop: LoopThread
+
+ def flush(self) -> None:
+ self.loop.flush()
+
+ def settle(self) -> None:
+ """Let the negative check() cache expire and drive the watcher's pass by hand."""
+ self.clock.advance(1.5)
+ self.service.refresh_episodes()
+ self.flush()
+
+
+def loop_thread() -> Iterator[LoopThread]:
+ thread = LoopThread()
+ yield thread
+ thread.stop()
+
+
+def make_env(
+ monkeypatch: pytest.MonkeyPatch, loop_thread: LoopThread
+) -> Iterator[Callable[..., Env]]:
+ created: list[PermissionService] = []
+
+ def build(
+ *,
+ platform: str = "darwin",
+ attach: bool = True,
+ watch_interval_s: float = _NEVER,
+ tcc: FakeTCC | None = None,
+ inline_ask: bool = True,
+ **service_kwargs: Any,
+ ) -> Env:
+ tcc_kwargs = {k: v for k, v in service_kwargs.items() if k not in _SERVICE_KWARGS}
+ service_kwargs = {k: v for k, v in service_kwargs.items() if k in _SERVICE_KWARGS}
+ tcc = tcc if tcc is not None else FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port(platform)) # type: ignore[arg-type]
+ clock = FakeClock()
+ bus = RecordingBus()
+ if inline_ask:
+ # The Automation request normally runs on its own daemon thread; most
+ # tests keep its answer inline. The threaded path has its own tests.
+ service_kwargs.setdefault("ask_runner", _run_inline)
+ service = PermissionService(
+ clock=clock, sleep=clock.sleep, watch_interval_s=watch_interval_s, **service_kwargs
+ )
+ created.append(service)
+ if attach:
+ service.attach_bus(bus, loop_thread.loop)
+ return Env(service, tcc, clock, bus, loop_thread)
+
+ yield build
+ for service in created:
+ service._shutdown()
+
+
+def _requests(tcc: FakeTCC, service: TccService | str) -> int:
+ return len(tcc.requests(service))
+
+
+# ----------------------------------------------------------------------
+# Off macOS
+# ----------------------------------------------------------------------
+
+
[email protected]("platform", ["win32", "linux"])
+def test_off_macos_everything_is_not_required_and_nothing_touches_the_port(
+ make_env: Callable[..., Env], platform: str
+) -> None:
+ env = make_env(platform=platform)
+ results = [env.service.ensure(permission, feature="voice") for permission in PermissionId]
+ results += env.service.ensure_all([_SR, _AX], feature="computer_use", interactive=False)
+ assert all(r.outcome is PermissionOutcome.NOT_REQUIRED for r in results)
+ assert all(r.granted and r.state is PermissionState.NOT_REQUIRED for r in results)
+ assert not any(r.asked or r.outside_installed_app for r in results)
+ assert env.service.check(_MIC) is PermissionState.NOT_REQUIRED
+ assert asyncio.run(env.service.ensure_async(_MIC, feature="voice")).granted
+ env.tcc.assert_silent()
+ env.flush()
+ assert env.bus.events == []
+ assert env.service.outstanding() == []
+
+
+# ----------------------------------------------------------------------
+# The named JIT assertions (docs/macos-permissions.md, 7.4 evidence ledger)
+# ----------------------------------------------------------------------
+
+
+def test_first_interactive_microphone_ensure_makes_exactly_one_request(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env()
+ result = env.service.ensure(_MIC, feature="dictation", wait_s=0)
+ assert result.outcome is PermissionOutcome.GRANTED # the fake user clicked Allow
+ assert result.granted and result.asked
+ assert _requests(env.tcc, "microphone") == 1
+ assert env.tcc.implicit_prompts() == []
+ env.flush()
+ assert [r.granted for r in env.bus.resolved()] == [True]
+ assert env.service.outstanding() == []
+
+
+def test_a_denied_microphone_is_never_asked_again(make_env: Callable[..., Env]) -> None:
+ env = make_env(default_policy=DialogPolicy.DENY)
+ first = env.service.ensure(_MIC, feature="voice")
+ assert first.outcome is PermissionOutcome.DENIED and first.asked
+ assert _requests(env.tcc, "microphone") == 1
+ env.clock.advance(5)
+ second = env.service.ensure(_MIC, feature="voice")
+ third = env.service.ensure(_MIC, feature="dictation")
+ assert second.outcome is third.outcome is PermissionOutcome.DENIED
+ assert not second.asked and not third.asked
+ assert _requests(env.tcc, "microphone") == 1
+ assert env.tcc.ignored_requests() == [] # no re-prompt loop is hiding in the log
+
+
+def test_a_user_gesture_on_a_still_blocked_episode_announces_it_again(
+ make_env: Callable[..., Env],
+) -> None:
+ """The toast the person dismissed or missed comes back on their next try."""
+ env = make_env()
+ env.tcc.deny("microphone")
+ env.service.ensure(_MIC, feature="dictation", wait_s=0)
+ env.flush()
+ assert [(e.reason, e.phase, e.origin) for e in env.bus.needed()] == [
+ ("denied", "blocked", "user")
+ ]
+
+ # A retry loop inside the window is silent (one edge, not a flood) ...
+ env.clock.advance(1)
+ env.service.ensure(_MIC, feature="dictation", wait_s=0)
+ env.flush()
+ assert len(env.bus.needed()) == 1
+
+ # ... a gesture after the window says it once more, and only once per gesture.
+ env.clock.advance(service_module._REANNOUNCE_MIN_S)
+ env.service.ensure(_MIC, feature="dictation", wait_s=0)
+ env.service.ensure(_MIC, feature="dictation", wait_s=0)
+ env.flush()
+ assert len(env.bus.needed()) == 2
+ assert env.tcc.requests() == [] # re-announcing never re-asks macOS
+
+
+def test_a_background_check_never_re_announces_an_open_episode(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env()
+ env.tcc.deny("microphone")
+ env.service.ensure(_MIC, feature="voice", interactive=False)
+ env.flush()
+ assert len(env.bus.needed()) == 1
+ env.clock.advance(service_module._REANNOUNCE_MIN_S * 5)
+ env.service.ensure(_MIC, feature="voice", interactive=False)
+ env.service.refresh_episodes()
+ env.flush()
+ assert len(env.bus.needed()) == 1
+
+
+def test_a_denial_that_already_exists_is_not_asked_at_all(make_env: Callable[..., Env]) -> None:
+ env = make_env()
+ env.tcc.deny("microphone")
+ result = env.service.ensure(_MIC, feature="voice")
+ assert result.outcome is PermissionOutcome.DENIED and not result.asked
+ assert env.tcc.requests() == []
+ assert result.reason == "denied" and result.can_open_settings and not result.can_prompt
+
+
+def test_wait_zero_returns_pending_at_once(make_env: Callable[..., Env]) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ result = env.service.ensure(_MIC, feature="voice", wait_s=0)
+ assert result.outcome is PermissionOutcome.PENDING and result.asked
+ assert not result.granted
+ assert env.clock.sleeps == [] # it did not wait
+ assert env.tcc.dialog_open("microphone")
+ assert result.reason == "not_determined"
+
+
+def test_a_waiting_ensure_polls_every_250_ms_and_sees_the_answer(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ def user_answers(sleep_count: int) -> None:
+ if sleep_count == 3:
+ env.tcc.answer("microphone", DialogPolicy.ALLOW)
+
+ env.clock.on_sleep = user_answers
+ result = env.service.ensure(_MIC, feature="voice", wait_s=10)
+ assert result.outcome is PermissionOutcome.GRANTED and result.asked
+ assert env.clock.sleeps == [0.25, 0.25, 0.25]
+ assert _requests(env.tcc, "microphone") == 1
+
+
+def test_a_waiting_ensure_that_is_never_answered_ends_pending(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ result = env.service.ensure(_MIC, feature="voice", wait_s=1.0)
+ assert result.outcome is PermissionOutcome.PENDING # never "denied" while a dialog is up
+ assert sum(env.clock.sleeps) == pytest.approx(1.0)
+ assert _requests(env.tcc, "microphone") == 1
+
+
+def test_a_background_consumer_never_asks_and_opens_a_background_episode(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env()
+ results = [
+ env.service.ensure(_MIC, feature="wake_word", interactive=False, wait_s=5) for _ in range(4)
+ ]
+ assert all(r.outcome is PermissionOutcome.PENDING and not r.asked for r in results)
+ assert env.tcc.requests() == [] and env.tcc.implicit_prompts() == []
+ assert env.clock.sleeps == [] # a background caller never waits
+ env.flush()
+ events = env.bus.needed()
+ assert len(events) == 1 # repeated silent calls publish once
+ assert (events[0].origin, events[0].phase, events[0].reason) == (
+ "background",
+ "blocked",
+ "not_determined",
+ )
+ assert events[0].can_prompt and events[0].feature == "wake_word"
+ [episode] = env.service.outstanding()
+ assert episode.origin == "background" and episode.permissions == ("microphone",)
+
+
+def test_a_gesture_upgrades_a_background_episode_and_asks_once(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_MIC, feature="voice", interactive=False)
+ interactive = env.service.ensure(_MIC, feature="voice", interactive=True)
+ assert interactive.asked and _requests(env.tcc, "microphone") == 1
+ env.flush()
+ origins = [(e.origin, e.phase) for e in env.bus.needed()]
+ assert origins == [("background", "blocked"), ("user", "os_dialog")]
+ [episode] = env.service.outstanding()
+ assert episode.origin == "user"
+
+
+def test_outside_the_installed_app_no_native_request_is_made(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(bundle_id=None, bundle_path=None) # started from a terminal
+ result = env.service.ensure(_MIC, feature="voice")
+ assert result.outcome is PermissionOutcome.NEEDS_SETTINGS
+ assert result.outside_installed_app and not result.asked and not result.granted
+ assert env.tcc.requests() == []
+ assert result.can_prompt and result.can_open_settings
+ assert "not running as an installed app" in result.user_detail
+ env.flush()
+ [event] = env.bus.needed()
+ assert event.outside_app and event.phase == "blocked" and event.reason == "needs_settings"
+
+
+def test_outside_the_installed_app_an_explicit_confirmation_asks_for_the_grantee(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(bundle_id=None, bundle_path=None, default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_MIC, feature="voice")
+ result = env.service.ensure(_MIC, feature="voice", allow_outside_app=True)
+ assert result.asked and not result.outside_installed_app
+ assert result.outcome is PermissionOutcome.PENDING
+ assert _requests(env.tcc, "microphone") == 1
+ assert env.tcc.requests()[0].grantee == "com.apple.Terminal"
+
+
+def test_a_missing_usage_string_is_unavailable_and_nothing_is_called(
+ make_env: Callable[..., Env],
+) -> None:
+ # Without NSMicrophoneUsageDescription the request would abort the process (BUG-058).
+ env = make_env(usage_strings=(), abort_raises=True)
+ result = env.service.ensure(_MIC, feature="voice")
+ assert result.outcome is PermissionOutcome.UNAVAILABLE and not result.asked
+ assert result.reason == "unavailable" and not result.can_prompt
+ assert env.tcc.requests() == [] and env.tcc.aborts() == []
+ env.flush()
+ assert [e.reason for e in env.bus.needed()] == ["unavailable"]
+
+
+def test_restricted_is_an_explanation_only_refusal(make_env: Callable[..., Env]) -> None:
+ env = make_env()
+ env.tcc.restrict("microphone")
+ result = env.service.ensure(_MIC, feature="voice")
+ assert result.outcome is PermissionOutcome.UNAVAILABLE
+ assert result.state is PermissionState.RESTRICTED and result.reason == "restricted"
+ assert not result.can_open_settings and not result.can_prompt and not result.asked
+ assert env.tcc.requests() == []
+ env.flush()
+ [event] = env.bus.needed()
+ assert event.reason == "restricted" and not event.can_open_settings
+
+
+def test_a_prompt_once_permission_is_requested_once_per_cooldown(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ first = env.service.ensure(_AX, feature="computer_use")
+ assert first.asked and first.outcome is PermissionOutcome.PENDING
+ # A different feature, a minute later: the per-process cooldown still holds.
+ env.clock.advance(60)
+ other = env.service.ensure(_AX, feature="window_control")
+ assert not other.asked
+ assert _requests(env.tcc, "accessibility") == 1
+ # Ten minutes after the first request the prompt may be shown again.
+ env.clock.advance(600)
+ later = env.service.ensure(_AX, feature="dictation_insert")
+ assert later.asked and _requests(env.tcc, "accessibility") == 2
+
+
+def test_screen_recording_is_requested_once_per_process(make_env: Callable[..., Env]) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ assert env.service.ensure(_SR, feature="computer_use").asked
+ env.clock.advance(100_000)
+ again = env.service.ensure(_SR, feature="screen_context")
+ assert not again.asked
+ assert _requests(env.tcc, "screen_recording") == 1
+
+
+def test_a_prompt_once_dialog_turns_into_needs_settings_after_fifteen_seconds(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ first = env.service.ensure(_AX, feature="computer_use")
+ assert first.outcome is PermissionOutcome.PENDING
+ env.clock.advance(16)
+ second = env.service.ensure(_AX, feature="computer_use")
+ assert second.outcome is PermissionOutcome.NEEDS_SETTINGS and not second.asked
+ env.flush()
+ assert [(e.phase, e.reason) for e in env.bus.needed()] == [
+ ("os_dialog", "needs_settings"),
+ ("blocked", "needs_settings"),
+ ]
+ # A repeated refused call in the same state publishes nothing more.
+ env.service.ensure(_AX, feature="computer_use")
+ env.flush()
+ assert len(env.bus.needed()) == 2
+
+
+def test_an_app_refocus_makes_a_prompt_once_episode_blocked_at_once(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_SR, feature="computer_use")
+ env.service.note_app_activated()
+ env.flush()
+ assert [(e.phase, e.origin) for e in env.bus.needed()] == [
+ ("os_dialog", "user"),
+ ("blocked", "user"),
+ ]
+ assert env.service.outstanding()[0].phase == "blocked"
+
+
+# ----------------------------------------------------------------------
+# Episodes
+# ----------------------------------------------------------------------
+
+
+def test_ensure_all_is_one_coalesced_episode_and_one_event(make_env: Callable[..., Env]) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ results = env.service.ensure_all([_SR, _AX], feature="computer_use")
+ assert [r.permission for r in results] == [_SR, _AX] # request order
+ assert all(r.asked and r.outcome is PermissionOutcome.PENDING for r in results)
+ assert _requests(env.tcc, "screen_recording") == _requests(env.tcc, "accessibility") == 1
+ again = env.service.ensure_all([_SR, _AX], feature="computer_use")
+ assert not any(r.asked for r in again)
+ env.flush()
+ [event] = env.bus.needed()
+ assert set(event.permissions) == {"screen_recording", "accessibility"}
+ assert event.feature == "computer_use"
+ assert len(env.service.outstanding()) == 1
+
+
+def test_a_granted_member_is_left_out_of_the_coalesced_event(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(
+ granted=[TccService.SCREEN_RECORDING], default_policy=DialogPolicy.NEVER_ANSWERED
+ )
+ results = env.service.ensure_all([_SR, _AX], feature="computer_use")
+ assert [r.granted for r in results] == [True, False]
+ env.flush()
+ [event] = env.bus.needed()
+ assert event.permissions == ("accessibility",)
+
+
+def test_event_posting_is_folded_into_accessibility(make_env: Callable[..., Env]) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ results = env.service.ensure_all([_AX, PermissionId.EVENT_POSTING], feature="computer_use")
+ assert _requests(env.tcc, "accessibility") == 1 # one request, one episode
+ assert [r.permission for r in results] == [_AX, PermissionId.EVENT_POSTING]
+ assert results[1].agent_detail.startswith("[permission_needed:accessibility] ")
+ env.flush()
+ [event] = env.bus.needed()
+ assert event.permissions == ("accessibility",)
+
+
+def test_the_episode_is_resolved_when_the_user_grants_and_the_watcher_pass_runs(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_AX, feature="computer_use")
+ env.tcc.grant("accessibility") # the user flips the switch in System Settings
+ env.settle()
+ [resolved] = env.bus.resolved()
+ assert resolved.granted and resolved.feature == "computer_use"
+ assert resolved.permissions == ("accessibility",)
+ assert env.service.outstanding() == []
+
+
+def test_a_granted_ensure_resolves_the_open_episode_of_another_feature(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_AX, feature="computer_use")
+ env.tcc.grant("accessibility")
+ env.clock.advance(1.5)
+ assert env.service.ensure(_AX, feature="window_control").granted
+ env.flush()
+ assert [r.feature for r in env.bus.resolved()] == ["computer_use"]
+
+
+def test_an_episode_nobody_touches_ends_without_a_grant(make_env: Callable[..., Env]) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_AX, feature="computer_use")
+ env.clock.advance(601)
+ env.service.refresh_episodes()
+ env.flush()
+ [resolved] = env.bus.resolved()
+ assert resolved.granted is False
+ assert env.service.outstanding() == []
+
+
+def test_a_denied_dialog_publishes_blocked_after_the_os_dialog_phase(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_MIC, feature="dictation")
+ env.tcc.answer("microphone", DialogPolicy.DENY)
+ env.settle()
+ assert [(e.phase, e.reason) for e in env.bus.needed()] == [
+ ("os_dialog", "not_determined"),
+ ("blocked", "denied"),
+ ]
+ assert env.service.outstanding()[0].reason == "denied"
+
+
+def test_outstanding_describes_the_open_episode(make_env: Callable[..., Env]) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_MIC, feature="voice", trace_id="6f1d3c0a-1f6e-4b0e-9d5a-0e1f3a4b5c6d")
+ [episode] = env.service.outstanding()
+ assert episode.feature == "voice" and episode.trace_id.startswith("6f1d3c0a")
+ assert episode.as_dict()["permissions"] == ["microphone"]
+ assert episode.detail and episode.opened_at_ns > 0
+
+
+def test_the_unknown_feature_is_tolerated_and_the_unknown_permission_is_a_value_error(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env()
+ assert env.service.ensure(_MIC, feature="not_a_feature").granted
+ with pytest.raises(ValueError):
+ env.service.ensure("camera", feature="voice")
+
+
+# ----------------------------------------------------------------------
+# EnsureResult
+# ----------------------------------------------------------------------
+
+
[email protected]("outcome", list(PermissionOutcome))
+def test_ensure_result_granted_is_true_only_for_granted_and_not_required(
+ outcome: PermissionOutcome,
+) -> None:
+ result = EnsureResult(
+ permission=_MIC,
+ outcome=outcome,
+ state=PermissionState.GRANTED,
+ asked=False,
+ outside_installed_app=False,
+ agent_detail="",
+ user_detail="",
+ )
+ assert result.granted is (
+ outcome in (PermissionOutcome.GRANTED, PermissionOutcome.NOT_REQUIRED)
+ )
+
+
+def test_every_outcome_the_service_produces_has_the_right_details(
+ make_env: Callable[..., Env],
+) -> None:
+ produced: dict[PermissionOutcome, EnsureResult] = {}
+
+ env = make_env()
+ env.tcc.grant("microphone")
+ produced[PermissionOutcome.GRANTED] = env.service.ensure(_MIC, feature="voice")
+
+ env = make_env(installed_players=[])
+ produced[PermissionOutcome.NOT_REQUIRED] = env.service.ensure(
+ _AUTOMATION, feature="audio_ducking", target=_MUSIC
+ )
+
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ produced[PermissionOutcome.PENDING] = env.service.ensure(_MIC, feature="voice")
+
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_AX, feature="computer_use")
+ env.clock.advance(20)
+ produced[PermissionOutcome.NEEDS_SETTINGS] = env.service.ensure(_AX, feature="computer_use")
+
+ env = make_env()
+ env.tcc.deny("microphone")
+ produced[PermissionOutcome.DENIED] = env.service.ensure(_MIC, feature="voice")
+
+ env = make_env()
+ env.tcc.restrict("microphone")
+ produced[PermissionOutcome.UNAVAILABLE] = env.service.ensure(_MIC, feature="voice")
+
+ assert set(produced) == set(PermissionOutcome)
+ for outcome, result in produced.items():
+ assert result.outcome is outcome
+ assert result.granted is (
+ outcome in (PermissionOutcome.GRANTED, PermissionOutcome.NOT_REQUIRED)
+ )
+ if result.granted:
+ assert result.agent_detail == "" and result.user_detail == ""
+ else:
+ tag = f"[permission_needed:{result.permission.value}] "
+ assert result.agent_detail.startswith(tag)
+ assert result.user_detail and result.user_detail.endswith(".")
+
+
[email protected]("permission", [p for p in PermissionId])
[email protected]("reason", PERMISSION_NEEDED_REASONS)
[email protected]("asking", [False, True])
+def test_the_sentences_are_fixed_english_templates(
+ permission: PermissionId, reason: str, asking: bool
+) -> None:
+ user = user_detail_for(permission, reason, asking=asking)
+ agent = agent_detail_for(permission, reason, asking=asking)
+ assert user.endswith(".") and user[0].isalpha()
+ assert "Traceback" not in user and "Exception" not in user and "/Users" not in user
+ family = "accessibility" if permission is PermissionId.EVENT_POSTING else permission.value
+ assert agent.startswith(f"[permission_needed:{family}] ")
+ # P9: prohibitive, never an invitation to click or retry.
+ assert "must not try to answer, click or dismiss any macOS system dialog" in agent
+ assert "must not retry" in agent
+
+
+def test_the_automation_sentence_names_the_player_from_the_fixed_table() -> None:
+ text = user_detail_for(_AUTOMATION, "denied", target=_MUSIC)
+ assert "Automation access for Music" in text
+ assert {name for name, _ in AUTOMATION_TARGETS} >= {"Music", "Spotify"}
+
+
+# ----------------------------------------------------------------------
+# Never raises
+# ----------------------------------------------------------------------
+
+_LEAK = "boom /Users/someone/Library/secret-window-title"
+
+
+class ExplodingPort:
+ """A port whose every native call raises with text the user must never see."""
+
+ platform = "darwin"
+ outside_installed_app = False
+
+ def __init__(self, *, state: PermissionState | None = None, usage_raises: bool = False):
+ self._state = state
+ self._usage_raises = usage_raises
+ self.request_calls = 0
+
+ def state(self, permission: Any, **_kwargs: Any) -> PermissionState:
+ if self._state is not None:
+ return self._state
+ raise RuntimeError(_LEAK)
+
+ def usage_string_present(self, permission: Any) -> bool:
+ if self._usage_raises:
+ raise RuntimeError(_LEAK)
+ return True
+
+ def request_native(self, permission: Any, **_kwargs: Any) -> str:
+ self.request_calls += 1
+ raise RuntimeError(_LEAK)
+
+ def open_settings(self, permission: Any) -> Any:
+ raise RuntimeError(_LEAK)
+
+
+def bare_service() -> Iterator[PermissionService]:
+ service = PermissionService(watch_interval_s=_NEVER)
+ yield service
+ service._shutdown()
+
+
+def _assert_clean(result: EnsureResult) -> None:
+ assert result.outcome is PermissionOutcome.UNAVAILABLE and not result.granted
+ for text in (result.user_detail, result.agent_detail):
+ assert "boom" not in text and "/Users" not in text and "secret" not in text
+
+
+def test_ensure_never_raises_when_the_state_read_raises(
+ monkeypatch: pytest.MonkeyPatch, bare_service: PermissionService
+) -> None:
+ monkeypatch.setattr(
+ service_module._permissions_module, "get_system_permission_port", ExplodingPort
+ )
+ _assert_clean(bare_service.ensure(_MIC, feature="voice"))
+ assert bare_service.check(_MIC) is PermissionState.UNAVAILABLE
+ assert bare_service.open_settings(_MIC) is False
+ _assert_clean(asyncio.run(bare_service.ensure_async(_MIC, feature="voice")))
+ [only] = bare_service.ensure_all([_MIC, _AX], feature="voice")[:1]
+ _assert_clean(only)
+
+
+def test_ensure_never_raises_when_the_native_request_raises(
+ monkeypatch: pytest.MonkeyPatch, bare_service: PermissionService
+) -> None:
+ port = ExplodingPort(state=PermissionState.NOT_DETERMINED)
+ monkeypatch.setattr(
+ service_module._permissions_module, "get_system_permission_port", lambda: port
+ )
+ result = bare_service.ensure(_MIC, feature="voice")
+ _assert_clean(result)
+ assert result.asked and port.request_calls == 1
+ # The failure is remembered for the episode: no hammering on every retry.
+ again = bare_service.ensure(_MIC, feature="voice")
+ assert not again.asked and port.request_calls == 1
+
+
+def test_a_failing_usage_string_check_fails_closed(
+ monkeypatch: pytest.MonkeyPatch, bare_service: PermissionService
+) -> None:
+ port = ExplodingPort(state=PermissionState.NOT_DETERMINED, usage_raises=True)
+ monkeypatch.setattr(
+ service_module._permissions_module, "get_system_permission_port", lambda: port
+ )
+ _assert_clean(bare_service.ensure(_MIC, feature="voice"))
+ assert port.request_calls == 0
+
+
+def test_a_broken_bus_never_breaks_a_check(
+ make_env: Callable[..., Env], loop_thread: LoopThread
+) -> None:
+ class ExplodingBus:
+ def publish(self, event: Event) -> Any:
+ raise RuntimeError(_LEAK)
+
+ env = make_env(attach=False, default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.attach_bus(ExplodingBus(), loop_thread.loop)
+ result = env.service.ensure(_MIC, feature="voice")
+ assert result.outcome is PermissionOutcome.PENDING
+
+
+def test_without_a_bus_the_episode_is_kept_and_a_debug_line_is_written(
+ make_env: Callable[..., Env], caplog: pytest.LogCaptureFixture
+) -> None:
+ env = make_env(attach=False, default_policy=DialogPolicy.NEVER_ANSWERED)
+ with caplog.at_level(logging.DEBUG, logger=service_module.log.name):
+ result = env.service.ensure(_MIC, feature="voice")
+ assert result.outcome is PermissionOutcome.PENDING
+ assert len(env.service.outstanding()) == 1
+ assert any("No bus attached" in record.getMessage() for record in caplog.records)
+
+
+def test_a_closed_loop_drops_the_event_without_raising(make_env: Callable[..., Env]) -> None:
+ env = make_env(attach=False, default_policy=DialogPolicy.NEVER_ANSWERED)
+ dead = asyncio.new_event_loop()
+ dead.close()
+ env.service.attach_bus(RecordingBus(), dead)
+ assert env.service.ensure(_MIC, feature="voice").outcome is PermissionOutcome.PENDING
+
+
+# ----------------------------------------------------------------------
+# Automation
+# ----------------------------------------------------------------------
+
+
+def test_automation_is_asked_only_for_a_scriptable_player(make_env: Callable[..., Env]) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC])
+ bad = env.service.ensure(_AUTOMATION, feature="audio_ducking", target="com.evil.app")
+ assert bad.outcome is PermissionOutcome.UNAVAILABLE and not bad.granted
+ missing = env.service.ensure(_AUTOMATION, feature="audio_ducking")
+ assert missing.outcome is PermissionOutcome.UNAVAILABLE
+ assert env.tcc.calls == () # nothing was probed or asked for a target outside the table
+
+
+def test_automation_asks_through_the_consent_runner_for_a_running_player(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC])
+ result = env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC)
+ assert result.outcome is PermissionOutcome.GRANTED and result.asked
+ assert [call.target for call in env.tcc.requests("automation")] == [_MUSIC]
+
+
+def test_automation_for_a_player_that_is_not_running_asks_nothing_and_can_retry(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(installed_players=[_SPOTIFY])
+ first = env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_SPOTIFY)
+ assert first.outcome is PermissionOutcome.UNAVAILABLE
+ assert env.tcc.requests("automation") == [] # the guarded script never launches the player
+ env.tcc.launch_player(_SPOTIFY)
+ second = env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_SPOTIFY)
+ assert second.asked and second.outcome is PermissionOutcome.GRANTED
+
+
+def test_automation_for_a_player_that_is_not_installed_is_not_required(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env()
+ result = env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC)
+ assert result.outcome is PermissionOutcome.NOT_REQUIRED and result.granted
+
+
+def test_the_credential_store_is_never_requested(make_env: Callable[..., Env]) -> None:
+ env = make_env(credential_backend="file")
+ result = env.service.ensure(PermissionId.CREDENTIAL_STORE, feature="voice")
+ assert result.outcome is PermissionOutcome.DENIED and not result.asked
+ assert env.tcc.requests() == [] and env.tcc.keychain_recover_calls == 0
+
+
+# ----------------------------------------------------------------------
+# check()
+# ----------------------------------------------------------------------
+
+
+def test_check_never_prompts_never_publishes_and_caches_a_grant_briefly(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(granted=[TccService.MICROPHONE])
+ assert env.service.check(_MIC) is PermissionState.GRANTED
+ probes = len(env.tcc.probes("microphone"))
+ for _ in range(5):
+ assert env.service.check(_MIC) is PermissionState.GRANTED
+ assert len(env.tcc.probes("microphone")) == probes # served from the cache
+ env.tcc.deny("microphone")
+ assert env.service.check(_MIC) is PermissionState.GRANTED # still inside the ~1 s window
+ env.clock.advance(1.1)
+ assert env.service.check(_MIC) is PermissionState.DENIED
+ env.tcc.assert_no_prompts()
+ env.flush()
+ assert env.bus.events == []
+
+
+def test_invalidate_bypasses_the_cache_after_a_capture_error(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(granted=[TccService.MICROPHONE])
+ assert env.service.check(_MIC) is PermissionState.GRANTED
+ env.tcc.deny("microphone")
+ env.service.invalidate(_MIC)
+ assert env.service.check(_MIC) is PermissionState.DENIED
+ env.service.invalidate()
+ assert env.service.check(_MIC) is PermissionState.DENIED
+
+
+def test_a_negative_is_cached_for_a_quarter_of_a_second_only(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env()
+ assert env.service.check(_MIC) is PermissionState.NOT_DETERMINED
+ env.tcc.grant("microphone")
+ env.clock.advance(0.1)
+ assert env.service.check(_MIC) is PermissionState.NOT_DETERMINED # cached
+ env.clock.advance(0.2)
+ assert env.service.check(_MIC) is PermissionState.GRANTED
+
+
+def test_check_takes_no_lock(make_env: Callable[..., Env]) -> None:
+ env = make_env(granted=[TccService.MICROPHONE])
+ answers: list[PermissionState] = []
+ with env.service._lock: # a writer holds the service lock
+ worker = threading.Thread(target=lambda: answers.append(env.service.check(_MIC)))
+ worker.start()
+ worker.join(timeout=5)
+ assert not worker.is_alive()
+ assert answers == [PermissionState.GRANTED]
+
+
+def test_a_screen_recording_grant_the_frozen_preflight_hides_is_seen_by_ensure(
+ make_env: Callable[..., Env],
+) -> None:
+ # BUG-161: the preflight is frozen per process, so only the window-title oracle
+ # sees a grant given while the app runs. ensure() and the watcher use it.
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ assert env.service.ensure(_SR, feature="computer_use").outcome is PermissionOutcome.PENDING
+ env.tcc.grant("screen_recording")
+ env.clock.advance(1.5)
+ assert env.service.check(_SR) is PermissionState.NOT_GRANTED # hot path: preflight only
+ assert env.service.ensure(_SR, feature="computer_use").granted
+ env.flush()
+ assert [r.granted for r in env.bus.resolved()] == [True]
+
+
+def test_in_the_world_where_a_screen_grant_needs_a_relaunch_the_user_is_told_to_wait(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED, screen_grant_needs_relaunch=True)
+ env.service.ensure(_SR, feature="computer_use")
+ env.tcc.grant("screen_recording")
+ env.clock.advance(20)
+ result = env.service.ensure(_SR, feature="computer_use")
+ assert not result.granted and result.outcome is PermissionOutcome.NEEDS_SETTINGS
+
+
+def test_check_reads_screen_recording_without_the_window_oracle(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env()
+ env.service.check(_SR)
+ apis = {call.api for call in env.tcc.calls}
+ assert "window title oracle" not in apis # deep=False: a hot path never enumerates windows
+
+
+# ----------------------------------------------------------------------
+# Threads, the bus and the loop
+# ----------------------------------------------------------------------
+
+
[email protected]("policy", [DialogPolicy.NEVER_ANSWERED, DialogPolicy.ALLOW])
+def test_many_threads_produce_one_native_request(
+ make_env: Callable[..., Env], policy: DialogPolicy
+) -> None:
+ env = make_env(default_policy=policy)
+ count = 24
+ barrier = threading.Barrier(count)
+ results: list[EnsureResult] = []
+ guard = threading.Lock()
+
+ def worker(index: int) -> None:
+ barrier.wait(timeout=5)
+ # Half the threads share one feature, half use another: the cooldown covers both.
+ feature = "voice" if index % 2 else "dictation"
+ result = env.service.ensure(_MIC, feature=feature, wait_s=0)
+ with guard:
+ results.append(result)
+
+ threads = [threading.Thread(target=worker, args=(i,)) for i in range(count)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(timeout=10)
+ assert len(results) == count
+ assert _requests(env.tcc, "microphone") == 1
+ assert sum(1 for r in results if r.asked) == 1
+ allowed = {PermissionOutcome.PENDING, PermissionOutcome.GRANTED}
+ assert {r.outcome for r in results} <= allowed
+
+
+def test_a_publish_from_a_worker_thread_reaches_the_loop(
+ monkeypatch: pytest.MonkeyPatch, loop_thread: LoopThread
+) -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ bus = EventBus()
+ delivered: list[tuple[PermissionNeeded, str]] = []
+ arrived = threading.Event()
+
+ async def handler(event: PermissionNeeded) -> None:
+ delivered.append((event, threading.current_thread().name))
+ arrived.set()
+
+ bus.subscribe(PermissionNeeded, handler)
+ service = PermissionService(watch_interval_s=_NEVER)
+ try:
+ service.attach_bus(bus, loop_thread.loop)
+ worker = threading.Thread(
+ target=lambda: service.ensure(_MIC, feature="voice"), name="tool-worker"
+ )
+ worker.start()
+ worker.join(timeout=5)
+ assert arrived.wait(timeout=5)
+ finally:
+ service._shutdown()
+ [(event, thread_name)] = delivered
+ assert thread_name == "test-loop" # the handler ran ON the loop, not on the worker
+ assert event.feature == "voice" and event.permissions == ("microphone",)
+
+
+async def test_ensure_on_the_loop_thread_never_blocks_on_its_own_publish(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A publish that waited for its own result on the thread that runs the loop would deadlock.
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ bus = EventBus()
+ seen: list[PermissionNeeded] = []
+
+ async def handler(event: PermissionNeeded) -> None:
+ seen.append(event)
+
+ bus.subscribe(PermissionNeeded, handler)
+ service = PermissionService(watch_interval_s=_NEVER)
+ try:
+ service.attach_bus(bus, asyncio.get_running_loop())
+ result = service.ensure(_MIC, feature="voice", wait_s=0) # a synchronous call on the loop
+ assert result.outcome is PermissionOutcome.PENDING
+ for _ in range(3):
+ await asyncio.sleep(0)
+ assert [e.feature for e in seen] == ["voice"]
+ finally:
+ service._shutdown()
+
+
+def test_a_listener_that_raises_does_not_stop_the_others(
+ make_env: Callable[..., Env], caplog: pytest.LogCaptureFixture
+) -> None:
+ env = make_env(attach=False, default_policy=DialogPolicy.NEVER_ANSWERED)
+ called: list[str] = []
+
+ def first() -> None:
+ called.append("first")
+
+ def broken() -> None:
+ called.append("broken")
+ raise RuntimeError("listener bug")
+
+ def last() -> None:
+ called.append("last")
+
+ for callback in (first, broken, last):
+ env.service.add_listener(_AX, callback)
+ env.service.ensure(_AX, feature="computer_use")
+ env.tcc.grant("accessibility")
+ with caplog.at_level(logging.WARNING, logger=service_module.log.name):
+ env.settle()
+ assert called == ["first", "broken", "last"]
+ assert any("A permission listener raised" in r.getMessage() for r in caplog.records)
+ # The edge fires once: another pass does not call anybody again.
+ env.settle()
+ assert called == ["first", "broken", "last"]
+
+
+def test_listeners_run_on_the_loop_thread_when_a_loop_is_attached(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ threads: list[str] = []
+ env.service.add_listener(_MIC, lambda: threads.append(threading.current_thread().name))
+ env.service.ensure(_MIC, feature="wake_word", interactive=False)
+ env.tcc.grant("microphone")
+ env.settle()
+ assert threads == ["test-loop"]
+
+
+def test_an_unsubscribed_listener_is_not_called(make_env: Callable[..., Env]) -> None:
+ env = make_env(attach=False, default_policy=DialogPolicy.NEVER_ANSWERED)
+ called: list[int] = []
+ unsubscribe = env.service.add_listener(PermissionId.EVENT_POSTING, lambda: called.append(1))
+ unsubscribe()
+ unsubscribe() # idempotent
+ env.service.ensure(_AX, feature="computer_use")
+ env.tcc.grant("accessibility")
+ env.settle()
+ assert called == []
+
+
+def test_a_listener_fires_per_permission_even_before_the_whole_episode_is_done(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(attach=False, default_policy=DialogPolicy.NEVER_ANSWERED)
+ fired: list[str] = []
+ env.service.add_listener(_SR, lambda: fired.append("sr"))
+ env.service.add_listener(_AX, lambda: fired.append("ax"))
+ env.service.ensure_all([_SR, _AX], feature="computer_use")
+ env.tcc.grant("accessibility")
+ env.settle()
+ assert fired == ["ax"] and len(env.service.outstanding()) == 1
+ env.tcc.grant("screen_recording")
+ env.clock.advance(10) # the frozen preflight needs the oracle, which is rate limited
+ env.settle()
+ assert fired == ["ax", "sr"] and env.service.outstanding() == []
+
+
+def test_the_thread_watcher_resolves_an_episode_without_a_loop(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ service = PermissionService(watch_interval_s=0.02, negative_ttl_s=0.0)
+ granted = threading.Event()
+ try:
+ service.add_listener(_AX, granted.set)
+ service.ensure(_AX, feature="computer_use")
+ assert service._watch_thread is not None and service._watch_thread.daemon
+ tcc.grant("accessibility")
+ assert granted.wait(timeout=5)
+ deadline = threading.Event()
+ for _ in range(100):
+ if not service._watch_running:
+ break
+ deadline.wait(0.02)
+ assert service.outstanding() == []
+ assert service._watch_running is False # it stops when nothing is open
+ finally:
+ service._shutdown()
+
+
+def test_the_task_watcher_publishes_resolved_through_the_bus(
+ monkeypatch: pytest.MonkeyPatch, loop_thread: LoopThread
+) -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ bus = RecordingBus()
+ service = PermissionService(watch_interval_s=0.02, negative_ttl_s=0.0)
+ try:
+ service.attach_bus(bus, loop_thread.loop)
+ service.ensure(_MIC, feature="wake_word", interactive=False)
+ assert service._watch_kind == "task"
+ tcc.grant("microphone")
+ for _ in range(250):
+ if bus.resolved():
+ break
+ threading.Event().wait(0.02)
+ [resolved] = bus.resolved()
+ assert resolved.granted and resolved.feature == "wake_word"
+ finally:
+ service._shutdown()
+
+
+async def test_ensure_async_polls_without_pinning_an_executor_worker(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ loop = asyncio.get_running_loop()
+ executor = ThreadPoolExecutor(max_workers=1) # one worker: a pinned worker would starve it
+ loop.set_default_executor(executor)
+ service = PermissionService(poll_s=0.01, watch_interval_s=_NEVER, negative_ttl_s=0.0)
+ try:
+ waiting = asyncio.create_task(service.ensure_async(_MIC, feature="voice", wait_s=5))
+ await asyncio.sleep(0.2) # the request is made and the polling loop is running
+ assert not waiting.done()
+ free = await asyncio.wait_for(loop.run_in_executor(None, lambda: "free"), timeout=2)
+ assert free == "free"
+ tcc.answer("microphone", DialogPolicy.ALLOW)
+ result = await asyncio.wait_for(waiting, timeout=5)
+ assert result.outcome is PermissionOutcome.GRANTED and result.asked
+ # Only the first read-and-request ran on a worker; every poll after that ran
+ # on the loop thread, so the single worker was never held while waiting.
+ loop_name = threading.current_thread().name
+ threads = [c.thread for c in tcc.calls if c.kind is CallKind.PROBE]
+ last_worker = max(i for i, name in enumerate(threads) if name != loop_name)
+ assert set(threads[last_worker + 1 :]) == {loop_name}
+ assert len(threads[last_worker + 1 :]) > 3
+ finally:
+ service._shutdown()
+ executor.shutdown(wait=False)
+
+
+async def test_ensure_async_wait_zero_returns_pending_at_once(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ service = PermissionService(watch_interval_s=_NEVER)
+ try:
+ result = await service.ensure_async(_MIC, feature="wake_word", wait_s=0)
+ assert result.outcome is PermissionOutcome.PENDING and result.asked
+ granted = await service.ensure_async(_AX, feature="computer_use", interactive=False)
+ assert not granted.granted and not granted.asked
+ finally:
+ service._shutdown()
+
+
+# ----------------------------------------------------------------------
+# Singleton, imports, reset
+# ----------------------------------------------------------------------
+
+
+def test_the_singleton_is_lazy_and_reset_drops_it(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(service_module, "_SERVICE", None)
+ first = get_permission_service()
+ assert get_permission_service() is first
+ service_module._reset_for_tests()
+ assert get_permission_service() is not first
+
+
+def test_importing_the_service_loads_no_native_framework() -> None:
+ code = (
+ "import sys\n"
+ "import jarvis.platform.permission_service as service\n"
+ "service.PermissionService()\n"
+ "loaded = [m for m in sys.modules if m.split('.')[0] in "
+ "('objc', 'Quartz', 'AppKit', 'Foundation', 'AVFoundation', 'ApplicationServices')]\n"
+ "assert not loaded, loaded\n"
+ )
+ done = subprocess.run( # noqa: S603 - fixed argv, no shell
+ [sys.executable, "-c", code],
+ capture_output=True,
+ encoding="utf-8",
+ timeout=60,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ assert done.returncode == 0, done.stderr
+
+
+def test_constructing_the_service_calls_no_framework(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc = FakeTCC()
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ service = PermissionService()
+ assert tcc.calls == () and tcc.loaded_modules == []
+ service._shutdown()
+
+
+def test_both_implementations_satisfy_the_gate_protocol() -> None:
+ assert isinstance(PermissionService(), PermissionGate)
+ assert isinstance(FakePermissionService(), PermissionGate)
+ assert "voice" in PERMISSION_FEATURES
+
+
+# ----------------------------------------------------------------------
+# The consumer-side fake
+# ----------------------------------------------------------------------
+
+
+def test_the_fake_service_serves_scripted_outcomes_and_logs_every_call() -> None:
+ gate = FakePermissionService()
+ gate.script(_AX, PermissionOutcome.DENIED, PermissionOutcome.GRANTED)
+ gate.script(_MIC, "pending")
+ denied = gate.ensure(_AX, feature="computer_use")
+ granted = gate.ensure(_AX, feature="computer_use")
+ pending = gate.ensure(_MIC, feature="voice", interactive=False)
+ assert (denied.outcome, granted.outcome) == (
+ PermissionOutcome.DENIED,
+ PermissionOutcome.GRANTED,
+ )
+ assert not denied.granted and granted.granted
+ assert denied.agent_detail.startswith("[permission_needed:accessibility] ")
+ assert pending.outcome is PermissionOutcome.PENDING and not pending.asked
+ assert gate.check(_MIC) is PermissionState.NOT_DETERMINED
+ assert [c.feature for c in gate.ensure_calls(_AX)] == ["computer_use", "computer_use"]
+ assert len(gate.check_calls(_MIC)) == 1
+ assert not gate.native_free() # the interactive AX ensure could have asked
+ assert gate.open_settings(_MIC) is True
+ assert FakePermissionService(settings_opens=False).open_settings(_MIC) is False
+
+
+def test_the_fake_service_can_prove_that_a_consumer_never_asked() -> None:
+ gate = FakePermissionService(default=PermissionOutcome.PENDING)
+ gate.ensure(_MIC, feature="wake_word", interactive=False)
+ gate.check(_MIC)
+ assert gate.native_free()
+ gate.ensure(_MIC, feature="voice")
+ assert not gate.native_free()
+
+
+def test_the_fake_service_returns_a_ready_made_result_as_it_is() -> None:
+ ready = make_result(_SR, PermissionOutcome.NEEDS_SETTINGS, asked=True)
+ gate = FakePermissionService({_SR: ready})
+ assert gate.ensure(_SR, feature="computer_use") is ready
+ assert asyncio.run(gate.ensure_async(_SR, feature="computer_use")) is ready
+ with pytest.raises(ValueError):
+ gate.script(_SR)
diff --git a/tests/unit/platform/test_permission_service_hardening.py b/tests/unit/platform/test_permission_service_hardening.py
new file mode 100644
index 0000000000..ed30bf6b19
--- /dev/null
+++ b/tests/unit/platform/test_permission_service_hardening.py
@@ -0,0 +1,1018 @@
+"""Regression tests for the three-lens review of the permission service.
+
+Every test pins one defect the review reproduced: a hung Automation probe wedging
+the watcher, the Automation request blocking ``ensure``, a Screen Recording grant
+that flapped back to "not granted", the window-title oracle running far too often,
+an explicit click held back by the re-ask cooldown, a ``restart_hint`` nobody could
+produce, duplicate episodes, a dead feature in a session without a desktop and a
+few smaller lifecycle gaps. The REAL service runs on a REAL ``SystemPermissionPort``
+that sits on ``FakeTCC``; nothing here ran on a real Mac, every macOS behaviour is a
+MODEL (see ``tests/fakes/fake_tcc.py``). Where a test needs a probe or a consent
+runner that blocks, it replaces that one seam of the port with a hand-written stub.
+"""
+
+# ruff: noqa: F811 - the harness fixtures (``make_env``, ``loop_thread``) are imported by name
+
+from __future__ import annotations
+
+import asyncio
+import subprocess
+import threading
+import time
+from collections.abc import Callable
+from typing import Any
+
+import pytest
+
+from jarvis.core.events import PERMISSION_NEEDED_REASONS
+from jarvis.platform import permission_service as service_module
+from jarvis.platform.permission_service import (
+ PermissionOutcome,
+ PermissionService,
+ user_detail_for,
+)
+from jarvis.platform.permissions import AUTOMATION_TARGETS, PermissionId, PermissionState
+from tests.fakes.fake_tcc import CallKind, DialogPolicy, FakeTCC, TccService, install_port
+from tests.unit.platform.test_permission_service import ( # noqa: F401 - fixtures
+ Env,
+ LoopThread,
+ RecordingBus,
+ loop_thread,
+ make_env,
+)
+
+_MUSIC = "com.apple.Music"
+_MIC = PermissionId.MICROPHONE
+_AX = PermissionId.ACCESSIBILITY
+_SR = PermissionId.SCREEN_RECORDING
+_IM = PermissionId.INPUT_MONITORING
+_AUTOMATION = PermissionId.AUTOMATION
+_NEVER = 3600.0
+_SETTINGS_BUNDLE_ID = "com.apple.systempreferences"
+
+
+def _wait_for(condition: Callable[[], bool], *, seconds: float = 5.0) -> bool:
+ deadline = time.monotonic() + seconds
+ while time.monotonic() < deadline:
+ if condition():
+ return True
+ time.sleep(0.01)
+ return condition()
+
+
+class BlockedConsentRunner:
+ """The ``osascript`` consent child, blocked on an open dialog until released."""
+
+ def __init__(self) -> None:
+ self.entered = threading.Event()
+ self.release = threading.Event()
+ self.scripts: list[str] = []
+
+ def __call__(self, script: str) -> Any:
+ self.scripts.append(script)
+ self.entered.set()
+ self.release.wait(10)
+ raise subprocess.TimeoutExpired(cmd="osascript", timeout=120.0)
+
+
+class HungProbe:
+ """A stand-in for ``AEDeterminePermissionToAutomateTarget`` that never returns."""
+
+ def __init__(self) -> None:
+ self.entered = threading.Event()
+ self.release = threading.Event()
+ self.calls = 0
+
+ def __call__(self, bundle_id: str, ask: bool) -> int | None:
+ self.calls += 1
+ self.entered.set()
+ self.release.wait(10)
+ return -1744 # "would require consent": what a hung call would say if it ever answered
+
+
+def _hang_automation_probe(service: PermissionService) -> HungProbe:
+ probe = HungProbe()
+ service._port()._automation_probe = probe
+ return probe
+
+
+def _oracle_calls(tcc: FakeTCC) -> int:
+ return len([c for c in tcc.probes("screen_recording") if "window title" in c.api])
+
+
+# ----------------------------------------------------------------------
+# A hung Automation probe never wedges anything else
+# ----------------------------------------------------------------------
+
+
+def test_a_hung_automation_probe_cannot_wedge_the_episode_watcher(
+ monkeypatch: pytest.MonkeyPatch, loop_thread: LoopThread
+) -> None:
+ tcc = FakeTCC(
+ default_policy=DialogPolicy.NEVER_ANSWERED,
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ )
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ bus = RecordingBus()
+ service = PermissionService(
+ watch_interval_s=0.05,
+ negative_ttl_s=0.0,
+ automation_timeout_s=5.0,
+ automation_refresh_wait_s=0.02,
+ ask_runner=lambda work: work(),
+ )
+ probe: HungProbe | None = None
+ try:
+ service.attach_bus(bus, loop_thread.loop)
+ service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC)
+ service.ensure(_MIC, feature="voice")
+ probe = _hang_automation_probe(service)
+ tcc.grant("microphone")
+
+ assert _wait_for(
+ lambda: any(r.permissions == ("microphone",) for r in bus.resolved()), seconds=3
+ ), "the microphone grant was never published: a stuck player starved the watcher"
+ assert probe.entered.wait(5) # the Apple Event probe really was hung meanwhile
+ assert [e.permissions for e in service.outstanding()] == [("automation",)]
+ finally:
+ if probe is not None:
+ probe.release.set()
+ service._shutdown()
+
+
+def test_a_hung_automation_read_times_out_and_the_player_is_quarantined(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ automation_timeout_s=0.2,
+ negative_ttl_s=0.0,
+ )
+ probe = _hang_automation_probe(env.service)
+ try:
+ started = time.monotonic()
+ assert env.service.check(_AUTOMATION, target=_MUSIC) is PermissionState.UNAVAILABLE
+ assert time.monotonic() - started < 3 # the hard timeout, not the hang
+
+ started = time.monotonic()
+ for _ in range(20): # quarantined: no thread, no waiting
+ assert env.service.check(_AUTOMATION, target=_MUSIC) is PermissionState.UNAVAILABLE
+ assert time.monotonic() - started < 0.5
+ assert probe.calls == 1 # one call in flight per target, never a pile of threads
+
+ env.clock.advance(601) # the quarantine is over, the old call is still hung
+ assert env.service.check(_AUTOMATION, target=_MUSIC) is PermissionState.UNAVAILABLE
+ assert probe.calls == 1
+ finally:
+ probe.release.set()
+
+
+def test_an_automation_read_without_a_player_asks_nobody(make_env: Callable[..., Env]) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC])
+
+ assert env.service.check(_AUTOMATION) is PermissionState.UNAVAILABLE
+ assert env.service.check(_AUTOMATION, target="com.evil.app") is PermissionState.UNAVAILABLE
+ # The aggregate would probe every running player and rewrite the consent record.
+ assert env.tcc.probes("automation") == []
+
+
+def test_an_automation_read_on_the_event_loop_never_waits_for_the_probe(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC], automation_timeout_s=5.0)
+ probe = _hang_automation_probe(env.service)
+
+ async def on_the_loop() -> tuple[PermissionState, float]:
+ started = time.monotonic()
+ return env.service.check(_AUTOMATION, target=_MUSIC), time.monotonic() - started
+
+ try:
+ state, elapsed = asyncio.run(on_the_loop())
+ assert state is PermissionState.NOT_DETERMINED # "unknown": the probe is still running
+ assert elapsed < 1.0
+ finally:
+ probe.release.set()
+
+
+async def test_ensure_async_never_probes_automation_on_the_loop_thread(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = FakeTCC(
+ default_policy=DialogPolicy.NEVER_ANSWERED,
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ )
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ service = PermissionService(poll_s=0.01, watch_interval_s=_NEVER, negative_ttl_s=0.0)
+ runner = BlockedConsentRunner()
+ service._port()._automation_consent_runner = runner # the dialog stays open
+ try:
+ result = await service.ensure_async(
+ _AUTOMATION, feature="audio_ducking", target=_MUSIC, wait_s=0.3
+ )
+ assert result.outcome is PermissionOutcome.PENDING and result.asked
+ loop_name = threading.current_thread().name
+ automation_calls = tcc.calls_of(service="automation")
+ assert automation_calls, "the test never reached the OS"
+ assert all(call.thread != loop_name for call in automation_calls), tcc.format_log()
+ finally:
+ runner.release.set()
+ service._shutdown()
+
+
+# ----------------------------------------------------------------------
+# The Automation request runs off the calling thread
+# ----------------------------------------------------------------------
+
+
+def test_the_automation_request_never_blocks_ensure_and_a_slow_user_is_not_a_missing_player(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC], inline_ask=False)
+ runner = BlockedConsentRunner()
+ env.service._port()._automation_consent_runner = runner
+ try:
+ started = time.monotonic()
+ result = env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC, wait_s=0)
+ assert time.monotonic() - started < 2.0 # the runner is blocked for up to 120 s
+ assert result.outcome is PermissionOutcome.PENDING and result.asked
+ assert runner.entered.wait(5)
+
+ # While the dialog is open the episode says so, with a full classification
+ # (never an episode with an empty reason and phase).
+ [episode] = env.service.outstanding()
+ assert (episode.reason, episode.phase) == ("not_determined", "os_dialog")
+ again = env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC)
+ assert again.outcome is PermissionOutcome.PENDING and not again.asked
+ assert len(runner.scripts) == 1
+
+ runner.release.set() # the runner is killed after its timeout, nobody answered
+ assert _wait_for(lambda: env.service.outstanding()[0].phase == "blocked")
+ [episode] = env.service.outstanding()
+ # Not "the player is not running": the user may ask again.
+ assert (episode.reason, episode.can_prompt) == ("not_determined", True)
+ env.clock.advance(1)
+ retry = env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC)
+ assert retry.asked and _wait_for(lambda: len(runner.scripts) == 2)
+ finally:
+ runner.release.set()
+
+
+def test_a_closed_player_is_unavailable_but_may_be_asked_again_once_it_runs(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(installed_players=[_MUSIC], inline_ask=False)
+
+ first = env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC, wait_s=2)
+
+ assert first.outcome is PermissionOutcome.UNAVAILABLE # the guarded script found no player
+ env.tcc.launch_player(_MUSIC)
+ env.clock.advance(1)
+ second = env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC, wait_s=2)
+ assert second.outcome is PermissionOutcome.GRANTED and second.asked # the fake user allows
+
+
+def test_an_episode_is_invisible_until_its_asks_are_finished(
+ make_env: Callable[..., Env],
+) -> None:
+ seen: dict[str, Any] = {}
+ runner = BlockedConsentRunner()
+
+ def observing_runner(work: Callable[[], None]) -> None:
+ # Runs inside ensure(), after the episode exists but before it is classified.
+ env.flush()
+ seen["outstanding"] = env.service.outstanding()
+ seen["events"] = env.bus.needed()
+ env.service.refresh_episodes()
+ env.flush()
+ seen["events_after_refresh"] = env.bus.needed()
+ threading.Thread(target=work, daemon=True).start()
+
+ env = make_env(
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ ask_runner=observing_runner,
+ inline_ask=False,
+ )
+ env.service._port()._automation_consent_runner = runner
+ try:
+ env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC)
+ env.flush()
+
+ assert seen["outstanding"] == [] and seen["events"] == []
+ assert seen["events_after_refresh"] == [] # no "blocked, can prompt" card mid-request
+ [event] = env.bus.needed()
+ assert (event.phase, event.reason) == ("os_dialog", "not_determined")
+ assert event.can_prompt is False and event.origin == "user"
+ finally:
+ runner.release.set()
+
+
+# ----------------------------------------------------------------------
+# Screen Recording: a proven grant stays proven, the oracle is rate limited
+# ----------------------------------------------------------------------
+
+
+def test_a_screen_recording_grant_proven_by_the_oracle_does_not_flap_back(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ assert env.service.ensure(_SR, feature="computer_use").outcome is PermissionOutcome.PENDING
+ env.tcc.grant("screen_recording") # the preflight stays frozen negative until a relaunch
+ env.clock.advance(0.5) # past the quarter second a negative answer is cached
+
+ assert env.service.ensure(_SR, feature="computer_use").granted # the oracle proved it
+ for seconds in (0.1, 1.5, 10, 60):
+ env.clock.advance(seconds)
+ assert env.service.check(_SR) is PermissionState.GRANTED, seconds
+
+ env.service.invalidate(_SR) # a capture error: the proof is dropped
+ assert env.service.check(_SR) is PermissionState.NOT_GRANTED
+ assert env.service.ensure(_SR, feature="computer_use").granted # and re-proven by a gesture
+
+
+def test_a_deep_read_after_a_revoke_is_not_papered_over_by_the_remembered_proof(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_SR, feature="computer_use")
+ env.tcc.grant("screen_recording") # the preflight stays frozen negative until a relaunch
+ env.clock.advance(0.5)
+ assert env.service.check_deep(_SR) is PermissionState.GRANTED # the oracle proves it
+ env.clock.advance(2)
+ assert env.service.check(_SR) is PermissionState.GRANTED # shallow reads keep the proof
+
+ env.tcc.deny("screen_recording") # revoked while Jarvis runs
+ env.clock.advance(2)
+
+ # The Computer-Use pre-dispatch gate reads deep to see exactly this.
+ assert env.service.check_deep(_SR) is not PermissionState.GRANTED
+ assert env.service.check(_SR) is not PermissionState.GRANTED # and the proof is gone
+
+
+def test_ensure_with_a_wait_on_the_event_loop_does_not_block_it(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ async def call() -> tuple[float, bool]:
+ started = time.monotonic()
+ result = env.service.ensure(_MIC, feature="voice", wait_s=30)
+ return time.monotonic() - started, result.granted
+
+ elapsed, granted = asyncio.run(call())
+
+ assert elapsed < 5 # the wait was refused, not served
+ assert not granted
+
+
+def test_a_reset_drops_the_screen_recording_proof(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_SR, feature="computer_use")
+ env.tcc.grant("screen_recording")
+ env.clock.advance(0.5)
+ assert env.service.ensure(_SR, feature="computer_use").granted
+
+ env.service.note_reset(_SR)
+
+ assert env.service.check(_SR) is PermissionState.NOT_GRANTED
+
+
+def test_the_oracle_runs_once_per_gesture_and_only_rarely_for_an_open_episode(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ env.service.ensure(_SR, feature="computer_use")
+ # One gesture: one look on entry, one right after the request it made.
+ assert _oracle_calls(env.tcc) == 2
+
+ for _ in range(4): # the watcher passes inside the cadence read the preflight only
+ env.clock.advance(2)
+ env.service.refresh_episodes()
+ assert _oracle_calls(env.tcc) == 2
+ env.clock.advance(10)
+ env.service.refresh_episodes()
+ assert _oracle_calls(env.tcc) == 3 # one every ten seconds at most
+ env.service.note_app_activated() # the user came back: look at once
+ env.clock.advance(0.5) # past the quarter second a negative answer is cached
+ env.service.refresh_episodes()
+ assert _oracle_calls(env.tcc) == 4
+
+
+def test_a_background_caller_never_runs_the_oracle(make_env: Callable[..., Env]) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ for _ in range(5):
+ env.clock.advance(20)
+ env.service.ensure(_SR, feature="computer_use", interactive=False)
+ env.service.refresh_episodes()
+
+ assert _oracle_calls(env.tcc) == 0
+ assert env.tcc.requests() == []
+
+
+async def test_ensure_on_the_event_loop_never_runs_the_oracle(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ service = PermissionService(watch_interval_s=_NEVER)
+ try:
+ result = service.ensure(_SR, feature="computer_use", wait_s=0) # a sync call on the loop
+ assert result.outcome is PermissionOutcome.PENDING
+ assert _oracle_calls(tcc) == 0
+ finally:
+ service._shutdown()
+
+
+# ----------------------------------------------------------------------
+# An explicit click is never held back by the re-ask cooldown
+# ----------------------------------------------------------------------
+
+
+def test_an_explicit_click_skips_the_cooldown_of_a_prompt_once_permission(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ assert env.service.ensure(_AX, feature="computer_use").asked
+ env.clock.advance(60)
+
+ automatic = env.service.ensure(_AX, feature="window_control")
+ click = env.service.ensure(_AX, feature="window_control", force_ask=True)
+
+ assert not automatic.asked # the cooldown still holds for automatic asks
+ assert click.asked
+ assert len(env.tcc.requests("accessibility")) == 2
+ # The same card clicked again inside its own episode is not a retry loop either.
+ env.clock.advance(6)
+ assert not env.service.ensure(_AX, feature="window_control").asked
+ assert env.service.ensure(_AX, feature="window_control", force_ask=True).asked
+ assert len(env.tcc.requests("accessibility")) == 3
+
+
+def test_an_explicit_click_asks_for_screen_recording_again_in_the_same_process(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ assert env.service.ensure(_SR, feature="computer_use").asked
+ env.clock.advance(60)
+
+ assert not env.service.ensure(_SR, feature="screen_context").asked
+ assert env.service.ensure(_SR, feature="screen_context", force_ask=True).asked
+
+
+def test_an_explicit_click_never_asks_about_a_denial_or_a_dialog_that_is_open(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env()
+ env.tcc.deny("microphone")
+ denied = env.service.ensure(_MIC, feature="voice", force_ask=True)
+ assert denied.outcome is PermissionOutcome.DENIED and not denied.asked
+ assert env.tcc.requests() == []
+
+ other = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ assert other.service.ensure(_MIC, feature="voice").asked
+ again = other.service.ensure(_MIC, feature="dictation", force_ask=True)
+ assert not again.asked # a dialog class request is still in flight
+
+
+# ----------------------------------------------------------------------
+# restart_hint has a producer now
+# ----------------------------------------------------------------------
+
+
+def test_a_real_failed_use_of_a_granted_screen_recording_raises_the_restart_hint(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_SR, feature="computer_use")
+ env.tcc.grant("screen_recording") # granted, but the capture still fails
+
+ result = env.service.report_failed_use(_SR, feature="computer_use")
+ env.flush()
+
+ assert result.reason == "restart_hint" and not result.granted
+ assert result.outcome is PermissionOutcome.NEEDS_SETTINGS
+ assert "quit and reopen" in result.user_detail
+ assert result.agent_detail.startswith("[permission_needed:screen_recording] ")
+ hint = [e for e in env.bus.needed() if e.reason == "restart_hint"]
+ assert [(e.phase, e.origin) for e in hint] == [("blocked", "user")]
+ [episode] = env.service.outstanding()
+ assert episode.reason == "restart_hint" and episode.permissions == ("screen_recording",)
+ # A hint is not a refusal: the state still reads granted and ensure still says so.
+ assert env.service.check(_SR) is PermissionState.GRANTED
+ assert env.service.ensure(_SR, feature="computer_use").granted
+
+
+def test_the_restart_hint_after_a_return_from_settings_in_the_frozen_preflight_world(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED, screen_grant_needs_relaunch=True)
+ env.service.ensure(_SR, feature="computer_use")
+ env.tcc.grant("screen_recording") # on in Settings, but the oracle cannot see it yet
+
+ assert env.service.report_failed_use(_SR, feature="computer_use").reason != "restart_hint"
+
+ env.service.note_app_activated() # the user came back from Settings
+ result = env.service.report_failed_use(_SR, feature="computer_use")
+
+ assert result.reason == "restart_hint"
+ assert env.service.check(_SR) is PermissionState.NOT_GRANTED # still frozen negative
+
+
+def test_the_restart_hint_is_only_for_screen_recording_and_input_monitoring(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(granted=[TccService.ACCESSIBILITY, TccService.INPUT_MONITORING])
+
+ ax = env.service.report_failed_use(_AX, feature="computer_use")
+ im = env.service.report_failed_use(_IM, feature="global_shortcuts")
+
+ assert ax.reason == "" and ax.granted # an ordinary ensure
+ assert im.reason == "restart_hint"
+ assert env.service.report_failed_use("event_posting", feature="computer_use").granted
+
+
+def test_report_failed_use_off_macos_is_not_required(make_env: Callable[..., Env]) -> None:
+ env = make_env(platform="linux")
+
+ assert env.service.report_failed_use(_SR, feature="computer_use").granted
+ env.tcc.assert_silent()
+
+
+# ----------------------------------------------------------------------
+# One record per feature and permission
+# ----------------------------------------------------------------------
+
+
+def test_granting_one_member_of_a_pair_never_opens_a_second_episode(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure_all([_SR, _AX], feature="computer_use")
+ env.tcc.grant("screen_recording")
+ env.clock.advance(10)
+
+ env.service.ensure_all([_SR, _AX], feature="computer_use")
+ env.flush()
+
+ [episode] = env.service.outstanding()
+ assert episode.permissions == ("accessibility",) # only what is still missing
+ assert env.bus.needed()[-1].permissions == ("accessibility",)
+ env.tcc.grant("accessibility")
+ env.settle()
+ assert [r.granted for r in env.bus.resolved()] == [True] # one resolve, not two
+ assert env.service.outstanding() == []
+
+
+def test_two_episodes_for_one_permission_call_the_listener_once_per_pass(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(attach=False, default_policy=DialogPolicy.NEVER_ANSWERED)
+ fired: list[int] = []
+ env.service.add_listener(_AX, lambda: fired.append(1))
+ env.service.ensure(_AX, feature="computer_use")
+ env.service.ensure(_AX, feature="window_control")
+ assert len(env.service.outstanding()) == 2
+ env.tcc.grant("accessibility")
+
+ env.settle()
+
+ assert fired == [1]
+
+
+# ----------------------------------------------------------------------
+# No desktop session, nothing to show
+# ----------------------------------------------------------------------
+
+
[email protected]("permission", [_MIC, _SR, _AX, _IM])
+def test_without_a_desktop_session_nothing_is_requested(
+ make_env: Callable[..., Env], permission: PermissionId
+) -> None:
+ env = make_env(headless=True)
+
+ result = env.service.ensure(permission, feature="voice", wait_s=0)
+
+ assert result.outcome is PermissionOutcome.UNAVAILABLE and not result.asked
+ assert env.tcc.requests() == [] and env.tcc.implicit_prompts() == []
+ [episode] = env.service.outstanding()
+ assert episode.reason == "unavailable" # a card with a reason, never a silent dead feature
+
+
+def test_a_dialog_nobody_answers_turns_blocked_instead_of_asking_forever(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_MIC, feature="wake_word")
+ [episode] = env.service.outstanding()
+ assert (episode.phase, episode.reason) == ("os_dialog", "not_determined")
+
+ env.clock.advance(131)
+ env.service.refresh_episodes()
+ env.flush()
+
+ [episode] = env.service.outstanding()
+ assert (episode.phase, episode.reason) == ("blocked", "needs_settings")
+
+
+# ----------------------------------------------------------------------
+# Opening a pane and resetting are light
+# ----------------------------------------------------------------------
+
+
+def test_opening_a_pane_probes_nothing_and_needs_no_installed_app(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(
+ bundle_id=None,
+ bundle_path=None,
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ )
+
+ assert env.service.open_settings(_AX) is True
+ assert env.service.open_settings(_AUTOMATION) is True
+
+ assert len(env.tcc.workspace_opened_urls) == 2
+ assert (
+ env.tcc.probes() == [] and env.tcc.requests() == []
+ ) # no snapshot, no oracle, no AE probe
+
+
+def test_opening_a_pane_without_a_desktop_session_fails_without_a_native_call(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(headless=True)
+
+ assert env.service.open_settings(_AX) is False
+ assert env.tcc.workspace_opened_urls == []
+
+
+def test_a_running_system_settings_is_closed_only_when_it_may_show_another_pane(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env()
+ env.tcc.launch_player(_SETTINGS_BUNDLE_ID)
+
+ assert env.service.open_settings(_AX) is True
+ assert not env.tcc.player_running(_SETTINGS_BUNDLE_ID) # unknown pane: closed first
+
+ env.tcc.launch_player(_SETTINGS_BUNDLE_ID) # opened on the Accessibility pane by us
+ assert env.service.open_settings(_AX) is True
+ assert env.tcc.player_running(_SETTINGS_BUNDLE_ID) # the right pane is already there
+
+ assert env.service.open_settings(_MIC) is True
+ assert not env.tcc.player_running(_SETTINGS_BUNDLE_ID) # another pane: closed first
+
+
+def test_going_to_settings_keeps_the_open_episode_alive(make_env: Callable[..., Env]) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED, episode_ttl_s=600.0)
+ env.service.ensure(_AX, feature="computer_use")
+ env.clock.advance(590)
+ assert env.service.open_settings(_AX) is True
+ env.clock.advance(590) # 20 minutes after the ask, 10 after the visit to Settings
+
+ env.service.refresh_episodes()
+ env.flush()
+
+ assert env.bus.resolved() == []
+ env.tcc.grant("accessibility")
+ env.settle()
+ assert [r.granted for r in env.bus.resolved()] == [True] # a late grant is still heard
+
+
+# ----------------------------------------------------------------------
+# The smaller lifecycle gaps
+# ----------------------------------------------------------------------
+
+
+def test_a_failed_native_request_is_retried_after_a_while_and_at_once_for_a_click(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class FailingPort:
+ platform = "darwin"
+ outside_installed_app = False
+
+ def __init__(self) -> None:
+ self.request_calls = 0
+
+ def state(self, permission: Any, **_kwargs: Any) -> PermissionState:
+ return PermissionState.NOT_GRANTED
+
+ def request_native(self, permission: Any, **_kwargs: Any) -> str:
+ self.request_calls += 1
+ return "unavailable"
+
+ port = FailingPort()
+ monkeypatch.setattr(
+ service_module._permissions_module, "get_system_permission_port", lambda: port
+ )
+ now = [1000.0]
+ service = PermissionService(clock=lambda: now[0], watch_interval_s=_NEVER)
+ try:
+ assert service.ensure(_AX, feature="computer_use").outcome is PermissionOutcome.UNAVAILABLE
+ assert not service.ensure(_AX, feature="computer_use").asked # no hammering
+ assert port.request_calls == 1
+ now[0] += 31
+ assert service.ensure(_AX, feature="computer_use").asked # the transient failure heals
+ assert port.request_calls == 2
+ assert service.ensure(_AX, feature="computer_use", force_ask=True).asked
+ assert port.request_calls == 3
+ finally:
+ service._shutdown()
+
+
+def test_resetting_automation_without_a_player_forgets_every_player(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC], inline_ask=False)
+ runner = BlockedConsentRunner()
+ env.service._port()._automation_consent_runner = runner
+ try:
+ assert env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC).asked
+ assert runner.entered.wait(5)
+ env.clock.advance(6)
+ assert not env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC).asked
+
+ env.service.note_reset(_AUTOMATION) # the route does not know the player
+
+ assert env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC).asked
+ assert _wait_for(lambda: len(runner.scripts) == 2)
+ finally:
+ runner.release.set()
+
+
[email protected]("decision", ["grant", "deny"])
+def test_a_decision_made_between_the_first_read_and_the_claim_is_never_asked_about(
+ make_env: Callable[..., Env], monkeypatch: pytest.MonkeyPatch, decision: str
+) -> None:
+ # Another thread's dialog was answered after this call read NOT_DETERMINED and before
+ # it claimed the request: asking again would make macOS re-prompt a decided permission.
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ original = env.service._claim
+
+ def claim_after_the_answer(*args: Any, **kwargs: Any) -> Any:
+ getattr(env.tcc, decision)("microphone") # the answer lands right here
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(env.service, "_claim", claim_after_the_answer)
+
+ result = env.service.ensure(_MIC, feature="voice")
+
+ assert env.tcc.requests("microphone") == [] # nothing was asked
+ assert result.asked is False
+ assert result.granted is (decision == "grant")
+
+
+def test_invalidate_never_raises_while_another_thread_fills_the_cache(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(granted=[TccService.MICROPHONE])
+ stop = threading.Event()
+
+ def filler() -> None:
+ index = 0
+ while not stop.is_set():
+ env.service._cache[(_MIC, str(index % 5000))] = (PermissionState.GRANTED, 0.0, False)
+ index += 1
+
+ thread = threading.Thread(target=filler, daemon=True)
+ thread.start()
+ try:
+ for _ in range(3000):
+ env.service.invalidate(_MIC)
+ finally:
+ stop.set()
+ thread.join(5)
+
+
+def test_a_read_that_started_before_an_invalidation_never_stores_its_answer(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ holder: dict[str, PermissionService] = {}
+
+ class RacingPort:
+ platform = "darwin"
+
+ def state(self, permission: Any, **_kwargs: Any) -> PermissionState:
+ holder["service"].invalidate(_MIC) # a capture error lands mid-read
+ return PermissionState.GRANTED
+
+ monkeypatch.setattr(
+ service_module._permissions_module, "get_system_permission_port", RacingPort
+ )
+ service = PermissionService(watch_interval_s=_NEVER)
+ holder["service"] = service
+ try:
+ assert service.check(_MIC) is PermissionState.GRANTED
+ assert service._cache == {} # the stale answer did not get a fresh one second
+ finally:
+ service._shutdown()
+
+
+def test_check_stays_lock_free_after_a_dialog_permission_was_decided(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.service.ensure(_MIC, feature="voice") # a request is "in flight"
+ env.tcc.answer("microphone", DialogPolicy.ALLOW)
+ env.clock.advance(1) # past the quarter second a negative answer is cached
+ answers: list[PermissionState] = []
+ with env.service._lock:
+ worker = threading.Thread(target=lambda: answers.append(env.service.check(_MIC)))
+ worker.start()
+ worker.join(timeout=5)
+ assert not worker.is_alive()
+ assert answers == [PermissionState.GRANTED]
+ assert (_MIC, "") not in env.service._last_native # the decision ended the "in flight" stamp
+
+
+def test_a_target_nobody_listed_is_never_echoed(make_env: Callable[..., Env]) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC])
+
+ result = env.service.ensure(_AUTOMATION, feature="audio_ducking", target="com.evil.app")
+ env.flush()
+
+ assert result.outcome is PermissionOutcome.UNAVAILABLE and result.target == ""
+ assert all("com.evil.app" not in repr(e) for e in env.bus.events)
+ assert all(e.target == "" for e in env.service.outstanding())
+ exploded = asyncio.run(
+ env.service.ensure_async(_AUTOMATION, feature="audio_ducking", target="/Users/x/app")
+ )
+ assert exploded.target == ""
+
+
+def test_an_unknown_feature_is_reported_without_one(
+ make_env: Callable[..., Env], caplog: pytest.LogCaptureFixture
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ env.service.ensure(_MIC, feature="teleport")
+ env.flush()
+
+ assert [e.feature for e in env.bus.needed()] == [""]
+ assert "unknown feature" in caplog.text
+
+
+def test_the_outside_sentence_names_the_right_grantee(make_env: Callable[..., Env]) -> None:
+ # One env after the other: each installs its own port as the process port.
+ terminal = make_env(bundle_id=None, bundle_path=None)
+ from_terminal = terminal.service.ensure(_MIC, feature="voice")
+ mounted = make_env(bundle_path="/Volumes/Personal Jarvis/Personal Jarvis.app")
+ from_dmg = mounted.service.ensure(_MIC, feature="voice")
+
+ assert from_terminal.outside_installed_app and from_dmg.outside_installed_app
+ assert "not running as an installed app" in from_terminal.user_detail
+ assert "granted to the app that started it" in from_terminal.user_detail
+ assert "outside its installed location" in from_dmg.user_detail
+ assert "app that started it" not in from_dmg.user_detail
+
+
+def test_the_sentences_state_facts_and_never_command_the_reader() -> None:
+ imperatives = ("Choose", "Turn", "Confirm", "Allow", "Open", "Click", "Press", "Quit", "Come")
+ for permission in PermissionId:
+ for reason in PERMISSION_NEEDED_REASONS:
+ for asking in (False, True):
+ for outside in (False, True):
+ text = user_detail_for(permission, reason, asking=asking, outside_app=outside)
+ sentences = [part.strip() for part in text.split(". ") if part.strip()]
+ for sentence in sentences:
+ assert not sentence.startswith(imperatives), sentence
+
+
+# ----------------------------------------------------------------------
+# Requirements the mutation run found unpinned
+# ----------------------------------------------------------------------
+
+
+def test_input_monitoring_is_not_re_asked_inside_its_cooldown(make_env: Callable[..., Env]) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ assert env.service.ensure(_IM, feature="global_shortcuts").asked
+ env.clock.advance(60)
+
+ assert not env.service.ensure(_IM, feature="dictation").asked # another episode, same cooldown
+
+ env.clock.advance(601)
+ assert env.service.ensure(_IM, feature="dictation").asked
+ assert len(env.tcc.requests("input_monitoring")) == 2
+
+
[email protected]("permission", [_SR, _AX], ids=["screen-recording", "accessibility"])
+def test_ask_again_after_a_reset_really_asks(
+ make_env: Callable[..., Env], permission: PermissionId
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ assert env.service.ensure(permission, feature="computer_use").asked
+ env.clock.advance(60)
+ assert not env.service.ensure(permission, feature="window_control").asked
+
+ env.service.note_reset(permission) # tccutil dropped the row: the cooldown is forgotten
+
+ assert env.service.ensure(permission, feature="window_control").asked
+
+
+def test_a_coalesced_episode_is_only_asking_while_every_member_is_asking(
+ make_env: Callable[..., Env],
+) -> None:
+ both_asking = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ both_asking.service.ensure_all([_AX, _SR], feature="computer_use")
+ both_asking.flush()
+ assert both_asking.bus.needed()[-1].phase == "os_dialog"
+
+ mixed = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ mixed.tcc.deny("microphone") # one member is already a final "no"
+ mixed.service.ensure_all([_MIC, _AX], feature="voice")
+ mixed.flush()
+ [event] = mixed.bus.needed()
+ assert (event.phase, event.reason) == ("blocked", "denied") # the card may open now
+
+
+def test_the_reason_a_coalesced_episode_shows_is_the_most_final_one() -> None:
+ assert service_module._REASON_PRIORITY == (
+ "restricted",
+ "unavailable",
+ "denied",
+ "needs_settings",
+ "restart_hint",
+ "not_determined",
+ )
+
+ def view(reason: str) -> service_module._View:
+ return service_module._View(
+ PermissionOutcome.DENIED, reason, "blocked", False, False, False
+ )
+
+ slot = service_module._Slot(family=_MIC, target="", probe=_MIC)
+ for stronger, weaker in (
+ ("restricted", "denied"),
+ ("denied", "needs_settings"),
+ ("needs_settings", "not_determined"),
+ ("restart_hint", "not_determined"),
+ ):
+ reason, _phase, _view = PermissionService._aggregate(
+ [(slot, view(weaker)), (slot, view(stronger))]
+ )
+ assert reason == stronger
+
+
+async def test_ensure_async_sees_a_screen_recording_grant_the_preflight_hides_while_waiting(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = FakeTCC(default_policy=DialogPolicy.NEVER_ANSWERED)
+ install_port(monkeypatch, tcc.port("darwin")) # type: ignore[arg-type]
+ service = PermissionService(
+ poll_s=0.01, watch_interval_s=_NEVER, negative_ttl_s=0.0, oracle_every_s=0.02
+ )
+ try:
+ waiting = asyncio.create_task(service.ensure_async(_SR, feature="computer_use", wait_s=5))
+ await asyncio.sleep(0.1)
+ assert not waiting.done()
+ tcc.grant("screen_recording") # the preflight stays frozen negative until a relaunch
+ result = await asyncio.wait_for(waiting, timeout=5)
+ assert result.granted and result.asked
+ assert service.check(_SR) is PermissionState.GRANTED # and it stays proven
+ finally:
+ service._shutdown()
+
+
+# ----------------------------------------------------------------------
+# Boot and the upgrader (design section 8)
+# ----------------------------------------------------------------------
+
+
+def test_an_upgrader_with_every_grant_in_place_sees_no_card_and_no_request(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(tcc=FakeTCC.all_granted(installed_players=[_MUSIC], running_players=[_MUSIC]))
+
+ results = env.service.ensure_all([_MIC, _SR, _AX, _IM], feature="computer_use")
+ results.append(env.service.ensure(_AUTOMATION, feature="audio_ducking", target=_MUSIC))
+ results.append(asyncio.run(env.service.ensure_async(_SR, feature="screen_context")))
+ env.service.refresh_episodes()
+ env.flush()
+
+ assert all(r.granted and not r.asked for r in results)
+ assert env.tcc.requests() == [] and env.tcc.implicit_prompts() == []
+ assert env.service.outstanding() == [] and env.bus.events == []
+
+
+def test_the_automation_player_table_is_what_the_service_may_ask_about() -> None:
+ assert {bundle_id for _name, bundle_id in AUTOMATION_TARGETS} >= {_MUSIC}
+
+
+def test_the_service_keeps_asking_through_the_frozen_api(make_env: Callable[..., Env]) -> None:
+ """The review added keyword arguments only: every frozen entry point still answers."""
+ env = make_env()
+ assert env.service.ensure(_MIC, feature="voice").granted
+ assert env.service.ensure_all([_MIC], feature="voice")[0].granted
+ assert asyncio.run(env.service.ensure_async(_MIC, feature="voice")).granted
+ assert env.service.check(_MIC) is PermissionState.GRANTED
+ assert env.service.open_settings(_MIC) is True
+ assert env.service.outstanding() == []
+ assert any(c.kind is CallKind.REQUEST for c in env.tcc.calls)
diff --git a/tests/unit/platform/test_permission_service_refused_use.py b/tests/unit/platform/test_permission_service_refused_use.py
new file mode 100644
index 0000000000..cc7c3d11a2
--- /dev/null
+++ b/tests/unit/platform/test_permission_service_refused_use.py
@@ -0,0 +1,483 @@
+"""Automation: a send refused with -1743 although the probe read GRANTED.
+
+``report_failed_use(AUTOMATION, ...)`` opens ONE background ``needs_settings`` episode
+that a granted probe never closes (the probe is exactly what lied); the next send that
+lands (``report_use_ok``), a reset or the episode TTL does. The path never asks. The REAL
+service runs on a REAL ``SystemPermissionPort`` that sits on ``FakeTCC``; the FakeTCC call
+log is the proof of what was (not) asked. Nothing here ran on a real Mac: the behaviour of
+an Apple Event after a grant is documented by Apple only as an error code, everything else
+is a MODEL (see ``tests/fakes/fake_tcc.py``).
+"""
+
+# ruff: noqa: F811 - the harness fixtures (``make_env``, ``loop_thread``) are imported by name
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Callable
+from typing import Any
+
+import pytest
+
+from jarvis.core.events import Event
+from jarvis.platform.permission_service import PermissionOutcome
+from jarvis.platform.permissions import PermissionId, PermissionState
+from tests.fakes.fake_tcc import DialogPolicy, TccService
+from tests.unit.platform.test_permission_service import ( # noqa: F401 - fixtures
+ Env,
+ LoopThread,
+ RecordingBus,
+ loop_thread,
+ make_env,
+)
+
+_MUSIC = "com.apple.Music"
+_SPOTIFY = "com.spotify.client"
+_AUTOMATION = PermissionId.AUTOMATION
+_SR = PermissionId.SCREEN_RECORDING
+_FEATURE = "audio_ducking"
+
+
+def _granted_music(make_env: Callable[..., Env], **kwargs: Any) -> Env:
+ """A Mac where Music runs and Automation reads GRANTED for it."""
+ return make_env(
+ granted=[TccService.AUTOMATION],
+ installed_players=[_MUSIC, _SPOTIFY],
+ running_players=[_MUSIC, _SPOTIFY],
+ **kwargs,
+ )
+
+
+def _report(env: Env, target: str = _MUSIC, **kwargs: Any):
+ return env.service.report_failed_use(_AUTOMATION, feature=_FEATURE, target=target, **kwargs)
+
+
+# ----------------------------------------------------------------------
+# What a refused send opens
+# ----------------------------------------------------------------------
+
+
+def test_a_refused_send_after_a_granted_read_opens_one_background_needs_settings_episode(
+ make_env: Callable[..., Env],
+) -> None:
+ env = _granted_music(make_env)
+
+ result = _report(env)
+ env.flush()
+
+ assert result.outcome is PermissionOutcome.NEEDS_SETTINGS and not result.granted
+ assert result.reason == "needs_settings" and result.target == _MUSIC
+ assert not result.can_prompt and result.can_open_settings and not result.asked
+ # The sentence names the player and does not claim the switch is off (the probe says on).
+ assert "Automation access for Music" in result.user_detail
+ assert "refused an Apple event" in result.user_detail and "is off" not in result.user_detail
+ assert result.agent_detail.startswith("[permission_needed:automation] ")
+ [needed] = env.bus.needed()
+ assert (
+ needed.feature,
+ needed.permissions,
+ needed.reason,
+ needed.phase,
+ needed.origin,
+ needed.target,
+ needed.can_prompt,
+ needed.can_open_settings,
+ needed.outside_app,
+ ) == (
+ _FEATURE,
+ ("automation",),
+ "needs_settings",
+ "blocked",
+ "background",
+ _MUSIC,
+ False,
+ True,
+ False,
+ )
+ [episode] = env.service.outstanding()
+ assert (episode.feature, episode.permissions, episode.reason, episode.origin) == (
+ _FEATURE,
+ ("automation",),
+ "needs_settings",
+ "background",
+ )
+ assert episode.target == _MUSIC and episode.detail == needed.detail
+ # It never asks: no native request, no dialog, nothing behind the user's back.
+ env.tcc.assert_no_prompts()
+ assert env.tcc.requests() == [] and env.tcc.dialogs_shown() == []
+
+
+def test_the_same_report_on_every_session_start_stays_one_event_and_one_episode(
+ make_env: Callable[..., Env],
+) -> None:
+ env = _granted_music(make_env)
+
+ for _ in range(4):
+ _report(env)
+ env.flush()
+
+ assert len(env.bus.needed()) == 1 and len(env.service.outstanding()) == 1
+ assert env.bus.resolved() == []
+ assert env.tcc.requests() == []
+
+
+def test_each_player_has_its_own_episode(make_env: Callable[..., Env]) -> None:
+ env = _granted_music(make_env)
+
+ _report(env, _MUSIC)
+ _report(env, _SPOTIFY)
+ env.flush()
+
+ assert sorted(e.target for e in env.service.outstanding()) == sorted([_MUSIC, _SPOTIFY])
+ assert env.service.report_use_ok(_AUTOMATION, feature=_FEATURE, target=_MUSIC) is True
+ env.flush()
+ assert [e.target for e in env.service.outstanding()] == [_SPOTIFY] # the other one is untouched
+
+
+def test_a_stale_user_origin_episode_of_the_player_never_lends_its_card_to_the_report(
+ make_env: Callable[..., Env],
+) -> None:
+ """The ask's own episode (user origin) is answered but not yet swept by the watcher."""
+ env = make_env(
+ default_policy=DialogPolicy.NEVER_ANSWERED,
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ )
+ env.service.ensure(_AUTOMATION, feature=_FEATURE, target=_MUSIC) # the switch-on gesture
+ assert [e.origin for e in env.service.outstanding()] == ["user"]
+ env.tcc.grant(TccService.AUTOMATION, _MUSIC) # answered; the watcher has not run yet
+
+ _report(env)
+ env.flush()
+
+ [episode] = env.service.outstanding()
+ assert (episode.reason, episode.origin) == ("needs_settings", "background")
+ assert [e.granted for e in env.bus.resolved()] == [True] # the answered ask ended first
+
+
+# ----------------------------------------------------------------------
+# What ends it, and what must not
+# ----------------------------------------------------------------------
+
+
+def test_a_granted_probe_never_resolves_it_but_a_landed_send_does(
+ make_env: Callable[..., Env],
+) -> None:
+ env = _granted_music(make_env)
+ _report(env)
+
+ for _ in range(3): # the watcher pass, a status read and ensure all see GRANTED
+ env.settle()
+ assert env.service.check(_AUTOMATION, target=_MUSIC) is PermissionState.GRANTED
+ assert env.service.ensure(
+ _AUTOMATION, feature=_FEATURE, interactive=False, target=_MUSIC
+ ).granted
+ assert env.service.ensure(_AUTOMATION, feature=_FEATURE, target=_MUSIC).granted
+ env.flush()
+ assert env.bus.resolved() == []
+ assert [e.reason for e in env.service.outstanding()] == ["needs_settings"]
+ assert env.tcc.requests() == [] # a granted state asks nothing, however often it is read
+
+ assert env.service.report_use_ok(_AUTOMATION, feature=_FEATURE, target=_MUSIC) is True
+ env.flush()
+
+ assert env.service.outstanding() == []
+ [resolved] = env.bus.resolved()
+ assert (resolved.feature, resolved.permissions, resolved.granted) == (
+ _FEATURE,
+ ("automation",),
+ True,
+ )
+ assert env.service.report_use_ok(_AUTOMATION, feature=_FEATURE, target=_MUSIC) is False
+
+
+def test_the_real_watcher_does_not_resolve_it_either(
+ make_env: Callable[..., Env], loop_thread: LoopThread
+) -> None:
+ import time
+
+ env = _granted_music(make_env, watch_interval_s=0.02)
+ _report(env)
+
+ deadline = time.monotonic() + 0.5 # many watcher passes, every one reads GRANTED
+ while time.monotonic() < deadline:
+ time.sleep(0.02)
+ env.flush()
+
+ assert env.bus.resolved() == []
+ assert [e.reason for e in env.service.outstanding()] == ["needs_settings"]
+
+
+def test_a_landed_send_only_clears_the_feature_and_player_it_names(
+ make_env: Callable[..., Env],
+) -> None:
+ env = _granted_music(make_env)
+ _report(env)
+
+ assert env.service.report_use_ok(_AUTOMATION, feature="voice", target=_MUSIC) is False
+ assert env.service.report_use_ok(_AUTOMATION, feature=_FEATURE, target=_SPOTIFY) is False
+ assert env.service.report_use_ok(_AUTOMATION, feature=_FEATURE) is False # no player named
+ assert env.service.report_use_ok(_SR, feature=_FEATURE, target=_MUSIC) is False
+ assert env.service.report_use_ok(_AUTOMATION, feature=_FEATURE, target="com.evil.app") is False
+
+ assert [e.reason for e in env.service.outstanding()] == ["needs_settings"]
+
+
+def test_the_episode_ends_by_its_ttl_and_every_report_keeps_it_alive(
+ make_env: Callable[..., Env],
+) -> None:
+ env = _granted_music(make_env)
+ _report(env)
+
+ env.clock.advance(400)
+ _report(env) # the refusal is still happening: the clock starts again
+ env.clock.advance(400)
+ env.service.refresh_episodes()
+ env.flush()
+ assert [e.reason for e in env.service.outstanding()] == ["needs_settings"]
+
+ env.clock.advance(201) # nobody reported for ten minutes: stale evidence
+ env.service.refresh_episodes()
+ env.flush()
+
+ assert env.service.outstanding() == []
+ assert [r.granted for r in env.bus.resolved()] == [False]
+
+
+def test_a_reset_ends_it_because_the_decision_is_gone(make_env: Callable[..., Env]) -> None:
+ env = _granted_music(make_env)
+ _report(env)
+
+ env.service.note_reset(_AUTOMATION) # "Ask again": tccutil dropped the Apple Events row
+ env.tcc.reset(TccService.AUTOMATION)
+ env.settle()
+
+ assert [e.reason for e in env.service.outstanding()] == ["not_determined"]
+ assert env.tcc.requests() == []
+
+
+def test_a_state_that_is_no_longer_granted_is_described_by_its_real_reason(
+ make_env: Callable[..., Env],
+) -> None:
+ env = _granted_music(make_env)
+ _report(env)
+
+ env.tcc.deny(TccService.AUTOMATION, _MUSIC)
+ env.settle()
+ [episode] = env.service.outstanding()
+ assert episode.reason == "denied" and "refused an Apple event" not in episode.detail
+
+ env.tcc.grant(TccService.AUTOMATION, _MUSIC) # fixed in Settings, but no send has landed yet
+ env.settle()
+ [episode] = env.service.outstanding()
+ assert episode.reason == "needs_settings" and "refused an Apple event" in episode.detail
+
+
+def test_a_live_state_that_is_not_granted_is_reported_through_the_plain_path(
+ make_env: Callable[..., Env],
+) -> None:
+ env = _granted_music(make_env)
+ env.tcc.deny(TccService.AUTOMATION, _MUSIC)
+
+ result = _report(env)
+ env.flush()
+
+ assert result.reason == "denied" and not result.granted and not result.asked
+ [episode] = env.service.outstanding()
+ assert (episode.reason, episode.origin, episode.target) == ("denied", "background", _MUSIC)
+ assert env.tcc.requests() == []
+
+
+# ----------------------------------------------------------------------
+# The path never asks, and leaves the ask rules alone
+# ----------------------------------------------------------------------
+
+
+def test_a_player_that_was_never_asked_is_not_asked_by_the_report(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(
+ default_policy=DialogPolicy.NEVER_ANSWERED,
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ )
+
+ result = _report(env)
+ env.flush()
+
+ assert result.reason == "not_determined" and not result.asked
+ assert env.tcc.requests() == [] and env.tcc.dialogs_shown() == []
+ assert [(e.origin, e.reason) for e in env.service.outstanding()] == [
+ ("background", "not_determined")
+ ]
+
+
+def test_the_report_leaves_the_one_request_per_episode_rule_alone(
+ make_env: Callable[..., Env],
+) -> None:
+ env = _granted_music(make_env)
+ _report(env)
+ env.tcc.reset(TccService.AUTOMATION, _MUSIC) # the grant is gone: undecided again
+ env.service.invalidate()
+
+ first = env.service.ensure(_AUTOMATION, feature=_FEATURE, target=_MUSIC) # the gesture
+ again = env.service.ensure(_AUTOMATION, feature=_FEATURE, target=_MUSIC)
+
+ assert first.asked and first.granted # the report neither used up the ask ...
+ assert not again.asked # ... nor doubled it
+ assert [call.target for call in env.tcc.requests("automation")] == [_MUSIC]
+
+
[email protected]("platform", ["win32", "linux"])
+def test_off_macos_nothing_happens(make_env: Callable[..., Env], platform: str) -> None:
+ env = make_env(
+ platform=platform,
+ granted=[TccService.AUTOMATION],
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ )
+
+ result = _report(env)
+ ok = env.service.report_use_ok(_AUTOMATION, feature=_FEATURE, target=_MUSIC)
+ env.flush()
+
+ assert result.outcome is PermissionOutcome.NOT_REQUIRED and result.granted and ok is False
+ assert env.service.outstanding() == [] and env.bus.events == []
+ env.tcc.assert_silent() # no framework loaded, no call of any kind
+
+
+# ----------------------------------------------------------------------
+# Unknown targets, reasons and origins
+# ----------------------------------------------------------------------
+
+
[email protected]("target", ["com.evil.app", "../../etc/passwd", "Music", "", None])
+def test_a_target_outside_the_player_table_is_rejected_and_never_echoed(
+ make_env: Callable[..., Env], target: str | None
+) -> None:
+ env = _granted_music(make_env)
+ mark = env.tcc.mark()
+
+ result = env.service.report_failed_use(_AUTOMATION, feature=_FEATURE, target=target)
+ env.flush()
+
+ assert result.outcome is PermissionOutcome.UNAVAILABLE and result.reason == "unavailable"
+ assert result.target == "" and not result.asked
+ for text in (repr(result), repr(env.bus.events), repr(env.service.outstanding())):
+ assert "evil" not in text and "passwd" not in text
+ assert env.service.outstanding() == [] and env.bus.events == []
+ assert env.tcc.calls_since(mark) == () # nothing was even read, let alone asked
+
+
+def test_a_reason_the_family_cannot_carry_is_a_plain_non_interactive_ensure(
+ make_env: Callable[..., Env],
+) -> None:
+ env = make_env(
+ granted=[TccService.AUTOMATION, TccService.SCREEN_RECORDING],
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ )
+
+ automation = _report(env, reason="restart_hint") # Apple Events are checked per send
+ screen = env.service.report_failed_use(_SR, feature="computer_use", reason="needs_settings")
+ env.flush()
+
+ assert automation.granted and screen.granted
+ assert env.service.outstanding() == [] and env.bus.events == []
+ assert env.tcc.requests() == []
+
+
+def test_the_origin_defaults_per_family_and_an_unknown_one_is_ignored(
+ make_env: Callable[..., Env],
+) -> None:
+ env = _granted_music(make_env)
+ env.tcc.grant(TccService.SCREEN_RECORDING)
+
+ _report(env) # Automation: background
+ env.service.report_failed_use(_SR, feature="computer_use") # Screen Recording: user
+ by_permission = {e.permissions: e.origin for e in env.service.outstanding()}
+ assert by_permission == {("automation",): "background", ("screen_recording",): "user"}
+
+ explicit = make_env(granted=[TccService.SCREEN_RECORDING])
+ explicit.service.report_failed_use(
+ _SR, feature="computer_use", origin="background"
+ ) # no card for a background consumer
+ assert [e.origin for e in explicit.service.outstanding()] == ["background"]
+
+ bogus = _granted_music(make_env)
+ _report(bogus, origin="floating_card") # outside the vocabulary: the family default
+ assert [e.origin for e in bogus.service.outstanding()] == ["background"]
+
+ user = _granted_music(make_env)
+ _report(user, origin="user") # a caller that really is a gesture may say so
+ assert [e.origin for e in user.service.outstanding()] == ["user"]
+
+
+# ----------------------------------------------------------------------
+# AP-18 / AP-30: a broken bus never breaks the report, and nothing fails silently
+# ----------------------------------------------------------------------
+
+
+class _SyncRaisingBus:
+ def publish(self, event: Event) -> None:
+ raise RuntimeError("the bus is broken")
+
+
+class _AsyncRaisingBus:
+ async def publish(self, event: Event) -> None:
+ raise RuntimeError("the subscriber blew up")
+
+
[email protected]("bus", [_SyncRaisingBus(), _AsyncRaisingBus()], ids=["sync", "async"])
+def test_a_bus_that_raises_never_breaks_the_report(
+ make_env: Callable[..., Env], bus: Any, caplog: pytest.LogCaptureFixture
+) -> None:
+ env = _granted_music(make_env)
+ env.service.attach_bus(bus, env.loop.loop)
+
+ with caplog.at_level("DEBUG", logger="jarvis.platform.permission_service"):
+ result = _report(env)
+ env.flush()
+
+ assert result.reason == "needs_settings"
+ assert [e.reason for e in env.service.outstanding()] == [
+ "needs_settings"
+ ] # the registry kept it
+ assert any(
+ "permission event" in r.message or "bus refused" in r.message for r in caplog.records
+ )
+ assert env.service.report_use_ok(_AUTOMATION, feature=_FEATURE, target=_MUSIC) is True
+
+
+def test_a_closed_loop_drops_the_event_but_not_the_episode(
+ make_env: Callable[..., Env], caplog: pytest.LogCaptureFixture
+) -> None:
+ env = _granted_music(make_env)
+ closed = asyncio.new_event_loop()
+ closed.close()
+ env.service.attach_bus(RecordingBus(), closed)
+
+ with caplog.at_level("DEBUG", logger="jarvis.platform.permission_service"):
+ result = _report(env)
+
+ assert result.reason == "needs_settings"
+ assert [e.reason for e in env.service.outstanding()] == ["needs_settings"]
+ assert any("dropped" in record.message for record in caplog.records)
+
+
+def test_a_failed_read_is_logged_and_never_raised(
+ make_env: Callable[..., Env], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ env = _granted_music(make_env)
+
+ def broken(*_args: Any, **_kwargs: Any) -> PermissionState:
+ raise RuntimeError("the native read failed")
+
+ monkeypatch.setattr(env.service, "_read_state", broken)
+
+ with caplog.at_level("DEBUG", logger="jarvis.platform.permission_service"):
+ result = _report(env)
+
+ assert result.outcome is PermissionOutcome.UNAVAILABLE and result.target == _MUSIC
+ assert any("report_failed_use" in record.message for record in caplog.records)
+ assert env.service.outstanding() == []
diff --git a/tests/unit/platform/test_permission_service_status_helpers.py b/tests/unit/platform/test_permission_service_status_helpers.py
new file mode 100644
index 0000000000..86a894926d
--- /dev/null
+++ b/tests/unit/platform/test_permission_service_status_helpers.py
@@ -0,0 +1,256 @@
+"""The read helpers the permission routes need from ``PermissionService``.
+
+``app_info`` (who this process is to macOS), ``check_deep`` (the fresh read with the
+Screen Recording window-title oracle), ``can_request`` (could a gesture make macOS
+show something) and the ``note_reset`` memory of an open episode. The REAL service
+runs on a REAL ``SystemPermissionPort`` that sits on ``FakeTCC``; nothing here ran on
+a real Mac, every macOS behaviour is a MODEL (see ``tests/fakes/fake_tcc.py``).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Iterator
+from typing import Any
+
+import pytest
+
+from jarvis.platform import permission_service as service_module
+from jarvis.platform.permission_service import AppInfo, PermissionOutcome, PermissionService
+from jarvis.platform.permissions import APP_NAME, PermissionId, PermissionState
+from tests.fakes.fake_tcc import DMG_BUNDLE_ID, DialogPolicy, FakeTCC, TccService, install_port
+
+_MIC = PermissionId.MICROPHONE
+_SR = PermissionId.SCREEN_RECORDING
+_AX = PermissionId.ACCESSIBILITY
+_AUTOMATION = PermissionId.AUTOMATION
+_MUSIC = "com.apple.Music"
+
+
+def make_service(
+ monkeypatch: pytest.MonkeyPatch,
+) -> Iterator[Callable[..., tuple[PermissionService, FakeTCC]]]:
+ created: list[PermissionService] = []
+
+ def build(*, platform: str = "darwin", **tcc_kwargs: Any) -> tuple[PermissionService, FakeTCC]:
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port(platform)) # type: ignore[arg-type]
+ service = PermissionService(watch_interval_s=3600.0)
+ created.append(service)
+ return service, tcc
+
+ yield build
+ for service in created:
+ service._shutdown()
+
+
+# ----------------------------------------------------------------------
+# app_info
+# ----------------------------------------------------------------------
+
+
+def test_app_info_of_the_installed_app(make_service) -> None:
+ service, _tcc = make_service()
+
+ assert service.app_info() == AppInfo(
+ platform="darwin",
+ app_name=APP_NAME,
+ bundle_id="com.personal-jarvis.desktop",
+ bundle_path="/Applications/Personal Jarvis.app",
+ launched_as_bundle=True,
+ stable=True,
+ outside_installed_app=False,
+ headless=False,
+ )
+
+
+def test_app_info_of_the_dmg_app_is_an_installed_app_too(make_service) -> None:
+ service, _tcc = make_service(bundle_id=DMG_BUNDLE_ID)
+
+ info = service.app_info()
+
+ assert info.bundle_id == DMG_BUNDLE_ID and info.stable and not info.outside_installed_app
+
+
+def test_app_info_outside_the_installed_app(make_service) -> None:
+ service, _tcc = make_service(bundle_id=None, bundle_path=None)
+
+ info = service.app_info()
+
+ assert info.outside_installed_app is True and info.stable is False
+ assert info.bundle_id is None and info.launched_as_bundle is False
+
+
+def test_app_info_reports_a_missing_desktop_session(make_service) -> None:
+ service, _tcc = make_service(headless=True)
+
+ assert service.app_info().headless is True
+
+
[email protected]("platform", ["win32", "linux"])
+def test_app_info_off_macos_has_no_bundle_and_is_not_outside_anything(
+ make_service, platform: str
+) -> None:
+ service, tcc = make_service(platform=platform)
+
+ info = service.app_info()
+
+ assert info.platform == platform
+ assert (info.bundle_id, info.bundle_path) == (None, None)
+ assert info.stable is False and info.outside_installed_app is False
+ tcc.assert_silent()
+
+
+def test_app_info_of_a_port_that_cannot_describe_itself_degrades(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class BarePort:
+ platform = "darwin"
+
+ monkeypatch.setattr(service_module._permissions_module, "get_system_permission_port", BarePort)
+ service = PermissionService()
+
+ info = service.app_info()
+
+ assert info.platform == "darwin" and info.app_name == APP_NAME
+ assert info.bundle_id is None and info.stable is False and info.headless is False
+
+
+# ----------------------------------------------------------------------
+# check_deep
+# ----------------------------------------------------------------------
+
+
+def test_check_deep_sees_the_screen_grant_the_frozen_preflight_still_denies(make_service) -> None:
+ service, tcc = make_service()
+ tcc.grant("screen_recording") # mid-process: the preflight is frozen until relaunch (BUG-161)
+
+ assert service.check(_SR) is PermissionState.NOT_GRANTED
+ assert service.check_deep(_SR) is PermissionState.GRANTED
+
+
+def test_check_deep_is_fresh_where_check_may_be_cached(make_service) -> None:
+ service, tcc = make_service(granted=[TccService.MICROPHONE])
+ assert service.check(_MIC) is PermissionState.GRANTED # cached for about a second
+
+ tcc.deny("microphone")
+
+ assert service.check(_MIC) is PermissionState.GRANTED # the cache answers
+ assert service.check_deep(_MIC) is PermissionState.DENIED # this one goes to the OS
+
+
+def test_check_deep_never_prompts(make_service) -> None:
+ service, tcc = make_service()
+
+ for permission in (_MIC, _SR, _AX):
+ service.check_deep(permission)
+
+ tcc.assert_no_prompts()
+
+
[email protected]("platform", ["win32", "linux"])
+def test_check_deep_off_macos_is_not_required_and_silent(make_service, platform: str) -> None:
+ service, tcc = make_service(platform=platform)
+
+ assert service.check_deep(_SR) is PermissionState.NOT_REQUIRED
+ tcc.assert_silent()
+
+
+def test_check_deep_never_raises(monkeypatch: pytest.MonkeyPatch) -> None:
+ class ExplodingPort:
+ platform = "darwin"
+
+ def state(self, *args: Any, **kwargs: Any) -> Any:
+ raise RuntimeError("the native bridge blew up")
+
+ monkeypatch.setattr(
+ service_module._permissions_module, "get_system_permission_port", ExplodingPort
+ )
+
+ assert PermissionService().check_deep(_MIC) is PermissionState.UNAVAILABLE
+
+
+# ----------------------------------------------------------------------
+# can_request
+# ----------------------------------------------------------------------
+
+
[email protected]("permission", [_MIC, _SR, _AX, PermissionId.INPUT_MONITORING])
+def test_a_permission_nobody_decided_can_be_requested(make_service, permission) -> None:
+ service, _tcc = make_service()
+
+ assert service.can_request(permission) is True
+
+
+def test_a_decided_permission_cannot_be_requested(make_service) -> None:
+ service, tcc = make_service(granted=[TccService.MICROPHONE])
+ tcc.deny("screen_recording")
+ tcc.restrict("accessibility")
+
+ assert service.can_request(_MIC) is False # granted
+ assert service.can_request(_SR, PermissionState.DENIED) is False # macOS will not ask again
+ assert service.can_request(_AX, PermissionState.RESTRICTED) is False
+ assert service.can_request(_AX, PermissionState.UNAVAILABLE) is False
+
+
+def test_the_keychain_has_no_native_request(make_service) -> None:
+ service, _tcc = make_service(credential_backend="file")
+
+ assert service.can_request(PermissionId.CREDENTIAL_STORE) is False
+
+
+def test_without_a_usage_string_nothing_may_be_requested(make_service) -> None:
+ service, tcc = make_service(usage_strings=[TccService.AUTOMATION])
+
+ assert service.can_request(_MIC) is False # BUG-058 class: asking would abort the process
+ assert tcc.requests() == []
+
+
+def test_automation_needs_a_player_or_a_known_state(make_service) -> None:
+ service, tcc = make_service(installed_players=[_MUSIC], running_players=[_MUSIC])
+
+ assert service.can_request(_AUTOMATION) is False # no player: never the aggregate read
+ assert tcc.calls == ()
+ assert service.can_request(_AUTOMATION, target=_MUSIC) is True
+ assert service.can_request(_AUTOMATION, PermissionState.NOT_DETERMINED) is True
+
+
[email protected]("platform", ["win32", "linux"])
+def test_nothing_can_be_requested_off_macos(make_service, platform: str) -> None:
+ service, tcc = make_service(platform=platform)
+
+ assert service.can_request(_MIC) is False
+ tcc.assert_silent()
+
+
+# ----------------------------------------------------------------------
+# note_reset: "Ask again" must really ask
+# ----------------------------------------------------------------------
+
+
+def test_after_a_reset_an_open_episode_may_ask_again(make_service) -> None:
+ service, tcc = make_service(default_policy=DialogPolicy.DENY)
+ first = service.ensure(_MIC, feature="voice")
+ assert first.asked and first.outcome is PermissionOutcome.DENIED
+ assert [o.permissions for o in service.outstanding()] == [("microphone",)] # still open
+
+ tcc.reset("microphone") # tccutil reset: the decision is gone
+ service.note_reset(_MIC)
+ tcc.set_policy("microphone", DialogPolicy.ALLOW)
+ second = service.ensure(_MIC, feature="voice")
+
+ assert second.asked is True and second.outcome is PermissionOutcome.GRANTED
+ assert len(tcc.requests("microphone")) == 2
+
+
+def test_without_note_reset_the_open_episode_would_not_ask_again(make_service) -> None:
+ """The reason ``note_reset`` clears the episode's memory: one ask per episode."""
+ service, tcc = make_service(default_policy=DialogPolicy.DENY)
+ service.ensure(_MIC, feature="voice")
+ tcc.reset("microphone")
+ tcc.set_policy("microphone", DialogPolicy.ALLOW)
+
+ second = service.ensure(_MIC, feature="voice")
+
+ assert second.asked is False
+ assert len(tcc.requests("microphone")) == 1
diff --git a/tests/unit/platform/test_permissions.py b/tests/unit/platform/test_permissions.py
index 3b286d0890..c4d9297905 100644
--- a/tests/unit/platform/test_permissions.py
+++ b/tests/unit/platform/test_permissions.py
@@ -1,4 +1,8 @@
-"""Unit coverage for the uncached macOS system-permission port."""
+"""Unit coverage for the uncached macOS system-permission port.
+
+Hand-written stubs stand in for the native frameworks; the stateful FakeTCC world
+is exercised in ``test_permission_characterization.py`` and ``test_fake_tcc.py``.
+"""
from __future__ import annotations
@@ -29,15 +33,7 @@ class _Bundle:
class _RunningApp:
- def __init__(self, *, active: bool = True, pid: int = 123) -> None:
- self._active = active
- self._pid = pid
-
- def isActive(self) -> bool:
- return self._active
-
- def processIdentifier(self) -> int:
- return self._pid
+ """A placeholder application: the port only asks whether a window server answers."""
class _Workspace:
@@ -70,9 +66,8 @@ class _CaptureDevice:
def _native_modules(
*,
bundle_id: str | None = EXPECTED_BUNDLE_ID,
- active: bool = True,
) -> tuple[dict[str, object], dict[str, bool], _Workspace]:
- current = _RunningApp(active=active)
+ current = _RunningApp()
workspace = _Workspace(current)
screen = {"granted": False, "requested": False}
event = {"listen": False, "post": False}
@@ -162,14 +157,14 @@ def _port(
)
-def _permission(snapshot: dict, permission_id: PermissionId) -> dict:
- return next(item for item in snapshot["permissions"] if item["id"] == permission_id)
-
-
def test_permission_bundle_id_matches_installed_app_identity() -> None:
assert EXPECTED_BUNDLE_ID == BUNDLE_ID
+def _identity(port: SystemPermissionPort):
+ return port._app_identity()[0]
+
+
def test_matching_bundle_id_at_noncanonical_path_is_not_stable(tmp_path: Path) -> None:
modules, _, _ = _native_modules()
copied_bundle = SimpleNamespace(
@@ -177,8 +172,10 @@ def test_matching_bundle_id_at_noncanonical_path_is_not_stable(tmp_path: Path) -
bundlePath=lambda: str(tmp_path / "Personal Jarvis.app"),
)
modules["Foundation"].NSBundle = SimpleNamespace(mainBundle=lambda: copied_bundle)
+ port = _port(modules)
- assert _port(modules).snapshot()["app_identity"]["stable"] is False
+ assert _identity(port).stable is False
+ assert port.outside_installed_app is True
def test_non_macos_degrades_to_not_required_without_native_imports() -> None:
@@ -187,47 +184,31 @@ def test_non_macos_degrades_to_not_required_without_native_imports() -> None:
platform_name="win32", module_loader=lambda name: imports.append(name)
)
- snapshot = port.snapshot()
+ states = {permission_id: port.state(permission_id) for permission_id in PermissionId}
assert imports == []
- assert snapshot["supported"] is False
- assert {item["status"] for item in snapshot["permissions"]} == {PermissionState.NOT_REQUIRED}
- assert all(feature["ready"] for feature in snapshot["features"].values())
+ assert set(states.values()) == {PermissionState.NOT_REQUIRED}
-def test_snapshot_maps_native_states_and_feature_readiness() -> None:
+def test_state_maps_native_states() -> None:
_CaptureDevice.status = 3
modules, _, _ = _native_modules()
+ port = _port(modules)
- snapshot = _port(modules).snapshot()
-
- assert snapshot["app_identity"]["stable"] is True
- assert snapshot["app_identity"]["foreground"] is True
- assert _permission(snapshot, PermissionId.MICROPHONE)["status"] == "granted"
- assert _permission(snapshot, PermissionId.SCREEN_RECORDING)["status"] == ("not_granted")
- assert snapshot["features"]["voice"] == {
- "ready": True,
- "missing": [],
- "identity_ready": True,
- "restart_required": False,
- }
- # event_posting is granted through the trusted Accessibility fixture, so
- # only the screen-recording grant is still missing for Computer-Use.
- assert snapshot["features"]["computer_use"] == {
- "ready": False,
- "missing": ["screen_recording"],
- "identity_ready": True,
- "restart_required": False,
- }
+ assert _identity(port).stable is True
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.GRANTED
+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
+ # Event posting follows the trusted Accessibility fixture.
+ assert port.state(PermissionId.EVENT_POSTING) is PermissionState.GRANTED
-def test_snapshot_is_uncached() -> None:
+def test_state_is_uncached() -> None:
modules, screen, _ = _native_modules()
port = _port(modules)
- assert _permission(port.snapshot(), PermissionId.SCREEN_RECORDING)["status"] == "not_granted"
+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
screen["granted"] = True
- assert _permission(port.snapshot(), PermissionId.SCREEN_RECORDING)["status"] == "granted"
+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.GRANTED
def test_state_probes_only_the_requested_permission() -> None:
@@ -245,142 +226,47 @@ def test_state_probes_only_the_requested_permission() -> None:
assert imports == ["AVFoundation"]
-def test_runtime_access_requires_stable_identity_and_fresh_grant() -> None:
+def test_state_reads_the_grant_whatever_the_identity_and_flags_a_foreign_app() -> None:
+ """Identity gates ASKING (the service), never what a read reports."""
_CaptureDevice.status = 3
modules, _, _ = _native_modules()
stable = _port(modules)
unstable_modules, _, _ = _native_modules(bundle_id="org.python.python")
+ unstable = _port(unstable_modules)
- assert stable.runtime_access_granted(PermissionId.MICROPHONE) is True
- assert _port(unstable_modules).runtime_access_granted(PermissionId.MICROPHONE) is False
+ assert stable.state(PermissionId.MICROPHONE) is PermissionState.GRANTED
+ assert stable.outside_installed_app is False
+ assert unstable.state(PermissionId.MICROPHONE) is PermissionState.GRANTED
+ assert unstable.outside_installed_app is True
_CaptureDevice.status = 2
- assert stable.runtime_access_granted(PermissionId.MICROPHONE) is False
+ assert stable.state(PermissionId.MICROPHONE) is PermissionState.DENIED
-def test_runtime_access_blocks_a_grant_the_frozen_preflight_cannot_confirm() -> None:
+def test_a_screen_request_does_not_unfreeze_the_preflight() -> None:
modules, screen, _ = _native_modules()
port = _port(modules)
- result = port.request(PermissionId.SCREEN_RECORDING)
+ outcome = port.request_native(PermissionId.SCREEN_RECORDING)
- assert result.ok is True
- # The frozen preflight still reads "no", so access must stay closed.
+ # CGRequestScreenCaptureAccess answered True, but the preflight is frozen for
+ # the life of the process: the answer is never evidence of a grant.
+ assert outcome == "no_dialog"
+ assert screen["requested"] is True
assert screen["granted"] is False
assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
- assert port.runtime_access_granted(PermissionId.SCREEN_RECORDING) is False
-def test_a_pending_restart_dies_the_moment_the_probe_reads_the_grant() -> None:
- """BUG-159: a live grant ends the restart claim — nothing else clears it.
-
- Holding the flag past a GRANTED probe is what disabled Computer-Use and
- hotkeys for the rest of the session after a single settings visit, with
- no code path left to undo it.
- """
- modules, screen, _ = _native_modules()
- port = _port(modules)
- port.request(PermissionId.SCREEN_RECORDING)
- assert port.snapshot()["restart_required"] is True
-
- # What a relaunch — or simply granting a live-reading permission — looks
- # like: the probe now sees the grant.
- screen["granted"] = True
-
- assert port.runtime_access_granted(PermissionId.SCREEN_RECORDING) is True
- snapshot = port.snapshot()
- assert snapshot["restart_required"] is False
- assert _permission(snapshot, PermissionId.SCREEN_RECORDING)["restart_required"] is False
- assert snapshot["features"]["computer_use"]["ready"] is True
-
-
-def test_opening_settings_for_a_granted_permission_demands_no_restart() -> None:
- """BUG-159: looking at an already-granted pane must change nothing.
-
- The old flow flagged a restart on every open-settings click, which turned
- a curious glance into "Computer-Use and hotkeys are off until you relaunch".
- """
- modules, screen, _ = _native_modules()
- screen["granted"] = True
- port = _port(modules, iohid_check=lambda _type: 0)
- assert port.runtime_feature_ready("computer_use") is True
-
- result = port.open_settings(PermissionId.ACCESSIBILITY)
-
- assert result.ok is True
- assert result.restart_required is False
- assert result.snapshot["restart_required"] is False
- assert result.snapshot["features"]["computer_use"]["ready"] is True
- assert port.runtime_feature_ready("computer_use") is True
- assert port.runtime_feature_ready("global_hotkeys") is True
-
-
-def test_microphone_status_distinguishes_denied_and_restricted() -> None:
+def test_microphone_state_distinguishes_denied_and_restricted() -> None:
modules, _, _ = _native_modules()
port = _port(modules)
_CaptureDevice.status = 2
- denied = _permission(port.snapshot(), PermissionId.MICROPHONE)
+ denied = port.state(PermissionId.MICROPHONE)
_CaptureDevice.status = 1
- restricted = _permission(port.snapshot(), PermissionId.MICROPHONE)
-
- assert denied["status"] == "denied"
- assert denied["can_request"] is False
- assert restricted["status"] == "restricted"
- assert restricted["can_request"] is False
+ restricted = port.state(PermissionId.MICROPHONE)
-
-def test_request_screen_capture_calls_native_api_and_requires_restart() -> None:
- modules, screen, _ = _native_modules()
-
- result = _port(modules).request(PermissionId.SCREEN_RECORDING)
-
- assert result.ok is True
- assert result.performed is True
- assert result.restart_required is True
- assert screen["requested"] is True
- assert result.snapshot["restart_required"] is True
- assert _permission(result.snapshot, PermissionId.SCREEN_RECORDING)["restart_required"] is True
-
-
-def test_request_reporting_false_points_at_system_settings() -> None:
- """A suppressed prompt must not promise a restart-only path (BUG-083 class).
-
- macOS prompts each app identity exactly once; a previously denied Screen
- Recording makes CGRequestScreenCaptureAccess return False WITHOUT any
- dialog. The user needs the System Settings pointer, not a restart loop.
- """
- modules, screen, _ = _native_modules()
- modules["Quartz"].CGRequestScreenCaptureAccess = lambda: False
-
- result = _port(modules).request(PermissionId.SCREEN_RECORDING)
-
- assert result.ok is True
- assert screen["granted"] is False
- assert "System Settings" in result.message
- assert "did not show a dialog" in result.message
- # The stranded-grant case is the one the message must not leave out: the
- # checkmark is already set in System Settings, so only a reset helps.
- assert "Ask again" in result.message
-
-
-def test_request_reporting_true_keeps_the_plain_restart_message() -> None:
- modules, _, _ = _native_modules()
-
- result = _port(modules).request(PermissionId.SCREEN_RECORDING)
-
- assert result.ok is True
- assert "If no system dialog appeared" not in result.message
-
-
-def test_restart_requirement_persists_until_the_process_restarts() -> None:
- modules, _, _ = _native_modules()
- port = _port(modules)
-
- port.request(PermissionId.SCREEN_RECORDING)
- later = port.snapshot()
-
- assert later["restart_required"] is True
- assert _permission(later, PermissionId.SCREEN_RECORDING)["restart_required"] is True
+ assert denied is PermissionState.DENIED
+ assert restricted is PermissionState.RESTRICTED
def test_request_microphone_uses_avfoundation_callback_api() -> None:
@@ -388,11 +274,9 @@ def test_request_microphone_uses_avfoundation_callback_api() -> None:
_CaptureDevice.requests = 0
modules, _, _ = _native_modules()
- result = _port(modules).request(PermissionId.MICROPHONE)
+ outcome = _port(modules).request_native(PermissionId.MICROPHONE)
- assert result.ok is True
- assert result.performed is True
- assert result.restart_required is False
+ assert outcome == "dialog_shown"
assert _CaptureDevice.requests == 1
@@ -405,88 +289,79 @@ def test_request_accessibility_uses_prompt_option() -> None:
kAXTrustedCheckOptionPrompt="prompt",
)
- result = _port(modules).request(PermissionId.ACCESSIBILITY)
+ outcome = _port(modules).request_native(PermissionId.ACCESSIBILITY)
- assert result.ok is True
- assert result.performed is True
- assert result.restart_required is True
- assert result.snapshot["features"]["global_hotkeys"]["restart_required"] is True
- assert result.snapshot["features"]["global_hotkeys"]["ready"] is False
+ assert outcome == "dialog_shown"
assert calls == [{"prompt": True}]
- "permission_id,request_name",
- [
- (PermissionId.INPUT_MONITORING, "CGRequestListenEventAccess"),
- (PermissionId.EVENT_POSTING, "CGRequestPostEventAccess"),
- ],
-)
-def test_request_event_permissions_use_coregraphics(
- permission_id: PermissionId, request_name: str
-) -> None:
+def test_request_input_monitoring_uses_the_listen_request_and_never_a_tap() -> None:
modules, _, _ = _native_modules()
calls: list[str] = []
- setattr(modules["Quartz"], request_name, lambda: calls.append(request_name))
- # Untrusted Accessibility keeps event_posting requestable: a trusted AX
- # grant already implies event posting and would short-circuit to granted.
+ modules["Quartz"].CGRequestListenEventAccess = lambda: calls.append("listen") or False
+
+ outcome = _port(modules).request_native(PermissionId.INPUT_MONITORING)
+
+ assert outcome == "dialog_shown"
+ assert calls == ["listen"]
+
+
+def test_event_posting_is_asked_through_the_accessibility_prompt() -> None:
+ """Event posting is an alias of Accessibility for asking: one request, one prompt."""
+ modules, _, _ = _native_modules()
+ post_requests: list[str] = []
+ modules["Quartz"].CGRequestPostEventAccess = lambda: post_requests.append("post")
+ calls: list[dict[str, bool]] = []
modules["ApplicationServices"] = SimpleNamespace(
AXIsProcessTrusted=lambda: False,
- AXIsProcessTrustedWithOptions=lambda _options: False,
+ AXIsProcessTrustedWithOptions=lambda options: calls.append(options),
kAXTrustedCheckOptionPrompt="prompt",
)
- result = _port(modules).request(permission_id)
+ outcome = _port(modules).request_native(PermissionId.EVENT_POSTING)
- assert result.ok is True
- assert result.performed is True
- assert calls == [request_name]
+ assert outcome == "dialog_shown"
+ assert calls == [{"prompt": True}]
+ assert post_requests == []
_IOHID_POST = 0 # kIOHIDRequestTypePostEvent
_IOHID_LISTEN = 1 # kIOHIDRequestTypeListenEvent
-def test_input_monitoring_denied_hides_request_and_keeps_settings() -> None:
- # macOS never re-prompts once the TCC state is determined; a visible
- # "request" button would silently do nothing (the dead Allow button).
+def test_input_monitoring_denied_reads_denied() -> None:
+ # macOS never re-prompts once the TCC state is determined; the tri-state read
+ # is what tells "denied" from "never asked".
modules, _, _ = _native_modules()
- snapshot = _port(modules, iohid_check=lambda t: 1 if t == _IOHID_LISTEN else None).snapshot()
+ port = _port(modules, iohid_check=lambda t: 1 if t == _IOHID_LISTEN else None)
- item = _permission(snapshot, PermissionId.INPUT_MONITORING)
- assert item["status"] == "denied"
- assert item["can_request"] is False
- assert item["can_open_settings"] is True
+ assert port.state(PermissionId.INPUT_MONITORING) is PermissionState.DENIED
-def test_input_monitoring_not_determined_still_offers_the_prompt() -> None:
+def test_input_monitoring_not_determined_reads_not_determined() -> None:
modules, _, _ = _native_modules()
- snapshot = _port(modules, iohid_check=lambda t: 2 if t == _IOHID_LISTEN else None).snapshot()
+ port = _port(modules, iohid_check=lambda t: 2 if t == _IOHID_LISTEN else None)
- item = _permission(snapshot, PermissionId.INPUT_MONITORING)
- assert item["status"] == "not_determined"
- assert item["can_request"] is True
+ assert port.state(PermissionId.INPUT_MONITORING) is PermissionState.NOT_DETERMINED
def test_input_monitoring_falls_back_to_boolean_preflight_without_iohid() -> None:
modules, _, _ = _native_modules()
- item = _permission(_port(modules).snapshot(), PermissionId.INPUT_MONITORING)
-
- assert item["status"] == "not_granted"
+ assert _port(modules).state(PermissionId.INPUT_MONITORING) is PermissionState.NOT_GRANTED
def test_event_posting_follows_live_accessibility_grant() -> None:
# The Accessibility grant authorizes event posting and updates live; it
- # must win over a stale per-process HID verdict so the row flips as soon
+ # must win over a stale per-process HID verdict so the state flips as soon
# as the user grants Accessibility.
modules, _, _ = _native_modules()
- snapshot = _port(modules, iohid_check=lambda _t: 1).snapshot()
+ port = _port(modules, iohid_check=lambda _t: 1)
- assert _permission(snapshot, PermissionId.EVENT_POSTING)["status"] == "granted"
+ assert port.state(PermissionId.EVENT_POSTING) is PermissionState.GRANTED
def test_event_posting_tristate_when_accessibility_untrusted() -> None:
@@ -497,69 +372,62 @@ def test_event_posting_tristate_when_accessibility_untrusted() -> None:
kAXTrustedCheckOptionPrompt="prompt",
)
- snapshot = _port(modules, iohid_check=lambda t: 1 if t == _IOHID_POST else None).snapshot()
+ port = _port(modules, iohid_check=lambda t: 1 if t == _IOHID_POST else None)
- item = _permission(snapshot, PermissionId.EVENT_POSTING)
- assert item["status"] == "denied"
- assert item["can_request"] is False
- assert item["can_open_settings"] is True
+ assert port.state(PermissionId.EVENT_POSTING) is PermissionState.DENIED
-def test_legacy_macos_event_posting_falls_back_to_accessibility_prompt() -> None:
+def test_event_posting_without_the_post_event_api_follows_accessibility() -> None:
modules, _, _ = _native_modules()
delattr(modules["Quartz"], "CGPreflightPostEventAccess")
delattr(modules["Quartz"], "CGRequestPostEventAccess")
- calls: list[dict[str, bool]] = []
modules["ApplicationServices"] = SimpleNamespace(
AXIsProcessTrusted=lambda: False,
- AXIsProcessTrustedWithOptions=lambda options: calls.append(options),
+ AXIsProcessTrustedWithOptions=lambda _options: False,
kAXTrustedCheckOptionPrompt="prompt",
)
- result = _port(modules).request(PermissionId.EVENT_POSTING)
+ assert _port(modules).state(PermissionId.EVENT_POSTING) is PermissionState.NOT_GRANTED
- assert result.ok is True
- assert result.performed is True
- assert calls == [{"prompt": True}]
+def test_open_pane_uses_permission_specific_launchservices_url() -> None:
+ modules, _, workspace = _native_modules()
+
+ assert _port(modules).open_pane(PermissionId.INPUT_MONITORING) is True
+ assert workspace.opened_urls == [
+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent"
+ ]
-def test_request_refuses_unstable_or_background_identity() -> None:
- modules, screen, _ = _native_modules(bundle_id="org.python.python")
- unstable = _port(modules).request(PermissionId.SCREEN_RECORDING)
- modules, _, _ = _native_modules(active=False)
- background = _port(modules).request(PermissionId.SCREEN_RECORDING)
- assert unstable.ok is False
- assert "Terminal or Python" in unstable.message
- assert background.ok is False
- assert "foreground" in background.message
- assert screen["requested"] is False
+def test_open_pane_takes_a_plain_string_and_ignores_an_unknown_id() -> None:
+ modules, _, workspace = _native_modules()
+ port = _port(modules)
+ assert port.open_pane("microphone") is True
+ assert port.open_pane("not_a_permission") is False
+ assert len(workspace.opened_urls) == 1
-def test_dry_run_never_invokes_native_request() -> None:
- modules, screen, _ = _native_modules()
- result = _port(modules).request(PermissionId.SCREEN_RECORDING, dry_run=True)
+def test_open_pane_needs_a_desktop_session() -> None:
+ modules, _, workspace = _native_modules()
+ workspace.current = None # frontmostApplication() is None: no window server answers
- assert result.ok is True
- assert result.dry_run is True
- assert result.performed is False
- assert screen["requested"] is False
+ assert _port(modules).open_pane(PermissionId.MICROPHONE) is False
+ assert workspace.opened_urls == []
-def test_open_settings_uses_permission_specific_launchservices_url() -> None:
+def test_open_pane_never_raises_when_launchservices_does() -> None:
modules, _, workspace = _native_modules()
- result = _port(modules).open_settings(PermissionId.INPUT_MONITORING)
+ def refuse(_url: str) -> bool:
+ raise RuntimeError("LaunchServices is gone")
- assert result.ok is True
- assert result.performed is True
- assert workspace.opened_urls == [
- "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent"
- ]
+ workspace.openURL_ = refuse
+
+ assert _port(modules).open_pane(PermissionId.MICROPHONE) is False
-def test_open_settings_quits_running_system_settings_before_navigating() -> None:
+def test_open_pane_quits_running_system_settings_before_navigating() -> None:
# System Settings ignores the pane anchor while already running: the URL
# only raises the stale window (live on macOS 15.7 the Input Monitoring
# link surfaced the last-open Files & Folders pane). The port must quit a
@@ -596,117 +464,32 @@ def test_open_settings_quits_running_system_settings_before_navigating() -> None
workspace.openURL_ = open_url
- result = _port(modules).open_settings(PermissionId.INPUT_MONITORING)
-
- assert result.ok is True
+ assert _port(modules).open_pane(PermissionId.INPUT_MONITORING) is True
assert lookups == ["com.apple.systempreferences"]
assert order == ["terminate", "open"]
-def test_screen_capture_restart_pending_hides_the_dead_allow_button() -> None:
- # CGPreflightScreenCaptureAccess stays frozen for the process lifetime, and
- # macOS never re-prompts after the first request — a second visible Allow
- # button could only ever do nothing (live Mac finding 2026-07-18).
- modules, screen, _ = _native_modules()
- port = _port(modules)
-
- port.request(PermissionId.SCREEN_RECORDING)
- # Mimic the real frozen preflight: the grant is invisible until relaunch.
- screen["granted"] = False
- item = _permission(port.snapshot(), PermissionId.SCREEN_RECORDING)
-
- assert item["status"] == "not_granted"
- assert item["restart_required"] is True
- assert item["can_request"] is False
- assert "restart" in (item["detail"] or "").lower()
- # And it must not offer the reset either: the frozen preflight cannot tell
- # a missing grant from the one the user just gave, so a reset here would
- # throw that fresh grant away.
- assert item["can_reset"] is False
-
-
-def test_a_stranded_grant_offers_the_reset_although_it_never_reads_denied() -> None:
- """BUG-159: the escape hatch must not hang off ``status == "denied"``.
-
- An ad-hoc signature change orphans the recorded TCC rows. System Settings
- keeps showing the checkmark while the boolean preflights report plain
- "not granted" — never "denied" — so a denial-keyed reset button was
- invisible on exactly the two rows that needed it.
- """
- modules, screen, _ = _native_modules()
- screen["granted"] = False
- modules["ApplicationServices"].AXIsProcessTrusted = lambda: False
- snapshot = _port(modules).snapshot()
-
- for permission_id in (PermissionId.SCREEN_RECORDING, PermissionId.ACCESSIBILITY):
- item = _permission(snapshot, permission_id)
- assert item["status"] == "not_granted", permission_id
- assert item["can_reset"] is True, permission_id
-
+def test_keychain_has_no_reset_because_it_owns_no_tcc_row(monkeypatch: pytest.MonkeyPatch) -> None:
+ import subprocess
-def test_a_granted_permission_never_offers_the_reset() -> None:
- modules, screen, _ = _native_modules()
- screen["granted"] = True
- snapshot = _port(modules, iohid_check=lambda _type: 0).snapshot()
-
- for item in snapshot["permissions"]:
- if item["status"] in {"granted", "not_required"}:
- assert item["can_reset"] is False, item["id"]
-
-
-def test_keychain_has_no_reset_because_it_owns_no_tcc_row() -> None:
- modules, _, _ = _native_modules()
- port = _port(modules, credential_backend=lambda: "file")
-
- item = _permission(port.snapshot(), PermissionId.CREDENTIAL_STORE)
-
- assert item["status"] == "not_granted"
- assert item["can_reset"] is False
-
-
-def test_a_signature_reset_is_explained_and_retired_once_grants_return(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """BUG-159: an app that silently forgot every permission reads as broken."""
- from jarvis.platform import permissions as permissions_module
-
- monkeypatch.setattr(permissions_module, "user_data_dir", lambda: tmp_path, raising=False)
monkeypatch.setattr(
- permissions_module,
- "identity_reset_marker_path",
- lambda: tmp_path / "macos-tcc-reset.json",
+ subprocess, "run", lambda *_a, **_k: pytest.fail("the Keychain has no tccutil row")
)
- permissions_module.record_identity_reset(("ScreenCapture", "Accessibility"))
-
- # _CaptureDevice.status is class state other tests leave behind; the
- # marker only retires when EVERY TCC row is back, microphone included.
- _CaptureDevice.status = 3
- modules, screen, _ = _native_modules()
- screen["granted"] = False
- modules["ApplicationServices"].AXIsProcessTrusted = lambda: False
- port = _port(modules)
-
- stranded = port.snapshot()
- assert stranded["identity_reset"] is not None
- assert stranded["identity_reset"]["reason"] == "signature-change"
+ modules, _, _ = _native_modules()
+ port = _port(modules, credential_backend=lambda: "file")
- # Everything granted again: the explanation has done its job and goes away.
- screen["granted"] = True
- modules["ApplicationServices"].AXIsProcessTrusted = lambda: True
- healed = _port(modules, iohid_check=lambda _type: 0).snapshot()
+ assert port.state(PermissionId.CREDENTIAL_STORE) is PermissionState.NOT_GRANTED
+ operation = port.reset_row(PermissionId.CREDENTIAL_STORE)
- assert healed["identity_reset"] is None
- assert not (tmp_path / "macos-tcc-reset.json").exists()
+ assert operation.ok is False
+ assert "no resettable macOS record" in operation.message
def test_missing_framework_reports_unavailable_without_raising() -> None:
modules, _, _ = _native_modules()
del modules["Quartz"]
- snapshot = _port(modules).snapshot()
-
- assert _permission(snapshot, PermissionId.SCREEN_RECORDING)["status"] == ("unavailable")
- assert snapshot["features"]["computer_use"]["ready"] is False
+ assert _port(modules).state(PermissionId.SCREEN_RECORDING) is PermissionState.UNAVAILABLE
def test_broken_native_bridge_import_fails_closed() -> None:
@@ -723,36 +506,28 @@ def test_broken_native_bridge_import_fails_closed() -> None:
credential_store_backend=broken_credential_probe,
)
- snapshot = port.snapshot()
-
- assert snapshot["app_identity"]["stable"] is False
- assert {item["status"] for item in snapshot["permissions"]} == {"unavailable"}
- assert all(not feature["ready"] for feature in snapshot["features"].values())
+ assert _identity(port).stable is False
+ assert port.outside_installed_app is True
+ assert {port.state(permission_id) for permission_id in PermissionId} == {
+ PermissionState.UNAVAILABLE
+ }
def test_credential_store_reports_granted_while_platform_keyring_serves() -> None:
modules, _, _ = _native_modules()
+ port = _port(modules)
- item = _permission(_port(modules).snapshot(), PermissionId.CREDENTIAL_STORE)
-
- assert item["status"] == "granted"
- assert item["can_open_settings"] is False
+ assert port.state(PermissionId.CREDENTIAL_STORE) is PermissionState.GRANTED
+ assert port.open_pane(PermissionId.CREDENTIAL_STORE) is False
-def test_credential_store_file_fallback_is_not_granted_and_requestable() -> None:
+def test_credential_store_file_fallback_is_not_granted() -> None:
# A declined macOS Keychain prompt degrades config to the 0600 file
- # fallback; the row must surface that honestly and keep the retry alive.
+ # fallback; the state must surface that honestly.
modules, _, _ = _native_modules()
port = _port(modules, credential_backend=lambda: "file")
- snapshot = port.snapshot()
- item = _permission(snapshot, PermissionId.CREDENTIAL_STORE)
-
- assert item["status"] == "not_granted"
- assert item["can_request"] is True
- assert item["can_open_settings"] is False
- assert "Keychain" in (item["detail"] or "")
- assert snapshot["features"]["api_keys"]["ready"] is False
+ assert port.state(PermissionId.CREDENTIAL_STORE) is PermissionState.NOT_GRANTED
def test_credential_store_request_replays_recovery_and_reports_live_state() -> None:
@@ -770,14 +545,11 @@ def test_credential_store_request_replays_recovery_and_reports_live_state() -> N
credential_recover=recover,
)
- result = port.request(PermissionId.CREDENTIAL_STORE)
+ outcome = port.request_native(PermissionId.CREDENTIAL_STORE)
- assert result.ok is True
- assert result.performed is True
- assert result.restart_required is False
+ assert outcome == "no_dialog"
assert state["recover_calls"] == 1
- assert _permission(result.snapshot, PermissionId.CREDENTIAL_STORE)["status"] == "granted"
- assert result.snapshot["restart_required"] is False
+ assert port.state(PermissionId.CREDENTIAL_STORE) is PermissionState.GRANTED
def test_credential_store_declined_again_stays_not_granted() -> None:
@@ -788,23 +560,17 @@ def test_credential_store_declined_again_stays_not_granted() -> None:
credential_recover=lambda: False,
)
- result = port.request(PermissionId.CREDENTIAL_STORE)
+ port.request_native(PermissionId.CREDENTIAL_STORE)
- assert result.ok is True
- assert result.performed is True
- assert _permission(result.snapshot, PermissionId.CREDENTIAL_STORE)["status"] == "not_granted"
+ assert port.state(PermissionId.CREDENTIAL_STORE) is PermissionState.NOT_GRANTED
-def test_credential_store_open_settings_refuses_honestly() -> None:
- # There is no System Settings pane for the Keychain; a silent no-op button
- # would look like the app is broken.
+def test_credential_store_open_pane_refuses_honestly() -> None:
+ # There is no System Settings pane for the Keychain: nothing is opened.
modules, _, workspace = _native_modules()
port = _port(modules, credential_backend=lambda: "file")
- result = port.open_settings(PermissionId.CREDENTIAL_STORE)
-
- assert result.ok is False
- assert "System Settings pane" in result.message
+ assert port.open_pane(PermissionId.CREDENTIAL_STORE) is False
assert workspace.opened_urls == []
@@ -814,13 +580,9 @@ def test_credential_store_probe_failure_reports_unavailable() -> None:
def broken_probe() -> str:
raise RuntimeError("probe failed")
- item = _permission(
- _port(modules, credential_backend=broken_probe).snapshot(),
- PermissionId.CREDENTIAL_STORE,
- )
+ port = _port(modules, credential_backend=broken_probe)
- assert item["status"] == "unavailable"
- assert item["can_request"] is False
+ assert port.state(PermissionId.CREDENTIAL_STORE) is PermissionState.UNAVAILABLE
# --- BUG-161: the app insisted permissions were missing after they were given
@@ -830,9 +592,8 @@ def test_the_app_in_the_shared_applications_folder_is_a_stable_identity() -> Non
"""Dragging the app to /Applications is normal, not a tampering signal.
The old rule accepted only ~/Applications, so the ordinary move turned the
- installed app into an "unstable identity": every request button vanished,
- every feature reported not-ready, and the banner kept demanding grants the
- user had already given, with nothing left to click (BUG-161).
+ installed app into an "unstable identity": the own-bundle reset was refused
+ and the app was read as a foreign one (BUG-161).
"""
modules, _, _ = _native_modules()
shared_copy = SimpleNamespace(
@@ -840,12 +601,169 @@ def test_the_app_in_the_shared_applications_folder_is_a_stable_identity() -> Non
bundlePath=lambda: "/Applications/Personal Jarvis.app",
)
modules["Foundation"].NSBundle = SimpleNamespace(mainBundle=lambda: shared_copy)
+ port = _port(modules)
+
+ assert _identity(port).stable is True
+ assert port.outside_installed_app is False
- snapshot = _port(modules).snapshot()
- assert snapshot["app_identity"]["stable"] is True
- assert _permission(snapshot, PermissionId.MICROPHONE)["can_request"] is False
- assert snapshot["features"]["voice"]["identity_ready"] is True
+# --- The downloaded .dmg app is an installed app too (its own bundle id)
+
+
+def _installed_as(modules: dict[str, object], bundle_id: str, path: str) -> None:
+ """Make ``NSBundle.mainBundle()`` answer as ``bundle_id`` installed at ``path``."""
+ running = SimpleNamespace(bundleIdentifier=lambda: bundle_id, bundlePath=lambda: path)
+ modules["Foundation"].NSBundle = SimpleNamespace(mainBundle=lambda: running)
+
+
+def test_the_downloaded_dmg_app_is_a_stable_identity() -> None:
+ """The release .dmg is a PyInstaller bundle with its own bundle id.
+
+ The identity check once accepted only the managed bundle's id, so the .dmg app
+ read as a foreign app: it could neither reset its own rows nor ask on its own.
+ """
+ from jarvis.core.branding import MACOS_DMG_BUNDLE_ID
+
+ _CaptureDevice.status = 3
+ modules, _, _ = _native_modules()
+ _installed_as(modules, MACOS_DMG_BUNDLE_ID, "/Applications/Personal Jarvis.app")
+ port = _port(modules, iohid_check=lambda _type: 0)
+
+ identity = _identity(port)
+
+ assert identity.stable is True
+ assert identity.bundle_id == MACOS_DMG_BUNDLE_ID
+ assert port.outside_installed_app is False
+ assert port.state(PermissionId.MICROPHONE) is PermissionState.GRANTED
+
+
+ "bundle_id", ["org.python.python", "com.apple.Terminal", "ai.personaljarvis.desktop.evil", None]
+)
+def test_an_app_that_is_not_ours_is_never_a_stable_identity(bundle_id: str | None) -> None:
+ """Widening the check to the .dmg id must not turn it into "any app"."""
+ modules, _, _ = _native_modules()
+ _installed_as(modules, bundle_id, "/Applications/Personal Jarvis.app") # type: ignore[arg-type]
+ port = _port(modules)
+
+ assert _identity(port).stable is False
+ assert port.outside_installed_app is True
+
+
+ "running_id",
+ [EXPECTED_BUNDLE_ID, "ai.personaljarvis.desktop"],
+)
+def test_reset_drops_the_rows_of_the_app_that_is_running(
+ monkeypatch: pytest.MonkeyPatch, running_id: str
+) -> None:
+ """``tccutil reset`` is scoped to one bundle id, so it must be the right one.
+
+ Resetting the managed id for the .dmg app would leave the .dmg app's own
+ rows untouched, leaving a stranded grant stranded.
+ """
+ import subprocess
+
+ modules, _, _ = _native_modules()
+ _installed_as(modules, running_id, "/Applications/Personal Jarvis.app")
+ commands: list[list[str]] = []
+
+ def fake_run(command, **_kwargs):
+ commands.append(list(command))
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+
+ operation = _port(modules).reset_row(PermissionId.SCREEN_RECORDING)
+
+ assert operation.ok is True
+ assert operation.performed is True
+ assert commands == [["/usr/bin/tccutil", "reset", "ScreenCapture", running_id]]
+
+
[email protected]("running_id", ["org.python.python", "com.apple.Terminal", None])
+def test_a_process_that_is_not_the_installed_app_cannot_reset_anything(
+ monkeypatch: pytest.MonkeyPatch, running_id: str | None
+) -> None:
+ """A development run must not be able to wipe the installed app's grants."""
+ import subprocess
+
+ modules, _, _ = _native_modules()
+ _installed_as(modules, running_id, "/Applications/Personal Jarvis.app") # type: ignore[arg-type]
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda *_a, **_k: pytest.fail("tccutil must not run for an unstable identity"),
+ )
+
+ operation = _port(modules).reset_row(PermissionId.SCREEN_RECORDING)
+
+ assert operation.ok is False
+ assert operation.performed is False
+ assert "installed app" in operation.message
+
+
+def test_a_dry_run_reset_changes_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ import subprocess
+
+ monkeypatch.setattr(
+ subprocess, "run", lambda *_a, **_k: pytest.fail("a dry run must not run tccutil")
+ )
+ modules, _, _ = _native_modules()
+
+ operation = _port(modules).reset_row(PermissionId.MICROPHONE, dry_run=True)
+
+ assert operation.ok is True
+ assert operation.dry_run is True
+ assert operation.performed is False
+ assert "Would reset" in operation.message
+
+
+ "failure",
+ [
+ SimpleNamespace(returncode=1, stdout="", stderr="tccutil: no such service /usr/bin/x"),
+ OSError(2, "No such file or directory: '/usr/bin/tccutil'"),
+ ],
+)
+def test_a_failed_reset_says_why_and_performs_nothing(
+ monkeypatch: pytest.MonkeyPatch, failure: object
+) -> None:
+ import subprocess
+
+ def fake_run(*_args, **_kwargs):
+ if isinstance(failure, Exception):
+ raise failure
+ return failure
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ modules, _, _ = _native_modules()
+
+ operation = _port(modules).reset_row(PermissionId.MICROPHONE)
+
+ assert operation.ok is False
+ assert operation.performed is False
+ assert operation.message == "Could not reset the Microphone record."
+ assert "/usr/bin" not in operation.message
+ assert "tccutil" not in operation.message
+
+
+def test_state_is_the_preflight_alone_unless_a_deep_read_is_asked_for() -> None:
+ """The default read never enumerates windows; only ``deep=True`` runs the oracle."""
+ modules, screen, _ = _native_modules()
+ screen["granted"] = False
+ oracle_calls: list[int] = []
+
+ def oracle() -> bool:
+ oracle_calls.append(1)
+ return True
+
+ port = _port(modules, screen_capture_live=oracle)
+
+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
+ assert oracle_calls == []
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.GRANTED
+ assert oracle_calls == [1]
def test_a_live_window_probe_beats_the_frozen_screen_recording_preflight() -> None:
@@ -861,9 +779,8 @@ def test_a_live_window_probe_beats_the_frozen_screen_recording_preflight() -> No
stale = _port(modules, screen_capture_live=lambda: None)
healed = _port(modules, screen_capture_live=lambda: True)
- assert stale.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
- assert healed.state(PermissionId.SCREEN_RECORDING) is PermissionState.GRANTED
- assert healed.runtime_access_granted(PermissionId.SCREEN_RECORDING) is True
+ assert stale.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.NOT_GRANTED
+ assert healed.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.GRANTED
def test_a_live_window_probe_never_invents_a_grant_the_preflight_denies() -> None:
@@ -873,7 +790,7 @@ def test_a_live_window_probe_never_invents_a_grant_the_preflight_denies() -> Non
port = _port(modules, screen_capture_live=lambda: False)
- assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.NOT_GRANTED
def test_a_crashing_live_probe_leaves_the_preflight_verdict_intact() -> None:
@@ -884,7 +801,7 @@ def test_a_crashing_live_probe_leaves_the_preflight_verdict_intact() -> None:
screen["granted"] = False
assert (
- _port(modules, screen_capture_live=_explode).state(PermissionId.SCREEN_RECORDING)
+ _port(modules, screen_capture_live=_explode).state(PermissionId.SCREEN_RECORDING, deep=True)
is PermissionState.NOT_GRANTED
)
@@ -904,24 +821,6 @@ def test_window_titles_prove_the_grant_only_from_another_apps_own_layer() -> Non
assert _window_titles_are_visible(foreign, 42) is True
-def test_open_settings_works_while_the_app_sits_in_the_background() -> None:
- """The Settings deep link is not a prompt, so it needs no foreground.
-
- Refusing it in the background left every non-foreground surface (the app
- behind System Settings, the browser view) with a permission banner whose
- only control answered "bring the app to the front" (BUG-161).
- """
- modules, _, workspace = _native_modules(active=False)
-
- snapshot = _port(modules).snapshot()
- operation = _port(modules).open_settings(PermissionId.MICROPHONE)
-
- assert snapshot["app_identity"]["foreground"] is False
- assert _permission(snapshot, PermissionId.MICROPHONE)["can_open_settings"] is True
- assert operation.ok is True
- assert workspace.opened_urls
-
-
# --- Automation (Apple Events): the Music/Spotify consent row
@@ -930,77 +829,40 @@ _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
+ """An ``NSRunningApplication`` stand-in for one running scriptable player."""
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[str],
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"))
+ return [_Player()] if bundle_id in running else []
- workspace.openApplicationAtURL_configuration_completionHandler_ = open_app # type: ignore[attr-defined]
+ # Tripwire: the port never launches a player; a call would land in this log.
+ launches: list[str] = []
+ workspace.openApplicationAtURL_configuration_completionHandler_ = ( # type: ignore[attr-defined]
+ lambda url, _configuration, _handler: launches.append(url)
+ )
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:
@@ -1010,86 +872,62 @@ def _automation_fixture(
return modules, launches, probes, probe
-def _consent_file(tmp_path: Path) -> dict:
- import json
+def test_the_default_automation_probe_never_forwards_an_asking_flag() -> None:
+ """The in-process Apple Event probe is a silent read: only the killable runner asks."""
+ import inspect
- path = tmp_path / "consent.json"
- return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else {}
+ import jarvis.platform.permissions as permissions
+ source = inspect.getsource(permissions._default_automation_probe)
-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
+ assert "if ask" not in source
+ assert "_AE_TYPE_WILDCARD, 0))" in source
-def test_automation_reads_a_running_player_live_and_records_the_answer(tmp_path: Path, monkeypatch):
+def test_automation_is_not_required_without_a_scriptable_player() -> None:
modules, _launches, probes, probe = _automation_fixture(
- tmp_path, monkeypatch, installed={_MUSIC}, running={_MUSIC}, answers={_MUSIC: 0}
+ installed=set(), running=set(), answers={}
)
- snapshot = _port(modules, automation_probe=probe).snapshot()
+ port = _port(modules, automation_probe=probe)
- 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"}
+ assert port.state(PermissionId.AUTOMATION) is PermissionState.NOT_REQUIRED
+ assert port.state(PermissionId.AUTOMATION, target=_MUSIC) is PermissionState.NOT_REQUIRED
+ assert probes == []
-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}
+def test_automation_reads_a_running_player_live_without_ever_asking() -> None:
+ modules, _launches, probes, probe = _automation_fixture(
+ installed={_MUSIC}, running={_MUSIC}, 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)
+ state = _port(modules, automation_probe=probe).state(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)
+ assert state is PermissionState.GRANTED
+ assert probes == [(_MUSIC, False)] # a status probe never raises the dialog
-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}
+def test_a_closed_player_reads_unknown_and_is_never_launched() -> None:
+ """Apple answers only for a running target: a closed player is unknown, not "denied"."""
+ modules, launches, probes, probe = _automation_fixture(
+ installed={_MUSIC}, running=set(), answers={_MUSIC: 0}
)
port = _port(modules, automation_probe=probe)
- port.request(PermissionId.AUTOMATION)
-
+ assert port.state(PermissionId.AUTOMATION) is PermissionState.NOT_DETERMINED
+ assert port.state(PermissionId.AUTOMATION, target=_MUSIC) is PermissionState.NOT_DETERMINED
assert launches == []
- assert port._running_automation_targets(modules["AppKit"], _MUSIC)
+ assert probes == []
-def test_automation_denial_offers_the_reset_and_the_reset_forgets_the_answer(
- tmp_path: Path, monkeypatch
-):
+def test_automation_denial_reads_denied_and_the_reset_is_scoped_to_the_own_bundle(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
modules, _launches, _probes, probe = _automation_fixture(
- tmp_path, monkeypatch, installed={_MUSIC}, running={_MUSIC}, answers={_MUSIC: -1743}
+ 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"}
+ assert port.state(PermissionId.AUTOMATION) is PermissionState.DENIED
commands: list[list[str]] = []
@@ -1098,48 +936,81 @@ def test_automation_denial_offers_the_reset_and_the_reset_forgets_the_answer(
return SimpleNamespace(returncode=0, stdout="", stderr="")
monkeypatch.setattr("subprocess.run", fake_run)
- result = port.reset(PermissionId.AUTOMATION)
+ operation = port.reset_row(PermissionId.AUTOMATION)
- assert result.ok and result.performed
+ assert operation.ok and operation.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):
+def test_automation_strictest_player_wins() -> None:
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()
+ # Music is not running (unknown) and Spotify has not been asked yet.
assert (
- _permission(snapshot, PermissionId.AUTOMATION)["status"] == PermissionState.NOT_DETERMINED
+ _port(modules, automation_probe=probe).state(PermissionId.AUTOMATION)
+ is 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
+ both_modules, _l, _p, both_probe = _automation_fixture(
+ installed={_MUSIC, _SPOTIFY},
+ running={_MUSIC, _SPOTIFY},
+ answers={_MUSIC: 0, _SPOTIFY: -1743},
+ )
+ assert (
+ _port(both_modules, automation_probe=both_probe).state(PermissionId.AUTOMATION)
+ is PermissionState.DENIED
+ )
- monkeypatch.setattr(
- permissions_module, "identity_reset_marker_path", lambda: tmp_path / "reset.json"
+ granted_modules, _l, _p, granted_probe = _automation_fixture(
+ installed={_MUSIC, _SPOTIFY},
+ running={_MUSIC, _SPOTIFY},
+ answers={_MUSIC: 0, _SPOTIFY: 0},
)
- monkeypatch.setattr(
- permissions_module, "automation_consent_path", lambda: tmp_path / "consent.json"
+ assert (
+ _port(granted_modules, automation_probe=granted_probe).state(PermissionId.AUTOMATION)
+ is PermissionState.GRANTED
)
- (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()
+# --- Leftover state files of the earlier permission wall
+
+
+def test_the_leftover_state_files_are_removed_and_nothing_else(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.platform import permissions as permissions_module
+
+ for name in ("macos-tcc-reset.json", "macos-automation-consent.json", "keep.json"):
+ (tmp_path / name).write_text("{}", encoding="utf-8")
+ monkeypatch.setattr(permissions_module, "_leftover_state_dir", lambda: tmp_path)
+
+ permissions_module.remove_leftover_state_files()
+ permissions_module.remove_leftover_state_files() # a second run finds nothing: no error
+
+ assert sorted(path.name for path in tmp_path.iterdir()) == ["keep.json"]
+
+
+def test_the_leftover_cleanup_never_raises(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ import logging
+
+ from jarvis.platform import permissions as permissions_module
+
+ # A directory with the file's name makes unlink fail with an OSError.
+ (tmp_path / "macos-tcc-reset.json").mkdir()
+ monkeypatch.setattr(permissions_module, "_leftover_state_dir", lambda: tmp_path)
+ with caplog.at_level(logging.DEBUG, logger=permissions_module.log.name):
+ permissions_module.remove_leftover_state_files()
+
+ def locate_fails() -> Path:
+ raise RuntimeError("no data directory")
+
+ monkeypatch.setattr(permissions_module, "_leftover_state_dir", locate_fails)
+ permissions_module.remove_leftover_state_files()
+
+ assert "Could not remove the leftover macos-tcc-reset.json." in caplog.text
diff --git a/tests/unit/platform/test_permissions_state_api.py b/tests/unit/platform/test_permissions_state_api.py
new file mode 100644
index 0000000000..e49f406889
--- /dev/null
+++ b/tests/unit/platform/test_permissions_state_api.py
@@ -0,0 +1,1126 @@
+"""Unit coverage for the additive just-in-time API of the permission port.
+
+``state(..., target=, deep=)``, ``request_native``, ``usage_string_present``,
+``outside_installed_app`` and the request-class / pane-family / settings-path
+metadata. Every native framework is a hand-written stub; nothing here talks to
+a real Mac, and every behaviour that Apple does not document stays labelled
+unverified in the port.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import subprocess
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.core.branding import MACOS_DMG_BUNDLE_ID
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.platform import permissions as permissions_module
+from jarvis.platform.permissions import (
+ ACCEPTED_BUNDLE_IDS,
+ AUTOMATION_TARGETS,
+ EXPECTED_BUNDLE_ID,
+ PANE_FAMILY,
+ REQUEST_CLASS,
+ SETTINGS_PATH_TEXT,
+ PermissionId,
+ PermissionState,
+ RequestClass,
+ SystemPermissionPort,
+ settings_path_text,
+)
+
+_MUSIC = "com.apple.Music"
+_SPOTIFY = "com.spotify.client"
+_INSTALLED_PATH = str(Path.home() / "Applications" / "Personal Jarvis.app")
+
+# kIOHIDRequestTypeListenEvent / kIOHIDAccessType* raw values (stable ABI).
+_IOHID_LISTEN = 1
+_IOHID_DENIED = 1
+_IOHID_UNKNOWN = 2
+
+_ALL_INFO = {
+ "NSMicrophoneUsageDescription": "Personal Jarvis uses the microphone.",
+ "NSAppleEventsUsageDescription": "Personal Jarvis sends commands to other apps.",
+}
+
+
+class _Bundle:
+ """``NSBundle.mainBundle()`` stand-in with a readable Info.plist."""
+
+ def __init__(
+ self,
+ bundle_id: str | None,
+ path: str,
+ info: dict[str, str] | None,
+ info_error: Exception | None = None,
+ ) -> None:
+ self._bundle_id = bundle_id
+ self._path = path
+ self._info = info or {}
+ self._info_error = info_error
+ self.info_reads: list[str] = []
+
+ def bundleIdentifier(self) -> str | None:
+ return self._bundle_id
+
+ def bundlePath(self) -> str:
+ return self._path
+
+ def objectForInfoDictionaryKey_(self, key: str) -> str | None:
+ self.info_reads.append(key)
+ if self._info_error is not None:
+ raise self._info_error
+ return self._info.get(key)
+
+
+class _CaptureDevice:
+ """``AVCaptureDevice`` stand-in reading and recording on its world."""
+
+ def __init__(self, world: _World) -> None:
+ self._world = world
+
+ def authorizationStatusForMediaType_(self, _media_type: str) -> int:
+ return self._world.mic_status
+
+ def requestAccessForMediaType_completionHandler_(self, media_type: str, handler: Any) -> None:
+ self._world.boom()
+ self._world.requests.append("microphone")
+ self._world.mic_media_types.append(media_type)
+ handler(True)
+
+
+class _Player:
+ def __init__(self, bundle_id: str) -> None:
+ self.bundle_id = bundle_id
+
+
+class _Workspace:
+ def __init__(self, world: _World) -> None:
+ self._world = world
+
+ def URLForApplicationWithBundleIdentifier_(self, bundle_id: str) -> str | None:
+ if bundle_id in self._world.installed:
+ return f"file:///Applications/{bundle_id}.app"
+ return None
+
+ def openApplicationAtURL_configuration_completionHandler_(self, url: str, *_rest: Any) -> None:
+ self._world.launches.append(url)
+
+ def frontmostApplication(self) -> SimpleNamespace:
+ return SimpleNamespace(processIdentifier=lambda: 123)
+
+
+class _World:
+ """One simulated Mac: native stubs, their answers and an ordered request log."""
+
+ def __init__(
+ self,
+ *,
+ bundle_id: str | None = EXPECTED_BUNDLE_ID,
+ bundle_path: str = _INSTALLED_PATH,
+ info: dict[str, str] | None = None,
+ info_error: Exception | None = None,
+ ) -> None:
+ self.bundle = _Bundle(
+ bundle_id, bundle_path, dict(_ALL_INFO) if info is None else info, info_error
+ )
+ self.imports: list[str] = []
+ # Every native call that could make macOS ask, in order. A state read
+ # must leave this empty.
+ self.requests: list[str] = []
+ self.event_taps = 0
+ self.launches: list[str] = []
+ self.mic_media_types: list[str] = []
+ self.explode = False # every native request raises
+ self.mic_status = 0 # not determined
+ self.screen_preflight = False
+ self.screen_request_answer = False
+ self.ax_trusted = False
+ self.ax_request_answer = False
+ self.ax_options: list[dict[str, bool]] = []
+ self.listen_request_answer = False
+ self.post_request_answer = False
+ self.iohid_state: dict[int, int | None] = {}
+ self.iohid_request_answer: bool | None = None
+ self.installed: set[str] = set()
+ self.running: set[str] = set()
+ self.probe_answers: dict[str, Any] = {}
+ self.probes: list[tuple[str, bool]] = []
+ self.live_check_answer: bool | None = None
+ self.live_checks = 0
+ self.consent_scripts: list[str] = []
+ self.consent_result: Any = SimpleNamespace(returncode=0, stdout="-\n", stderr="")
+ self.recover_calls = 0
+ self.modules = self._build_modules()
+
+ # ---- stubs -----------------------------------------------------------
+ def boom(self) -> None:
+ if self.explode:
+ raise RuntimeError("native call exploded")
+
+ def _build_modules(self) -> dict[str, object]:
+ workspace = _Workspace(self)
+ current = SimpleNamespace(isActive=lambda: True, processIdentifier=lambda: 123)
+
+ def running(bundle_id: str) -> list[_Player]:
+ return [_Player(bundle_id)] if bundle_id in self.running else []
+
+ def request_screen() -> bool:
+ self.boom()
+ self.requests.append("screen_recording")
+ return self.screen_request_answer
+
+ def request_listen() -> bool:
+ self.boom()
+ self.requests.append("listen")
+ return self.listen_request_answer
+
+ def request_post() -> bool:
+ self.boom()
+ self.requests.append("post")
+ return self.post_request_answer
+
+ def request_ax(options: dict[str, bool]) -> bool:
+ if options.get("prompt"):
+ self.boom()
+ self.requests.append("accessibility")
+ self.ax_options.append(dict(options))
+ return self.ax_request_answer
+ return self.ax_trusted
+
+ def event_tap(*_args: Any) -> None:
+ self.event_taps += 1
+
+ return {
+ "Foundation": SimpleNamespace(
+ NSBundle=SimpleNamespace(mainBundle=lambda: self.bundle),
+ NSURL=SimpleNamespace(URLWithString_=lambda value: value),
+ ),
+ "AppKit": SimpleNamespace(
+ NSWorkspace=SimpleNamespace(sharedWorkspace=lambda: workspace),
+ NSRunningApplication=SimpleNamespace(
+ currentApplication=lambda: current,
+ runningApplicationsWithBundleIdentifier_=running,
+ ),
+ ),
+ "AVFoundation": SimpleNamespace(
+ AVCaptureDevice=_CaptureDevice(self),
+ AVMediaTypeAudio="audio",
+ AVAuthorizationStatusNotDetermined=0,
+ AVAuthorizationStatusRestricted=1,
+ AVAuthorizationStatusDenied=2,
+ AVAuthorizationStatusAuthorized=3,
+ ),
+ "Quartz": SimpleNamespace(
+ CGPreflightScreenCaptureAccess=lambda: self.screen_preflight,
+ CGRequestScreenCaptureAccess=request_screen,
+ CGPreflightListenEventAccess=lambda: False,
+ CGRequestListenEventAccess=request_listen,
+ CGPreflightPostEventAccess=lambda: False,
+ CGRequestPostEventAccess=request_post,
+ CGEventTapCreate=event_tap,
+ ),
+ "ApplicationServices": SimpleNamespace(
+ AXIsProcessTrusted=lambda: self.ax_trusted,
+ AXIsProcessTrustedWithOptions=request_ax,
+ kAXTrustedCheckOptionPrompt="prompt",
+ ),
+ }
+
+ def load(self, name: str) -> object:
+ self.imports.append(name)
+ if name not in self.modules:
+ raise ModuleNotFoundError(name)
+ return self.modules[name]
+
+ def _probe(self, bundle_id: str, ask: bool) -> int | None:
+ self.probes.append((bundle_id, ask))
+ if ask:
+ self.requests.append(f"ae_ask:{bundle_id}")
+ answer = self.probe_answers.get(bundle_id)
+ if isinstance(answer, Exception):
+ raise answer
+ return answer
+
+ def _live_check(self) -> bool | None:
+ self.live_checks += 1
+ return self.live_check_answer
+
+ def _consent_runner(self, script: str) -> Any:
+ self.boom()
+ self.consent_scripts.append(script)
+ self.requests.append("consent_runner")
+ if isinstance(self.consent_result, Exception):
+ raise self.consent_result
+ return self.consent_result
+
+ def _iohid_request(self, request_type: int) -> bool | None:
+ self.boom()
+ self.requests.append(f"iohid_request:{request_type}")
+ return self.iohid_request_answer
+
+ def _recover(self) -> bool:
+ self.boom()
+ self.recover_calls += 1
+ self.requests.append("keychain_replay")
+ return True
+
+ def port(self, *, default_live_check: bool = False) -> SystemPermissionPort:
+ kwargs: dict[str, Any] = {}
+ if not default_live_check:
+ kwargs["screen_capture_live_check"] = self._live_check
+ return SystemPermissionPort(
+ platform_name="darwin",
+ module_loader=self.load,
+ iohid_check=lambda request_type: self.iohid_state.get(request_type),
+ credential_store_backend=lambda: "platform",
+ credential_store_recover=self._recover,
+ automation_probe=self._probe,
+ iohid_request=self._iohid_request,
+ automation_consent_runner=self._consent_runner,
+ **kwargs,
+ )
+
+
+def _non_darwin_port(imports: list[str]) -> SystemPermissionPort:
+ def load(name: str) -> object:
+ imports.append(name)
+ raise AssertionError(f"a non-macOS port must not load {name}")
+
+ return SystemPermissionPort(platform_name="win32", module_loader=load)
+
+
+# --- request class, pane family and settings path metadata ------------------
+
+
+def test_request_class_vocabulary_is_stable() -> None:
+ assert [item.value for item in RequestClass] == ["dialog", "prompt_once", "native", "none"]
+ assert RequestClass.DIALOG == "dialog"
+
+
+def test_every_permission_has_a_request_class() -> None:
+ assert set(REQUEST_CLASS) == set(PermissionId)
+
+
+ ("permission", "expected"),
+ [
+ (PermissionId.MICROPHONE, RequestClass.DIALOG),
+ (PermissionId.SCREEN_RECORDING, RequestClass.PROMPT_ONCE),
+ (PermissionId.ACCESSIBILITY, RequestClass.PROMPT_ONCE),
+ (PermissionId.INPUT_MONITORING, RequestClass.PROMPT_ONCE),
+ (PermissionId.EVENT_POSTING, RequestClass.PROMPT_ONCE),
+ (PermissionId.AUTOMATION, RequestClass.DIALOG),
+ (PermissionId.CREDENTIAL_STORE, RequestClass.NONE),
+ ],
+)
+def test_request_class_follows_the_policy_table(
+ permission: PermissionId, expected: RequestClass
+) -> None:
+ assert REQUEST_CLASS[permission] is expected
+
+
+def test_event_posting_and_accessibility_share_one_pane_family() -> None:
+ assert PANE_FAMILY[PermissionId.EVENT_POSTING] is PermissionId.ACCESSIBILITY
+ assert PANE_FAMILY[PermissionId.ACCESSIBILITY] is PermissionId.ACCESSIBILITY
+
+
+def test_pane_family_names_a_canonical_member_for_every_permission() -> None:
+ assert set(PANE_FAMILY) == set(PermissionId)
+ for permission, family in PANE_FAMILY.items():
+ assert PANE_FAMILY[family] is family, permission
+ # Every other permission keeps a family of its own.
+ families = {family for permission, family in PANE_FAMILY.items()}
+ assert len(families) == len(PermissionId) - 1
+
+
+def test_pane_family_agrees_with_the_settings_deep_links() -> None:
+ urls = permissions_module._SETTINGS_URLS
+ for first in urls:
+ for second in urls:
+ assert (urls[first] == urls[second]) == (PANE_FAMILY[first] == PANE_FAMILY[second])
+
+
+def test_settings_path_text_is_plain_english_for_every_pane() -> None:
+ assert set(SETTINGS_PATH_TEXT) == set(permissions_module._SETTINGS_URLS)
+ for permission, text in SETTINGS_PATH_TEXT.items():
+ assert text.startswith("System Settings > Privacy & Security > "), permission
+ assert text.isascii(), permission
+ assert SETTINGS_PATH_TEXT[PermissionId.MICROPHONE] == (
+ "System Settings > Privacy & Security > Microphone"
+ )
+ assert (
+ SETTINGS_PATH_TEXT[PermissionId.EVENT_POSTING]
+ == (SETTINGS_PATH_TEXT[PermissionId.ACCESSIBILITY])
+ )
+
+
+def test_settings_path_helper_takes_strings_and_has_no_path_for_the_keychain() -> None:
+ assert settings_path_text("input_monitoring") == (
+ "System Settings > Privacy & Security > Input Monitoring"
+ )
+ assert settings_path_text(PermissionId.CREDENTIAL_STORE) is None
+
+
+def test_the_existing_labels_and_deep_links_are_untouched() -> None:
+ assert permissions_module._LABELS[PermissionId.EVENT_POSTING] == "Input Control"
+ assert permissions_module._SETTINGS_URLS[PermissionId.INPUT_MONITORING] == (
+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent"
+ )
+
+
+# --- state(): live, never asks, optional target and depth --------------------
+
+
+def test_state_never_calls_a_request_function() -> None:
+ world = _World()
+ world.installed = {_MUSIC}
+ world.running = {_MUSIC}
+ world.probe_answers = {_MUSIC: -1744} # would require consent: the dialog trigger
+ port = world.port()
+
+ for permission in PermissionId:
+ port.state(permission)
+ port.state(permission, deep=True)
+ port.state(permission, deep=False)
+ port.state(PermissionId.AUTOMATION, target=_MUSIC)
+
+ assert world.requests == []
+ assert world.event_taps == 0
+ assert world.launches == []
+ assert world.probes
+ assert all(ask is False for _bundle_id, ask in world.probes)
+
+
+def test_state_stays_live_and_uncached() -> None:
+ world = _World()
+ port = world.port()
+
+ world.mic_status = 0
+ first = port.state(PermissionId.MICROPHONE)
+ world.mic_status = 3
+ second = port.state("microphone")
+
+ assert (first, second) == (PermissionState.NOT_DETERMINED, PermissionState.GRANTED)
+
+
+def test_target_and_deep_are_keyword_only() -> None:
+ port = _World().port()
+
+ with pytest.raises(TypeError):
+ port.state(PermissionId.SCREEN_RECORDING, None, True) # type: ignore[misc]
+
+
+def test_a_target_is_ignored_for_every_permission_but_automation() -> None:
+ world = _World()
+ world.mic_status = 3
+ port = world.port()
+
+ assert port.state(PermissionId.MICROPHONE, target="not.a.player") is PermissionState.GRANTED
+ assert world.probes == []
+
+
+def test_a_shallow_screen_recording_read_is_the_preflight_alone() -> None:
+ world = _World()
+ world.live_check_answer = True # the oracle WOULD upgrade the verdict
+ port = world.port()
+
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=False) is PermissionState.NOT_GRANTED
+ assert world.live_checks == 0
+
+
+def test_a_deep_screen_recording_read_runs_the_oracle_only_when_it_can_help() -> None:
+ world = _World()
+ world.live_check_answer = True
+ port = world.port()
+
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.GRANTED
+ assert world.live_checks == 1
+
+ # A granted preflight needs no second opinion.
+ world.screen_preflight = True
+ world.live_checks = 0
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.GRANTED
+ assert world.live_checks == 0
+
+
+def test_a_deep_read_never_invents_a_grant_the_oracle_cannot_prove() -> None:
+ world = _World()
+ world.live_check_answer = None
+ port = world.port()
+
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.NOT_GRANTED
+
+
+def test_only_a_deep_read_enumerates_windows(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The default oracle lists the on-screen windows; a shallow read must not."""
+ enumerations: list[int] = []
+
+ def windows(*_args: Any) -> list[dict[str, object]]:
+ enumerations.append(1)
+ return [{"kCGWindowLayer": 0, "kCGWindowOwnerPID": os.getpid() + 1, "kCGWindowName": "X"}]
+
+ monkeypatch.setitem(
+ sys.modules,
+ "Quartz",
+ SimpleNamespace(
+ CGWindowListCopyWindowInfo=windows,
+ kCGWindowListOptionOnScreenOnly=1,
+ kCGWindowListExcludeDesktopElements=16,
+ kCGNullWindowID=0,
+ ),
+ )
+ port = _World().port(default_live_check=True)
+
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=False) is PermissionState.NOT_GRANTED
+ assert enumerations == []
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.GRANTED
+ assert enumerations == [1]
+
+
+def test_a_state_read_off_macos_loads_nothing() -> None:
+ imports: list[str] = []
+ port = _non_darwin_port(imports)
+
+ for permission in PermissionId:
+ assert port.state(permission) is PermissionState.NOT_REQUIRED
+ assert port.state(permission, deep=True, target=_MUSIC) is PermissionState.NOT_REQUIRED
+ assert imports == []
+
+
+# --- state(AUTOMATION, target=): one player, read-only -------------------------
+
+
+ ("answer", "expected"),
+ [
+ (0, PermissionState.GRANTED),
+ (-1743, PermissionState.DENIED),
+ (-1744, PermissionState.NOT_DETERMINED),
+ ],
+)
+def test_a_running_player_is_read_live_without_asking(
+ answer: int, expected: PermissionState
+) -> None:
+ world = _World()
+ world.installed = {_MUSIC, _SPOTIFY}
+ world.running = {_MUSIC}
+ world.probe_answers = {_MUSIC: answer, _SPOTIFY: 0}
+
+ state = world.port().state(PermissionId.AUTOMATION, target=_MUSIC)
+
+ assert state is expected
+ # Exactly the one requested player is probed, and never with ask=True.
+ assert world.probes == [(_MUSIC, False)]
+
+
+def test_a_player_that_is_not_running_is_unknown_not_granted() -> None:
+ world = _World()
+ world.installed = {_MUSIC}
+ world.probe_answers = {_MUSIC: 0} # would read granted if it were asked
+
+ state = world.port().state(PermissionId.AUTOMATION, target=_MUSIC)
+
+ assert state is PermissionState.NOT_DETERMINED
+ assert world.probes == []
+
+
+def test_a_probe_without_an_answer_for_a_running_player_is_unknown() -> None:
+ world = _World()
+ world.installed = {_MUSIC}
+ world.running = {_MUSIC}
+ world.probe_answers = {_MUSIC: -600} # raced with the player quitting
+
+ assert world.port().state(PermissionId.AUTOMATION, target=_MUSIC) is (
+ PermissionState.NOT_DETERMINED
+ )
+
+
+def test_a_probe_that_raises_degrades_to_unknown() -> None:
+ world = _World()
+ world.installed = {_MUSIC}
+ world.running = {_MUSIC}
+ world.probe_answers = {_MUSIC: RuntimeError("Apple Event Manager hung up")}
+
+ assert world.port().state(PermissionId.AUTOMATION, target=_MUSIC) is (
+ PermissionState.NOT_DETERMINED
+ )
+
+
+def test_a_player_that_is_not_installed_needs_no_consent() -> None:
+ world = _World()
+ world.installed = {_SPOTIFY}
+
+ assert world.port().state(PermissionId.AUTOMATION, target=_MUSIC) is (
+ PermissionState.NOT_REQUIRED
+ )
+
+
+def test_an_unknown_target_is_unavailable_and_logged_not_raised(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ world = _World()
+ world.installed = {_MUSIC}
+ world.running = {_MUSIC}
+ caplog.set_level(logging.DEBUG, logger="jarvis.platform.permissions")
+
+ for target in ("com.example.NotAPlayer", "", "Music"):
+ assert world.port().state(PermissionId.AUTOMATION, target=target) is (
+ PermissionState.UNAVAILABLE
+ )
+
+ assert world.probes == []
+ assert any("com.example.NotAPlayer" in record.getMessage() for record in caplog.records)
+
+
+def test_a_missing_appkit_makes_a_target_read_unavailable() -> None:
+ world = _World()
+ del world.modules["AppKit"]
+
+ assert world.port().state(PermissionId.AUTOMATION, target=_MUSIC) is (
+ PermissionState.UNAVAILABLE
+ )
+
+
+def test_every_known_player_is_a_valid_target() -> None:
+ world = _World()
+ world.installed = {bundle_id for _name, bundle_id in AUTOMATION_TARGETS}
+ port = world.port()
+
+ for _name, bundle_id in AUTOMATION_TARGETS:
+ assert port.state(PermissionId.AUTOMATION, target=bundle_id) is (
+ PermissionState.NOT_DETERMINED
+ )
+
+
+# --- request_native(): only the native request, never raises -------------------
+
+
+def test_a_microphone_request_that_can_show_a_dialog_says_so() -> None:
+ world = _World()
+ world.mic_status = 0 # not determined
+
+ outcome = world.port().request_native(PermissionId.MICROPHONE)
+
+ assert outcome == "dialog_shown"
+ assert world.requests == ["microphone"]
+ assert world.mic_media_types == ["audio"]
+
+
[email protected]("status", [1, 2, 3])
+def test_a_microphone_that_is_already_decided_shows_no_dialog(status: int) -> None:
+ world = _World()
+ world.mic_status = status
+
+ assert world.port().request_native(PermissionId.MICROPHONE) == "no_dialog"
+ assert world.requests == ["microphone"] # still the one native call, nothing else
+
+
[email protected](("answer", "expected"), [(False, "dialog_shown"), (True, "no_dialog")])
+def test_screen_recording_request_reports_what_the_os_may_be_doing(
+ answer: bool, expected: str
+) -> None:
+ world = _World()
+ world.screen_request_answer = answer
+
+ assert world.port().request_native(PermissionId.SCREEN_RECORDING) == expected
+ assert world.requests == ["screen_recording"]
+
+
[email protected](("answer", "expected"), [(False, "dialog_shown"), (True, "no_dialog")])
+def test_accessibility_request_uses_the_prompt_option(answer: bool, expected: str) -> None:
+ world = _World()
+ world.ax_request_answer = answer
+
+ assert world.port().request_native(PermissionId.ACCESSIBILITY) == expected
+ assert world.ax_options == [{"prompt": True}]
+
+
+def test_event_posting_is_the_accessibility_request() -> None:
+ world = _World()
+
+ outcome = world.port().request_native(PermissionId.EVENT_POSTING)
+
+ assert outcome == "dialog_shown"
+ assert world.requests == ["accessibility"] # not CGRequestPostEventAccess
+ assert world.ax_options == [{"prompt": True}]
+
+
+def test_input_monitoring_not_determined_may_show_a_dialog() -> None:
+ world = _World()
+ world.iohid_state = {_IOHID_LISTEN: _IOHID_UNKNOWN}
+
+ assert world.port().request_native(PermissionId.INPUT_MONITORING) == "dialog_shown"
+ assert world.requests == ["listen"]
+
+
+def test_input_monitoring_with_a_decision_on_file_shows_no_dialog() -> None:
+ world = _World()
+ world.iohid_state = {_IOHID_LISTEN: _IOHID_DENIED}
+
+ assert world.port().request_native(PermissionId.INPUT_MONITORING) == "no_dialog"
+ assert world.requests == ["listen"] # the request is still made; the OS ignores it
+
+
+def test_input_monitoring_already_granted_shows_no_dialog() -> None:
+ world = _World()
+ world.listen_request_answer = True
+
+ assert world.port().request_native(PermissionId.INPUT_MONITORING) == "no_dialog"
+
+
+def test_input_monitoring_without_a_tristate_reads_the_boolean_answer() -> None:
+ world = _World() # no IOHID answer at all
+
+ assert world.port().request_native(PermissionId.INPUT_MONITORING) == "dialog_shown"
+
+
+def test_input_monitoring_falls_back_to_iohid_when_quartz_lacks_the_request() -> None:
+ world = _World()
+ del world.modules["Quartz"].CGRequestListenEventAccess
+ world.iohid_state = {_IOHID_LISTEN: _IOHID_UNKNOWN}
+ world.iohid_request_answer = False
+
+ assert world.port().request_native(PermissionId.INPUT_MONITORING) == "dialog_shown"
+ assert world.requests == [f"iohid_request:{_IOHID_LISTEN}"]
+
+
+def test_input_monitoring_with_no_way_to_ask_is_unavailable() -> None:
+ world = _World()
+ del world.modules["Quartz"].CGRequestListenEventAccess
+ world.iohid_request_answer = None
+
+ assert world.port().request_native(PermissionId.INPUT_MONITORING) == "unavailable"
+
+
+def test_a_native_request_never_creates_an_event_tap() -> None:
+ world = _World()
+ port = world.port()
+
+ for permission in PermissionId:
+ port.request_native(permission, target=_MUSIC)
+
+ assert world.event_taps == 0
+
+
+ ("missing_module", "permission", "attempted"),
+ [
+ ("AVFoundation", PermissionId.MICROPHONE, []),
+ ("Quartz", PermissionId.SCREEN_RECORDING, []),
+ ("ApplicationServices", PermissionId.ACCESSIBILITY, []),
+ ("ApplicationServices", PermissionId.EVENT_POSTING, []),
+ # Input Monitoring tries IOHIDRequestAccess when Quartz is gone; the
+ # stub has no answer for it, so there is still no way to ask.
+ ("Quartz", PermissionId.INPUT_MONITORING, [f"iohid_request:{_IOHID_LISTEN}"]),
+ ],
+)
+def test_a_missing_framework_makes_the_request_unavailable(
+ missing_module: str, permission: PermissionId, attempted: list[str]
+) -> None:
+ world = _World()
+ del world.modules[missing_module]
+
+ assert world.port().request_native(permission) == "unavailable"
+ assert world.requests == attempted
+
+
+def test_a_request_function_the_binding_lacks_is_unavailable() -> None:
+ world = _World()
+ del world.modules["Quartz"].CGRequestScreenCaptureAccess
+
+ assert world.port().request_native(PermissionId.SCREEN_RECORDING) == "unavailable"
+
+
[email protected]("permission", list(PermissionId))
+def test_request_native_never_raises_when_the_native_call_does(
+ permission: PermissionId, caplog: pytest.LogCaptureFixture
+) -> None:
+ world = _World()
+ world.explode = True
+ caplog.set_level(logging.DEBUG, logger="jarvis.platform.permissions")
+
+ outcome = world.port().request_native(permission, target=_MUSIC)
+
+ assert outcome == "unavailable"
+ # Never silent (AP-30): the failure is logged with its traceback.
+ assert any(record.exc_info for record in caplog.records), permission
+
+
+def test_request_native_ignores_an_unknown_permission() -> None:
+ world = _World()
+
+ assert world.port().request_native("bogus") == "unavailable"
+ assert world.requests == []
+
+
+def test_request_native_off_macos_loads_nothing_and_asks_nothing() -> None:
+ imports: list[str] = []
+ port = _non_darwin_port(imports)
+
+ for permission in PermissionId:
+ assert port.request_native(permission, target=_MUSIC) == "unavailable"
+ assert imports == []
+
+
+ ("bundle_id", "path"),
+ [
+ (None, "/usr/local/bin"),
+ ("org.python.python", "/Library/Frameworks/Python.framework/Python.app"),
+ (EXPECTED_BUNDLE_ID, "/Users/someone/Downloads/Personal Jarvis.app"),
+ ],
+)
+def test_request_native_makes_no_identity_check_of_its_own(
+ bundle_id: str | None, path: str
+) -> None:
+ """Whether we may ask is the service's decision (design P6), not the port's."""
+ world = _World(bundle_id=bundle_id, bundle_path=path, info={})
+ port = world.port()
+ assert port.outside_installed_app is True
+
+ assert port.request_native(PermissionId.MICROPHONE) == "dialog_shown"
+ assert port.request_native(PermissionId.SCREEN_RECORDING) == "dialog_shown"
+ assert world.requests == ["microphone", "screen_recording"]
+ # ... and it does not look for the usage string either: that is the service's job.
+ assert world.bundle.info_reads == []
+
+
+def test_a_request_answer_is_never_evidence_of_a_grant() -> None:
+ world = _World()
+ world.screen_request_answer = True # the API says "already granted"
+ world.ax_request_answer = True
+ port = world.port()
+
+ assert port.request_native(PermissionId.SCREEN_RECORDING) == "no_dialog"
+ assert port.request_native(PermissionId.ACCESSIBILITY) == "no_dialog"
+
+ # Only the live read says anything about access, and it still says no.
+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
+ assert port.state(PermissionId.ACCESSIBILITY) is PermissionState.NOT_GRANTED
+
+
+# --- request_native(AUTOMATION): a killable, guarded child, never a launch -----
+
+
+def test_automation_needs_a_scriptable_player() -> None:
+ world = _World()
+ port = world.port()
+
+ assert port.request_native(PermissionId.AUTOMATION) == "unavailable"
+ assert port.request_native(PermissionId.AUTOMATION, target="com.example.Evil") == "unavailable"
+ assert port.request_native(PermissionId.AUTOMATION, target='x" & (do shell script "id")') == (
+ "unavailable"
+ )
+ assert world.consent_scripts == []
+ assert world.requests == []
+
+
+def test_automation_runs_one_guarded_script_and_never_launches_the_player() -> None:
+ world = _World()
+ world.installed = {_MUSIC} # installed, NOT running
+
+ outcome = world.port().request_native(PermissionId.AUTOMATION, target=_MUSIC)
+
+ assert outcome == "no_dialog"
+ assert len(world.consent_scripts) == 1
+ script = world.consent_scripts[0]
+ # The running check sits INSIDE the script, so a bare tell can never launch it.
+ assert f'if application id "{_MUSIC}" is running then' in script
+ assert f'tell application id "{_MUSIC}" to get player state' in script
+ assert "launch" not in script and "activate" not in script
+ assert world.launches == []
+ # No in-process Apple Event ask and no player probe.
+ assert world.probes == []
+
+
+ "result",
+ [
+ SimpleNamespace(returncode=0, stdout="-\n", stderr=""), # player not running
+ SimpleNamespace(returncode=0, stdout="+\n", stderr=""), # event sent and permitted
+ SimpleNamespace(returncode=1, stdout="", stderr="execution error: (-1743)"), # denied
+ ],
+ ids=["not_running", "permitted", "denied"],
+)
+def test_a_finished_automation_request_leaves_no_dialog_open(result: Any) -> None:
+ world = _World()
+ world.consent_result = result
+
+ # Synchronous: the answer, if any, is in state(); the return value is not one.
+ assert world.port().request_native(PermissionId.AUTOMATION, target=_SPOTIFY) == "no_dialog"
+ assert world.requests == ["consent_runner"]
+
+
+def test_an_unanswered_automation_request_is_timed_out_not_a_missing_player() -> None:
+ world = _World()
+ world.consent_result = subprocess.TimeoutExpired(cmd="osascript", timeout=120.0)
+
+ # Nobody answered before the runner was killed: the caller must not read that as
+ # "the player is not running" (which "no_dialog" means), it may ask again later.
+ assert world.port().request_native(PermissionId.AUTOMATION, target=_SPOTIFY) == "timed_out"
+ assert world.requests == ["consent_runner"]
+
+
+def test_automation_is_unavailable_when_osascript_cannot_run() -> None:
+ world = _World()
+ world.consent_result = FileNotFoundError("osascript")
+
+ assert world.port().request_native(PermissionId.AUTOMATION, target=_MUSIC) == "unavailable"
+
+
+def test_automation_is_unavailable_when_the_runner_reports_nothing() -> None:
+ world = _World()
+ world.consent_result = None
+
+ assert world.port().request_native(PermissionId.AUTOMATION, target=_MUSIC) == "unavailable"
+
+
+def test_the_default_consent_runner_is_killable_windowless_and_shell_free(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_run(argv: list[str], **kwargs: Any) -> SimpleNamespace:
+ captured["argv"] = argv
+ captured["kwargs"] = kwargs
+ return SimpleNamespace(returncode=0, stdout="-\n", stderr="")
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+
+ permissions_module._default_automation_consent_runner("return 1")
+
+ assert captured["argv"] == ["osascript", "-e", "return 1"]
+ kwargs = captured["kwargs"]
+ # 120 s: long enough for a person to answer, and subprocess.run kills the
+ # child when it passes (never a 3 s kill that tears the dialog down).
+ assert kwargs["timeout"] == 120.0
+ assert kwargs["creationflags"] == NO_WINDOW_CREATIONFLAGS
+ assert kwargs["encoding"] == "utf-8"
+ assert not kwargs.get("shell")
+
+
+def test_the_keychain_replay_is_a_synchronous_request() -> None:
+ world = _World()
+
+ assert world.port().request_native(PermissionId.CREDENTIAL_STORE) == "no_dialog"
+ assert world.recover_calls == 1
+
+
+# --- usage_string_present() -----------------------------------------------------
+
+_NEEDS_A_KEY = [
+ (PermissionId.MICROPHONE, "NSMicrophoneUsageDescription"),
+ (PermissionId.AUTOMATION, "NSAppleEventsUsageDescription"),
+]
+_NEEDS_NO_KEY = [
+ PermissionId.SCREEN_RECORDING,
+ PermissionId.ACCESSIBILITY,
+ PermissionId.INPUT_MONITORING,
+ PermissionId.EVENT_POSTING,
+ PermissionId.CREDENTIAL_STORE,
+]
+
+
[email protected](("permission", "key"), _NEEDS_A_KEY)
+def test_the_usage_string_is_found_in_the_main_bundle(permission: PermissionId, key: str) -> None:
+ world = _World()
+
+ assert world.port().usage_string_present(permission) is True
+ assert world.bundle.info_reads == [key]
+
+
[email protected](("permission", "key"), _NEEDS_A_KEY)
+def test_a_missing_usage_string_refuses(permission: PermissionId, key: str) -> None:
+ other = {name: text for name, text in _ALL_INFO.items() if name != key}
+ world = _World(info=other)
+
+ assert world.port().usage_string_present(permission) is False
+
+
[email protected](("permission", "key"), _NEEDS_A_KEY)
[email protected]("blank", ["", " ", "\n"])
+def test_a_blank_usage_string_counts_as_missing(
+ permission: PermissionId, key: str, blank: str
+) -> None:
+ world = _World(info={key: blank})
+
+ assert world.port().usage_string_present(permission) is False
+
+
+def test_only_the_microphone_key_is_missing() -> None:
+ world = _World(info={"NSAppleEventsUsageDescription": "Sends commands."})
+ port = world.port()
+
+ assert port.usage_string_present(PermissionId.MICROPHONE) is False
+ assert port.usage_string_present(PermissionId.AUTOMATION) is True
+
+
[email protected]("permission", _NEEDS_NO_KEY)
+def test_a_permission_without_a_usage_key_never_refuses(permission: PermissionId) -> None:
+ world = _World(info={}) # no strings at all
+
+ assert world.port().usage_string_present(permission) is True
+ assert world.bundle.info_reads == []
+
+
[email protected](("permission", "_key"), _NEEDS_A_KEY)
+def test_no_bundle_id_means_a_terminal_is_responsible_and_the_key_is_not_applicable(
+ permission: PermissionId, _key: str
+) -> None:
+ world = _World(bundle_id=None, bundle_path="/usr/local/bin", info={})
+
+ assert world.port().usage_string_present(permission) is True
+ assert world.bundle.info_reads == []
+
+
[email protected](("permission", "_key"), _NEEDS_A_KEY)
+def test_an_unloadable_foundation_means_no_bundle_id_and_so_not_applicable(
+ permission: PermissionId, _key: str
+) -> None:
+ world = _World()
+ del world.modules["Foundation"]
+
+ assert world.port().usage_string_present(permission) is True
+
+
+def test_a_foreign_bundle_without_the_key_refuses() -> None:
+ """A frozen Python.app or any other bundle that lacks the key would be killed."""
+ world = _World(bundle_id="org.python.python", info={})
+
+ assert world.port().usage_string_present(PermissionId.MICROPHONE) is False
+
+
+def test_an_unreadable_info_dictionary_fails_closed_without_raising(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ world = _World(info_error=RuntimeError("bundle vanished"))
+ caplog.set_level(logging.DEBUG, logger="jarvis.platform.permissions")
+
+ assert world.port().usage_string_present(PermissionId.MICROPHONE) is False
+ assert any(record.exc_info for record in caplog.records)
+
+
+def test_the_usage_string_check_accepts_a_plain_string_id() -> None:
+ assert _World().port().usage_string_present("microphone") is True
+
+
+def test_the_usage_string_check_off_macos_loads_nothing() -> None:
+ imports: list[str] = []
+ port = _non_darwin_port(imports)
+
+ for permission in PermissionId:
+ assert port.usage_string_present(permission) is True
+ assert imports == []
+
+
+def test_the_usage_keys_are_keys_the_bundles_really_carry() -> None:
+ strings = pytest.importorskip("jarvis.core.macos_privacy_strings")
+
+ for key in permissions_module._USAGE_DESCRIPTION_KEYS.values():
+ assert key in strings.REQUIRED_USAGE_KEYS
+
+
+# --- outside_installed_app -------------------------------------------------------
+
+
+ ("bundle_id", "path"),
+ [
+ (None, "/usr/local/bin"),
+ ("org.python.python", "/Library/Frameworks/Python.framework/Versions/3.11/Python.app"),
+ ("com.apple.Terminal", "/System/Applications/Utilities/Terminal.app"),
+ ("ai.personaljarvis.desktop.evil", "/Applications/Personal Jarvis.app"),
+ ],
+ ids=["no_bundle", "python_framework", "terminal", "lookalike_id"],
+)
+def test_a_development_run_is_outside_the_installed_app(bundle_id: str | None, path: str) -> None:
+ assert _World(bundle_id=bundle_id, bundle_path=path).port().outside_installed_app is True
+
+
[email protected]("bundle_id", ACCEPTED_BUNDLE_IDS)
[email protected]("path", [_INSTALLED_PATH, "/Applications/Personal Jarvis.app"])
+def test_an_installed_bundle_is_inside_whichever_accepted_id_it_carries(
+ bundle_id: str, path: str
+) -> None:
+ assert _World(bundle_id=bundle_id, bundle_path=path).port().outside_installed_app is False
+
+
+def test_the_downloaded_dmg_app_is_inside_once_it_is_installed() -> None:
+ world = _World(bundle_id=MACOS_DMG_BUNDLE_ID, bundle_path="/Applications/Personal Jarvis.app")
+
+ assert world.port().outside_installed_app is False
+
+
+def test_the_dmg_app_running_from_the_mounted_image_is_still_outside() -> None:
+ world = _World(
+ bundle_id=MACOS_DMG_BUNDLE_ID,
+ bundle_path="/Volumes/Personal Jarvis/Personal Jarvis.app",
+ )
+
+ assert world.port().outside_installed_app is True
+
+
+def test_a_bundle_not_in_an_application_folder_is_outside_even_with_our_id() -> None:
+ world = _World(bundle_path="/Users/someone/Downloads/Personal Jarvis.app")
+
+ assert world.port().outside_installed_app is True
+
+
+def test_outside_installed_app_is_the_inverse_of_the_reported_stable_identity() -> None:
+ for bundle_id, path in [
+ (EXPECTED_BUNDLE_ID, _INSTALLED_PATH),
+ (MACOS_DMG_BUNDLE_ID, "/Volumes/Personal Jarvis/Personal Jarvis.app"),
+ (None, "/usr/local/bin"),
+ ]:
+ port = _World(bundle_id=bundle_id, bundle_path=path).port()
+ assert port.outside_installed_app is (not port._app_identity()[0].stable)
+
+
+def test_the_reported_app_identity_keeps_its_shape() -> None:
+ identity, headless = _World().port()._app_identity()
+
+ assert set(vars(identity)) == {
+ "app_name",
+ "bundle_id",
+ "bundle_path",
+ "launched_as_bundle",
+ "stable",
+ }
+ assert identity.stable is True
+ assert identity.bundle_id == EXPECTED_BUNDLE_ID
+ assert headless is False
+
+
+def test_the_default_screen_recording_read_is_the_preflight_alone() -> None:
+ """``deep`` defaults to False: a caller that wants the window-title oracle says so."""
+ world = _World()
+ world.live_check_answer = True # the oracle WOULD upgrade the verdict
+ port = world.port()
+
+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED
+ assert world.live_checks == 0
+ assert port.state(PermissionId.SCREEN_RECORDING, deep=True) is PermissionState.GRANTED
+ assert world.live_checks == 1
+
+
+def test_reading_the_identity_asks_the_os_for_nothing() -> None:
+ world = _World(bundle_id=None, bundle_path="/usr/local/bin")
+
+ assert world.port().outside_installed_app is True
+ assert world.requests == []
+ assert world.imports == ["Foundation"]
+
+
+def test_outside_installed_app_is_true_off_macos_and_loads_nothing() -> None:
+ imports: list[str] = []
+
+ assert _non_darwin_port(imports).outside_installed_app is True
+ assert imports == []
diff --git a/tests/unit/platform/test_probes.py b/tests/unit/platform/test_probes.py
index 0dfc66e3fb..eb107b7256 100644
--- a/tests/unit/platform/test_probes.py
+++ b/tests/unit/platform/test_probes.py
@@ -125,49 +125,6 @@ def test_ax_permission_linux_needs_bus(monkeypatch):
assert probes.ax_permission_granted() is True
-# --- screen_recording_granted (tri-state, H1) ------------------------------
-
-
-def test_screen_recording_true_off_darwin(monkeypatch):
- # Only macOS gates screenshots behind a TCC Screen-Recording grant; Windows
- # and Linux need no per-app grant.
- _force_platform(monkeypatch, "win32")
- assert probes.screen_recording_granted() is True
- _force_platform(monkeypatch, "linux")
- assert probes.screen_recording_granted() is True
-
-
-def test_screen_recording_macos_reflects_preflight(monkeypatch):
- import sys
- import types
-
- _force_platform(monkeypatch, "darwin")
- # Replaces any already-cached Quartz module so the function-local
- # `from Quartz import ...` re-resolves to this fake (matters on a real Mac
- # with pyobjc installed, where the genuine module would otherwise win).
- monkeypatch.setitem(
- sys.modules,
- "Quartz",
- types.SimpleNamespace(CGPreflightScreenCaptureAccess=lambda: True),
- )
- assert probes.screen_recording_granted() is True
- monkeypatch.setitem(
- sys.modules,
- "Quartz",
- types.SimpleNamespace(CGPreflightScreenCaptureAccess=lambda: False),
- )
- assert probes.screen_recording_granted() is False
-
-
-def test_screen_recording_macos_unknown_without_quartz(monkeypatch):
- import sys
-
- _force_platform(monkeypatch, "darwin")
- # pyobjc-Quartz absent → import raises → unknown (None), never a hard False.
- monkeypatch.setitem(sys.modules, "Quartz", None)
- assert probes.screen_recording_granted() is None
-
-
# --- has_elevation ---------------------------------------------------------
@@ -255,5 +212,4 @@ def test_all_probes_run_without_raising_on_host():
assert isinstance(probes.has_overlay(), bool)
assert isinstance(probes.has_elevation(), bool)
assert probes.ax_permission_granted() in (True, False, None)
- assert probes.screen_recording_granted() in (True, False, None)
assert isinstance(probes.webview_backend_available(), bool)
diff --git a/tests/unit/platform/test_screen_access.py b/tests/unit/platform/test_screen_access.py
new file mode 100644
index 0000000000..6cbf2962d6
--- /dev/null
+++ b/tests/unit/platform/test_screen_access.py
@@ -0,0 +1,513 @@
+"""Unit coverage for ``jarvis.platform.screen_access``: the Screen Recording seam of the
+capture consumers. The gate is the scripted ``FakePermissionService`` (or a tiny
+hand-written stub where a method the Protocol lacks matters); the macOS behaviour
+itself is covered with ``FakeTCC`` in ``tests/unit/cu/test_capture_permissions.py``.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.platform import screen_access
+from jarvis.platform.permissions import PermissionId, PermissionState
+from jarvis.platform.screen_access import (
+ ScreenCaptureRefused,
+ frame_is_blank,
+ refusal_for_state,
+ require_screen_recording,
+ require_screen_recording_async,
+ screen_recording_blocked,
+ screen_recording_state,
+ verify_frame_is_real,
+)
+from tests.fakes.fake_permission_service import FakePermissionService
+from tests.fakes.fake_screen_pixels import textured_pixels, wallpaper_pixels
+
+_SR = PermissionId.SCREEN_RECORDING
+_SIZE = (64, 36)
+
+
+class _StubGate:
+ """A gate with the optional ``check_deep`` / ``invalidate`` / ``ensure`` of the service."""
+
+ def __init__(self, states, deep=None, ensure=None):
+ self._states = list(states)
+ self._deep = list(deep or [])
+ self._ensure = ensure
+ self.log: list[str] = []
+
+ def check(self, permission, *, target=None):
+ self.log.append("check")
+ return self._states.pop(0) if len(self._states) > 1 else self._states[0]
+
+ def check_deep(self, permission, *, target=None):
+ self.log.append("check_deep")
+ return self._deep.pop(0) if len(self._deep) > 1 else self._deep[0]
+
+ def invalidate(self, permission=None):
+ self.log.append("invalidate")
+
+ def ensure(self, permission, **kwargs):
+ self.log.append("ensure")
+ return self._ensure
+
+
+# ---------------------------------------------------------------------------
+# Silent reads
+# ---------------------------------------------------------------------------
+
+
+def test_a_not_granted_preflight_is_re_read_deeply_before_it_is_believed():
+ gate = _StubGate([PermissionState.NOT_GRANTED], deep=[PermissionState.GRANTED])
+
+ assert screen_recording_state(gate) is PermissionState.GRANTED
+ assert gate.log == ["check", "check_deep"]
+
+
+def test_a_granted_preflight_costs_one_cached_read_and_no_window_enumeration():
+ gate = _StubGate([PermissionState.GRANTED], deep=[PermissionState.NOT_GRANTED])
+
+ assert screen_recording_state(gate) is PermissionState.GRANTED
+ assert gate.log == ["check"]
+
+
[email protected]("state", [PermissionState.RESTRICTED, PermissionState.UNAVAILABLE])
+def test_restricted_and_unavailable_are_final_and_skip_the_deep_read(state):
+ gate = _StubGate([state], deep=[PermissionState.GRANTED])
+
+ assert screen_recording_state(gate) is state
+ assert gate.log == ["check"]
+
+
+def test_a_gate_without_a_deep_read_answers_with_check_alone():
+ gate = FakePermissionService({_SR: "needs_settings"})
+
+ assert screen_recording_blocked(gate) is True
+ assert gate.native_free()
+ assert gate.ensure_calls() == []
+
+
+def test_the_helper_read_never_asks():
+ gate = FakePermissionService({_SR: "pending"})
+
+ assert screen_recording_blocked(gate) is True
+
+ assert gate.ensure_calls() == []
+
+
+def test_off_macos_the_read_is_not_blocked():
+ assert screen_recording_blocked(FakePermissionService({_SR: "not_required"})) is False
+
+
+ ("state", "reason"),
+ [
+ (PermissionState.DENIED, "denied"),
+ (PermissionState.NOT_GRANTED, "needs_settings"),
+ (PermissionState.NOT_DETERMINED, "not_determined"),
+ (PermissionState.RESTRICTED, "restricted"),
+ (PermissionState.UNAVAILABLE, "unavailable"),
+ ],
+)
+def test_refusal_text_is_prohibitive_for_the_agent_and_plain_for_people(state, reason):
+ refused = refusal_for_state(state)
+
+ assert refused.reason == reason
+ assert str(refused).startswith("[permission_needed:screen_recording] ")
+ assert "must not" in refused.agent_detail
+ assert refused.user_detail and not refused.user_detail.startswith("[")
+ # Fixed templates only: no exception text, file path or window title.
+ for text in (refused.agent_detail, refused.user_detail):
+ assert "Traceback" not in text and ".py" not in text
+
+
+# ---------------------------------------------------------------------------
+# The gesture entry asks
+# ---------------------------------------------------------------------------
+
+
+def test_the_gesture_entry_asks_once_interactively_without_waiting():
+ gate = FakePermissionService({_SR: "pending"})
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ require_screen_recording("screen_context", gate=gate)
+
+ (call,) = gate.ensure_calls(_SR)
+ assert (call.feature, call.interactive, call.wait_s) == ("screen_context", True, 0.0)
+ assert refused.value.reason == "not_determined"
+
+
+def test_the_gesture_entry_does_not_ask_when_the_grant_is_live():
+ gate = FakePermissionService({_SR: "granted"})
+
+ require_screen_recording("computer_use", gate=gate)
+
+ assert gate.ensure_calls() == []
+
+
+def test_a_grant_the_oracle_sees_does_not_ask_either():
+ gate = _StubGate([PermissionState.NOT_GRANTED], deep=[PermissionState.GRANTED])
+
+ require_screen_recording("computer_use", gate=gate)
+
+ assert "ensure" not in gate.log
+
+
[email protected]("outcome", ["pending", "needs_settings", "denied", "unavailable"])
+def test_only_a_live_grant_proceeds(outcome):
+ gate = FakePermissionService({_SR: outcome})
+
+ with pytest.raises(ScreenCaptureRefused):
+ require_screen_recording("computer_use", gate=gate)
+
+
+async def test_the_async_gesture_entry_uses_ensure_async():
+ gate = FakePermissionService({_SR: "needs_settings"})
+
+ with pytest.raises(ScreenCaptureRefused):
+ await require_screen_recording_async("appshot", gate=gate)
+
+ (call,) = gate.ensure_calls(_SR)
+ assert call.method == "ensure_async"
+ assert call.feature == "appshot"
+ assert call.wait_s == 0.0
+
+
+async def test_the_async_gesture_entry_passes_when_granted():
+ gate = FakePermissionService({_SR: "granted"})
+
+ await require_screen_recording_async("screen_context", gate=gate)
+
+ assert gate.ensure_calls() == []
+
+
+# ---------------------------------------------------------------------------
+# The pixel sanity check
+# ---------------------------------------------------------------------------
+
+
+def test_blank_detection_on_flat_textured_short_and_empty_frames():
+ assert frame_is_blank(_SIZE, wallpaper_pixels(_SIZE)[1])
+ assert not frame_is_blank(_SIZE, textured_pixels(_SIZE)[1])
+ assert frame_is_blank(_SIZE, b"\x00" * 10) # shorter than the size claims
+ assert frame_is_blank((0, 0), b"")
+ # A one-pixel edge on an otherwise flat frame is still content when sampled.
+ sparse = bytearray(wallpaper_pixels(_SIZE)[1])
+ for i in range(0, len(sparse), 3):
+ sparse[i] = (i // 3) % 200 # a ramp in one channel
+ assert not frame_is_blank(_SIZE, bytes(sparse))
+
+
[email protected](autouse=True)
+def _fresh_evidence_cache():
+ screen_access.reset_window_evidence_cache()
+ yield
+ screen_access.reset_window_evidence_cache()
+
+
+def test_a_real_frame_costs_one_fresh_read_and_never_asks(monkeypatch):
+ gate = _StubGate([PermissionState.GRANTED], deep=[PermissionState.NOT_GRANTED])
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (3, 1))
+
+ verify_frame_is_real(_SIZE, textured_pixels(_SIZE)[1], feature="computer_use", gate=gate)
+
+ # One preflight after the grab (the cache is dropped first): no deep read, no ask.
+ assert gate.log == ["invalidate", "check"]
+
+
[email protected]("pixels", [wallpaper_pixels, textured_pixels], ids=["flat", "textured"])
+def test_a_frame_with_a_state_that_is_not_granted_is_refused_after_the_grab(pixels):
+ # The entry gate ran before the grab; the revoke landed during it. Blank or not,
+ # the frame is not a success and the episode is opened.
+ from tests.fakes.fake_permission_service import make_result
+
+ gate = _StubGate(
+ [PermissionState.NOT_GRANTED],
+ deep=[PermissionState.NOT_GRANTED],
+ ensure=make_result(_SR, "needs_settings"),
+ )
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ verify_frame_is_real(_SIZE, pixels(_SIZE)[1], feature="computer_use", gate=gate)
+
+ assert gate.log == ["invalidate", "check", "check_deep", "ensure"]
+ assert refused.value.reason == "needs_settings"
+
+
+def test_a_not_granted_frame_that_the_service_now_grants_is_still_not_trusted():
+ from tests.fakes.fake_permission_service import make_result
+
+ gate = _StubGate(
+ [PermissionState.NOT_GRANTED],
+ deep=[PermissionState.NOT_GRANTED],
+ ensure=make_result(_SR, "granted"),
+ )
+
+ with pytest.raises(ScreenCaptureRefused):
+ verify_frame_is_real(_SIZE, textured_pixels(_SIZE)[1], feature="computer_use", gate=gate)
+
+
+def test_the_background_origin_is_passed_on_when_a_frame_is_refused():
+ gate = FakePermissionService({_SR: "needs_settings"})
+
+ with pytest.raises(ScreenCaptureRefused):
+ verify_frame_is_real(
+ _SIZE,
+ textured_pixels(_SIZE)[1],
+ feature="computer_use",
+ interactive=False,
+ gate=gate,
+ )
+
+ (call,) = gate.ensure_calls(_SR)
+ assert (call.feature, call.interactive, call.wait_s) == ("computer_use", False, 0.0)
+
+
+def test_off_macos_a_frame_reads_no_window_list_and_asks_nothing(monkeypatch):
+ gate = FakePermissionService({_SR: "not_required"})
+ monkeypatch.setattr(
+ screen_access,
+ "_window_evidence",
+ lambda: (_ for _ in ()).throw(AssertionError("no window list off macOS")),
+ )
+
+ verify_frame_is_real(_SIZE, wallpaper_pixels(_SIZE)[1], feature="computer_use", gate=gate)
+
+ assert gate.ensure_calls() == []
+
+
+def test_a_blank_frame_under_a_grant_only_the_oracle_sees_is_still_checked(monkeypatch):
+ # The frozen preflight says "not granted" (BUG-161) but the grant works: the
+ # sanity check must not skip just because the cheap read is stale-negative.
+ gate = _StubGate(
+ [PermissionState.NOT_GRANTED], deep=[PermissionState.GRANTED, PermissionState.GRANTED]
+ )
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (3, 0))
+
+ with pytest.raises(ScreenCaptureRefused):
+ verify_frame_is_real(_SIZE, wallpaper_pixels(_SIZE)[1], feature="computer_use", gate=gate)
+
+
[email protected]("pixels", [wallpaper_pixels, textured_pixels], ids=["flat", "textured"])
+def test_a_frame_with_windows_but_no_readable_title_is_refused(monkeypatch, pixels):
+ # A photographic wallpaper is not a flat frame: the verdict must not wait for blankness.
+ gate = _StubGate([PermissionState.GRANTED], deep=[PermissionState.GRANTED])
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (4, 0))
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ verify_frame_is_real(_SIZE, pixels(_SIZE)[1], feature="computer_use", gate=gate)
+
+ assert refused.value.reason == "needs_settings"
+
+
+ "evidence", [(4, 2), (0, 0), None], ids=["titles", "no_windows", "unknown"]
+)
[email protected]("pixels", [wallpaper_pixels, textured_pixels], ids=["flat", "textured"])
+def test_a_frame_is_accepted_when_the_window_list_does_not_contradict_the_grant(
+ monkeypatch, evidence, pixels
+):
+ gate = _StubGate([PermissionState.GRANTED], deep=[PermissionState.GRANTED])
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: evidence)
+
+ verify_frame_is_real(_SIZE, pixels(_SIZE)[1], feature="computer_use", gate=gate)
+
+ assert gate.log == ["invalidate", "check"]
+
+
+def _restart_hint_result():
+ """What the service answers a failed-use report with: NEEDS_SETTINGS / restart_hint."""
+ from jarvis.platform.permission_service import (
+ EnsureResult,
+ PermissionOutcome,
+ agent_detail_for,
+ user_detail_for,
+ )
+
+ return EnsureResult(
+ permission=_SR,
+ outcome=PermissionOutcome.NEEDS_SETTINGS,
+ state=PermissionState.GRANTED,
+ asked=False,
+ outside_installed_app=False,
+ agent_detail=agent_detail_for(_SR, "restart_hint"),
+ user_detail=user_detail_for(_SR, "restart_hint"),
+ reason="restart_hint",
+ can_open_settings=True,
+ )
+
+
+class _ReportingGate(_StubGate):
+ """A gate that also has the service's failed-use report and its episode reset."""
+
+ def __init__(self, *args, outcome=None, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.outcome = outcome
+ self.reports: list[tuple[PermissionId, str]] = []
+ self.resets: list[PermissionId] = []
+
+ def report_failed_use(self, permission, *, feature, target=None, trace_id=None):
+ self.reports.append((permission, feature))
+ return self.outcome
+
+ def note_reset(self, permission, *, target=None):
+ self.resets.append(permission)
+
+
+def test_an_unusable_grant_reports_the_failed_use_and_refuses_with_the_restart_text(monkeypatch):
+ gate = _ReportingGate(
+ [PermissionState.GRANTED],
+ deep=[PermissionState.GRANTED],
+ outcome=_restart_hint_result(),
+ )
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (4, 0))
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ verify_frame_is_real(_SIZE, textured_pixels(_SIZE)[1], feature="appshot", gate=gate)
+
+ assert gate.reports == [(_SR, "appshot")] # the CALLER's feature, once
+ assert refused.value.reason == "restart_hint"
+ assert str(refused.value).startswith("[permission_needed:screen_recording] ")
+ assert gate.log == ["invalidate", "check"] # no ensure: reporting is not asking
+
+
+def test_a_background_frame_with_an_unusable_grant_reports_nothing(monkeypatch):
+ gate = _ReportingGate([PermissionState.GRANTED], deep=[PermissionState.GRANTED])
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (4, 0))
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ verify_frame_is_real(
+ _SIZE, textured_pixels(_SIZE)[1], feature="appshot", interactive=False, gate=gate
+ )
+
+ assert gate.reports == []
+ assert refused.value.reason == "needs_settings"
+
+
+def test_a_verified_frame_from_any_feature_ends_the_reported_episode_once(monkeypatch):
+ gate = _ReportingGate(
+ [PermissionState.GRANTED],
+ deep=[PermissionState.GRANTED],
+ outcome=_restart_hint_result(),
+ )
+ answers = iter([(4, 0), (4, 2), (4, 2)])
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: next(answers))
+ frame = textured_pixels(_SIZE)[1]
+
+ with pytest.raises(ScreenCaptureRefused):
+ verify_frame_is_real(_SIZE, frame, feature="appshot", gate=gate)
+ # The grant is process-wide: a healthy frame of ANOTHER feature proves it works,
+ # so the episode appshot opened is cleaned up (once, not per frame).
+ verify_frame_is_real(_SIZE, frame, feature="screen_context", gate=gate)
+ verify_frame_is_real(_SIZE, frame, feature="appshot", gate=gate)
+ assert gate.resets == [_SR]
+
+
+def test_a_failing_episode_cleanup_never_fails_a_verified_frame(monkeypatch):
+ class _BrokenReset(_ReportingGate):
+ def note_reset(self, permission): # noqa: ANN001
+ raise RuntimeError("service down")
+
+ gate = _BrokenReset([PermissionState.GRANTED], deep=[PermissionState.GRANTED])
+ screen_access._failed_use_reported.add("appshot")
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (4, 2))
+
+ verify_frame_is_real(_SIZE, textured_pixels(_SIZE)[1], feature="appshot", gate=gate)
+
+ assert screen_access._failed_use_reported == set()
+
+
[email protected]("evidence", [(0, 0), None], ids=["no_windows", "unknown"])
+def test_a_frame_without_proof_does_not_end_the_reported_episode(monkeypatch, evidence):
+ # "No windows" or "no evidence" proves nothing about the grant: the hint stays.
+ gate = _ReportingGate([PermissionState.GRANTED], deep=[PermissionState.GRANTED])
+ screen_access._failed_use_reported.add("appshot")
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: evidence)
+
+ verify_frame_is_real(_SIZE, textured_pixels(_SIZE)[1], feature="appshot", gate=gate)
+
+ assert gate.resets == []
+
+
+def test_a_gate_without_the_failed_use_call_gets_the_plain_refusal(monkeypatch):
+ gate = _StubGate([PermissionState.GRANTED], deep=[PermissionState.GRANTED])
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (4, 0))
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ verify_frame_is_real(_SIZE, textured_pixels(_SIZE)[1], feature="appshot", gate=gate)
+
+ assert refused.value.reason == "needs_settings"
+
+
+def test_the_window_list_is_read_once_per_few_seconds_not_once_per_frame(monkeypatch):
+ gate = _StubGate([PermissionState.GRANTED], deep=[PermissionState.GRANTED])
+ reads: list[int] = []
+ clock = {"now": 100.0}
+
+ def evidence():
+ reads.append(1)
+ return (3, 1)
+
+ monkeypatch.setattr(screen_access, "_window_evidence", evidence)
+ monkeypatch.setattr(screen_access, "_monotonic", lambda: clock["now"])
+ frame = textured_pixels(_SIZE)[1]
+
+ for _ in range(5):
+ verify_frame_is_real(_SIZE, frame, feature="computer_use", gate=gate)
+ assert len(reads) == 1
+
+ clock["now"] += screen_access._EVIDENCE_TTL_S + 0.1
+ verify_frame_is_real(_SIZE, frame, feature="computer_use", gate=gate)
+ assert len(reads) == 2
+
+
+def test_a_flat_frame_accepts_only_a_younger_verdict(monkeypatch):
+ gate = _StubGate([PermissionState.GRANTED], deep=[PermissionState.GRANTED])
+ reads: list[int] = []
+ clock = {"now": 100.0}
+
+ def evidence():
+ reads.append(1)
+ return (3, 1)
+
+ monkeypatch.setattr(screen_access, "_window_evidence", evidence)
+ monkeypatch.setattr(screen_access, "_monotonic", lambda: clock["now"])
+ verify_frame_is_real(_SIZE, textured_pixels(_SIZE)[1], feature="computer_use", gate=gate)
+ clock["now"] += screen_access._BLANK_EVIDENCE_TTL_S + 0.1
+
+ verify_frame_is_real(_SIZE, wallpaper_pixels(_SIZE)[1], feature="computer_use", gate=gate)
+
+ assert len(reads) == 2
+
+
+def test_an_unusable_verdict_is_never_cached_so_a_fixed_grant_is_believed_at_once(monkeypatch):
+ gate = _StubGate([PermissionState.GRANTED], deep=[PermissionState.GRANTED])
+ answers = iter([(4, 0), (4, 2)])
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: next(answers))
+ frame = textured_pixels(_SIZE)[1]
+
+ with pytest.raises(ScreenCaptureRefused):
+ verify_frame_is_real(_SIZE, frame, feature="computer_use", gate=gate)
+ verify_frame_is_real(_SIZE, frame, feature="computer_use", gate=gate) # no raise
+
+
+def test_the_blank_sample_does_not_alias_on_power_of_two_native_sizes():
+ # 2560x1600 sampled with a plain count // 2048 step only ever hit 32 columns: a
+ # frame whose content sits in the other columns read as blank.
+ width, height = 2560, 1600
+ data = bytearray(width * height * 3)
+ for y in range(0, height, 2):
+ for x in range(1, width, 2): # content in odd columns only
+ data[(y * width + x) * 3] = 255
+ assert not frame_is_blank((width, height), bytes(data))
+
+
+def test_the_default_window_evidence_is_none_without_the_native_bridge(monkeypatch):
+ # Hermetic: a real Mac runner ships Quartz, so make the import fail rather
+ # than assume the host has no native bridge. "No evidence", never an exception.
+ import sys
+
+ monkeypatch.setitem(sys.modules, "Quartz", None)
+ assert screen_access._default_window_evidence() is None
diff --git a/tests/unit/platform/test_window_capture_pending.py b/tests/unit/platform/test_window_capture_pending.py
new file mode 100644
index 0000000000..977c876d42
--- /dev/null
+++ b/tests/unit/platform/test_window_capture_pending.py
@@ -0,0 +1,95 @@
+"""A ScreenCaptureKit wait that times out is PENDING, never DENIED, when the state explains it.
+
+On macOS 15+ the first capture may show an OS confirmation (unverified), and the
+shareable-content call then waits for the user. The seam must not read that as a
+denial: when the live Screen Recording read says granted, or a request is in
+flight, the reason is ``pending_confirmation``; otherwise it is a plain
+``timeout`` (still not a denial). The framework is a hand-written stub whose
+completion handler never fires; the permission state comes from the REAL service
+on ``FakeTCC``. Nothing here ran on a real Mac.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+import types
+
+import pytest
+
+from jarvis.platform import window_capture
+from jarvis.platform.permission_service import get_permission_service
+from jarvis.platform.permissions import PermissionId
+from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, TccService, install_port
+
+_BBOX = {"left": 0, "top": 0, "width": 80, "height": 60}
+
+
+def silent_sck(monkeypatch):
+ """A ScreenCaptureKit whose shareable-content handler never fires (a dialog is up)."""
+
+ class _Content:
+ @staticmethod
+ def getShareableContentWithCompletionHandler_(_handler): # noqa: N802 - Cocoa selector
+ return None # never calls back
+
+ sck = types.SimpleNamespace(SCScreenshotManager=object(), SCShareableContent=_Content)
+ appkit = types.SimpleNamespace(NSBitmapImageRep=object())
+ monkeypatch.setitem(sys.modules, "ScreenCaptureKit", sck)
+ monkeypatch.setitem(sys.modules, "AppKit", appkit)
+ monkeypatch.setattr(window_capture, "detect_platform", lambda: "darwin")
+ monkeypatch.setattr(window_capture, "_SCK_TIMEOUT_S", 0.01)
+
+
+def _darwin(monkeypatch, **kwargs) -> FakeTCC:
+ tcc = FakeTCC(**kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
+
+
+def test_timeout_with_a_live_grant_is_pending_confirmation(monkeypatch, silent_sck, caplog):
+ _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING])
+
+ with caplog.at_level(logging.INFO, logger=window_capture.log.name):
+ assert window_capture.grab_window(7, _BBOX) is None
+
+ assert window_capture.last_grab_failure() == "pending_confirmation"
+ assert "may be asking you to confirm" in caplog.text
+
+
+def test_timeout_while_a_request_is_in_flight_is_pending_confirmation(monkeypatch, silent_sck):
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ get_permission_service().ensure(PermissionId.SCREEN_RECORDING, feature="computer_use", wait_s=0)
+ assert tcc.dialog_open(TccService.SCREEN_RECORDING)
+
+ assert window_capture.grab_window(7, _BBOX) is None
+
+ assert window_capture.last_grab_failure() == "pending_confirmation"
+
+
+def test_timeout_nothing_explains_is_a_plain_timeout_not_a_denial(monkeypatch, silent_sck):
+ tcc = _darwin(monkeypatch) # never asked, not granted
+ mark = tcc.mark()
+
+ assert window_capture.grab_window(7, _BBOX) is None
+
+ assert window_capture.last_grab_failure() == "timeout"
+ assert tcc.calls_of("request", since=mark) == []
+
+
+def test_the_classification_never_asks(monkeypatch, silent_sck):
+ tcc = _darwin(monkeypatch)
+
+ window_capture.grab_window(7, _BBOX)
+
+ tcc.assert_no_prompts()
+
+
+def test_a_later_grab_clears_the_previous_reason(monkeypatch):
+ window_capture._failure.reason = "pending_confirmation"
+ monkeypatch.setattr(window_capture, "detect_platform", lambda: "linux")
+
+ window_capture.grab_window(7, _BBOX)
+
+ assert window_capture.last_grab_failure() == ""
diff --git a/tests/unit/platform/test_window_state.py b/tests/unit/platform/test_window_state.py
index f172a8447e..4067acdb39 100644
--- a/tests/unit/platform/test_window_state.py
+++ b/tests/unit/platform/test_window_state.py
@@ -20,21 +20,21 @@ def _cp(returncode: int, stdout: str = "", stderr: str = ""):
return types.SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)
-def _patch_macos_accessibility(monkeypatch, *, granted: bool) -> None:
- from jarvis.platform.permissions import PermissionState
-
- port = types.SimpleNamespace(
- runtime_access_granted=lambda _permission_id: granted,
- state=lambda _permission_id: (
- PermissionState.GRANTED
- if granted
- else PermissionState.NOT_GRANTED
- ),
- )
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: port,
+def _patch_macos_accessibility(monkeypatch, *, granted: bool):
+ """A darwin FakeTCC behind the REAL port; the process-wide service sits on it.
+
+ ``granted=False`` leaves the Accessibility dialog unanswered: "the user has not
+ allowed it yet". Returns the FakeTCC so a test can read what macOS was asked.
+ Nothing here ran on a real Mac; FakeTCC models the OS.
+ """
+ from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, install_port
+
+ tcc = FakeTCC(
+ granted=("accessibility",) if granted else (),
+ default_policy=DialogPolicy.NEVER_ANSWERED,
)
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
# --- WindowInfo basics ------------------------------------------------------
@@ -746,16 +746,65 @@ def test_resolve_macos_ax_window_uses_bounds_for_duplicate_titles(monkeypatch):
assert target is second
-def test_maximize_window_macos_fails_closed_without_accessibility(monkeypatch):
+def test_maximize_window_macos_asks_once_and_refuses_without_accessibility(monkeypatch):
+ """Maximizing is an ACTION: it asks macOS, and only a live grant proceeds."""
monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")
- _patch_macos_accessibility(monkeypatch, granted=False)
- services = types.SimpleNamespace(AXIsProcessTrusted=lambda: False)
- monkeypatch.setitem(sys.modules, "ApplicationServices", services)
+ tcc = _patch_macos_accessibility(monkeypatch, granted=False)
+ writes: list[str] = []
+ monkeypatch.setitem(sys.modules, "ApplicationServices", types.SimpleNamespace(
+ AXUIElementSetAttributeValue=lambda _el, attr, _value: writes.append(attr) or 0,
+ ))
ok, message = ws.maximize_window(WindowInfo("notes.txt", handle=77))
+ ok_again, _message_again = ws.maximize_window(WindowInfo("notes.txt", handle=77))
- assert ok is False
- assert "Accessibility" in message
+ assert ok is False and ok_again is False
+ assert message.startswith("[permission_needed:accessibility] ")
+ assert "Settings > Permissions" not in message
+ assert len(tcc.requests("accessibility")) == 1
+ assert writes == [] # nothing acted
+
+
+def test_window_reads_never_ask_macos_for_accessibility(monkeypatch):
+ """Listing windows and reading the maximized state are background reads."""
+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")
+ tcc = _patch_macos_accessibility(monkeypatch, granted=False)
+ monkeypatch.setattr(
+ ws,
+ "_quartz_window_list",
+ lambda **_kwargs: [{
+ "kCGWindowLayer": 0,
+ "kCGWindowName": "notes.txt",
+ "kCGWindowOwnerPID": 42,
+ "kCGWindowNumber": 9,
+ }],
+ )
+ monkeypatch.setitem(sys.modules, "ApplicationServices", types.SimpleNamespace(
+ AXUIElementCreateApplication=lambda _pid: object(),
+ AXUIElementCopyAttributeValue=lambda *_args: (1, None),
+ ))
+
+ windows = ws.list_windows()
+ maximized = ws.window_is_maximized(WindowInfo("notes.txt", handle=9, pid=42))
+
+ assert [w.title for w in windows] == ["notes.txt"] # listing stays ungated
+ assert maximized is None # cannot be read without the grant
+ assert tcc.requests() == []
+ assert tcc.implicit_prompts() == []
+
+
+def test_window_control_off_macos_never_touches_the_permission_layer(monkeypatch):
+ from tests.fakes.fake_tcc import FakeTCC, install_port
+
+ tcc = FakeTCC()
+ install_port(monkeypatch, tcc.port("linux"))
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "is_wayland", lambda: True)
+
+ ws.maximize_window(WindowInfo("notes.txt", handle=77))
+ ws.focus_window("notes")
+
+ tcc.assert_silent()
# --- real smoke on the host platform (non-deterministic, just must not crash)
diff --git a/tests/unit/plugins/tool/test_hotkey_tool.py b/tests/unit/plugins/tool/test_hotkey_tool.py
index 7c7f201a83..3fd843d379 100644
--- a/tests/unit/plugins/tool/test_hotkey_tool.py
+++ b/tests/unit/plugins/tool/test_hotkey_tool.py
@@ -152,3 +152,22 @@ async def test_screenshot_bound_hotkey_refuses_changed_foreground(monkeypatch):
assert result.success is False
assert "foreground window changed" in (result.error or "")
assert sent == []
+
+
+async def test_macos_permission_refusal_reaches_the_agent_with_the_stable_prefix(monkeypatch):
+ """The flat tool body is unchanged: the new exception rides the old error mapping."""
+ from jarvis.cu.actuate.base import PermissionNeededError
+ from jarvis.platform.permissions import PermissionId
+ from tests.fakes.fake_permission_service import make_result
+
+ def _refused():
+ raise PermissionNeededError(make_result(PermissionId.ACCESSIBILITY, "needs_settings"))
+
+ monkeypatch.setattr(hk.os, "name", "posix")
+ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", _refused)
+
+ result = await HotkeyTool().execute({"keys": ["cmd", "a"]}, _Ctx())
+
+ assert result.success is False
+ assert result.error.startswith("[permission_needed:accessibility] ")
+ assert "must not retry" in result.error # prohibitive: the model must not loop on it
diff --git a/tests/unit/plugins/tool/test_screen_snapshot.py b/tests/unit/plugins/tool/test_screen_snapshot.py
index fe5a70a030..2a89450599 100644
--- a/tests/unit/plugins/tool/test_screen_snapshot.py
+++ b/tests/unit/plugins/tool/test_screen_snapshot.py
@@ -1,52 +1,43 @@
-"""ScreenSnapshotTool honesty on macOS without the Screen-Recording grant.
-
-Audit finding 2026-07-06: without the TCC grant, mss "succeeds" but captures
-only the desktop wallpaper — the tool then returned success=True with a
-useless image and the model analyzed a wallpaper as if it were the screen.
-The tool must refuse honestly with the actionable permission message instead.
+"""ScreenSnapshotTool: asks for Screen Recording on the gesture, never returns wallpaper.
+
+Audit finding 2026-07-06: without the TCC grant, mss "succeeds" but captures only the
+desktop wallpaper - the tool then returned success=True with a useless image and the
+model analyzed a wallpaper as if it were the screen. The tool body is the gesture
+entry of a capture a person asked for, so it ASKS macOS (once per episode, through the
+permission service) instead of refusing on its own preflight, only a live GRANTED
+captures, and any refusal is an honest, prohibitive error naming the permission.
+
+The REAL permission service runs on a REAL ``SystemPermissionPort`` that sits on
+``FakeTCC``; its call log is the proof of what was (not) asked. Nothing here ran on
+a real Mac (see the fidelity ledger in ``tests/fakes/fake_tcc.py``).
"""
from __future__ import annotations
+import sys
+import types
from types import SimpleNamespace
import pytest
+from jarvis.platform.permission_service import get_permission_service
from jarvis.plugins.tool.screen_snapshot import ScreenSnapshotTool
+from tests.fakes.fake_screen_pixels import textured_pixels, wallpaper_pixels
+from tests.fakes.fake_tcc import (
+ DialogPolicy,
+ FakeTCC,
+ TccService,
+ install_port,
+ make_non_darwin_port,
+)
+_SIZE = (8, 8)
-async def test_macos_screen_recording_denied_is_honest_failure(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(
- "jarvis.plugins.tool.screen_snapshot.warn_if_screen_recording_denied",
- lambda: True,
- )
-
- res = await ScreenSnapshotTool().execute({}, SimpleNamespace())
-
- assert res.success is False
- assert "Screen Recording" in (res.error or "")
- assert not getattr(res, "artifacts", ())
-
-
-async def test_grant_present_does_not_block(monkeypatch: pytest.MonkeyPatch) -> None:
- """With the grant present (probe returns False) the capture path runs.
- The mss grab itself is faked so the test works on headless CI."""
- monkeypatch.setattr(
- "jarvis.plugins.tool.screen_snapshot.warn_if_screen_recording_denied",
- lambda: False,
- )
-
- class _FakeShot:
- size = (4, 4)
- rgb = b"\x10\x20\x30" * 16
+def _fake_mss(monkeypatch: pytest.MonkeyPatch, frame: tuple[tuple[int, int], bytes]) -> None:
class _FakeSct:
monitors = [
{"left": 0, "top": 0, "width": 8, "height": 8},
- {"left": 0, "top": 0, "width": 4, "height": 4},
+ {"left": 0, "top": 0, "width": 8, "height": 8},
]
def __enter__(self):
@@ -56,19 +47,123 @@ async def test_grant_present_does_not_block(monkeypatch: pytest.MonkeyPatch) ->
return False
def grab(self, target):
- return _FakeShot()
-
- import sys
- import types
+ size, rgb = frame
+ return SimpleNamespace(size=size, rgb=rgb)
- fake_mss = types.SimpleNamespace(mss=lambda: _FakeSct())
- monkeypatch.setitem(sys.modules, "mss", fake_mss)
+ monkeypatch.setitem(sys.modules, "mss", types.SimpleNamespace(mss=lambda: _FakeSct()))
monkeypatch.setattr(
"jarvis.plugins.tool.screen_snapshot.select_capture_monitor",
lambda monitors, strategy="foreground": monitors[1],
)
+
+def _darwin(monkeypatch: pytest.MonkeyPatch, **kwargs) -> FakeTCC:
+ tcc = FakeTCC(**kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
+
+
+async def test_not_determined_asks_once_and_refuses_while_the_dialog_is_open(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ _fake_mss(monkeypatch, textured_pixels(_SIZE))
+
+ first = await ScreenSnapshotTool().execute({}, SimpleNamespace())
+ second = await ScreenSnapshotTool().execute({}, SimpleNamespace())
+
+ assert first.success is False and second.success is False
+ assert (first.error or "").startswith("[permission_needed:screen_recording] ")
+ assert "must not" in (first.error or "") # prohibitive: the model never answers the dialog
+ assert not getattr(first, "artifacts", ())
+ # The gesture asked exactly once across two attempts; the capture never ran.
+ assert len(tcc.requests(TccService.SCREEN_RECORDING)) == 1
+ assert tcc.implicit_prompts() == []
+
+
+async def test_a_denial_is_stable_and_never_asked_again(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.DENY)
+ _fake_mss(monkeypatch, textured_pixels(_SIZE))
+
+ first = await ScreenSnapshotTool().execute({}, SimpleNamespace())
+ second = await ScreenSnapshotTool().execute({}, SimpleNamespace())
+
+ assert first.success is False and second.success is False
+ assert len(tcc.requests(TccService.SCREEN_RECORDING)) == 1
+ assert tcc.ignored_requests() == []
+
+
+async def test_the_user_allowing_it_lets_the_capture_proceed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.ALLOW)
+ _fake_mss(monkeypatch, textured_pixels(_SIZE))
+
+ # The frozen preflight may keep the ask itself refused (the grant is only visible
+ # to the window-title oracle a moment later); the call after it must go through
+ # with no second request.
+ first = await ScreenSnapshotTool().execute({"reason": "test"}, SimpleNamespace())
+ res = first if first.success else await ScreenSnapshotTool().execute(
+ {"reason": "test"}, SimpleNamespace()
+ )
+
+ assert res.success is True
+ assert res.artifacts and res.artifacts[0]["type"] == "image"
+ assert len(tcc.requests(TccService.SCREEN_RECORDING)) == 1
+
+
+async def test_grant_present_does_not_block_and_asks_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING])
+ _fake_mss(monkeypatch, textured_pixels(_SIZE))
+
res = await ScreenSnapshotTool().execute({"reason": "test"}, SimpleNamespace())
assert res.success is True
assert res.artifacts and res.artifacts[0]["type"] == "image"
+ tcc.assert_no_prompts()
+
+
+async def test_a_wallpaper_frame_after_a_revoke_is_an_error_and_an_episode(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING], preflight_frozen=())
+ service = get_permission_service()
+ assert service.check("screen_recording").value == "granted" # warms the 1 s cache
+ _fake_mss(monkeypatch, wallpaper_pixels(_SIZE))
+ # The user revokes in System Settings between the entry read and the grab.
+ real_grab = sys.modules["mss"].mss
+
+ def revoking_mss():
+ tcc.deny(TccService.SCREEN_RECORDING)
+ return real_grab()
+
+ sys.modules["mss"].mss = revoking_mss # type: ignore[attr-defined]
+
+ res = await ScreenSnapshotTool().execute({}, SimpleNamespace())
+
+ assert res.success is False
+ assert (res.error or "").startswith("[permission_needed:screen_recording] ")
+ assert not getattr(res, "artifacts", ())
+ assert [e.feature for e in service.outstanding()] == ["screen_context"]
+ assert tcc.dialogs_shown() == []
+
+
+async def test_non_darwin_is_unchanged_and_reads_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ _fake_mss(monkeypatch, wallpaper_pixels(_SIZE)) # a flat frame is fine off macOS
+
+ res = await ScreenSnapshotTool().execute({"reason": "test"}, SimpleNamespace())
+
+ assert res.success is True
+ tcc.assert_silent()
diff --git a/tests/unit/plugins/tool/test_switch_window.py b/tests/unit/plugins/tool/test_switch_window.py
index b8991d2e33..0dc2d9ee4b 100644
--- a/tests/unit/plugins/tool/test_switch_window.py
+++ b/tests/unit/plugins/tool/test_switch_window.py
@@ -33,6 +33,23 @@ def _ctx() -> ExecutionContext:
# --- macOS (Quartz/AppKit/AX) ----------------------------------------------
+def _macos_permission_world(monkeypatch, *, trusted: bool):
+ """A darwin FakeTCC behind the REAL port; the process-wide service sits on it.
+
+ ``trusted=False`` leaves the Accessibility dialog on screen unanswered, so a
+ refusal is "the user has not allowed it yet". Nothing here ran on a real Mac:
+ FakeTCC models the OS.
+ """
+ from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, install_port
+
+ tcc = FakeTCC(
+ granted=("accessibility",) if trusted else (),
+ default_policy=DialogPolicy.NEVER_ANSWERED,
+ )
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
+
+
def _install_fake_macos_apis(
monkeypatch,
*,
@@ -40,9 +57,8 @@ def _install_fake_macos_apis(
minimized=False,
activate_result=True,
set_attr_error=None,
+ tcc=None,
):
- from jarvis.platform.permissions import PermissionState
-
ax_window = object()
ax_root = object()
calls: list[tuple] = []
@@ -82,18 +98,8 @@ def _install_fake_macos_apis(
)
monkeypatch.setitem(sys.modules, "AppKit", appkit)
monkeypatch.setitem(sys.modules, "ApplicationServices", services)
- permission_port = types.SimpleNamespace(
- runtime_access_granted=lambda _permission_id: trusted,
- state=lambda _permission_id: (
- PermissionState.GRANTED
- if trusted
- else PermissionState.NOT_GRANTED
- ),
- )
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: permission_port,
- )
+ if tcc is None:
+ _macos_permission_world(monkeypatch, trusted=trusted)
return calls
@@ -189,15 +195,43 @@ def test_macos_focus_fails_when_raise_and_frontmost_both_fail(monkeypatch):
assert "refused to focus" in msg
-def test_macos_accessibility_denied_message(monkeypatch):
- _install_fake_macos_apis(monkeypatch, trusted=False)
+def test_macos_focus_without_accessibility_asks_once_and_refuses_with_the_prefix(monkeypatch):
+ """Focusing is an ACTION: the first one asks macOS; nothing is raised until GRANTED."""
+ tcc = _macos_permission_world(monkeypatch, trusted=False)
+ calls = _install_fake_macos_apis(monkeypatch, trusted=False, tcc=tcc)
monkeypatch.setattr(
"jarvis.platform.window_state._quartz_window_list",
lambda **_kwargs: [_mac_window()],
)
+
found, msg = _find_and_focus_macos("Editor")
- assert found is False
- assert "Accessibility" in msg
+ again, _msg_again = _find_and_focus_macos("Editor")
+
+ assert found is False and again is False
+ assert msg.startswith("[permission_needed:accessibility] ")
+ assert "must not retry" in msg
+ assert len(tcc.requests("accessibility")) == 1 # the second call is inside the cooldown
+ assert not [call for call in calls if call[0] in ("perform", "set")] # nothing was touched
+ assert tcc.implicit_prompts() == []
+
+
+def test_macos_focus_the_dialog_answer_is_picked_up_without_a_restart(monkeypatch):
+ tcc = _macos_permission_world(monkeypatch, trusted=False)
+ calls = _install_fake_macos_apis(monkeypatch, trusted=False, tcc=tcc)
+ monkeypatch.setattr(
+ "jarvis.platform.window_state._quartz_window_list",
+ lambda **_kwargs: [_mac_window()],
+ )
+ assert _find_and_focus_macos("Editor")[0] is False
+
+ tcc.answer("accessibility") # the user flips the switch
+ from jarvis.platform.permission_service import get_permission_service
+
+ get_permission_service().invalidate()
+ found, msg = _find_and_focus_macos("Editor")
+
+ assert found is True and msg == "My Editor"
+ assert ("perform", "AXRaise") in calls
def test_macos_missing_native_frameworks(monkeypatch):
diff --git a/tests/unit/plugins/tool/test_type_text.py b/tests/unit/plugins/tool/test_type_text.py
index ec01e31789..144e1a9490 100644
--- a/tests/unit/plugins/tool/test_type_text.py
+++ b/tests/unit/plugins/tool/test_type_text.py
@@ -104,6 +104,32 @@ async def test_screenshot_bound_typing_refuses_changed_foreground(monkeypatch):
assert typed == []
+async def test_macos_permission_refusal_keeps_its_prefix_at_the_start(monkeypatch):
+ """The engine maps the "[permission_needed:" prefix: type_text must not wrap it."""
+ from jarvis.cu.actuate.base import ActuationUnavailable, PermissionNeededError
+ from jarvis.platform.permissions import PermissionId
+ from tests.fakes.fake_permission_service import make_result
+
+ def _refused():
+ raise PermissionNeededError(make_result(PermissionId.ACCESSIBILITY, "needs_settings"))
+
+ monkeypatch.setattr(tt.os, "name", "posix")
+ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", _refused)
+
+ result = await TypeTextTool().execute({"text": "hello"}, _Ctx())
+
+ assert result.success is False
+ assert result.error.startswith("[permission_needed:accessibility] ")
+
+ # Any other actuation failure keeps the old wrapping.
+ def _headless():
+ raise ActuationUnavailable("no display")
+
+ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", _headless)
+ other = await TypeTextTool().execute({"text": "hello"}, _Ctx())
+ assert other.error == "text input unavailable: no display"
+
+
# ---------------------------------------------------------------------------
# RC#1 regression (Google-Flights typing bug, 2026-06-22): the SendInput INPUT
# union must be sized to its LARGEST member (MOUSEINPUT). If it only carries
diff --git a/tests/unit/plugins/tool/test_verify_localhost.py b/tests/unit/plugins/tool/test_verify_localhost.py
index 79f32adcae..4c0f16607e 100644
--- a/tests/unit/plugins/tool/test_verify_localhost.py
+++ b/tests/unit/plugins/tool/test_verify_localhost.py
@@ -105,27 +105,125 @@ async def test_http_call_is_offloaded_via_to_thread(
assert recorder.calls[0][0] is httpx.get
-async def test_screenshot_refuses_capture_when_screen_recording_is_blocked(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A wallpaper-only macOS capture must never be reported as evidence."""
+def _http_ok(monkeypatch: pytest.MonkeyPatch) -> None:
import httpx
monkeypatch.setattr(
httpx, "get", lambda *_a, **_k: _FakeResponse(status_code=200, text="hi")
)
- monkeypatch.setattr(
- "jarvis.vision.screenshot.warn_if_screen_recording_denied",
- lambda: True,
- )
+
+
+async def test_screenshot_degrades_honestly_and_never_asks_when_screen_recording_is_off(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The screenshot is an optional extra, not a gesture: it reads the state silently.
+
+ A wallpaper-only macOS capture must never be reported as evidence, and the
+ degradation carries the prohibitive permission text. The REAL permission
+ service runs on ``FakeTCC``; its call log proves nothing was requested.
+ """
+ from tests.fakes.fake_tcc import FakeTCC, install_port
+
+ _http_ok(monkeypatch)
+ tcc = FakeTCC()
+ install_port(monkeypatch, tcc.port("darwin"))
tool = VerifyLocalhostTool()
- result = await tool.execute(
- {"port": 5173, "take_screenshot": True}, ctx=None
- )
+ result = await tool.execute({"port": 5173, "take_screenshot": True}, ctx=None)
assert result.success is True
assert result.artifacts
error = result.artifacts[0]["screenshot_error"]
- assert "Screen Recording permission is not granted" in error
+ assert error.startswith("[permission_needed:screen_recording] ")
+ assert "must not" in error
+ assert "screenshot_path" not in result.artifacts[0]
+ tcc.assert_no_prompts()
+
+
+def _install_fake_mss(monkeypatch: pytest.MonkeyPatch, pixels, saved: list[str]) -> None:
+ import sys
+ import types
+
+ size, rgb = pixels
+
+ class _Raw:
+ pass
+
+ raw = _Raw()
+ raw.size = size # type: ignore[attr-defined]
+ raw.rgb = rgb # type: ignore[attr-defined]
+
+ class _Sct:
+ monitors = [{"left": 0, "top": 0, "width": size[0], "height": size[1]}] * 2
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ return False
+
+ def grab(self, _monitor):
+ return raw
+
+ def to_png(_rgb, _size, output):
+ saved.append(output)
+
+ fake_mss = types.ModuleType("mss")
+ fake_mss.mss = _Sct # type: ignore[attr-defined]
+ fake_mss.tools = types.ModuleType("mss.tools") # type: ignore[attr-defined]
+ fake_mss.tools.to_png = to_png # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "mss", fake_mss)
+ monkeypatch.setitem(sys.modules, "mss.tools", fake_mss.tools)
+
+
+async def test_screenshot_is_taken_when_the_grant_is_live(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jarvis.platform import screen_access
+ from tests.fakes.fake_screen_pixels import textured_pixels
+ from tests.fakes.fake_tcc import FakeTCC, TccService, install_port
+
+ _http_ok(monkeypatch)
+ screen_access.reset_window_evidence_cache()
+ tcc = FakeTCC(granted=[TccService.SCREEN_RECORDING])
+ install_port(monkeypatch, tcc.port("darwin"))
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (3, 2))
+ saved: list[str] = []
+ _install_fake_mss(monkeypatch, textured_pixels((64, 36)), saved)
+
+ result = await VerifyLocalhostTool().execute({"port": 5173, "take_screenshot": True}, ctx=None)
+
+ assert result.artifacts == ({"screenshot_path": "monitor-1.png"},)
+ assert saved == ["monitor-1.png"]
+ tcc.assert_no_prompts()
+
+
+async def test_a_wallpaper_screenshot_is_never_evidence_even_when_the_state_says_granted(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The grab is pixel-checked: a photographic wallpaper is not a screenshot."""
+ from jarvis.platform import screen_access
+ from tests.fakes.fake_screen_pixels import photo_wallpaper_pixels
+ from tests.fakes.fake_tcc import FakeTCC, TccService, install_port
+
+ _http_ok(monkeypatch)
+ screen_access.reset_window_evidence_cache()
+ tcc = FakeTCC(granted=[TccService.SCREEN_RECORDING])
+ install_port(monkeypatch, tcc.port("darwin"))
+ # Other apps' windows are on screen and none has a readable title: the grant
+ # is not usable although the preflight says granted.
+ monkeypatch.setattr(screen_access, "_window_evidence", lambda: (2, 0))
+ saved: list[str] = []
+ _install_fake_mss(monkeypatch, photo_wallpaper_pixels((64, 36)), saved)
+
+ result = await VerifyLocalhostTool().execute({"port": 5173, "take_screenshot": True}, ctx=None)
+
+ assert result.artifacts
+ assert result.artifacts[0]["screenshot_error"].startswith(
+ "[permission_needed:screen_recording] "
+ )
+ assert saved == []
+ tcc.assert_no_prompts()
diff --git a/tests/unit/screen_context/test_ports_pending_confirmation.py b/tests/unit/screen_context/test_ports_pending_confirmation.py
new file mode 100644
index 0000000000..7f36be9b2d
--- /dev/null
+++ b/tests/unit/screen_context/test_ports_pending_confirmation.py
@@ -0,0 +1,119 @@
+"""A native window capture that times out while macOS may be asking is PENDING.
+
+The REAL permission service runs on ``FakeTCC`` (a stateful model of macOS privacy);
+``grab_window`` is a hand-written stub that records the failure reason the way the
+real ScreenCaptureKit path does. Nothing here ran on a real Mac.
+
+* With a request still open (macOS may be showing its dialog) the capture is refused
+ with the "may be showing a dialog" text, takes NO rect grab of the wallpaper and
+ asks for nothing new.
+* With a live grant the rect grab is the safe fallback and carries on.
+* A plain timeout that the state does not explain refuses with the state's text.
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+from contextlib import nullcontext
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.platform import window_capture
+from jarvis.platform.permission_service import get_permission_service
+from jarvis.platform.permissions import PermissionId
+from jarvis.screen_context import ports
+from tests.fakes.fake_screen_pixels import textured_pixels
+from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, TccService, install_port
+
+_SR = PermissionId.SCREEN_RECORDING
+_BBOX = (0, 0, 80, 60)
+
+
+class _Raw:
+ def __init__(self, size: tuple[int, int], rgb: bytes) -> None:
+ self.size = size
+ self.rgb = rgb
+
+
+def _install_mss(monkeypatch: pytest.MonkeyPatch, grabs: list[dict[str, int]]) -> None:
+ """A stand-in ``mss`` whose rect grab is recorded and returns real-looking pixels."""
+ size, rgb = textured_pixels((80, 60))
+
+ class _Sct:
+ def __enter__(self) -> _Sct:
+ return self
+
+ def __exit__(self, *_exc: object) -> bool:
+ return False
+
+ def grab(self, bbox: dict[str, int]) -> _Raw:
+ grabs.append(dict(bbox))
+ return _Raw(size, rgb)
+
+ module = types.ModuleType("mss")
+ module.mss = _Sct # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "mss", module)
+
+
+def _native_fails_with(monkeypatch: pytest.MonkeyPatch, reason: str) -> None:
+ def native(_handle: int, _bbox: dict[str, int]) -> None:
+ window_capture._failure.reason = reason
+ return None
+
+ monkeypatch.setattr(window_capture, "grab_window", native)
+ # The rect fallback is refused on Windows by design (ports.py branches on os.name):
+ # these tests model a Mac, so they must not depend on the host OS.
+ monkeypatch.setattr(ports, "os", SimpleNamespace(name="posix"))
+ monkeypatch.setattr(ports, "_is_wayland", lambda: False)
+ monkeypatch.setattr(ports, "_input_space", nullcontext)
+ monkeypatch.setattr("jarvis.cu.indicator.capture_guard.indicator_suppressed", nullcontext)
+
+
+def _darwin(monkeypatch: pytest.MonkeyPatch, **kwargs) -> FakeTCC:
+ tcc = FakeTCC(**kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
+
+
+def test_a_timeout_while_a_request_is_open_is_pending_not_denied(monkeypatch):
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ get_permission_service().ensure(_SR, feature="screen_context", wait_s=0)
+ assert tcc.dialog_open(TccService.SCREEN_RECORDING)
+ grabs: list[dict[str, int]] = []
+ _install_mss(monkeypatch, grabs)
+ _native_fails_with(monkeypatch, "pending_confirmation")
+
+ with pytest.raises(ports.CaptureUnavailable) as refused:
+ ports.NativeSurfaceCapturer().grab(_BBOX, window_handle=9)
+
+ assert "macOS may be showing a dialog" in str(refused.value)
+ assert "denied" not in str(refused.value).lower()
+ assert grabs == [] # no rect grab of what would be the wallpaper
+ assert len(tcc.requests()) == 1 # nothing new was asked
+
+
+def test_a_timeout_with_a_live_grant_falls_through_to_the_rect_grab(monkeypatch):
+ tcc = _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING])
+ grabs: list[dict[str, int]] = []
+ _install_mss(monkeypatch, grabs)
+ _native_fails_with(monkeypatch, "pending_confirmation")
+
+ (width, height), rgb = ports.NativeSurfaceCapturer().grab(_BBOX, window_handle=9)
+
+ assert (width, height) == (80, 60) and rgb
+ assert grabs == [{"left": 0, "top": 0, "width": 80, "height": 60}]
+ tcc.assert_no_prompts()
+
+
+def test_a_failure_that_is_not_a_timeout_never_looks_at_the_permission(monkeypatch):
+ tcc = _darwin(monkeypatch)
+ grabs: list[dict[str, int]] = []
+ _install_mss(monkeypatch, grabs)
+ _native_fails_with(monkeypatch, "")
+
+ ports.NativeSurfaceCapturer().grab(_BBOX, window_handle=9)
+
+ assert len(grabs) == 1
+ tcc.assert_no_prompts()
diff --git a/tests/unit/screen_context/test_service.py b/tests/unit/screen_context/test_service.py
index b8177766b1..2ff61dac41 100644
--- a/tests/unit/screen_context/test_service.py
+++ b/tests/unit/screen_context/test_service.py
@@ -433,18 +433,27 @@ async def test_monitor_capture_fails_closed_when_denylist_cannot_be_verified() -
assert "could not be verified" in (outcome.message or "")
-async def test_missing_permission_refuses_before_capturing() -> None:
+async def test_missing_permission_asks_once_then_refuses_before_capturing() -> None:
+ from tests.fakes.fake_permission_service import FakePermissionService
+
capturer = FakeCapturer()
+ gate = FakePermissionService({"screen_recording": "needs_settings"})
service = make_service(
capturer=capturer,
permission_probe=lambda: "Screen recording permission is missing.",
+ permission_gate=gate,
)
outcome = await service.capture_for_turn("look at this", locale="en")
assert outcome.status == "refused"
assert capturer.grabs == []
- assert "permission" in (outcome.message or "").lower()
+ assert "permission" in (outcome.message or "").lower() or "Screen Recording" in (
+ outcome.message or ""
+ )
+ # The capture a person started is the gesture: it asked, once, and only a live
+ # grant lets it go on (the probe never decides).
+ assert len(gate.ensure_calls("screen_recording")) == 1
async def test_disabled_feature_refuses_honestly() -> None:
diff --git a/tests/unit/screen_context/test_service_permissions.py b/tests/unit/screen_context/test_service_permissions.py
new file mode 100644
index 0000000000..0561dc206d
--- /dev/null
+++ b/tests/unit/screen_context/test_service_permissions.py
@@ -0,0 +1,342 @@
+"""Screen Context and the Screen Recording permission (just-in-time).
+
+A capture a person starts (a spoken request, the bar button, an appshot gesture) is
+the moment macOS is asked: ``ScreenContextService.capture`` asks through the
+permission service, once per episode, and only a live GRANTED captures. The status
+probes (``capture_permission_error``, ``accessibility_permission_error``) are SILENT:
+they describe, they never ask. A frame that is wallpaper-only while the state claims
+GRANTED is never a success.
+
+The REAL permission service runs on a REAL ``SystemPermissionPort`` that sits on
+``FakeTCC`` (a stateful model of macOS privacy); its call log is the proof of what was
+(not) asked. Nothing here ran on a real Mac (see the fidelity ledger in
+``tests/fakes/fake_tcc.py``).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.platform.permission_service import get_permission_service
+from jarvis.screen_context import ports
+from jarvis.screen_context.models import WindowFacts
+from jarvis.screen_context.ports import CapturePermissionIssue, WindowSnapshot
+from jarvis.screen_context.service import ScreenContextService, ScreenContextSettings
+from tests.fakes.fake_permission_service import FakePermissionService
+from tests.fakes.fake_screen_pixels import textured_pixels, wallpaper_pixels
+from tests.fakes.fake_tcc import (
+ DialogPolicy,
+ FakeTCC,
+ TccService,
+ install_port,
+ make_non_darwin_port,
+)
+
+
[email protected](autouse=True)
+def _no_real_wayland(monkeypatch):
+ monkeypatch.setattr(ports, "_is_wayland", lambda: False)
+
+
+_MONITORS = [
+ {"left": 0, "top": 0, "width": 320, "height": 240, "name": "virtual"},
+ {"left": 0, "top": 0, "width": 320, "height": 240, "name": "primary"},
+]
+
+
+class _Cursor:
+ name = "fake-cursor"
+
+ def position(self):
+ return (100, 100)
+
+
+class _Displays:
+ name = "fake-displays"
+
+ def monitors(self):
+ return list(_MONITORS)
+
+
+class _Window:
+ name = "fake-window"
+
+ def foreground_snapshot(self):
+ facts = WindowFacts(
+ app_name="editor", title="notes.md", pid=42, frame_rect=(0, 0, 320, 240)
+ )
+ return WindowSnapshot(facts, 7)
+
+
+class _Capturer:
+ """Records every grab; ``frame`` produces the pixels, ``before_grab`` runs first."""
+
+ name = "fake-capture"
+
+ def __init__(self, frame=None, before_grab=None) -> None:
+ self.grabs: list[tuple] = []
+ self._frame = frame or (lambda: textured_pixels((64, 48)))
+ self._before = before_grab
+
+ def grab(self, bbox, *, window_handle=None):
+ self.grabs.append((tuple(bbox), window_handle))
+ if self._before is not None:
+ self._before()
+ return self._frame()
+
+
+class _Text:
+ name = "fake-text"
+
+ async def read(self, *, window_title_filter=None):
+ return None
+
+
+def _service(capturer=None, **overrides) -> ScreenContextService:
+ kwargs = {
+ "settings": ScreenContextSettings(),
+ "cursor": _Cursor(),
+ "bar": _Cursor(),
+ "displays": _Displays(),
+ "window_probe": _Window(),
+ "capturer": capturer or _Capturer(),
+ "ui_text_reader": _Text(),
+ }
+ kwargs.update(overrides)
+ return ScreenContextService(**kwargs)
+
+
+def _darwin(monkeypatch, **kwargs) -> FakeTCC:
+ tcc = FakeTCC(**kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ monkeypatch.setattr(ports, "_is_wayland", lambda: False)
+ return tcc
+
+
+# ---------------------------------------------------------------------------
+# The capture asks once; the probe never does
+# ---------------------------------------------------------------------------
+
+
+async def test_a_capture_while_not_determined_asks_once_and_refuses_until_answered(
+ monkeypatch,
+) -> None:
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ capturer = _Capturer()
+ service = _service(capturer)
+
+ first = await service.capture_for_turn("look at this", locale="en")
+ second = await service.capture_for_turn("look at this", locale="en")
+
+ for outcome in (first, second):
+ assert outcome.status == "refused"
+ assert outcome.reason_kind == "technical"
+ assert outcome.reason_code == "capture_permission"
+ assert outcome.message and not outcome.message.startswith("[permission_needed")
+ assert capturer.grabs == []
+ assert len(tcc.requests(TccService.SCREEN_RECORDING)) == 1
+ assert tcc.implicit_prompts() == []
+
+
+async def test_a_capture_proceeds_when_the_user_allows(monkeypatch) -> None:
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.ALLOW)
+ capturer = _Capturer()
+
+ service = _service(capturer)
+
+ # The frozen preflight may keep the ask itself refused (the grant is only visible
+ # to the window-title oracle a moment later); the next capture must go through
+ # with no second request.
+ outcome = await service.capture_for_turn("look at this", locale="en")
+ if outcome.status != "captured":
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert outcome.status == "captured"
+ assert len(capturer.grabs) == 1
+ assert len(tcc.requests(TccService.SCREEN_RECORDING)) == 1
+
+
+async def test_a_denial_is_stable_and_never_asked_again(monkeypatch) -> None:
+ tcc = _darwin(monkeypatch, default_policy=DialogPolicy.DENY)
+ capturer = _Capturer()
+ service = _service(capturer)
+
+ await service.capture_for_turn("look at this", locale="en")
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert outcome.status == "refused"
+ assert outcome.reason_code == "capture_permission"
+ assert capturer.grabs == []
+ assert len(tcc.requests(TccService.SCREEN_RECORDING)) == 1
+ assert tcc.ignored_requests() == []
+
+
+async def test_a_live_grant_captures_without_asking(monkeypatch) -> None:
+ tcc = _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING])
+
+ outcome = await _service().capture_for_turn("look at this", locale="en")
+
+ assert outcome.status == "captured"
+ tcc.assert_no_prompts()
+
+
+async def test_the_capture_asks_with_the_feature_that_started_it() -> None:
+ gate = FakePermissionService({"screen_recording": "needs_settings"})
+ service = _service(
+ permission_probe=lambda: "Screen recording permission is missing.",
+ permission_gate=gate,
+ )
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert outcome.status == "refused"
+ assert outcome.reason_code == "capture_permission"
+ assert "Screen Recording" in (outcome.message or "")
+ (call,) = gate.ensure_calls("screen_recording")
+ assert (call.method, call.feature, call.interactive, call.wait_s) == (
+ "ensure_async",
+ "screen_context",
+ True,
+ 0.0,
+ )
+
+ # An appshot (take_appshot) says so in its verdict evidence; the shared service
+ # carries a shutter hook for every capture, so the hook cannot tell them apart.
+ from jarvis.screen_context.models import IntentVerdict, VisualIntent
+
+ await service.capture(verdict=IntentVerdict(intent=VisualIntent.WINDOW, evidence=("appshot",)))
+ assert gate.ensure_calls("screen_recording")[-1].feature == "appshot"
+
+
+async def test_a_probe_that_reports_an_issue_the_gate_overrules_lets_the_capture_go() -> None:
+ # The probe only DESCRIBES (it may read a stale preflight); only a live GRANTED
+ # from the permission service decides.
+ gate = FakePermissionService({"screen_recording": "granted"})
+ capturer = _Capturer()
+ service = _service(
+ capturer,
+ permission_probe=lambda: "Screen recording permission is missing.",
+ permission_gate=gate,
+ )
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert outcome.status == "captured"
+ assert len(capturer.grabs) == 1
+
+
+async def test_a_wayland_issue_is_never_asked_about() -> None:
+ gate = FakePermissionService()
+ service = _service(
+ permission_probe=lambda: CapturePermissionIssue(
+ code="wayland_portal", message="A desktop portal is required."
+ ),
+ permission_gate=gate,
+ )
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert outcome.reason_code == "wayland_portal"
+ assert gate.calls == []
+
+
+# ---------------------------------------------------------------------------
+# Wallpaper-only frames are never a success
+# ---------------------------------------------------------------------------
+
+
+async def test_a_wallpaper_frame_after_a_revoke_is_refused_and_opens_an_episode(
+ monkeypatch,
+) -> None:
+ tcc = _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING], preflight_frozen=())
+ revoke = lambda: tcc.deny(TccService.SCREEN_RECORDING) # noqa: E731
+ capturer = _Capturer(frame=lambda: wallpaper_pixels((64, 48)), before_grab=revoke)
+ service = _service(capturer)
+ shutter: list = []
+ service.set_shutter_hook(lambda *args: shutter.append(args))
+
+ outcome = await service.capture_for_turn("look at this", locale="en")
+
+ assert outcome.status == "refused"
+ assert outcome.reason_code == "capture_permission"
+ assert outcome.context is None and outcome.handle_id is None
+ assert shutter == [] # no shutter effect for a frame that is not a screenshot
+ assert [e.feature for e in get_permission_service().outstanding()] == ["screen_context"]
+ assert tcc.dialogs_shown() == []
+
+
+# ---------------------------------------------------------------------------
+# Status probes are silent
+# ---------------------------------------------------------------------------
+
+
+def test_the_status_probe_describes_the_issue_and_never_asks(monkeypatch) -> None:
+ tcc = _darwin(monkeypatch)
+
+ issue = ports.capture_permission_error()
+
+ assert issue is not None
+ assert issue.code == "capture_permission"
+ assert "Screen Recording" in issue.message
+ assert not issue.message.startswith("[permission_needed")
+ tcc.assert_no_prompts()
+
+
+def test_the_status_probe_reads_a_grant_given_mid_session(monkeypatch) -> None:
+ tcc = _darwin(monkeypatch)
+ assert ports.capture_permission_error() is not None
+ tcc.grant(TccService.SCREEN_RECORDING) # the frozen preflight stays negative
+
+ assert ports.capture_permission_error() is None
+ tcc.assert_no_prompts()
+
+
+def test_the_shallow_status_probe_never_runs_the_window_title_oracle(monkeypatch) -> None:
+ tcc = _darwin(monkeypatch)
+ mark = tcc.mark()
+
+ issue = ports.capture_permission_error(deep=False)
+
+ assert issue is not None # the preflight says no and nothing proves otherwise
+ oracle_probes = [
+ call for call in tcc.calls_since(mark) if "window title oracle" in call.api + call.detail
+ ]
+ assert oracle_probes == []
+ tcc.assert_no_prompts()
+
+
+def test_the_accessibility_probe_is_silent_and_keeps_the_image_available(monkeypatch) -> None:
+ tcc = _darwin(monkeypatch)
+
+ message = ports.accessibility_permission_error()
+
+ assert message is not None
+ assert "still available" in message
+ assert "Settings > Permissions" not in message
+ tcc.assert_no_prompts()
+ tcc.grant(TccService.ACCESSIBILITY)
+ get_permission_service().invalidate() # the 250 ms negative cache, nothing else
+ assert ports.accessibility_permission_error() is None
+
+
+def test_the_probes_are_silent_and_empty_off_macos(monkeypatch) -> None:
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ monkeypatch.setattr(ports, "_is_wayland", lambda: False)
+
+ assert ports.capture_permission_error() is None
+ assert ports.accessibility_permission_error() is None
+ tcc.assert_silent()
+
+
+async def test_a_capture_off_macos_is_unchanged_and_reads_nothing(monkeypatch) -> None:
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ monkeypatch.setattr(ports, "_is_wayland", lambda: False)
+ capturer = _Capturer(frame=lambda: wallpaper_pixels((64, 48))) # flat is fine off macOS
+
+ outcome = await _service(capturer).capture_for_turn("look at this", locale="en")
+
+ assert outcome.status == "captured"
+ tcc.assert_silent()
+ assert get_permission_service().outstanding() == []
diff --git a/tests/unit/setup/test_macos_app_bundle.py b/tests/unit/setup/test_macos_app_bundle.py
index ded35468a6..ada7f248b5 100644
--- a/tests/unit/setup/test_macos_app_bundle.py
+++ b/tests/unit/setup/test_macos_app_bundle.py
@@ -62,7 +62,7 @@ def test_bundle_layout_and_plist(tmp_path: Path, monkeypatch) -> None:
assert info["CFBundlePackageType"] == "APPL"
assert "microphone" in info["NSMicrophoneUsageDescription"].lower()
assert "screen" in info["NSScreenCaptureUsageDescription"].lower()
- assert "dictate" in info["NSAppleEventsUsageDescription"].lower()
+ assert "other apps" in info["NSAppleEventsUsageDescription"].lower()
executable = bundle / "Contents" / "MacOS" / executable_name
assert executable.read_bytes()[:4] == b"\xcf\xfa\xed\xfe"
if os.name != "nt":
@@ -70,6 +70,44 @@ def test_bundle_layout_and_plist(tmp_path: Path, monkeypatch) -> None:
assert macos_app_bundle_is_launchable(bundle) is True
+def test_bundle_plist_carries_the_shared_usage_strings_and_no_removed_key(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """The managed app shows the same permission dialogs as the .dmg app (one table)."""
+ from jarvis.core import macos_privacy_strings as table
+
+ bundle = _build(tmp_path, monkeypatch)
+ info = plistlib.loads((bundle / "Contents" / "Info.plist").read_bytes())
+
+ for key, text in table.usage_descriptions().items():
+ assert info[key] == text, key
+ for key in table.REMOVED_USAGE_KEYS:
+ assert key not in info, key
+ # These three were missing from the managed bundle before the table existed.
+ for key in (
+ "NSDesktopFolderUsageDescription",
+ "NSDocumentsFolderUsageDescription",
+ "NSDownloadsFolderUsageDescription",
+ ):
+ assert info[key].strip()
+
+
+def test_cosmetic_usage_strings_do_not_force_an_installed_bundle_rebuild(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """Adding prompt text must not rebuild installed bundles.
+
+ An ad-hoc rebuild is a new identity and re-asks every permission, so the
+ folder/volume/local-network strings ride the next rebuild that happens for
+ another reason instead of forcing one.
+ """
+ bundle = _build(tmp_path, monkeypatch)
+ info = plistlib.loads((bundle / "Contents" / "Info.plist").read_bytes())
+
+ assert info["JarvisBundleFormatVersion"] == 3
+ assert macos_app_bundle_is_launchable(bundle) is True
+
+
def test_rerun_preserves_existing_bundle_byte_for_byte(tmp_path: Path, monkeypatch) -> None:
first = _build(tmp_path, monkeypatch)
executable_name = plistlib.loads((first / "Contents" / "Info.plist").read_bytes())[
@@ -453,7 +491,12 @@ def test_build_native_bundle_layout_and_clang_invocation(
from jarvis.setup.macos_app_bundle import _BUNDLE_FORMAT_VERSION
assert info["JarvisBundleFormatVersion"] == _BUNDLE_FORMAT_VERSION
- assert "dictate" in info["NSAppleEventsUsageDescription"].lower()
+ assert "other apps" in info["NSAppleEventsUsageDescription"].lower()
+ # The German and Spanish dialog text is laid out with the bundle, before signing.
+ assert info["CFBundleLocalizations"] == ["en", "de", "es"]
+ for language in ("de", "es"):
+ strings = bundle / "Contents" / "Resources" / f"{language}.lproj" / "InfoPlist.strings"
+ assert "NSMicrophoneUsageDescription" in strings.read_text(encoding="utf-8")
executable = bundle / "Contents" / "MacOS" / "PersonalJarvis"
assert executable.read_bytes()[:4] == b"\xcf\xfa\xed\xfe"
if os.name != "nt":
@@ -616,33 +659,96 @@ def test_reset_stale_tcc_grants_survives_a_failing_tccutil() -> None:
assert attempts == list(mab._TCC_SERVICES)
-def test_a_recurring_rebuild_wipes_the_grants_only_once(tmp_path: Path, monkeypatch) -> None:
- """BUG-159: a rebuild loop must not re-ask for every permission each start.
+def _redirect_data_dir(tmp_path: Path, monkeypatch) -> Path:
+ """Point every data-directory lookup at an empty folder the test can inspect.
- The reset is the right move once. Repeating it while the user has not yet
- answered the first one destroys the grants they just re-gave — which is
- exactly what "I allow everything, restart, and it asks again" looks like.
+ The deleted reset note was written under ``user_data_dir()``, never beside the
+ bundle, so asserting an empty bundle folder alone could not see it come back.
"""
+ import jarvis.core.paths as paths
import jarvis.platform.permissions as permissions
+
+ data = tmp_path / "jarvis-data"
+ data.mkdir()
+ monkeypatch.setattr(paths, "user_data_dir", lambda: data)
+ monkeypatch.setattr(permissions, "_leftover_state_dir", lambda: data)
+ return data
+
+
+def test_an_identity_change_resets_the_own_rows_and_leaves_no_marker_behind(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """The reset names the own bundle id's rows and writes nothing for a note.
+
+ A rebuild loop is stopped one layer up (the rebuild fingerprint, BUG-161);
+ this layer only resets once per rebuild that really happened, and the app
+ asks again just in time instead of explaining the reset up front.
+ """
import jarvis.setup.macos_app_bundle as mab
- marker = tmp_path / "macos-tcc-reset.json"
- monkeypatch.setattr(permissions, "identity_reset_marker_path", lambda: marker)
- hashes = iter(['cdhash H"two"', 'cdhash H"three"'])
- monkeypatch.setattr(mab, "_bundle_tcc_identity", lambda _bundle: next(hashes))
+ data = _redirect_data_dir(tmp_path, monkeypatch)
+ monkeypatch.setattr(mab, "_bundle_tcc_identity", lambda _bundle: 'cdhash H"two"')
sweeps: list[int] = []
monkeypatch.setattr(mab, "_reset_stale_tcc_grants", lambda: sweeps.append(1))
-
bundle = tmp_path / APP_DIR_NAME
- mab._reset_or_explain(bundle, 'cdhash H"one"')
- assert sweeps == [1]
- assert marker.is_file()
- # Second rebuild, first reset still unanswered: explain, never wipe again.
- mab._reset_or_explain(bundle, 'cdhash H"two"')
+ mab._reset_after_identity_change(bundle, 'cdhash H"one"')
assert sweeps == [1]
- assert marker.is_file()
+ assert list(tmp_path.iterdir()) == [data]
+ assert list(data.iterdir()) == []
+
+
+def test_a_leftover_state_file_of_an_earlier_build_is_removed_on_the_darwin_install_path(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """An upgrade deletes the two files the permission wall kept; it never asks anything."""
+ import jarvis.autostart.macos as autostart_macos
+ import jarvis.platform.permissions as permissions
+ import jarvis.setup.macos_app_bundle as mab
+
+ data = tmp_path / "data"
+ data.mkdir()
+ for name in ("macos-tcc-reset.json", "macos-automation-consent.json", "keep.json"):
+ (data / name).write_text("{}", encoding="utf-8")
+ monkeypatch.setattr(permissions, "_leftover_state_dir", lambda: data)
+ monkeypatch.setattr(mab.sys, "platform", "darwin")
+ monkeypatch.setattr(mab, "_ensure_macos_app_bundle", lambda **_kw: None)
+ monkeypatch.setattr(mab, "macos_app_bundle_path", lambda **_kw: tmp_path / "missing.app")
+ monkeypatch.setattr(autostart_macos, "retarget_launch_agent", lambda _target: True)
+
+ assert ensure_macos_app_bundle() is None
+
+ assert sorted(path.name for path in data.iterdir()) == ["keep.json"]
+
+
+ ("platform", "inject_applications_dir"),
+ [("linux", False), ("win32", False), ("darwin", True)],
+ ids=["off-darwin", "windows", "darwin-with-injected-applications-dir"],
+)
+def test_the_leftover_cleanup_leaves_other_installs_and_injected_dirs_alone(
+ tmp_path: Path, monkeypatch, platform: str, inject_applications_dir: bool
+) -> None:
+ """Only the real darwin install path deletes; every other call keeps the files."""
+ import jarvis.platform.permissions as permissions
+ import jarvis.setup.macos_app_bundle as mab
+
+ data = tmp_path / "data"
+ data.mkdir()
+ for name in ("macos-tcc-reset.json", "macos-automation-consent.json"):
+ (data / name).write_text("{}", encoding="utf-8")
+ monkeypatch.setattr(permissions, "_leftover_state_dir", lambda: data)
+ monkeypatch.setattr(mab.sys, "platform", platform)
+ monkeypatch.setattr(mab, "_ensure_macos_app_bundle", lambda **_kw: None)
+ applications_dir = tmp_path / "Applications" if inject_applications_dir else None
+
+ assert ensure_macos_app_bundle(applications_dir=applications_dir) is None
+
+ assert sorted(path.name for path in data.iterdir()) == [
+ "macos-automation-consent.json",
+ "macos-tcc-reset.json",
+ ]
# --- BUG-161: a rebuild loop that wiped the grants on every single start
@@ -961,7 +1067,9 @@ def test_resign_in_place_keeps_the_files_and_resets_against_the_old_identity(
monkeypatch.setattr(mab, "_signed_with_certificate", lambda _b: True)
monkeypatch.setattr(mab, "macos_app_bundle_is_launchable", lambda _b: True)
resets: list[tuple[Path, str | None]] = []
- monkeypatch.setattr(mab, "_reset_or_explain", lambda b, previous: resets.append((b, previous)))
+ monkeypatch.setattr(
+ mab, "_reset_after_identity_change", lambda b, previous: resets.append((b, previous))
+ )
result = mab._resign_bundle_in_place(bundle, "ABCDEF")
@@ -983,7 +1091,9 @@ def test_resign_in_place_rolls_back_when_the_result_cannot_launch(
monkeypatch.setattr(mab, "_sign_bundle", lambda target, identity=None: None)
monkeypatch.setattr(mab, "_signed_with_certificate", lambda _b: True)
monkeypatch.setattr(mab, "macos_app_bundle_is_launchable", lambda _b: False)
- monkeypatch.setattr(mab, "_reset_or_explain", lambda *_a: pytest.fail("no reset on rollback"))
+ monkeypatch.setattr(
+ mab, "_reset_after_identity_change", lambda *_a: pytest.fail("no reset on rollback")
+ )
with pytest.raises(RuntimeError):
mab._resign_bundle_in_place(bundle, "ABCDEF")
@@ -993,18 +1103,17 @@ def test_resign_in_place_rolls_back_when_the_result_cannot_launch(
def test_a_rebuild_with_the_identity_never_resets_the_grants(tmp_path: Path, monkeypatch) -> None:
"""Same certificate before and after: TCC sees the same app, nothing to reset."""
- import jarvis.platform.permissions as permissions
import jarvis.setup.macos_app_bundle as mab
- same ='identifier "com.personal-jarvis.desktop" and certificate leaf = H"0e14"'
+ same = 'identifier "com.personal-jarvis.desktop" and certificate leaf = H"0e14"'
monkeypatch.setattr(mab, "_bundle_tcc_identity", lambda _b: same)
monkeypatch.setattr(mab, "_reset_stale_tcc_grants", lambda: pytest.fail("must not reset"))
- marker = tmp_path / "macos-tcc-reset.json"
- monkeypatch.setattr(permissions, "identity_reset_marker_path", lambda: marker)
+ data = _redirect_data_dir(tmp_path, monkeypatch)
- mab._reset_or_explain(tmp_path / APP_DIR_NAME, same)
+ mab._reset_after_identity_change(tmp_path / APP_DIR_NAME, same)
- assert not marker.exists()
+ assert list(tmp_path.iterdir()) == [data]
+ assert list(data.iterdir()) == []
def _healthy_darwin_bundle(tmp_path: Path, monkeypatch, *, identity: str | None):
diff --git a/tests/unit/setup/test_macos_dmg_identity.py b/tests/unit/setup/test_macos_dmg_identity.py
new file mode 100644
index 0000000000..ad5b1f87a1
--- /dev/null
+++ b/tests/unit/setup/test_macos_dmg_identity.py
@@ -0,0 +1,98 @@
+"""The downloadable .dmg app is its own installed app, with its own identity.
+
+``jarvis.spec`` (PyInstaller) cannot import ``jarvis.core.branding``, so it
+carries the .dmg bundle id as a literal. The permission port accepts that id as
+an installed identity; if the two ever drift apart, every macOS feature of the
+.dmg app fails closed again — with every permission granted and no button left
+to fix it. These tests pin the literal, and the lookup that finds the .dmg app
+for tools that have to bring it to the front.
+"""
+
+from __future__ import annotations
+
+import plistlib
+import re
+from pathlib import Path
+
+import pytest
+
+import jarvis.setup.macos_app_bundle as mab
+from jarvis.core.branding import MACOS_BUNDLE_ID, MACOS_DMG_BUNDLE_ID
+from jarvis.platform.permissions import ACCEPTED_BUNDLE_IDS
+from jarvis.setup.macos_app_bundle import APP_DIR_NAME, installed_macos_app_bundle_path
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+PYINSTALLER_SPEC = REPO_ROOT / "jarvis.spec"
+
+
+def test_the_spec_names_the_bundle_id_the_app_accepts_as_its_own() -> None:
+ spec = PYINSTALLER_SPEC.read_text(encoding="utf-8")
+
+ match = re.search(r'^MACOS_BUNDLE_IDENTIFIER\s*=\s*"([^"]+)"', spec, re.MULTILINE)
+
+ assert match is not None, "jarvis.spec must declare MACOS_BUNDLE_IDENTIFIER"
+ assert match.group(1) == MACOS_DMG_BUNDLE_ID
+ # The Info.plist and the BUNDLE call must both use that one literal.
+ assert '"CFBundleIdentifier": MACOS_BUNDLE_IDENTIFIER' in spec
+ assert "bundle_identifier=MACOS_BUNDLE_IDENTIFIER" in spec
+
+
+def test_the_two_installed_identities_stay_distinct() -> None:
+ """The managed installer tells the .dmg app apart by id and must keep doing so."""
+ assert MACOS_DMG_BUNDLE_ID != MACOS_BUNDLE_ID
+ assert ACCEPTED_BUNDLE_IDS == (MACOS_BUNDLE_ID, MACOS_DMG_BUNDLE_ID)
+
+
+def roots(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path]:
+ system = tmp_path / "Applications"
+ user = tmp_path / "home" / "Applications"
+ system.mkdir()
+ user.mkdir(parents=True)
+ monkeypatch.setattr(mab, "SYSTEM_APPLICATIONS_DIR", system)
+ monkeypatch.setattr(mab, "user_applications_dir", lambda: user)
+ return system, user
+
+
+def _app(root: Path, bundle_id: str) -> Path:
+ bundle = root / APP_DIR_NAME
+ (bundle / "Contents").mkdir(parents=True)
+ with (bundle / "Contents" / "Info.plist").open("wb") as stream:
+ plistlib.dump({"CFBundleIdentifier": bundle_id}, stream)
+ return bundle
+
+
+def test_a_mac_with_only_the_downloaded_app_finds_it(roots) -> None:
+ system, _user = roots
+ dmg_app = _app(system, MACOS_DMG_BUNDLE_ID)
+
+ assert installed_macos_app_bundle_path() == dmg_app
+
+
+def test_the_managed_install_wins_when_both_are_present(roots) -> None:
+ system, user = roots
+ _app(system, MACOS_DMG_BUNDLE_ID)
+ managed = _app(user, MACOS_BUNDLE_ID)
+
+ assert installed_macos_app_bundle_path() == managed
+
+
+def test_an_unrelated_app_with_our_name_is_never_returned(roots) -> None:
+ system, user = roots
+ _app(system, "org.example.imposter")
+
+ path = installed_macos_app_bundle_path()
+
+ assert path != system / APP_DIR_NAME
+ assert path == user / APP_DIR_NAME
+ assert not path.exists()
+
+
+def test_without_any_install_the_managed_location_is_reported(roots) -> None:
+ system, user = roots
+
+ path = installed_macos_app_bundle_path()
+
+ assert path.name == APP_DIR_NAME
+ assert path.parent in {system, user}
+ assert not path.exists()
diff --git a/tests/unit/setup/test_onboarding_meta.py b/tests/unit/setup/test_onboarding_meta.py
index 354c54ce4a..ed8550cfc7 100644
--- a/tests/unit/setup/test_onboarding_meta.py
+++ b/tests/unit/setup/test_onboarding_meta.py
@@ -5,18 +5,26 @@ def test_meta_constants():
assert m.CURRENT_TERMS_VERSION == "1.0"
# Setup runs inside the real app (2026-09-30): consent, one key on the API
# Keys page, a subscription for the agents on its Agents tab (2026-10-01),
- # macOS permissions, the wake word in Settings, then the start. The "how"
- # step (2026-10-01) explains the product before anything is set up.
- assert m.ONBOARDING_STEPS == [
- "welcome", "how", "keys", "subscriptions", "permissions", "voice", "ready",
- ]
+ # the wake word in Settings, then the start. The "how" step (2026-10-01)
+ # explains the product before anything is set up. There is no macOS
+ # permissions step: permissions are asked just in time, where a feature
+ # needs them.
+ assert m.ONBOARDING_STEPS == ["welcome", "how", "keys", "subscriptions", "voice", "ready"]
assert m.ONBOARDING_STEPS.index("how") < m.ONBOARDING_STEPS.index("keys")
- # Restart batching (2026-07-18): permissions + voice sit LAST before the
- # final step so the single unconditional completion restart covers both.
- assert m.ONBOARDING_STEPS.index("permissions") < m.ONBOARDING_STEPS.index("voice")
+ # Restart batching (2026-07-18): voice sits LAST before the final step so
+ # the single unconditional completion restart covers it.
assert m.ONBOARDING_STEPS[-2] == "voice"
# Retired step ids must not come back through a partial revert.
- for retired in ("terms", "language", "api-keys", "wake-word", "finish", "brain", "agents"):
+ for retired in (
+ "terms",
+ "language",
+ "api-keys",
+ "wake-word",
+ "finish",
+ "brain",
+ "agents",
+ "permissions",
+ ):
assert retired not in m.ONBOARDING_STEPS
assert len(m.WAKE_WORD_LEGAL_REFERENCES) >= 3
for ref in m.WAKE_WORD_LEGAL_REFERENCES:
diff --git a/tests/unit/speech/test_dictation_lifecycle_events.py b/tests/unit/speech/test_dictation_lifecycle_events.py
index f3ced409af..34b0f5737f 100644
--- a/tests/unit/speech/test_dictation_lifecycle_events.py
+++ b/tests/unit/speech/test_dictation_lifecycle_events.py
@@ -295,11 +295,11 @@ async def test_a_crashing_dictation_publishes_exactly_one_completion(
@pytest.mark.asyncio
-async def test_a_closed_capture_gate_is_refused_out_loud() -> None:
+async def test_a_refused_microphone_is_refused_out_loud() -> None:
bus = EventBus()
seen = _Collector(bus)
pipe = _dictation_pipeline(bus)
- pipe._activation_gate = lambda: False
+ pipe._user_activation_gate = lambda: False
assert pipe.start_dictation() is False
await _drain_bus()
@@ -391,7 +391,7 @@ async def test_every_refusal_reason_comes_from_the_shared_vocabulary(
seen = _Collector(bus)
closed_gate = _dictation_pipeline(bus)
- closed_gate._activation_gate = lambda: False
+ closed_gate._user_activation_gate = lambda: False
closed_gate.start_dictation()
no_stt = _dictation_pipeline(bus)
diff --git a/tests/unit/speech/test_dictation_stale_hangup.py b/tests/unit/speech/test_dictation_stale_hangup.py
index b80eab22f8..6e7a61bde8 100644
--- a/tests/unit/speech/test_dictation_stale_hangup.py
+++ b/tests/unit/speech/test_dictation_stale_hangup.py
@@ -69,9 +69,9 @@ async def test_start_dictation_clears_stale_hangup() -> None:
@pytest.mark.asyncio
-async def test_start_dictation_does_not_spawn_when_capture_gate_is_closed() -> None:
+async def test_start_dictation_does_not_spawn_when_the_microphone_is_refused() -> None:
pipe = _make_idle_pipeline()
- pipe._activation_gate = lambda: False
+ pipe._user_activation_gate = lambda: False
assert pipe.start_dictation() is False
assert pipe._dictation_task is None
diff --git a/tests/unit/speech/test_dictation_wake_gate.py b/tests/unit/speech/test_dictation_wake_gate.py
index c99aef79ce..6965771219 100644
--- a/tests/unit/speech/test_dictation_wake_gate.py
+++ b/tests/unit/speech/test_dictation_wake_gate.py
@@ -172,11 +172,32 @@ async def test_mute_still_wins_and_is_reported_first() -> None:
pipe._dictation_task.cancel()
-def test_a_closed_capture_gate_is_named_without_guessing() -> None:
+def test_a_closed_background_gate_is_named_without_guessing() -> None:
pipe = _gate_pipeline()
pipe._activation_gate = lambda: False
assert pipe._activation_allowed() is False
- assert "microphone capture is not permitted" in pipe._activation_block_reason()
+ assert pipe._activation_block_reason() == "microphone access is not granted"
+
+
+def test_a_closed_user_gate_is_named_without_guessing() -> None:
+ pipe = _gate_pipeline()
+ pipe._user_activation_gate = lambda: False
+ assert pipe._gesture_activation_allowed() is False
+ assert (
+ pipe._activation_block_reason(explicit=True)
+ == "microphone access is denied or unavailable"
+ )
+ # The wake word is judged by the background gate, which this test left open.
+ assert pipe._activation_allowed() is True
+
+
+def test_an_undecided_microphone_closes_wake_but_not_a_deliberate_press() -> None:
+ """Wake needs a live grant; a key press only needs the mic not to be refused."""
+ pipe = _gate_pipeline()
+ pipe._activation_gate = lambda: False # not granted
+ pipe._user_activation_gate = lambda: True # not refused either
+ assert pipe._activation_allowed() is False
+ assert pipe._gesture_activation_allowed() is True
# --------------------------------------------------------------------------
diff --git a/tests/unit/speech/test_mic_level_helper.py b/tests/unit/speech/test_mic_level_helper.py
index 050ceb41fc..b94cac2fce 100644
--- a/tests/unit/speech/test_mic_level_helper.py
+++ b/tests/unit/speech/test_mic_level_helper.py
@@ -2,11 +2,18 @@
diagnostics (``step_mic_level``) and the onboarding mic-level route
(``GET /api/settings/wake-word/mic-level``). It must never raise -- a
headless host / missing device / any capture error degrades to the honest
-floor -120.0 dBFS instead of bubbling up.
+floor -120.0 dBFS instead of bubbling up. The one exception is a microphone the
+OS has not granted: that is NOT "no microphone", so ``MicrophoneAccessError``
+propagates (carrying the permission layer's answer) and the CLI reports it.
"""
+import numpy as np
import pytest
+from jarvis.audio.capture import MicrophoneAccessError
+from jarvis.platform.permission_service import PermissionOutcome
+from jarvis.platform.permissions import PermissionId
from jarvis.speech import diagnose
+from tests.fakes.fake_permission_service import make_result
@pytest.mark.asyncio
@@ -18,7 +25,7 @@ async def test_measure_mic_dbfs_no_device_returns_floor(monkeypatch):
async def __aexit__(self, *a):
return False
- monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda: _NoMic())
+ monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda **_kwargs: _NoMic())
val = await diagnose.measure_mic_dbfs(duration_s=0.1)
assert val == -120.0 # honest floor, never raises
@@ -37,7 +44,7 @@ async def test_measure_mic_dbfs_never_raises_on_unexpected_error(monkeypatch):
def stream(self):
raise RuntimeError("PortAudio exploded")
- monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda: _Boom())
+ monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda **_kwargs: _Boom())
val = await diagnose.measure_mic_dbfs(duration_s=0.1)
assert val == -120.0
@@ -63,7 +70,7 @@ async def test_measure_mic_dbfs_reports_loud_signal(monkeypatch):
arr = np.full(160, 32767, dtype=np.int16)
yield _Chunk(arr.tobytes())
- monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda: _LoudMic())
+ monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda **_kwargs: _LoudMic())
val = await diagnose.measure_mic_dbfs(duration_s=1.0)
assert val > -1.0 # near 0 dBFS for a full-scale signal
@@ -89,7 +96,7 @@ async def test_measure_mic_dbfs_invokes_on_frame_callback(monkeypatch):
arr = np.full(160, 32767, dtype=np.int16)
yield _Chunk(arr.tobytes())
- monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda: _OneShotMic())
+ monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda **_kwargs: _OneShotMic())
calls = []
val = await diagnose.measure_mic_dbfs(
duration_s=1.0, on_frame=lambda dbfs, running_max, n: calls.append((dbfs, running_max, n))
@@ -98,3 +105,106 @@ async def test_measure_mic_dbfs_invokes_on_frame_callback(monkeypatch):
dbfs, running_max, n = calls[0]
assert running_max == val
assert n == 160
+
+
+class _DeniedMic:
+ """A capture whose open is refused by the permission layer."""
+
+ def __init__(self, **kwargs) -> None:
+ self.kwargs = kwargs
+
+ async def __aenter__(self):
+ result = make_result(PermissionId.MICROPHONE, PermissionOutcome.DENIED)
+ raise MicrophoneAccessError(result.user_detail, result=result)
+
+ async def __aexit__(self, *a):
+ return False
+
+
+async def test_a_denied_microphone_is_not_reported_as_no_microphone(monkeypatch):
+ monkeypatch.setattr(diagnose, "MicrophoneCapture", _DeniedMic)
+
+ with pytest.raises(MicrophoneAccessError) as refused:
+ await diagnose.measure_mic_dbfs(duration_s=0.1)
+
+ assert refused.value.result.outcome is PermissionOutcome.DENIED # not the -120.0 floor
+
+
+async def test_measure_hands_the_gesture_flag_to_the_capture(monkeypatch):
+ seen: list[dict] = []
+
+ class _Recorder(_DeniedMic):
+ def __init__(self, **kwargs) -> None:
+ seen.append(kwargs)
+ super().__init__(**kwargs)
+
+ monkeypatch.setattr(diagnose, "MicrophoneCapture", _Recorder)
+
+ for interactive in (False, True):
+ with pytest.raises(MicrophoneAccessError):
+ await diagnose.measure_mic_dbfs(
+ duration_s=0.1, interactive=interactive, permission_wait_s=3.0
+ )
+
+ assert [(k["permission_feature"], k["interactive"], k["permission_wait_s"]) for k in seen] == [
+ ("voice", False, 3.0),
+ ("voice", True, 3.0),
+ ]
+
+
+async def test_the_default_measurement_never_asks_the_os(monkeypatch):
+ """A route that already ensured the permission measures without a second ask."""
+ seen: list[dict] = []
+
+ class _Recorder(_DeniedMic):
+ def __init__(self, **kwargs) -> None:
+ seen.append(kwargs)
+ super().__init__(**kwargs)
+
+ monkeypatch.setattr(diagnose, "MicrophoneCapture", _Recorder)
+ with pytest.raises(MicrophoneAccessError):
+ await diagnose.measure_mic_dbfs(duration_s=0.1)
+
+ assert seen[0]["interactive"] is False
+
+
+async def test_cli_mic_step_says_not_granted_and_returns_no_measurement(monkeypatch, capsys):
+ monkeypatch.setattr(diagnose, "MicrophoneCapture", _DeniedMic)
+
+ level = await diagnose.step_mic_level(duration_s=0.1)
+
+ out = capsys.readouterr().out
+ assert level is None # a permission answer, not a silent room
+ assert "Microphone access is not granted" in out
+ assert "NO audio" not in out # never the "check your mic selection" advice
+ assert "turned off for Personal Jarvis" in out # the layer's own sentence
+
+
+async def test_cli_mic_step_still_measures_a_granted_microphone(monkeypatch, capsys):
+ class _Chunk:
+ pcm = np.full(160, 16000, dtype=np.int16).tobytes()
+
+ class _Mic:
+ def __init__(self, **kwargs) -> None:
+ self.kwargs = kwargs
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *a):
+ return False
+
+ async def stream(self):
+ yield _Chunk()
+
+ monkeypatch.setattr(diagnose, "MicrophoneCapture", _Mic)
+
+ level = await diagnose.step_mic_level(duration_s=1.0)
+
+ assert level is not None and level > -20.0
+ assert "Samples received: 160" in capsys.readouterr().out
diff --git a/tests/unit/speech/test_pipeline_push_to_talk.py b/tests/unit/speech/test_pipeline_push_to_talk.py
index 1bc0504b87..d6f39dedeb 100644
--- a/tests/unit/speech/test_pipeline_push_to_talk.py
+++ b/tests/unit/speech/test_pipeline_push_to_talk.py
@@ -27,8 +27,11 @@ from types import SimpleNamespace
import jarvis.speech.pipeline as pipeline_mod
from jarvis.core.events import TranscriptionUpdate
from jarvis.core.protocols import AudioChunk
+from jarvis.platform.permission_service import PermissionOutcome
+from jarvis.platform.permissions import PermissionId
from jarvis.sessions.constants import HANGUP_HOTKEY, HANGUP_TURN_COMPLETE
from jarvis.speech.pipeline import PipelineState, SpeechPipeline, TurnTakingState
+from tests.fakes.fake_permission_service import FakePermissionService
class FakeTTS:
@@ -146,11 +149,37 @@ def test_ptt_key_repeat_within_grace_never_heals():
assert not pipe._ptt_release_event.is_set()
-def test_ptt_press_blocked_when_activation_gate_closed():
+def test_ptt_press_blocked_when_the_state_gate_is_closed():
pipe = _make_pipeline()
- pipe._activation_allowed = lambda: False # type: ignore[method-assign]
+ pipe._muted = True
pipe._on_ptt_press()
assert pipe._ptt_mode is False
+ assert not pipe._call_event.is_set()
+
+
+def test_a_refused_microphone_still_reaches_ensure_and_never_arms_a_recording():
+ """A denied/restricted/unavailable microphone is refused BY ``ensure`` (which
+ publishes the PermissionNeeded card), never by the silent user predicate alone:
+ the press must reach the permission layer so the refusal is not silent."""
+ pipe = _make_pipeline()
+ pipe._user_activation_gate = lambda: False
+ gate = FakePermissionService()
+ gate.script(PermissionId.MICROPHONE, PermissionOutcome.DENIED)
+ pipe._permission_gate = gate
+ pipe._on_ptt_press()
+ assert pipe._ptt_mode is False
+ assert not pipe._call_event.is_set()
+ (call,) = gate.ensure_calls(PermissionId.MICROPHONE)
+ assert (call.feature, call.interactive, call.wait_s) == ("voice", True, 0.0)
+
+
+def test_ptt_press_needs_no_background_grant():
+ """The wake-word gate (a live grant) must not close a deliberate press: the
+ press is what asks the OS, so an undecided microphone still gets through."""
+ pipe = _make_pipeline()
+ pipe._activation_gate = lambda: False
+ pipe._on_ptt_press()
+ assert pipe._ptt_mode is True
def test_ptt_release_is_noop_when_not_armed():
@@ -349,9 +378,9 @@ async def test_call_hotkey_bypasses_post_hangup_wake_lock():
assert pipe._state == PipelineState.IDLE
-async def test_closed_activation_gate_discards_call_and_clears_ptt_mode():
+async def test_closed_user_capture_gate_discards_call_and_clears_ptt_mode():
pipe = _make_pipeline()
- pipe._activation_allowed = lambda: False # type: ignore[method-assign]
+ pipe._user_activation_gate = lambda: False
pipe._ptt_mode = True
pipe._call_event.set()
@@ -361,6 +390,26 @@ async def test_closed_activation_gate_discards_call_and_clears_ptt_mode():
assert pipe._state == PipelineState.IDLE
+async def test_closed_background_gate_discards_a_wake_call_but_not_an_explicit_one():
+ """The wake word needs a live grant; a deliberate press needs only a not-refused mic."""
+ wake = _make_pipeline()
+ del wake._activation_allowed # the real predicate, not the harness stub
+ wake._activation_gate = lambda: False
+ wake._call_event.set()
+ ran = _accepting_session_stub(wake)
+ await _pump_state_loop_once(wake)
+ assert ran["session"] is False
+
+ explicit = _make_pipeline()
+ del explicit._activation_allowed
+ explicit._activation_gate = lambda: False
+ explicit._explicit_call_pending = True
+ explicit._call_event.set()
+ ran = _accepting_session_stub(explicit)
+ await _pump_state_loop_once(explicit)
+ assert ran["session"] is True
+
+
# ----------------------------------------------------------------------
# ACK — PTT must NOT run the 400 ms echo dead-zone before the mic opens
# ----------------------------------------------------------------------
diff --git a/tests/unit/speech/test_request_voice_session.py b/tests/unit/speech/test_request_voice_session.py
index 961c07e6da..24b0bd686e 100644
--- a/tests/unit/speech/test_request_voice_session.py
+++ b/tests/unit/speech/test_request_voice_session.py
@@ -11,7 +11,10 @@ import asyncio
import threading
import time
+from jarvis.platform.permission_service import PermissionOutcome
+from jarvis.platform.permissions import PermissionId
from jarvis.speech.pipeline import PipelineState, SpeechPipeline, TurnTakingState
+from tests.fakes.fake_permission_service import FakePermissionService
class _FakeBrain:
@@ -30,7 +33,9 @@ def _pipe(*, state=PipelineState.IDLE, gate=True, ptt=False, brain=None):
p._ptt_mode = ptt
p._state = state
p._call_event = asyncio.Event()
- p._activation_gate = (lambda: gate)
+ # A deliberate action is judged by the USER gate (not refused), never by the
+ # background wake gate (a live grant).
+ p._user_activation_gate = (lambda: gate)
p._muted = False
p._last_wake_keyword = ""
p._brain = brain
@@ -89,12 +94,19 @@ def test_noop_when_ptt_active() -> None:
assert not p._call_event.is_set()
-def test_noop_when_activation_not_allowed_and_does_not_seed() -> None:
+def test_noop_when_the_microphone_is_refused_and_does_not_seed() -> None:
+ """The refusal comes from ``ensure`` (so the card is published), not from the
+ silent user predicate alone: the request must reach the permission layer."""
brain = _FakeBrain()
p = _pipe(gate=False, brain=brain)
+ gate = FakePermissionService()
+ gate.script(PermissionId.MICROPHONE, PermissionOutcome.DENIED)
+ p._permission_gate = gate
assert p.request_voice_session(seed_messages=[("user", "x")]) is False
assert not p._call_event.is_set()
assert brain.seeded is None
+ (call,) = gate.ensure_calls(PermissionId.MICROPHONE)
+ assert (call.feature, call.interactive, call.wait_s) == ("voice", True, 0.0)
def test_seed_failure_still_arms() -> None:
diff --git a/tests/unit/speech/test_voice_permission_jit.py b/tests/unit/speech/test_voice_permission_jit.py
new file mode 100644
index 0000000000..7466daad90
--- /dev/null
+++ b/tests/unit/speech/test_voice_permission_jit.py
@@ -0,0 +1,599 @@
+"""Voice gestures ask for the microphone at the moment they need it; boot never does.
+
+The contract (docs/macos-permissions.md, 4.6 rows on the voice gates, and 4.7 boot rule):
+
+* A GESTURE (the dictation key or button, push-to-talk, the call key, "speak in
+ this conversation") calls ``ensure(MICROPHONE, wait_s=0)``. The first press of an
+ undecided microphone makes macOS ask and is refused for now (``DictationRefused``
+ with the existing ``microphone_unavailable`` reason, plus the ``PermissionNeeded``
+ episode the service publishes); nothing starts retroactively once it is answered,
+ the next press does. A denial is stable: the second press adds no native request.
+* ``dictation_available()`` no longer has a permission term, so the mic button is
+ visible on a fresh Mac.
+* BOOT asks nothing: with every permission ``not_determined`` the voice pipeline
+ warms up and (wake word on or off) performs no request, no implicit prompt and
+ opens no input stream; for an upgrader with every grant present there are zero
+ requests and zero ``PermissionNeeded`` episodes.
+* Off macOS nothing is consulted at all (the FakeTCC call log stays empty).
+
+The consumer cases use ``FakePermissionService``; the macOS behaviour cases run the
+REAL service over ``FakeTCC``. No audio is started anywhere.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+import jarvis.speech.pipeline as pipeline_mod
+from jarvis.core.bus import EventBus
+from jarvis.core.events import DictationRefused, PermissionNeeded, PermissionResolved
+from jarvis.platform.permission_service import (
+ PermissionOutcome,
+ get_permission_service,
+)
+from jarvis.platform.permissions import PermissionId
+from jarvis.speech.pipeline import PipelineState, SpeechPipeline
+from jarvis.ui.desktop_app import _local_voice_permission_granted, _local_voice_permission_usable
+from tests.fakes.fake_permission_service import FakePermissionService, make_result
+from tests.fakes.fake_tcc import (
+ DialogPolicy,
+ FakeAudioInput,
+ FakeTCC,
+ TccService,
+ install_port,
+ make_non_darwin_port,
+)
+
+_MIC = PermissionId.MICROPHONE
+
+
+class _StubSTT:
+ async def transcribe_pcm(self, pcm: bytes): # pragma: no cover - never called
+ raise AssertionError("no transcription in this unit test")
+
+
+def _pipeline(
+ *,
+ permission: object | None = None,
+ bus: EventBus | None = None,
+ activation_gate=None, # noqa: ANN001
+ user_gate=None, # noqa: ANN001
+) -> SpeechPipeline:
+ """A pipeline reduced to what the voice gestures read; no audio, no providers."""
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._bus = bus
+ pipe._utterance_stt = _StubSTT()
+ pipe._input_device = "default"
+ pipe._input_priority = ()
+ pipe._dictation_task = None
+ pipe._dictation_stop_event = asyncio.Event()
+ pipe._dictation_wake_block_until = 0.0
+ pipe._ptt_mode = False
+ pipe._state = PipelineState.IDLE
+ pipe._muted = False
+ pipe._call_event = asyncio.Event()
+ pipe._ptt_release_event = asyncio.Event()
+ pipe._explicit_call_pending = False
+ pipe._runtime_loop = None
+ pipe._brain = None
+ pipe._last_wake_keyword = ""
+ pipe._hangup_event = asyncio.Event()
+ if permission is not None:
+ pipe._permission_gate = permission
+ if activation_gate is not None:
+ pipe._activation_gate = activation_gate
+ if user_gate is not None:
+ pipe._user_activation_gate = user_gate
+ return pipe
+
+
+def _record_commits(pipe: SpeechPipeline) -> list[str]:
+ """Replace the recording start so a started dictation never touches a microphone."""
+ started: list[str] = []
+
+ def _commit(loop, *, target, source): # noqa: ANN001, ANN202
+ started.append(source)
+ return True
+
+ pipe._commit_dictation = _commit # type: ignore[method-assign]
+ return started
+
+
+async def _drain() -> None:
+ for _ in range(6):
+ await asyncio.sleep(0)
+
+
+class _Seen:
+ """Collects the dictation refusals and permission episodes a test provokes."""
+
+ def __init__(self, bus: EventBus) -> None:
+ self.refused: list[DictationRefused] = []
+ self.needed: list[PermissionNeeded] = []
+ bus.subscribe(DictationRefused, self._refused)
+ bus.subscribe(PermissionNeeded, self._needed)
+
+ async def _refused(self, event: DictationRefused) -> None:
+ self.refused.append(event)
+
+ async def _needed(self, event: PermissionNeeded) -> None:
+ self.needed.append(event)
+
+
+# --------------------------------------------------------------------------
+# Consumer contract (FakePermissionService)
+# --------------------------------------------------------------------------
+
+
+def test_the_mic_button_is_visible_on_a_fresh_mac() -> None:
+ """``dictation_available`` has no permission term: the first press is what asks."""
+ gate = FakePermissionService()
+ gate.script(_MIC, PermissionOutcome.PENDING)
+ pipe = _pipeline(permission=gate, activation_gate=lambda: False, user_gate=lambda: False)
+
+ assert pipe.dictation_available() is True
+ assert gate.calls == []
+
+
+def test_the_mic_button_still_needs_an_stt_and_an_input_device() -> None:
+ pipe = _pipeline()
+ pipe._utterance_stt = None
+ assert pipe.dictation_available() is False
+ pipe = _pipeline()
+ pipe._input_device = "none"
+ assert pipe.dictation_available() is False
+
+
+async def test_the_first_dictation_press_asks_and_refuses_with_the_existing_reason() -> None:
+ bus = EventBus()
+ seen = _Seen(bus)
+ gate = FakePermissionService()
+ gate.script(_MIC, PermissionOutcome.PENDING)
+ pipe = _pipeline(permission=gate, bus=bus)
+ started = _record_commits(pipe)
+
+ assert pipe.start_dictation(source="hold_key") is False
+ await _drain()
+
+ (call,) = gate.ensure_calls(_MIC)
+ assert (call.feature, call.interactive, call.wait_s) == ("dictation", True, 0.0)
+ assert [event.reason for event in seen.refused] == ["microphone_unavailable"]
+ # The sentence is the permission layer's fixed template (no exception text).
+ assert seen.refused[0].detail == make_result(_MIC, PermissionOutcome.PENDING).user_detail
+ assert "Microphone" in seen.refused[0].detail
+ assert started == [], "nothing may start retroactively"
+
+
+async def test_the_press_after_the_grant_starts_the_dictation() -> None:
+ gate = FakePermissionService()
+ gate.script(_MIC, PermissionOutcome.PENDING, PermissionOutcome.GRANTED)
+ pipe = _pipeline(permission=gate)
+ started = _record_commits(pipe)
+
+ assert pipe.start_dictation(source="hold_key") is False
+ assert started == []
+ assert pipe.start_dictation(source="hold_key") is True
+ assert started == ["hold_key"]
+
+
+async def test_a_refusing_user_gate_blocks_dictation_even_when_the_service_says_granted() -> None:
+ bus = EventBus()
+ seen = _Seen(bus)
+ pipe = _pipeline(permission=FakePermissionService(), bus=bus, user_gate=lambda: False)
+ started = _record_commits(pipe)
+
+ assert pipe.start_dictation() is False
+ await _drain()
+
+ assert [event.reason for event in seen.refused] == ["microphone_unavailable"]
+ assert started == []
+
+
+async def test_dictation_without_an_stt_provider_does_not_ask_the_os() -> None:
+ """Asking for the microphone just to say "no provider" would be a pointless dialog."""
+ gate = FakePermissionService()
+ gate.script(_MIC, PermissionOutcome.PENDING)
+ pipe = _pipeline(permission=gate)
+ pipe._utterance_stt = None
+ pipe._publish_event_soon = lambda event: None # type: ignore[method-assign]
+
+ assert pipe.start_dictation() is False
+ assert gate.calls == []
+
+
+def test_ptt_press_asks_once_per_press_and_arms_only_on_a_grant() -> None:
+ gate = FakePermissionService()
+ gate.script(_MIC, PermissionOutcome.PENDING, PermissionOutcome.GRANTED)
+ pipe = _pipeline(permission=gate)
+
+ pipe._on_ptt_press()
+ assert pipe._ptt_mode is False
+ assert not pipe._call_event.is_set()
+
+ pipe._ptt_key_seen_at = 0.0
+ pipe._on_ptt_press()
+ assert pipe._ptt_mode is True
+ assert pipe._call_event.is_set()
+
+ calls = gate.ensure_calls(_MIC)
+ assert [(c.feature, c.interactive, c.wait_s) for c in calls] == [("voice", True, 0.0)] * 2
+
+
+def test_a_muted_ptt_press_never_asks_the_os() -> None:
+ gate = FakePermissionService()
+ gate.script(_MIC, PermissionOutcome.PENDING)
+ pipe = _pipeline(permission=gate)
+ pipe._muted = True
+
+ pipe._on_ptt_press()
+
+ assert gate.calls == []
+ assert pipe._ptt_mode is False
+
+
+def test_a_denied_ptt_press_does_not_arm_a_recording() -> None:
+ gate = FakePermissionService()
+ gate.script(_MIC, PermissionOutcome.DENIED)
+ pipe = _pipeline(permission=gate)
+
+ pipe._on_ptt_press()
+
+ assert pipe._ptt_mode is False
+ assert not pipe._call_event.is_set()
+ assert len(gate.ensure_calls(_MIC)) == 1
+
+
+def test_the_call_key_asks_and_opens_a_session_only_on_a_grant() -> None:
+ gate = FakePermissionService()
+ gate.script(_MIC, PermissionOutcome.PENDING, PermissionOutcome.GRANTED)
+ pipe = _pipeline(permission=gate)
+
+ pipe._dispatch_hotkey_event("call")
+ assert not pipe._call_event.is_set()
+ assert pipe._explicit_call_pending is False
+
+ pipe._dispatch_hotkey_event("call")
+ assert pipe._call_event.is_set()
+ assert pipe._explicit_call_pending is True
+ assert [(c.feature, c.interactive) for c in gate.ensure_calls(_MIC)] == [("voice", True)] * 2
+
+
+def test_request_voice_session_asks_and_arms_only_on_a_grant() -> None:
+ gate = FakePermissionService()
+ gate.script(_MIC, PermissionOutcome.PENDING, PermissionOutcome.GRANTED)
+ brain = SimpleNamespace(seeded=None)
+ brain.seed_history = lambda turns: setattr(brain, "seeded", list(turns))
+ pipe = _pipeline(permission=gate)
+ pipe._brain = brain
+
+ assert pipe.request_voice_session(seed_messages=[("user", "hi")]) is False
+ assert not pipe._call_event.is_set()
+ assert brain.seeded is None, "a refused request must not pollute the brain history"
+
+ assert pipe.request_voice_session(seed_messages=[("user", "hi")]) is True
+ assert pipe._call_event.is_set()
+ assert brain.seeded == [("user", "hi")]
+
+
+def test_an_unreadable_permission_refuses_the_gesture() -> None:
+ class _Broken:
+ def ensure(self, *_a: object, **_k: object) -> object:
+ raise RuntimeError("native failure with a /secret/path")
+
+ pipe = _pipeline(permission=_Broken())
+
+ pipe._on_ptt_press()
+
+ assert pipe._ptt_mode is False
+
+
+# --------------------------------------------------------------------------
+# macOS behaviour: the REAL service over FakeTCC
+# --------------------------------------------------------------------------
+
+
+def _mac(monkeypatch: pytest.MonkeyPatch, **tcc_kwargs: object) -> FakeTCC:
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
+
+
+async def test_first_press_makes_one_microphone_request_and_nothing_starts_retroactively(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _mac(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ bus = EventBus()
+ seen = _Seen(bus)
+ get_permission_service().attach_bus(bus, asyncio.get_running_loop())
+ pipe = _pipeline(bus=bus)
+ started = _record_commits(pipe)
+
+ assert pipe.start_dictation(source="hold_key") is False # the dialog is up
+ await _drain()
+
+ assert len(tcc.requests(TccService.MICROPHONE)) == 1
+ assert tcc.implicit_prompts() == []
+ assert [event.reason for event in seen.refused] == ["microphone_unavailable"]
+ (needed,) = seen.needed
+ assert needed.permissions == ("microphone",)
+ assert (needed.feature, needed.reason, needed.phase, needed.origin) == (
+ "dictation",
+ "not_determined",
+ "os_dialog",
+ "user",
+ )
+
+ # The user answers Allow in the macOS dialog: still nothing starts by itself.
+ tcc.answer(TccService.MICROPHONE, DialogPolicy.ALLOW)
+ await _drain()
+ assert started == []
+ await asyncio.sleep(0.3) # a human takes longer than the service's 250 ms negative cache
+
+ # "Allowed - press again": the second press starts, without a second request.
+ assert pipe.start_dictation(source="hold_key") is True
+ assert started == ["hold_key"]
+ assert len(tcc.requests(TccService.MICROPHONE)) == 1
+
+
+async def test_denied_microphone_second_press_adds_no_request(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _mac(monkeypatch, default_policy=DialogPolicy.DENY)
+ bus = EventBus()
+ seen = _Seen(bus)
+ get_permission_service().attach_bus(bus, asyncio.get_running_loop())
+ pipe = _pipeline(bus=bus)
+ _record_commits(pipe)
+
+ assert pipe.start_dictation() is False
+ await _drain()
+ assert len(tcc.requests(TccService.MICROPHONE)) == 1
+
+ assert pipe.start_dictation() is False
+ await _drain()
+ assert len(tcc.requests(TccService.MICROPHONE)) == 1, "a denial is a stable state"
+ assert tcc.ignored_requests() == [], "macOS was not even asked a second time"
+ assert [event.reason for event in seen.refused] == ["microphone_unavailable"] * 2
+ assert any(event.reason == "denied" and event.phase == "blocked" for event in seen.needed)
+
+
+async def test_a_denied_microphone_refuses_ptt_and_speak_with_one_card_per_episode(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The microphone was denied in an earlier run: the silent user predicate is closed,
+ yet the PTT press and the speak button still reach ``ensure`` so the refusal is
+ never silent. They publish ONE ``PermissionNeeded`` (denied, blocked, user) per
+ episode, make no native request and never arm anything."""
+ tcc = _mac(monkeypatch)
+ tcc.deny(TccService.MICROPHONE)
+ bus = EventBus()
+ seen = _Seen(bus)
+ get_permission_service().attach_bus(bus, asyncio.get_running_loop())
+ pipe = _pipeline(
+ bus=bus, user_gate=lambda: _local_voice_permission_usable(platform_name="darwin")
+ )
+ assert pipe._user_capture_allowed() is False, "the harness must model the closed predicate"
+
+ pipe._on_ptt_press()
+ await _drain()
+ assert pipe._ptt_mode is False
+ assert not pipe._call_event.is_set()
+ assert [(e.permissions, e.reason, e.phase, e.origin, e.feature) for e in seen.needed] == [
+ (("microphone",), "denied", "blocked", "user", "voice")
+ ]
+
+ # Another gesture family in the same episode adds neither a request nor a card.
+ pipe._ptt_key_seen_at = 0.0
+ pipe._on_ptt_press()
+ assert pipe.request_voice_session() is False
+ await _drain()
+ assert len(seen.needed) == 1, "a refusal publishes once per episode"
+ assert not pipe._call_event.is_set()
+ assert tcc.requests() == []
+
+
+async def test_dictation_is_unaffected_when_the_microphone_is_granted(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _mac(monkeypatch, granted=(TccService.MICROPHONE,))
+ pipe = _pipeline()
+ started = _record_commits(pipe)
+
+ assert pipe.start_dictation() is True
+ assert started == ["api"]
+ assert tcc.requests() == []
+
+
+async def test_non_macos_gestures_consult_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ bus = EventBus()
+ seen = _Seen(bus)
+ get_permission_service().attach_bus(bus, asyncio.get_running_loop())
+ pipe = _pipeline(bus=bus)
+ started = _record_commits(pipe)
+
+ assert pipe.start_dictation() is True
+ pipe._on_ptt_press()
+ assert pipe._ptt_mode is True
+ pipe._ptt_mode = False
+ pipe._state = PipelineState.IDLE
+ assert pipe.request_voice_session() is True
+ await _drain()
+
+ assert started == ["api"]
+ tcc.assert_silent()
+ assert seen.needed == [] and seen.refused == []
+
+
+# --------------------------------------------------------------------------
+# The boot rule: nothing is asked at launch
+# --------------------------------------------------------------------------
+
+
+class _Capture:
+ """Stands in for ``MicrophoneCapture``: opening one at boot is a failure."""
+
+ constructed: list[dict[str, object]] = []
+
+ def __init__(self, **kwargs: object) -> None:
+ type(self).constructed.append(kwargs)
+
+
+class _Boot:
+ """The voice pipeline's boot (warm-up, then the wake loop when it is on) over FakeTCC."""
+
+ def __init__(self, monkeypatch: pytest.MonkeyPatch, tcc: FakeTCC, *, wake_word: bool) -> None:
+ self.tcc = tcc
+ self.audio = FakeAudioInput(tcc, caller="boot")
+ _Capture.constructed = []
+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _Capture)
+ import jarvis.audio.capture as capture
+
+ monkeypatch.setattr(capture, "sd", SimpleNamespace(InputStream=self.audio))
+ monkeypatch.setattr(
+ pipeline_mod,
+ "wait_for_stable_audio_devices",
+ lambda **kw: {"available": True, "device_count": 1, "stable": True, "waited_s": 0.0},
+ )
+ monkeypatch.setattr(pipeline_mod, "iter_all_start_ack", lambda: [])
+ self.bus = EventBus()
+ self.seen = _Seen(self.bus)
+ get_permission_service().attach_bus(self.bus, asyncio.get_running_loop())
+ self.listened = asyncio.Event()
+
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ self.pipe = pipe
+ pipe._bus = self.bus
+ pipe._output_device = "auto-headset"
+ pipe._player = SimpleNamespace(set_device=lambda device: None, play_pcm=_no_audio)
+ pipe._stt = None
+ pipe._whisper_wake_enabled = False
+ pipe._openwakeword_enabled = wake_word
+ pipe._vad = SimpleNamespace(_ensure_model=lambda: None)
+ pipe._tts = SimpleNamespace(_ensure_client=lambda: None)
+ pipe._wake = SimpleNamespace(start=_no_audio)
+ pipe._ack_phrase = "Ja?"
+ pipe._ack_pcm = b""
+ pipe._task_ack_pcm = {}
+ pipe._wake_reload_event = asyncio.Event()
+ pipe._wake_parked_on_permission = False
+ pipe._state = PipelineState.IDLE
+ pipe._muted = False
+ pipe._dictation_task = None
+ pipe._dictation_wake_block_until = 0.0
+ pipe._wake_phrase_label = "Hey Jarvis"
+ # The gates are the desktop app's own: silent reads of the real service.
+ pipe._activation_gate = lambda: _local_voice_permission_granted(platform_name="darwin")
+ pipe._user_activation_gate = lambda: _local_voice_permission_usable(platform_name="darwin")
+ pipe._run_parallel_wake = self._listen # type: ignore[method-assign]
+
+ async def _listen(self) -> None:
+ self.listened.set()
+ await asyncio.sleep(3600)
+
+ async def run(self) -> None:
+ """Warm up, then start the wake loop exactly when ``run()`` would."""
+ await self.pipe._warmup()
+ await self.pipe._deferred_warmup_task
+ wake_task = (
+ asyncio.create_task(self.pipe._wake_loop())
+ if self.pipe._wake_listening_enabled()
+ else None
+ )
+ try:
+ await asyncio.sleep(0.2)
+ await _drain()
+ finally:
+ if wake_task is not None:
+ wake_task.cancel()
+ try:
+ await wake_task
+ except asyncio.CancelledError:
+ pass
+ await self.pipe._cancel_warmup_background()
+
+ def assert_nothing_was_asked(self) -> None:
+ assert self.tcc.requests() == [], self.tcc.format_log()
+ assert self.tcc.implicit_prompts() == [], self.tcc.format_log()
+ assert self.audio.starts == [] and self.audio.streams == []
+ assert _Capture.constructed == [], "boot opened a microphone capture"
+
+
+async def _no_audio(*_args: object, **_kwargs: object) -> None:
+ return None
+
+
[email protected]("wake_word", [False, True], ids=["wake_word_off", "wake_word_on"])
+async def test_boot_with_every_permission_not_determined_asks_nothing(
+ monkeypatch: pytest.MonkeyPatch, wake_word: bool
+) -> None:
+ tcc = _mac(monkeypatch)
+ boot = _Boot(monkeypatch, tcc, wake_word=wake_word)
+
+ await boot.run()
+
+ boot.assert_nothing_was_asked()
+ assert not boot.listened.is_set(), "the wake loop listened without a grant"
+ if wake_word:
+ # The wake word waits (parked) and says so in the status snapshot only: one
+ # background-origin episode, never a toast, never a native ask.
+ origins = {(n.feature, n.origin, n.reason) for n in boot.seen.needed}
+ assert origins == {("wake_word", "background", "not_determined")}
+ else:
+ assert boot.seen.needed == []
+ assert get_permission_service().outstanding() == []
+
+
[email protected]("wake_word", [False, True], ids=["wake_word_off", "wake_word_on"])
+async def test_boot_of_an_upgrader_with_every_grant_present_shows_no_card_and_makes_no_request(
+ monkeypatch: pytest.MonkeyPatch, wake_word: bool
+) -> None:
+ tcc = _mac(monkeypatch, granted=tuple(TccService))
+ boot = _Boot(monkeypatch, tcc, wake_word=wake_word)
+
+ await boot.run()
+
+ assert tcc.requests() == [], tcc.format_log()
+ assert tcc.implicit_prompts() == []
+ assert boot.seen.needed == [], "zero permission episodes for an upgrader"
+ assert get_permission_service().outstanding() == []
+ assert boot.listened.is_set() is wake_word # granted: the wake loop listens at once
+
+
+ ("granted", "permissions", "parked", "wakes"),
+ [
+ (True, ("microphone",), True, True),
+ (False, ("microphone",), True, False), # an expired episode is not a grant: no churn
+ (True, ("accessibility",), True, False),
+ (True, ("microphone",), False, False), # a wake capture that runs is never torn down
+ ],
+)
+async def test_only_a_microphone_grant_wakes_a_parked_wake_loop(
+ granted: bool, permissions: tuple[str, ...], parked: bool, wakes: bool
+) -> None:
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._wake_reload_event = asyncio.Event()
+ pipe._wake_parked_on_permission = parked
+
+ await pipe._on_permission_resolved(
+ PermissionResolved(permissions=permissions, feature="wake_word", granted=granted)
+ )
+
+ assert pipe._wake_reload_event.is_set() is wakes
+
+
+async def test_boot_on_a_non_macos_host_never_consults_tcc(monkeypatch: pytest.MonkeyPatch) -> None:
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ boot = _Boot(monkeypatch, tcc, wake_word=True)
+
+ await boot.run()
+
+ tcc.assert_silent()
+ assert boot.seen.needed == []
+ assert boot.listened.is_set()
diff --git a/tests/unit/speech/test_wake_dead_state.py b/tests/unit/speech/test_wake_dead_state.py
index d00821563f..c8bded3e06 100644
--- a/tests/unit/speech/test_wake_dead_state.py
+++ b/tests/unit/speech/test_wake_dead_state.py
@@ -15,6 +15,13 @@ Two concrete permanent-dead-state paths found in the wake plumbing:
hotkey-only mode per the 2026-07-04 product rule, re-armable in-app by a later
``set_wake_plan``), and must NOT fall back to a branded 'Hey Rhasspy' model
(listening for a word the user never says).
+
+3. A wake loop whose only blocker is the MICROPHONE PERMISSION must park, not
+ poll: it opens one background episode (``ensure(interactive=False)``: never an
+ ask), then waits on ``_wake_reload_event``, which a microphone
+ ``PermissionResolved``, ``set_wake_plan`` or the fallback timeout sets. A grant
+ given later in System Settings therefore wakes it in-app, with no restart and
+ no 0.25 s re-probing. Mute / a running dictation keep their short poll.
"""
from __future__ import annotations
@@ -23,8 +30,15 @@ from types import SimpleNamespace
import pytest
+import jarvis.speech.pipeline as pipeline_mod
+from jarvis.audio.capture import MicrophoneAccessError
+from jarvis.core.bus import EventBus
+from jarvis.core.events import PermissionResolved
+from jarvis.platform.permission_service import PermissionOutcome
+from jarvis.platform.permissions import PermissionId
from jarvis.speech.pipeline import PipelineState, SpeechPipeline
from jarvis.speech.wake_phrase import resolve_wake_plan
+from tests.fakes.fake_permission_service import FakePermissionService
@pytest.fixture(autouse=True)
@@ -148,3 +162,287 @@ def test_set_wake_plan_stt_match_with_whisper_uses_rolling_wake(monkeypatch) ->
assert pipe._openwakeword_enabled is False
assert pipe._whisper_wake_enabled is True
assert pipe._wake_listening_enabled() is True
+
+
+# --------------------------------------------------------------------------
+# The wake loop parks on the microphone permission (it never polls, never asks)
+# --------------------------------------------------------------------------
+
+
+class _Wake:
+ """A wake-loop harness: a gate the test opens, a permission fake, no audio."""
+
+ def __init__(self, *, granted: bool = False) -> None:
+ self.granted = granted
+ self.gate_reads = 0
+ self.listened = asyncio.Event()
+ self.permission = FakePermissionService()
+ self.permission.script(PermissionId.MICROPHONE, PermissionOutcome.PENDING)
+ self.pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe = self.pipe
+ pipe._openwakeword_enabled = True
+ pipe._whisper_wake_enabled = False
+ pipe._wake_reload_event = asyncio.Event()
+ pipe._wake_parked_on_permission = False
+ pipe._state = PipelineState.IDLE
+ pipe._muted = False
+ pipe._dictation_task = None
+ pipe._dictation_wake_block_until = 0.0
+ pipe._wake_phrase_label = "Neko"
+ pipe._permission_gate = self.permission
+ pipe._activation_gate = self._gate
+ pipe._run_parallel_wake = self._listen # type: ignore[method-assign]
+
+ def _gate(self) -> bool:
+ self.gate_reads += 1
+ return self.granted
+
+ async def _listen(self) -> None:
+ self.listened.set()
+ await asyncio.sleep(3600) # listening: the loop does not spin
+
+ def grant(self) -> None:
+ """The user allowed the microphone: the gate reads open from now on."""
+ self.granted = True
+ self.permission.grant(PermissionId.MICROPHONE)
+
+ async def run(self, body) -> None: # noqa: ANN001
+ task = asyncio.create_task(self.pipe._wake_loop())
+ try:
+ await body()
+ finally:
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+async def test_wake_loop_parks_on_the_permission_instead_of_polling() -> None:
+ """The old loop slept 0.25 s and re-probed the permission forever (4 reads a
+ second). The new one reads the gate, opens ONE background episode and waits."""
+ wake = _Wake()
+
+ async def body() -> None:
+ await asyncio.sleep(0.8)
+ assert not wake.listened.is_set(), "the wake loop listened without a grant"
+ assert wake.pipe._wake_parked_on_permission is True
+ # One iteration reads the gate for the decision and once more for the log
+ # reason; the old 0.25 s churn would have read it about ten times by now.
+ assert wake.gate_reads <= 3, f"the parked wake loop re-probed {wake.gate_reads} times"
+
+ await wake.run(body)
+
+ calls = wake.permission.ensure_calls(PermissionId.MICROPHONE)
+ assert len(calls) == 1, "the park opens exactly one episode"
+ assert calls[0].feature == "wake_word"
+ assert calls[0].interactive is False, "a background consumer never asks the OS"
+ assert wake.permission.native_free()
+
+
+async def test_a_microphone_grant_wakes_the_parked_loop_without_a_restart() -> None:
+ wake = _Wake()
+ bus = EventBus()
+ bus.subscribe(PermissionResolved, wake.pipe._on_permission_resolved)
+
+ async def body() -> None:
+ await asyncio.sleep(0.1)
+ assert wake.pipe._wake_parked_on_permission is True
+ wake.grant()
+ await bus.publish(
+ PermissionResolved(permissions=("microphone",), feature="wake_word", granted=True)
+ )
+ await asyncio.wait_for(wake.listened.wait(), timeout=2.0)
+
+ await wake.run(body)
+ assert wake.pipe._wake_parked_on_permission is False
+
+
+async def test_only_a_microphone_grant_wakes_the_parked_loop() -> None:
+ wake = _Wake()
+
+ async def body() -> None:
+ await asyncio.sleep(0.1)
+ handler = wake.pipe._on_permission_resolved
+ await handler(PermissionResolved(permissions=("microphone",), granted=False))
+ await handler(PermissionResolved(permissions=("accessibility",), granted=True))
+ await asyncio.sleep(0.1)
+ assert wake.pipe._wake_parked_on_permission is True
+ assert not wake.pipe._wake_reload_event.is_set()
+
+ await wake.run(body)
+
+
+async def test_a_grant_for_a_loop_that_is_not_parked_does_not_restart_the_wake_mic() -> None:
+ """A dictation's grant must not tear down a wake capture that is already running."""
+ wake = _Wake(granted=True)
+
+ async def body() -> None:
+ await asyncio.wait_for(wake.listened.wait(), timeout=2.0)
+ assert wake.pipe._wake_parked_on_permission is False
+ await wake.pipe._on_permission_resolved(
+ PermissionResolved(permissions=("microphone",), feature="dictation", granted=True)
+ )
+ assert not wake.pipe._wake_reload_event.is_set()
+
+ await wake.run(body)
+ assert wake.permission.ensure_calls() == [], "an open gate never opens an episode"
+
+
+async def test_a_wake_plan_change_also_wakes_the_parked_loop() -> None:
+ """``set_wake_plan`` flips the same event: the park is recoverable in-app."""
+ wake = _Wake()
+
+ async def body() -> None:
+ await asyncio.sleep(0.1)
+ wake.grant() # the grant landed, but its edge never arrived
+ wake.pipe._wake_reload_event.set() # what set_wake_plan does
+ await asyncio.wait_for(wake.listened.wait(), timeout=2.0)
+
+ await wake.run(body)
+
+
+async def test_the_fallback_timeout_rereads_the_gate_when_an_edge_was_missed(monkeypatch) -> None:
+ monkeypatch.setattr(pipeline_mod, "_WAKE_PERMISSION_PARK_S", 0.05)
+ wake = _Wake()
+
+ async def body() -> None:
+ await asyncio.sleep(0.1)
+ assert not wake.listened.is_set()
+ wake.granted = True # no event, no listener call: only the timeout can see it
+ await asyncio.wait_for(wake.listened.wait(), timeout=2.0)
+
+ await wake.run(body)
+
+
+async def test_a_lost_grant_at_open_parks_instead_of_looping_on_an_exception() -> None:
+ """``MicrophoneAccessError`` from the capture open is a permission answer, not a
+ crash: no traceback, no 0.5 s retry churn; the loop parks and waits for the grant."""
+ wake = _Wake(granted=True) # the gate said yes, the open then found it gone
+ attempts = 0
+
+ async def _refused() -> None:
+ nonlocal attempts
+ attempts += 1
+ wake.granted = False
+ raise MicrophoneAccessError("Microphone access is not granted for Personal Jarvis.")
+
+ wake.pipe._run_parallel_wake = _refused # type: ignore[method-assign]
+
+ async def body() -> None:
+ await asyncio.sleep(0.8)
+ assert attempts == 1, "the loop retried a refused open instead of parking"
+ assert wake.pipe._wake_parked_on_permission is True
+
+ await wake.run(body)
+ assert len(wake.permission.ensure_calls(PermissionId.MICROPHONE)) == 1
+
+
+async def test_mute_keeps_the_short_poll_and_never_opens_a_permission_episode() -> None:
+ """Only a missing PERMISSION parks. A mute changes on its own clock (no event
+ announces the unmute), so the loop keeps polling the state - and asks nothing."""
+ wake = _Wake(granted=True)
+ wake.pipe._muted = True
+
+ async def body() -> None:
+ await asyncio.sleep(0.1)
+ assert not wake.listened.is_set()
+ assert wake.pipe._wake_parked_on_permission is False
+ wake.pipe._muted = False
+ await asyncio.wait_for(wake.listened.wait(), timeout=1.0)
+
+ await wake.run(body)
+ assert wake.permission.calls == []
+
+
+async def test_switching_the_wake_word_off_while_parked_stops_touching_the_permission(
+ monkeypatch,
+) -> None:
+ """P7: a wake word the user switched OFF owns no permission. The park used to
+ re-open a ``wake_word`` episode on every wake-up because only the pre-loop block
+ looked at the detector flags."""
+ monkeypatch.setattr(pipeline_mod, "_WAKE_PERMISSION_PARK_S", 0.05)
+ wake = _Wake()
+
+ async def body() -> None:
+ await asyncio.sleep(0.2)
+ assert wake.pipe._wake_parked_on_permission is True
+ before = len(wake.permission.ensure_calls(PermissionId.MICROPHONE))
+ assert before >= 1
+ # What ``set_wake_activation(False)`` does: detectors off, reload event set.
+ wake.pipe._openwakeword_enabled = False
+ wake.pipe._whisper_wake_enabled = False
+ wake.pipe._wake_reload_event.set()
+ await asyncio.sleep(0.4) # many park intervals
+ assert wake.pipe._wake_parked_on_permission is False
+ assert len(wake.permission.ensure_calls(PermissionId.MICROPHONE)) == before
+ assert not wake.listened.is_set()
+ # Switching it back on re-arms the loop in-app (the park is recoverable).
+ wake.grant()
+ wake.pipe._openwakeword_enabled = True
+ wake.pipe._wake_reload_event.set()
+ await asyncio.wait_for(wake.listened.wait(), timeout=2.0)
+
+ await wake.run(body)
+
+
+async def test_the_park_itself_opens_no_episode_for_a_switched_off_wake_word() -> None:
+ """The guard also holds for a caller that read the gate before the switch-off."""
+ wake = _Wake()
+ wake.pipe._openwakeword_enabled = False
+ wake.pipe._whisper_wake_enabled = False
+
+ await wake.pipe._park_until_microphone_allowed()
+
+ assert wake.permission.calls == []
+ assert wake.pipe._wake_parked_on_permission is False
+
+
+async def test_the_real_pipeline_subscribes_the_wake_loop_to_microphone_grants() -> None:
+ """The wiring, not just the handler: a ``PermissionResolved(microphone)`` published
+ on the bus a REAL ``SpeechPipeline`` was built with wakes its parked loop well
+ inside the 30 s fallback. Deleting the ``subscribe`` line in ``__init__`` makes it
+ wait for that fallback instead."""
+ bus = EventBus()
+ pipe = SpeechPipeline(tts=_NoTTS(), bus=bus, enable_whisper_wake=False)
+ assert pipeline_mod._WAKE_PERMISSION_PARK_S >= 10.0, "the test needs a long fallback"
+ permission = FakePermissionService()
+ permission.script(PermissionId.MICROPHONE, PermissionOutcome.PENDING)
+ pipe._permission_gate = permission
+ pipe._openwakeword_enabled = True
+ pipe._whisper_wake_enabled = False
+ pipe._wake_phrase_label = "Neko"
+ pipe._state = PipelineState.IDLE
+ state = {"granted": False}
+ pipe._activation_gate = lambda: state["granted"]
+ listened = asyncio.Event()
+
+ async def _listen() -> None:
+ listened.set()
+ await asyncio.sleep(3600)
+
+ pipe._run_parallel_wake = _listen # type: ignore[method-assign]
+ task = asyncio.create_task(pipe._wake_loop())
+ try:
+ await asyncio.sleep(0.1)
+ assert pipe._wake_parked_on_permission is True
+ state["granted"] = True
+ await bus.publish(
+ PermissionResolved(permissions=("microphone",), feature="wake_word", granted=True)
+ )
+ await asyncio.wait_for(listened.wait(), timeout=2.0)
+ finally:
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+class _NoTTS:
+ name = "no-tts"
+ supports_streaming = False
+
+ async def synthesize(self, text: str, language_code=None): # noqa: ANN001, ANN201
+ if False: # pragma: no cover - never called
+ yield b""
diff --git a/tests/unit/tasks/test_scheduler.py b/tests/unit/tasks/test_scheduler.py
index 87b7d11a3e..e085c1c059 100644
--- a/tests/unit/tasks/test_scheduler.py
+++ b/tests/unit/tasks/test_scheduler.py
@@ -10,7 +10,7 @@ import pytest
from jarvis.control.cancel import CancelToken
from jarvis.core.bus import EventBus
-from jarvis.core.events import MessageSent
+from jarvis.core.events import MessageSent, PermissionNeeded
from jarvis.tasks.scheduler import TaskScheduler, _match_filter
from jarvis.tasks.schema import (
SpeakAction,
@@ -162,6 +162,27 @@ async def test_on_event_filter_expr_blocks_non_match(
assert runner.dispatched == [str(spec.id)]
+async def test_on_event_never_dispatches_permission_episodes(
+ store: TaskStore, bus: EventBus, runner: FakeRunner
+) -> None:
+ """A routine stored through any path still cannot react to a system dialog."""
+ scheduler = TaskScheduler(store=store, bus=bus, runner=runner)
+ scheduler.bind_bus()
+
+ spec = TaskSpec(
+ title="permission-watcher",
+ trigger=TriggerOnEvent(event_name="PermissionNeeded", filter_expr=None),
+ action=SpeakAction(text="x"),
+ )
+ await scheduler.schedule(spec)
+
+ await bus.publish(
+ PermissionNeeded(permissions=("microphone",), feature="voice", reason="denied")
+ )
+
+ assert runner.dispatched == []
+
+
# ----------------------------------------------------------------------
# cancel
# ----------------------------------------------------------------------
diff --git a/tests/unit/trigger/test_hotkey_backends.py b/tests/unit/trigger/test_hotkey_backends.py
index ccd3de3688..c98a319db8 100644
--- a/tests/unit/trigger/test_hotkey_backends.py
+++ b/tests/unit/trigger/test_hotkey_backends.py
@@ -440,7 +440,10 @@ def test_noop_backend_explains_the_ACTUAL_reason(monkeypatch):
monkeypatch.setattr("jarvis.platform.detect_platform", lambda: "darwin")
macos = explain_unavailable()
- assert "Accessibility" in macos and "Input Monitoring" in macos
+ # A listen-only tap needs Input Monitoring only; there is no wizard and no restart.
+ assert "Input Monitoring" in macos and "Quartz" in macos
+ assert "Accessibility" not in macos
+ assert "Settings > Permissions" not in macos and "restart" not in macos.lower()
def test_noop_backend_reason_never_raises(monkeypatch):
@@ -623,11 +626,12 @@ def _install_fake_pynput(monkeypatch, built: list) -> None:
monkeypatch.setitem(sys.modules, "pynput", fake_pynput)
-def test_pynput_backend_darwin_without_ax_grant_degrades(monkeypatch, caplog):
+def test_pynput_backend_darwin_without_input_monitoring_degrades(monkeypatch, caplog):
# pynput's darwin backend creates a Quartz event tap on its own internal
- # thread; without the Accessibility grant that native init can abort the
- # whole process (uncatchable — BUG-058 class). The backend must preflight
- # AXIsProcessTrusted and degrade instead of touching pynput at all.
+ # thread; without Input Monitoring that native init can abort the whole
+ # process (uncatchable — BUG-058 class). The backend must preflight the
+ # grant and degrade instead of touching pynput at all, and its text names
+ # Input Monitoring only (a listen-only tap needs nothing else).
import jarvis.trigger.backends.pynput as pynput_backend
from jarvis.trigger.backends.pynput import PynputBackend
@@ -639,7 +643,9 @@ def test_pynput_backend_darwin_without_ax_grant_degrades(monkeypatch, caplog):
with caplog.at_level(logging.WARNING):
backend.start()
assert built == [] # no Listener constructed under the missing grant
- assert "accessibility" in caplog.text.lower()
+ assert "input monitoring" in caplog.text.lower()
+ assert "accessibility" not in caplog.text.lower()
+ assert "settings > permissions" not in caplog.text.lower()
def test_pynput_backend_darwin_unverifiable_grant_degrades(monkeypatch, caplog):
diff --git a/tests/unit/trigger/test_quartz_backend.py b/tests/unit/trigger/test_quartz_backend.py
index daa25e1178..24b8a69b6d 100644
--- a/tests/unit/trigger/test_quartz_backend.py
+++ b/tests/unit/trigger/test_quartz_backend.py
@@ -9,6 +9,7 @@ degrade paths; the live tap is exercised on macOS hardware/CI only.
from __future__ import annotations
+import logging
import re
from pathlib import Path
@@ -94,12 +95,18 @@ def test_permission_revocation_clears_chords_and_blocks_handlers() -> None:
assert backend._held == set()
-def test_start_without_permission_is_a_noop(caplog) -> None:
+def test_start_without_permission_is_a_silent_noop(caplog) -> None:
+ """Boot without Input Monitoring: no tap, INFO only, never a warning."""
backend = _backend_with_permission(granted=False)
- backend.start()
+ with caplog.at_level(logging.DEBUG, logger="jarvis.trigger.backends.quartz"):
+ backend.start()
assert backend._started is False
assert backend._tap is None
- assert any("hotkeys disabled" in r.message.lower() for r in caplog.records)
+ assert backend.waiting_for_permission is True
+ assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
+ text = " ".join(r.message for r in caplog.records)
+ assert "Input Monitoring" in text
+ assert "Accessibility" not in text and "Settings > Permissions" not in text
def test_start_without_quartz_degrades(monkeypatch, caplog) -> None:
diff --git a/tests/unit/trigger/test_quartz_jit_permissions.py b/tests/unit/trigger/test_quartz_jit_permissions.py
new file mode 100644
index 0000000000..a2b72b6b24
--- /dev/null
+++ b/tests/unit/trigger/test_quartz_jit_permissions.py
@@ -0,0 +1,871 @@
+"""The macOS global-shortcut tap under just-in-time permissions (AP-35).
+
+Driven against ``FakeTCC`` + ``FakeEventTap`` (the stateful macOS simulator in
+``tests/fakes``), so the REAL permission port, the REAL permission service and
+the REAL ``QuartzHotkeyBackend`` / ``HotkeyTrigger`` run on top of it. Nothing
+here is verified on a real Mac; the fidelity labels of ``fake_tcc`` apply.
+
+What is pinned:
+
+* Boot with nothing granted creates no event tap, makes no request and logs at
+ INFO only (the lazy tap; never a tap to provoke a prompt, BUG-058 class).
+* The requirement is Input Monitoring ONLY; Accessibility is not consulted.
+* A grant re-arms the tap in process through the service listener, once.
+* The tap callback never reaches the service's ensure path or its lock.
+* The raw-callback counter, the deaf-tap rules and "never auto-restart".
+* Non-darwin: nothing requested, nothing published, backends without the probe
+ untouched.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+
+import pytest
+
+from jarvis.platform import permission_service as service_mod
+from jarvis.platform.permissions import PermissionId, PermissionState
+from jarvis.trigger.backends import quartz as quartz_mod
+from jarvis.trigger.backends.pynput import _macos_hotkey_permissions_granted
+from jarvis.trigger.backends.quartz import QuartzHotkeyBackend
+from jarvis.trigger.hotkey import HotkeyTrigger
+from tests.fakes.fake_quartz_tap import FakeQuartz
+from tests.fakes.fake_tcc import (
+ FakeTCC,
+ TccService,
+ install_port,
+ make_darwin_port,
+ make_non_darwin_port,
+)
+
+_KC_J = 0x26
+_FLAG_CTRL = 1 << 18
+
+
+def _darwin(monkeypatch: pytest.MonkeyPatch) -> tuple[FakeTCC, FakeQuartz]:
+ """A Mac where nothing was decided yet, with the fake tap installed."""
+ port, tcc = make_darwin_port()
+ install_port(monkeypatch, port)
+ fake = FakeQuartz(tcc).install(monkeypatch)
+ return tcc, fake
+
+
+def _backend(*rows: list) -> QuartzHotkeyBackend:
+ backend = QuartzHotkeyBackend() # the DEFAULT permission seam: the service
+ backend.register(list(rows) or [["control + j", lambda: None, None]])
+ return backend
+
+
+# --------------------------------------------------------------------------
+# Boot: lazy, silent, never asking.
+# --------------------------------------------------------------------------
+
+
+def test_boot_with_nothing_granted_creates_no_tap_and_asks_nothing(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ backend = _backend()
+
+ with caplog.at_level(logging.DEBUG, logger="jarvis.trigger.backends.quartz"):
+ backend.start()
+
+ assert fake.tap.attempts == [], "CGEventTapCreate must wait for the grant"
+ assert tcc.requests() == []
+ assert tcc.implicit_prompts() == []
+ assert tcc.dialogs_shown() == []
+ assert backend.is_listening() is False
+ assert backend.waiting_for_permission is True
+ # The decision is still the user's: nothing registered the app as denied.
+ assert tcc.state(TccService.INPUT_MONITORING).value == "not_determined"
+ quiet = [r for r in caplog.records if r.levelno >= logging.WARNING]
+ assert quiet == [], "an unattended Mac at boot must not produce warnings"
+ assert any(
+ r.levelno == logging.INFO and "Input Monitoring" in r.message for r in caplog.records
+ )
+
+
+def test_boot_is_silent_with_input_monitoring_denied_too(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ tcc.deny(TccService.INPUT_MONITORING)
+ _backend().start()
+ assert fake.tap.attempts == []
+ assert tcc.requests() == [] and tcc.implicit_prompts() == []
+
+
+def test_the_requirement_is_input_monitoring_only(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc, _fake = _darwin(monkeypatch)
+ tcc.grant(TccService.ACCESSIBILITY) # Accessibility alone does not arm the tap
+ assert _macos_hotkey_permissions_granted() is False
+
+ service_mod.get_permission_service().invalidate() # skip the 250 ms negative cache
+ tcc.grant(TccService.INPUT_MONITORING)
+ tcc.deny(TccService.ACCESSIBILITY) # and it is not needed once Input Monitoring is on
+ assert _macos_hotkey_permissions_granted() is True
+
+
+def test_input_monitoring_granted_creates_the_tap_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ tcc.grant(TccService.INPUT_MONITORING)
+ backend = _backend()
+ try:
+ backend.start()
+ backend.start() # idempotent: the permission listener may call it again
+ assert fake.tap.attempts == ["live"]
+ assert backend.is_listening() is True
+ assert backend.waiting_for_permission is False
+ assert tcc.requests() == [] and tcc.implicit_prompts() == []
+ finally:
+ backend.stop()
+
+
+def test_a_listening_tap_still_never_asks_for_anything(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ tcc.grant(TccService.INPUT_MONITORING)
+ backend = _backend()
+ try:
+ backend.start()
+ fake.deliver_flags(_FLAG_CTRL)
+ fake.deliver_key(_KC_J)
+ assert tcc.requests() == []
+ finally:
+ backend.stop()
+
+
+# --------------------------------------------------------------------------
+# The tap callback: lock-free cached verdict, never the service's ensure path.
+# --------------------------------------------------------------------------
+
+
+class _ForbiddenLock:
+ """A lock that fails the test the moment anything takes it."""
+
+ def __enter__(self) -> None:
+ raise AssertionError("the tap callback took a permission-service lock")
+
+ def __exit__(self, *_exc: object) -> None:
+ return None
+
+ def acquire(self, *_args: object, **_kwargs: object) -> bool:
+ raise AssertionError("the tap callback took a permission-service lock")
+
+ def release(self) -> None:
+ return None
+
+
+def test_the_tap_callback_never_calls_ensure_or_takes_a_service_lock(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ tcc.grant(TccService.INPUT_MONITORING)
+ fired: list[str] = []
+ backend = _backend(["control + j", lambda: fired.append("down"), lambda: fired.append("up")])
+ service = service_mod.get_permission_service()
+ real_lock = service._lock
+ reads: list[str] = []
+ real_check = service.check
+
+ def counting_check(permission, **kwargs): # noqa: ANN001, ANN003
+ reads.append(str(permission))
+ return real_check(permission, **kwargs)
+
+ def forbidden(*_args: object, **_kwargs: object) -> None:
+ raise AssertionError("the tap callback reached the service's ensure path")
+
+ try:
+ backend.start()
+ monkeypatch.setattr(service, "check", counting_check)
+ for name in ("ensure", "ensure_all", "ensure_async", "ensure_all_async", "open_settings"):
+ monkeypatch.setattr(service, name, forbidden)
+ monkeypatch.setattr(service, "_lock", _ForbiddenLock())
+
+ # Force a re-probe inside the callback (the cached verdict went stale).
+ backend._permission_checked_at = 0.0
+ assert fake.deliver_flags(_FLAG_CTRL)
+ assert fake.deliver_key(_KC_J)
+ fake.deliver_key(_KC_J, down=False)
+ finally:
+ service._lock = real_lock # the fixture's teardown needs the real one
+ backend.stop()
+
+ assert fired == ["down", "up"]
+ assert reads and set(reads) == {"input_monitoring"}, "only the silent check, only IM"
+
+
+def test_the_callback_reads_a_cached_verdict_not_a_probe_per_event(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ tcc.grant(TccService.INPUT_MONITORING)
+ backend = _backend()
+ try:
+ backend.start()
+ for _ in range(60):
+ fake.deliver_key(_KC_J)
+ fake.deliver_key(_KC_J, down=False)
+ # One verdict at most, not one native probe per keystroke.
+ assert len(tcc.probes(TccService.INPUT_MONITORING)) <= 2
+ finally:
+ backend.stop()
+
+
+# --------------------------------------------------------------------------
+# Raw-callback counter and the deaf-tap rules.
+# --------------------------------------------------------------------------
+
+
+def test_every_event_the_tap_hears_counts_bound_or_not(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ tcc.grant(TccService.INPUT_MONITORING)
+ backend = _backend()
+ try:
+ backend.start()
+ assert backend.raw_event_count() == 0
+ fake.deliver_key(0x00) # "a": not part of any chord
+ fake.deliver_flags(_FLAG_CTRL)
+ fake.deliver_key(0x00, down=False)
+ assert backend.raw_event_count() == 3
+ assert backend.received_any_event() is False, "no BOUND chord fired"
+ finally:
+ backend.stop()
+
+
+def _listening_backend(monkeypatch: pytest.MonkeyPatch) -> tuple[QuartzHotkeyBackend, FakeQuartz]:
+ tcc, fake = _darwin(monkeypatch)
+ tcc.grant(TccService.INPUT_MONITORING)
+ backend = _backend()
+ backend.start()
+ assert backend.is_listening()
+ backend._secure_input_enabled = lambda: False # the Carbon flag cannot be read here
+ return backend, fake
+
+
+def test_a_tap_that_is_not_listening_is_never_called_deaf(monkeypatch: pytest.MonkeyPatch) -> None:
+ _darwin(monkeypatch)
+ backend = _backend()
+ assert backend.deaf_tap_suspected() is False
+
+
+def test_deaf_needs_user_typing_after_the_tap_came_up(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, _fake = _listening_backend(monkeypatch)
+ try:
+ now = quartz_mod.time.monotonic()
+ backend._armed_at = now - 30.0
+
+ # The user typed 5 s ago, i.e. after the tap came up, and it heard nothing.
+ backend._seconds_since_last_key = lambda: 5.0
+ assert backend.deaf_tap_suspected() is True
+
+ # Nobody has typed since the tap came up: not deaf, just idle.
+ backend._seconds_since_last_key = lambda: 600.0
+ assert backend.deaf_tap_suspected() is False
+
+ # The idle counter is unreadable: no claim.
+ backend._seconds_since_last_key = lambda: None
+ assert backend.deaf_tap_suspected() is False
+
+ # Too young to judge.
+ backend._armed_at = now - 1.0
+ backend._seconds_since_last_key = lambda: 0.5
+ assert backend.deaf_tap_suspected() is False
+ finally:
+ backend.stop()
+
+
+def test_secure_event_input_never_reads_as_a_deaf_tap(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Under Secure Event Input macOS hides key events from every tap by design."""
+ backend, _fake = _listening_backend(monkeypatch)
+ try:
+ backend._armed_at = quartz_mod.time.monotonic() - 30.0
+ # The idle counter advances (the user typed into a password field) ...
+ backend._seconds_since_last_key = lambda: 5.0
+ backend._secure_input_enabled = lambda: True
+ assert backend.deaf_tap_suspected() is False, "a healthy tap must not ask for a restart"
+ # ... an unreadable flag makes no claim either ...
+ backend._secure_input_enabled = lambda: None
+ assert backend.deaf_tap_suspected() is False
+ # ... and with the flag read as off the same evidence is a deaf tap.
+ backend._secure_input_enabled = lambda: False
+ assert backend.deaf_tap_suspected() is True
+ finally:
+ backend.stop()
+
+
+def test_the_secure_input_probe_is_lazy_and_reads_unknown_when_carbon_is_missing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A missing Carbon framework reads "unknown", never an exception.
+
+ Hermetic: on a real Mac the framework exists, so the load is made to fail
+ instead of relying on the host being something other than a Mac.
+ """
+ import ctypes
+
+ def _no_framework(*_args: object, **_kwargs: object) -> object:
+ raise OSError("Carbon.framework is not available")
+
+ monkeypatch.setattr(ctypes.cdll, "LoadLibrary", _no_framework)
+ assert quartz_mod._secure_event_input_enabled() is None
+
+
+def test_stop_waits_for_a_start_that_is_already_running(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A grant-driven start in a worker thread must not outlive the stop that follows."""
+ import threading
+
+ tcc, _fake = _darwin(monkeypatch)
+ tcc.grant(TccService.INPUT_MONITORING)
+ backend = _backend()
+ inside, release = threading.Event(), threading.Event()
+ real_check = backend._permission_check
+
+ def slow_check() -> bool:
+ inside.set()
+ assert release.wait(5), "the test never released the start"
+ return real_check()
+
+ backend._permission_check = slow_check
+ starter = threading.Thread(target=backend.start)
+ starter.start()
+ assert inside.wait(5)
+ stopper = threading.Thread(target=backend.stop)
+ stopper.start()
+ stopper.join(0.2)
+ assert stopper.is_alive(), "stop() must wait for the start in flight"
+ release.set()
+ starter.join(5)
+ stopper.join(5)
+ assert not stopper.is_alive() and not starter.is_alive()
+ assert backend.is_listening() is False, "no orphan tap after the stop"
+
+
+def test_one_heard_event_ends_the_suspicion(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, fake = _listening_backend(monkeypatch)
+ try:
+ backend._armed_at = quartz_mod.time.monotonic() - 30.0
+ backend._seconds_since_last_key = lambda: 5.0
+ assert backend.deaf_tap_suspected() is True
+ fake.deliver_key(0x00)
+ assert backend.deaf_tap_suspected() is False
+ finally:
+ backend.stop()
+
+
+def test_a_deaf_tap_is_never_restarted_automatically(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, fake = _listening_backend(monkeypatch)
+ try:
+ backend._armed_at = quartz_mod.time.monotonic() - 30.0
+ backend._seconds_since_last_key = lambda: 5.0
+ thread = backend._thread
+ for _ in range(3):
+ assert backend.deaf_tap_suspected() is True
+ assert backend.is_listening() is True
+ assert backend._thread is thread
+ assert fake.tap.attempts == ["live"], "the hint must not recreate the tap"
+ finally:
+ backend.stop()
+
+
+def test_a_restarted_tap_starts_a_fresh_count(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, fake = _listening_backend(monkeypatch)
+ try:
+ fake.deliver_key(0x00)
+ assert backend.raw_event_count() == 1
+ backend.stop()
+ backend.start()
+ assert backend.raw_event_count() == 0
+ finally:
+ backend.stop()
+
+
+def _make_deaf(backend: QuartzHotkeyBackend) -> None:
+ """The user typed after the tap came up and the tap heard nothing."""
+ backend._armed_at = quartz_mod.time.monotonic() - 30.0
+ backend._seconds_since_last_key = lambda: 5.0
+
+
+def test_a_deaf_tap_is_reported_once_as_a_restart_hint_and_never_restarted(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ backend, fake = _listening_backend(monkeypatch)
+ service = service_mod.get_permission_service()
+ reports: list[tuple[str, str]] = []
+ real_report = service.report_failed_use
+
+ def spy(permission, *, feature, **kwargs): # noqa: ANN001, ANN003
+ reports.append((str(permission), feature))
+ return real_report(permission, feature=feature, **kwargs)
+
+ monkeypatch.setattr(service, "report_failed_use", spy)
+ try:
+ _make_deaf(backend)
+ thread = backend._thread
+ for _ in range(3):
+ assert backend.report_if_deaf() is True # still worth watching
+ assert reports == [("input_monitoring", "global_shortcuts")], "once per tap"
+ (episode,) = service.outstanding()
+ assert (episode.permissions, episode.feature, episode.reason, episode.origin) == (
+ ("input_monitoring",),
+ "global_shortcuts",
+ "restart_hint",
+ "user",
+ )
+ # A hint: nothing was asked, nothing restarted.
+ assert backend.is_listening() is True and backend._thread is thread
+ assert fake.tap.attempts == ["live"]
+ assert fake.tcc.requests() == []
+ finally:
+ backend.stop()
+
+
+def test_a_tap_that_has_heard_events_is_never_reported_and_stops_the_watch(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ backend, fake = _listening_backend(monkeypatch)
+ try:
+ _make_deaf(backend)
+ fake.deliver_key(0x00)
+ assert backend.report_if_deaf() is False # healthy: nothing left to watch
+ assert service_mod.get_permission_service().outstanding() == []
+ finally:
+ backend.stop()
+
+
+ "secure_input, idle",
+ [(True, 5.0), (None, 5.0), (False, 600.0), (False, None)],
+ ids=["secure_input", "flag_unreadable", "nobody_typed", "idle_unreadable"],
+)
+def test_the_deaf_rules_gate_the_report(
+ monkeypatch: pytest.MonkeyPatch, secure_input: bool | None, idle: float | None
+) -> None:
+ backend, _fake = _listening_backend(monkeypatch)
+ try:
+ _make_deaf(backend)
+ backend._secure_input_enabled = lambda: secure_input
+ backend._seconds_since_last_key = lambda: idle
+ assert backend.report_if_deaf() is True
+ assert service_mod.get_permission_service().outstanding() == []
+ finally:
+ backend.stop()
+
+
+def test_a_tap_that_is_not_listening_reads_nothing_and_reports_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, _fake = _darwin(monkeypatch)
+ backend = _backend()
+ backend.start() # nothing granted: no tap
+ before = len(tcc.calls)
+ assert backend.report_if_deaf() is True
+ assert len(tcc.calls) == before, "no tap, so the liveness pass reads nothing"
+ assert tcc.requests() == []
+ assert service_mod.get_permission_service().outstanding() == []
+
+
+def test_a_tap_that_starts_hearing_after_the_report_ends_the_episode(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ backend, fake = _listening_backend(monkeypatch)
+ service = service_mod.get_permission_service()
+ try:
+ _make_deaf(backend)
+ backend.report_if_deaf()
+ assert [e.reason for e in service.outstanding()] == ["restart_hint"]
+
+ fake.deliver_key(0x00) # the tap hears the keyboard after all
+ assert backend.report_if_deaf() is False
+ service.refresh_episodes()
+ assert service.outstanding() == []
+ finally:
+ backend.stop()
+
+
+def test_a_restarted_tap_is_a_new_episode(monkeypatch: pytest.MonkeyPatch) -> None:
+ backend, fake = _listening_backend(monkeypatch)
+ service = service_mod.get_permission_service()
+ try:
+ _make_deaf(backend)
+ backend.report_if_deaf()
+ assert backend._deaf_reported is True
+ assert [e.reason for e in service.outstanding()] == ["restart_hint"]
+ backend.stop()
+ backend.start()
+ assert backend._deaf_reported is False
+ # The episode the old tap opened is still open until a tap hears something.
+ assert [e.reason for e in service.outstanding()] == ["restart_hint"]
+
+ backend._secure_input_enabled = lambda: False
+ fake.deliver_key(0x00) # the NEW tap hears the keyboard
+ assert backend.report_if_deaf() is False
+ service.refresh_episodes()
+ assert service.outstanding() == [], "a healthy new tap must end the old card"
+ finally:
+ backend.stop()
+
+
+# --------------------------------------------------------------------------
+# HotkeyTrigger: the grant re-arms the backend in process.
+# --------------------------------------------------------------------------
+
+
+async def _enter_trigger(monkeypatch: pytest.MonkeyPatch) -> HotkeyTrigger:
+ import jarvis.trigger.hotkey as hotkey_mod
+
+ monkeypatch.setattr(hotkey_mod, "make_hotkey_backend", lambda: QuartzHotkeyBackend())
+ trigger = HotkeyTrigger({"call": ["control+j"]})
+ await trigger.__aenter__()
+ return trigger
+
+
+async def _settle(trigger: HotkeyTrigger) -> None:
+ for _ in range(100):
+ task = trigger._grant_task
+ if task is not None and task.done():
+ return
+ await asyncio.sleep(0.01)
+
+
+async def test_a_grant_after_boot_arms_the_tap_once(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ service = service_mod.get_permission_service()
+ trigger = await _enter_trigger(monkeypatch)
+ try:
+ assert trigger.listening() is False
+ assert trigger.armed is False
+ assert trigger.needs_input_monitoring is True
+ assert fake.tap.attempts == []
+ # The wait opened a background episode: no request, no dialog.
+ assert tcc.requests() == [] and tcc.dialogs_shown() == []
+ assert [e.permissions for e in service.outstanding()] == [("input_monitoring",)]
+
+ tcc.grant(TccService.INPUT_MONITORING) # the user flips the switch in System Settings
+ service.invalidate() # the 250 ms negative cache has long expired by the watcher's tick
+ await asyncio.to_thread(service.refresh_episodes)
+ await _settle(trigger)
+
+ assert fake.tap.attempts == ["live"], "exactly one tap, created after the grant"
+ assert trigger.armed is True
+ assert trigger.needs_input_monitoring is False
+ assert tcc.requests() == []
+ finally:
+ await trigger.__aexit__(None, None, None)
+
+
+async def test_a_second_grant_signal_does_not_create_a_second_tap(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ trigger = await _enter_trigger(monkeypatch)
+ try:
+ tcc.grant(TccService.INPUT_MONITORING)
+ service_mod.get_permission_service().invalidate() # as the service's own detection does
+ trigger._on_input_monitoring_granted()
+ trigger._on_input_monitoring_granted()
+ await asyncio.sleep(0.05)
+ await _settle(trigger)
+ trigger._on_input_monitoring_granted()
+ await asyncio.sleep(0.05)
+ await _settle(trigger)
+ assert fake.tap.attempts == ["live"]
+ finally:
+ await trigger.__aexit__(None, None, None)
+
+
+async def test_an_all_granted_upgrader_arms_at_boot_with_zero_requests(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ tcc.grant(TccService.INPUT_MONITORING)
+ trigger = await _enter_trigger(monkeypatch)
+ try:
+ assert trigger.armed is True
+ assert fake.tap.attempts == ["live"]
+ assert tcc.requests() == [] and tcc.implicit_prompts() == []
+ assert service_mod.get_permission_service().outstanding() == []
+ finally:
+ await trigger.__aexit__(None, None, None)
+
+
+async def test_a_failing_rearm_never_leaks_out_of_its_task(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ """AP-18: a backend that raises in ``start`` is logged, not propagated."""
+ tcc, _fake = _darwin(monkeypatch)
+ trigger = await _enter_trigger(monkeypatch)
+ try:
+ backend = trigger._backend
+ assert backend is not None
+
+ def explode() -> None:
+ raise RuntimeError("tap thread exploded")
+
+ monkeypatch.setattr(backend, "start", explode)
+ tcc.grant(TccService.INPUT_MONITORING)
+ with caplog.at_level(logging.ERROR, logger="jarvis.trigger.hotkey"):
+ trigger._on_input_monitoring_granted()
+ await _settle(trigger)
+ task = trigger._grant_task
+ assert task is not None and task.done() and task.exception() is None
+ assert any("Re-arming the global shortcuts" in r.message for r in caplog.records)
+ finally:
+ await trigger.__aexit__(None, None, None)
+
+
+async def test_leaving_the_trigger_unsubscribes_its_grant_listener(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _tcc, _fake = _darwin(monkeypatch)
+ service = service_mod.get_permission_service()
+ trigger = await _enter_trigger(monkeypatch)
+ assert service._listeners.get(PermissionId.INPUT_MONITORING)
+ await trigger.__aexit__(None, None, None)
+ assert not service._listeners.get(PermissionId.INPUT_MONITORING)
+
+
+async def test_a_grant_long_after_the_service_episode_would_have_expired_still_arms(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The trigger renews its background episode, so the 10-minute expiry never hides a grant."""
+ import jarvis.trigger.hotkey as hotkey_mod
+
+ tcc, fake = _darwin(monkeypatch)
+ service = service_mod.get_permission_service()
+ service._episode_ttl_s = 0.3 # stands in for the service's 600 s expiry
+ monkeypatch.setattr(hotkey_mod, "_EPISODE_RENEW_S", 0.05)
+ trigger = await _enter_trigger(monkeypatch)
+ try:
+ for _ in range(8): # well past the expiry: each tick runs the service's own sweep
+ await asyncio.sleep(0.1)
+ await asyncio.to_thread(service.refresh_episodes)
+ assert [e.permissions for e in service.outstanding()] == [("input_monitoring",)]
+ assert fake.tap.attempts == []
+
+ tcc.grant(TccService.INPUT_MONITORING)
+ service.invalidate()
+ await asyncio.to_thread(service.refresh_episodes)
+ await _settle(trigger)
+ assert fake.tap.attempts == ["live"], "the grant after the expiry window must re-arm"
+ assert tcc.requests() == [] and tcc.dialogs_shown() == []
+ finally:
+ await trigger.__aexit__(None, None, None)
+
+
+async def test_the_episode_renewal_task_ends_with_the_trigger(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jarvis.trigger.hotkey as hotkey_mod
+
+ _tcc, _fake = _darwin(monkeypatch)
+ monkeypatch.setattr(hotkey_mod, "_EPISODE_RENEW_S", 0.05)
+ trigger = await _enter_trigger(monkeypatch)
+ keepalive = trigger._keepalive_task
+ assert keepalive is not None and not keepalive.done()
+ await trigger.__aexit__(None, None, None)
+ await asyncio.sleep(0)
+ assert keepalive.done()
+ assert trigger._keepalive_task is None
+
+
+async def test_leaving_during_a_grant_rearm_leaves_no_orphan_tap(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``__aexit__`` waits for the ``start`` running in a worker thread before ``stop``."""
+ import threading
+
+ tcc, fake = _darwin(monkeypatch)
+ trigger = await _enter_trigger(monkeypatch)
+ backend = trigger._backend
+ assert backend is not None
+ gate = threading.Event()
+ real_start = backend.start
+
+ def slow_start() -> None:
+ assert gate.wait(5), "the test never released the start"
+ real_start()
+
+ monkeypatch.setattr(backend, "start", slow_start)
+ tcc.grant(TccService.INPUT_MONITORING)
+ service_mod.get_permission_service().invalidate()
+ trigger._on_input_monitoring_granted()
+ await asyncio.sleep(0.05) # the start is now blocked inside its worker thread
+ leaving = asyncio.create_task(trigger.__aexit__(None, None, None))
+ await asyncio.sleep(0.05)
+ assert not leaving.done(), "the exit must wait for the start in flight"
+ gate.set()
+ await asyncio.wait_for(leaving, 10)
+ await asyncio.sleep(0.1)
+ assert backend.is_listening() is False, "no live tap may outlive the trigger"
+ assert fake.tap.attempts == ["live"] # the start did finish, then the stop tore it down
+
+
+async def test_a_grant_signal_after_leaving_starts_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc, fake = _darwin(monkeypatch)
+ trigger = await _enter_trigger(monkeypatch)
+ await trigger.__aexit__(None, None, None)
+ tcc.grant(TccService.INPUT_MONITORING)
+ trigger._on_input_monitoring_granted()
+ await asyncio.sleep(0.05)
+ assert trigger._grant_task is None
+ assert fake.tap.attempts == []
+
+
+async def test_no_backend_and_the_noop_backend_report_that_nothing_listens(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The Esc pill must not promise a key when no listener exists (any OS)."""
+ import jarvis.trigger.hotkey as hotkey_mod
+ from jarvis.trigger.backends.noop import NoopBackend
+
+ port, _tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ assert HotkeyTrigger({"cu_cancel": ["esc"]}).listening() is None, "not entered yet"
+
+ monkeypatch.setattr(hotkey_mod, "make_hotkey_backend", lambda: NoopBackend())
+ async with HotkeyTrigger({"cu_cancel": ["esc"]}) as noop:
+ assert noop.listening() is False
+
+ def refuse() -> None:
+ raise RuntimeError("no backend")
+
+ monkeypatch.setattr(hotkey_mod, "make_hotkey_backend", refuse)
+ async with HotkeyTrigger({"cu_cancel": ["esc"]}) as failed:
+ assert failed._backend is None
+ assert failed.listening() is False
+
+
+async def test_the_trigger_watches_a_listening_tap_and_reports_it_when_it_is_deaf(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jarvis.trigger.hotkey as hotkey_mod
+
+ monkeypatch.setattr(hotkey_mod, "_LIVENESS_POLL_S", 0.01)
+ tcc, fake = _darwin(monkeypatch)
+ tcc.grant(TccService.INPUT_MONITORING)
+ trigger = await _enter_trigger(monkeypatch)
+ backend = trigger._backend
+ assert backend is not None and trigger._liveness_task is not None
+ try:
+ backend._secure_input_enabled = lambda: False
+ _make_deaf(backend)
+ for _ in range(200):
+ if service_mod.get_permission_service().outstanding():
+ break
+ await asyncio.sleep(0.01)
+ (episode,) = service_mod.get_permission_service().outstanding()
+ assert (episode.feature, episode.reason) == ("global_shortcuts", "restart_hint")
+ assert fake.tap.attempts == ["live"], "the hint never recreates the tap"
+ assert tcc.requests() == []
+ finally:
+ await trigger.__aexit__(None, None, None)
+ assert trigger._liveness_task is None
+
+
+async def test_boot_with_nothing_granted_runs_the_watch_without_touching_the_os(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jarvis.trigger.hotkey as hotkey_mod
+
+ monkeypatch.setattr(hotkey_mod, "_LIVENESS_POLL_S", 0.01)
+ tcc, fake = _darwin(monkeypatch)
+ trigger = await _enter_trigger(monkeypatch)
+ try:
+ calls_before = len(tcc.calls)
+ await asyncio.sleep(0.1) # several liveness passes
+ assert len(tcc.calls) == calls_before, "no tap, so nothing to read"
+ assert fake.tap.attempts == [] and tcc.requests() == []
+ finally:
+ await trigger.__aexit__(None, None, None)
+
+
+async def test_a_backend_without_the_liveness_probe_gets_no_watch(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jarvis.trigger.hotkey as hotkey_mod
+
+ port, tcc = make_non_darwin_port("win32")
+ install_port(monkeypatch, port)
+ monkeypatch.setattr(hotkey_mod, "make_hotkey_backend", lambda: _PlainBackend())
+ async with HotkeyTrigger({"call": ["f3+f4"]}) as trigger:
+ assert trigger._liveness_task is None
+ tcc.assert_silent()
+
+
+# --------------------------------------------------------------------------
+# Off macOS nothing changes.
+# --------------------------------------------------------------------------
+
+
+class _PlainBackend:
+ """A hand-written backend like the Windows poller: no permission probes."""
+
+ def __init__(self) -> None:
+ self.started = 0
+
+ def register(self, bindings, on_event=None) -> None: # noqa: ANN001
+ return None
+
+ def unregister(self) -> None:
+ return None
+
+ def start(self) -> None:
+ self.started += 1
+
+ def stop(self) -> None:
+ return None
+
+ def received_any_event(self) -> bool:
+ return False
+
+ def chord_is_down(self, combo: str) -> bool | None:
+ return None
+
+
+async def test_a_backend_without_a_permission_never_touches_the_service(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jarvis.trigger.hotkey as hotkey_mod
+
+ port, tcc = make_non_darwin_port("win32")
+ install_port(monkeypatch, port)
+ monkeypatch.setattr(hotkey_mod, "make_hotkey_backend", lambda: _PlainBackend())
+ trigger = HotkeyTrigger({"call": ["f3+f4"]})
+ async with trigger:
+ assert trigger.listening() is None, "cannot say: the pill keeps its old behaviour"
+ assert trigger.armed is False
+ assert trigger.needs_input_monitoring is False
+ tcc.assert_silent()
+ assert service_mod._SERVICE is None or not service_mod._SERVICE._listeners
+
+
+def test_off_macos_the_default_probe_reads_not_required_and_asks_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ assert service_mod.get_permission_service().check(PermissionId.INPUT_MONITORING) is (
+ PermissionState.NOT_REQUIRED
+ )
+ assert _macos_hotkey_permissions_granted() is True
+ tcc.assert_silent()
+
+
+def test_the_backend_factory_is_unchanged_per_platform(monkeypatch: pytest.MonkeyPatch) -> None:
+ from jarvis.platform import capabilities as caps_mod
+ from jarvis.trigger import backends as backends_pkg
+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend
+
+ class _Caps:
+ has_hotkey = True
+
+ monkeypatch.setattr(caps_mod, "detect_capabilities", lambda: _Caps())
+ import jarvis.platform as platform_mod
+
+ monkeypatch.setattr(platform_mod, "detect_platform", lambda: "darwin")
+ assert type(backends_pkg.make_hotkey_backend()) is QuartzHotkeyBackend
+ monkeypatch.setattr(platform_mod, "detect_platform", lambda: "win32")
+ assert type(backends_pkg.make_hotkey_backend()) is GlobalHotkeysBackend
diff --git a/tests/unit/ui/test_desktop_macos_permission_gate.py b/tests/unit/ui/test_desktop_macos_permission_gate.py
index 10e2bf5278..d0823e85cd 100644
--- a/tests/unit/ui/test_desktop_macos_permission_gate.py
+++ b/tests/unit/ui/test_desktop_macos_permission_gate.py
@@ -1,49 +1,156 @@
+"""The desktop voice gates are SILENT reads of the permission service.
+
+Two predicates reach the speech pipeline: ``_local_voice_permission_granted``
+(background voice: the wake word needs a live GRANT) and
+``_local_voice_permission_usable`` (a user gesture: push-to-talk, a voice session,
+dictation only need the microphone not to be refused, because the gesture asks).
+Neither ever asks the OS: with the real service over ``FakeTCC`` the call log
+holds probes only.
+"""
+
from __future__ import annotations
+import pytest
+
+from jarvis.platform.permission_service import PermissionOutcome, get_permission_service
from jarvis.platform.permissions import PermissionId, PermissionState
-from jarvis.ui.desktop_app import _local_voice_permission_granted
+from jarvis.ui.desktop_app import (
+ _local_voice_permission_granted,
+ _local_voice_permission_usable,
+)
+from tests.fakes.fake_permission_service import FakePermissionService
+from tests.fakes.fake_tcc import FakeTCC, TccService, install_port, make_darwin_port
+_STATES = {
+ "granted": PermissionOutcome.GRANTED,
+ "not_determined": PermissionOutcome.PENDING,
+ "denied": PermissionOutcome.DENIED,
+ "needs_settings": PermissionOutcome.NEEDS_SETTINGS,
+ "unavailable": PermissionOutcome.UNAVAILABLE,
+}
-class _PermissionPort:
- def __init__(self, state: PermissionState, *, stable: bool = True) -> None:
- self.permission_state = state
- self.stable = stable
- self.calls: list[PermissionId] = []
- def runtime_access_granted(self, permission_id: PermissionId) -> bool:
- self.calls.append(permission_id)
- return self.stable and self.permission_state is PermissionState.GRANTED
+def _gate(state: str) -> FakePermissionService:
+ gate = FakePermissionService()
+ gate.script(PermissionId.MICROPHONE, _STATES[state])
+ return gate
-def test_macos_voice_gate_tracks_fresh_microphone_state() -> None:
- port = _PermissionPort(PermissionState.NOT_DETERMINED)
+ ("state", "background", "user"),
+ [
+ ("granted", True, True),
+ ("not_determined", False, True),
+ ("needs_settings", False, True),
+ ("denied", False, False),
+ ("unavailable", False, False),
+ ],
+)
+def test_macos_voice_gates_follow_the_silent_microphone_state(
+ state: str, background: bool, user: bool
+) -> None:
+ gate = _gate(state)
- assert not _local_voice_permission_granted(
- platform_name="darwin", permission_port=port
- )
- port.permission_state = PermissionState.GRANTED
- assert _local_voice_permission_granted(
- platform_name="darwin", permission_port=port
- )
- port.permission_state = PermissionState.DENIED
- assert not _local_voice_permission_granted(
- platform_name="darwin", permission_port=port
+ assert (
+ _local_voice_permission_granted(platform_name="darwin", permission_gate=gate) is background
)
- assert port.calls == [PermissionId.MICROPHONE] * 3
+ assert _local_voice_permission_usable(platform_name="darwin", permission_gate=gate) is user
+ # Silent: only ``check`` was called, never an ``ensure`` (which could ask).
+ assert gate.ensure_calls() == []
+ assert [call.permission for call in gate.check_calls()] == [PermissionId.MICROPHONE] * 2
-def test_macos_voice_gate_rejects_grant_under_unstable_identity() -> None:
- port = _PermissionPort(PermissionState.GRANTED, stable=False)
+def test_restricted_microphone_is_not_usable_by_a_gesture() -> None:
+ class _Restricted:
+ def check(self, _permission): # noqa: ANN001, ANN202
+ return PermissionState.RESTRICTED
assert not _local_voice_permission_granted(
- platform_name="darwin", permission_port=port
+ platform_name="darwin", permission_gate=_Restricted()
)
+ assert not _local_voice_permission_usable(platform_name="darwin", permission_gate=_Restricted())
+
+
+def test_an_unreadable_state_closes_both_gates() -> None:
+ class _Broken:
+ def check(self, _permission): # noqa: ANN001, ANN202
+ raise RuntimeError("native read failed")
+
+ assert not _local_voice_permission_granted(platform_name="darwin", permission_gate=_Broken())
+ assert not _local_voice_permission_usable(platform_name="darwin", permission_gate=_Broken())
+
+
+def test_non_macos_voice_gates_never_consult_the_service() -> None:
+ gate = _gate("denied")
+
+ assert _local_voice_permission_granted(platform_name="linux", permission_gate=gate)
+ assert _local_voice_permission_usable(platform_name="win32", permission_gate=gate)
+ assert gate.calls == []
-def test_non_macos_voice_gate_never_consults_tcc() -> None:
- port = _PermissionPort(PermissionState.DENIED)
+def test_the_real_service_over_fake_tcc_is_only_ever_probed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ port, tcc = make_darwin_port()
+ install_port(monkeypatch, port)
+ service = get_permission_service()
- assert _local_voice_permission_granted(
- platform_name="linux", permission_port=port
+ # An undecided microphone: wake stays closed, a gesture may try.
+ assert not _local_voice_permission_granted(platform_name="darwin", permission_gate=service)
+ assert _local_voice_permission_usable(platform_name="darwin", permission_gate=service)
+ tcc.deny(TccService.MICROPHONE)
+ service.invalidate()
+ assert not _local_voice_permission_usable(platform_name="darwin", permission_gate=service)
+ tcc.grant(TccService.MICROPHONE)
+ service.invalidate()
+ assert _local_voice_permission_granted(platform_name="darwin", permission_gate=service)
+
+ assert tcc.requests() == []
+ assert tcc.implicit_prompts() == []
+
+
+def test_a_fresh_mac_boots_both_gates_without_a_request(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc = FakeTCC()
+ install_port(monkeypatch, tcc.port("darwin"))
+
+ # The default resolver (no gate injected) is the process service.
+ assert not _local_voice_permission_granted(platform_name="darwin")
+ assert _local_voice_permission_usable(platform_name="darwin")
+
+ tcc.assert_no_prompts()
+ assert tcc.requests() == []
+
+
+def test_the_boot_path_hands_both_silent_gates_to_the_speech_pipeline() -> None:
+ """Wiring guard: ``_start_speech_and_orb`` must pass BOTH predicates.
+
+ The two gates are built in a closure of that method, so the harness-built gates
+ of the voice tests cannot notice a dropped kwarg. If ``user_activation_gate``
+ went missing the pipeline would default it to ``lambda: True`` and the two-
+ predicate design (wake needs a grant, a gesture only needs "not refused")
+ would regress with every other test green. A source-level check is the
+ cheapest honest guard for a closure that cannot be built without a desktop.
+ """
+ import inspect
+ import re
+
+ from jarvis.speech.pipeline import SpeechPipeline
+ from jarvis.ui.desktop_app import DesktopApp
+
+ init_params = inspect.signature(SpeechPipeline.__init__).parameters
+ assert "activation_gate" in init_params and "user_activation_gate" in init_params
+
+ source = inspect.getsource(DesktopApp._start_speech_and_orb)
+ assert re.search(r"^\s+activation_gate=voice_activation_gate,$", source, re.M)
+ assert re.search(r"^\s+user_activation_gate=voice_user_gate,$", source, re.M)
+ # Each closure reads the matching silent predicate, not the other one.
+ assert re.search(
+ r"def voice_activation_gate\(\) -> bool:\s+return "
+ r"_local_voice_permission_granted\(platform_name=sys\.platform\)",
+ source,
+ )
+ assert re.search(
+ r"def voice_user_gate\(\) -> bool:\s+return "
+ r"_local_voice_permission_usable\(platform_name=sys\.platform\)",
+ source,
)
- assert port.calls == []
diff --git a/tests/unit/ui/test_orb_bus_bridge_microphone_refusal.py b/tests/unit/ui/test_orb_bus_bridge_microphone_refusal.py
new file mode 100644
index 0000000000..b5cf54a713
--- /dev/null
+++ b/tests/unit/ui/test_orb_bus_bridge_microphone_refusal.py
@@ -0,0 +1,254 @@
+"""A dictation refused for the microphone names the switch and where to flip it.
+
+The native bar has no permission toast (that lives in the web window), so the one
+sentence a refused dictation shows there has to carry the answer. On macOS the
+reason ``microphone_unavailable`` is the microphone permission, so the bridge shows
+a localized sentence instead of the pipeline's generic English one: an undecided
+microphone says "answer the dialog, then press the key again" (there is a dialog), a
+denied one names System Settings > Privacy & Security > Microphone (there is none),
+and a run outside the installed app points at the Jarvis window. A refusal the user
+cannot fix at all (restricted, unavailable) keeps the permission layer's own sentence.
+The notice stays up long enough to read. Other reasons, and other operating systems,
+keep the event's own detail.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+if str(_REPO_ROOT) in sys.path:
+ sys.path.remove(str(_REPO_ROOT))
+sys.path.insert(0, str(_REPO_ROOT))
+sys.modules.pop("ui", None)
+
+try: # noqa: SIM105 — deliberate try-import (top-level `ui` discovery quirk)
+ from ui.orb import bus_bridge as bridge_mod # type: ignore[import-not-found]
+ from ui.orb.bus_bridge import OrbBusBridge # type: ignore[import-not-found]
+except ModuleNotFoundError: # pragma: no cover
+ pytest.skip(
+ "ui.orb not importable in this pytest pythonpath — run from repo root.",
+ allow_module_level=True,
+ )
+
+from jarvis.core.events import DictationRefused # noqa: E402
+from jarvis.platform.permission_service import user_detail_for # noqa: E402
+from jarvis.platform.permissions import PermissionId # noqa: E402
+
+_PIPELINE_DETAIL = "Microphone access is not ready — check the microphone permission."
+
+
+class _FakeBus:
+ def subscribe(self, *_a, **_k) -> None:
+ pass
+
+
+class _Orb:
+ def __init__(self) -> None:
+ self.transcripts: list[str] = []
+
+ def show(self, mode: str = "listen") -> None: ...
+ def hide(self) -> None: ...
+ def set_level(self, level: float) -> None: ...
+ def play_animation(self, name: str, **_kw) -> None: ...
+ def stop_animation(self, name: str) -> None: ...
+
+ def show_listening_transcript(self, text: str = "", duration_ms: int = 0) -> None:
+ self.transcripts.append(text)
+
+
+def _bridge(orb: _Orb, language: str = "en") -> OrbBusBridge:
+ return OrbBusBridge( # type: ignore[arg-type]
+ bus=_FakeBus(),
+ orb=orb,
+ hide_on_idle=True,
+ idle_animations_enabled=False,
+ language=language,
+ )
+
+
+async def _refuse(bridge: OrbBusBridge, orb: _Orb, reason: str) -> str:
+ await bridge._on_dictation_refused(DictationRefused(reason=reason, detail=_PIPELINE_DETAIL))
+ # Stop the stand-down timer the refusal arms so it cannot outlive the test.
+ bridge._cancel_dictation_standdown()
+ return orb.transcripts[-1]
+
+
+ "table",
+ [
+ "MICROPHONE_REFUSAL_TEXT",
+ "MICROPHONE_DENIED_REFUSAL_TEXT",
+ "MICROPHONE_OUTSIDE_REFUSAL_TEXT",
+ ],
+)
+def test_every_table_covers_every_interface_language(table: str) -> None:
+ assert set(getattr(bridge_mod, table)) == set(bridge_mod.PET_STATUS_LANGUAGES)
+
+
+ ("language", "switch", "place"),
+ [
+ ("en", "Personal Jarvis", "Privacy & Security > Microphone"),
+ ("de", "Personal Jarvis", "Datenschutz & Sicherheit > Mikrofon"), # i18n-allow
+ ("es", "Personal Jarvis", "Privacidad y seguridad > Micrófono"), # i18n-allow
+ ],
+)
+async def test_a_denied_microphone_names_the_switch_and_the_place(
+ monkeypatch: pytest.MonkeyPatch, language: str, switch: str, place: str
+) -> None:
+ monkeypatch.setattr(sys, "platform", "darwin")
+ orb = _Orb()
+ bridge = _bridge(orb, language)
+
+ await bridge._on_dictation_refused(
+ DictationRefused(
+ reason="microphone_unavailable",
+ detail=user_detail_for(PermissionId.MICROPHONE, "denied"),
+ )
+ )
+ bridge._cancel_dictation_standdown()
+ shown = orb.transcripts[-1]
+
+ assert switch in shown and place in shown
+ assert shown == bridge_mod.MICROPHONE_DENIED_REFUSAL_TEXT[language]
+ if language == "en":
+ assert "dialog" not in shown.lower() # no dialog exists after a denial
+
+
[email protected]("language", ["en", "de", "es"])
+async def test_an_undecided_microphone_says_to_answer_the_dialog_and_press_again(
+ monkeypatch: pytest.MonkeyPatch, language: str
+) -> None:
+ monkeypatch.setattr(sys, "platform", "darwin")
+ orb = _Orb()
+ shown = await _refuse(_bridge(orb, language), orb, "microphone_unavailable")
+
+ assert shown == bridge_mod.MICROPHONE_REFUSAL_TEXT[language]
+ assert shown != _PIPELINE_DETAIL
+ assert "System Settings" not in shown and "Systemeinstellungen" not in shown # i18n-allow
+
+
[email protected]("language", ["en", "de", "es"])
[email protected]("launched_as_bundle", [True, False])
+async def test_outside_the_installed_app_the_bar_points_at_the_jarvis_window(
+ monkeypatch: pytest.MonkeyPatch, language: str, launched_as_bundle: bool
+) -> None:
+ monkeypatch.setattr(sys, "platform", "darwin")
+ orb = _Orb()
+ bridge = _bridge(orb, language)
+ sentence = user_detail_for(
+ PermissionId.MICROPHONE,
+ "not_determined",
+ outside_app=True,
+ launched_as_bundle=launched_as_bundle,
+ )
+
+ await bridge._on_dictation_refused(
+ DictationRefused(reason="microphone_unavailable", detail=sentence)
+ )
+ bridge._cancel_dictation_standdown()
+
+ shown = orb.transcripts[-1]
+ assert shown == bridge_mod.MICROPHONE_OUTSIDE_REFUSAL_TEXT[language]
+ assert "The user" not in shown # the service's third-person sentence is not shown
+
+
+async def test_a_microphone_notice_stays_up_long_enough_to_read(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(sys, "platform", "darwin")
+ orb = _Orb()
+ bridge = _bridge(orb)
+ dwells: list[float] = []
+ monkeypatch.setattr(bridge, "_schedule_notice_standdown", dwells.append)
+
+ await bridge._on_dictation_refused(
+ DictationRefused(reason="microphone_unavailable", detail=_PIPELINE_DETAIL)
+ )
+ await bridge._on_dictation_refused(DictationRefused(reason="no_stt", detail=_PIPELINE_DETAIL))
+
+ assert dwells == [bridge_mod.MICROPHONE_REFUSAL_DWELL_S, bridge_mod.DICTATION_REFUSAL_DWELL_S]
+ assert bridge_mod.MICROPHONE_REFUSAL_DWELL_S >= 8.0
+
+
+ ("reason", "kwargs"),
+ [
+ ("restricted", {}),
+ ("unavailable", {}),
+ ],
+)
+async def test_a_refusal_the_user_cannot_switch_keeps_the_permission_layers_sentence(
+ monkeypatch: pytest.MonkeyPatch, reason: str, kwargs: dict[str, bool]
+) -> None:
+ """Restricted (MDM) and unavailable (no GUI session) are not fixed by any switch:
+ the service's own sentence stays on the bar for those."""
+ monkeypatch.setattr(sys, "platform", "darwin")
+ sentence = user_detail_for(PermissionId.MICROPHONE, reason, **kwargs)
+ orb = _Orb()
+ bridge = _bridge(orb)
+
+ await bridge._on_dictation_refused(
+ DictationRefused(reason="microphone_unavailable", detail=sentence)
+ )
+ bridge._cancel_dictation_standdown()
+
+ assert orb.transcripts[-1] == sentence
+ assert orb.transcripts[-1] != bridge_mod.MICROPHONE_REFUSAL_TEXT["en"]
+
+
+ ("reason", "kwargs"),
+ [("not_determined", {}), ("not_determined", {"asking": True})],
+)
+async def test_an_undecided_microphone_gets_the_localized_table_from_the_services_sentence(
+ monkeypatch: pytest.MonkeyPatch, reason: str, kwargs: dict[str, bool]
+) -> None:
+ monkeypatch.setattr(sys, "platform", "darwin")
+ orb = _Orb()
+ bridge = _bridge(orb)
+
+ await bridge._on_dictation_refused(
+ DictationRefused(
+ reason="microphone_unavailable",
+ detail=user_detail_for(PermissionId.MICROPHONE, reason, **kwargs),
+ )
+ )
+ bridge._cancel_dictation_standdown()
+
+ assert orb.transcripts[-1] == bridge_mod.MICROPHONE_REFUSAL_TEXT["en"]
+
+
+async def test_an_unknown_language_falls_back_to_english(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(sys, "platform", "darwin")
+ orb = _Orb()
+ bridge = _bridge(orb)
+ monkeypatch.setattr(bridge, "_status_language", lambda: "fr")
+
+ assert (
+ await _refuse(bridge, orb, "microphone_unavailable")
+ == (bridge_mod.MICROPHONE_REFUSAL_TEXT["en"])
+ )
+
+
[email protected]("platform_name", ["win32", "linux"])
+async def test_other_operating_systems_keep_the_pipelines_sentence(
+ monkeypatch: pytest.MonkeyPatch, platform_name: str
+) -> None:
+ """The reason also means "the desktop window is not visible" off macOS, and the
+ System Settings path would be wrong there."""
+ monkeypatch.setattr(sys, "platform", platform_name)
+ orb = _Orb()
+
+ assert await _refuse(_bridge(orb), orb, "microphone_unavailable") == _PIPELINE_DETAIL
+
+
+async def test_other_refusal_reasons_are_untouched(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(sys, "platform", "darwin")
+ orb = _Orb()
+
+ assert await _refuse(_bridge(orb), orb, "no_stt") == _PIPELINE_DETAIL
diff --git a/tests/unit/ui/web/test_dictation_start_failures_parity.py b/tests/unit/ui/web/test_dictation_start_failures_parity.py
new file mode 100644
index 0000000000..07b7653c3d
--- /dev/null
+++ b/tests/unit/ui/web/test_dictation_start_failures_parity.py
@@ -0,0 +1,65 @@
+"""AP-4 parity for the dictation refusal reasons the web UI reacts to.
+
+The WebSocket hook (``useWebSocket``) resets the optimistic recording pill when the
+backend refuses a dictation start, and ONLY for the reasons in
+``DICTATION_START_FAILURES`` (``lib/dictationRefusal.ts``). A token spelled differently
+on the two sides would leave the pill stuck with a waveform and no error anywhere, so the
+TypeScript set is regex-read here and every member must be a refusal reason Python can send
+(``DICTATION_REFUSAL_REASONS``).
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from jarvis.core.events import DICTATION_REFUSAL_REASONS
+
+_TS = (
+ Path(__file__).resolve().parents[4]
+ / "jarvis"
+ / "ui"
+ / "web"
+ / "frontend"
+ / "src"
+ / "lib"
+ / "dictationRefusal.ts"
+)
+
+# The reasons that mean "the start did not happen". The others (``already_running`` and the
+# post-recording ``nothing_to_paste`` / ``paste_unavailable`` / ``history_disabled``) come from
+# another trigger or from a recording that is over and must NOT drop a live pill.
+_NOT_START_FAILURES = {
+ "already_running",
+ "nothing_to_paste",
+ "paste_unavailable",
+ "history_disabled",
+}
+
+
+def _ts_tokens() -> set[str]:
+ assert _TS.exists(), f"frontend twin missing: {_TS}"
+ source = _TS.read_text(encoding="utf-8")
+ match = re.search(
+ r"export const DICTATION_START_FAILURES: ReadonlySet<string> = new Set\(\[(.*?)\]\);",
+ source,
+ re.DOTALL,
+ )
+ assert match, "DICTATION_START_FAILURES missing from lib/dictationRefusal.ts"
+ tokens = set(re.findall(r'"([a-z_]+)"', match.group(1)))
+ assert tokens, "parsed no tokens"
+ return tokens
+
+
+def test_the_dictation_start_failures_are_refusal_reasons_python_can_send() -> None:
+ """The WS hook resets the recording pill only for these tokens: they must exist (AP-4)."""
+ assert _ts_tokens() <= set(DICTATION_REFUSAL_REASONS)
+
+
+def test_a_start_failure_is_never_one_of_the_post_recording_reasons() -> None:
+ assert not _ts_tokens() & _NOT_START_FAILURES
+
+
+def test_every_reason_python_can_send_is_classified_one_way_or_the_other() -> None:
+ """A new refusal reason must be decided on: does it reset the pill, or not?"""
+ assert set(DICTATION_REFUSAL_REASONS) <= _ts_tokens() | _NOT_START_FAILURES
diff --git a/tests/unit/ui/web/test_keybinds_input_monitoring_ask.py b/tests/unit/ui/web/test_keybinds_input_monitoring_ask.py
new file mode 100644
index 0000000000..c2fbda67d1
--- /dev/null
+++ b/tests/unit/ui/web/test_keybinds_input_monitoring_ask.py
@@ -0,0 +1,347 @@
+"""PUT /api/settings/keybinds: SAVING a global shortcut is the gesture that asks macOS.
+
+A global shortcut is a background listener, so nothing the user does at the moment
+they press it can carry a system dialog. The one moment that can is the save: on
+macOS, when the key tap is not already listening, the route asks for Input
+Monitoring through the permission service with ``wait_s=0`` (it never waits for the
+dialog) and saves the shortcut either way. It never asks for a cleared shortcut,
+off macOS, from a GET, from a rejected save, or at launch; and a failing ask never
+fails the save.
+
+The macOS cases run the REAL service over ``FakeTCC`` (no Mac was available: its
+fidelity labels apply, what the real dialog does is unverified), so what the OS was
+asked is checked against its own call log. The consumer-level cases use
+``FakePermissionService`` and read what the route asked of the gate.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+import jarvis.ui.web.settings_routes as settings_routes
+from jarvis.core import config_writer
+from jarvis.platform import permission_service
+from jarvis.platform.permission_service import PermissionOutcome, get_permission_service
+from jarvis.ui.web.settings_routes import router
+from tests.fakes.fake_permission_service import FakePermissionService
+from tests.fakes.fake_tcc import (
+ DialogPolicy,
+ FakeTCC,
+ TccService,
+ install_port,
+ make_non_darwin_port,
+)
+
+_SAVE_KEYS = {"ok", "action", "hotkey", "persisted", "applied_live", "restart_required", "cautions"}
+
+
+class _Trigger:
+ """The slice of ``HotkeyTrigger`` the route reads: ``listening()``."""
+
+ def __init__(self, listening: bool | None) -> None:
+ self._listening = listening
+
+ def listening(self) -> bool | None:
+ return self._listening
+
+
+class _Pipeline:
+ def __init__(self, trigger: _Trigger | None) -> None:
+ self._hotkey_trigger = trigger
+ self.rearmed: list[dict[str, list[str]]] = []
+
+ def set_keybinds(self, **kwargs: list[str]) -> None:
+ self.rearmed.append(kwargs)
+
+
+def _client(pipeline: object | None = None, **state: object) -> TestClient:
+ app = FastAPI()
+ app.include_router(router)
+ app.state.config = SimpleNamespace(
+ trigger=SimpleNamespace(
+ hotkey="ctrl+right_alt+j", hotkey_call="f3+f4", hotkey_hangup="f1+f2", push_to_talk=True
+ )
+ )
+ if pipeline is not None:
+ app.state.speech_pipeline = pipeline
+ for name, value in state.items():
+ setattr(app.state, name, value)
+ return TestClient(app)
+
+
[email protected](autouse=True)
+def _persist_nothing(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str]]:
+ saved: list[tuple[str, str]] = []
+ monkeypatch.setattr(
+ config_writer, "set_keybind", lambda action, hotkey: saved.append((action, hotkey))
+ )
+ return saved
+
+
+def _on_macos(monkeypatch: pytest.MonkeyPatch, **tcc_kwargs: object) -> FakeTCC:
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: True)
+ return tcc
+
+
+def _save(client: TestClient, action: str = "call", hotkey: str = "f5+f6"):
+ return client.put("/api/settings/keybinds", json={"action": action, "hotkey": hotkey})
+
+
+def test_saving_a_shortcut_on_a_fresh_mac_asks_once_and_still_saves_it(
+ monkeypatch: pytest.MonkeyPatch, _persist_nothing: list[tuple[str, str]]
+) -> None:
+ tcc = _on_macos(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ pipeline = _Pipeline(_Trigger(listening=False))
+
+ response = _save(_client(pipeline))
+
+ assert response.status_code == 200
+ body = response.json()
+ assert _SAVE_KEYS <= set(body)
+ assert body["ok"] is True and body["hotkey"] == "f5+f6" and body["persisted"] is True
+ assert body["applied_live"] is True
+ assert _persist_nothing == [("call", "f5+f6")]
+ assert pipeline.rearmed == [{"call": ["f5+f6"]}]
+ # The dialog is up (the route did not wait for the answer): one native request,
+ # and nothing implicit.
+ assert len(tcc.requests(TccService.INPUT_MONITORING)) == 1
+ assert tcc.implicit_prompts() == []
+ (episode,) = get_permission_service().outstanding()
+ assert (episode.feature, episode.origin, episode.permissions) == (
+ "global_shortcuts",
+ "user",
+ ("input_monitoring",),
+ )
+
+
+def test_the_route_returns_while_the_dialog_is_still_open(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``wait_s=0``: an unanswered dialog never holds the save."""
+ tcc = _on_macos(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ response = _save(_client(_Pipeline(_Trigger(listening=False))))
+
+ assert response.status_code == 200
+ assert tcc.dialog_open(TccService.INPUT_MONITORING) is True
+
+
+def test_a_second_save_in_the_same_episode_does_not_ask_macOS_again(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _on_macos(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ client = _client(_Pipeline(_Trigger(listening=False)))
+
+ assert _save(client).status_code == 200
+ assert _save(client, action="hangup", hotkey="f7+f8").status_code == 200
+
+ assert len(tcc.requests(TccService.INPUT_MONITORING)) == 1
+
+
+def test_a_running_tap_means_no_ask(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc = _on_macos(monkeypatch, granted=(TccService.INPUT_MONITORING,))
+
+ response = _save(_client(_Pipeline(_Trigger(listening=True))))
+
+ assert response.status_code == 200
+ assert tcc.requests() == []
+ assert get_permission_service().outstanding() == []
+
+
+def test_a_granted_permission_asks_nothing_even_when_the_tap_is_not_up_yet(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _on_macos(monkeypatch, granted=(TccService.INPUT_MONITORING,))
+
+ response = _save(_client(_Pipeline(_Trigger(listening=False))))
+
+ assert response.status_code == 200
+ assert tcc.requests() == []
+
+
+def test_a_denied_permission_is_reported_not_asked_again(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _on_macos(monkeypatch)
+ tcc.deny(TccService.INPUT_MONITORING)
+
+ response = _save(_client(_Pipeline(_Trigger(listening=False))))
+
+ assert response.status_code == 200
+ assert response.json()["persisted"] is True
+ assert tcc.requests() == []
+ (episode,) = get_permission_service().outstanding()
+ assert episode.feature == "global_shortcuts" and episode.origin == "user"
+
+
+def test_re_saving_the_combo_already_in_force_asks_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A no-op save is not a new gesture: no native request, no episode."""
+ tcc = _on_macos(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ pipeline = _Pipeline(_Trigger(listening=False))
+
+ # "f3+f4" is the combo the client's config already holds for the call action.
+ response = _save(_client(pipeline), action="call", hotkey="f3+f4")
+
+ assert response.status_code == 200
+ assert response.json()["hotkey"] == "f3+f4"
+ assert tcc.requests() == []
+ assert tcc.probes() == []
+ assert get_permission_service().outstanding() == []
+
+
+def test_an_identical_re_save_does_not_announce_a_denied_permission_again(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _on_macos(monkeypatch)
+ tcc.deny(TccService.INPUT_MONITORING)
+ published: list[object] = []
+ service = get_permission_service()
+ monkeypatch.setattr(service, "_publish", published.append)
+ # A gesture re-announces an open episode (service re-announce window); with the
+ # window at zero only the route's "changed" rule can keep the identical save quiet.
+ monkeypatch.setattr(permission_service, "_REANNOUNCE_MIN_S", 0.0)
+ client = _client(_Pipeline(_Trigger(listening=False)))
+
+ assert _save(client, action="call", hotkey="f5+f6").status_code == 200
+ assert len(published) == 1 # the denied permission is announced once
+
+ # The same combo again (any case or padding) is no gesture: nothing is published.
+ assert _save(client, action="call", hotkey=" F5+F6 ").status_code == 200
+ assert len(published) == 1
+ assert tcc.requests() == []
+
+
+def test_clearing_a_shortcut_asks_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc = _on_macos(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ response = _save(_client(_Pipeline(_Trigger(listening=False))), hotkey="")
+
+ assert response.status_code == 200
+ assert response.json()["hotkey"] == ""
+ assert tcc.requests() == []
+ assert tcc.probes() == []
+
+
+def test_a_rejected_save_asks_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ tcc = _on_macos(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ client = _client(_Pipeline(_Trigger(listening=False)))
+
+ # Same chord as the hangup action: the save is refused before anything else.
+ refused = _save(client, action="call", hotkey="f1+f2")
+
+ assert refused.status_code == 400
+ assert tcc.requests() == []
+ assert tcc.probes() == []
+
+
+def test_a_get_never_asks_and_no_longer_carries_a_shortcuts_status(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _on_macos(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ body = _client(_Pipeline(_Trigger(listening=False))).get("/api/settings/keybinds").json()
+
+ assert "shortcuts_status" not in body
+ assert tcc.requests() == []
+ assert tcc.probes() == []
+
+
+def test_without_a_voice_pipeline_the_save_still_asks_on_macos(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """No tap object to read: the save is still the user's gesture for the permission."""
+ tcc = _on_macos(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ response = _save(_client())
+
+ assert response.status_code == 200
+ assert response.json()["applied_live"] is False
+ assert len(tcc.requests(TccService.INPUT_MONITORING)) == 1
+
+
+def test_off_macos_the_permission_layer_is_never_touched(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ port, tcc = make_non_darwin_port("win32")
+ install_port(monkeypatch, port)
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: False)
+ gate = FakePermissionService()
+
+ response = _save(_client(_Pipeline(_Trigger(listening=None)), permission_service=gate))
+
+ assert response.status_code == 200
+ assert gate.ensure_calls() == []
+ assert gate.native_free()
+ tcc.assert_silent()
+
+
+def test_the_route_asks_the_gate_exactly_once_non_blocking_and_interactive(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: True)
+ gate = FakePermissionService({"input_monitoring": PermissionOutcome.PENDING})
+
+ response = _save(_client(_Pipeline(_Trigger(listening=False)), permission_service=gate))
+
+ assert response.status_code == 200
+ (call,) = gate.ensure_calls()
+ assert call.method == "ensure"
+ assert call.permission.value == "input_monitoring"
+ assert call.feature == "global_shortcuts"
+ assert call.interactive is True
+ assert call.wait_s == 0.0
+
+
+def test_a_gate_that_says_no_never_fails_the_save(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: True)
+ gate = FakePermissionService({"input_monitoring": PermissionOutcome.DENIED})
+
+ response = _save(_client(_Pipeline(_Trigger(listening=False)), permission_service=gate))
+
+ assert response.status_code == 200
+ assert response.json()["persisted"] is True
+
+
+def test_a_gate_that_raises_never_fails_the_save(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: True)
+
+ def boom(*_args: object, **_kwargs: object) -> None:
+ raise RuntimeError("native layer exploded")
+
+ broken = SimpleNamespace(ensure=boom)
+
+ with caplog.at_level("DEBUG", logger=settings_routes.log.name):
+ response = _save(_client(_Pipeline(_Trigger(listening=False)), permission_service=broken))
+
+ assert response.status_code == 200
+ assert _SAVE_KEYS <= set(response.json())
+ # AP-30: the failure is logged, not swallowed.
+ assert any("Input Monitoring" in record.getMessage() for record in caplog.records)
+
+
+def test_a_trigger_whose_probe_raises_still_saves_and_asks(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class _Broken:
+ def listening(self) -> bool:
+ raise RuntimeError("probe failed")
+
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: True)
+ gate = FakePermissionService({"input_monitoring": PermissionOutcome.PENDING})
+
+ response = _save(_client(_Pipeline(_Broken()), permission_service=gate)) # type: ignore[arg-type]
+
+ assert response.status_code == 200
+ assert response.json()["persisted"] is True
+ # A probe that fails is "unknown", which is not "listening": the ask still happens.
+ assert len(gate.ensure_calls()) == 1
diff --git a/tests/unit/ui/web/test_mute_music_route.py b/tests/unit/ui/web/test_mute_music_route.py
new file mode 100644
index 0000000000..6247b95918
--- /dev/null
+++ b/tests/unit/ui/web/test_mute_music_route.py
@@ -0,0 +1,170 @@
+"""PUT /api/settings/mute-music: the switch is the gesture that may ask for Automation.
+
+The route runs against the REAL ``AudioDuckController`` and ``MacOSScriptDucker`` on a
+REAL permission service over ``FakeTCC`` (a stateful model of macOS privacy), so the
+response is checked against what the OS was actually asked. The existing keys
+(``ok``, ``enabled``, ``persisted``, ``applied_live``) stay exactly as they were; the
+permission answer is one additive ``permission`` key.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.audio.ducking.controller import AudioDuckController
+from jarvis.audio.ducking.macos import MacOSScriptDucker
+from jarvis.platform.permissions import AUTOMATION_TARGETS
+from jarvis.ui.web.settings_routes import router
+from tests.fakes.fake_tcc import CallKind, DialogPolicy, FakeTCC, install_port, make_non_darwin_port
+
+_MUSIC = "com.apple.Music"
+_SPOTIFY = "com.spotify.client"
+_LEGACY_KEYS = {"ok", "enabled", "persisted", "applied_live"}
+_PLAYER_KEYS = {
+ "player",
+ "target",
+ "outcome",
+ "reason",
+ "can_open_settings",
+ "asked",
+ "outside_installed_app",
+ "detail",
+}
+
+
+def _osascript(tcc: FakeTCC):
+ """Answers the ducker's pure "is it running" queries from the FakeTCC player table."""
+
+ def run(script: str) -> subprocess.CompletedProcess:
+ bundle = next(b for _name, b in AUTOMATION_TARGETS if f'"{b}"' in script)
+ out = "+" if tcc.player_running(bundle) else "-"
+ return subprocess.CompletedProcess(["osascript"], 0, stdout=f"{out}\n", stderr="")
+
+ return run
+
+
+class _Bus:
+ def subscribe(self, _event, _handler) -> None:
+ return None
+
+
+def _app(ducker) -> FastAPI:
+ app = FastAPI()
+ app.include_router(router)
+ app.state.config = SimpleNamespace(
+ ducking=SimpleNamespace(enabled=False, restore_delay_ms=0, never_mute=[])
+ )
+ app.state.desktop_app = SimpleNamespace(
+ _ducker=AudioDuckController(bus=_Bus(), cfg=app.state.config, ducker=ducker)
+ )
+ return app
+
+
[email protected](autouse=True)
+def _no_toml_write(monkeypatch):
+ import jarvis.core.config_writer as cw
+
+ monkeypatch.setattr(cw, "set_mute_music", lambda v, **k: None)
+
+
+def _mac(monkeypatch, **tcc_kwargs):
+ tcc_kwargs.setdefault("installed_players", [_MUSIC, _SPOTIFY])
+ tcc_kwargs.setdefault("running_players", [_MUSIC])
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ client = TestClient(_app(MacOSScriptDucker(run=_osascript(tcc))))
+ return tcc, client
+
+
+def test_switching_on_with_music_running_answers_per_player_and_asks_once(monkeypatch):
+ tcc, client = _mac(monkeypatch)
+ body = client.put("/api/settings/mute-music", json={"enabled": True}).json()
+ assert _LEGACY_KEYS <= set(body)
+ assert body["ok"] is True and body["enabled"] is True and body["applied_live"] is True
+ permission = body["permission"]
+ assert permission["feature"] == "audio_ducking"
+ assert permission["checked"] is True and permission["asked"] is True
+ assert permission["note"] == "" and permission["not_running"] == ["Spotify"]
+ (player,) = permission["players"]
+ assert set(player) == _PLAYER_KEYS
+ assert player["player"] == "Music" and player["target"] == _MUSIC
+ assert player["outcome"] == "granted" and player["reason"] == ""
+ assert player["can_open_settings"] is False and player["asked"] is True
+ assert [call.target for call in tcc.requests("automation")] == [_MUSIC]
+
+
+def test_switching_on_with_no_player_running_says_it_is_checked_while_one_runs(monkeypatch):
+ tcc, client = _mac(monkeypatch, running_players=[])
+ body = client.put("/api/settings/mute-music", json={"enabled": True}).json()
+ assert body["applied_live"] is True
+ permission = body["permission"]
+ assert permission["checked"] is False and permission["asked"] is False
+ assert permission["players"] == [] and set(permission["not_running"]) == {"Music", "Spotify"}
+ assert "checked while the player is running" in permission["note"]
+ assert tcc.calls_of(CallKind.REQUEST) == [] and tcc.implicit_prompts() == []
+
+
+def test_a_denied_player_comes_back_with_the_way_to_system_settings(monkeypatch):
+ tcc, client = _mac(monkeypatch, default_policy=DialogPolicy.DENY)
+ body = client.put("/api/settings/mute-music", json={"enabled": True}).json()
+ (player,) = body["permission"]["players"]
+ assert (player["outcome"], player["reason"]) == ("denied", "denied")
+ assert player["can_open_settings"] is True and player["asked"] is True
+ assert "Automation access for Music" in player["detail"]
+
+ # A second switch-on does not ask again: macOS keeps the decision.
+ again = client.put("/api/settings/mute-music", json={"enabled": True}).json()
+ assert again["permission"]["players"][0]["asked"] is False
+ assert len(tcc.requests("automation")) == 1 and tcc.ignored_requests() == []
+
+
+def test_switching_off_asks_nothing_and_adds_no_permission_key(monkeypatch):
+ tcc, client = _mac(monkeypatch)
+ body = client.put("/api/settings/mute-music", json={"enabled": False}).json()
+ assert set(body) == _LEGACY_KEYS and body["enabled"] is False
+ tcc.assert_silent()
+
+
+def test_a_backend_without_an_asking_path_keeps_the_response_exactly_as_it_was(monkeypatch):
+ port, tcc = make_non_darwin_port("win32")
+ install_port(monkeypatch, port)
+
+ class WindowsLike: # no prewarm: the Windows ducker has no permission concept
+ def mute_others(self, *, own_pid, never):
+ return []
+
+ def restore(self, pids):
+ return None
+
+ client = TestClient(_app(WindowsLike()))
+ body = client.put("/api/settings/mute-music", json={"enabled": True}).json()
+ assert body == {"ok": True, "enabled": True, "persisted": True, "applied_live": True}
+ tcc.assert_silent()
+
+
+def test_a_report_that_cannot_be_rendered_never_fails_the_toggle(monkeypatch):
+ class BadReport:
+ def as_dict(self):
+ raise ValueError("not serialisable")
+
+ class Setter:
+ async def set_enabled(self, enabled):
+ return BadReport()
+
+ app = FastAPI()
+ app.include_router(router)
+ app.state.config = SimpleNamespace(ducking=SimpleNamespace(enabled=False))
+ app.state.desktop_app = SimpleNamespace(_ducker=Setter())
+ body = TestClient(app).put("/api/settings/mute-music", json={"enabled": True}).json()
+ assert body == {"ok": True, "enabled": True, "persisted": True, "applied_live": True}
+
+
+def test_get_mute_music_never_asks(monkeypatch):
+ tcc, client = _mac(monkeypatch)
+ assert client.get("/api/settings/mute-music").json() == {"enabled": False}
+ tcc.assert_silent()
diff --git a/tests/unit/ui/web/test_no_permissions_settings_page.py b/tests/unit/ui/web/test_no_permissions_settings_page.py
new file mode 100644
index 0000000000..371f39d35b
--- /dev/null
+++ b/tests/unit/ui/web/test_no_permissions_settings_page.py
@@ -0,0 +1,63 @@
+"""Settings has no Privacy / Permissions page on any OS (the UI reset, ADR-0038 amendment).
+
+macOS shows its own dialog when a feature first needs a permission, and the app adds
+one toast for the silent failure after it. A Settings page for permissions (and its
+nav entry, search entries and reset button) was deleted on purpose; this guard keeps
+it from coming back unnoticed. It reads the frontend source the way the other AP-4
+parity tests do, so it runs without node.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+import pytest
+
+_FRONTEND = Path(__file__).resolve().parents[4] / "jarvis" / "ui" / "web" / "frontend" / "src"
+_LOCALES = ("en", "de", "es")
+_FORBIDDEN_SECTION_IDS = {"permissions", "privacy"}
+_DELETED_PAGE_FILES = (
+ "views/settings/PermissionsPanel.tsx",
+ "components/permissions/PermissionPromptLayer.tsx",
+ "components/permissions/PermissionPromptHost.tsx",
+ "components/permissions/InlinePermissionNote.tsx",
+)
+
+
+def _settings_section_ids() -> list[str]:
+ source = (_FRONTEND / "views" / "SettingsView.tsx").read_text(encoding="utf-8")
+ block = source[source.index("const SECTIONS") :]
+ block = block[: block.index("];")]
+ return re.findall(r'\{\s*id:\s*"([^"]+)"', block)
+
+
+def test_settings_sections_are_found() -> None:
+ """The regex reads real sections (else the guard below would pass vacuously)."""
+ ids = _settings_section_ids()
+ assert "languages" in ids and "wake-word" in ids
+
+
+def test_settings_has_no_permissions_or_privacy_section() -> None:
+ assert not (set(_settings_section_ids()) & _FORBIDDEN_SECTION_IDS)
+
+
[email protected]("locale", _LOCALES)
+def test_no_locale_carries_a_permissions_nav_label(locale: str) -> None:
+ data = json.loads((_FRONTEND / "i18n" / "locales" / f"{locale}.json").read_text("utf-8"))
+ nav = data["settings_view"]["nav"]
+ assert not (set(nav) & _FORBIDDEN_SECTION_IDS)
+
+
+def test_settings_search_has_no_permissions_group() -> None:
+ source = (_FRONTEND / "views" / "settings" / "settingsSearch.ts").read_text(encoding="utf-8")
+ assert "nav.permissions" not in source
+ ids = set(re.findall(r'\{\s*id:\s*"([^"]+)"', source))
+ assert {"languages", "wake-word"} <= ids # the regex reads the real groups
+ assert not (ids & _FORBIDDEN_SECTION_IDS)
+
+
[email protected]("relative", _DELETED_PAGE_FILES)
+def test_the_deleted_permission_ui_stays_deleted(relative: str) -> None:
+ assert not (_FRONTEND / relative).exists()
diff --git a/tests/unit/ui/web/test_permissions_routes.py b/tests/unit/ui/web/test_permissions_routes.py
index 76d59c53ee..ae4be25e99 100644
--- a/tests/unit/ui/web/test_permissions_routes.py
+++ b/tests/unit/ui/web/test_permissions_routes.py
@@ -1,117 +1,655 @@
-"""Route contract tests for the system-permissions API."""
+"""Route tests for the just-in-time permission flows: request, open settings, reset.
+
+The REAL ``PermissionService`` runs on a REAL ``SystemPermissionPort`` that sits on
+``FakeTCC`` (``tests/fakes/fake_tcc.py``), a stateful MODEL of macOS privacy, behind
+a real FastAPI ``TestClient``. The FakeTCC call log is the proof of what macOS was
+(not) asked. Nothing here ran on a real Mac: every macOS behaviour is a model, and
+the fidelity ledger in ``fake_tcc.py`` says which parts Apple documents.
+
+The status snapshot and the single-row read have their own file
+(``test_permissions_snapshot.py``). Time for the rate limiter is injected, so no
+test waits for a cooldown.
+"""
from __future__ import annotations
+import subprocess
+import threading
+import time
+from dataclasses import dataclass
+
+import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from jarvis.platform.permissions import PermissionOperation
+from jarvis.platform.permission_service import get_permission_service
+from jarvis.platform.permissions import PermissionId
+from jarvis.ui.web import permissions_routes as routes
from jarvis.ui.web.control_auth import require_control_key_or_session
from jarvis.ui.web.permissions_routes import router
+from tests.fakes.fake_permission_service import FakePermissionService
+from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, install_port
+
+_MUSIC = "com.apple.Music"
+_SPOTIFY = "com.spotify.client"
+
+
+class _Clock:
+ """A monotonic clock a test advances; the rate limiter reads it."""
+
+ def __init__(self) -> None:
+ self.now = 100.0
+
+ def __call__(self) -> float:
+ return self.now
+
+ def advance(self, seconds: float) -> None:
+ self.now += seconds
+
+
+@dataclass
+class Env:
+ client: TestClient
+ tcc: FakeTCC
+ app: FastAPI
+ clock: _Clock
+
+ def post(self, path: str, **kwargs):
+ return self.client.post(f"/api/permissions/{path}", **kwargs)
+
+
+def make_env(monkeypatch: pytest.MonkeyPatch):
+ def build(
+ *,
+ platform: str = "darwin",
+ service: object | None = None,
+ config: object | None = None,
+ **tcc_kwargs,
+ ) -> Env:
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port(platform)) # type: ignore[arg-type]
+ app = FastAPI()
+ app.include_router(router)
+ app.dependency_overrides[require_control_key_or_session] = lambda: None
+ clock = _Clock()
+ runtime = routes._Runtime()
+ runtime.limiter = routes._RateLimiter(clock=clock)
+ app.state.permissions_runtime = runtime
+ if service is not None:
+ app.state.permission_service = service
+ if config is not None:
+ app.state.config = config
+ return Env(TestClient(app), tcc, app, clock)
+
+ return build
+
+
+def _use_fake_tccutil(monkeypatch: pytest.MonkeyPatch, tcc: FakeTCC) -> None:
+ """``tccutil`` is a subprocess; the port imports ``subprocess`` lazily, so patch the module."""
+ monkeypatch.setattr(subprocess, "run", tcc.run_tccutil)
+
+
+# ----------------------------------------------------------------------
+# POST /{id}/request: the just-in-time ask
+# ----------------------------------------------------------------------
+
+
+def test_request_asks_macos_once_and_answers_at_once_with_the_outcome(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ started = time.monotonic()
+ response = env.post("microphone/request")
+ elapsed = time.monotonic() - started
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["permission"] == "microphone"
+ assert body["outcome"] == "pending" and body["granted"] is False
+ assert body["asked"] is True and body["reason"] == "not_determined"
+ assert body["user_detail"]
+ assert body["agent_detail"].startswith("[permission_needed:microphone] ")
+ assert len(env.tcc.requests("microphone")) == 1
+ assert env.tcc.dialog_open("microphone") # macOS owns the next step
+ assert elapsed < 2.0 # no HTTP hold on an unanswered dialog
+
+
+def test_request_reports_granted_when_the_person_allowed_in_the_dialog(make_env) -> None:
+ env = make_env() # the fake person clicks Allow
+
+ body = env.post("microphone/request").json()
+
+ assert body["outcome"] == "granted" and body["granted"] is True and body["asked"] is True
+ assert body["reason"] == "" and body["user_detail"] == "" and body["agent_detail"] == ""
+
+
+def test_request_is_attributed_to_the_feature_it_names(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ env.post("microphone/request", json={"feature": "browser_voice"})
+
+ [episode] = get_permission_service().outstanding()
+ assert episode.feature == "browser_voice" and episode.origin == "user"
+ assert episode.permissions == ("microphone",)
+
+
+def test_a_refused_browser_voice_microphone_opens_a_user_episode_the_toast_can_tell(
+ make_env,
+) -> None:
+ """The embedded window reports its own refused getUserMedia through this route."""
+ env = make_env()
+ env.tcc.deny("microphone")
+
+ body = env.post("microphone/request?dry_run=false", json={"feature": "browser_voice"}).json()
+
+ assert body["outcome"] == "denied" and body["asked"] is False
+ [episode] = get_permission_service().outstanding()
+ assert (episode.feature, episode.origin, episode.phase, episode.reason) == (
+ "browser_voice",
+ "user",
+ "blocked",
+ "denied",
+ )
+ assert env.tcc.requests() == [] # a denial is never asked again
+
+
+ ("permission", "feature"),
+ [
+ ("microphone", "voice"),
+ ("screen_recording", "computer_use"),
+ ("accessibility", "computer_use"),
+ ("input_monitoring", "global_shortcuts"),
+ ],
+)
+def test_request_without_a_feature_uses_the_first_feature_of_the_permission(
+ make_env, permission: str, feature: str
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ env.post(f"{permission}/request")
+
+ [episode] = get_permission_service().outstanding()
+ assert episode.feature == feature
+
+
+ "body",
+ [{"feature": "teleport"}, {"target": "com.evil.app"}, {"allow_outside": True}],
+ ids=["unknown-feature", "unknown-player", "misspelled-consent-flag"],
+)
+def test_request_refuses_an_unknown_feature_player_or_key(make_env, body: dict) -> None:
+ env = make_env()
+
+ response = env.post("microphone/request", json=body)
+
+ assert response.status_code == 422
+ assert env.tcc.requests() == []
+
+
+def test_a_denied_permission_is_reported_and_never_asked_again(make_env) -> None:
+ env = make_env()
+ env.tcc.deny("microphone")
+
+ body = env.post("microphone/request").json()
+
+ assert body["outcome"] == "denied" and body["asked"] is False
+ assert body["reason"] == "denied" and body["can_open_settings"] is True
+ assert body["can_prompt"] is False
+ assert env.tcc.requests() == []
+
+
+def test_outside_the_installed_app_nothing_is_asked_without_the_confirm_flag(make_env) -> None:
+ env = make_env(bundle_id=None, bundle_path=None, default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ first = env.post("microphone/request").json()
+
+ assert first["outcome"] == "needs_settings" and first["asked"] is False
+ assert first["outside_installed_app"] is True
+ assert env.tcc.requests() == [] and env.tcc.implicit_prompts() == []
+
+ env.clock.advance(6) # past the per-permission cooldown
+ confirmed = env.post("microphone/request", json={"allow_outside_app": True}).json()
+
+ assert confirmed["asked"] is True and confirmed["outcome"] == "pending"
+ assert len(env.tcc.requests("microphone")) == 1
+
+
+def test_the_confirm_flag_is_never_assumed(make_env) -> None:
+ env = make_env(bundle_id=None, bundle_path=None)
+
+ body = env.post("microphone/request", json={"allow_outside_app": False}).json()
+
+ assert body["asked"] is False and body["outcome"] == "needs_settings"
+ assert env.tcc.requests() == []
+
+
[email protected]("platform", ["win32", "linux"])
+def test_request_off_macos_is_not_required_and_touches_nothing(make_env, platform: str) -> None:
+ env = make_env(platform=platform)
+
+ body = env.post("microphone/request").json()
+
+ assert body["outcome"] == "not_required" and body["granted"] is True
+ assert body["asked"] is False
+ env.tcc.assert_silent()
+
+
+def test_event_posting_is_an_alias_of_accessibility_for_asking(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ body = env.post("event_posting/request").json()
+ assert body["permission"] == "event_posting" and body["outcome"] == "pending"
+ [episode] = get_permission_service().outstanding()
+ assert episode.permissions == ("accessibility",) # one request, one episode
-def _snapshot() -> dict:
- return {
- "platform": "darwin",
- "supported": True,
- "headless": False,
- "app_identity": {
- "app_name": "Personal Jarvis",
- "expected_bundle_id": "com.personal-jarvis.desktop",
- "bundle_id": "com.personal-jarvis.desktop",
- "bundle_path": "/Applications/Personal Jarvis.app",
- "launched_as_bundle": True,
- "stable": True,
- "foreground": True,
- },
- "permissions": [],
- "features": {},
- "restart_required": False,
+
+def test_request_hands_the_fake_service_exactly_one_interactive_non_waiting_ensure(
+ make_env,
+) -> None:
+ gate = FakePermissionService({PermissionId.MICROPHONE: "pending"})
+ env = make_env(service=gate)
+
+ body = env.post(
+ "microphone/request", json={"feature": "dictation", "allow_outside_app": True}
+ ).json()
+
+ assert body["outcome"] == "pending"
+ [call] = gate.ensure_calls(PermissionId.MICROPHONE)
+ assert (call.method, call.feature, call.interactive) == ("ensure", "dictation", True)
+ assert call.wait_s == 0 and call.allow_outside_app is True
+ env.tcc.assert_silent() # the fake service never reached the OS
+
+
+def test_dry_run_changes_nothing(make_env, monkeypatch: pytest.MonkeyPatch) -> None:
+ env = make_env()
+ _use_fake_tccutil(monkeypatch, env.tcc)
+
+ for action in ("request", "open-settings", "reset"):
+ response = env.post(f"microphone/{action}?dry_run=true")
+ body = response.json()
+ assert response.status_code == 200, action
+ assert body["dry_run"] is True and body["performed"] is False and body["ok"] is True
+ assert body["action"] == action.replace("-", "_")
+
+ assert env.tcc.requests() == [] and env.tcc.workspace_opened_urls == []
+ assert env.tcc.tccutil_calls == []
+
+
+def test_a_dry_run_does_not_count_against_the_rate_limit(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ env.post("microphone/request?dry_run=true")
+ env.post("microphone/request?dry_run=true")
+
+ assert env.post("microphone/request").status_code == 200
+
+
+# ----------------------------------------------------------------------
+# The Automation ask: blocking natively, never an HTTP hold
+# ----------------------------------------------------------------------
+
+
+def test_automation_without_a_player_asks_the_first_one_that_runs(make_env) -> None:
+ env = make_env(installed_players=[_MUSIC, _SPOTIFY], running_players=[_SPOTIFY])
+
+ body = env.post("automation/request").json()
+
+ # Music is first in the table but is not running: the guarded script asks
+ # nothing for it, so the route goes on to Spotify.
+ assert body["asked"] is True and body["outcome"] == "granted"
+ assert [call.target for call in env.tcc.requests("automation")] == [_SPOTIFY]
+ assert body["target"] == _SPOTIFY
+
+
+def test_automation_with_a_named_player_asks_only_that_one(make_env) -> None:
+ env = make_env(installed_players=[_MUSIC, _SPOTIFY], running_players=[_MUSIC, _SPOTIFY])
+
+ env.post("automation/request", json={"target": _SPOTIFY})
+
+ assert [call.target for call in env.tcc.requests("automation")] == [_SPOTIFY]
+
+
+def test_automation_with_no_player_running_launches_nothing_and_is_unavailable(make_env) -> None:
+ env = make_env(installed_players=[_MUSIC])
+
+ body = env.post("automation/request").json()
+
+ assert body["outcome"] == "unavailable" and body["granted"] is False
+ assert env.tcc.requests("automation") == [] and env.tcc.launches == []
+
+
+def test_an_automation_dialog_that_is_still_open_answers_pending_and_does_not_hold(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC])
+ service = get_permission_service()
+ entered: list[str | None] = []
+ release = threading.Event()
+ reached = threading.Event() # set by the stub itself: no assertion races a slow thread start
+ real_ensure = service.ensure
+
+ def blocking_ensure(*args, **kwargs):
+ entered.append(kwargs.get("target"))
+ reached.set()
+ release.wait(10) # the consent runner, blocked on an open dialog
+ return real_ensure(*args, **kwargs)
+
+ monkeypatch.setattr(service, "ensure", blocking_ensure)
+ monkeypatch.setattr(routes, "_AUTOMATION_ASK_WAIT_S", 0.2)
+ try:
+ started = time.monotonic()
+ body = env.post("automation/request").json()
+ elapsed = time.monotonic() - started
+
+ assert body["outcome"] == "pending" and body["asked"] is True
+ assert body["can_prompt"] is False and "Waiting for the user" in body["user_detail"]
+ assert elapsed < 5.0
+ # While that call is still blocked a second one starts nothing.
+ env.clock.advance(6)
+ again = env.post("automation/request").json()
+ assert again["outcome"] == "pending" and again["asked"] is False
+ assert reached.wait(5)
+ assert entered == [_MUSIC]
+ finally:
+ release.set()
+ thread = env.app.state.permissions_runtime.automation_ask._thread
+ if thread is not None:
+ thread.join(5)
+
+
+# ----------------------------------------------------------------------
+# The Keychain row: "Try again" replays the failed read
+# ----------------------------------------------------------------------
+
+
+def test_keychain_try_again_replays_the_failed_read(make_env) -> None:
+ env = make_env(credential_backend="file")
+
+ body = env.post("credential_store/request").json()
+
+ assert env.tcc.keychain_recover_calls == 1
+ assert body["permission"] == "credential_store"
+ assert body["outcome"] == "granted" and body["asked"] is True
+
+
+def test_keychain_try_again_that_is_declined_again_says_so(make_env) -> None:
+ env = make_env(credential_backend="file")
+ env.tcc.keychain_recover_result = False
+
+ body = env.post("credential_store/request").json()
+
+ assert body["outcome"] == "denied" and body["reason"] == "denied"
+ assert body["can_prompt"] is True and body["can_open_settings"] is False
+ assert "local file" in body["user_detail"]
+
+
+def test_keychain_that_already_works_replays_nothing(make_env) -> None:
+ env = make_env(credential_backend="platform")
+
+ body = env.post("credential_store/request").json()
+
+ assert body["outcome"] == "granted" and body["asked"] is False
+ assert env.tcc.keychain_recover_calls == 0
+
+
+# ----------------------------------------------------------------------
+# Rate limits: a cooldown per (action, permission) and a global cap
+# ----------------------------------------------------------------------
+
+
+def test_a_second_request_for_one_permission_within_five_seconds_is_429(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ assert env.post("microphone/request").status_code == 200
+ again = env.post("microphone/request")
+
+ assert again.status_code == 429
+ assert again.json() == {
+ "error": "rate_limited",
+ "scope": "permission",
+ "action": "request",
+ "permission_id": "microphone",
+ "retry_after_s": 5,
}
+ assert again.headers["retry-after"] == "5"
+ assert len(env.tcc.requests("microphone")) == 1 # the refusal never reached the OS
+ env.clock.advance(5.1)
+ assert env.post("microphone/request").status_code == 200
-class _Port:
- def __init__(self, *, fail: bool = False) -> None:
- self.fail = fail
- self.calls: list[tuple[str, str, bool]] = []
-
- def snapshot(self) -> dict:
- return _snapshot()
-
- def request(self, permission_id, *, dry_run: bool = False):
- self.calls.append(("request", permission_id.value, dry_run))
- return PermissionOperation(
- not self.fail,
- permission_id.value,
- "request",
- not dry_run and not self.fail,
- dry_run,
- False,
- "failed" if self.fail else "requested",
- _snapshot(),
- )
- def open_settings(self, permission_id, *, dry_run: bool = False):
- self.calls.append(("open_settings", permission_id.value, dry_run))
- return PermissionOperation(
- True,
- permission_id.value,
- "open_settings",
- not dry_run,
- dry_run,
- False,
- "opened",
- _snapshot(),
- )
+def test_the_cooldown_is_per_permission_and_per_action(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ assert env.post("microphone/request").status_code == 200
+ assert env.post("screen_recording/request").status_code == 200
+ assert env.post("microphone/open-settings").status_code == 200
+ again = env.post("microphone/open-settings")
+ assert again.status_code == 429 and again.json()["action"] == "open_settings"
+
+
+def test_an_alias_cannot_dodge_the_cooldown_of_its_pane_family(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ assert env.post("accessibility/request").status_code == 200
+ assert env.post("event_posting/request").status_code == 429
+
+
+def test_the_global_cap_covers_request_and_open_settings_together(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.app.state.permissions_runtime.limiter = routes._RateLimiter(
+ cooldown_s=0, global_max=3, global_window_s=60, clock=env.clock
+ )
+
+ assert env.post("microphone/request").status_code == 200
+ assert env.post("microphone/open-settings").status_code == 200
+ assert env.post("screen_recording/request").status_code == 200
+ refused = env.post("screen_recording/open-settings")
+
+ assert refused.status_code == 429
+ body = refused.json()
+ assert body["scope"] == "global" and body["retry_after_s"] == 60
+ assert len(env.tcc.workspace_opened_urls) == 1 # the refused call opened nothing
+
+ env.clock.advance(61) # the window slides on
+ assert env.post("screen_recording/open-settings").status_code == 200
+
+
+def test_a_refused_call_is_not_counted(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.app.state.permissions_runtime.limiter = routes._RateLimiter(
+ cooldown_s=5, global_max=2, global_window_s=60, clock=env.clock
+ )
+
+ assert env.post("microphone/request").status_code == 200
+ for _ in range(5):
+ assert env.post("microphone/request").status_code == 429 # cooldown, not the cap
+ assert env.post("screen_recording/request").status_code == 200 # the 2nd counted call
-def _client(port: _Port) -> TestClient:
- app = FastAPI()
- app.include_router(router)
- app.state.system_permission_port = port
- app.dependency_overrides[require_control_key_or_session] = lambda: None
- return TestClient(app)
+def test_reset_is_rate_limited_like_the_other_routes_that_change_what_macos_shows(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # "Reset, then request" in a loop would defeat the re-ask limits (P4).
+ env = make_env()
+ _use_fake_tccutil(monkeypatch, env.tcc)
-def test_status_returns_uncached_port_snapshot() -> None:
- body = _client(_Port()).get("/api/permissions/status").json()
+ assert env.post("microphone/reset").status_code == 200
+ again = env.post("microphone/reset")
+ assert again.status_code == 429 and again.json()["action"] == "reset"
+ assert len(env.tcc.tccutil_calls) == 1 # the refusal never reached tccutil
- assert body["platform"] == "darwin"
- assert body["app_identity"]["stable"] is True
+ env.clock.advance(5.1)
+ assert env.post("microphone/reset").status_code == 200
-def test_request_passes_stable_id_and_dry_run() -> None:
- port = _Port()
+# ----------------------------------------------------------------------
+# POST /{id}/open-settings
+# ----------------------------------------------------------------------
- response = _client(port).post("/api/permissions/screen_recording/request?dry_run=true")
+
+def test_open_settings_opens_the_matching_pane_and_returns_the_row(make_env) -> None:
+ env = make_env()
+
+ response = env.post("microphone/open-settings")
assert response.status_code == 200
- assert response.json()["dry_run"] is True
- assert port.calls == [("request", "screen_recording", True)]
+ body = response.json()
+ assert body["ok"] is True and body["action"] == "open_settings" and body["performed"] is True
+ assert body["permission_id"] == "microphone" and body["dry_run"] is False
+ assert body["permission"]["id"] == "microphone"
+ assert env.tcc.workspace_opened_urls == [
+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"
+ ]
+ assert env.tcc.requests() == [] # opening a pane is not a prompt
+
+
+def test_open_settings_that_cannot_open_is_a_409_with_the_full_payload(make_env) -> None:
+ env = make_env(headless=True) # no desktop session: the port refuses
+
+ response = env.post("microphone/open-settings")
+
+ assert response.status_code == 409
+ body = response.json()
+ assert body["ok"] is False and body["performed"] is False
+ assert body["message"] == "System Settings could not be opened."
+ assert env.tcc.workspace_opened_urls == []
+
+
+def test_the_keychain_has_no_settings_pane(make_env) -> None:
+ env = make_env()
+
+ response = env.post("credential_store/open-settings")
+
+ assert response.status_code == 409
+ assert "no System Settings pane" in response.json()["message"]
+ assert env.tcc.workspace_opened_urls == []
+
+
+# ----------------------------------------------------------------------
+# POST /{id}/reset ("Ask again")
+# ----------------------------------------------------------------------
+
+
+def test_reset_is_refused_with_409_while_the_permission_is_granted(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ env = make_env(granted=["microphone"])
+ _use_fake_tccutil(monkeypatch, env.tcc)
+
+ response = env.post("microphone/reset")
+ assert response.status_code == 409
+ body = response.json()
+ assert body["ok"] is False and body["performed"] is False
+ assert "allowed right now" in body["message"]
+ assert env.tcc.tccutil_calls == []
+ assert env.tcc.state("microphone").value == "granted"
+
+
+def test_reset_is_refused_when_only_the_window_oracle_sees_the_screen_grant(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ env = make_env()
+ _use_fake_tccutil(monkeypatch, env.tcc)
+ env.tcc.grant("screen_recording") # mid-process: the frozen preflight still says no
+
+ shallow = env.client.get("/api/permissions/screen_recording").json()
+ response = env.post("screen_recording/reset")
+
+ assert shallow["status"] == "not_granted" # the snapshot never uses the oracle
+ assert response.status_code == 409 # a reset must never throw a working grant away
+ assert env.tcc.tccutil_calls == []
-def test_open_settings_passes_permission_id() -> None:
- port = _Port()
- response = _client(port).post("/api/permissions/microphone/open-settings")
+def test_reset_of_a_denied_permission_drops_this_apps_own_row(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ env = make_env()
+ _use_fake_tccutil(monkeypatch, env.tcc)
+ env.tcc.deny("microphone")
+
+ response = env.post("microphone/reset")
assert response.status_code == 200
- assert response.json()["action"] == "open_settings"
- assert port.calls == [("open_settings", "microphone", False)]
+ body = response.json()
+ assert body["ok"] is True and body["performed"] is True and body["action"] == "reset"
+ assert env.tcc.tccutil_calls == [["/usr/bin/tccutil", "reset", "Microphone", env.tcc.grantee]]
+ assert env.tcc.state("microphone").value == "not_determined"
+ assert body["permission"]["status"] == "not_determined"
+
+
+def test_ask_again_after_a_reset_really_asks(make_env, monkeypatch: pytest.MonkeyPatch) -> None:
+ env = make_env(default_policy=DialogPolicy.DENY)
+ _use_fake_tccutil(monkeypatch, env.tcc)
+
+ first = env.post("microphone/request").json()
+ assert first["outcome"] == "denied" and first["asked"] is True
+ env.clock.advance(6)
+ assert env.post("microphone/request").json()["asked"] is False # stable: not asked again
+ assert env.post("microphone/reset").status_code == 200
+ env.clock.advance(6)
+ env.tcc.set_policy("microphone", DialogPolicy.ALLOW)
+ again = env.post("microphone/request").json()
-def test_failed_native_operation_is_conflict_with_full_payload() -> None:
- response = _client(_Port(fail=True)).post("/api/permissions/accessibility/request")
+ assert again["asked"] is True and again["outcome"] == "granted"
+ assert len(env.tcc.requests("microphone")) == 2
+
+
+def test_reset_outside_the_installed_app_is_refused_by_the_port(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ env = make_env(bundle_id=None, bundle_path=None)
+ _use_fake_tccutil(monkeypatch, env.tcc)
+ env.tcc.deny("microphone")
+
+ response = env.post("microphone/reset")
assert response.status_code == 409
- assert response.json()["ok"] is False
- assert response.json()["snapshot"]["platform"] == "darwin"
+ assert env.tcc.tccutil_calls == [] # a developer run must not wipe the installed app's rows
-def test_unknown_permission_id_is_rejected() -> None:
- response = _client(_Port()).post("/api/permissions/camera/request")
[email protected]("platform", ["win32", "linux"])
+def test_reset_off_macos_is_a_409(make_env, platform: str) -> None:
+ env = make_env(platform=platform)
- assert response.status_code == 422
+ response = env.post("microphone/reset")
+
+ assert response.status_code == 409
+ assert "only possible on macOS" in response.json()["message"]
+ env.tcc.assert_silent()
+
+
+def test_a_restricted_permission_cannot_be_reset(make_env, monkeypatch: pytest.MonkeyPatch) -> None:
+ env = make_env()
+ _use_fake_tccutil(monkeypatch, env.tcc)
+ env.tcc.restrict("microphone")
+
+ response = env.post("microphone/reset")
+
+ assert response.status_code == 409
+ assert "cannot be reset from here" in response.json()["message"]
+ assert env.tcc.tccutil_calls == []
+
+
+# ----------------------------------------------------------------------
+# Contract
+# ----------------------------------------------------------------------
+
+
+def test_unknown_permission_id_is_rejected(make_env) -> None:
+ env = make_env()
+
+ for method, path in (
+ ("post", "camera/request"),
+ ("post", "camera/open-settings"),
+ ("post", "camera/reset"),
+ ("get", "camera"),
+ ):
+ assert getattr(env.client, method)(f"/api/permissions/{path}").status_code == 422, path
def test_mutating_routes_are_marked_dangerous_in_openapi() -> None:
@@ -120,8 +658,361 @@ def test_mutating_routes_are_marked_dangerous_in_openapi() -> None:
paths = app.openapi()["paths"]
- assert paths["/api/permissions/{permission_id}/request"]["post"]["x-jarvis-dangerous"] is True
+ for action in ("request", "open-settings", "reset"):
+ route = paths[f"/api/permissions/{{permission_id}}/{action}"]["post"]
+ assert route["x-jarvis-dangerous"] is True, action
+ for read in ("/api/permissions/status", "/api/permissions/{permission_id}"):
+ assert "x-jarvis-dangerous" not in paths[read]["get"] # reads are never gated
+
+
+def test_every_handler_is_a_sync_def() -> None:
+ """A native call must never run on the event loop (scripts/ci/check_async_routes.py)."""
+ import inspect
+
+ for route in router.routes:
+ assert not inspect.iscoroutinefunction(route.endpoint), route.path
+
+
+def test_no_route_reaches_the_old_readiness_aggregation(make_env) -> None:
+ """The routes stopped using ``port.snapshot()`` (the feature/``wanted`` aggregation)."""
+ from jarvis.platform.permissions import SystemPermissionPort
+
+ env = make_env(granted=["microphone"])
+
+ # The aggregation is gone from the port altogether (the ratchet test pins it).
+ assert not hasattr(SystemPermissionPort, "snapshot")
+ assert env.client.get("/api/permissions/status").status_code == 200
+ assert env.client.get("/api/permissions/microphone").status_code == 200
+ assert env.post("microphone/request").status_code == 200
+
+
+def test_open_settings_and_reset_are_light_and_never_snapshot_or_probe_other_permissions(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Both "way out" routes used to run two full snapshots each: the Automation probe of
+ every running player, the window-title oracle and a consent-file write."""
+ env = make_env(
+ default_policy=DialogPolicy.NEVER_ANSWERED,
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ )
+ _use_fake_tccutil(monkeypatch, env.tcc)
+
+ assert env.post("accessibility/open-settings").status_code == 200
+ assert env.post("microphone/reset").status_code == 200
+
+ assert env.tcc.probes("screen_recording") == [] # no oracle, no preflight
+ assert env.tcc.probes("automation") == [] # no Apple Event probe of the player
+ assert len(env.tcc.workspace_opened_urls) == 1 and len(env.tcc.tccutil_calls) == 1
+
+
+def test_open_settings_works_outside_the_installed_app_because_it_is_not_a_prompt(
+ make_env,
+) -> None:
+ env = make_env(bundle_id=None, bundle_path=None)
+
+ body = env.post("microphone/open-settings").json()
+
+ assert body["ok"] is True and body["performed"] is True
+ assert body["permission"]["can_open_settings"] is True # the row says what the route does
+ assert len(env.tcc.workspace_opened_urls) == 1
+
+
+# ----------------------------------------------------------------------
+# Who may confirm a grant for the app that started Jarvis, and who may skip the cooldown
+# ----------------------------------------------------------------------
+
+
+def control_key() -> dict[str, str]:
+ """A Bearer control key: the way a coding agent drives the CLI.
+
+ The auth dependency is overridden in these tests; the routes only look at whether a
+ Bearer is PRESENT (an agent), never at its value.
+ """
+ return {"Authorization": "Bearer agent-key"}
+
+
+def test_an_agent_with_only_the_control_key_cannot_confirm_a_grant_for_another_app(
+ make_env, control_key: dict[str, str]
+) -> None:
+ env = make_env(bundle_id=None, bundle_path=None, default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ env.client.cookies.clear() # an agent has no browser session, only the control key
+ refused = env.post("microphone/request", json={"allow_outside_app": True}, headers=control_key)
+
+ assert refused.status_code == 403
+ assert refused.json()["error"] == "confirmation_requires_ui"
+ assert env.tcc.requests() == [] and env.tcc.implicit_prompts() == []
+ # The same agent may still ask without the confirmation (nothing is requested
+ # outside the installed app, the answer says so).
+ plain = env.post("microphone/request", headers=control_key).json()
+ assert plain["outside_installed_app"] is True and plain["asked"] is False
+
+
+def test_the_ui_may_confirm_a_grant_for_the_app_that_started_jarvis(make_env) -> None:
+ env = make_env(bundle_id=None, bundle_path=None, default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ body = env.post("microphone/request", json={"allow_outside_app": True}).json()
+
+ assert body["asked"] is True and len(env.tcc.requests("microphone")) == 1
+
+
+def test_only_an_explicit_ui_click_skips_the_reask_cooldown(
+ make_env, control_key: dict[str, str]
+) -> None:
+ gate = FakePermissionService({PermissionId.ACCESSIBILITY: "pending"})
+ env = make_env(service=gate)
+
+ env.post("accessibility/request") # the person clicked "Allow" in the Jarvis window
+ env.clock.advance(6)
+ env.client.cookies.clear() # an agent has no browser session, only the control key
+ env.post("accessibility/request", headers=control_key)
+
+ ui_call, agent_call = gate.ensure_calls(PermissionId.ACCESSIBILITY)
+ assert ui_call.force_ask is True and agent_call.force_ask is False
+
+
+def _script_client(env: Env) -> TestClient:
+ """A local script: no browser session cookie (the test harness adds one to every
+ client), no Authorization header and no ``Sec-Fetch-Site``."""
+ client = TestClient(env.app)
+ client.cookies.clear()
+ return client
+
+
+def test_the_ui_without_a_session_cookie_is_recognised_by_the_browsers_own_header(
+ make_env,
+) -> None:
+ # Open local access: the desktop WebView has no session cookie at all.
+ env = make_env(bundle_id=None, bundle_path=None, default_policy=DialogPolicy.NEVER_ANSWERED)
+ webview = _script_client(env)
+
+ body = webview.post(
+ "/api/permissions/microphone/request",
+ json={"allow_outside_app": True},
+ headers={"Sec-Fetch-Site": "same-origin"},
+ ).json()
+
+ assert body["asked"] is True and len(env.tcc.requests("microphone")) == 1
+
+
+def test_a_caller_with_no_credential_at_all_is_treated_as_an_agent(make_env) -> None:
+ # Open local access lets any loopback process reach the router without a key or a
+ # cookie; the person at the window is told apart by the browser's own header.
+ gate = FakePermissionService({PermissionId.ACCESSIBILITY: "pending"})
+ env = make_env(
+ service=gate, bundle_id=None, bundle_path=None, default_policy=DialogPolicy.NEVER_ANSWERED
+ )
+ script = _script_client(env)
+
+ refused = script.post("/api/permissions/microphone/request", json={"allow_outside_app": True})
+ script.post("/api/permissions/accessibility/request")
+ env.clock.advance(6)
+ script.post("/api/permissions/accessibility/request")
+
+ assert refused.status_code == 403
+ assert refused.json()["error"] == "confirmation_requires_ui"
+ assert env.tcc.requests() == []
+ assert [call.force_ask for call in gate.ensure_calls(PermissionId.ACCESSIBILITY)] == [
+ False,
+ False,
+ ]
+
+
+def test_an_agent_cannot_reset_and_so_cannot_rearm_the_request_cooldown(
+ make_env, control_key: dict[str, str], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ _use_fake_tccutil(monkeypatch, env.tcc)
+ env.post("accessibility/request") # asked once, the dialog was ignored
+ script = _script_client(env)
+
+ bearer_only = script.post("/api/permissions/accessibility/reset", headers=control_key)
+ no_credential = script.post("/api/permissions/accessibility/reset")
+ env.clock.advance(6)
+ again = script.post("/api/permissions/accessibility/request", headers=control_key).json()
+
+ assert bearer_only.status_code == 403 and no_credential.status_code == 403
+ assert bearer_only.json()["error"] == "confirmation_requires_ui"
+ assert env.tcc.tccutil_calls == []
+ assert again["asked"] is False # the per-process cooldown still stands
+ assert len(env.tcc.requests("accessibility")) == 1
+
+
+def test_an_agent_may_still_dry_run_a_reset(make_env, control_key: dict[str, str]) -> None:
+ env = make_env()
+
+ body = _script_client(env).post(
+ "/api/permissions/microphone/reset?dry_run=true", headers=control_key
+ )
+
+ assert body.status_code in (200, 409) # the plan is readable; nothing was reset
+ assert env.tcc.tccutil_calls == []
+
+
+def test_an_agent_loop_cannot_use_up_the_budget_of_the_persons_click(
+ make_env, control_key: dict[str, str]
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.app.state.permissions_runtime.limiter = routes._RateLimiter(
+ cooldown_s=5, global_max=2, global_window_s=60, clock=env.clock
+ )
+ script = _script_client(env)
+
+ assert (
+ script.post("/api/permissions/microphone/request", headers=control_key).status_code == 200
+ )
assert (
- paths["/api/permissions/{permission_id}/open-settings"]["post"]["x-jarvis-dangerous"]
- is True
+ script.post("/api/permissions/screen_recording/request", headers=control_key).status_code
+ == 200
)
+ assert (
+ script.post("/api/permissions/accessibility/request", headers=control_key).status_code
+ == 429
+ ) # the agent's own global cap
+
+ assert env.post("microphone/request").status_code == 200 # the person's click is not starved
+ assert env.post("screen_recording/open-settings").status_code == 200
+
+
+def test_the_allow_button_asks_again_in_the_real_service_after_the_cooldown_of_a_dismissed_prompt(
+ make_env,
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+
+ first = env.post("accessibility/request").json()
+ env.clock.advance(6) # past the route's own 5 s cooldown, inside the 10 minute re-ask window
+ second = env.post("accessibility/request").json()
+
+ assert first["asked"] is True and second["asked"] is True
+ assert len(env.tcc.requests("accessibility")) == 2
+
+
+def test_reset_is_refused_while_any_player_is_still_allowed(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The strictest-answer aggregate hid a working player behind one never asked."""
+ env = make_env(installed_players=[_MUSIC, _SPOTIFY], running_players=[_MUSIC, _SPOTIFY])
+ env.tcc.grant("automation", _MUSIC) # Spotify was never asked
+ _use_fake_tccutil(monkeypatch, env.tcc)
+
+ response = env.post("automation/reset")
+
+ assert response.status_code == 409
+ assert "allowed right now" in response.json()["message"]
+ assert env.tcc.tccutil_calls == [] # the working Music grant was not thrown away
+
+
+# ----------------------------------------------------------------------
+# ?activated=1: the first refetch after the window regained focus
+# ----------------------------------------------------------------------
+
+
+class _RecordingService:
+ """A real service whose ``note_app_activated`` / ``refresh_episodes`` order is logged."""
+
+ def __init__(self) -> None:
+ from jarvis.platform.permission_service import PermissionService
+
+ self.inner = PermissionService()
+ self.log: list[str] = []
+
+ def __getattr__(self, name: str):
+ return getattr(self.inner, name)
+
+ def note_app_activated(self) -> None:
+ self.log.append("activated")
+ self.inner.note_app_activated()
+
+ def refresh_episodes(self) -> None:
+ self.log.append("refresh")
+ self.inner.refresh_episodes()
+
+
[email protected]("path", ["status", "screen_recording"])
+def test_the_activated_flag_notes_the_refocus_before_the_episodes_are_refreshed(
+ make_env, path: str
+) -> None:
+ service = _RecordingService()
+ env = make_env(service=service, default_policy=DialogPolicy.NEVER_ANSWERED)
+ try:
+ # An open Screen Recording episode, so the refresh has something to do.
+ service.inner.ensure(PermissionId.SCREEN_RECORDING, feature="computer_use")
+
+ assert env.client.get(f"/api/permissions/{path}").status_code == 200
+ assert "activated" not in service.log, "no flag, no hint"
+
+ service.log.clear()
+ assert env.client.get(f"/api/permissions/{path}?activated=1").status_code == 200
+ assert service.log[0] == "activated"
+ assert service.log.count("activated") == 1
+ assert "refresh" in service.log
+ finally:
+ service.inner._shutdown()
+
+
[email protected]("path", ["status", "screen_recording"])
+def test_an_agent_cannot_use_the_activated_flag_to_promote_an_episode(
+ make_env, control_key: dict[str, str], path: str
+) -> None:
+ service = _RecordingService()
+ env = make_env(service=service, default_policy=DialogPolicy.NEVER_ANSWERED)
+ try:
+ service.inner.ensure(PermissionId.SCREEN_RECORDING, feature="computer_use")
+ service.log.clear()
+
+ response = _script_client(env).get(
+ f"/api/permissions/{path}?activated=1", headers=control_key
+ )
+
+ assert response.status_code == 200
+ assert "activated" not in service.log # a focus hint is the person's alone
+ finally:
+ service.inner._shutdown()
+
+
+def test_the_activated_flag_promotes_a_dialog_the_user_left_to_blocked(make_env) -> None:
+ # Screen Recording's dialog only offers "Open System Settings": once the user is
+ # back in the app the card may show, without waiting for the 15 s of silence.
+ service = _RecordingService()
+ env = make_env(service=service, default_policy=DialogPolicy.NEVER_ANSWERED)
+ try:
+ service.inner.ensure(PermissionId.SCREEN_RECORDING, feature="computer_use")
+
+ before = env.client.get("/api/permissions/status").json()["needed"]
+ assert [e["phase"] for e in before] == ["os_dialog"]
+
+ after = env.client.get("/api/permissions/status?activated=1").json()["needed"]
+ assert [(e["feature"], e["phase"], e["reason"]) for e in after] == [
+ ("computer_use", "blocked", "needs_settings")
+ ]
+ # A hint about what the user did, never a prompt: still one native request.
+ assert len(env.tcc.requests("screen_recording")) == 1
+ finally:
+ service.inner._shutdown()
+
+
+def test_a_failing_activation_hint_never_turns_a_read_into_a_500(make_env) -> None:
+ class _Broken(_RecordingService):
+ def note_app_activated(self) -> None:
+ raise RuntimeError("boom")
+
+ service = _Broken()
+ env = make_env(service=service)
+ try:
+ assert env.client.get("/api/permissions/status?activated=1").status_code == 200
+ assert env.client.get("/api/permissions/microphone?activated=1").status_code == 200
+ finally:
+ service.inner._shutdown()
+
+
+def test_the_activated_flag_is_documented_on_both_get_routes() -> None:
+ from fastapi import FastAPI
+
+ app = FastAPI()
+ app.include_router(router)
+ paths = app.openapi()["paths"]
+ for read in ("/api/permissions/status", "/api/permissions/{permission_id}"):
+ names = {parameter["name"] for parameter in paths[read]["get"]["parameters"]}
+ assert "activated" in names, read
diff --git a/tests/unit/ui/web/test_permissions_snapshot.py b/tests/unit/ui/web/test_permissions_snapshot.py
new file mode 100644
index 0000000000..fb2653d676
--- /dev/null
+++ b/tests/unit/ui/web/test_permissions_snapshot.py
@@ -0,0 +1,918 @@
+"""Snapshot v2 and the single-row read of the permission routes.
+
+``GET /api/permissions/status`` is passive: it never prompts and never blocks. Every
+test runs the REAL ``PermissionService`` on a REAL ``SystemPermissionPort`` that sits
+on ``FakeTCC`` (``tests/fakes/fake_tcc.py``), behind a real FastAPI ``TestClient``.
+The FakeTCC call log is the proof that nothing was asked. Nothing here ran on a real
+Mac: every macOS behaviour is a MODEL (see the fidelity ledger in ``fake_tcc.py``).
+
+The key sets of the snapshot cross Python and JSON (the CLI and the CI probe read them):
+the TypedDicts of ``permissions_routes`` are read back here against the real answer. The
+web UI no longer reads the snapshot (it listens to ``PermissionNeeded`` /
+``PermissionResolved`` only, whose vocabulary ``test_permission_events.py`` pins against
+``lib/permissionEvents.ts``), so there is no TypeScript twin of it any more.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import subprocess
+import threading
+import time
+from collections.abc import Iterator
+from dataclasses import dataclass
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any, get_type_hints
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.core.events import PERMISSION_FEATURES, PermissionResolved
+from jarvis.platform import permission_service as service_module
+from jarvis.platform.permission_service import Episode, PermissionService, get_permission_service
+from jarvis.platform.permissions import PermissionId, SystemPermissionPort
+from jarvis.ui.web import permissions_routes as routes
+from jarvis.ui.web.control_auth import require_control_key_or_session
+from jarvis.ui.web.permissions_routes import (
+ AppIdentityBlock,
+ NeededEpisode,
+ PermissionRow,
+ PermissionsSnapshot,
+ router,
+)
+from tests.fakes.fake_tcc import DMG_BUNDLE_ID, DialogPolicy, FakeTCC, TccService, install_port
+
+_MUSIC = "com.apple.Music"
+_SPOTIFY = "com.spotify.client"
+_REMOVED_KEYS = {"features", "wanted", "active", "identity_reset", "restart_required", "foreground"}
+
+
+# ----------------------------------------------------------------------
+# Harness
+# ----------------------------------------------------------------------
+
+
+class _RecordingBus:
+ """A bus stand-in: ``publish`` is a coroutine, like ``EventBus.publish``."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self.events: list[Any] = []
+
+ async def publish(self, event: Any) -> None:
+ with self._lock:
+ self.events.append(event)
+
+
+class _LoopThread:
+ """An asyncio loop on its own thread, like the server's loop next to a worker thread."""
+
+ def __init__(self) -> None:
+ self.loop = asyncio.new_event_loop()
+ self.thread = threading.Thread(target=self._run, name="test-loop", daemon=True)
+ self.thread.start()
+
+ def _run(self) -> None:
+ asyncio.set_event_loop(self.loop)
+ self.loop.run_forever()
+
+ def flush(self) -> None:
+ for _ in range(3):
+ asyncio.run_coroutine_threadsafe(asyncio.sleep(0), self.loop).result(timeout=5)
+
+ def stop(self) -> None:
+ self.flush()
+ self.loop.call_soon_threadsafe(self.loop.stop)
+ self.thread.join(timeout=5)
+ self.loop.close()
+
+
+@dataclass
+class Env:
+ client: TestClient
+ tcc: FakeTCC
+ app: FastAPI
+
+ def status(self, query: str = "") -> dict:
+ response = self.client.get(f"/api/permissions/status{query}")
+ assert response.status_code == 200, response.text
+ return response.json()
+
+ def row(self, permission: str) -> dict:
+ response = self.client.get(f"/api/permissions/{permission}")
+ assert response.status_code == 200, response.text
+ return response.json()
+
+ def rows(self, query: str = "") -> dict[str, dict]:
+ return {row["id"]: row for row in self.status(query)["permissions"]}
+
+ def post(self, path: str, **kwargs: Any):
+ return self.client.post(f"/api/permissions/{path}", **kwargs)
+
+
+def make_env(monkeypatch: pytest.MonkeyPatch):
+ def build(*, platform: str = "darwin", config: object | None = None, **tcc_kwargs: Any) -> Env:
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port(platform)) # type: ignore[arg-type]
+ app = FastAPI()
+ app.include_router(router)
+ app.dependency_overrides[require_control_key_or_session] = lambda: None
+ runtime = routes._Runtime()
+ # No cooldown: these tests ask more than once for the same permission.
+ runtime.limiter = routes._RateLimiter(cooldown_s=0, global_max=10_000)
+ app.state.permissions_runtime = runtime
+ if config is not None:
+ app.state.config = config
+ return Env(TestClient(app), tcc, app)
+
+ return build
+
+
+def loop_thread() -> Iterator[_LoopThread]:
+ thread = _LoopThread()
+ yield thread
+ # The watcher task lives on this loop: cancel it before the loop stops.
+ service_module._reset_for_tests()
+ thread.stop()
+
+
+def _ducking(enabled: bool) -> SimpleNamespace:
+ return SimpleNamespace(ducking=SimpleNamespace(enabled=enabled))
+
+
+def _typed_keys(typed_dict: type) -> set[str]:
+ return set(get_type_hints(typed_dict))
+
+
+def _walk_keys(value: Any) -> Iterator[str]:
+ if isinstance(value, dict):
+ for key, inner in value.items():
+ yield key
+ yield from _walk_keys(inner)
+ elif isinstance(value, list):
+ for inner in value:
+ yield from _walk_keys(inner)
+
+
+def _restart_hint_episode(permission: str) -> Episode:
+ """What the service will publish once a consumer reports a restart hint."""
+ return Episode(
+ permissions=(permission,),
+ feature="computer_use",
+ reason="restart_hint",
+ phase="blocked",
+ origin="user",
+ target="",
+ can_prompt=False,
+ can_open_settings=True,
+ outside_app=False,
+ detail="",
+ trace_id="00000000-0000-0000-0000-000000000000",
+ opened_at_ns=1,
+ )
+
+
+# ----------------------------------------------------------------------
+# The key set (AP-4)
+# ----------------------------------------------------------------------
+
+
+def test_the_snapshot_has_exactly_the_keys_of_its_typed_dicts(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.post("microphone/request") # one open episode, so `needed` has an entry to check
+
+ snapshot = env.status("?include=automation")
+
+ assert set(snapshot) == _typed_keys(PermissionsSnapshot)
+ assert set(snapshot["app_identity"]) == _typed_keys(AppIdentityBlock)
+ assert snapshot["permissions"], "no rows"
+ for row in snapshot["permissions"]:
+ assert set(row) == _typed_keys(PermissionRow), row["id"]
+ assert snapshot["needed"], "no open episode"
+ for episode in snapshot["needed"]:
+ assert set(episode) == _typed_keys(NeededEpisode)
+
+
+def test_the_row_read_has_the_keys_of_a_snapshot_row(make_env) -> None:
+ env = make_env()
+
+ for permission in ("microphone", "screen_recording", "accessibility", "input_monitoring"):
+ assert set(env.row(permission)) == _typed_keys(PermissionRow), permission
+
+
[email protected]("platform", ["win32", "linux"])
+def test_the_non_macos_snapshot_has_the_same_key_set(make_env, platform: str) -> None:
+ env = make_env(platform=platform)
+
+ snapshot = env.status("?include=automation")
+
+ assert set(snapshot) == _typed_keys(PermissionsSnapshot)
+ assert set(snapshot["app_identity"]) == _typed_keys(AppIdentityBlock)
+ assert all(set(row) == _typed_keys(PermissionRow) for row in snapshot["permissions"])
+
+
+def test_the_retired_keys_are_gone_everywhere(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.post("microphone/request")
+
+ keys = set(_walk_keys(env.status("?include=automation")))
+
+ assert not keys & _REMOVED_KEYS, keys & _REMOVED_KEYS
+ assert not set(_walk_keys(env.row("microphone"))) & _REMOVED_KEYS
+
+
+def test_the_keys_other_consumers_read_are_unchanged(make_env) -> None:
+ """``check_frozen_browser.py`` and the CLI relay read these four."""
+ env = make_env(granted=[TccService.MICROPHONE])
+
+ snapshot = env.status()
+
+ assert snapshot["platform"] == "darwin"
+ assert snapshot["app_identity"]["bundle_id"] == "com.personal-jarvis.desktop"
+ microphone = next(row for row in snapshot["permissions"] if row["id"] == "microphone")
+ assert microphone["status"] == "granted"
+
+
+def test_the_snapshot_survives_a_json_round_trip(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.post("microphone/request")
+
+ snapshot = env.status("?include=automation")
+
+ assert json.loads(json.dumps(snapshot)) == snapshot
+
+
+def test_used_for_speaks_the_event_feature_vocabulary(make_env) -> None:
+ rows = make_env().rows("?include=automation")
+
+ for row in rows.values():
+ assert set(row["used_for"]) <= set(PERMISSION_FEATURES), row["id"]
+ assert rows["credential_store"]["used_for"] == [] # the Keychain has no event feature
+ assert rows["microphone"]["used_for"][0] == "voice"
+ assert rows["automation"]["used_for"] == ["audio_ducking"]
+
+
+def test_every_used_for_entry_is_a_known_feature() -> None:
+ for permission, features in routes._USED_FOR.items():
+ assert set(features) <= set(PERMISSION_FEATURES), permission
+ assert set(routes._USED_FOR) == set(routes._ROW_ORDER)
+ assert set(routes._ROW_LABELS) == set(routes._ROW_ORDER)
+
+
+def test_the_real_answers_carry_exactly_the_keys_of_their_typed_dicts(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ monkeypatch.setattr(subprocess, "run", env.tcc.run_tccutil)
+
+ ensured = env.post("microphone/request").json()
+ refused = env.post("microphone/request") # inside the route's own cooldown
+ opened = env.post("microphone/open-settings").json()
+ env.tcc.deny("microphone")
+ reset = env.post("microphone/reset").json()
+
+ assert set(ensured) == _typed_keys(routes.EnsurePayload)
+ assert set(opened) == _typed_keys(routes.OperationPayload)
+ assert set(reset) == _typed_keys(routes.OperationPayload)
+ assert set(opened["permission"]) == _typed_keys(PermissionRow)
+ if refused.status_code == 429: # the harness limiter has no cooldown: cover the 429 shape
+ assert set(refused.json()) == _typed_keys(routes.RateLimitedPayload)
+ limited = routes._rate_limited(
+ routes._Refusal("permission", 4.2), "request", PermissionId.MICROPHONE
+ )
+ assert set(json.loads(limited.body)) == _typed_keys(routes.RateLimitedPayload)
+
+
+# ----------------------------------------------------------------------
+# Passive: never prompts, never blocks
+# ----------------------------------------------------------------------
+
+
+def test_status_never_prompts_on_a_fresh_mac(make_env) -> None:
+ env = make_env() # every permission not_determined
+
+ for _ in range(3):
+ env.status("?include=automation")
+ env.row("microphone")
+ env.row("screen_recording")
+
+ env.tcc.assert_no_prompts()
+ assert env.tcc.requests() == [] and env.tcc.implicit_prompts() == []
+ assert env.tcc.launches == []
+ assert env.status()["needed"] == [] # nothing asked, nothing is waiting
+
+
+def test_status_never_blocks_on_a_dialog_nobody_answered(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.post("microphone/request")
+
+ started = time.monotonic()
+ snapshot = env.status()
+ elapsed = time.monotonic() - started
+
+ assert elapsed < 2.0
+ assert [episode["permissions"] for episode in snapshot["needed"]] == [["microphone"]]
+
+
+def test_status_reads_screen_recording_with_the_shallow_preflight_only(make_env) -> None:
+ env = make_env()
+ env.tcc.grant("screen_recording") # mid-process: the preflight stays frozen (BUG-161)
+
+ row = env.rows()["screen_recording"]
+
+ # Documented limitation of the snapshot: the window-title oracle is a gesture
+ # and watcher tool (it enumerates windows), never a status read.
+ assert row["status"] == "not_granted"
+
+
+def test_status_never_uses_the_old_readiness_aggregation(make_env, monkeypatch) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC])
+
+ def forbidden(self, *args, **kwargs): # noqa: ANN001, ARG001
+ raise AssertionError("the status routes must not aggregate")
+
+ # The readiness aggregation no longer exists on the port at all.
+ assert not hasattr(SystemPermissionPort, "snapshot")
+ # The aggregate Automation read is a live probe of every player: never from here.
+ monkeypatch.setattr(SystemPermissionPort, "_automation_state", forbidden)
+
+ snapshot = env.status("?include=automation")
+
+ assert [row["id"] for row in snapshot["permissions"]] == [
+ "microphone",
+ "screen_recording",
+ "accessibility",
+ "input_monitoring",
+ "automation",
+ "credential_store",
+ ]
+
+
+def test_event_posting_has_no_row_of_its_own(make_env) -> None:
+ env = make_env()
+
+ assert "event_posting" not in env.rows("?include=automation")
+ folded = env.row("event_posting") # the alias answers with its pane family
+ assert folded["id"] == "accessibility"
+
+
+def test_unknown_permission_is_a_422(make_env) -> None:
+ assert make_env().client.get("/api/permissions/camera").status_code == 422
+
+
+# ----------------------------------------------------------------------
+# The rows on a Mac
+# ----------------------------------------------------------------------
+
+
+def test_a_fresh_mac_offers_every_row_a_way_forward(make_env) -> None:
+ rows = make_env().rows()
+
+ assert list(rows) == [
+ "microphone",
+ "screen_recording",
+ "accessibility",
+ "input_monitoring",
+ "credential_store",
+ ]
+ assert rows["microphone"]["status"] == "not_determined"
+ for permission in ("microphone", "screen_recording", "accessibility", "input_monitoring"):
+ row = rows[permission]
+ assert row["can_request"] is True, permission
+ assert row["can_open_settings"] is True, permission
+ assert row["can_reset"] is True, permission
+ assert row["restart_hint"] is False
+ assert row["settings_path"].startswith("System Settings > Privacy & Security > ")
+ assert rows["microphone"]["detail"].startswith("Personal Jarvis needs Microphone access")
+
+
+def test_granted_rows_offer_nothing_to_fix(make_env) -> None:
+ env = make_env(granted=[TccService.MICROPHONE, TccService.ACCESSIBILITY])
+
+ rows = env.rows()
+
+ for permission in ("microphone", "accessibility"):
+ row = rows[permission]
+ assert row["status"] == "granted" and row["detail"] == ""
+ assert row["can_request"] is False and row["can_reset"] is False
+ assert row["can_open_settings"] is True # a person may still want to look at the pane
+
+
+def test_the_keychain_row_offers_nothing_while_the_vault_works(make_env) -> None:
+ row = make_env(credential_backend="platform").rows()["credential_store"]
+
+ assert row["status"] == "granted" and row["can_request"] is False and row["detail"] == ""
+
+
+def test_the_keychain_row_offers_try_again_after_a_declined_prompt(make_env) -> None:
+ declined = make_env(credential_backend="file").rows()["credential_store"]
+
+ assert declined["status"] == "not_granted" and declined["can_request"] is True
+ assert "local file" in declined["detail"]
+ assert declined["can_open_settings"] is False and declined["settings_path"] is None
+ assert declined["can_reset"] is False # not a TCC row
+
+
+def test_a_denied_row_points_at_settings_and_offers_ask_again_but_no_prompt(make_env) -> None:
+ env = make_env()
+ env.tcc.deny("microphone")
+
+ row = env.rows()["microphone"]
+
+ assert row["status"] == "denied"
+ assert row["can_request"] is False # macOS will not ask a second time
+ assert row["can_reset"] is True and row["can_open_settings"] is True
+ assert "turned off" in row["detail"] and "Microphone" in row["detail"]
+
+
+def test_a_restricted_row_is_explained_not_actionable(make_env) -> None:
+ env = make_env()
+ env.tcc.restrict("microphone")
+
+ row = env.rows()["microphone"]
+
+ assert row["status"] == "restricted"
+ assert row["can_request"] is False and row["can_reset"] is False
+ assert "restricted" in row["detail"]
+
+
+def test_a_missing_framework_reads_unavailable_with_a_fixed_sentence(make_env) -> None:
+ env = make_env()
+ env.tcc.drop_framework("AVFoundation")
+
+ row = env.rows()["microphone"]
+
+ assert row["status"] == "unavailable" and row["can_request"] is False
+ assert row["detail"] == "Personal Jarvis cannot ask for Microphone access in this session."
+
+
+def test_a_missing_usage_string_means_the_row_cannot_be_asked(make_env) -> None:
+ env = make_env(usage_strings=[TccService.AUTOMATION]) # no NSMicrophoneUsageDescription
+
+ row = env.rows()["microphone"]
+
+ assert row["status"] == "not_determined"
+ assert row["can_request"] is False # asking would abort the process (BUG-058 class)
+ assert env.tcc.requests() == []
+
+
+def test_a_headless_session_offers_no_dialog_and_no_window(make_env) -> None:
+ env = make_env(headless=True)
+
+ snapshot = env.status()
+
+ assert snapshot["headless"] is True
+ for row in snapshot["permissions"]:
+ assert not (row["can_request"] or row["can_open_settings"] or row["can_reset"]), row["id"]
+
+
+def test_outside_the_installed_app_asking_and_opening_a_pane_stay_possible_but_resetting_does_not(
+ make_env,
+) -> None:
+ env = make_env(bundle_id=None, bundle_path=None)
+
+ snapshot = env.status()
+
+ assert snapshot["outside_installed_app"] is True
+ assert snapshot["app_identity"]["stable"] is False
+ assert snapshot["app_identity"]["launched_as_bundle"] is False
+ row = next(row for row in snapshot["permissions"] if row["id"] == "microphone")
+ assert row["can_request"] is True # after an explicit confirmation naming the grantee
+ assert row["can_reset"] is False # tccutil is scoped to the installed app's own bundle id
+ # Opening a pane is not an action on the permission (P6): it needs a desktop
+ # session, not the installed-app identity.
+ assert row["can_open_settings"] is True
+
+
+def test_the_installed_app_reports_a_stable_identity(make_env) -> None:
+ snapshot = make_env().status()
+
+ assert snapshot["outside_installed_app"] is False
+ assert snapshot["app_identity"] == {
+ "app_name": "Personal Jarvis",
+ "bundle_id": "com.personal-jarvis.desktop",
+ "bundle_path": "/Applications/Personal Jarvis.app",
+ "launched_as_bundle": True,
+ "stable": True,
+ }
+
+
+def test_the_dmg_app_is_an_installed_app_too(make_env) -> None:
+ snapshot = make_env(bundle_id=DMG_BUNDLE_ID).status()
+
+ assert snapshot["app_identity"]["bundle_id"] == DMG_BUNDLE_ID
+ assert snapshot["outside_installed_app"] is False
+
+
+# ----------------------------------------------------------------------
+# Off macOS
+# ----------------------------------------------------------------------
+
+
[email protected]("platform", ["win32", "linux"])
+def test_off_macos_every_row_is_not_required_and_nothing_is_open(make_env, platform: str) -> None:
+ env = make_env(platform=platform)
+
+ snapshot = env.status("?include=automation")
+
+ assert snapshot["platform"] == platform and snapshot["supported"] is False
+ assert snapshot["outside_installed_app"] is False # there is no app bundle to be outside of
+ assert snapshot["needed"] == []
+ assert len(snapshot["permissions"]) == 6
+ for row in snapshot["permissions"]:
+ assert row["status"] == "not_required", row["id"]
+ assert not (row["can_request"] or row["can_open_settings"] or row["can_reset"])
+ assert row["restart_hint"] is False and row["settings_path"] is None
+ assert row["detail"] == "This operating system does not require a macOS privacy permission."
+ env.tcc.assert_silent() # the FakeTCC call log stays empty
+
+
+# ----------------------------------------------------------------------
+# needed[]: the open episodes
+# ----------------------------------------------------------------------
+
+
+def test_needed_reflects_the_open_episodes_and_empties_when_they_resolve(make_env) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.post("microphone/request", json={"feature": "dictation"})
+
+ [episode] = env.status()["needed"]
+
+ assert episode["permissions"] == ["microphone"] and episode["feature"] == "dictation"
+ assert episode["origin"] == "user" and episode["phase"] == "os_dialog"
+ assert episode["reason"] == "not_determined"
+ assert episode["trace_id"] and episode["opened_at_ns"] > 0
+
+ env.tcc.answer("microphone", DialogPolicy.ALLOW)
+ get_permission_service().invalidate() # a negative answer is cached for ~250 ms
+ snapshot = env.status()
+
+ assert snapshot["needed"] == []
+ assert (
+ next(r for r in snapshot["permissions"] if r["id"] == "microphone")["status"] == "granted"
+ )
+
+
+def test_needed_lists_a_background_consumer_without_asking(make_env) -> None:
+ env = make_env()
+ result = get_permission_service().ensure("microphone", feature="wake_word", interactive=False)
+
+ [episode] = env.status()["needed"]
+
+ assert not result.asked and env.tcc.requests() == []
+ assert (episode["origin"], episode["feature"]) == ("background", "wake_word")
+ assert episode["can_prompt"] is True
+
+
+def test_needed_keeps_denied_episodes_and_folds_event_posting(make_env) -> None:
+ env = make_env()
+ env.tcc.deny("microphone")
+ get_permission_service().ensure("microphone", feature="voice")
+ get_permission_service().ensure("event_posting", feature="computer_use", interactive=False)
+
+ needed = {tuple(e["permissions"]): e for e in env.status()["needed"]}
+
+ assert set(needed) == {("microphone",), ("accessibility",)}
+ assert needed[("microphone",)]["reason"] == "denied"
+
+
+def test_a_status_read_publishes_the_resolve_edge(make_env, loop_thread: _LoopThread) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ bus = _RecordingBus()
+ get_permission_service().attach_bus(bus, loop_thread.loop)
+ env.post("microphone/request")
+ env.tcc.answer("microphone", DialogPolicy.ALLOW)
+ get_permission_service().invalidate() # a negative answer is cached for ~250 ms
+ loop_thread.flush()
+ assert not [e for e in bus.events if isinstance(e, PermissionResolved)]
+
+ env.status() # the watcher has not ticked: this path sees the edge first
+ loop_thread.flush()
+
+ resolved = [e for e in bus.events if isinstance(e, PermissionResolved)]
+ assert [(e.permissions, e.granted) for e in resolved] == [(("microphone",), True)]
+
+
+def test_the_single_row_read_publishes_the_resolve_edge_too(
+ make_env, loop_thread: _LoopThread
+) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ bus = _RecordingBus()
+ get_permission_service().attach_bus(bus, loop_thread.loop)
+ env.post("microphone/request")
+ env.tcc.answer("microphone", DialogPolicy.ALLOW)
+ get_permission_service().invalidate() # a negative answer is cached for ~250 ms
+
+ row = env.row("microphone")
+ loop_thread.flush()
+
+ assert row["status"] == "granted"
+ assert [e.granted for e in bus.events if isinstance(e, PermissionResolved)] == [True]
+
+
+def test_a_restart_hint_episode_marks_its_row(make_env, monkeypatch: pytest.MonkeyPatch) -> None:
+ env = make_env()
+ hint = _restart_hint_episode("screen_recording")
+ monkeypatch.setattr(PermissionService, "outstanding", lambda self: [hint])
+
+ rows = env.rows()
+
+ assert rows["screen_recording"]["restart_hint"] is True
+ assert "quit and reopened" in rows["screen_recording"]["detail"]
+ assert rows["microphone"]["restart_hint"] is False
+
+
+def test_a_restart_hint_marks_a_granted_row_after_a_real_failed_use(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A wallpaper-only capture while the state reads granted still needs the hint."""
+ env = make_env(granted=[TccService.SCREEN_RECORDING])
+ hint = _restart_hint_episode("screen_recording")
+ monkeypatch.setattr(PermissionService, "outstanding", lambda self: [hint])
+
+ row = env.rows()["screen_recording"]
+
+ assert row["status"] == "granted" and row["restart_hint"] is True
+ assert "quit and reopened" in row["detail"]
+
+
+def test_a_restart_hint_never_marks_a_row_that_is_not_required(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ env = make_env(platform="linux")
+ hint = _restart_hint_episode("screen_recording")
+ monkeypatch.setattr(PermissionService, "outstanding", lambda self: [hint])
+
+ rows = env.rows()
+
+ assert all(row["restart_hint"] is False for row in rows.values())
+
+
+# ----------------------------------------------------------------------
+# The Automation row
+# ----------------------------------------------------------------------
+
+
+def test_the_automation_row_is_not_computed_while_ducking_is_off(make_env) -> None:
+ env = make_env(config=_ducking(False), installed_players=[_MUSIC], running_players=[_MUSIC])
+
+ assert "automation" not in env.rows()
+ assert env.tcc.probes("automation") == [] and env.tcc.requests("automation") == []
+
+
+def test_the_automation_row_is_absent_without_a_configuration_too(make_env) -> None:
+ assert "automation" not in make_env().rows()
+
+
+def test_the_automation_row_appears_when_ducking_is_on(make_env) -> None:
+ env = make_env(config=_ducking(True), installed_players=[_MUSIC], running_players=[_MUSIC])
+
+ rows = env.rows()
+
+ assert rows["automation"]["status"] == "not_determined"
+ assert rows["automation"]["can_request"] is True
+ assert "Checked only while Music or Spotify is running." in rows["automation"]["detail"]
+ assert env.tcc.requests("automation") == [] # reading asks nothing
+
+
+def test_the_automation_row_appears_on_request(make_env) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC])
+
+ assert "automation" in env.rows("?include=automation")
+ assert "automation" in env.rows("?include=foo, automation")
+ assert "automation" not in env.rows("?include=foo")
+
+
+ ("setup", "status", "can_request"),
+ [
+ ({"installed_players": [_MUSIC], "running_players": [_MUSIC]}, "not_determined", True),
+ ({"installed_players": [_MUSIC]}, "not_determined", True), # closed: unknown, not "no"
+ ({}, "not_required", False), # no scriptable player installed
+ ],
+ ids=["running", "closed", "no-players"],
+)
+def test_the_automation_row_reflects_the_players(
+ make_env, setup: dict, status: str, can_request: bool
+) -> None:
+ row = make_env(**setup).rows("?include=automation")["automation"]
+
+ assert row["status"] == status and row["can_request"] is can_request
+
+
+def test_the_automation_row_reads_granted_and_denied_per_player(make_env) -> None:
+ env = make_env(installed_players=[_MUSIC, _SPOTIFY], running_players=[_MUSIC, _SPOTIFY])
+ env.tcc.grant("automation", _MUSIC)
+ env.tcc.grant("automation", _SPOTIFY)
+ assert env.rows("?include=automation")["automation"]["status"] == "granted"
+
+ env.tcc.deny("automation", _SPOTIFY) # the strictest player wins
+ get_permission_service().invalidate() # a grant is cached for a second at most
+ row = env.rows("?include=automation")["automation"]
+
+ assert row["status"] == "denied" and row["can_request"] is False and row["can_reset"] is True
+
+
+def test_the_automation_row_never_launches_a_player_or_writes_a_consent_file(
+ make_env, tmp_path: Path
+) -> None:
+ env = make_env(installed_players=[_MUSIC, _SPOTIFY])
+
+ env.rows("?include=automation")
+
+ assert env.tcc.launches == []
+ assert not list(tmp_path.rglob("macos-automation-consent.json"))
+
+
+def _refused_send_env(make_env):
+ """Music and Spotify read granted; a send to Music was refused (-1743), so the service
+ holds one background ``needs_settings`` episode that names Music."""
+ env = make_env(
+ config=_ducking(True),
+ granted=[TccService.AUTOMATION],
+ installed_players=[_MUSIC, _SPOTIFY],
+ running_players=[_MUSIC, _SPOTIFY],
+ )
+ result = get_permission_service().report_failed_use(
+ PermissionId.AUTOMATION, feature="audio_ducking", target=_MUSIC
+ )
+ assert result.reason == "needs_settings"
+ return env
+
+
+def test_a_refused_send_names_the_player_in_the_automation_row_and_in_needed(make_env) -> None:
+ env = _refused_send_env(make_env)
+
+ snapshot = env.status()
+ row = {row["id"]: row for row in snapshot["permissions"]}["automation"]
+
+ # The row keeps the probe's status (no key is added: AP-4), says what happened for the
+ # player that refused, and still offers the pane. It never offers a request.
+ assert row["status"] == "granted" and row["restart_hint"] is False
+ assert row["can_open_settings"] is True and row["can_request"] is False
+ assert "Automation access for Music" in row["detail"]
+ assert "refused an Apple event" in row["detail"]
+ assert "access for Spotify" not in row["detail"] # only the player that refused is named
+ assert "Checked only while Music or Spotify is running." in row["detail"]
+ [episode] = snapshot["needed"]
+ assert (
+ episode["feature"],
+ episode["permissions"],
+ episode["reason"],
+ episode["phase"],
+ episode["origin"],
+ episode["target"],
+ episode["can_prompt"],
+ episode["can_open_settings"],
+ ) == (
+ "audio_ducking",
+ ["automation"],
+ "needs_settings",
+ "blocked",
+ "background",
+ _MUSIC,
+ False,
+ True,
+ )
+ assert "Automation access for Music" in episode["detail"]
+ assert set(episode) == _typed_keys(NeededEpisode)
+
+
+def test_the_single_automation_row_read_says_the_same_and_stays_prompt_free(make_env) -> None:
+ env = _refused_send_env(make_env)
+
+ row = env.row("automation")
+ again = env.row("automation") # a read, however often, never asks
+ status = env.status()
+
+ assert row == again
+ assert row["status"] == "granted" and "refused an Apple event" in row["detail"]
+ assert row["can_open_settings"] is True and row["can_request"] is False
+ assert env.rows()["automation"]["detail"] == row["detail"]
+ assert len(status["needed"]) == 1 # reading never resolved or doubled the episode
+ env.tcc.assert_no_prompts()
+ assert env.tcc.requests() == [] and env.tcc.implicit_prompts() == []
+ assert env.tcc.launches == []
+
+
+def test_a_landed_send_empties_the_row_detail_and_needed_again(make_env) -> None:
+ env = _refused_send_env(make_env)
+ assert env.row("automation")["detail"] != ""
+
+ assert (
+ get_permission_service().report_use_ok(
+ PermissionId.AUTOMATION, feature="audio_ducking", target=_MUSIC
+ )
+ is True
+ )
+
+ row = env.row("automation")
+ assert row["status"] == "granted" and row["detail"] == ""
+ assert env.status()["needed"] == []
+
+
+def test_a_needs_settings_episode_whose_probe_is_not_granted_is_not_called_a_refusal(
+ make_env,
+) -> None:
+ """Outside the installed app the ask is withheld: that is plain needs_settings."""
+ env = make_env(
+ config=_ducking(True),
+ bundle_id=None,
+ bundle_path="/usr/bin/python3",
+ installed_players=[_MUSIC],
+ running_players=[_MUSIC],
+ )
+ result = get_permission_service().ensure(
+ PermissionId.AUTOMATION, feature="audio_ducking", target=_MUSIC
+ )
+ assert result.reason == "needs_settings"
+
+ row = env.row("automation")
+
+ assert row["status"] == "not_determined" and "refused" not in row["detail"]
+ [episode] = env.status()["needed"]
+ assert episode["reason"] == "needs_settings" and episode["origin"] == "user"
+
+
+def test_an_automation_probe_that_hangs_is_bounded_and_not_piled_up(
+ make_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ env = make_env(installed_players=[_MUSIC], running_players=[_MUSIC])
+ release = threading.Event()
+ reached = threading.Event() # set by the stub itself: no assertion races a slow thread start
+ entered: list[int] = []
+
+ def hanging(service: PermissionService):
+ entered.append(1)
+ reached.set()
+ release.wait(10)
+ return routes._worst_automation([])
+
+ monkeypatch.setattr(routes, "_read_automation", hanging)
+ monkeypatch.setattr(routes, "_AUTOMATION_PROBE_TIMEOUT_S", 0.2)
+ try:
+ started = time.monotonic()
+ first = env.rows("?include=automation")["automation"]
+ second = env.rows("?include=automation")["automation"]
+ elapsed = time.monotonic() - started
+
+ assert elapsed < 5.0
+ for row in (first, second):
+ assert row["status"] == "unavailable" and row["can_request"] is False
+ assert row["detail"].startswith("The Automation check did not answer in time.")
+ assert reached.wait(5)
+ assert entered == [1] # one hung thread, never a second
+ finally:
+ release.set()
+ thread = env.app.state.permissions_runtime.automation_probe._thread
+ if thread is not None:
+ thread.join(5)
+
+
+def test_a_hanging_episode_refresh_is_bounded(make_env, monkeypatch: pytest.MonkeyPatch) -> None:
+ env = make_env(default_policy=DialogPolicy.NEVER_ANSWERED)
+ env.post("microphone/request") # an open episode, so the refresh has work to do
+ release = threading.Event()
+ monkeypatch.setattr(PermissionService, "refresh_episodes", lambda self: release.wait(10))
+ monkeypatch.setattr(routes, "_REFRESH_TIMEOUT_S", 0.2)
+ try:
+ started = time.monotonic()
+ snapshot = env.status()
+ elapsed = time.monotonic() - started
+
+ assert elapsed < 5.0
+ assert len(snapshot["needed"]) == 1 # still answered, from the registry
+ finally:
+ release.set()
+ thread = env.app.state.permissions_runtime.refresh._thread
+ if thread is not None:
+ thread.join(5)
+
+
+def test_a_quiet_status_read_does_not_start_a_refresh_thread(make_env) -> None:
+ env = make_env()
+
+ env.status()
+
+ assert env.app.state.permissions_runtime.refresh._thread is None # nothing was open
+
+
+# ----------------------------------------------------------------------
+# The runtime
+# ----------------------------------------------------------------------
+
+
+def test_the_runtime_is_created_once_per_app(make_env) -> None:
+ env = make_env()
+ del env.app.state.permissions_runtime # a production app starts without one
+
+ env.status()
+ first = env.app.state.permissions_runtime
+ env.status()
+
+ assert env.app.state.permissions_runtime is first
diff --git a/tests/unit/ui/web/test_wake_activation_permission.py b/tests/unit/ui/web/test_wake_activation_permission.py
new file mode 100644
index 0000000000..e81cfbdce2
--- /dev/null
+++ b/tests/unit/ui/web/test_wake_activation_permission.py
@@ -0,0 +1,213 @@
+"""POST /api/settings/wake-word/activation: the SWITCH is the gesture that asks.
+
+Switching the always-on wake word ON is the just-in-time moment for the
+microphone. The route asks through the permission service (``wait_s=0``: it
+returns at once, the answer arrives later through ``PermissionResolved``), saves
+and applies the switch either way, and answers with an additive ``permission``
+object ``{outcome, reason, can_open_settings}``. Every existing key is kept.
+Switching OFF asks nothing, and another OS never touches the service.
+
+The macOS cases run the REAL service over ``FakeTCC``, so what the OS was asked is
+checked against its own call log.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+import jarvis.ui.web.settings_routes as settings_routes
+from jarvis.core import config_writer
+from jarvis.core.config import WakeWordConfig
+from jarvis.platform.permission_service import PermissionOutcome, get_permission_service
+from jarvis.ui.web.settings_routes import router
+from tests.fakes.fake_permission_service import FakePermissionService
+from tests.fakes.fake_tcc import (
+ DialogPolicy,
+ FakeTCC,
+ TccService,
+ install_port,
+ make_non_darwin_port,
+)
+
+_LEGACY_KEYS = {"ok", "enabled", "applied_live", "restart_required", "persisted", "message"}
+_PERMISSION_KEYS = {"outcome", "reason", "can_open_settings"}
+
+
+class _Pipeline:
+ def __init__(self) -> None:
+ self.activation: bool | None = None
+
+ def set_wake_activation(self, enabled: bool) -> None:
+ self.activation = enabled
+
+
+def _client(pipeline: object | None = None, **state: object) -> TestClient:
+ app = FastAPI()
+ app.include_router(router)
+ app.state.config = SimpleNamespace(trigger=SimpleNamespace(wake_word=WakeWordConfig()))
+ if pipeline is not None:
+ app.state.speech_pipeline = pipeline
+ for name, value in state.items():
+ setattr(app.state, name, value)
+ return TestClient(app)
+
+
[email protected](autouse=True)
+def _persist_nothing(monkeypatch: pytest.MonkeyPatch) -> list[bool]:
+ saved: list[bool] = []
+ monkeypatch.setattr(config_writer, "set_wake_word_enabled", saved.append)
+ return saved
+
+
+def _on_macos(monkeypatch: pytest.MonkeyPatch, **tcc_kwargs: object) -> FakeTCC:
+ tcc = FakeTCC(**tcc_kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: True)
+ return tcc
+
+
+def test_switching_on_on_a_fresh_mac_asks_once_and_still_saves_the_switch(
+ monkeypatch: pytest.MonkeyPatch, _persist_nothing: list[bool]
+) -> None:
+ tcc = _on_macos(monkeypatch, default_policy=DialogPolicy.NEVER_ANSWERED)
+ pipe = _Pipeline()
+
+ response = _client(pipe).post("/api/settings/wake-word/activation", json={"enabled": True})
+
+ assert response.status_code == 200
+ body = response.json()
+ assert _LEGACY_KEYS <= set(body)
+ assert body["ok"] is True and body["enabled"] is True and body["persisted"] is True
+ assert body["applied_live"] is True
+ # The dialog is up (the route did not wait for the answer): pending, not granted.
+ assert set(body["permission"]) == _PERMISSION_KEYS
+ assert body["permission"]["outcome"] == PermissionOutcome.PENDING.value
+ assert body["permission"]["reason"] == "not_determined"
+ assert pipe.activation is True and _persist_nothing == [True]
+ assert len(tcc.requests(TccService.MICROPHONE)) == 1
+ assert tcc.implicit_prompts() == []
+ (episode,) = get_permission_service().outstanding()
+ assert (episode.feature, episode.origin, episode.permissions) == (
+ "wake_word",
+ "user",
+ ("microphone",),
+ )
+
+
+def test_switching_on_with_the_microphone_already_granted_asks_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _on_macos(monkeypatch, granted=(TccService.MICROPHONE,))
+
+ body = (
+ _client(_Pipeline())
+ .post("/api/settings/wake-word/activation", json={"enabled": True})
+ .json()
+ )
+
+ assert body["permission"] == {"outcome": "granted", "reason": "", "can_open_settings": False}
+ assert tcc.requests() == []
+ assert get_permission_service().outstanding() == []
+
+
+def test_switching_on_with_a_denied_microphone_points_at_settings(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _on_macos(monkeypatch)
+ tcc.deny(TccService.MICROPHONE)
+
+ body = (
+ _client(_Pipeline())
+ .post("/api/settings/wake-word/activation", json={"enabled": True})
+ .json()
+ )
+
+ assert body["permission"]["outcome"] == PermissionOutcome.DENIED.value
+ assert body["permission"]["reason"] == "denied"
+ assert body["permission"]["can_open_settings"] is True
+ assert tcc.requests() == [], "a denial is a stable state: macOS is not asked again"
+
+
+def test_switching_off_asks_nothing_and_says_nothing_is_required(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ tcc = _on_macos(monkeypatch)
+ pipe = _Pipeline()
+
+ body = _client(pipe).post("/api/settings/wake-word/activation", json={"enabled": False}).json()
+
+ assert body["permission"] == {
+ "outcome": "not_required",
+ "reason": "",
+ "can_open_settings": False,
+ }
+ assert pipe.activation is False
+ tcc.assert_silent()
+ assert tcc.calls == ()
+
+
+def test_the_route_asks_through_the_injected_service_with_a_zero_wait(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: True)
+ gate = FakePermissionService()
+ gate.script("microphone", PermissionOutcome.PENDING)
+
+ body = (
+ _client(permission_service=gate)
+ .post("/api/settings/wake-word/activation", json={"enabled": True})
+ .json()
+ )
+
+ (call,) = gate.ensure_calls("microphone")
+ assert (call.method, call.feature, call.interactive, call.wait_s) == (
+ "ensure",
+ "wake_word",
+ True,
+ 0.0,
+ )
+ assert body["permission"]["outcome"] == "pending"
+
+
+def test_a_broken_service_never_fails_the_switch(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: True)
+
+ class _Broken:
+ def ensure(self, *_a: object, **_k: object) -> object:
+ raise RuntimeError("native failure at /secret/path")
+
+ pipe = _Pipeline()
+ response = _client(pipe, permission_service=_Broken()).post(
+ "/api/settings/wake-word/activation", json={"enabled": True}
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["ok"] is True and body["applied_live"] is True
+ assert body["permission"]["outcome"] == "unavailable"
+ assert "secret" not in response.text
+ assert pipe.activation is True
+
+
[email protected]("enabled", [True, False])
+def test_other_platforms_never_touch_the_permission_layer(
+ monkeypatch: pytest.MonkeyPatch, enabled: bool
+) -> None:
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: False)
+ gate = FakePermissionService()
+
+ body = (
+ _client(_Pipeline(), permission_service=gate)
+ .post("/api/settings/wake-word/activation", json={"enabled": enabled})
+ .json()
+ )
+
+ assert body["permission"]["outcome"] == "not_required"
+ assert gate.calls == []
+ tcc.assert_silent()
diff --git a/tests/unit/vision/test_ax_tree.py b/tests/unit/vision/test_ax_tree.py
index b0ae76199d..f32530bace 100644
--- a/tests/unit/vision/test_ax_tree.py
+++ b/tests/unit/vision/test_ax_tree.py
@@ -145,34 +145,70 @@ def test_real_pyobjc_axvalue_round_trip_without_tcc() -> None:
assert _ax_size(size) == (800, 600)
-def test_ax_permission_uses_unified_runtime_identity_gate(monkeypatch) -> None:
- from jarvis.platform.permissions import PermissionId
-
- seen = []
- port = types.SimpleNamespace(
- runtime_access_granted=lambda permission: seen.append(permission) or False,
- )
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: port,
+def _macos_accessibility(monkeypatch, *, granted: bool):
+ """A darwin FakeTCC behind the REAL port; the process-wide service reads it.
+
+ The Accessibility dialog (if anything asks) stays on screen unanswered, so an
+ unexpected prompt shows up as a ``request`` in the call log. Nothing here ran
+ on a real Mac; FakeTCC models the OS.
+ """
+ from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, install_port
+
+ tcc = FakeTCC(
+ granted=("accessibility",) if granted else (),
+ default_policy=DialogPolicy.NEVER_ANSWERED,
)
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
+
+
+def test_ax_read_is_a_silent_check_of_the_live_accessibility_grant(monkeypatch) -> None:
+ tcc = _macos_accessibility(monkeypatch, granted=False)
assert AXTreeSource._ax_is_process_trusted() is False
- assert seen == [PermissionId.ACCESSIBILITY]
+ # A background read degrades; it never asks macOS and never opens a card.
+ assert tcc.requests() == []
+ assert tcc.implicit_prompts() == []
-def test_ax_permission_reprobes_live_revocation(monkeypatch) -> None:
- outcomes = iter((True, False))
- port = types.SimpleNamespace(
- runtime_access_granted=lambda _permission: next(outcomes),
- )
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: port,
- )
+def test_ax_read_reprobes_live_revocation(monkeypatch) -> None:
+ from jarvis.platform.permission_service import get_permission_service
+
+ tcc = _macos_accessibility(monkeypatch, granted=True)
assert AXTreeSource._ax_is_process_trusted() is True
+
+ tcc.deny("accessibility")
+ get_permission_service().invalidate() # a grant is cached for about a second
+
assert AXTreeSource._ax_is_process_trusted() is False
+ assert tcc.requests() == []
+
+
+def test_ax_read_off_macos_is_not_gated(monkeypatch) -> None:
+ from tests.fakes.fake_tcc import FakeTCC, install_port
+
+ tcc = FakeTCC()
+ install_port(monkeypatch, tcc.port("linux"))
+
+ assert AXTreeSource._ax_is_process_trusted() is True
+ tcc.assert_silent()
+
+
+async def test_observe_without_the_grant_degrades_and_never_prompts(monkeypatch) -> None:
+ tcc = _macos_accessibility(monkeypatch, granted=False)
+ consulted = {"called": False}
+
+ def _traverser(_depth, _filter):
+ consulted["called"] = True
+ return ("should-not-appear", 0, [])
+
+ obs = await AXTreeSource(traverser=_traverser).observe()
+
+ assert obs.nodes == () and obs.source == "screenshot_only"
+ assert consulted["called"] is False
+ assert tcc.requests() == []
def test_secure_ax_field_redacts_value_and_preserves_focus() -> None:
diff --git a/tests/unit/vision/test_element_at_point.py b/tests/unit/vision/test_element_at_point.py
index 9ec19eae83..ecd1563da6 100644
--- a/tests/unit/vision/test_element_at_point.py
+++ b/tests/unit/vision/test_element_at_point.py
@@ -22,6 +22,23 @@ from tests.fakes.fake_capabilities import (
fake_windows_capabilities,
)
+
+def _macos_accessibility(monkeypatch, *, granted: bool):
+ """A darwin FakeTCC behind the REAL port; the process-wide service reads it.
+
+ An unanswered dialog makes any unexpected prompt visible as a ``request`` in the
+ call log. Nothing here ran on a real Mac; FakeTCC models the OS.
+ """
+ from tests.fakes.fake_tcc import DialogPolicy, FakeTCC, install_port
+
+ tcc = FakeTCC(
+ granted=("accessibility",) if granted else (),
+ default_policy=DialogPolicy.NEVER_ANSWERED,
+ )
+ install_port(monkeypatch, tcc.port("darwin"))
+ return tcc
+
+
_OS_RESOLVERS = (
eap.WindowsPointerResolver,
eap.AXPointerResolver,
@@ -42,14 +59,7 @@ def test_resolver_returns_injected_element() -> None:
@pytest.mark.parametrize("cls", _OS_RESOLVERS)
def test_resolver_swallows_query_errors(cls, monkeypatch) -> None:
if cls is eap.AXPointerResolver:
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: type(
- "GrantedPermissionPort",
- (),
- {"runtime_access_granted": lambda self, permission: True},
- )(),
- )
+ _macos_accessibility(monkeypatch, granted=True)
def boom(x: int, y: int) -> PointerElement:
raise RuntimeError("native query failed")
@@ -60,14 +70,7 @@ def test_resolver_swallows_query_errors(cls, monkeypatch) -> None:
@pytest.mark.parametrize("cls", _OS_RESOLVERS)
def test_resolver_passes_coords_to_query(cls, monkeypatch) -> None:
if cls is eap.AXPointerResolver:
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: type(
- "GrantedPermissionPort",
- (),
- {"runtime_access_granted": lambda self, permission: True},
- )(),
- )
+ _macos_accessibility(monkeypatch, granted=True)
seen: dict[str, tuple[int, int]] = {}
@@ -79,50 +82,40 @@ def test_resolver_passes_coords_to_query(cls, monkeypatch) -> None:
assert seen["xy"] == (42, 99)
- "blocked_reason",
- ("unstable_identity", "pending_restart", "revoked_grant"),
-)
-def test_macos_resolver_fails_closed_when_runtime_access_is_blocked(
- monkeypatch,
- blocked_reason: str,
-) -> None:
+def test_macos_resolver_fails_closed_without_the_grant_and_never_prompts(monkeypatch) -> None:
calls: list[tuple[int, int]] = []
- port = type(
- "BlockedPermissionPort",
- (),
- {"runtime_access_granted": lambda self, permission: False},
- )()
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: port,
- )
+ tcc = _macos_accessibility(monkeypatch, granted=False)
resolver = eap.AXPointerResolver(query=lambda x, y: calls.append((x, y)))
- assert resolver.at(42, 99) is None, blocked_reason
+ assert resolver.at(42, 99) is None
assert calls == []
+ # An element-at-point read is background work: a silent check, never a request.
+ assert tcc.requests() == []
+ assert tcc.implicit_prompts() == []
-def test_macos_resolver_queries_when_runtime_access_is_granted(monkeypatch) -> None:
+def test_macos_resolver_fails_closed_after_a_live_revocation(monkeypatch) -> None:
+ from jarvis.platform.permission_service import get_permission_service
+
sentinel = PointerElement(name="Allowed", role="Button", bounds=(1, 2, 3, 4))
- seen: list[object] = []
- port = type(
- "GrantedPermissionPort",
- (),
- {
- "runtime_access_granted": (
- lambda self, permission: seen.append(permission) or True
- ),
- },
- )()
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: port,
- )
+ tcc = _macos_accessibility(monkeypatch, granted=True)
+ resolver = eap.AXPointerResolver(query=lambda x, y: sentinel)
+ assert resolver.at(4, 5) is sentinel
+
+ tcc.deny("accessibility")
+ get_permission_service().invalidate() # a grant is cached for about a second
+
+ assert resolver.at(4, 5) is None
+ assert tcc.requests() == []
+
+
+def test_macos_resolver_queries_when_accessibility_is_granted(monkeypatch) -> None:
+ sentinel = PointerElement(name="Allowed", role="Button", bounds=(1, 2, 3, 4))
+ tcc = _macos_accessibility(monkeypatch, granted=True)
assert eap.AXPointerResolver(query=lambda x, y: sentinel).at(4, 5) is sentinel
- assert [permission.value for permission in seen] == ["accessibility"]
+ assert tcc.requests() == []
def test_factory_windows(monkeypatch) -> None:
diff --git a/tests/unit/vision/test_screen_recording_warning.py b/tests/unit/vision/test_screen_recording_warning.py
index 15fc704833..e1517fc915 100644
--- a/tests/unit/vision/test_screen_recording_warning.py
+++ b/tests/unit/vision/test_screen_recording_warning.py
@@ -1,92 +1,223 @@
-"""H1: a denied macOS Screen-Recording grant must surface a clear English
-onboarding message at the screenshot capture point, instead of silently
-capturing the desktop wallpaper (which would make Computer-Use click blind).
-
-These force the grant state via the permission-port seam — no real macOS
-needed. Seam-level only: this proves uncached fail-closed behavior, not the
-native CGPreflightScreenCaptureAccess implementation.
+"""H1: a missing macOS Screen-Recording grant must surface a clear, honest message at
+the screenshot capture point, instead of silently capturing the desktop wallpaper
+(which would make Computer-Use click blind) - and the helpers that do so must never
+ASK macOS: only a gesture entry point does (docs/macos-permissions.md, 4.6).
+
+The REAL permission service runs on a REAL ``SystemPermissionPort`` that sits on
+``FakeTCC`` (a stateful model of macOS privacy); its call log proves nothing was
+requested. Nothing here ran on a real Mac: see the fidelity ledger in
+``tests/fakes/fake_tcc.py``.
"""
from __future__ import annotations
import logging
+import sys
+import types
+
+import pytest
+from jarvis.platform import screen_access
+from jarvis.platform.permission_service import get_permission_service
+from jarvis.platform.permissions import PermissionId, PermissionState
+from jarvis.platform.screen_access import ScreenCaptureRefused
from jarvis.vision import screenshot
+from tests.fakes.fake_screen_pixels import textured_pixels, wallpaper_pixels
+from tests.fakes.fake_tcc import FakeTCC, TccService, install_port, make_non_darwin_port
_MSG = "Screen Recording permission not granted"
-def _permission_port(monkeypatch, states):
- remaining = list(states)
-
- class _Port:
- current = None
-
- def state(self, _permission_id):
- return self.current
-
- def runtime_access_granted(self, _permission_id):
- from jarvis.platform.permissions import PermissionState
-
- self.current = remaining.pop(0)
- return self.current in {
- PermissionState.GRANTED,
- PermissionState.NOT_REQUIRED,
- }
-
- port = _Port()
- monkeypatch.setattr(
- "jarvis.platform.permissions.get_system_permission_port",
- lambda: port,
- )
- return remaining
+def _darwin(monkeypatch, **kwargs) -> FakeTCC:
+ tcc = FakeTCC(**kwargs)
+ install_port(monkeypatch, tcc.port("darwin"))
+ monkeypatch.setattr(screenshot, "_screen_recording_warned", False)
+ return tcc
-def test_warns_once_when_screen_recording_denied(monkeypatch, caplog):
- from jarvis.platform.permissions import PermissionState
+def test_warns_once_when_screen_recording_is_not_granted(monkeypatch, caplog):
+ tcc = _darwin(monkeypatch)
- monkeypatch.setattr(screenshot, "_screen_recording_warned", False)
- remaining = _permission_port(
- monkeypatch,
- [PermissionState.NOT_GRANTED, PermissionState.NOT_GRANTED],
- )
with caplog.at_level(logging.WARNING):
assert screenshot.warn_if_screen_recording_denied() is True
assert screenshot.warn_if_screen_recording_denied() is True
+
assert caplog.text.count(_MSG) == 1
- assert remaining == [], "the native state must be probed on both calls"
+ assert "Settings > Permissions" not in caplog.text
+ assert "Screen & System Audio Recording" in caplog.text
+ # It only READS the state: nothing was asked, nothing prompted behind our back.
+ tcc.assert_no_prompts()
def test_no_warning_when_granted(monkeypatch, caplog):
- from jarvis.platform.permissions import PermissionState
+ _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING])
- monkeypatch.setattr(screenshot, "_screen_recording_warned", False)
- _permission_port(monkeypatch, [PermissionState.GRANTED])
with caplog.at_level(logging.WARNING):
assert screenshot.warn_if_screen_recording_denied() is False
+
assert _MSG not in caplog.text
def test_unavailable_native_probe_fails_closed(monkeypatch, caplog):
- from jarvis.platform.permissions import PermissionState
+ _darwin(monkeypatch, missing_frameworks=["Quartz"])
- monkeypatch.setattr(screenshot, "_screen_recording_warned", False)
- _permission_port(monkeypatch, [PermissionState.UNAVAILABLE])
with caplog.at_level(logging.WARNING):
assert screenshot.warn_if_screen_recording_denied() is True
+
assert _MSG in caplog.text
def test_permission_recovery_is_observed_without_restart(monkeypatch, caplog):
- from jarvis.platform.permissions import PermissionState
-
- monkeypatch.setattr(screenshot, "_screen_recording_warned", False)
- _permission_port(
- monkeypatch,
- [PermissionState.NOT_GRANTED, PermissionState.GRANTED],
- )
+ tcc = _darwin(monkeypatch)
with caplog.at_level(logging.INFO):
assert screenshot.warn_if_screen_recording_denied() is True
+ # The user flips the switch in System Settings while Jarvis runs: the
+ # frozen preflight stays negative, the window-title oracle sees the grant.
+ tcc.grant(TccService.SCREEN_RECORDING)
assert screenshot.warn_if_screen_recording_denied() is False
assert "available again" in caplog.text
+ tcc.assert_no_prompts()
+
+
+def test_non_darwin_reads_nothing_and_never_warns(monkeypatch, caplog):
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ monkeypatch.setattr(screenshot, "_screen_recording_warned", False)
+
+ with caplog.at_level(logging.WARNING):
+ assert screenshot.warn_if_screen_recording_denied() is False
+
+ assert _MSG not in caplog.text
+ tcc.assert_silent()
+
+
+# ---------------------------------------------------------------------------
+# Helpers refuse honestly and never ask
+# ---------------------------------------------------------------------------
+
+
+def test_capture_region_refuses_with_the_permission_named_and_asks_nothing(monkeypatch):
+ pytest.importorskip("PIL")
+ tcc = _darwin(monkeypatch)
+ grabbed = []
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ screenshot.capture_region(
+ {"left": 0, "top": 0, "width": 4, "height": 4},
+ grab=lambda bbox: grabbed.append(bbox),
+ )
+
+ assert grabbed == []
+ assert str(refused.value).startswith("[permission_needed:screen_recording] ")
+ # A RuntimeError subclass: every existing ``except RuntimeError`` keeps working.
+ assert isinstance(refused.value, RuntimeError)
+ tcc.assert_no_prompts()
+
+
+def test_capture_region_grabs_once_the_grant_is_live(monkeypatch):
+ pytest.importorskip("PIL")
+ _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING])
+
+ data = screenshot.capture_region(
+ {"left": 0, "top": 0, "width": 4, "height": 4},
+ grab=lambda _bbox: textured_pixels((4, 4)),
+ )
+
+ assert data[:2] == b"\xff\xd8"
+
+
+class _FakeSct:
+ """mss.mss() stand-in whose grab returns a fixed frame."""
+
+ frame: tuple[tuple[int, int], bytes] = ((8, 8), b"")
+
+ monitors = [
+ {"left": 0, "top": 0, "width": 8, "height": 8},
+ {"left": 0, "top": 0, "width": 8, "height": 8},
+ ]
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ return False
+
+ def grab(self, _monitor):
+ size, rgb = type(self).frame
+ return types.SimpleNamespace(size=size, rgb=rgb)
+
+
+def _fake_mss(monkeypatch, frame) -> None:
+ sct = type("Sct", (_FakeSct,), {"frame": frame})
+ fake = types.ModuleType("mss")
+ fake.mss = sct # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "mss", fake)
+
+
+def test_vision_source_refuses_without_the_grant_and_never_asks(monkeypatch):
+ pytest.importorskip("PIL")
+ tcc = _darwin(monkeypatch)
+ _fake_mss(monkeypatch, textured_pixels((8, 8)))
+ source = screenshot.ScreenshotSource(save_blob=False, monitor_strategy="primary")
+
+ with pytest.raises(ScreenCaptureRefused) as refused:
+ source._capture_image()
+
+ assert refused.value.reason == "needs_settings"
+ tcc.assert_no_prompts()
+
+
+def test_vision_source_wallpaper_frame_is_no_success_and_stays_background(monkeypatch):
+ # The grant reads as granted (cached), then is revoked: the frame is the
+ # wallpaper. The vision source is a background observer, so the episode it
+ # opens has the background origin (status snapshot only, no toast) and no request.
+ pytest.importorskip("PIL")
+ tcc = _darwin(monkeypatch, granted=[TccService.SCREEN_RECORDING], preflight_frozen=())
+ _fake_mss(monkeypatch, wallpaper_pixels((8, 8)))
+ source = screenshot.ScreenshotSource(save_blob=False, monitor_strategy="primary")
+ service = get_permission_service()
+ assert service.check(PermissionId.SCREEN_RECORDING) is PermissionState.GRANTED
+ tcc.deny(TccService.SCREEN_RECORDING)
+
+ # The helper's own state read sees the revocation first (cache bypassed by the
+ # deep fallback), so it refuses before grabbing; either way no wallpaper escapes.
+ with pytest.raises(ScreenCaptureRefused):
+ source._capture_image()
+
+ assert tcc.dialogs_shown() == []
+ assert tcc.requests() == []
+ assert all(episode.origin != "user" for episode in service.outstanding())
+
+
+def test_vision_source_non_darwin_is_unchanged(monkeypatch):
+ pytest.importorskip("PIL")
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ _fake_mss(monkeypatch, wallpaper_pixels((8, 8)))
+ source = screenshot.ScreenshotSource(save_blob=False, monitor_strategy="primary")
+
+ captured = source._capture_image()
+
+ assert captured is not None
+ tcc.assert_silent()
+
+
+def test_screen_access_imports_no_native_framework_at_module_scope():
+ # AP-26: importing the module must not load Quartz/AppKit/pyobjc; the one
+ # function that needs Quartz imports it lazily.
+ import ast
+ import inspect
+
+ tree = ast.parse(inspect.getsource(screen_access))
+ top_level = {
+ alias.name.split(".")[0]
+ for node in tree.body
+ if isinstance(node, ast.Import)
+ for alias in node.names
+ } | {
+ (node.module or "").split(".")[0]
+ for node in tree.body
+ if isinstance(node, ast.ImportFrom)
+ }
+ assert not top_level & {"Quartz", "AppKit", "objc", "Foundation", "AVFoundation"}
diff --git a/tests/unit/voice/test_action_phrases.py b/tests/unit/voice/test_action_phrases.py
index ba32d7c381..20afdff954 100644
--- a/tests/unit/voice/test_action_phrases.py
+++ b/tests/unit/voice/test_action_phrases.py
@@ -3,8 +3,11 @@ from __future__ import annotations
import re
+import pytest
+
from jarvis.voice.action_phrases import (
action_phrase,
+ cu_blocked_permission_sentence,
cu_failure_readback,
resolve_phrase_language,
)
@@ -326,6 +329,182 @@ class TestElevationPausePhrases:
assert needs_elev != gave_up
+class TestBlockedPermissionReadback:
+ """A mission stopped by a macOS permission says what is missing and where to allow it.
+
+ The engine writes ``[cu] blocked_permission at step-N: <sentence>`` and ALWAYS
+ appends a ``[cu] mission profile`` line after it. The profile line used to trip
+ the diagnostic gate, so the readback degraded to the generic "an action failed".
+ """
+
+ _SENTENCE = (
+ "Accessibility is off for Personal Jarvis. The user has to turn it on in "
+ "System Settings > Privacy & Security > Accessibility. Then try the task again."
+ )
+ _PROFILE = "[cu] mission profile: steps=3 total=9.5s act=3.0s observe=0.3s plan=1.6s\n"
+
+ def _detail(self, sentence: str | None = None) -> str:
+ return (
+ f"[cu] blocked_permission at step-3: {sentence or self._SENTENCE}\n"
+ + self._PROFILE
+ )
+
+ def test_profile_line_does_not_degrade_to_the_generic_phrase(self) -> None:
+ for lang in ("de", "en", "es"):
+ out = cu_failure_readback(
+ lang, error=None, exit_code=8, detail=self._detail()
+ )
+ assert out != action_phrase("cu_exit_action_failed", lang), out
+ assert out != action_phrase("cu_failed", lang), out
+
+ def test_english_forwards_the_engine_sentence_without_telemetry(self) -> None:
+ out = cu_failure_readback("en", error=None, exit_code=8, detail=self._detail())
+ assert "Accessibility is off for Personal Jarvis." in out
+ assert "Then try the task again." in out
+ assert "mission profile" not in out
+ assert "[cu]" not in out
+ assert not _EXIT_TOKEN_RE.search(out), out
+
+ def test_german_and_spanish_name_the_permission_and_where_to_allow_it(self) -> None:
+ de = cu_failure_readback("de", error=None, exit_code=8, detail=self._detail())
+ es = cu_failure_readback("es", error=None, exit_code=8, detail=self._detail())
+ assert "Bedienungshilfen" in de # i18n-allow: asserts the German phrase
+ assert "Accesibilidad" in es
+ assert "Datenschutz" in de # i18n-allow: the Settings path is spoken, not just the name
+ assert "Privacidad" in es
+ for out in (de, es):
+ assert ">" not in out and "&" not in out # separators become words
+ assert "[cu]" not in out
+ assert "steps=" not in out
+
+ def test_english_is_addressed_to_the_listener_and_the_path_is_speakable(self) -> None:
+ out = cu_failure_readback("en", error=None, exit_code=8, detail=self._detail())
+ assert "You have to turn it on" in out
+ assert "the user" not in out.lower()
+ assert ">" not in out and "&" not in out
+ assert "System Settings, then Privacy and Security, then Accessibility" in out
+
+ def test_screen_recording_is_named_by_keyword(self) -> None:
+ sentence = (
+ "Screen Recording access is off for Personal Jarvis. The user has to turn it "
+ "on in System Settings > Privacy & Security > Screen & System Audio Recording."
+ )
+ de = cu_failure_readback(
+ "de", error=None, exit_code=8, detail=self._detail(sentence)
+ )
+ assert "Bildschirm" in de # i18n-allow: asserts the German phrase
+
+ def test_system_dialog_asks_the_person_to_answer_it(self) -> None:
+ sentence = (
+ "A macOS system dialog is open. Personal Jarvis never answers system dialogs "
+ "for you: answer it yourself, then try the task again."
+ )
+ en = cu_failure_readback("en", error=None, exit_code=8, detail=self._detail(sentence))
+ de = cu_failure_readback("de", error=None, exit_code=8, detail=self._detail(sentence))
+ assert "system dialog" in en
+ assert de == action_phrase("cu_blocked_dialog", "de")
+
+ def test_restricted_permission_is_explained_not_asked_for(self) -> None:
+ sentence = (
+ "Accessibility access is restricted on this Mac by a profile or a parental "
+ "control, so Personal Jarvis cannot use it. This cannot be changed from the app."
+ )
+ de = cu_failure_readback("de", error=None, exit_code=8, detail=self._detail(sentence))
+ assert de == action_phrase("cu_blocked_restricted", "de")
+
+ def test_unrecognised_sentence_falls_back_to_the_fixed_phrase_in_de_and_es(self) -> None:
+ sentence = "A macOS permission is needed to continue, so the task stopped."
+ for lang in ("de", "es"):
+ out = cu_failure_readback(
+ lang, error=None, exit_code=8, detail=self._detail(sentence)
+ )
+ assert out == action_phrase("cu_blocked_generic", lang)
+
+ def test_noisy_sentence_is_dropped_for_the_fixed_phrase(self) -> None:
+ # A sentence that smells like telemetry or a path is never spoken verbatim.
+ noisy = "steps=3 total=9.5s act=3.0s C:\\Users\\x\\frame.png"
+ assert cu_blocked_permission_sentence(self._detail(noisy)) == ""
+ out = cu_failure_readback("en", error=None, exit_code=8, detail=self._detail(noisy))
+ assert out == action_phrase("cu_blocked_generic", "en")
+ assert "frame.png" not in out
+
+ def test_token_is_only_honoured_on_the_tool_failure_exit_code(self) -> None:
+ out = cu_failure_readback("en", error=None, exit_code=5, detail=self._detail())
+ assert self._SENTENCE not in out
+
+ def test_blocked_line_may_sit_anywhere_in_stderr(self) -> None:
+ detail = "[cu] cannot see the screen: boom\n" + self._detail()
+ assert cu_blocked_permission_sentence(detail) == self._SENTENCE
+
+ def test_other_failures_are_not_mistaken_for_a_block(self) -> None:
+ other = "[cu] fail at step-2: no news\n" + self._PROFILE
+ assert cu_blocked_permission_sentence(other) is None
+ assert cu_blocked_permission_sentence(None) is None
+ out = cu_failure_readback("en", error=None, exit_code=8, detail=self._PROFILE)
+ assert out == action_phrase("cu_exit_action_failed", "en")
+
+ @pytest.mark.parametrize("lang", ["de", "es"])
+ @pytest.mark.parametrize(
+ "permission",
+ ["screen_recording", "accessibility", "input_monitoring", "microphone", "automation"],
+ )
+ @pytest.mark.parametrize(
+ "reason, asking, phrase",
+ [
+ ("restart_hint", False, "cu_blocked_restart_hint"),
+ ("unavailable", False, "cu_blocked_unavailable"),
+ ("not_determined", True, "cu_blocked_waiting"),
+ ("needs_settings", True, "cu_blocked_waiting"),
+ ],
+ )
+ def test_the_remedy_follows_the_reason_not_only_the_permission(
+ self, lang: str, permission: str, reason: str, asking: bool, phrase: str
+ ) -> None:
+ # The engine's own sentence, built from the service's fixed templates, so a
+ # reworded template breaks this test instead of silently degrading the voice.
+ from jarvis.platform.permission_service import user_detail_for
+ from jarvis.platform.permissions import PermissionId
+
+ sentence = user_detail_for(PermissionId(permission), reason, asking=asking)
+ out = cu_failure_readback(lang, error=None, exit_code=8, detail=self._detail(sentence))
+ assert out.startswith(action_phrase(phrase, lang, permission="@@").split("@@")[0]), out
+ # Never the "allow it in Settings" advice for a grant that is on / a dialog
+ # that is open / a permission that cannot be asked for.
+ assert out != action_phrase("cu_blocked_generic", lang)
+ assert "Settings" not in out and "Ajustes" not in out and "Systemeinstellungen" not in out
+
+ @pytest.mark.parametrize("lang", ["de", "es"])
+ def test_a_switch_that_is_off_still_says_where_to_allow_it(self, lang: str) -> None:
+ from jarvis.platform.permission_service import user_detail_for
+ from jarvis.platform.permissions import PermissionId
+
+ sentence = user_detail_for(PermissionId.MICROPHONE, "denied")
+ out = cu_failure_readback(lang, error=None, exit_code=8, detail=self._detail(sentence))
+ assert out.startswith(
+ action_phrase("cu_blocked_permission", lang, permission="@@", pane="##").split("@@")[0]
+ ), out
+ assert "Mikrofon" in out or "Micrófono" in out # i18n-allow: asserts the phrase
+
+ def test_every_blocked_phrase_exists_in_all_languages(self) -> None:
+ for key in (
+ "cu_blocked_permission",
+ "cu_blocked_dialog",
+ "cu_blocked_restricted",
+ "cu_blocked_generic",
+ "cu_blocked_restart_hint",
+ "cu_blocked_unavailable",
+ "cu_blocked_waiting",
+ ):
+ texts = {
+ lang: action_phrase(
+ key, lang, sentence="S.", permission="P", pane="Pane"
+ )
+ for lang in ("de", "en", "es")
+ }
+ assert len(set(texts.values())) == 3, key
+ assert all(len(text) > 10 for text in texts.values()), key
+
+
class TestCuSuccessReadback:
"""The SUCCESS sibling of cu_failure_readback (live bug 2026-06-18, session
241a1984): "open the browser and check which tabs I have open" was answered
diff --git a/tests/unit/voice/test_action_phrases_permission_cause.py b/tests/unit/voice/test_action_phrases_permission_cause.py
new file mode 100644
index 0000000000..5b4ec964e2
--- /dev/null
+++ b/tests/unit/voice/test_action_phrases_permission_cause.py
@@ -0,0 +1,125 @@
+"""The agent text of a permission refusal never reaches a person's readback."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.brain.manager import BrainManager
+from jarvis.platform.permission_service import agent_detail_for
+from jarvis.platform.permissions import PermissionId
+from jarvis.realtime.session import _speakable_failure_reason
+from jarvis.voice.action_phrases import (
+ action_phrase,
+ cu_failure_readback,
+ extract_speakable_reason,
+ localize_failure_reason,
+)
+
+_AGENT_MARKERS = ("[permission_needed", "You must not", "must not retry", "the user")
+_PERMISSIONS = (
+ ("screen_recording", "needs_settings"),
+ ("accessibility", "denied"),
+ ("microphone", "not_determined"),
+ ("input_monitoring", "needs_settings"),
+)
+
+
+def _agent_text(permission: str, reason: str) -> str:
+ return agent_detail_for(PermissionId(permission), reason)
+
+
+def _assert_clean(text: str) -> None:
+ for marker in _AGENT_MARKERS:
+ assert marker not in text, text
+
+
[email protected](("permission", "reason"), _PERMISSIONS)
+def test_extract_speakable_reason_replaces_the_agent_text_by_one_cause(permission, reason) -> None:
+ cause = extract_speakable_reason(_agent_text(permission, reason))
+
+ assert cause is not None
+ _assert_clean(cause)
+ assert cause.count(".") == 1 # one short sentence, not the prohibitive paragraph
+
+
+def test_a_wrapped_agent_refusal_is_replaced_too() -> None:
+ wrapped = "could not select existing text: " + _agent_text("accessibility", "denied")
+
+ cause = extract_speakable_reason(wrapped)
+
+ assert cause is not None and "Accessibility" in cause
+ _assert_clean(cause)
+
+
+def test_a_harness_output_dict_is_replaced_too() -> None:
+ output = {"exit_code": 1, "stderr": _agent_text("screen_recording", "needs_settings")}
+
+ cause = extract_speakable_reason("exit 1", output)
+
+ assert cause is not None and "Screen Recording" in cause
+ _assert_clean(cause)
+
+
[email protected]("lang", ["de", "en", "es"])
[email protected](("permission", "reason"), _PERMISSIONS)
+def test_the_canned_floor_speaks_the_cause_in_the_turn_language(lang, permission, reason) -> None:
+ cause = extract_speakable_reason(_agent_text(permission, reason))
+
+ line = action_phrase("action_failed_reason", lang, reason=localize_failure_reason(cause, lang))
+
+ _assert_clean(line)
+ if lang != "en":
+ assert "Personal Jarvis does not have" not in line # not left in English
+
+
[email protected]("lang", ["de", "en", "es"])
+def test_the_computer_use_readback_never_speaks_the_agent_text(lang) -> None:
+ line = cu_failure_readback(lang, error=_agent_text("screen_recording", "denied"), exit_code=1)
+
+ _assert_clean(line)
+
+
+def test_an_unknown_permission_token_still_degrades_to_a_fixed_sentence() -> None:
+ cause = extract_speakable_reason("[permission_needed:something_new] This action cannot run.")
+
+ assert cause == "A macOS permission is missing right now."
+
+
+def test_a_system_dialog_refusal_has_its_own_cause() -> None:
+ cause = extract_speakable_reason("[permission_needed:system_dialog] You must not answer it.")
+
+ assert cause is not None and "system dialog" in cause
+ assert "Systemdialog" in localize_failure_reason(cause, "de")
+
+
+def test_the_realtime_failure_line_gets_the_cause_not_the_agent_text() -> None:
+ result = {"success": False, "error": _agent_text("screen_recording", "needs_settings")}
+
+ reason = _speakable_failure_reason(result)
+
+ assert "Screen Recording" in reason
+ _assert_clean(reason)
+
+
[email protected]("lang", ["de", "en", "es"])
+async def test_the_brain_failure_readback_never_speaks_the_agent_text(lang) -> None:
+ mgr = BrainManager.__new__(BrainManager)
+ mgr._reply_language = lang
+ result = SimpleNamespace(
+ success=False, output=None, error=_agent_text("screen_recording", "needs_settings")
+ )
+
+ reply = await mgr._honest_failure_readback(
+ result,
+ user_text="take a screenshot",
+ situation="The action could not be completed.",
+ generic_key="action_failed_generic",
+ reason_key="action_failed_reason",
+ lang=lang,
+ )
+
+ assert reply.strip()
+ _assert_clean(reply)
diff --git a/tests/unit/web/test_mic_level_route.py b/tests/unit/web/test_mic_level_route.py
index 3c9f8c4986..c862f7a85b 100644
--- a/tests/unit/web/test_mic_level_route.py
+++ b/tests/unit/web/test_mic_level_route.py
@@ -7,15 +7,10 @@ import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
+from jarvis.platform.permission_service import PermissionOutcome
+from jarvis.platform.permissions import PermissionId
from jarvis.ui.web.settings_routes import router
-
-
-class _PermissionPort:
- def __init__(self, allowed: bool) -> None:
- self.allowed = allowed
-
- def runtime_access_granted(self, _permission_id) -> bool:
- return self.allowed
+from tests.fakes.fake_permission_service import FakePermissionService
@pytest.fixture(autouse=True)
@@ -23,7 +18,7 @@ def _default_to_permissionless_test_platform(monkeypatch):
"""Keep generic route tests independent of this Mac's TCC state."""
import jarvis.ui.web.settings_routes as settings_routes
- monkeypatch.setattr(settings_routes.sys, "platform", "linux")
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: False)
@pytest.fixture
@@ -105,10 +100,33 @@ def test_mic_level_never_500s_on_helper_error(monkeypatch):
assert b["too_quiet"] is False
-def test_macos_permission_block_never_opens_microphone(monkeypatch):
- import jarvis.speech.diagnose as d
+def _macos_app(monkeypatch, outcome: PermissionOutcome) -> tuple[FastAPI, FakePermissionService]:
import jarvis.ui.web.settings_routes as settings_routes
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: True)
+ gate = FakePermissionService()
+ gate.script(PermissionId.MICROPHONE, outcome)
+ app = FastAPI()
+ app.state.permission_service = gate
+ app.state.config = SimpleNamespace(
+ trigger=SimpleNamespace(
+ wake_word=SimpleNamespace(
+ phrase="Hey Nova",
+ engine="auto",
+ custom_model_path="",
+ fuzzy_match_ratio=0.8,
+ )
+ ),
+ stt=SimpleNamespace(language="en"),
+ ui=SimpleNamespace(language="en"),
+ )
+ app.include_router(router)
+ return app, gate
+
+
+def test_macos_mic_level_never_opens_the_microphone_without_a_grant(monkeypatch):
+ import jarvis.speech.diagnose as d
+
calls = 0
async def forbidden_measure(duration_s=3.0):
@@ -116,27 +134,80 @@ def test_macos_permission_block_never_opens_microphone(monkeypatch):
calls += 1
return -15.0
- monkeypatch.setattr(settings_routes.sys, "platform", "darwin")
monkeypatch.setattr(d, "measure_mic_dbfs", forbidden_measure)
- app = FastAPI()
- app.state.system_permission_port = _PermissionPort(False)
- app.include_router(router)
+ app, gate = _macos_app(monkeypatch, PermissionOutcome.DENIED)
response = TestClient(app).get("/api/settings/wake-word/mic-level")
assert response.status_code == 200
- assert response.json() == {
- "max_dbfs": -120.0,
+ body = response.json()
+ assert body["permission_required"] is True
+ assert body["permission"] == "microphone"
+ assert body["can_open_settings"] is True
+ assert body["max_dbfs"] == -120.0
+ assert body["no_device"] is False and body["too_quiet"] is False
+ assert "System Settings > Privacy & Security > Microphone" in body["hint"]
+ assert "Settings > Permissions" not in body["message"] + body["hint"]
+ assert calls == 0
+ # A GET reads the state silently: it never asks.
+ assert gate.ensure_calls() == []
+
+
+def test_macos_mic_level_on_an_undecided_mac_reports_permission_required_without_asking(
+ monkeypatch,
+):
+ app, gate = _macos_app(monkeypatch, PermissionOutcome.PENDING)
+
+ body = TestClient(app).get("/api/settings/wake-word/mic-level").json()
+
+ assert body["permission_required"] is True
+ assert body["can_open_settings"] is True
+ # An app that never asked is not in the Privacy pane yet: the hint points at the
+ # test button (the just-in-time ask), not at a Settings row that does not exist.
+ assert body["hint"] == "Press the test button and choose Allow in the macOS dialog."
+ assert "System Settings" not in body["hint"]
+ assert gate.ensure_calls() == []
+ assert gate.native_free()
+
+
+def test_macos_mic_level_measures_once_the_microphone_is_granted(monkeypatch):
+ import jarvis.speech.diagnose as d
+
+ async def fake_measure(duration_s=3.0):
+ return -15.0
+
+ monkeypatch.setattr(d, "measure_mic_dbfs", fake_measure)
+ app, gate = _macos_app(monkeypatch, PermissionOutcome.GRANTED)
+
+ body = TestClient(app).get("/api/settings/wake-word/mic-level").json()
+
+ assert body == {
+ "max_dbfs": -15.0,
"no_device": False,
"too_quiet": False,
- "permission_required": True,
+ "permission_required": False,
}
- assert calls == 0
+ assert gate.ensure_calls() == []
-def test_macos_wake_self_test_does_not_bypass_permission_gate(monkeypatch):
+def test_macos_mic_level_reports_a_grant_lost_during_the_measurement(monkeypatch):
+ import jarvis.speech.diagnose as d
+ from jarvis.audio.capture import MicrophoneAccessError
+
+ async def revoked(duration_s=3.0):
+ raise MicrophoneAccessError("revoked")
+
+ monkeypatch.setattr(d, "measure_mic_dbfs", revoked)
+ app, _gate = _macos_app(monkeypatch, PermissionOutcome.GRANTED)
+
+ body = TestClient(app).get("/api/settings/wake-word/mic-level").json()
+
+ assert body["permission_required"] is True
+ assert body["max_dbfs"] == -120.0
+
+
+def test_macos_wake_self_test_asks_at_the_button_and_never_measures_without_a_grant(monkeypatch):
import jarvis.speech.diagnose as d
- import jarvis.ui.web.settings_routes as settings_routes
calls = 0
@@ -145,27 +216,57 @@ def test_macos_wake_self_test_does_not_bypass_permission_gate(monkeypatch):
calls += 1
return -15.0
- monkeypatch.setattr(settings_routes.sys, "platform", "darwin")
monkeypatch.setattr(d, "measure_mic_dbfs", forbidden_measure)
- app = FastAPI()
- app.state.system_permission_port = _PermissionPort(False)
- app.state.config = SimpleNamespace(
- trigger=SimpleNamespace(
- wake_word=SimpleNamespace(
- phrase="Hey Nova",
- engine="auto",
- custom_model_path="",
- fuzzy_match_ratio=0.8,
- )
- ),
- stt=SimpleNamespace(language="en"),
- ui=SimpleNamespace(language="en"),
- )
- app.include_router(router)
+ app, gate = _macos_app(monkeypatch, PermissionOutcome.DENIED)
response = TestClient(app).post("/api/settings/wake-word/self-test")
assert response.status_code == 200
- assert response.json()["permission_required"] is True
- assert response.json()["no_device"] is False
+ body = response.json()
+ assert body["permission_required"] is True
+ assert body["permission"] == "microphone"
+ assert body["can_open_settings"] is True
+ assert body["no_device"] is False
+ assert "System Settings > Privacy & Security > Microphone" in body["hint"]
+ assert "Settings > Permissions" not in body["message"] + body["hint"]
assert calls == 0
+ # The test button IS the just-in-time moment: an interactive ask, waiting for the dialog.
+ (call,) = gate.ensure_calls(PermissionId.MICROPHONE)
+ assert call.method == "ensure_async"
+ assert (call.feature, call.interactive, call.wait_s) == ("wake_word", True, 60.0)
+
+
+def test_macos_wake_self_test_measures_after_the_dialog_is_allowed(monkeypatch):
+ import jarvis.speech.diagnose as d
+
+ async def fake_measure(duration_s=3.0):
+ return -20.0
+
+ monkeypatch.setattr(d, "measure_mic_dbfs", fake_measure)
+ app, gate = _macos_app(monkeypatch, PermissionOutcome.GRANTED)
+
+ body = TestClient(app).post("/api/settings/wake-word/self-test").json()
+
+ assert body["permission_required"] is False
+ assert body["mic_ok"] is True
+ assert len(gate.ensure_calls(PermissionId.MICROPHONE)) == 1
+
+
+def test_non_macos_routes_never_touch_the_permission_service(monkeypatch):
+ import jarvis.speech.diagnose as d
+ import jarvis.ui.web.settings_routes as settings_routes
+
+ async def fake_measure(duration_s=3.0):
+ return -20.0
+
+ monkeypatch.setattr(d, "measure_mic_dbfs", fake_measure)
+ monkeypatch.setattr(settings_routes, "_is_macos", lambda: False)
+ gate = FakePermissionService()
+ app = FastAPI()
+ app.state.permission_service = gate
+ app.include_router(router)
+
+ body = TestClient(app).get("/api/settings/wake-word/mic-level").json()
+
+ assert body["permission_required"] is False
+ assert gate.calls == []
diff --git a/tests/unit/web/test_screen_context_routes.py b/tests/unit/web/test_screen_context_routes.py
index e16534a091..c0f749edb1 100644
--- a/tests/unit/web/test_screen_context_routes.py
+++ b/tests/unit/web/test_screen_context_routes.py
@@ -141,10 +141,12 @@ def test_status_requires_the_complete_visual_context_path(monkeypatch) -> None:
"_ocr_capability",
lambda _enabled: (False, "Optional OCR is switched off."),
)
- monkeypatch.setattr(
- "jarvis.screen_context.ports.capture_permission_error",
- lambda: None,
- )
+ probe_kwargs: list[dict] = []
+
+ def capture_probe(**kwargs):
+ probe_kwargs.append(kwargs)
+
+ monkeypatch.setattr("jarvis.screen_context.ports.capture_permission_error", capture_probe)
monkeypatch.setattr(
"jarvis.screen_context.ports.accessibility_permission_error",
lambda: None,
@@ -153,6 +155,7 @@ def test_status_requires_the_complete_visual_context_path(monkeypatch) -> None:
response = TestClient(_app()).get("/api/screen-context/status")
assert response.status_code == 200
+ assert probe_kwargs == [{"deep": False}] # a GET never runs the window-title oracle
payload = response.json()
assert payload["available"] is False
assert payload["components"]["capture"]["ready"] is True
@@ -208,3 +211,60 @@ def test_single_capture_discard_never_returns_pixels(monkeypatch) -> None:
assert response.status_code == 200
assert response.json() == {"ok": True, "discarded": 1}
assert "image" not in response.text
+
+
+def _status_service() -> SimpleNamespace:
+ return SimpleNamespace(
+ settings=SimpleNamespace(enabled=True, ocr_enabled=False, ttl_s=120.0),
+ displays=SimpleNamespace(monitors=lambda: [{"name": "virtual"}, {"name": "primary"}]),
+ cursor=SimpleNamespace(position=lambda: (10, 10)),
+ held_count=0,
+ )
+
+
+def _status_capabilities(monkeypatch) -> None:
+ monkeypatch.setattr(screen_context_routes, "_get_service", lambda _r: _status_service())
+ monkeypatch.setattr(screen_context_routes, "_capture_backend_capability", lambda: (True, ""))
+ monkeypatch.setattr(screen_context_routes, "_indicator_capability", lambda: (True, ""))
+ monkeypatch.setattr(screen_context_routes, "_vision_capability", lambda: (True, ""))
+ monkeypatch.setattr(screen_context_routes, "_ocr_capability", lambda _e: (False, ""))
+ monkeypatch.setattr("jarvis.screen_context.ports._is_wayland", lambda: False)
+
+
+def test_status_never_prompts_and_describes_the_missing_permission(monkeypatch) -> None:
+ """GET /status reads the permission state; asking is a gesture's job.
+
+ The REAL permission service runs on ``FakeTCC`` (a model of macOS privacy, nothing
+ here ran on a real Mac): the call log proves a status poll made macOS ask nothing.
+ """
+ from tests.fakes.fake_tcc import FakeTCC, install_port
+
+ tcc = FakeTCC()
+ install_port(monkeypatch, tcc.port("darwin"))
+ _status_capabilities(monkeypatch)
+ client = TestClient(_app())
+
+ for _ in range(3): # polling must not turn into asking
+ payload = client.get("/api/screen-context/status").json()
+
+ assert payload["available"] is False
+ permission = payload["components"]["permission"]
+ assert permission["ready"] is False
+ # The sentence of the issue, not the repr of its dataclass.
+ assert permission["detail"].startswith("Screen Recording access is off for Personal Jarvis")
+ assert "CapturePermissionIssue" not in str(payload)
+ assert payload["blocked_reason"] == permission["detail"]
+ tcc.assert_no_prompts()
+
+
+def test_status_is_ready_and_silent_off_macos(monkeypatch) -> None:
+ from tests.fakes.fake_tcc import install_port, make_non_darwin_port
+
+ port, tcc = make_non_darwin_port("linux")
+ install_port(monkeypatch, port)
+ _status_capabilities(monkeypatch)
+
+ payload = TestClient(_app()).get("/api/screen-context/status").json()
+
+ assert payload["components"]["permission"] == {"ready": True, "detail": ""}
+ tcc.assert_silent()
diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.py
index 916081ce04..61da4ecca8 100644
--- a/ui/orb/bus_bridge.py
+++ b/ui/orb/bus_bridge.py
@@ -32,6 +32,7 @@ import asyncio
import logging
import random
import re
+import sys
import time
from typing import TYPE_CHECKING, Any
@@ -133,6 +134,92 @@ DICTATION_REFUSAL_DWELL_S = 3.0
# surface says the one thing that is true without the detail.
DICTATION_REFUSAL_FALLBACK_TEXT = "Dictation could not start."
+# A refused dictation whose reason is ``microphone_unavailable`` is, on macOS,
+# nearly always the microphone permission. The pipeline's English sentence says
+# "check the microphone permission"; the three tables below say what to do NEXT in
+# the interface language (answer the dialog, flip the switch, open the window),
+# because on this surface the sentence is all the user gets (the permission toast
+# lives in the web window). macOS only: the sentences name System Settings, and the
+# same reason on another OS can also mean "the desktop window is not visible".
+# Keys are the supported UI languages. This first table is for a microphone that
+# macOS has not been asked about yet.
+MICROPHONE_REFUSAL_TEXT: dict[str, str] = {
+ "en": (
+ "Microphone access is needed: allow it in the macOS dialog, then press the "
+ "key again."
+ ),
+ "de": ( # i18n-allow
+ "Mikrofonzugriff nötig: im macOS-Dialog erlauben und die Taste dann noch " # i18n-allow
+ "einmal drücken." # i18n-allow
+ ),
+ "es": ( # i18n-allow
+ "Se necesita acceso al micrófono: permítelo en el diálogo de macOS y vuelve " # i18n-allow
+ "a pulsar la tecla." # i18n-allow
+ ),
+}
+
+# The microphone is DENIED (or macOS applies the switch only in Settings): there is no
+# dialog any more, so the sentence names the switch and the place instead.
+MICROPHONE_DENIED_REFUSAL_TEXT: dict[str, str] = {
+ "en": (
+ "Microphone is off for Personal Jarvis: switch it on in System Settings > "
+ "Privacy & Security > Microphone, then press the key again."
+ ),
+ "de": ( # i18n-allow
+ "Mikrofon ist für Personal Jarvis aus: schalte es in Systemeinstellungen > " # i18n-allow
+ "Datenschutz & Sicherheit > Mikrofon ein und drücke die Taste dann noch " # i18n-allow
+ "einmal." # i18n-allow
+ ),
+ "es": ( # i18n-allow
+ "El micrófono está desactivado para Personal Jarvis: actívalo en Ajustes del " # i18n-allow
+ "Sistema > Privacidad y seguridad > Micrófono y vuelve a pulsar la tecla." # i18n-allow
+ ),
+}
+
+# Running outside the installed app: the confirmation lives in the web window, and
+# the permission layer's own sentence talks about "the user" in the third person.
+MICROPHONE_OUTSIDE_REFUSAL_TEXT: dict[str, str] = {
+ "en": "Open the Personal Jarvis window to continue.",
+ "de": "Öffne das Personal-Jarvis-Fenster, um fortzufahren.", # i18n-allow
+ "es": "Abre la ventana de Personal Jarvis para continuar.", # i18n-allow
+}
+
+# A microphone-permission notice is a sentence with a place name in it: 3 s is too
+# short to read it, so it stays up longer than an ordinary refusal.
+MICROPHONE_REFUSAL_DWELL_S = 8.0
+
+
+def _microphone_refusal_kind(detail: str) -> str:
+ """Which notice a macOS ``microphone_unavailable`` refusal gets.
+
+ ``"keep"``: restricted (a profile or parental control), or a session where macOS
+ cannot be asked: the permission service's fixed sentence stays, because "switch it
+ on in System Settings" would be wrong. ``"outside"``: running outside the installed
+ app (the grantee is another app and only the window can confirm). ``"denied"``: the
+ switch is off, no dialog exists any more. ``"undecided"``: anything else (the
+ pipeline's generic sentence, the not-determined templates). The kind is read from
+ the service's FIXED sentences, never parsed from free text. Never raises: an
+ unreadable service means "undecided" (the table is the safe default for the bar).
+ """
+ try:
+ from jarvis.platform.permission_service import user_detail_for
+ from jarvis.platform.permissions import PermissionId
+
+ mic = PermissionId.MICROPHONE
+ if detail in {user_detail_for(mic, "restricted"), user_detail_for(mic, "unavailable")}:
+ return "keep"
+ if detail in {
+ user_detail_for(mic, "not_determined", outside_app=True, launched_as_bundle=True),
+ user_detail_for(mic, "not_determined", outside_app=True, launched_as_bundle=False),
+ }:
+ return "outside"
+ if detail in {user_detail_for(mic, "denied"), user_detail_for(mic, "needs_settings")}:
+ return "denied"
+ except Exception: # noqa: BLE001 - the table is the safe default for the bar
+ log.debug("Microphone refusal templates unavailable; using the table.", exc_info=True)
+ return "undecided"
+
+
# How long the bar stays up after a dictation that came back with NOTHING —
# silence, or a provider that refused. Short, and deliberately not zero: the
# recording look was on screen a moment ago, so vanishing without a beat is
@@ -1959,6 +2046,17 @@ class OrbBusBridge:
reason = (event.reason or "").strip() or "unspecified"
detail = (event.detail or "").strip() or DICTATION_REFUSAL_FALLBACK_TEXT
log.info("OrbBridge._on_dictation_refused: reason=%s — %s", reason, detail)
+ dwell_s = DICTATION_REFUSAL_DWELL_S
+ if reason == "microphone_unavailable" and sys.platform == "darwin":
+ kind = _microphone_refusal_kind(detail)
+ table = {
+ "undecided": MICROPHONE_REFUSAL_TEXT,
+ "denied": MICROPHONE_DENIED_REFUSAL_TEXT,
+ "outside": MICROPHONE_OUTSIDE_REFUSAL_TEXT,
+ }.get(kind)
+ if table is not None:
+ detail = table.get(self._status_language(), table["en"])
+ dwell_s = MICROPHONE_REFUSAL_DWELL_S
if reason in DICTATION_INERT_REFUSALS:
# "A dictation is already recording" is not a failure — it is the
# statement that the turn the user is watching is alive and will
@@ -1983,7 +2081,7 @@ class OrbBusBridge:
self._cancel_dictation_standdown()
self._show_notice_mode()
self._show_listening_transcript(detail)
- self._schedule_notice_standdown(DICTATION_REFUSAL_DWELL_S)
+ self._schedule_notice_standdown(dwell_s)
def _rest_surface(self) -> None:
"""Drop the working look NOW, without closing the surface yet.