Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(platform): macOS permissions surface — TCC probes, permissions routes/CLI/panel, launcher entry, autostart
Ruben Lütke0b96bfd0efaf
diff --git a/.github/workflows/macos-desktop.yml b/.github/workflows/macos-desktop.ymlnew file mode 100644index 0000000000..dfb04c9330--- /dev/null+++ b/.github/workflows/macos-desktop.yml@@ -0,0 +1,132 @@+# 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;+# the release checklist retains one physical-Mac grant/click sign-off.++name: macOS desktop++on:+ pull_request:+ paths:+ - ".github/workflows/macos-desktop.yml"+ - "install/**"+ - "jarvis/cu/**"+ - "jarvis/platform/**"+ - "jarvis/setup/**"+ - "jarvis/trigger/**"+ - "jarvis/ui/**"+ - "jarvis/vision/**"+ - "pyproject.toml"+ - "tests/**"+ - "uv.lock"+ workflow_dispatch:++concurrency:+ group: macos-desktop-${{ github.ref }}+ cancel-in-progress: true++permissions:+ contents: read++jobs:+ desktop:+ name: ${{ matrix.name }} / Python ${{ matrix.python }}+ strategy:+ fail-fast: false+ matrix:+ include:+ - name: Intel+ runner: macos-15-intel+ architecture: x86_64+ python: "3.12"+ - name: Apple Silicon+ runner: macos-15+ architecture: arm64+ python: "3.13"+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 45++ steps:+ - name: Checkout+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2+ with:+ persist-credentials: false++ - name: Set up Python+ uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0+ with:+ python-version: ${{ matrix.python }}++ - name: Verify native architecture+ shell: bash+ run: |+ python -c "import platform; actual=platform.machine(); expected='${{ matrix.architecture }}'; print(actual); assert actual == expected, (actual, expected)"++ - name: Install the advertised full profile+ shell: bash+ run: |+ python -m pip install --upgrade pip+ python -m pip install -e ".[full,dev]"++ - name: Import native permission frameworks+ run: python -c "import AVFoundation, ApplicationServices, AppKit, Foundation, HIServices, Quartz, ScreenCaptureKit"++ - name: Verify headless TCC requests 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"++ - name: Build and self-probe the native app identity+ shell: bash+ run: |+ python - <<'PY'+ import plistlib+ import tempfile+ from pathlib import Path++ from jarvis.setup.macos_app_bundle import (+ BUNDLE_ID,+ ensure_macos_app_bundle,+ macos_app_bundle_is_launchable,+ )++ with tempfile.TemporaryDirectory() as raw:+ bundle = ensure_macos_app_bundle(+ install_dir=Path.cwd(),+ applications_dir=Path(raw),+ )+ assert bundle is not None+ assert macos_app_bundle_is_launchable(bundle)+ with (bundle / "Contents" / "Info.plist").open("rb") as stream:+ assert plistlib.load(stream)["CFBundleIdentifier"] == BUNDLE_ID+ PY++ - name: macOS permission, bundle, and Computer-Use tests+ shell: bash+ run: |+ python -m pytest -q \+ tests/unit/platform/test_permissions.py \+ tests/unit/audio/test_capture_permission_gate.py \+ tests/unit/ui/web/test_permissions_routes.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 \+ tests/unit/autostart/test_macos.py \+ tests/unit/autostart/test_command.py \+ tests/unit/cu/test_geometry.py \+ tests/unit/cu/test_actuate.py \+ tests/unit/cu/test_capture.py \+ tests/unit/cu/test_engine_loop.py \+ tests/unit/cu/test_target_guard.py \+ tests/unit/harness/test_action_registry.py \+ tests/unit/platform/test_window_state.py \+ tests/unit/platform/test_window_state_rects.py \+ tests/unit/plugins/tool/test_click_foreground_guard.py \+ tests/unit/plugins/tool/test_hotkey_tool.py \+ tests/unit/plugins/tool/test_scroll.py \+ tests/unit/plugins/tool/test_type_text.py \+ 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.pydiff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.pyindex 52348a126e..e3bc8c7c87 100644--- a/jarvis/audio/capture.py+++ b/jarvis/audio/capture.py@@ -12,8 +12,9 @@ and performs a stateful CPU resample before yielding each chunk.from __future__ import annotationsimport asyncio+import sysimport time-from collections.abc import AsyncIterator, Iterator, Sequence+from collections.abc import AsyncIterator, Callable, Iterator, Sequencefrom typing import TYPE_CHECKING, Anyimport numpy as np@@ -37,6 +38,39 @@ CHANNELS = 1 # Mono is sufficient for speechBLOCKSIZE = 1600 # 100 ms blocks — compromise between latency and CPU overheadDTYPE = "int16"++class MicrophoneAccessError(PermissionError):+ """The current process is not allowed to open the local microphone."""+++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.+ """+ 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 _allowed() -> bool:+ try:+ return port.runtime_access_granted(PermissionId.MICROPHONE)+ except Exception: # noqa: BLE001 - a probe failure is not permission+ return False++ return _allowed+# 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# time the drop-OLDEST overflow policy keeps the audio near-present (so@@ -523,6 +557,7 @@ 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.25def __init__(self,@@ -532,7 +567,11 @@ class MicrophoneCapture:channels: int = CHANNELS,max_queue_chunks: int = 20,device_priority: Sequence[str] | None = None,+ access_gate: Callable[[], bool] | None = None,) -> None:+ self._access_gate = (+ access_gate if access_gate is not None else _macos_microphone_access_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.@@ -585,6 +624,21 @@ class MicrophoneCapture:self._watchdog_task: asyncio.Task | None = Noneself._restart_count: int = 0+ def _require_microphone_access(self) -> None:+ """Fail before a native open and whenever a live grant is revoked."""+ gate = self._access_gate+ if gate is None:+ return+ 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."+ )+def _callback(self, indata, frames, time_info, status) -> None:"""PortAudio callback — runs in the audio thread, NOT in the asyncio loop.@@ -661,6 +715,7 @@ class MicrophoneCapture:Extracted from __aenter__ so the stall watchdog can reuse the sameopen logic for restarts."""+ self._require_microphone_access()attempts: list[int | str | None] = [self._device]try:if isinstance(self._device, int):@@ -687,6 +742,7 @@ class MicrophoneCapture:attempt_count = 0for attempt, capture_rate in _open_candidates():attempt_count += 1+ self._require_microphone_access()try:capture_blocksize = (0@@ -866,7 +922,20 @@ class MicrophoneCapture:only sees a brief audio gap and continues reading."""while not self._closed:- chunk = await self._queue.get()+ self._require_microphone_access()+ if self._access_gate is None:+ chunk = await self._queue.get()+ else:+ try:+ chunk = await asyncio.wait_for(+ self._queue.get(), timeout=self._ACCESS_RECHECK_S+ )+ 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._require_microphone_access()yield chunk@propertydiff --git a/jarvis/autostart/command.py b/jarvis/autostart/command.pyindex ca548c7708..1694b29c9c 100644--- a/jarvis/autostart/command.py+++ b/jarvis/autostart/command.py@@ -80,14 +80,53 @@ def resolve_launch_spec(cfg: object | None = None) -> LaunchSpec:if autostart is not None:minimized = bool(getattr(autostart, "start_minimized", False))+ args: tuple[str, ...] = ("-m", LAUNCHER_MODULE)if sys.platform == "win32":program = _detect_pythonw()+ elif sys.platform == "darwin":+ # LaunchServices keeps login startup under the same stable .app/TCC+ # identity used by Spotlight and manual launches. Never fall back to a+ # raw interpreter: that would create a second TCC identity and make+ # grants appear to vanish. Missing bundles fail closed until repaired.+ bundle = Path.home() / "Applications" / "Personal Jarvis.app"+ program = "/usr/bin/open"+ try:+ from jarvis.setup.macos_app_bundle import (+ macos_app_bundle_is_launchable,+ macos_app_bundle_path,+ macos_launch_services_command,+ )++ bundle = macos_app_bundle_path()+ if not macos_app_bundle_is_launchable(bundle):+ log.warning(+ "macOS app bundle is unavailable; autostart will fail closed "+ "until desktop integration repairs %s.",+ bundle,+ )+ command = macos_launch_services_command(+ bundle,+ background=minimized,+ wait_for_exit=True,+ )+ program, *launch_args = command+ args = tuple(launch_args)+ except Exception as exc: # noqa: BLE001 - stable-identity fallback+ log.warning(+ "Could not validate the macOS app bundle; autostart will use "+ "the canonical LaunchServices path: %s",+ exc,+ )+ launch_args = ["-W", "-a", str(bundle)]+ if minimized:+ launch_args.insert(0, "-g")+ args = tuple(launch_args)else:program = sys.executablereturn LaunchSpec(program=program,- args=("-m", LAUNCHER_MODULE),+ args=args,working_dir=str(PROJECT_ROOT),minimized=minimized,)diff --git a/jarvis/autostart/macos.py b/jarvis/autostart/macos.pyindex 30d40736ee..2bfd273045 100644--- a/jarvis/autostart/macos.py+++ b/jarvis/autostart/macos.py@@ -1,7 +1,9 @@"""macOS login autostart via a per-user LaunchAgent.Writes ``~/Library/LaunchAgents/com.personal-jarvis.autostart.plist`` with-``RunAtLoad=true``. A **LaunchAgent (per-user), not a LaunchDaemon** — the agent+``RunAtLoad=true``. The canonical launch specification uses ``/usr/bin/open``+to enter through ``Personal Jarvis.app`` and preserve its TCC identity. A+**LaunchAgent (per-user), not a LaunchDaemon** — the agentruns inside the user's GUI session so it keeps microphone access (a Daemon runsas a non-interactive system context with no mic/seat, the macOS analogue of the"no Windows Service" rule, AP-17).@@ -82,6 +84,9 @@ class MacOSAutostart:matches = (data.get("ProgramArguments") == _program_arguments(spec)and data.get("WorkingDirectory") == spec.working_dir+ and data.get("RunAtLoad") is True+ and data.get("ProcessType") == "Interactive"+ and data.get("LimitLoadToSessionType") == "Aqua")return AutostartStatus(supported=True,@@ -105,6 +110,8 @@ class MacOSAutostart:"WorkingDirectory": spec.working_dir,"RunAtLoad": True,"ProcessType": "Interactive",+ # Keep voice and Computer-Use inside the signed-in GUI session.+ "LimitLoadToSessionType": "Aqua",}tmp = self._path.with_suffix(".plist.tmp")with tmp.open("wb") as fh:diff --git a/jarvis/cli_ctl/commands/permissions.py b/jarvis/cli_ctl/commands/permissions.pynew file mode 100644index 0000000000..59196201e8--- /dev/null+++ b/jarvis/cli_ctl/commands/permissions.py@@ -0,0 +1,124 @@+"""permissions: inspect and request desktop privacy access."""++from __future__ import annotations++import importlib+import subprocess+import time+from pathlib import Path+from typing import Annotated, NoReturn++import typer++from jarvis.cli_ctl import invoke, options, render+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.platform import detect_platform+from jarvis.platform.permissions import APP_NAME, EXPECTED_BUNDLE_ID, PermissionId++app = typer.Typer(+ no_args_is_help=True,+ help="Inspect and request macOS privacy permissions.",+)+++def _installed_macos_app() -> Path:+ return Path.home() / "Applications" / f"{APP_NAME}.app"+++def _activation_error(message: str) -> NoReturn:+ render.error(message)+ raise typer.Exit(code=1)+++def _activate_macos_app_for_tcc() -> None:+ """Foreground the canonical bundle before its server invokes a TCC API."""+ if detect_platform() != "darwin":+ return+ 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."+ )+ try:+ completed = subprocess.run(+ ["open", str(bundle)],+ check=False,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ timeout=10,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, subprocess.SubprocessError):+ _activation_error("Personal Jarvis could not be activated through LaunchServices.")+ if completed.returncode != 0:+ _activation_error("Personal Jarvis could not be activated through LaunchServices.")++ try:+ appkit = importlib.import_module("AppKit")+ workspace = appkit.NSWorkspace.sharedWorkspace()+ deadline = time.monotonic() + 3.0+ 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:+ return+ time.sleep(0.05)+ except Exception as exc: # noqa: BLE001 - native verification fails closed+ _activation_error(+ "The macOS foreground app could not be verified "+ f"({type(exc).__name__})."+ )+ _activation_error(+ "Personal Jarvis did not become the foreground app. Activate its window "+ "and retry the permission command."+ )+++def status() -> None:+ """Show permission and feature readiness without caching native state."""+ invoke.run("GET", "/api/permissions/status")+++def request(+ permission_id: Annotated[+ PermissionId,+ typer.Argument(help="Permission to request from macOS."),+ ],+ yes: bool = options.yes_opt(),+ dry_run: bool = options.dry_opt(),+) -> None:+ """Show the native macOS prompt for one permission."""+ invoke.run(+ "POST",+ f"/api/permissions/{permission_id.value}/request",+ assume_yes=yes,+ dry_run=dry_run,+ dangerous=True,+ before_request=_activate_macos_app_for_tcc,+ )++[email protected]("open-settings")+def open_settings(+ permission_id: Annotated[+ PermissionId,+ typer.Argument(help="Permission pane to open in macOS System Settings."),+ ],+ yes: bool = options.yes_opt(),+ dry_run: bool = options.dry_opt(),+) -> None:+ """Open the matching macOS privacy pane through LaunchServices."""+ invoke.run(+ "POST",+ f"/api/permissions/{permission_id.value}/open-settings",+ assume_yes=yes,+ dry_run=dry_run,+ dangerous=True,+ before_request=_activate_macos_app_for_tcc,+ )+++__all__ = ["app"]diff --git a/jarvis/platform/macos_ax.py b/jarvis/platform/macos_ax.pynew file mode 100644index 0000000000..cd5aba8d67--- /dev/null+++ b/jarvis/platform/macos_ax.py@@ -0,0 +1,97 @@+"""Import-clean helpers for decoding macOS Accessibility geometry.++Accessibility position and size attributes are ``AXValueRef`` objects on a+real Mac. PyObjC 8.4 and newer ship manual wrappers for ``AXValueCreate`` and+``AXValueGetValue``; the generic metadata bridge used by older releases could+crash when handed the C output pointer. Keep that ABI-sensitive operation in+one small module, use only the manual wrapper, and degrade to ``None`` when an+old or incomplete PyObjC installation is encountered.+"""+from __future__ import annotations++import math+from collections.abc import Sequence+from typing import Any+++def _finite_pair(first: Any, second: Any) -> tuple[float, float] | None:+ try:+ pair = float(first), float(second)+ except (TypeError, ValueError):+ return None+ return pair if all(math.isfinite(item) for item in pair) else None+++def _manual_axvalue_pair(+ value: Any,+ constant_names: tuple[str, ...],+) -> tuple[float, float] | None:+ """Decode with PyObjC's crash-safe manual wrapper, never raw ``ctypes``."""+ try:+ import HIServices # type: ignore[import-not-found] # noqa: PLC0415++ value_type = next(+ getattr(HIServices, name)+ for name in constant_names+ if hasattr(HIServices, name)+ )+ get_type = getattr(HIServices, "AXValueGetType", None)+ if callable(get_type) and get_type(value) != value_type:+ return None+ ok, decoded = HIServices.AXValueGetValue(value, value_type, None)+ if not ok:+ return None+ # PyObjC generated structs expose sequence slots without registering+ # with collections.abc.Sequence. Capability access works for both+ # those structs and the tuple returned by newer bridge releases.+ try:+ if len(decoded) != 2:+ return None+ return _finite_pair(decoded[0], decoded[1])+ except (AttributeError, IndexError, KeyError, TypeError):+ return None+ except Exception: # noqa: BLE001 -- unsupported PyObjC safely degrades+ return None+++def decode_ax_point(value: Any) -> tuple[float, float] | None:+ """Decode a CGPoint-like value without importing PyObjC off macOS."""+ if value is None:+ return None+ if isinstance(value, dict):+ return _finite_pair(+ value.get("x", value.get("X")),+ value.get("y", value.get("Y")),+ )+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):+ if len(value) == 2:+ return _finite_pair(value[0], value[1])+ x, y = getattr(value, "x", None), getattr(value, "y", None)+ if x is not None and y is not None:+ return _finite_pair(x, y)+ return _manual_axvalue_pair(+ value,+ ("kAXValueCGPointType", "kAXValueTypeCGPoint"),+ )+++def decode_ax_size(value: Any) -> tuple[float, float] | None:+ """Decode a CGSize-like value without importing PyObjC off macOS."""+ if value is None:+ return None+ if isinstance(value, dict):+ return _finite_pair(+ value.get("w", value.get("width", value.get("Width"))),+ value.get("h", value.get("height", value.get("Height"))),+ )+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):+ if len(value) == 2:+ return _finite_pair(value[0], value[1])+ width = getattr(value, "width", None)+ height = getattr(value, "height", None)+ if width is not None and height is not None:+ return _finite_pair(width, height)+ return _manual_axvalue_pair(+ value,+ ("kAXValueCGSizeType", "kAXValueTypeCGSize"),+ )diff --git a/jarvis/platform/permissions.py b/jarvis/platform/permissions.pynew file mode 100644index 0000000000..59260872ca--- /dev/null+++ b/jarvis/platform/permissions.py@@ -0,0 +1,627 @@+"""Uncached macOS system-permission probes and user-initiated requests.++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.+"""++from __future__ import annotations++import importlib+import logging+import os+from collections.abc import Callable+from dataclasses import asdict, dataclass+from enum import StrEnum+from pathlib import Path+from typing import Any++from . import PlatformName, detect_platform++log = logging.getLogger(__name__)++EXPECTED_BUNDLE_ID = "com.personal-jarvis.desktop"+APP_NAME = "Personal Jarvis"+++class PermissionId(StrEnum):+ """Stable identifiers shared by the API and desktop permission UI."""++ MICROPHONE = "microphone"+ SCREEN_RECORDING = "screen_recording"+ ACCESSIBILITY = "accessibility"+ INPUT_MONITORING = "input_monitoring"+ EVENT_POSTING = "event_posting"+++class PermissionState(StrEnum):+ """Cross-platform permission states; never infer denial from uncertainty."""++ GRANTED = "granted"+ NOT_DETERMINED = "not_determined"+ DENIED = "denied"+ RESTRICTED = "restricted"+ NOT_GRANTED = "not_granted"+ UNAVAILABLE = "unavailable"+ 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,),+}++_LABELS: dict[PermissionId, str] = {+ PermissionId.MICROPHONE: "Microphone",+ PermissionId.SCREEN_RECORDING: "Screen Recording",+ PermissionId.ACCESSIBILITY: "Accessibility",+ PermissionId.INPUT_MONITORING: "Input Monitoring",+ PermissionId.EVENT_POSTING: "Input Control",+}++_SETTINGS_URLS: dict[PermissionId, str] = {+ PermissionId.MICROPHONE: (+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"+ ),+ PermissionId.SCREEN_RECORDING: (+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"+ ),+ PermissionId.ACCESSIBILITY: (+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"+ ),+ PermissionId.INPUT_MONITORING: (+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent"+ ),+ PermissionId.EVENT_POSTING: (+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"+ ),+}++_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,+ }+)+++@dataclass(frozen=True)+class AppIdentity:+ 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+ 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:+ 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:+ """Read and request OS permissions without caching native state."""++ def __init__(+ self,+ *,+ platform_name: PlatformName | None = None,+ module_loader: Callable[[str], Any] = importlib.import_module,+ ) -> None:+ self._platform_name = platform_name+ self._module_loader = module_loader+ # 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()++ @property+ def platform(self) -> PlatformName:+ return self._platform_name or detect_platform()++ def _load(self, module: str) -> Any | None:+ try:+ return self._module_loader(module)+ except Exception: # noqa: BLE001 - a broken native bridge fails closed+ log.debug("Native permission framework %s is unavailable.", module, exc_info=True)+ return None++ def _app_identity(self) -> tuple[AppIdentity, bool]:+ 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: str | None = None+ bundle_path: str | None = None+ foundation = self._load("Foundation")+ if foundation is not None:+ try:+ bundle = foundation.NSBundle.mainBundle()+ raw_id = bundle.bundleIdentifier()+ raw_path = bundle.bundlePath()+ bundle_id = str(raw_id) if raw_id else None+ bundle_path = str(raw_path) if raw_path else None+ except Exception: # noqa: BLE001 - native metadata is advisory+ log.debug("Could not read the current macOS app identity.", exc_info=True)++ launched_as_bundle = bool(bundle_path and ".app/" in f"{bundle_path}/")+ canonical_path = False+ if launched_as_bundle and bundle_path:+ try:+ expected_path = Path.home() / "Applications" / f"{APP_NAME}.app"+ canonical_path = Path(bundle_path).resolve() == expected_path.resolve()+ except (OSError, ValueError):+ canonical_path = False+ stable = (+ bundle_id == EXPECTED_BUNDLE_ID+ and launched_as_bundle+ and canonical_path+ )+ 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()+ )+ except Exception: # noqa: BLE001 - fail closed for prompt safety+ 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,+ )++ def _microphone_state(self) -> PermissionState:+ av = self._load("AVFoundation")+ if av is None:+ return PermissionState.UNAVAILABLE+ try:+ raw = av.AVCaptureDevice.authorizationStatusForMediaType_(av.AVMediaTypeAudio)+ mapping = {+ int(+ getattr(av, "AVAuthorizationStatusNotDetermined", 0)+ ): PermissionState.NOT_DETERMINED,+ int(getattr(av, "AVAuthorizationStatusRestricted", 1)): PermissionState.RESTRICTED,+ int(getattr(av, "AVAuthorizationStatusDenied", 2)): PermissionState.DENIED,+ int(getattr(av, "AVAuthorizationStatusAuthorized", 3)): PermissionState.GRANTED,+ }+ return mapping.get(int(raw), PermissionState.UNAVAILABLE)+ except Exception: # noqa: BLE001 - native probes never crash callers+ return PermissionState.UNAVAILABLE++ def _boolean_state(self, module_name: str, function_name: str) -> PermissionState:+ module = self._load(module_name)+ function = getattr(module, function_name, None) if module is not None else None+ if not callable(function):+ return PermissionState.UNAVAILABLE+ try:+ return PermissionState.GRANTED if bool(function()) else PermissionState.NOT_GRANTED+ except Exception: # noqa: BLE001 - native probes never crash callers+ return PermissionState.UNAVAILABLE++ def _state(self, permission_id: PermissionId) -> PermissionState:+ if self.platform != "darwin":+ return PermissionState.NOT_REQUIRED+ if permission_id is PermissionId.MICROPHONE:+ return self._microphone_state()+ if permission_id is PermissionId.SCREEN_RECORDING:+ return self._boolean_state("Quartz", "CGPreflightScreenCaptureAccess")+ if permission_id is PermissionId.ACCESSIBILITY:+ return self._boolean_state("ApplicationServices", "AXIsProcessTrusted")+ if permission_id is PermissionId.INPUT_MONITORING:+ return self._boolean_state("Quartz", "CGPreflightListenEventAccess")+ quartz = self._load("Quartz")+ if callable(getattr(quartz, "CGPreflightPostEventAccess", None)):+ return self._boolean_state("Quartz", "CGPreflightPostEventAccess")+ # Older supported macOS releases protect CGEvent posting through the+ # Accessibility grant and do not expose the separate PostEvent API.+ return self._boolean_state("ApplicationServices", "AXIsProcessTrusted")++ def state(self, permission_id: PermissionId | str) -> PermissionState:+ """Probe one permission directly without constructing a full snapshot."""+ return self._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._state(resolved) in _READY_STATES+ identity, _headless = self._app_identity()+ return (+ identity.stable+ and resolved not in self._restart_required+ and self._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._state(item) in _READY_STATES for item in requirements)+ identity, _headless = self._app_identity()+ return identity.stable and all(+ item not in self._restart_required+ and self._state(item) is PermissionState.GRANTED+ for item in requirements+ )++ def _requester_available(self, permission_id: PermissionId) -> bool:+ 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+ )+ for permission_id in PermissionId:+ state = self._state(permission_id)+ states[permission_id] = state+ required = tuple(+ feature+ for feature, requirements in FEATURE_REQUIREMENTS.items()+ if permission_id in requirements+ )+ can_request = (+ eligible+ and self._requester_available(permission_id)+ and state+ not in {+ PermissionState.GRANTED,+ PermissionState.NOT_REQUIRED,+ PermissionState.RESTRICTED,+ PermissionState.DENIED,+ PermissionState.UNAVAILABLE,+ }+ )+ statuses.append(+ PermissionStatus(+ id=permission_id.value,+ label=_LABELS[permission_id],+ status=state.value,+ required=required,+ can_request=can_request,+ can_open_settings=eligible,+ restart_required=permission_id in self._restart_required,+ detail=self._detail(state),+ )+ )++ 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,+ }++ return {+ "platform": self.platform,+ "supported": self.platform == "darwin",+ "headless": headless,+ "app_identity": asdict(identity),+ "permissions": [status.to_dict() for status in statuses],+ "features": features,+ "restart_required": bool(self._restart_required),+ }++ def _eligibility_error(self, snapshot: dict[str, Any]) -> 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."+ )+ if not identity["foreground"]:+ return "Bring Personal Jarvis to the foreground and try again."+ return None++ def _native_request(self, permission_id: PermissionId) -> None:+ if permission_id is PermissionId.MICROPHONE:+ av = self._load("AVFoundation")+ av.AVCaptureDevice.requestAccessForMediaType_completionHandler_(+ av.AVMediaTypeAudio, lambda _granted: None+ )+ return+ if permission_id is PermissionId.ACCESSIBILITY:+ app_services = self._load("ApplicationServices")+ prompt_key = app_services.kAXTrustedCheckOptionPrompt+ app_services.AXIsProcessTrustedWithOptions({prompt_key: True})+ return+ 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):+ requester()+ return+ if permission_id is PermissionId.EVENT_POSTING:+ app_services = self._load("ApplicationServices")+ prompt_key = app_services.kAXTrustedCheckOptionPrompt+ app_services.AXIsProcessTrustedWithOptions({prompt_key: True})+ return+ 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,+ )+ try:+ 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(),+ )+ restart = permission_id in _RESTART_AFTER_CHANGE+ if restart:+ self._restart_required.add(permission_id)+ after = self.snapshot()+ return PermissionOperation(+ True,+ permission_id.value,+ "request",+ True,+ False,+ restart,+ (+ "Permission requested. Restart Personal Jarvis after granting access."+ if restart+ else "Permission requested; the status will update after your choice."+ ),+ after,+ )+ def _open_settings(self, permission_id: PermissionId) -> bool:+ appkit = self._load("AppKit")+ foundation = self._load("Foundation")+ if appkit is None or foundation is None:+ return False+ url = foundation.NSURL.URLWithString_(_SETTINGS_URLS[permission_id])+ return bool(appkit.NSWorkspace.sharedWorkspace().openURL_(url))++ def open_settings(+ self, permission_id: PermissionId, *, dry_run: bool = False+ ) -> PermissionOperation:+ """Open the matching System Settings pane via LaunchServices."""+ before = self.snapshot()+ 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)+ 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+ restart = opened and permission_id in _RESTART_AFTER_CHANGE+ 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,+ )+++_DEFAULT_SYSTEM_PERMISSION_PORT = SystemPermissionPort()+++def get_system_permission_port() -> SystemPermissionPort:+ """Return the process-wide port that retains only pending-restart state."""+ return _DEFAULT_SYSTEM_PERMISSION_PORT+++__all__ = [+ "APP_NAME",+ "EXPECTED_BUNDLE_ID",+ "FEATURE_REQUIREMENTS",+ "AppIdentity",+ "PermissionId",+ "PermissionOperation",+ "PermissionState",+ "PermissionStatus",+ "SystemPermissionPort",+ "get_system_permission_port",+]diff --git a/jarvis/setup/macos_app_bundle.py b/jarvis/setup/macos_app_bundle.pyindex 84da26c367..1540637268 100644--- a/jarvis/setup/macos_app_bundle.py+++ b/jarvis/setup/macos_app_bundle.py@@ -1,47 +1,60 @@-"""macOS ``.app`` bundle so Jarvis is discoverable like a real app (BUG-060).--A plain pip install ships no bundle, so after closing the desktop app on a-Mac there was no way back: Spotlight found nothing, Launchpad and-``/Applications`` showed nothing, and relaunching required a terminal-command. :func:`ensure_macos_app_bundle` writes a minimal per-user-``~/Applications/Personal Jarvis.app`` whose executable is a two-line bash-script exec'ing the install venv's Python desktop launcher — Spotlight-indexes ``~/Applications``, so Cmd+Space finds "Personal Jarvis".--Bonus: a real bundle gives TCC an identity. The microphone permission-prompt names "Personal Jarvis" with the honest usage string below, instead-of attributing (or denying) access to whichever terminal happened to start-the process.--The bundle build is pure stdlib file writes — CI-provable on any OS via the-injectable directories (same pattern as ``jarvis/autostart/macos.py``). Only-the optional icon conversion shells out to ``iconutil`` (darwin-only,-best-effort: a missing icon never blocks the bundle).+"""Build the managed-install macOS app identity (BUG-060).++The bundle's main executable must remain a Mach-O process. A shell launcher+that ``exec``s an external virtual-environment Python loses its ``NSBundle``+identity and causes TCC grants to attach to Python or a terminal instead of+Personal Jarvis. The managed installer therefore uses py2app's alias mode: its+native bootstrap embeds the active Python runtime in the app process while the+source and dependencies remain in the managed checkout.++The locally generated app is ad-hoc signed and is preserved byte-for-byte on+ordinary source updates so its local TCC identity does not churn. Public binary+distribution still requires the separate Developer-ID signing and notarization+pipeline; this module never claims an ad-hoc app is a notarized artifact."""+from __future__ import annotations+import jsonimport logging+import os+import platformimport plistlib+import shutilimport statimport subprocessimport sysimport tempfilefrom pathlib import Path+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+log = logging.getLogger(__name__)APP_NAME = "Personal Jarvis"APP_DIR_NAME = f"{APP_NAME}.app"BUNDLE_ID = "com.personal-jarvis.desktop"-_EXECUTABLE_NAME = "PersonalJarvis"+_BUNDLE_FORMAT_VERSION = 1+_MACHO_MAGICS = frozenset(+ {+ b"\xfe\xed\xfa\xce",+ b"\xce\xfa\xed\xfe",+ b"\xfe\xed\xfa\xcf",+ b"\xcf\xfa\xed\xfe",+ b"\xca\xfe\xba\xbe",+ b"\xbe\xba\xfe\xca",+ b"\xca\xfe\xba\xbf",+ b"\xbf\xba\xfe\xca",+ }+)_MIC_USAGE = ("Personal Jarvis listens on this microphone for your wake word and ""voice commands.")-_APPLE_EVENTS_USAGE = (- "Personal Jarvis uses AppleScript to focus and arrange application "- "windows you ask it to control."+_SCREEN_CAPTURE_USAGE = (+ "Personal Jarvis captures the screen only when you ask it to see or "+ "control applications.")@@ -50,12 +63,12 @@ def _version() -> str:from jarvis import __version__return __version__- except Exception: # noqa: BLE001 — version is cosmetic here+ except Exception: # noqa: BLE001 - version metadata is cosmetic herereturn "0.0.0"def _default_install_dir() -> Path:- """The install root — the parent of the ``jarvis`` package directory."""+ """Return the parent of the installed ``jarvis`` package directory."""import jarvisreturn Path(jarvis.__file__).resolve().parents[1]@@ -63,61 +76,366 @@ def _default_install_dir() -> Path:def _venv_python(install_dir: Path) -> Path:candidate = install_dir / ".venv" / "bin" / "python"- if candidate.exists():+ if candidate.is_file() and os.access(candidate, os.X_OK):return candidate- # Editable dev install / non-standard layout: whatever runs us now.return Path(sys.executable)-def _try_build_icns(resources_dir: Path) -> str | None:- """Best-effort ``jarvis.icns`` from the packaged PNG. darwin-only.+def macos_app_bundle_path(*, applications_dir: Path | None = None) -> Path:+ """Return the one canonical per-user application-bundle path."""+ root = applications_dir or (Path.home() / "Applications")+ return root / APP_DIR_NAME- Returns the CFBundleIconFile stem, or ``None`` — a missing icon must- never block the bundle (macOS falls back to the generic app icon).- """++def _is_macho_executable(path: Path) -> bool:+ try:+ mode = path.stat().st_mode+ with path.open("rb") as stream:+ magic = stream.read(4)+ except OSError:+ return False+ # Windows cannot represent POSIX execute bits. The only Windows caller is+ # the explicit cross-platform fixture seam; production validation runs on+ # macOS and therefore still requires an executable mode.+ executable_mode = os.name == "nt" or bool(+ mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)+ )+ return executable_mode and magic in _MACHO_MAGICS+++def _codesign_valid(bundle: Path) -> bool:+ if sys.platform != "darwin":+ return True+ try:+ result = subprocess.run(+ ["/usr/bin/codesign", "--verify", "--deep", "--strict", str(bundle)],+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, subprocess.TimeoutExpired):+ return False+ return result.returncode == 0+++def macos_app_bundle_is_launchable(bundle: Path | None = None) -> bool:+ """Validate native executable, canonical metadata, and code signature."""+ candidate = bundle or macos_app_bundle_path()+ info_path = candidate / "Contents" / "Info.plist"+ if (+ candidate.name != APP_DIR_NAME+ or candidate.is_symlink()+ or not candidate.is_dir()+ or not info_path.is_file()+ ):+ return False+ try:+ with info_path.open("rb") as stream:+ info = plistlib.load(stream)+ except (OSError, plistlib.InvalidFileException):+ return False+ executable_name = info.get("CFBundleExecutable")+ if (+ not isinstance(executable_name, str)+ or Path(executable_name).name != executable_name+ or info.get("CFBundleIdentifier") != BUNDLE_ID+ or info.get("CFBundlePackageType") != "APPL"+ or info.get("JarvisBundleFormatVersion") != _BUNDLE_FORMAT_VERSION+ ):+ return False+ executable = candidate / "Contents" / "MacOS" / executable_name+ return (+ executable.is_file()+ and not executable.is_symlink()+ and _is_macho_executable(executable)+ and _codesign_valid(candidate)+ )+++def macos_launch_services_command(+ bundle: Path | None = None,+ *,+ background: bool = False,+ wait_for_exit: bool = False,+ new_instance: bool = False,+ arguments: tuple[str, ...] = (),+) -> list[str]:+ """Build the ``open`` argv that enters through LaunchServices."""+ candidate = bundle or macos_app_bundle_path()+ command = ["/usr/bin/open"]+ if background:+ command.append("-g")+ if wait_for_exit:+ command.append("-W")+ if new_instance:+ command.append("-n")+ command.extend(["-a", str(candidate)])+ if arguments:+ command.append("--args")+ command.extend(arguments)+ return command+++def _try_build_icns(resources_dir: Path) -> str | None:+ """Best-effort ``jarvis.icns`` creation; never block bundle creation."""if sys.platform != "darwin":return Nonetry:- from PIL import Image # noqa: PLC0415 — optional at this call site+ from PIL import Image # noqa: PLC0415 - optional at this boundary- src = Path(__file__).resolve().parents[1] / "assets" / "icons" / "jarvis.png"- if not src.is_file():+ source = Path(__file__).resolve().parents[1] / "assets" / "icons" / "jarvis.png"+ if not source.is_file():return None- with tempfile.TemporaryDirectory() as tmp:- iconset = Path(tmp) / "jarvis.iconset"+ with tempfile.TemporaryDirectory() as raw_tmp:+ iconset = Path(raw_tmp) / "jarvis.iconset"iconset.mkdir()- img = Image.open(src).convert("RGBA")+ image = Image.open(source).convert("RGBA")for size in (16, 32, 64, 128, 256, 512):- img.resize((size, size)).save(iconset / f"icon_{size}x{size}.png")- img.resize((size * 2, size * 2)).save(+ image.resize((size, size)).save(iconset / f"icon_{size}x{size}.png")+ image.resize((size * 2, size * 2)).save(iconset / f"icon_{size}x{size}@2x.png")- out = resources_dir / "jarvis.icns"+ output = resources_dir / "jarvis.icns"result = subprocess.run(- ["iconutil", "-c", "icns", str(iconset), "-o", str(out)],+ ["iconutil", "-c", "icns", str(iconset), "-o", str(output)],capture_output=True,text=True,timeout=60,check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,)- if result.returncode == 0 and out.is_file():+ if result.returncode == 0 and output.is_file():return "jarvis"- except Exception as exc: # noqa: BLE001 — icon is a nicety, never a blocker+ except Exception as exc: # noqa: BLE001 - the icon is optionallog.debug("icns build skipped: %s", exc)return None+def _bundle_plist() -> dict[str, object]:+ """Return metadata shared by local and future signed bundle builders."""+ return {+ "CFBundleName": APP_NAME,+ "CFBundleDisplayName": APP_NAME,+ "CFBundleIdentifier": BUNDLE_ID,+ "CFBundlePackageType": "APPL",+ "CFBundleShortVersionString": _version(),+ "CFBundleVersion": _version(),+ "JarvisBundleFormatVersion": _BUNDLE_FORMAT_VERSION,+ "LSMinimumSystemVersion": "11.0",+ "NSHighResolutionCapable": True,+ "NSMicrophoneUsageDescription": _MIC_USAGE,+ "NSScreenCaptureUsageDescription": _SCREEN_CAPTURE_USAGE,+ }+++def _remove_path(path: Path) -> None:+ if path.is_symlink() or path.is_file():+ path.unlink(missing_ok=True)+ elif path.exists():+ shutil.rmtree(path)+++def _write_cross_platform_fixture_bundle(bundle: Path) -> Path:+ """Create a structural fixture when a test injects a path off macOS."""+ _remove_path(bundle)+ contents = bundle / "Contents"+ macos_dir = contents / "MacOS"+ resources = contents / "Resources"+ macos_dir.mkdir(parents=True)+ resources.mkdir(parents=True)+ executable_name = "PersonalJarvis"+ executable = macos_dir / executable_name+ executable.write_bytes(b"\xcf\xfa\xed\xfeJARVIS_TEST_FIXTURE\n")+ executable.chmod(+ executable.stat().st_mode+ | stat.S_IXUSR+ | stat.S_IXGRP+ | stat.S_IXOTH+ )+ info = _bundle_plist()+ info["CFBundleExecutable"] = executable_name+ with (contents / "Info.plist").open("wb") as stream:+ plistlib.dump(info, stream)+ return bundle+++def _build_py2app_alias(install_root: Path, work_dir: Path) -> Path:+ """Build a native alias launcher with the managed virtual environment."""+ entry = install_root / "jarvis" / "setup" / "macos_launcher_entry.py"+ if not entry.is_file():+ raise FileNotFoundError(f"macOS launcher entry is missing: {entry}")++ resources = work_dir / "resources"+ resources.mkdir()+ options: dict[str, object] = {+ "argv_emulation": False,+ "plist": _bundle_plist(),+ }+ icon_stem = _try_build_icns(resources)+ if icon_stem is not None:+ options["iconfile"] = str(resources / f"{icon_stem}.icns")++ setup_source = (+ "from setuptools import setup\n\n"+ "setup(\n"+ f" name={APP_NAME!r},\n"+ f" version={_version()!r},\n"+ f" app={[str(entry)]!r},\n"+ f" options={{'py2app': {options!r}}},\n"+ ")\n"+ )+ setup_path = work_dir / "setup.py"+ setup_path.write_text(setup_source, encoding="utf-8")+ result = subprocess.run(+ [str(_venv_python(install_root)), str(setup_path), "py2app", "--alias"],+ cwd=work_dir,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=300,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ if result.returncode != 0:+ detail = (result.stderr or result.stdout or "unknown py2app error").strip()+ raise RuntimeError(f"py2app alias build failed: {detail[-1200:]}")+ candidates = tuple((work_dir / "dist").glob("*.app"))+ if len(candidates) != 1:+ raise RuntimeError(+ f"py2app produced {len(candidates)} application bundles; expected one"+ )+ return candidates[0]+++def _sign_bundle(bundle: Path) -> None:+ result = subprocess.run(+ ["/usr/bin/codesign", "--force", "--deep", "--sign", "-", str(bundle)],+ capture_output=True,+ text=True,+ timeout=60,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ if result.returncode != 0:+ detail = (result.stderr or result.stdout or "unknown codesign error").strip()+ raise RuntimeError(f"ad-hoc code signing failed: {detail[-1200:]}")+ if not _codesign_valid(bundle):+ raise RuntimeError("the generated macOS bundle failed code-signature verification")+++def _runtime_identity_valid(bundle: Path, *, install_root: Path) -> bool:+ """Verify native identity and imports against the managed checkout."""+ if sys.platform != "darwin":+ return True+ descriptor, raw_probe = tempfile.mkstemp(+ prefix="jarvis-bundle-probe-", suffix=".json"+ )+ os.close(descriptor)+ probe = Path(raw_probe)+ probe.unlink(missing_ok=True)+ try:+ result = subprocess.run(+ macos_launch_services_command(+ bundle,+ wait_for_exit=True,+ new_instance=True,+ arguments=("--jarvis-identity-probe", str(probe)),+ ),+ capture_output=True,+ text=True,+ timeout=60,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ if result.returncode != 0 or not probe.is_file():+ return False+ payload = json.loads(probe.read_text(encoding="utf-8"))+ expected_bundle = bundle.resolve()+ reported_bundle = Path(str(payload.get("bundle_path", ""))).resolve()+ executable = Path(str(payload.get("executable", ""))).resolve()+ launcher_file = Path(str(payload.get("launcher_file", ""))).resolve()+ reported_install_root = Path(str(payload.get("install_root", ""))).resolve()+ executable_root = expected_bundle / "Contents" / "MacOS"+ expected_install_root = install_root.resolve()+ expected_launcher_root = expected_install_root / "jarvis" / "ui" / "web"+ return (+ payload.get("bundle_id") == BUNDLE_ID+ and reported_bundle == expected_bundle+ and executable.is_relative_to(executable_root)+ and launcher_file.is_file()+ and launcher_file.is_relative_to(expected_launcher_root)+ and reported_install_root == expected_install_root+ and payload.get("python_version")+ == f"{sys.version_info.major}.{sys.version_info.minor}"+ and payload.get("machine") == platform.machine()+ )+ except (OSError, ValueError, json.JSONDecodeError, subprocess.TimeoutExpired):+ return False+ finally:+ probe.unlink(missing_ok=True)+++def _current_process_identity_valid(bundle: Path, *, install_root: Path) -> bool:+ """Recognize the already-running canonical app without spawning a probe."""+ if sys.platform != "darwin":+ return False+ try:+ from Foundation import NSBundle # type: ignore[import-not-found]++ import jarvis.ui.web.launcher as launcher++ current = NSBundle.mainBundle()+ current_bundle = Path(str(current.bundlePath() or "")).resolve()+ launcher_file = Path(str(launcher.__file__ or "")).resolve()+ expected_root = install_root.resolve()+ return (+ str(current.bundleIdentifier() or "") == BUNDLE_ID+ and current_bundle == bundle.resolve()+ and launcher_file.is_file()+ and launcher_file.is_relative_to(expected_root / "jarvis" / "ui" / "web")+ )+ except (ImportError, OSError, TypeError, ValueError):+ return False+++def _install_native_bundle(install_root: Path, bundle: Path) -> Path:+ """Build beside the destination and replace it atomically with rollback."""+ parent = bundle.parent+ parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(prefix=".jarvis-py2app-", dir=parent) as raw_work:+ work = Path(raw_work)+ built = _build_py2app_alias(install_root, work)+ _sign_bundle(built)+ previous = work / "previous.app"+ if bundle.exists() or bundle.is_symlink():+ bundle.rename(previous)+ try:+ built.rename(bundle)+ if not macos_app_bundle_is_launchable(bundle):+ raise RuntimeError("the installed macOS application bundle is invalid")+ if not _runtime_identity_valid(bundle, install_root=install_root):+ raise RuntimeError("the installed app reported an unexpected runtime identity")+ except Exception:+ _remove_path(bundle)+ if previous.exists() or previous.is_symlink():+ previous.rename(bundle)+ raise+ return bundle++def ensure_macos_app_bundle(*,install_dir: Path | None = None,applications_dir: Path | None = None,) -> Path | None:- """Write (or refresh) ``~/Applications/Personal Jarvis.app``.+ """Ensure ``~/Applications/Personal Jarvis.app`` has a stable identity.- Returns the bundle path, or ``None`` off darwin (unless- ``applications_dir`` is injected — the cross-platform test seam).- Never raises: a failed bundle write is logged and returns ``None`` —- the app itself keeps working, only rediscovery stays terminal-based.+ A valid existing bundle is preserved byte-for-byte so normal source+ updates cannot churn its local TCC identity. Off macOS, this is a no-op+ unless a caller explicitly injects an applications directory for tests."""if applications_dir is None:if sys.platform != "darwin":@@ -125,70 +443,38 @@ def ensure_macos_app_bundle(return Noneapplications_dir = Path.home() / "Applications"try:- install_root = install_dir or _default_install_dir()- python = _venv_python(install_root)-- bundle = applications_dir / APP_DIR_NAME- contents = bundle / "Contents"- macos_dir = contents / "MacOS"- resources = contents / "Resources"- macos_dir.mkdir(parents=True, exist_ok=True)- resources.mkdir(parents=True, exist_ok=True)-- exe = macos_dir / _EXECUTABLE_NAME- exe.write_text(- "#!/bin/bash\n"- "# Launches the Personal Jarvis desktop app from its install venv.\n"- f'exec "{python}" -m jarvis.ui.web.launcher "$@"\n',- encoding="utf-8",- )- exe.chmod(- exe.stat().st_mode- | stat.S_IXUSR- | stat.S_IXGRP- | stat.S_IXOTH- )-- info: dict[str, object] = {- "CFBundleName": APP_NAME,- "CFBundleDisplayName": APP_NAME,- "CFBundleIdentifier": BUNDLE_ID,- "CFBundleExecutable": _EXECUTABLE_NAME,- "CFBundlePackageType": "APPL",- "CFBundleShortVersionString": _version(),- "CFBundleVersion": _version(),- "LSMinimumSystemVersion": "11.0",- "NSHighResolutionCapable": True,- "NSMicrophoneUsageDescription": _MIC_USAGE,- "NSAppleEventsUsageDescription": _APPLE_EVENTS_USAGE,- }- icon_stem = _try_build_icns(resources)- if icon_stem is not None:- info["CFBundleIconFile"] = icon_stem-- with (contents / "Info.plist").open("wb") as fh:- plistlib.dump(info, fh)-- log.info("macOS app bundle written: %s", bundle)- return bundle- except Exception as exc: # noqa: BLE001 — rediscovery nicety, never fatal+ install_root = (install_dir or _default_install_dir()).resolve()+ bundle = macos_app_bundle_path(applications_dir=applications_dir)+ if macos_app_bundle_is_launchable(bundle):+ if _current_process_identity_valid(+ bundle, install_root=install_root+ ) or _runtime_identity_valid(bundle, install_root=install_root):+ return bundle+ log.warning(+ "Existing macOS bundle failed its runtime/import probe; rebuilding: %s",+ bundle,+ )+ if sys.platform != "darwin":+ return _write_cross_platform_fixture_bundle(bundle)+ installed = _install_native_bundle(install_root, bundle)+ log.info("Native macOS app bundle installed: %s", installed)+ return installed+ except Exception as exc: # noqa: BLE001 - installer consumes the None resultlog.warning("macOS app bundle could not be written: %s", exc)return Nonedef remove_macos_app_bundle(*, applications_dir: Path | None = None) -> bool:- """Delete the bundle (uninstall path). Returns True when it is gone."""+ """Delete the bundle on uninstall and report whether it is gone."""if applications_dir is None:if sys.platform != "darwin":return Trueapplications_dir = Path.home() / "Applications"- bundle = applications_dir / APP_DIR_NAME- if not bundle.exists():+ bundle = macos_app_bundle_path(applications_dir=applications_dir)+ if not bundle.exists() and not bundle.is_symlink():return Truetry:- import shutil-- shutil.rmtree(bundle)+ _remove_path(bundle)log.info("macOS app bundle removed: %s", bundle)return Trueexcept OSError as exc:@@ -201,5 +487,8 @@ __all__ = ["APP_NAME","BUNDLE_ID","ensure_macos_app_bundle",+ "macos_app_bundle_is_launchable",+ "macos_app_bundle_path",+ "macos_launch_services_command","remove_macos_app_bundle",]diff --git a/jarvis/setup/macos_launcher_entry.py b/jarvis/setup/macos_launcher_entry.pynew file mode 100644index 0000000000..49b7b79fe6--- /dev/null+++ b/jarvis/setup/macos_launcher_entry.py@@ -0,0 +1,73 @@+"""Native-bundle entry point for installer-managed macOS applications.++py2app's alias launcher embeds the active Python runtime in the Mach-O app+process and then executes this source file in place. Keeping the code outside+the bundle lets normal source updates apply without rebuilding or changing the+TCC identity of the installed application.+"""++from __future__ import annotations++import json+import os+import platform+import sys+from importlib import import_module+from pathlib import Path+++def _write_identity_probe(destination: Path) -> int:+ """Record the native identity and managed-checkout import target."""+ try:+ from Foundation import NSBundle++ bundle = NSBundle.mainBundle()+ # Import the real launcher without starting it. A py2app alias can+ # retain a valid Mach-O signature while its editable environment has+ # become unusable (for example after a Python/venv replacement). The+ # installer probe must catch that before preserving the old bundle.+ launcher = import_module("jarvis.ui.web.launcher")+ install_root = Path(__file__).resolve().parents[2]+ payload = {+ "bundle_id": str(bundle.bundleIdentifier() or ""),+ "bundle_path": str(bundle.bundlePath() or ""),+ "executable": str(bundle.executablePath() or ""),+ "launcher_file": str(getattr(launcher, "__file__", "") or ""),+ "install_root": str(install_root),+ "python_version": f"{sys.version_info.major}.{sys.version_info.minor}",+ "machine": platform.machine(),+ }+ destination.write_text(json.dumps(payload, sort_keys=True), encoding="utf-8")+ except Exception as exc: # noqa: BLE001 - the installer treats this as failure+ payload = {"error": type(exc).__name__}+ destination.write_text(json.dumps(payload, sort_keys=True), encoding="utf-8")+ return 2+ return 0+++def main(argv: list[str] | None = None) -> int:+ """Start the desktop launcher from the installer-managed checkout."""+ arguments = list(sys.argv[1:] if argv is None else argv)+ try:+ probe_index = arguments.index("--jarvis-identity-probe")+ probe_path = Path(arguments[probe_index + 1])+ except (ValueError, IndexError):+ probe_path = None+ if probe_path is not None:+ return _write_identity_probe(probe_path)++ install_root = Path(__file__).resolve().parents[2]+ os.chdir(install_root)++ # Resolve the editable managed checkout only at runtime. Keeping this+ # import dynamic prevents the alias builder from trying to package the+ # entire editable distribution into the identity-only launcher.+ launch_desktop = import_module("jarvis.ui.web.launcher").main+ return launch_desktop()+++if __name__ == "__main__":+ raise SystemExit(main())+++__all__ = ["main"]diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 79461c6262..99495d0e19 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -62,6 +62,27 @@ WINDOW_TITLE = "Personal Jarvis"_LOCK_ACQUIRE_TIMEOUT = 0.0+def _local_voice_permission_granted(+ *,+ platform_name: str | None = None,+ permission_port: 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":+ return True+ from jarvis.platform.permissions import (+ PermissionId,+ get_system_permission_port,+ )++ port = permission_port or get_system_permission_port()+ try:+ return bool(port.runtime_access_granted(PermissionId.MICROPHONE))+ except Exception: # noqa: BLE001 - protected capture must fail closed+ return False++def _supported_call_kwargs(function: Callable[..., Any],kwargs: dict[str, Any],@@ -320,6 +341,65 @@ def focus_existing_instance_robust() -> bool:return _bring_window_to_front_by_title(WINDOW_TITLE) or focused+def _force_foreground_hwnd(hwnd: int, user32: Any, kernel32: Any) -> bool:+ """Raise one HWND through Windows' foreground-lock restriction.++ ``SetForegroundWindow`` commonly returns false when the request originates+ from the desktop server thread rather than recent user input. Attaching the+ caller's input queue to both the current foreground and target threads is+ the supported recovery. Every attachment is detached in ``finally`` so a+ failed focus attempt cannot poison keyboard routing.+ """+ user32.ShowWindow(hwnd, 9) # SW_RESTORE+ if user32.SetForegroundWindow(hwnd):+ user32.SetActiveWindow(hwnd)+ if user32.GetForegroundWindow() == hwnd:+ return True++ current_thread = kernel32.GetCurrentThreadId()+ foreground = user32.GetForegroundWindow()+ foreground_thread = (+ user32.GetWindowThreadProcessId(foreground, None) if foreground else 0+ )+ target_thread = user32.GetWindowThreadProcessId(hwnd, None)+ attached_foreground = False+ attached_target = False+ try:+ if foreground_thread and foreground_thread != current_thread:+ attached_foreground = bool(+ user32.AttachThreadInput(+ current_thread, foreground_thread, True+ )+ )+ if target_thread and target_thread not in (+ current_thread,+ foreground_thread,+ ):+ attached_target = bool(+ user32.AttachThreadInput(current_thread, target_thread, True)+ )+ user32.BringWindowToTop(hwnd)+ user32.ShowWindow(hwnd, 9) # SW_RESTORE+ user32.SetForegroundWindow(hwnd)+ user32.SetActiveWindow(hwnd)+ if user32.GetForegroundWindow() == hwnd:+ return True++ # UIPI or another foreground transition can still reject activation.+ # A short topmost pulse at least makes the already-visible window+ # discoverable, then immediately restores its normal z-order policy.+ flags = 0x0001 | 0x0002 | 0x0040 # NOMOVE | NOSIZE | SHOWWINDOW+ user32.SetWindowPos(hwnd, -1, 0, 0, 0, 0, flags) # HWND_TOPMOST+ user32.SetWindowPos(hwnd, -2, 0, 0, 0, 0, flags) # HWND_NOTOPMOST+ user32.SetForegroundWindow(hwnd)+ return user32.GetForegroundWindow() == hwnd+ finally:+ if attached_foreground:+ user32.AttachThreadInput(current_thread, foreground_thread, False)+ if attached_target:+ user32.AttachThreadInput(current_thread, target_thread, False)++def _bring_window_to_front_by_title(title: str) -> bool:"""Win32 fallback for hidden/minimized pywebview windows.@@ -352,6 +432,25 @@ def _bring_window_to_front_by_title(title: str) -> bool:user32.BringWindowToTop.argtypes = [wintypes.HWND]user32.SetForegroundWindow.argtypes = [wintypes.HWND]user32.SetActiveWindow.argtypes = [wintypes.HWND]+ user32.GetWindowThreadProcessId.argtypes = [+ wintypes.HWND,+ ctypes.POINTER(wintypes.DWORD),+ ]+ user32.GetWindowThreadProcessId.restype = wintypes.DWORD+ user32.AttachThreadInput.argtypes = [+ wintypes.DWORD,+ wintypes.DWORD,+ wintypes.BOOL,+ ]+ user32.SetWindowPos.argtypes = [+ wintypes.HWND,+ wintypes.HWND,+ ctypes.c_int,+ ctypes.c_int,+ ctypes.c_int,+ ctypes.c_int,+ wintypes.UINT,+ ]hwnd = user32.FindWindowW(None, title)if not hwnd:return False@@ -376,10 +475,7 @@ def _bring_window_to_front_by_title(title: str) -> bool:if width > 5000 or height > 5000:width, height = 1280, 800user32.MoveWindow(hwnd, 80, 60, width, height, True)- user32.BringWindowToTop(hwnd)- user32.SetForegroundWindow(hwnd)- user32.SetActiveWindow(hwnd)- return True+ return _force_foreground_hwnd(hwnd, user32, ctypes.windll.kernel32)except Exception: # noqa: BLE001return False@@ -860,7 +956,10 @@ class DesktopApp:else:from jarvis.ui.web.fast_bootstrap import FastBootstrap- bootstrap = FastBootstrap()+ bootstrap = FastBootstrap(+ session_token=self.session_token,+ vite_dev_url=(self.cfg.ui.vite_dev_url if self.cfg.ui.dev_mode else None),+ )loop.run_until_complete(bootstrap.serve("127.0.0.1", self.cfg.ui.admin_api_port))@@ -2279,6 +2378,32 @@ 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()++ def voice_activation_gate() -> bool:+ return _local_voice_permission_granted(+ platform_name=sys.platform,+ permission_port=permission_port,+ )++ 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."+ )+# On-screen overlay in its own Tk daemon thread — the bus bridge reacts# to SystemStateChanged and drives whichever surface is selected.# Style is chosen by [ui].orb_style: "jarvis_bar" (slim default),@@ -2680,7 +2805,7 @@ class DesktopApp:output_device=self.cfg.audio.output_device or None,config=self.cfg,vision_provider=voice_vision,- activation_gate=lambda: True,+ activation_gate=voice_activation_gate,ack_brain=voice_ack_brain,# Resolved custom-wake-word plan: drives the OWW model + the# phrase matcher for the verifier + rolling-whisper.@@ -3007,21 +3132,28 @@ class DesktopApp:desktop._window.show()desktop._window.restore()desktop._window_visible = True- _bring_window_to_front_by_title(WINDOW_TITLE)+ focused = _bring_window_to_front_by_title(WINDOW_TITLE)# Restore the persistent bar if a prior minimise cleared it.desktop._restore_overlay_for_visible_window()- return {"ok": True, "focused": True}+ if focused:+ return {"ok": True, "focused": True}+ return {+ "ok": False,+ "focused": False,+ "reason": "foreground_lock",+ }except Exception as exc: # noqa: BLE001return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}# ---- WebView hooks -------------------------------------------------------def _inject_token(self, window: Any) -> None:- """Sets ``window.__JARVIS_TOKEN`` in the frontend via ``evaluate_js``.+ """Offer the one-time process token to the UI session exchange.- Called by ``webview.start(func=..., args=...)`` once the window is- ready. Must be robust against reloads — the frontend reads the- token on its first WS connect.+ The static shell is intentionally public and receives no credential.+ This late WebView hook dispatches an event that ``AuthGate`` exchanges+ once for an HttpOnly cookie and then clears; sockets never put either+ token in a URL.This is also where the taskbar/titlebar icon gets set. pywebviewdoes not expose an icon parameter on Windows — we go through the@@ -3029,12 +3161,14 @@ class DesktopApp:single-instance lock)."""token_literal = json.dumps(self.session_token)- js = f"window.__JARVIS_TOKEN = {token_literal};"+ js = (+ f"window.__JARVIS_TOKEN = {token_literal};"+ "window.dispatchEvent(new Event('jarvis-token-ready'));"+ )try:window.evaluate_js(js)except Exception: # noqa: BLE001- # Not a fatal error — the frontend can fall back to fetching the- # token via the ``?token=`` URL or /api/ui/bootstrap.+ # Not fatal: the local control key can still unlock AuthGate.passtry:diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsxnew file mode 100644index 0000000000..0cbd053c16--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx@@ -0,0 +1,54 @@+import { expect, it } from "vitest";+import type { PermissionSnapshot } from "@/hooks/usePermissions";+import { permissionSnapshotReady } from "./PermissionsStep";++const IDS = [+ "microphone",+ "screen_recording",+ "accessibility",+ "input_monitoring",+ "event_posting",+] as const;++function macSnapshot(overrides: Partial<PermissionSnapshot> = {}): PermissionSnapshot {+ return {+ platform: "darwin",+ supported: true,+ headless: false,+ app_identity: { stable: true },+ permissions: IDS.map((id) => ({+ id,+ status: "granted",+ required: [],+ can_request: false,+ can_open_settings: true,+ restart_required: false,+ })),+ features: {},+ restart_required: false,+ ...overrides,+ };+}++it("accepts a complete stable macOS permission snapshot", () => {+ expect(permissionSnapshotReady(macSnapshot())).toBe(true);+});++it("fails closed for an unstable macOS app identity", () => {+ expect(+ permissionSnapshotReady(macSnapshot({ app_identity: { stable: false } })),+ ).toBe(false);+});++it("fails closed for an empty or incomplete macOS permission list", () => {+ expect(permissionSnapshotReady(macSnapshot({ permissions: [] }))).toBe(false);+ expect(+ permissionSnapshotReady(macSnapshot({ permissions: macSnapshot().permissions.slice(1) })),+ ).toBe(false);+});++it("accepts supported non-macOS platforms without TCC grants", () => {+ expect(permissionSnapshotReady(macSnapshot({ platform: "linux", permissions: [] }))).toBe(true);+ expect(permissionSnapshotReady(macSnapshot({ platform: "win32", permissions: [] }))).toBe(true);+ expect(permissionSnapshotReady(macSnapshot({ platform: "unknown", permissions: [] }))).toBe(false);+});diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsxnew file mode 100644index 0000000000..35e36fce8e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsx@@ -0,0 +1,78 @@+import { ShieldCheck } from "lucide-react";+import { useCallback, useState } from "react";+import { Button } from "@/components/ui/button";+import type { PermissionId, PermissionSnapshot } from "@/hooks/usePermissions";+import { useT } from "@/i18n";+import { PermissionRows } from "@/views/settings/PermissionsPanel";+import type { StepProps } from "../OnboardingFlow";++const EXPECTED_MACOS_PERMISSIONS = new Set<PermissionId>([+ "microphone",+ "screen_recording",+ "accessibility",+ "input_monitoring",+ "event_posting",+]);++export function permissionSnapshotReady(snapshot: PermissionSnapshot | null): boolean {+ if (!snapshot) return false;+ if (snapshot.platform === "linux" || snapshot.platform === "win32") return true;+ if (snapshot.platform !== "darwin") return false;+ if (snapshot.app_identity.stable !== true || snapshot.restart_required) return false;+ if (snapshot.permissions.length !== EXPECTED_MACOS_PERMISSIONS.size) return false;++ const observed = new Set(snapshot.permissions.map((item) => item.id));+ if (+ observed.size !== EXPECTED_MACOS_PERMISSIONS.size ||+ [...EXPECTED_MACOS_PERMISSIONS].some((id) => !observed.has(id))+ ) {+ return false;+ }+ return snapshot.permissions.every((item) =>+ ["granted", "not_required"].includes(item.status),+ );+}++export function PermissionsStep({ goNext, skip }: StepProps) {+ const t = useT();+ const [allReady, setAllReady] = useState(false);+ const onSnapshot = useCallback((snapshot: PermissionSnapshot | null) => {+ setAllReady(permissionSnapshotReady(snapshot));+ }, []);++ return (+ <div className="flex flex-col gap-4">+ <div className="flex items-center gap-3">+ <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 text-primary">+ <ShieldCheck className="h-5 w-5" />+ </div>+ <div>+ <h2 className="font-display text-lg font-semibold">+ {t("onboarding.permissions.title")}+ </h2>+ <p className="text-sm text-muted-foreground">+ {t("onboarding.permissions.body")}+ </p>+ </div>+ </div>++ <PermissionRows compact onSnapshot={onSnapshot} />++ <p className="text-xs text-muted-foreground">+ {t("onboarding.permissions.privacy_note")}+ </p>+ <Button className="w-full" disabled={!allReady} onClick={goNext}>+ {t("onboarding.permissions.continue")}+ </Button>+ {!allReady && (+ <button+ type="button"+ className="text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground"+ onClick={skip}+ >+ {t("onboarding.permissions.text_only")}+ </button>+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/hooks/usePermissions.test.tsx b/jarvis/ui/web/frontend/src/hooks/usePermissions.test.tsxnew file mode 100644index 0000000000..e97f0c8351--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/usePermissions.test.tsx@@ -0,0 +1,80 @@+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { usePermissions, type PermissionSnapshot } from "./usePermissions";++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,+ 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");+});diff --git a/jarvis/ui/web/frontend/src/hooks/usePermissions.ts b/jarvis/ui/web/frontend/src/hooks/usePermissions.tsnew file mode 100644index 0000000000..981e808325--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/usePermissions.ts@@ -0,0 +1,174 @@+import { useCallback, useEffect, useMemo, useState } from "react";++export type PermissionId =+ | "microphone"+ | "screen_recording"+ | "accessibility"+ | "input_monitoring"+ | "event_posting";++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;+ restart_required: boolean;+ detail?: string | null;+}++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>;+ restart_required: boolean;+}++const EMPTY_SNAPSHOT: PermissionSnapshot = {+ platform: "unknown",+ supported: false,+ headless: false,+ app_identity: {},+ permissions: [],+ features: {},+ 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 refetch = useCallback(async () => {+ try {+ const payload = await readJson(await fetch("/api/permissions/status"));+ setSnapshot(normalizeSnapshot(payload));+ setError(null);+ } catch (exc) {+ setError(exc instanceof Error ? exc.message : String(exc));+ } finally {+ setLoading(false);+ }+ }, []);++ const mutate = useCallback(+ async (id: PermissionId, action: "request" | "open-settings") => {+ setPendingId(id);+ try {+ const payload = await readJson(+ await fetch(`/api/permissions/${id}/${action}?dry_run=false`, {+ method: "POST",+ }),+ );+ setSnapshot(normalizeSnapshot(payload));+ setError(null);+ } catch (exc) {+ setError(exc instanceof Error ? exc.message : String(exc));+ throw exc;+ } finally {+ setPendingId(null);+ }+ },+ [],+ );++ useEffect(() => {+ void 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]);++ return {+ snapshot,+ loading,+ error,+ pendingId,+ refetch,+ request: (id: PermissionId) => mutate(id, "request"),+ openSettings: (id: PermissionId) => mutate(id, "open-settings"),+ };+}diff --git a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.test.tsx b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.test.tsxnew file mode 100644index 0000000000..501a12262a--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.test.tsx@@ -0,0 +1,58 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++const request = vi.fn();+const openSettings = vi.fn();++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: {+ platform: "darwin",+ app_identity: { stable: true },+ permissions: [+ {+ id: "screen_recording",+ status: "not_granted",+ required: ["computer_use"],+ can_request: true,+ can_open_settings: true,+ restart_required: false,+ },+ ],+ restart_required: false,+ },+ loading: false,+ error: null,+ pendingId: null,+ refetch: vi.fn(),+ request,+ openSettings,+ }),+}));++import { PermissionRows } from "./PermissionsPanel";++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("PermissionRows", () => {+ it("keeps System Settings available when a native request can also run", () => {+ render(<PermissionRows />);++ expect(screen.getByRole("button", { name: "permissions.request" })).toBeDefined();+ expect(+ screen.getByRole("button", { name: "permissions.open_settings" }),+ ).toBeDefined();+ });+});diff --git a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsxnew file mode 100644index 0000000000..e7d22e068c--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx@@ -0,0 +1,218 @@+import {+ Accessibility,+ CheckCircle2,+ CircleAlert,+ Keyboard,+ Loader2,+ Mic,+ Monitor,+ MousePointer2,+ RefreshCw,+ ShieldCheck,+} 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,+} from "@/hooks/usePermissions";+import { SettingsBlock } from "@/views/settings/SettingsBlock";++const ICONS = {+ microphone: Mic,+ screen_recording: Monitor,+ accessibility: Accessibility,+ input_monitoring: Keyboard,+ event_posting: MousePointer2,+} satisfies Record<PermissionId, typeof Mic>;++const READY_STATES = new Set(["granted", "not_required"]);++export function PermissionRows({+ compact = false,+ onSnapshot,+}: {+ compact?: 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 } =+ 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 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/40 p-3 text-xs text-muted-foreground">+ <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-emerald-500" />+ {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 border border-amber-500/40 bg-amber-500/5 p-3 text-xs text-amber-500">+ <CircleAlert className="mt-0.5 h-4 w-4 shrink-0" />+ {t("permissions.identity_warning")}+ </div>+ )}+ {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))}+ />+ ))}+ {snapshot?.restart_required && (+ <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-amber-500/40 bg-amber-500/5 p-3">+ <p className="text-xs text-amber-500">{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>+ );+}++function PermissionRow({+ item,+ busy,+ compact,+ onRequest,+ onOpenSettings,+}: {+ item: PermissionItem;+ busy: boolean;+ compact: boolean;+ onRequest: () => void;+ onOpenSettings: () => 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;++ return (+ <div className={`rounded-lg border border-border bg-background/40 ${compact ? "p-3" : "p-4"}`}>+ <div className="flex flex-wrap items-center gap-3">+ <Icon className="h-4 w-4 shrink-0 text-primary" />+ <div className="min-w-[12rem] flex-1">+ <div className="text-sm font-medium">{t(`permissions.items.${item.id}.title`)}</div>+ {!compact && (+ <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-[10px] font-medium uppercase tracking-wide ${+ ready+ ? "bg-emerald-500/10 text-emerald-500"+ : "bg-amber-500/10 text-amber-500"+ }`}+ >+ {t(`permissions.status.${item.status}`)}+ </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>+ )}+ </div>+ </div>+ );+}++export function PermissionsPanel() {+ const t = useT();+ return (+ <div className="mt-8 space-y-4">+ <h3 className="font-display text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ {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/permissions_routes.py b/jarvis/ui/web/permissions_routes.pynew file mode 100644index 0000000000..36eddf3b45--- /dev/null+++ b/jarvis/ui/web/permissions_routes.py@@ -0,0 +1,73 @@+"""Local-user API for macOS system-permission status and request flows."""++from __future__ import annotations++from typing import Any++from fastapi import APIRouter, Depends, Query, Request+from fastapi.responses import JSONResponse++from jarvis.platform.permissions import (+ PermissionId,+ SystemPermissionPort,+ get_system_permission_port,+)++from .control_auth import require_control_key_or_session++router = APIRouter(+ prefix="/api/permissions",+ tags=["permissions"],+ 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()++[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 _operation_response(payload: dict) -> Any:+ if payload["ok"]:+ return payload+ return JSONResponse(status_code=409, content=payload)+++ "/{permission_id}/request",+ summary="Request a system permission",+ openapi_extra={"x-jarvis-dangerous": True},+ response_model=None,+)+def request_permission(+ permission_id: PermissionId,+ request: Request,+ 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)+++ "/{permission_id}/open-settings",+ summary="Open a system permission settings pane",+ openapi_extra={"x-jarvis-dangerous": True},+ response_model=None,+)+def open_permission_settings(+ permission_id: PermissionId,+ 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)+++__all__ = ["router"]diff --git a/tests/unit/audio/test_capture_permission_gate.py b/tests/unit/audio/test_capture_permission_gate.pynew file mode 100644index 0000000000..7b280ae781--- /dev/null+++ b/tests/unit/audio/test_capture_permission_gate.py@@ -0,0 +1,90 @@+"""macOS microphone capture never discovers TCC access by opening a device."""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.audio import capture+from jarvis.core.protocols import AudioChunk+++class _Stream:+ def __init__(self) -> None:+ self.started = False+ self.stopped = False+ self.closed = False++ def start(self) -> None:+ self.started = True++ def stop(self) -> None:+ self.stopped = True++ def close(self) -> None:+ self.closed = True+++def test_macos_default_gate_uses_process_wide_permission_port(monkeypatch) -> None:+ import jarvis.platform.permissions as permissions++ 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()++ assert gate is not None and gate() is True+ assert calls == [permissions.PermissionId.MICROPHONE]+++async def test_denied_gate_fails_before_portaudio_open(monkeypatch) -> None:+ opens: list[object] = []++ def _input_stream(**_kwargs):+ opens.append(object())+ return _Stream()++ monkeypatch.setattr(capture, "sd", SimpleNamespace(InputStream=_input_stream))+ mic = capture.MicrophoneCapture(device=0, access_gate=lambda: False)++ with pytest.raises(capture.MicrophoneAccessError):+ await mic.__aenter__()++ assert opens == []+++async def test_live_revocation_stops_stream_and_closes_device(monkeypatch) -> None:+ allowed = True+ stream = _Stream()+ monkeypatch.setattr(+ capture,+ "sd",+ SimpleNamespace(InputStream=lambda **_kwargs: stream),+ )+ mic = capture.MicrophoneCapture(device=0, access_gate=lambda: allowed)++ with pytest.raises(capture.MicrophoneAccessError):+ async with mic:+ iterator = mic.stream()+ mic._safe_put(+ AudioChunk(+ pcm=b"\x00\x00",+ sample_rate=16_000,+ timestamp_ns=1,+ channels=1,+ )+ )+ assert (await anext(iterator)).timestamp_ns == 1+ allowed = False+ await anext(iterator)++ assert stream.started is True+ assert stream.stopped is True+ assert stream.closed is Truediff --git a/tests/unit/autostart/test_command.py b/tests/unit/autostart/test_command.pyindex 54ef292732..ff962ee613 100644--- a/tests/unit/autostart/test_command.py+++ b/tests/unit/autostart/test_command.py@@ -10,7 +10,8 @@ from jarvis.core.config import PROJECT_ROOTfrom .conftest import make_cfg-def test_args_target_the_full_voice_launcher() -> None:+def test_args_target_the_full_voice_launcher(monkeypatch) -> None:+ monkeypatch.setattr(sys, "platform", "linux")spec = resolve_launch_spec(make_cfg())assert spec.args == ("-m", LAUNCHER_MODULE)assert LAUNCHER_MODULE == "jarvis.ui.web.launcher"@@ -29,6 +30,40 @@ def test_program_is_python_on_posix(monkeypatch) -> None:assert spec.program == sys.executable+def test_program_uses_macos_bundle_identity(monkeypatch, tmp_path) -> None:+ import jarvis.setup.macos_app_bundle as bundle_module++ bundle = tmp_path / "Personal Jarvis.app"+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(bundle_module, "macos_app_bundle_path", lambda: bundle)+ monkeypatch.setattr(+ bundle_module, "macos_app_bundle_is_launchable", lambda _bundle: True+ )++ spec = resolve_launch_spec(make_cfg(start_minimized=True))++ assert spec.program == "/usr/bin/open"+ assert spec.args == ("-g", "-W", "-a", str(bundle))+++def test_program_fails_closed_to_launchservices_without_macos_bundle(+ monkeypatch, tmp_path+) -> None:+ import jarvis.setup.macos_app_bundle as bundle_module++ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(+ bundle_module,+ "macos_app_bundle_path",+ lambda: tmp_path / "missing.app",+ )++ spec = resolve_launch_spec(make_cfg(start_minimized=False))++ assert spec.program == "/usr/bin/open"+ assert spec.args == ("-W", "-a", str(tmp_path / "missing.app"))++def test_program_prefers_pythonw_on_windows(monkeypatch) -> None:monkeypatch.setattr(sys, "platform", "win32")monkeypatch.setattr(@@ -43,6 +78,7 @@ def test_minimized_follows_config() -> None:assert resolve_launch_spec(make_cfg(start_minimized=True)).minimized is True-def test_command_line_joins_program_and_args() -> None:+def test_command_line_joins_program_and_args(monkeypatch) -> None:+ monkeypatch.setattr(sys, "platform", "linux")spec = resolve_launch_spec(make_cfg())assert spec.command_line().endswith("-m jarvis.ui.web.launcher")diff --git a/tests/unit/autostart/test_macos.py b/tests/unit/autostart/test_macos.pyindex ddf893b5ba..2f8ba48e16 100644--- a/tests/unit/autostart/test_macos.py+++ b/tests/unit/autostart/test_macos.py@@ -14,10 +14,10 @@ from jarvis.autostart.macos import MacOSAutostartfrom jarvis.autostart.protocol import LaunchSpec-def _spec(program: str = "/usr/bin/python3", working_dir: str = "/Users/u/jarvis") -> LaunchSpec:+def _spec(program: str = "/usr/bin/open", working_dir: str = "/Users/u/jarvis") -> LaunchSpec:return LaunchSpec(program=program,- args=("-m", "jarvis.ui.web.launcher"),+ args=("-W", "-a", "/Users/u/Applications/Personal Jarvis.app"),working_dir=working_dir,minimized=True,)@@ -33,8 +33,14 @@ def test_install_writes_launchagent_plist(monkeypatch, tmp_path: Path) -> None:with plist_path.open("rb") as fh:data = plistlib.load(fh)assert data["Label"] == "com.personal-jarvis.autostart"- assert data["ProgramArguments"] == ["/usr/bin/python3", "-m", "jarvis.ui.web.launcher"]+ assert data["ProgramArguments"] == [+ "/usr/bin/open",+ "-W",+ "-a",+ "/Users/u/Applications/Personal Jarvis.app",+ ]assert data["RunAtLoad"] is True+ assert data["LimitLoadToSessionType"] == "Aqua"assert status.matches_spec is True@@ -45,6 +51,20 @@ def test_status_detects_drift(monkeypatch, tmp_path: Path) -> None:assert mgr.status(_spec(program="/new/python3")).matches_spec is False+def test_status_refreshes_legacy_non_aqua_entry(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)+ mgr = MacOSAutostart()+ mgr.install(_spec())+ plist_path = tmp_path / "com.personal-jarvis.autostart.plist"+ with plist_path.open("rb") as fh:+ data = plistlib.load(fh)+ data.pop("LimitLoadToSessionType")+ with plist_path.open("wb") as fh:+ plistlib.dump(data, fh)++ assert mgr.status(_spec()).matches_spec is False++def test_uninstall_removes_plist(monkeypatch, tmp_path: Path) -> None:monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)mgr = MacOSAutostart()diff --git a/tests/unit/cli_ctl/test_commands_permissions.py b/tests/unit/cli_ctl/test_commands_permissions.pynew file mode 100644index 0000000000..faa4c2b32f--- /dev/null+++ b/tests/unit/cli_ctl/test_commands_permissions.py@@ -0,0 +1,112 @@+from __future__ import annotations++from types import SimpleNamespace++from typer.testing import CliRunner++from jarvis.cli_ctl.__main__ import app++runner = CliRunner()+++def test_status_reads_fresh_snapshot(capture_api):+ result = runner.invoke(app, ["permissions", "status"])+ assert result.exit_code == 0+ call = capture_api["calls"][-1]+ assert call["method"] == "GET"+ assert call["path"] == "/api/permissions/status"+++def test_request_requires_yes(capture_api):+ result = runner.invoke(app, ["permissions", "request", "microphone"])+ assert result.exit_code == 1+ assert capture_api["calls"] == []+++def test_request_with_yes_uses_permission_path(capture_api):+ result = runner.invoke(+ app, ["permissions", "request", "screen_recording", "--yes"]+ )+ assert result.exit_code == 0+ call = capture_api["calls"][-1]+ assert call["method"] == "POST"+ assert call["path"] == "/api/permissions/screen_recording/request"+++def test_request_activates_app_after_confirmation(monkeypatch, capture_api):+ calls: list[str] = []+ monkeypatch.setattr(+ "jarvis.cli_ctl.commands.permissions._activate_macos_app_for_tcc",+ lambda: calls.append("activate"),+ )++ result = runner.invoke(+ app, ["permissions", "request", "screen_recording", "--yes"]+ )++ assert result.exit_code == 0+ assert calls == ["activate"]+++def test_open_settings_with_yes_uses_permission_path(capture_api):+ result = runner.invoke(+ app, ["permissions", "open-settings", "accessibility", "--yes"]+ )+ assert result.exit_code == 0+ call = capture_api["calls"][-1]+ assert call["method"] == "POST"+ assert call["path"] == "/api/permissions/accessibility/open-settings"+++def test_request_dry_run_sends_nothing(capture_api):+ result = runner.invoke(+ app, ["--json", "permissions", "request", "microphone", "--dry-run"]+ )+ assert result.exit_code == 0+ assert capture_api["calls"] == []+ assert "dry_run" in result.stdout+++def test_request_dry_run_does_not_activate_app(monkeypatch, capture_api):+ calls: list[str] = []+ monkeypatch.setattr(+ "jarvis.cli_ctl.commands.permissions._activate_macos_app_for_tcc",+ lambda: calls.append("activate"),+ )++ result = runner.invoke(+ app, ["permissions", "request", "microphone", "--dry-run"]+ )++ assert result.exit_code == 0+ assert calls == []+ assert capture_api["calls"] == []+++def test_macos_activation_targets_canonical_bundle_and_waits_for_identity(+ monkeypatch, tmp_path+):+ 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)+ workspace = SimpleNamespace(frontmostApplication=lambda: frontmost)+ appkit = SimpleNamespace(+ NSWorkspace=SimpleNamespace(sharedWorkspace=lambda: workspace)+ )+ monkeypatch.setattr(module, "detect_platform", lambda: "darwin")+ monkeypatch.setattr(module, "_installed_macos_app", lambda: bundle)+ monkeypatch.setattr(+ module.subprocess,+ "run",+ lambda command, **_kwargs: (+ commands.append(command) or SimpleNamespace(returncode=0)+ ),+ )+ monkeypatch.setattr(module.importlib, "import_module", lambda _name: appkit)++ module._activate_macos_app_for_tcc()++ assert commands == [["open", str(bundle)]]diff --git a/tests/unit/platform/test_permissions.py b/tests/unit/platform/test_permissions.pynew file mode 100644index 0000000000..e87f9fb659--- /dev/null+++ b/tests/unit/platform/test_permissions.py@@ -0,0 +1,415 @@+"""Unit coverage for the uncached macOS system-permission port."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.platform.permissions import (+ EXPECTED_BUNDLE_ID,+ PermissionId,+ PermissionState,+ SystemPermissionPort,+)+from jarvis.setup.macos_app_bundle import BUNDLE_ID+++class _Bundle:+ def __init__(self, bundle_id: str | None = EXPECTED_BUNDLE_ID) -> None:+ self._bundle_id = bundle_id++ def bundleIdentifier(self) -> str | None:+ return self._bundle_id++ def bundlePath(self) -> str:+ return str(Path.home() / "Applications" / "Personal Jarvis.app")+++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+++class _Workspace:+ def __init__(self, current: _RunningApp) -> None:+ self.current = current+ self.opened_urls: list[str] = []++ def frontmostApplication(self) -> _RunningApp:+ return self.current++ def openURL_(self, url: str) -> bool:+ self.opened_urls.append(url)+ return True+++class _CaptureDevice:+ status = 3+ requests = 0++ @classmethod+ def authorizationStatusForMediaType_(cls, _media_type: str) -> int:+ return cls.status++ @classmethod+ def requestAccessForMediaType_completionHandler_(cls, _media_type, callback):+ cls.requests += 1+ callback(True)+++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)+ workspace = _Workspace(current)+ screen = {"granted": False, "requested": False}+ event = {"listen": False, "post": False}+ ax = {"trusted": True, "prompted": False}++ def request_screen() -> bool:+ screen["requested"] = True+ screen["granted"] = True+ return True++ def request_listen() -> bool:+ event["listen"] = True+ return True++ def request_post() -> bool:+ event["post"] = True+ return True++ def request_ax(options: dict[str, bool]) -> bool:+ ax["prompted"] = bool(options["prompt"])+ return ax["trusted"]++ modules = {+ "Foundation": SimpleNamespace(+ NSBundle=SimpleNamespace(mainBundle=lambda: _Bundle(bundle_id)),+ NSURL=SimpleNamespace(URLWithString_=lambda value: value),+ ),+ "AppKit": SimpleNamespace(+ NSWorkspace=SimpleNamespace(sharedWorkspace=lambda: workspace),+ NSRunningApplication=SimpleNamespace(currentApplication=lambda: current),+ ),+ "AVFoundation": SimpleNamespace(+ AVCaptureDevice=_CaptureDevice,+ AVMediaTypeAudio="audio",+ AVAuthorizationStatusNotDetermined=0,+ AVAuthorizationStatusRestricted=1,+ AVAuthorizationStatusDenied=2,+ AVAuthorizationStatusAuthorized=3,+ ),+ "Quartz": SimpleNamespace(+ CGPreflightScreenCaptureAccess=lambda: screen["granted"],+ CGRequestScreenCaptureAccess=request_screen,+ CGPreflightListenEventAccess=lambda: event["listen"],+ CGRequestListenEventAccess=request_listen,+ CGPreflightPostEventAccess=lambda: event["post"],+ CGRequestPostEventAccess=request_post,+ ),+ "ApplicationServices": SimpleNamespace(+ AXIsProcessTrusted=lambda: ax["trusted"],+ AXIsProcessTrustedWithOptions=request_ax,+ kAXTrustedCheckOptionPrompt="prompt",+ ),+ }+ return modules, screen, workspace+++def _port(modules: dict[str, object]) -> SystemPermissionPort:+ def load(name: str) -> object:+ if name not in modules:+ raise ModuleNotFoundError(name)+ return modules[name]++ return SystemPermissionPort(platform_name="darwin", module_loader=load)+++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 test_matching_bundle_id_at_noncanonical_path_is_not_stable(tmp_path: Path) -> None:+ modules, _, _ = _native_modules()+ copied_bundle = SimpleNamespace(+ bundleIdentifier=lambda: EXPECTED_BUNDLE_ID,+ bundlePath=lambda: str(tmp_path / "Personal Jarvis.app"),+ )+ modules["Foundation"].NSBundle = SimpleNamespace(+ mainBundle=lambda: copied_bundle+ )++ assert _port(modules).snapshot()["app_identity"]["stable"] is False+++def test_non_macos_degrades_to_not_required_without_native_imports() -> None:+ imports: list[str] = []+ port = SystemPermissionPort(+ platform_name="win32", module_loader=lambda name: imports.append(name)+ )++ snapshot = port.snapshot()++ 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())+++def test_snapshot_maps_native_states_and_feature_readiness() -> None:+ _CaptureDevice.status = 3+ modules, _, _ = _native_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,+ }+ assert snapshot["features"]["computer_use"] == {+ "ready": False,+ "missing": ["screen_recording", "event_posting"],+ "identity_ready": True,+ "restart_required": False,+ }+++def test_snapshot_is_uncached() -> None:+ modules, screen, _ = _native_modules()+ port = _port(modules)++ assert _permission(port.snapshot(), PermissionId.SCREEN_RECORDING)["status"] == "not_granted"+ screen["granted"] = True+ assert _permission(port.snapshot(), PermissionId.SCREEN_RECORDING)["status"] == "granted"+++def test_state_probes_only_the_requested_permission() -> None:+ _CaptureDevice.status = 3+ modules, _, _ = _native_modules()+ imports: list[str] = []++ def load(name: str) -> object:+ imports.append(name)+ return modules[name]++ port = SystemPermissionPort(platform_name="darwin", module_loader=load)++ assert port.state("microphone") is PermissionState.GRANTED+ assert imports == ["AVFoundation"]+++def test_runtime_access_requires_stable_identity_and_fresh_grant() -> None:+ _CaptureDevice.status = 3+ modules, _, _ = _native_modules()+ stable = _port(modules)+ unstable_modules, _, _ = _native_modules(bundle_id="org.python.python")++ assert stable.runtime_access_granted(PermissionId.MICROPHONE) is True+ assert (+ _port(unstable_modules).runtime_access_granted(PermissionId.MICROPHONE)+ is False+ )+ _CaptureDevice.status = 2+ assert stable.runtime_access_granted(PermissionId.MICROPHONE) is False+++def test_runtime_access_blocks_pending_restart_even_after_native_grant() -> None:+ modules, _, _ = _native_modules()+ port = _port(modules)++ result = port.request(PermissionId.SCREEN_RECORDING)++ assert result.ok is True+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.GRANTED+ assert port.runtime_access_granted(PermissionId.SCREEN_RECORDING) is False+++def test_microphone_status_distinguishes_denied_and_restricted() -> None:+ modules, _, _ = _native_modules()+ port = _port(modules)++ _CaptureDevice.status = 2+ denied = _permission(port.snapshot(), 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+++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_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+++def test_request_microphone_uses_avfoundation_callback_api() -> None:+ _CaptureDevice.status = 0+ _CaptureDevice.requests = 0+ modules, _, _ = _native_modules()++ result = _port(modules).request(PermissionId.MICROPHONE)++ assert result.ok is True+ assert result.performed is True+ assert result.restart_required is False+ assert _CaptureDevice.requests == 1+++def test_request_accessibility_uses_prompt_option() -> None:+ modules, _, _ = _native_modules()+ calls: list[dict[str, bool]] = []+ modules["ApplicationServices"] = SimpleNamespace(+ AXIsProcessTrusted=lambda: False,+ AXIsProcessTrustedWithOptions=lambda options: calls.append(options),+ kAXTrustedCheckOptionPrompt="prompt",+ )++ result = _port(modules).request(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 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:+ modules, _, _ = _native_modules()+ calls: list[str] = []+ setattr(modules["Quartz"], request_name, lambda: calls.append(request_name))++ result = _port(modules).request(permission_id)++ assert result.ok is True+ assert result.performed is True+ assert calls == [request_name]+++def test_legacy_macos_event_posting_falls_back_to_accessibility_prompt() -> 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),+ kAXTrustedCheckOptionPrompt="prompt",+ )++ result = _port(modules).request(PermissionId.EVENT_POSTING)++ assert result.ok is True+ assert result.performed is True+ assert calls == [{"prompt": True}]+++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_dry_run_never_invokes_native_request() -> None:+ modules, screen, _ = _native_modules()++ result = _port(modules).request(PermissionId.SCREEN_RECORDING, dry_run=True)++ assert result.ok is True+ assert result.dry_run is True+ assert result.performed is False+ assert screen["requested"] is False+++def test_open_settings_uses_permission_specific_launchservices_url() -> None:+ modules, _, workspace = _native_modules()++ result = _port(modules).open_settings(PermissionId.INPUT_MONITORING)++ assert result.ok is True+ assert result.performed is True+ assert workspace.opened_urls == [+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent"+ ]+++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+++def test_broken_native_bridge_import_fails_closed() -> None:+ def broken_loader(_name: str) -> object:+ raise OSError("incompatible native framework")++ port = SystemPermissionPort(platform_name="darwin", module_loader=broken_loader)++ 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())diff --git a/tests/unit/setup/test_macos_app_bundle.py b/tests/unit/setup/test_macos_app_bundle.pyindex 36362fca7c..2756c4e4d8 100644--- a/tests/unit/setup/test_macos_app_bundle.py+++ b/tests/unit/setup/test_macos_app_bundle.py@@ -1,73 +1,135 @@-"""macOS .app bundle writer (BUG-060).--After closing the desktop app on a Mac there was no way back: Spotlight and-/Applications showed nothing because a plain pip install ships no bundle.-``ensure_macos_app_bundle`` writes a per-user ``Personal Jarvis.app`` whose-executable script exec's the venv Python desktop launcher. Contracts:--- correct bundle layout + Info.plist (incl. NSMicrophoneUsageDescription —- a bundled process gets its own TCC identity, so the mic prompt must carry- an honest usage string instead of being killed for lacking one),-- launcher script points at the install's venv python and the launcher module,-- idempotent re-runs, no-op off darwin without an explicit override.--Pure file writes — provable on any OS via injectable directories (same-pattern as jarvis/autostart/macos.py).-"""+"""Tests for the stable native macOS application identity (BUG-060)."""+from __future__ import annotations+import jsonimport os+import platformimport plistlibimport stat+import sysfrom pathlib import Path+from types import ModuleType, SimpleNamespace++import pytestfrom jarvis.setup.macos_app_bundle import (APP_DIR_NAME,ensure_macos_app_bundle,+ macos_app_bundle_is_launchable,+ macos_app_bundle_path,+ macos_launch_services_command,)-def _build(tmp_path: Path) -> Path:+def _build(tmp_path: Path, monkeypatch) -> Path:+ import jarvis.setup.macos_app_bundle as mab++ # The explicit-path branch builds a structural native fixture off macOS.+ # Real py2app/codesign/LaunchServices coverage lives in macOS CI.+ monkeypatch.setattr(mab.sys, "platform", "linux")install_dir = tmp_path / "install"(install_dir / ".venv" / "bin").mkdir(parents=True)(install_dir / ".venv" / "bin" / "python").write_text("", encoding="utf-8")- apps = tmp_path / "Applications"bundle = ensure_macos_app_bundle(- install_dir=install_dir, applications_dir=apps+ install_dir=install_dir,+ applications_dir=tmp_path / "Applications",)assert bundle is not Nonereturn bundle-def test_bundle_layout_and_plist(tmp_path: Path) -> None:- bundle = _build(tmp_path)- assert bundle.name == APP_DIR_NAME # "Personal Jarvis.app"+def test_bundle_layout_and_plist(tmp_path: Path, monkeypatch) -> None:+ bundle = _build(tmp_path, monkeypatch)+ assert bundle.name == APP_DIR_NAMEplist_path = bundle / "Contents" / "Info.plist"- with plist_path.open("rb") as fh:- info = plistlib.load(fh)- assert info["CFBundleExecutable"] == "PersonalJarvis"+ with plist_path.open("rb") as stream:+ info = plistlib.load(stream)+ executable_name = info["CFBundleExecutable"]assert info["CFBundleIdentifier"] == "com.personal-jarvis.desktop"assert info["CFBundlePackageType"] == "APPL"- # TCC: a bundled app is killed on first mic open without a usage string.assert "microphone" in info["NSMicrophoneUsageDescription"].lower()- exe = bundle / "Contents" / "MacOS" / "PersonalJarvis"- body = exe.read_text(encoding="utf-8")- assert body.startswith("#!/bin/bash")- assert "jarvis.ui.web.launcher" in body- assert ".venv" in body # exec's the install venv's python- if os.name == "posix":- assert exe.stat().st_mode & stat.S_IXUSR---def test_rerun_is_idempotent(tmp_path: Path) -> None:- first = _build(tmp_path)+ assert "screen" in info["NSScreenCaptureUsageDescription"].lower()+ assert "NSAppleEventsUsageDescription" not in info+ executable = bundle / "Contents" / "MacOS" / executable_name+ assert executable.read_bytes()[:4] == b"\xcf\xfa\xed\xfe"+ if os.name != "nt":+ assert executable.stat().st_mode & stat.S_IXUSR+ 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()+ )["CFBundleExecutable"]+ executable = first / "Contents" / "MacOS" / executable_name+ marker = executable.read_bytes()second = ensure_macos_app_bundle(install_dir=tmp_path / "install",applications_dir=tmp_path / "Applications",)assert second == first- with (first / "Contents" / "Info.plist").open("rb") as fh:- assert plistlib.load(fh)["CFBundleExecutable"] == "PersonalJarvis"+ assert executable.read_bytes() == marker+++def test_failed_runtime_probe_rebuilds_instead_of_preserving(+ tmp_path: Path, monkeypatch+) -> None:+ import jarvis.setup.macos_app_bundle as mab++ bundle = _build(tmp_path, monkeypatch)+ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "_codesign_valid", lambda _bundle: True)+ monkeypatch.setattr(+ mab,+ "_current_process_identity_valid",+ lambda _bundle, *, install_root: False,+ )+ monkeypatch.setattr(+ mab,+ "_runtime_identity_valid",+ lambda _bundle, *, install_root: False,+ )+ rebuilt: list[tuple[Path, Path]] = []++ def _rebuild(install_root: Path, destination: Path) -> Path:+ rebuilt.append((install_root, destination))+ return destination++ monkeypatch.setattr(mab, "_install_native_bundle", _rebuild)+ install_root = tmp_path / "install"++ assert ensure_macos_app_bundle(+ install_dir=install_root,+ applications_dir=tmp_path / "Applications",+ ) == bundle+ assert rebuilt == [(install_root.resolve(), bundle)]+++def test_running_canonical_app_skips_second_launchservices_probe(+ tmp_path: Path, monkeypatch+) -> None:+ import jarvis.setup.macos_app_bundle as mab++ bundle = _build(tmp_path, monkeypatch)+ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "_codesign_valid", lambda _bundle: True)+ monkeypatch.setattr(+ mab,+ "_current_process_identity_valid",+ lambda _bundle, *, install_root: True,+ )+ monkeypatch.setattr(+ mab,+ "_runtime_identity_valid",+ lambda *_args, **_kwargs: pytest.fail("must not spawn a second app probe"),+ )++ assert ensure_macos_app_bundle(+ install_dir=tmp_path / "install",+ applications_dir=tmp_path / "Applications",+ ) == bundledef test_noop_off_darwin_without_override(monkeypatch) -> None:@@ -75,12 +137,89 @@ def test_noop_off_darwin_without_override(monkeypatch) -> None:assert ensure_macos_app_bundle() is None-def test_missing_icon_tooling_still_builds_bundle(tmp_path: Path, monkeypatch) -> None:- # iconutil/PIL failures are best-effort: no icon key, bundle still works.+def test_bundle_path_and_launchservices_command(tmp_path: Path, monkeypatch) -> None:+ bundle = _build(tmp_path, monkeypatch)+ probe = str(tmp_path / "probe.json")+ assert macos_app_bundle_path(+ applications_dir=tmp_path / "Applications"+ ) == bundle+ assert macos_launch_services_command(+ bundle,+ background=True,+ wait_for_exit=True,+ ) == ["/usr/bin/open", "-g", "-W", "-a", str(bundle)]+ assert macos_launch_services_command(+ bundle,+ wait_for_exit=True,+ new_instance=True,+ arguments=("--jarvis-identity-probe", probe),+ ) == [+ "/usr/bin/open",+ "-W",+ "-n",+ "-a",+ str(bundle),+ "--args",+ "--jarvis-identity-probe",+ probe,+ ]+++def test_shell_executable_is_rejected(tmp_path: Path, monkeypatch) -> None:import jarvis.setup.macos_app_bundle as mab- monkeypatch.setattr(mab, "_try_build_icns", lambda _res: None)- bundle = _build(tmp_path)- with (bundle / "Contents" / "Info.plist").open("rb") as fh:- info = plistlib.load(fh)- assert "CFBundleIconFile" not in info+ monkeypatch.setattr(mab.sys, "platform", "linux")+ bundle = tmp_path / APP_DIR_NAME+ executable = bundle / "Contents" / "MacOS" / "PersonalJarvis"+ executable.parent.mkdir(parents=True)+ executable.write_text("#!/bin/bash\nexit 0\n", encoding="utf-8")+ executable.chmod(executable.stat().st_mode | stat.S_IXUSR)+ info = {+ "CFBundleExecutable": "PersonalJarvis",+ "CFBundleIdentifier": "com.personal-jarvis.desktop",+ "CFBundlePackageType": "APPL",+ "JarvisBundleFormatVersion": 1,+ }+ with (bundle / "Contents" / "Info.plist").open("wb") as stream:+ plistlib.dump(info, stream)+ assert macos_app_bundle_is_launchable(bundle) is False+++def test_incomplete_bundle_is_not_launchable(tmp_path: Path) -> None:+ bundle = tmp_path / APP_DIR_NAME+ bundle.mkdir()+ assert macos_app_bundle_is_launchable(bundle) is False+++def test_launcher_identity_probe_uses_main_bundle(tmp_path: Path, monkeypatch) -> None:+ from jarvis.setup.macos_launcher_entry import main++ bundle = SimpleNamespace(+ bundleIdentifier=lambda: "com.personal-jarvis.desktop",+ bundlePath=lambda: "/Users/test/Applications/Personal Jarvis.app",+ executablePath=lambda: (+ "/Users/test/Applications/Personal Jarvis.app/Contents/MacOS/launcher"+ ),+ )+ foundation = ModuleType("Foundation")+ foundation.NSBundle = SimpleNamespace(mainBundle=lambda: bundle)+ monkeypatch.setitem(sys.modules, "Foundation", foundation)+ probe = tmp_path / "probe.json"+ assert main(["--jarvis-identity-probe", str(probe)]) == 0+ assert json.loads(probe.read_text(encoding="utf-8")) == {+ "bundle_id": "com.personal-jarvis.desktop",+ "bundle_path": "/Users/test/Applications/Personal Jarvis.app",+ "executable": (+ "/Users/test/Applications/Personal Jarvis.app/Contents/MacOS/launcher"+ ),+ "launcher_file": str(+ Path(__file__).resolve().parents[3]+ / "jarvis"+ / "ui"+ / "web"+ / "launcher.py"+ ),+ "install_root": str(Path(__file__).resolve().parents[3]),+ "python_version": f"{sys.version_info.major}.{sys.version_info.minor}",+ "machine": platform.machine(),+ }diff --git a/tests/unit/ui/test_desktop_focus.py b/tests/unit/ui/test_desktop_focus.pynew file mode 100644index 0000000000..8a451e9af2--- /dev/null+++ b/tests/unit/ui/test_desktop_focus.py@@ -0,0 +1,62 @@+"""Windows foreground recovery used by the desktop visibility endpoint."""++from __future__ import annotations++from jarvis.ui.desktop_app import _force_foreground_hwnd+++class _Kernel32:+ @staticmethod+ def GetCurrentThreadId() -> int:+ return 10+++class _User32:+ def __init__(self) -> None:+ self.foreground = 100+ self.set_calls = 0+ self.attachments: list[tuple[int, int, bool]] = []++ def ShowWindow(self, _hwnd: int, _mode: int) -> bool:+ return True++ def SetForegroundWindow(self, hwnd: int) -> bool:+ self.set_calls += 1+ if self.set_calls >= 2:+ self.foreground = hwnd+ return True+ return False++ def SetActiveWindow(self, _hwnd: int) -> int:+ return 1++ def GetForegroundWindow(self) -> int:+ return self.foreground++ @staticmethod+ def GetWindowThreadProcessId(hwnd: int, _pid: object) -> int:+ return {100: 20, 200: 30}.get(hwnd, 0)++ def AttachThreadInput(self, source: int, target: int, attach: bool) -> bool:+ self.attachments.append((source, target, attach))+ return True++ @staticmethod+ def BringWindowToTop(_hwnd: int) -> bool:+ return True++ @staticmethod+ def SetWindowPos(*_args: object) -> bool:+ return True+++def test_foreground_lock_recovery_attaches_and_always_detaches() -> None:+ user32 = _User32()++ assert _force_foreground_hwnd(200, user32, _Kernel32()) is True+ assert user32.attachments == [+ (10, 20, True),+ (10, 30, True),+ (10, 20, False),+ (10, 30, False),+ ]diff --git a/tests/unit/ui/test_desktop_macos_permission_gate.py b/tests/unit/ui/test_desktop_macos_permission_gate.pynew file mode 100644index 0000000000..10e2bf5278--- /dev/null+++ b/tests/unit/ui/test_desktop_macos_permission_gate.py@@ -0,0 +1,49 @@+from __future__ import annotations++from jarvis.platform.permissions import PermissionId, PermissionState+from jarvis.ui.desktop_app import _local_voice_permission_granted+++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 test_macos_voice_gate_tracks_fresh_microphone_state() -> None:+ port = _PermissionPort(PermissionState.NOT_DETERMINED)++ 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 port.calls == [PermissionId.MICROPHONE] * 3+++def test_macos_voice_gate_rejects_grant_under_unstable_identity() -> None:+ port = _PermissionPort(PermissionState.GRANTED, stable=False)++ assert not _local_voice_permission_granted(+ platform_name="darwin", permission_port=port+ )+++def test_non_macos_voice_gate_never_consults_tcc() -> None:+ port = _PermissionPort(PermissionState.DENIED)++ assert _local_voice_permission_granted(+ platform_name="linux", permission_port=port+ )+ assert port.calls == []diff --git a/tests/unit/ui/web/test_permissions_routes.py b/tests/unit/ui/web/test_permissions_routes.pynew file mode 100644index 0000000000..76d59c53ee--- /dev/null+++ b/tests/unit/ui/web/test_permissions_routes.py@@ -0,0 +1,127 @@+"""Route contract tests for the system-permissions API."""++from __future__ import annotations++from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.platform.permissions import PermissionOperation+from jarvis.ui.web.control_auth import require_control_key_or_session+from jarvis.ui.web.permissions_routes import router+++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,+ }+++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 _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_status_returns_uncached_port_snapshot() -> None:+ body = _client(_Port()).get("/api/permissions/status").json()++ assert body["platform"] == "darwin"+ assert body["app_identity"]["stable"] is True+++def test_request_passes_stable_id_and_dry_run() -> None:+ port = _Port()++ response = _client(port).post("/api/permissions/screen_recording/request?dry_run=true")++ assert response.status_code == 200+ assert response.json()["dry_run"] is True+ assert port.calls == [("request", "screen_recording", True)]+++def test_open_settings_passes_permission_id() -> None:+ port = _Port()++ response = _client(port).post("/api/permissions/microphone/open-settings")++ assert response.status_code == 200+ assert response.json()["action"] == "open_settings"+ assert port.calls == [("open_settings", "microphone", False)]+++def test_failed_native_operation_is_conflict_with_full_payload() -> None:+ response = _client(_Port(fail=True)).post("/api/permissions/accessibility/request")++ assert response.status_code == 409+ assert response.json()["ok"] is False+ assert response.json()["snapshot"]["platform"] == "darwin"+++def test_unknown_permission_id_is_rejected() -> None:+ response = _client(_Port()).post("/api/permissions/camera/request")++ assert response.status_code == 422+++def test_mutating_routes_are_marked_dangerous_in_openapi() -> None:+ app = FastAPI()+ app.include_router(router)++ paths = app.openapi()["paths"]++ assert paths["/api/permissions/{permission_id}/request"]["post"]["x-jarvis-dangerous"] is True+ assert (+ paths["/api/permissions/{permission_id}/open-settings"]["post"]["x-jarvis-dangerous"]+ is True+ )