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
fix(macos): a granted permission stops reading as missing (BUG-159)
Haraldc55a403d663f
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 64504aaa6e..12bd6d213c 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -11106,3 +11106,91 @@ chat hook already ran the `TriggerMatcher` and were never affected.`tests/unit/skills/test_prompt_injection.py`(`test_realtime_directive_*`), `tests/unit/brain/test_run_skill_tool.py`(`test_run_skill_resolves_a_display_name_to_the_installed_slug`).++## BUG-159: macOS permissions read as missing although System Settings shows them enabled — a sticky restart flag, a hidden recovery, and a silent grant-wiping rebuild (HIGH, FIXED 2026-08-20)++**Symptom (maintainer's Mac, reported 2026-08-20).** Every start warned that+macOS permissions were not enabled. Clicking the warning's button opened+System Settings, where the permission was already switched ON. Toggling it off+and on changed nothing: the next start showed the same warning. Restarting the+app did not help either.++**Root causes (three independent defects, plus the underlying identity churn).**++1. *The pending-restart flag was sticky and self-inflicted.* Any click on+ "Open Settings" for Screen Recording, Accessibility or Input Monitoring+ added the permission to `SystemPermissionPort._restart_required` — even+ when the pane showed it as already granted and the user changed nothing.+ Nothing ever removed it again except `reset()` or process exit. While set,+ `snapshot()` reported `restart_required`, every affected feature reported+ `ready: false`, and `runtime_access_granted()` returned False, so+ Computer-Use and the global hotkeys were genuinely switched off for the+ rest of the session although every grant was in place. Reproduced against+ the project's own fakes: all-granted → one `open_settings()` call →+ `computer_use`, `global_hotkeys` and `window_control` all flip to+ `ready: false` and stay there. The old test suite pinned this as intended+ behaviour (`test_runtime_access_blocks_pending_restart_even_after_native_grant`).++2. *The one recovery control was unreachable on the rows that need it.* An+ ad-hoc signature change strands the recorded TCC rows (BUG-083): System+ Settings keeps showing the checkmark while the kernel refuses. The way out+ is `tccutil reset` for this bundle id, offered as "Ask again" — but the+ frontend showed that button only for `status === "denied"`, and the boolean+ preflights behind Screen Recording (`CGPreflightScreenCaptureAccess`) and+ Accessibility (`AXIsProcessTrusted`) never produce "denied"; a stranded+ grant reads as plain `not_granted`. The two most frequently stranded rows+ therefore had no escape hatch at all, and the app-wide alert banner carried+ no reset button in any state.++3. *A request that macOS swallowed still promised a restart.* When a decision+ is already on file, `CGRequest*` returns False without showing a dialog.+ The flow set the restart flag anyway and reported success, so the user+ restarted into exactly the same state — the dead-button loop BUG-083 set+ out to end, reintroduced through the flag.++4. *A rebuild that wipes every grant was invisible.* `ensure_desktop_integration()`+ runs on every app start and rebuilds the bundle whenever an identity probe+ fails (Python minor-version change, moved checkout, failed signature+ check). The rebuild changes the ad-hoc signature, so `_reset_stale_tcc_grants()`+ drops all five TCC rows — correct, but silent: the log said only "failed its+ runtime/import probe" with no reason, and the UI simply showed everything as+ missing again, which reads as "the app forgot my permissions".++**Fix (2026-08-20).**+(a) `_live_state()` retires a pending-restart flag the moment a probe reads the+grant as ready, and every read path (`state`, `runtime_access_granted`,+`runtime_feature_ready`, `snapshot`) goes through it. A GRANTED probe IS live+access — the only per-process-frozen probe, Screen Recording, can go stale+negative but never falsely positive.+(b) `open_settings()` flags a restart only for a permission that is actually+missing, so looking at a granted pane changes nothing.+(c) New `can_reset` field on every permission row: offered whenever a+TCC-governed grant is missing under a stable app identity, suppressed only for+Screen Recording while a restart is pending (its frozen preflight cannot tell a+missing grant from the one just given, and a reset would discard it). Panel and+banner both render it, plus a hint naming the stranded-grant case.+(d) `record_identity_reset()` leaves a marker when a rebuild drops the grants;+`snapshot()` surfaces it as `identity_reset` and retires it once every TCC row+is back, so the re-ask is explained instead of looking amnesic.+(e) `_launchable_issue()` and diagnostics on both identity probes make every+rebuild log WHY it is rebuilding, at WARNING, naming that it resets permissions.++**Class rule.** A permission flag that outlives the condition it describes is a+lie the user cannot clear. Anything the UI derives from a probe must die the+moment the probe contradicts it, and any recovery control must be keyed off an+explicit backend capability — never off one particular status string, because+the OS reports the same real condition through several of them.++**Guards.** `tests/unit/platform/test_permissions.py::test_a_pending_restart_dies_the_moment_the_probe_reads_the_grant`,+`::test_opening_settings_for_a_granted_permission_demands_no_restart`,+`::test_a_stranded_grant_offers_the_reset_although_it_never_reads_denied`,+`::test_a_granted_permission_never_offers_the_reset`,+`::test_a_signature_reset_is_explained_and_retired_once_grants_return`,+`PermissionsPanel.test.tsx` and `PermissionsAlertBanner.test.tsx`+(stranded-grant reset + signature-change explanation). The Screen Recording+fake no longer pretends the frozen preflight updates in-process.++**Still open.** The underlying churn is the ad-hoc signature itself: any forced+rebuild remains a new app to TCC. A Developer-ID signing identity is the+structural fix; until then a rebuild costs the user one round of re-granting,+now visible in the log and explained in the UI.diff --git a/jarvis/platform/permissions.py b/jarvis/platform/permissions.pyindex f90ab743de..f9aa877b2a 100644--- a/jarvis/platform/permissions.py+++ b/jarvis/platform/permissions.py@@ -31,6 +31,61 @@ log = logging.getLogger(__name__)_SYSTEM_SETTINGS_BUNDLE_ID = "com.apple.systempreferences"+# Left behind when a bundle rebuild changed this app's ad-hoc signature and+# the installer therefore dropped its own TCC rows. Without it the user meets+# an app that has silently forgotten every permission and reads that as the+# app being broken; with it the UI can say WHY it is asking again.+_IDENTITY_RESET_FILENAME = "macos-tcc-reset.json"+++def identity_reset_marker_path() -> Path:+ """Where the "macOS sees this app as new" note lives."""+ from jarvis.core.paths import user_data_dir++ return user_data_dir() / _IDENTITY_RESET_FILENAME+++def record_identity_reset(services: tuple[str, ...] | list[str]) -> None:+ """Note that a signature change forced this app's TCC grants to be reset.++ Best-effort: a note that cannot be written costs an explanation, never a+ working install.+ """+ import json++ path = identity_reset_marker_path()+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps(+ {"reason": "signature-change", "services": list(services)},+ sort_keys=True,+ ),+ encoding="utf-8",+ )+ except OSError:+ log.debug("Could not record the macOS TCC reset marker.", exc_info=True)+++def _read_identity_reset() -> dict[str, Any] | None:+ import json++ path = identity_reset_marker_path()+ try:+ if not path.is_file():+ return None+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+ return payload if isinstance(payload, dict) else None+++def _clear_identity_reset() -> None:+ try:+ identity_reset_marker_path().unlink(missing_ok=True)+ except OSError:+ log.debug("Could not clear the macOS TCC reset marker.", exc_info=True)+class PermissionId(StrEnum):"""Stable identifiers shared by the API and desktop permission UI."""@@ -194,6 +249,12 @@ class PermissionStatus:required: tuple[str, ...]can_request: boolcan_open_settings: bool+ # Whether dropping THIS app's own TCC row is a sensible next step. The UI+ # must never derive it from ``status == "denied"``: the boolean preflights+ # behind Screen Recording and Accessibility report a stranded grant as+ # "not_granted", so a denial-only rule hid the one control that recovers+ # them — the two permissions most often stranded (BUG-159).+ can_reset: boolrestart_required: booldetail: str | None@@ -438,33 +499,50 @@ class SystemPermissionPort:# Accessibility grant and do not expose the separate PostEvent API.return ax_state+ def _live_state(self, permission_id: PermissionId) -> PermissionState:+ """Probe once and retire a pending-restart flag the OS has overtaken.++ A pending restart means exactly one thing: "the grant is not usable in+ THIS process yet". The moment a live probe reads it as ready that claim+ is false, so the flag must die right there — no probe can report a+ grant the process cannot use (the one per-process-frozen probe, Screen+ Recording, can only stay stale NEGATIVE; it never turns falsely+ positive). Keeping the flag past that point is what made a single+ "Open Settings" click disable Computer-Use and hotkeys until relaunch+ even though every permission was granted, and no code path ever+ cleared it again (BUG-159).+ """+ state = self._state(permission_id)+ if state in _READY_STATES:+ self._restart_required.discard(permission_id)+ return state+def state(self, permission_id: PermissionId | str) -> PermissionState:"""Probe one permission directly without constructing a full snapshot."""- return self._state(PermissionId(permission_id))+ return self._live_state(PermissionId(permission_id))def runtime_access_granted(self, permission_id: PermissionId | str) -> bool:"""Fail closed unless this installed app can use the grant right now."""resolved = PermissionId(permission_id)if self.platform != "darwin":- return self._state(resolved) in _READY_STATES+ return self._live_state(resolved) in _READY_STATES# Only the STATIC identity half gates runtime access — skip the# AppKit foreground probe _app_identity() also performs; its result# was never consulted here and it costs a window-server round trip.- return (- self._stable_identity()- and resolved not in self._restart_required- and self._state(resolved) is PermissionState.GRANTED- )+ # _live_state clears any stale pending-restart flag first, so no+ # separate check against it remains: a GRANTED probe IS live access.+ return self._stable_identity() and self._live_state(resolved) is PermissionState.GRANTEDdef 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)- return self._stable_identity() and all(- item not in self._restart_required and self._state(item) is PermissionState.GRANTED- for item in requirements- )+ return all(self._live_state(item) in _READY_STATES for item in requirements)+ # all() short-circuits, so probe every requirement first: a later+ # requirement's stale restart flag must heal even when an earlier one+ # is still missing.+ states = [self._live_state(item) for item in requirements]+ return self._stable_identity() and all(state is PermissionState.GRANTED for state in states)def _requester_available(self, permission_id: PermissionId) -> bool:if permission_id is PermissionId.CREDENTIAL_STORE:@@ -513,7 +591,7 @@ class SystemPermissionPort:self.platform == "darwin" and identity.stable and identity.foreground and not headless)for permission_id in PermissionId:- state = self._state(permission_id)+ state = self._live_state(permission_id)states[permission_id] = staterequired = tuple(feature@@ -548,11 +626,42 @@ class SystemPermissionPort:"local file for now. Allow access to store them encrypted ""in the macOS Keychain.")+ # Offer the tccutil escape hatch whenever a TCC-governed grant is+ # missing — NOT only on an explicit "denied". A stranded grant+ # (the recorded row belongs to a previous ad-hoc signature) reads+ # as plain "not granted" while System Settings still shows the+ # checkmark, and no request can ever reach the user because macOS+ # already has a decision on file.+ #+ # The one row that must NOT offer it is Screen Recording with a+ # restart pending: its preflight is frozen for the life of the+ # process, so "not granted" there may well be a grant the user+ # just gave — resetting would throw it away. Every other probe+ # reads live TCC state, so a missing grant is really missing and+ # the reset is safe even mid-restart.+ can_reset = (+ self.platform == "darwin"+ and identity.stable+ and not headless+ and permission_id in _TCC_RESET_SERVICES+ and state not in _READY_STATES+ and not (restart_pending and permission_id is PermissionId.SCREEN_RECORDING)+ )if restart_pending and state not in _READY_STATES:detail = ("Permission changes made in System Settings take effect ""after Personal Jarvis restarts.")+ elif can_reset and not can_request:+ # No prompt left and the grant is missing: name the only move+ # that still works instead of leaving a dead-end row.+ detail = (+ "macOS already has a decision on file for this app and "+ "will not ask again. If System Settings shows access as "+ "enabled, the recorded grant belongs to an earlier build "+ 'of the app — use "Ask again" to clear it, then allow '+ "access once more."+ )statuses.append(PermissionStatus(id=permission_id.value,@@ -563,6 +672,7 @@ class SystemPermissionPort:# The Keychain has no System Settings pane; its only# recovery path is the request flow above.can_open_settings=eligible and permission_id in _SETTINGS_URLS,+ can_reset=can_reset,restart_required=restart_pending,detail=detail,)@@ -586,6 +696,16 @@ class SystemPermissionPort:"restart_required": restart_required,}+ # A signature change wipes the recorded grants. Surface that as its own+ # fact so the UI can explain the re-ask instead of looking amnesic, and+ # retire the note the moment every TCC-governed grant is back.+ identity_reset = _read_identity_reset() if self.platform == "darwin" else None+ if identity_reset is not None and all(+ states[permission_id] in _READY_STATES for permission_id in _TCC_RESET_SERVICES+ ):+ _clear_identity_reset()+ identity_reset = None+return {"platform": self.platform,"supported": self.platform == "darwin",@@ -593,6 +713,7 @@ class SystemPermissionPort:"app_identity": asdict(identity),"permissions": [status.to_dict() for status in statuses],"features": features,+ "identity_reset": identity_reset,"restart_required": bool(self._restart_required),}@@ -708,26 +829,30 @@ class SystemPermissionPort:f"The native permission request failed: {type(exc).__name__}.",self.snapshot(),)- restart = permission_id in _RESTART_AFTER_CHANGE- if restart:+ if permission_id in _RESTART_AFTER_CHANGE:self._restart_required.add(permission_id)after = self.snapshot()+ # Read the flag back from the snapshot: a permission whose probe reads+ # live (Accessibility, Input Monitoring) is already granted again by+ # the time we get here, and _live_state retired the flag. Reporting a+ # restart the snapshot contradicts is how the banner and the row ended+ # up disagreeing (BUG-159).+ restart = permission_id in self._restart_requiredmessage = ("Permission requested. Restart Personal Jarvis after granting access."if restartelse "Permission requested; the status will update after your choice.")if prompted is False:- # macOS prompts each app identity exactly once. A requester that- # reports False may have the dialog up right now — or may have- # been silently suppressed because a denial is already on record- # (the Screen Recording preflight cannot tell those apart).- # Promising only a restart in that second case is the dead-button- # class of BUG-083: the user restarts forever and is never asked.- message += (- " If no system dialog appeared, macOS has already recorded an "- "earlier decision — enable Personal Jarvis in System Settings "- "> Privacy & Security for this permission."+ # macOS prompts each app identity exactly once. Name both the+ # Settings route and the reset, because a checkmark that is+ # already set there means the recorded grant is stranded on an+ # older signature and only a reset can revive the prompt.+ message = (+ "macOS did not show a dialog: it already has a decision on "+ "file for this app. Enable Personal Jarvis in System Settings "+ "> Privacy & Security — and if it is already enabled there, "+ 'use "Ask again" to clear the stale record first.')return PermissionOperation(True,@@ -778,9 +903,7 @@ class SystemPermissionPort:url = foundation.NSURL.URLWithString_(_SETTINGS_URLS[permission_id])return bool(appkit.NSWorkspace.sharedWorkspace().openURL_(url))- def reset(- self, permission_id: PermissionId, *, dry_run: bool = False- ) -> PermissionOperation:+ def reset(self, permission_id: PermissionId, *, dry_run: bool = False) -> PermissionOperation:"""Drop this app's own TCC row so the native prompt can appear again.The in-app way out of the auto-denied trap: once ANY build of the@@ -904,7 +1027,14 @@ class SystemPermissionPort:opened = self._open_settings(permission_id)except Exception: # noqa: BLE001 - native settings boundaryopened = False- restart = opened and permission_id in _RESTART_AFTER_CHANGE+ # Only a grant that is actually MISSING can be changed into something+ # this process must restart for. Flagging a restart merely because the+ # user looked at an already-granted pane disabled the very features+ # the pane governs until relaunch (BUG-159).+ already_granted = next(+ item for item in before["permissions"] if item["id"] == permission_id.value+ )["status"] in {PermissionState.GRANTED.value, PermissionState.NOT_REQUIRED.value}+ restart = opened and permission_id in _RESTART_AFTER_CHANGE and not already_grantedif restart:self._restart_required.add(permission_id)after = self.snapshot()diff --git a/jarvis/setup/macos_app_bundle.py b/jarvis/setup/macos_app_bundle.pyindex d2e0fe1ab5..5a2de9849f 100644--- a/jarvis/setup/macos_app_bundle.py+++ b/jarvis/setup/macos_app_bundle.py@@ -173,10 +173,6 @@ def _codesign_issue(bundle: Path) -> str | None:return (result.stderr or result.stdout or "unknown codesign error").strip()-def _codesign_valid(bundle: Path) -> bool:- return _codesign_issue(bundle) is None--def _bundle_cdhash(bundle: Path) -> str | None:"""Return the bundle's code-directory hash — its TCC identity — or ``None``.@@ -236,40 +232,68 @@ def _reset_stale_tcc_grants(runner=subprocess.run) -> None:else:detail = (result.stderr or result.stdout or "unknown error").strip()log.warning("TCC reset for %s failed: %s", service, detail[-300:])+ # Whether or not every individual reset succeeded, the signature DID+ # change: from here on the user faces an app macOS treats as a stranger.+ # Record that so the permissions view explains the re-ask instead of+ # silently showing everything as missing again (BUG-159).+ try:+ from jarvis.platform.permissions import record_identity_reset+ record_identity_reset(_TCC_SERVICES)+ except Exception: # noqa: BLE001 - the explanation is never load-bearing+ log.debug("Could not record the TCC reset marker.", exc_info=True)-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()++def _launchable_issue(candidate: Path) -> str | None:+ """Name the first reason ``candidate`` is not a usable app bundle.++ Every rebuild changes the ad-hoc signature and therefore voids every+ recorded TCC grant (BUG-083). A rebuild that cannot say WHY it happened is+ undiagnosable from a user's log — which is exactly the position the+ "permissions keep resetting" reports left us in (BUG-159).+ """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+ if candidate.name != APP_DIR_NAME:+ return f"unexpected bundle directory name: {candidate.name}"+ if candidate.is_symlink():+ return "bundle path is a symlink"+ if not candidate.is_dir():+ return "bundle directory is missing"+ if not info_path.is_file():+ return "Info.plist is missing"try:with info_path.open("rb") as stream:info = plistlib.load(stream)- except (OSError, plistlib.InvalidFileException):- return False+ except (OSError, plistlib.InvalidFileException) as exc:+ return f"Info.plist is unreadable: {exc}"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+ if not isinstance(executable_name, str) or Path(executable_name).name != executable_name:+ return f"invalid CFBundleExecutable: {executable_name!r}"+ if info.get("CFBundleIdentifier") != BUNDLE_ID:+ return f"bundle id is {info.get('CFBundleIdentifier')!r}, expected {BUNDLE_ID!r}"+ if info.get("CFBundlePackageType") != "APPL":+ return f"package type is {info.get('CFBundlePackageType')!r}, expected 'APPL'"+ if info.get("JarvisBundleFormatVersion") != _BUNDLE_FORMAT_VERSION:+ return (+ f"bundle format version is {info.get('JarvisBundleFormatVersion')!r}, "+ f"expected {_BUNDLE_FORMAT_VERSION}"+ )executable = candidate / "Contents" / "MacOS" / executable_name- return (- executable.is_file()- and not executable.is_symlink()- and _is_macho_executable(executable)- and _codesign_valid(candidate)- )+ if not executable.is_file():+ return f"executable is missing: {executable.name}"+ if executable.is_symlink():+ return "executable is a symlink"+ if not _is_macho_executable(executable):+ return "executable is not a Mach-O binary"+ signature = _codesign_issue(candidate)+ if signature is not None:+ return f"code signature is invalid: {signature[-300:]}"+ return None+++def macos_app_bundle_is_launchable(bundle: Path | None = None) -> bool:+ """Validate native executable, canonical metadata, and code signature."""+ return _launchable_issue(bundle or macos_app_bundle_path()) is Nonedef macos_launch_services_command(@@ -704,7 +728,12 @@ def _runtime_identity_valid(probe.unlink(missing_ok=True)-def _current_process_identity_valid(bundle: Path, *, install_root: Path) -> bool:+def _current_process_identity_valid(+ bundle: Path,+ *,+ install_root: Path,+ diagnostics: list[str] | None = None,+) -> bool:"""Recognize the already-running canonical app without spawning a probe."""if sys.platform != "darwin":return False@@ -717,13 +746,22 @@ def _current_process_identity_valid(bundle: Path, *, install_root: Path) -> boolcurrent_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):+ current_id = str(current.bundleIdentifier() or "")+ reasons: list[str] = []+ if current_id != BUNDLE_ID:+ reasons.append(f"running bundle id is {current_id!r}, expected {BUNDLE_ID!r}")+ if current_bundle != bundle.resolve():+ reasons.append(f"running from {current_bundle}, expected {bundle.resolve()}")+ if not launcher_file.is_file():+ reasons.append(f"launcher module has no file on disk: {launcher_file}")+ elif not launcher_file.is_relative_to(expected_root / "jarvis" / "ui" / "web"):+ reasons.append(f"launcher {launcher_file} is outside the checkout {expected_root}")+ if diagnostics is not None:+ diagnostics.extend(f"current process: {reason}" for reason in reasons)+ return not reasons+ except (ImportError, OSError, TypeError, ValueError) as exc:+ if diagnostics is not None:+ diagnostics.append(f"current process: probe failed: {type(exc).__name__}: {exc}")return False@@ -787,20 +825,30 @@ def ensure_macos_app_bundle(try: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):+ launchable_issue = _launchable_issue(bundle) if bundle.exists() else "bundle not installed"+ if launchable_issue is None:+ diagnostics: list[str] = []if _current_process_identity_valid(- bundle, install_root=install_root- ) or _runtime_identity_valid(bundle, install_root=install_root):+ bundle, install_root=install_root, diagnostics=diagnostics+ ) or _runtime_identity_valid(+ bundle, install_root=install_root, diagnostics=diagnostics+ ):# A healthy bundle is kept byte-for-byte, but LaunchServices may# still not know it — an interrupted earlier run, or a database# rebuilt since. Re-registering is a no-op when it is known, and# repairs "installed but unsearchable" when it is not.register_with_launch_services(bundle)return bundle- log.warning(- "Existing macOS bundle failed its runtime/import probe; rebuilding: %s",- bundle,- )+ launchable_issue = "; ".join(diagnostics) or "identity probe failed without detail"+ # A rebuild is never routine: it changes the ad-hoc signature and macOS+ # then discards every permission the user granted. Say why, at WARNING,+ # so a recurring rebuild is visible in the log instead of showing up as+ # "the app keeps forgetting my permissions".+ log.warning(+ "Rebuilding the macOS app bundle (this resets its macOS permissions) — reason: %s [%s]",+ launchable_issue,+ bundle,+ )if sys.platform != "darwin":return _write_cross_platform_fixture_bundle(bundle)installed = _install_native_bundle(install_root, bundle)diff --git a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsx b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsxindex 75c14a232c..d6bd0ab75a 100644--- a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsx@@ -4,6 +4,7 @@ import type { PermissionSnapshot } from "@/hooks/usePermissions";const request = vi.fn();const openSettings = vi.fn();+const reset = vi.fn();let mockSnapshot: PermissionSnapshot | null = null;@@ -25,6 +26,7 @@ vi.mock("@/hooks/usePermissions", () => ({refetch: vi.fn(),request,openSettings,+ reset,}),}));@@ -43,6 +45,7 @@ function darwinSnapshot(overrides: Partial<PermissionSnapshot> = {}): Permissionrequired: ["voice"],can_request: false,can_open_settings: true,+ can_reset: false,restart_required: false,},],@@ -81,6 +84,7 @@ describe("PermissionsAlertBanner", () => {required: ["voice"],can_request: true,can_open_settings: true,+ can_reset: false,restart_required: false,},],@@ -110,6 +114,7 @@ describe("PermissionsAlertBanner", () => {required: ["computer_use"],can_request: false,can_open_settings: true,+ can_reset: false,restart_required: true,},],@@ -137,6 +142,7 @@ describe("PermissionsAlertBanner", () => {required: ["computer_use"],can_request: false,can_open_settings: true,+ can_reset: false,restart_required: true,},],@@ -171,6 +177,7 @@ describe("PermissionsAlertBanner", () => {required: ["voice"],can_request: false,can_open_settings: true,+ can_reset: false,restart_required: false,},],@@ -185,4 +192,38 @@ describe("PermissionsAlertBanner", () => {render(<PermissionsAlertBanner />);expect(screen.queryByTestId("permissions-alert-banner")).toBeNull();});++ it("offers the reset for a stranded grant that never reads 'denied' (BUG-159)", () => {+ // Screen Recording's preflight reports an orphaned TCC row as plain+ // "not_granted" while System Settings still shows the checkmark. The+ // banner used to carry no reset at all, so this row was a dead end.+ mockSnapshot = darwinSnapshot({+ permissions: [+ {+ id: "screen_recording",+ status: "not_granted",+ required: ["computer_use"],+ can_request: false,+ can_open_settings: true,+ can_reset: true,+ restart_required: false,+ },+ ],+ features: { computer_use: { ready: false, missing: ["screen_recording"] } },+ });+ render(<PermissionsAlertBanner />);++ expect(screen.getByText("permissions.stale_grant_hint")).toBeDefined();+ fireEvent.click(screen.getByRole("button", { name: "permissions.ask_again" }));+ expect(reset).toHaveBeenCalledWith("screen_recording");+ });++ it("explains a signature change instead of looking amnesic", () => {+ mockSnapshot = darwinSnapshot({+ identity_reset: { reason: "signature-change", services: ["ScreenCapture"] },+ });+ render(<PermissionsAlertBanner />);++ expect(screen.getByText("permissions.identity_reset")).toBeDefined();+ });});diff --git a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsxindex 7a2bdc3577..fee9149354 100644--- a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx@@ -58,7 +58,7 @@ export function PermissionsAlertBanner() {const pushToast = useEventStore((state) => state.pushToast);const [collapsed, setCollapsed] = useState(false);const [restarting, setRestarting] = useState(false);- const { snapshot, pendingId, request, openSettings } = usePermissions();+ const { snapshot, pendingId, request, openSettings, reset } = usePermissions();if (!snapshot || snapshot.platform !== "darwin" || snapshot.headless) return null;@@ -148,6 +148,9 @@ export function PermissionsAlertBanner() {{snapshot.app_identity.stable === false && (<p className="text-xs text-amber-200/90">{t("permissions.identity_warning")}</p>)}+ {snapshot.identity_reset && (+ <p className="text-xs text-amber-200/90">{t("permissions.identity_reset")}</p>+ )}{missing.map((item) => (<MissingPermissionRowkey={item.id}@@ -155,6 +158,7 @@ export function PermissionsAlertBanner() {busy={pendingId === item.id}onRequest={() => void run(() => request(item.id))}onOpenSettings={() => void run(() => openSettings(item.id))}+ onReset={() => void run(() => reset(item.id))}/>))}{snapshot.restart_required && (@@ -178,11 +182,13 @@ function MissingPermissionRow({busy,onRequest,onOpenSettings,+ onReset,}: {item: PermissionItem;busy: boolean;onRequest: () => void;onOpenSettings: () => void;+ onReset: () => void;}) {const t = useT();// A newer backend may report a permission id this build does not know yet;@@ -206,6 +212,12 @@ function MissingPermissionRow({<p className="mt-0.5 text-xs text-muted-foreground">{t(`permissions.items.${item.id}.description`)}</p>+ {/* macOS will not prompt again and the grant is missing: the+ checkmark in System Settings belongs to an older signature of+ this app, so toggling it there leads nowhere (BUG-159). */}+ {item.can_reset && !item.can_request && (+ <p className="mt-1 text-xs text-amber-200/90">{t("permissions.stale_grant_hint")}</p>+ )}</div><span className="rounded-full bg-amber-500/10 px-2 py-1 text-[10px] font-medium uppercase tracking-wide text-amber-500">{t(`permissions.status.${statusKey}`)}@@ -222,6 +234,12 @@ function MissingPermissionRow({{t("permissions.open_settings")}</Button>)}+ {item.can_reset && (+ <Button size="sm" variant="ghost" disabled={busy} onClick={onReset}>+ {busy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}+ {t("permissions.ask_again")}+ </Button>+ )}</div>);}diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsxindex b6144e4cbd..97eb2b611a 100644--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx@@ -23,6 +23,7 @@ function macSnapshot(overrides: Partial<PermissionSnapshot> = {}): PermissionSnarequired: [],can_request: false,can_open_settings: true,+ can_reset: false,restart_required: false,})),features: {},diff --git a/jarvis/ui/web/frontend/src/hooks/usePermissions.test.tsx b/jarvis/ui/web/frontend/src/hooks/usePermissions.test.tsxindex e97f0c8351..c4b2240cd2 100644--- a/jarvis/ui/web/frontend/src/hooks/usePermissions.test.tsx+++ b/jarvis/ui/web/frontend/src/hooks/usePermissions.test.tsx@@ -21,6 +21,7 @@ function snapshot(status: "not_determined" | "granted"): PermissionSnapshot {required: ["voice"],can_request: status === "not_determined",can_open_settings: true,+ can_reset: status !== "granted",restart_required: false,},],diff --git a/jarvis/ui/web/frontend/src/hooks/usePermissions.ts b/jarvis/ui/web/frontend/src/hooks/usePermissions.tsindex e6eaa3d063..83bc0333ac 100644--- a/jarvis/ui/web/frontend/src/hooks/usePermissions.ts+++ b/jarvis/ui/web/frontend/src/hooks/usePermissions.ts@@ -23,10 +23,24 @@ export interface PermissionItem {required: string[];can_request: boolean;can_open_settings: boolean;+ /**+ * Whether dropping this app's own TCC record is a sensible next step. Always+ * read this instead of testing `status === "denied"`: the Screen Recording+ * and Accessibility preflights report a grant stranded on an older app+ * signature as plain "not_granted", so the denial test hid the reset from+ * exactly the two rows that need it most (BUG-159).+ */+ can_reset: boolean;restart_required: boolean;detail?: string | null;}+/** Set when a rebuild changed the app signature and macOS discarded the grants. */+export interface PermissionIdentityReset {+ reason: string;+ services: string[];+}+export interface PermissionFeature {ready: boolean;missing: PermissionId[];@@ -47,6 +61,7 @@ export interface PermissionSnapshot {};permissions: PermissionItem[];features: Record<string, PermissionFeature>;+ identity_reset?: PermissionIdentityReset | null;restart_required: boolean;}@@ -57,6 +72,7 @@ const EMPTY_SNAPSHOT: PermissionSnapshot = {app_identity: {},permissions: [],features: {},+ identity_reset: null,restart_required: false,};diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex a4c2c066d8..c96611a683 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1588,7 +1588,9 @@"api_keys": "Sichere API-Key-Ablage"},"restart_deferred": "Neu erteilte Freigaben werden mit dem automatischen Neustart am Ende der Einrichtung aktiv - jetzt ist nichts zu tun.",- "ask_again": "Erneut fragen"+ "ask_again": "Erneut fragen",+ "stale_grant_hint": "macOS fragt für diesen Zugriff nicht mehr nach. Steht der Haken in den Systemeinstellungen schon, gehört er zu einer älteren Version der App — tippe auf „Erneut fragen“ und erlaube den Zugriff danach neu.",+ "identity_reset": "macOS sieht Personal Jarvis seit dem letzten Neuaufbau der App als neue App an und hat dabei alle erteilten Zugriffe verworfen. Bitte einmal neu erlauben — danach bleiben sie erhalten."},"settings_view": {"silence_window": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex bd390da98c..0a55e41c1c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1588,7 +1588,9 @@"api_keys": "Secure API-key storage"},"restart_deferred": "Newly granted access turns on with the automatic restart at the end of setup - nothing to do now.",- "ask_again": "Ask again"+ "ask_again": "Ask again",+ "stale_grant_hint": "macOS will not ask for this access again. If System Settings already shows it as enabled, that record belongs to an older version of the app — tap “Ask again” and allow access once more.",+ "identity_reset": "Since the app was last rebuilt, macOS treats Personal Jarvis as a new app and discarded every access you had granted. Please allow them once more — they will stick from then on."},"settings_view": {"silence_window": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 061e59da2a..0127d6ec15 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1588,7 +1588,9 @@"api_keys": "Almacenamiento seguro de claves API"},"restart_deferred": "Los permisos recién concedidos se activan con el reinicio automático al final de la configuración; no hay nada que hacer ahora.",- "ask_again": "Preguntar de nuevo"+ "ask_again": "Preguntar de nuevo",+ "stale_grant_hint": "macOS ya no volverá a preguntar por este acceso. Si Ajustes del Sistema ya lo muestra activado, ese registro pertenece a una versión anterior de la app: pulsa «Preguntar de nuevo» y concede el acceso otra vez.",+ "identity_reset": "Desde la última reconstrucción, macOS considera Personal Jarvis una app nueva y descartó todos los accesos concedidos. Vuelve a concederlos una vez; a partir de ahí se mantendrán."},"settings_view": {"silence_window": {diff --git a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.test.tsx b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.test.tsxindex 501a12262a..f3e02b0d41 100644--- a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.test.tsx@@ -1,8 +1,12 @@-import { cleanup, render, screen } from "@testing-library/react";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";+import type { PermissionItem, PermissionSnapshot } from "@/hooks/usePermissions";const request = vi.fn();const openSettings = vi.fn();+const reset = vi.fn();++let mockSnapshot: PermissionSnapshot | null = null;vi.mock("@/i18n", () => ({useT: () => (key: string) => key,@@ -15,39 +19,51 @@ vi.mock("@/store/events", () => ({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,- },+ snapshot: mockSnapshot,loading: false,error: null,pendingId: null,refetch: vi.fn(),request,openSettings,+ reset,}),}));import { PermissionRows } from "./PermissionsPanel";+function snapshotWith(row: Partial<PermissionItem>): PermissionSnapshot {+ return {+ platform: "darwin",+ supported: true,+ headless: false,+ app_identity: { stable: true },+ permissions: [+ {+ id: "screen_recording",+ status: "not_granted",+ required: ["computer_use"],+ can_request: true,+ can_open_settings: true,+ can_reset: false,+ restart_required: false,+ ...row,+ } as PermissionItem,+ ],+ features: { computer_use: { ready: false, missing: ["screen_recording"] } },+ restart_required: false,+ };+}+afterEach(() => {cleanup();vi.clearAllMocks();+ mockSnapshot = null;});describe("PermissionRows", () => {it("keeps System Settings available when a native request can also run", () => {+ mockSnapshot = snapshotWith({});render(<PermissionRows />);expect(screen.getByRole("button", { name: "permissions.request" })).toBeDefined();@@ -55,4 +71,23 @@ describe("PermissionRows", () => {screen.getByRole("button", { name: "permissions.open_settings" }),).toBeDefined();});++ it("offers the reset on a stranded grant that never reads 'denied' (BUG-159)", () => {+ // The old rule was `status === "denied"`, which the Screen Recording and+ // Accessibility preflights never produce — the recovery button was+ // unreachable on exactly the rows a signature change strands.+ mockSnapshot = snapshotWith({ can_request: false, can_reset: true });+ render(<PermissionRows />);++ fireEvent.click(screen.getByRole("button", { name: "permissions.ask_again" }));+ expect(reset).toHaveBeenCalledWith("screen_recording");+ expect(screen.getByText("permissions.stale_grant_hint")).toBeDefined();+ });++ it("hides the reset while a grant is in place", () => {+ mockSnapshot = snapshotWith({ status: "granted", can_request: false, can_reset: false });+ render(<PermissionRows />);++ expect(screen.queryByRole("button", { name: "permissions.ask_again" })).toBeNull();+ });});diff --git a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsxindex 4d7a1c7ab5..7933ba55a0 100644--- a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx@@ -124,6 +124,14 @@ export function PermissionRows({{t("permissions.identity_warning")}</div>)}+ {/* A rebuild changed the app's signature, so macOS discarded every+ recorded grant. Without this the app just looks amnesic. */}+ {snapshot?.identity_reset && (+ <div className="flex items-start gap-2 rounded-lg 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_reset")}+ </div>+ )}{items.map((permission) => (<PermissionRowkey={permission.id}@@ -179,11 +187,16 @@ function PermissionRow({const showSettings = !ready && item.can_open_settings;// macOS auto-denies an app that ever created an input listener before the// user was asked, and a signature change orphans recorded grants (BUG-083)- // — either way the row reads a dead "Denied" and macOS never prompts- // again. "Ask again" drops OUR OWN record (tccutil, scoped to this app's- // bundle id) so the real system dialog can fire once more. Keychain has- // no TCC row, hence the exclusion.- const showReset = item.status === "denied" && item.id !== "credential_store";+ // — either way macOS never prompts again. "Ask again" drops OUR OWN record+ // (tccutil, scoped to this app's bundle id) so the real system dialog can+ // fire once more. The backend decides when that helps: keying it off a+ // "denied" status hid it from Screen Recording and Accessibility, whose+ // boolean preflights report a stranded grant as "not_granted" (BUG-159).+ const showReset = item.can_reset;+ // No prompt left AND the grant is missing: the checkmark the user sees in+ // System Settings belongs to an older signature of the app. Say so, because+ // toggling it there is exactly what they will otherwise try forever.+ const showStaleHint = item.can_reset && !item.can_request;// Screen Recording is the one probe macOS freezes per process: after the// user grants it in System Settings, the live value stays stale until the// app restarts. Show the honest pending label instead of the stale state;@@ -236,6 +249,9 @@ function PermissionRow({</Button>)}</div>+ {showStaleHint && (+ <p className="mt-2 text-xs text-amber-500">{t("permissions.stale_grant_hint")}</p>+ )}</div>);}diff --git a/tests/unit/platform/test_permissions.py b/tests/unit/platform/test_permissions.pyindex 9762af6635..e33634c241 100644--- a/tests/unit/platform/test_permissions.py+++ b/tests/unit/platform/test_permissions.py@@ -79,8 +79,13 @@ def _native_modules(ax = {"trusted": True, "prompted": False}def request_screen() -> bool:+ # CGPreflightScreenCaptureAccess is frozen for the life of the process:+ # a grant given in response to this request stays INVISIBLE to the+ # preflight until the app relaunches. Flipping ``granted`` here would+ # model a macOS that does not exist and would hide every regression in+ # the restart handling, so tests that want the post-relaunch view set+ # ``screen["granted"]`` themselves.screen["requested"] = True- screen["granted"] = Truereturn Truedef request_listen() -> bool:@@ -247,17 +252,63 @@ def test_runtime_access_requires_stable_identity_and_fresh_grant() -> None:assert stable.runtime_access_granted(PermissionId.MICROPHONE) is False-def test_runtime_access_blocks_pending_restart_even_after_native_grant() -> None:- modules, _, _ = _native_modules()+def test_runtime_access_blocks_a_grant_the_frozen_preflight_cannot_confirm() -> None:+ modules, screen, _ = _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+ # The frozen preflight still reads "no", so access must stay closed.+ assert screen["granted"] is False+ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTEDassert port.runtime_access_granted(PermissionId.SCREEN_RECORDING) is False+def test_a_pending_restart_dies_the_moment_the_probe_reads_the_grant() -> None:+ """BUG-159: a live grant ends the restart claim — nothing else clears it.++ Holding the flag past a GRANTED probe is what disabled Computer-Use and+ hotkeys for the rest of the session after a single settings visit, with+ no code path left to undo it.+ """+ modules, screen, _ = _native_modules()+ port = _port(modules)+ port.request(PermissionId.SCREEN_RECORDING)+ assert port.snapshot()["restart_required"] is True++ # What a relaunch — or simply granting a live-reading permission — looks+ # like: the probe now sees the grant.+ screen["granted"] = True++ assert port.runtime_access_granted(PermissionId.SCREEN_RECORDING) is True+ snapshot = port.snapshot()+ assert snapshot["restart_required"] is False+ assert _permission(snapshot, PermissionId.SCREEN_RECORDING)["restart_required"] is False+ assert snapshot["features"]["computer_use"]["ready"] is True+++def test_opening_settings_for_a_granted_permission_demands_no_restart() -> None:+ """BUG-159: looking at an already-granted pane must change nothing.++ The old flow flagged a restart on every open-settings click, which turned+ a curious glance into "Computer-Use and hotkeys are off until you relaunch".+ """+ modules, screen, _ = _native_modules()+ screen["granted"] = True+ port = _port(modules, iohid_check=lambda _type: 0)+ assert port.runtime_feature_ready("computer_use") is True++ result = port.open_settings(PermissionId.ACCESSIBILITY)++ assert result.ok is True+ assert result.restart_required is False+ assert result.snapshot["restart_required"] is False+ assert result.snapshot["features"]["computer_use"]["ready"] is True+ assert port.runtime_feature_ready("computer_use") is True+ assert port.runtime_feature_ready("global_hotkeys") is True++def test_microphone_status_distinguishes_denied_and_restricted() -> None:modules, _, _ = _native_modules()port = _port(modules)@@ -301,7 +352,10 @@ def test_request_reporting_false_points_at_system_settings() -> None:assert result.ok is Trueassert screen["granted"] is Falseassert "System Settings" in result.message- assert "If no system dialog appeared" in result.message+ assert "did not show a dialog" in result.message+ # The stranded-grant case is the one the message must not leave out: the+ # checkmark is already set in System Settings, so only a reset helps.+ assert "Ask again" in result.messagedef test_request_reporting_true_keeps_the_plain_restart_message() -> None:@@ -560,6 +614,84 @@ def test_screen_capture_restart_pending_hides_the_dead_allow_button() -> None:assert item["restart_required"] is Trueassert item["can_request"] is Falseassert "restart" in (item["detail"] or "").lower()+ # And it must not offer the reset either: the frozen preflight cannot tell+ # a missing grant from the one the user just gave, so a reset here would+ # throw that fresh grant away.+ assert item["can_reset"] is False+++def test_a_stranded_grant_offers_the_reset_although_it_never_reads_denied() -> None:+ """BUG-159: the escape hatch must not hang off ``status == "denied"``.++ An ad-hoc signature change orphans the recorded TCC rows. System Settings+ keeps showing the checkmark while the boolean preflights report plain+ "not granted" — never "denied" — so a denial-keyed reset button was+ invisible on exactly the two rows that needed it.+ """+ modules, screen, _ = _native_modules()+ screen["granted"] = False+ modules["ApplicationServices"].AXIsProcessTrusted = lambda: False+ snapshot = _port(modules).snapshot()++ for permission_id in (PermissionId.SCREEN_RECORDING, PermissionId.ACCESSIBILITY):+ item = _permission(snapshot, permission_id)+ assert item["status"] == "not_granted", permission_id+ assert item["can_reset"] is True, permission_id+++def test_a_granted_permission_never_offers_the_reset() -> None:+ modules, screen, _ = _native_modules()+ screen["granted"] = True+ snapshot = _port(modules, iohid_check=lambda _type: 0).snapshot()++ for item in snapshot["permissions"]:+ if item["status"] in {"granted", "not_required"}:+ assert item["can_reset"] is False, item["id"]+++def test_keychain_has_no_reset_because_it_owns_no_tcc_row() -> None:+ modules, _, _ = _native_modules()+ port = _port(modules, credential_backend=lambda: "file")++ item = _permission(port.snapshot(), PermissionId.CREDENTIAL_STORE)++ assert item["status"] == "not_granted"+ assert item["can_reset"] is False+++def test_a_signature_reset_is_explained_and_retired_once_grants_return(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """BUG-159: an app that silently forgot every permission reads as broken."""+ from jarvis.platform import permissions as permissions_module++ monkeypatch.setattr(permissions_module, "user_data_dir", lambda: tmp_path, raising=False)+ monkeypatch.setattr(+ permissions_module,+ "identity_reset_marker_path",+ lambda: tmp_path / "macos-tcc-reset.json",+ )+ permissions_module.record_identity_reset(("ScreenCapture", "Accessibility"))++ # _CaptureDevice.status is class state other tests leave behind; the+ # marker only retires when EVERY TCC row is back, microphone included.+ _CaptureDevice.status = 3+ modules, screen, _ = _native_modules()+ screen["granted"] = False+ modules["ApplicationServices"].AXIsProcessTrusted = lambda: False+ port = _port(modules)++ stranded = port.snapshot()+ assert stranded["identity_reset"] is not None+ assert stranded["identity_reset"]["reason"] == "signature-change"++ # Everything granted again: the explanation has done its job and goes away.+ screen["granted"] = True+ modules["ApplicationServices"].AXIsProcessTrusted = lambda: True+ healed = _port(modules, iohid_check=lambda _type: 0).snapshot()++ assert healed["identity_reset"] is None+ assert not (tmp_path / "macos-tcc-reset.json").exists()def test_missing_framework_reports_unavailable_without_raising() -> None:diff --git a/tests/unit/setup/test_macos_app_bundle.py b/tests/unit/setup/test_macos_app_bundle.pyindex 02b2caf61b..ee43e8a4aa 100644--- a/tests/unit/setup/test_macos_app_bundle.py+++ b/tests/unit/setup/test_macos_app_bundle.py@@ -78,16 +78,16 @@ def test_failed_runtime_probe_rebuilds_instead_of_preserving(tmp_path: Path, monbundle = _build(tmp_path, monkeypatch)monkeypatch.setattr(mab.sys, "platform", "darwin")- monkeypatch.setattr(mab, "_codesign_valid", lambda _bundle: True)+ monkeypatch.setattr(mab, "_codesign_issue", lambda _bundle: None)monkeypatch.setattr(mab,"_current_process_identity_valid",- lambda _bundle, *, install_root: False,+ lambda _bundle, *, install_root, diagnostics=None: False,)monkeypatch.setattr(mab,"_runtime_identity_valid",- lambda _bundle, *, install_root: False,+ lambda _bundle, *, install_root, diagnostics=None: False,)rebuilt: list[tuple[Path, Path]] = []@@ -115,11 +115,11 @@ def test_running_canonical_app_skips_second_launchservices_probe(bundle = _build(tmp_path, monkeypatch)monkeypatch.setattr(mab.sys, "platform", "darwin")- monkeypatch.setattr(mab, "_codesign_valid", lambda _bundle: True)+ monkeypatch.setattr(mab, "_codesign_issue", lambda _bundle: None)monkeypatch.setattr(mab,"_current_process_identity_valid",- lambda _bundle, *, install_root: True,+ lambda _bundle, *, install_root, diagnostics=None: True,)monkeypatch.setattr(mab,@@ -278,7 +278,7 @@ def test_codesign_verify_never_uses_strict_or_deep(tmp_path: Path, monkeypatch)return SimpleNamespace(returncode=0, stdout="", stderr="")monkeypatch.setattr(mab.subprocess, "run", _fake_run)- assert mab._codesign_valid(tmp_path / APP_DIR_NAME) is True+ assert mab._codesign_issue(tmp_path / APP_DIR_NAME) is Noneassert len(seen) == 1assert seen[0][:2] == ["/usr/bin/codesign", "--verify"]assert "--strict" not in seen[0]