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 permission the user gave is never asked for again
Harald751aedfe275d
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 38489dd83e..8539890d06 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -11271,3 +11271,100 @@ counterweight — suppression must not cost the mute recovery), and`tests/unit/realtime/test_lookup_never_reports_done.py` (a finished search isnever "Erledigt."; an empty one says so; a wordless ACTION still reports done;the facts handed to the composer carry the content and never the URLs).++---++## BUG-161: macOS permissions still read as missing after BUG-159 — every start rebuilt the app bundle, and a copy in /Applications was treated as a stranger (HIGH, FIXED 2026-08-21)++**Symptom (maintainer's Mac, reported 2026-08-21).** The app kept asking for+permissions it had already been given. Granting them again changed nothing;+neither did a restart. This is BUG-159's symptom surviving BUG-159's fix,+which had closed three real defects but left the mechanism that produces the+loop untouched — its own "Still open" note named it.++**Root causes (four, each sufficient on its own).**++1. *A rebuild that cannot repair itself repeated on every single start.*+ `ensure_desktop_integration()` runs at every boot and rebuilds the app+ bundle whenever the identity probe refuses it. The rebuild changes the+ ad-hoc signature, and macOS answers a changed signature by orphaning every+ recorded TCC grant. When the probe fails for a reason a rebuild does not+ touch — a moved checkout, an interpreter the probe reads differently, an+ `open -W -n` that will not complete — the same rebuild happens again next+ start, and again after that. BUG-159 (f) only suppressed the second+ `tccutil reset`, and only while the user had NOT restored the grants:+ `snapshot()` retires that marker as soon as every row is back, so the user+ who did the right thing armed the next wipe. Grant everything, restart,+ be asked again — exactly as reported.++2. *A copy in `/Applications` was not recognized as this app.* The canonical+ location was `~/Applications` alone, everywhere: `_current_process_identity_valid()`+ compared the running bundle against that one path, so dragging the app to+ `/Applications` — the most ordinary thing a Mac user does — made the+ `~/Applications` slot look empty. Every start then built a bundle there,+ under the SAME bundle id, and the signature change stripped the grants of+ the copy that was running at that moment.++3. *The permission port called the same move a tampering signal.* `_bundle_identity()`+ applied the identical `~/Applications`-only rule to `stable`. An app in+ `/Applications` therefore reported an unstable identity: every request and+ settings button disappeared, `runtime_access_granted()` returned False for+ every grant, every feature reported not-ready, and the banner demanded+ permissions with nothing left to click. TCC pins a grant to the bundle id+ and its signature, never to a path, so the strict rule bought no safety.++4. *A Screen Recording grant given in System Settings was invisible forever.*+ `CGPreflightScreenCaptureAccess` answers from a value macOS freezes when the+ process first asks. The port had exactly one way to learn otherwise: a+ pending-restart flag that only its OWN request/settings flow set. A user who+ opened System Settings themselves — which is what macOS's own prompt tells+ them to do — got no flag and a permanent "not granted", however often they+ granted it.++**Fix (2026-08-21).**+(a) `_running_managed_bundle()` replaces `_current_process_identity_valid()`+and runs FIRST, before the launchable check: a process executing as a bundle+with our id, importing the managed checkout, IS the installed app and is left+alone — wherever the user keeps it. Location is no longer part of the verdict.+(b) `_rebuild_would_repeat()` records what each rebuild produced (cdhash,+checkout, interpreter minor version, machine). When a launchable bundle fails+its identity probe and a fresh build would reproduce the same app, the build is+skipped and the reason is logged at WARNING — a launchable app is worth more+than a probe verdict no rebuild can satisfy. A bundle that genuinely cannot+launch is still rebuilt every time.+(c) `_canonical_app_roots()` accepts `~/Applications` and `/Applications`+alike for the `stable` identity.+(d) `_default_screen_capture_live_check()` proves the grant by using it: window+TITLES of other applications are screen-recording-gated data, so one on-screen+window on layer 0 owned by another process and carrying a name means the grant+works right now. It only ever upgrades the frozen preflight — an empty result+is `None`, never a denial — and it costs nothing on the hot path, where the+preflight already reads granted.+(e) Opening a System Settings pane no longer requires the foreground. Only the+native prompt does (a dialog behind other windows is one the user never+answers); refusing the deep link left every background surface with a banner+whose single control answered "bring the app to the front".++**Class rule.** A repair that does not fix its own trigger is a loop, and a+loop that costs the user something must run at most once. Prove the cost is+buying a change before paying it again. Second half: a permission is bound to+an identity, never to a location — any check stricter than the OS's own turns+a normal user action into a permanent failure the user cannot even name.++**Guards.** `tests/unit/setup/test_macos_app_bundle.py::test_a_rebuild_that_reproduces_the_same_app_is_not_repeated`,+`::test_a_changed_interpreter_still_earns_a_fresh_rebuild`,+`::test_a_broken_bundle_is_always_rebuilt_however_often_it_recurs`,+`::test_the_running_app_is_accepted_wherever_the_user_keeps_it`,+`::test_the_running_bundle_probe_ignores_the_install_location`,+`::test_a_foreign_bundle_id_is_never_taken_for_the_managed_app`,+`tests/unit/platform/test_permissions.py::test_the_app_in_the_shared_applications_folder_is_a_stable_identity`,+`::test_a_live_window_probe_beats_the_frozen_screen_recording_preflight`,+`::test_a_live_window_probe_never_invents_a_grant_the_preflight_denies`,+`::test_window_titles_prove_the_grant_only_from_another_apps_own_layer`,+`::test_open_settings_works_while_the_app_sits_in_the_background`.++**Still open.** The ad-hoc signature remains the underlying churn: a rebuild+that IS necessary still costs one round of re-granting. A Developer-ID signing+identity is the structural fix. The rebuild guard also arms only after the+first rebuild it observes, so an install already caught in the loop pays for+one more round before it stops.diff --git a/jarvis/platform/permissions.py b/jarvis/platform/permissions.pyindex 1b1de87d72..3b8c625edb 100644--- a/jarvis/platform/permissions.py+++ b/jarvis/platform/permissions.py@@ -182,6 +182,67 @@ _IOHID_ACCESS_STATES: dict[int, PermissionState] = {}+def _canonical_app_roots() -> tuple[Path, ...]:+ """The directories a legitimately installed copy of this app may live in.++ Both are equally canonical. The installer writes ``~/Applications``, but+ ``/Applications`` is where Mac users put apps, and dragging it there is a+ normal move — not a tampering signal. TCC pins a grant to the bundle id+ and its signature, never to a path, so a stricter rule buys no safety and+ costs everything: an app read as "unstable" hides every request button,+ reports every feature as not ready, and keeps insisting the permissions+ are missing while System Settings shows them enabled (BUG-161).+ """+ return (Path.home() / "Applications", Path("/Applications"))+++def _default_screen_capture_live_check() -> bool | None:+ """Prove the Screen Recording grant by USING it; ``None`` when unknowable.++ ``CGPreflightScreenCaptureAccess`` answers from a value macOS freezes when+ the process first asks. A grant given in System Settings while the app runs+ therefore stays invisible until relaunch, and the app keeps demanding a+ permission the user has already given — however often they give it again+ (BUG-161). Window TITLES of other applications are screen-recording-gated+ data, so one on-screen window owned by another process and carrying a name+ is live proof the grant works right now. The reverse does not hold (there+ may simply be no other window on screen), so an empty result is ``None``+ and never contradicts the preflight.+ """+ try:+ import Quartz # type: ignore[import-not-found]++ windows = Quartz.CGWindowListCopyWindowInfo(+ Quartz.kCGWindowListOptionOnScreenOnly | Quartz.kCGWindowListExcludeDesktopElements,+ Quartz.kCGNullWindowID,+ )+ except Exception: # noqa: BLE001 - a missing native bridge proves nothing+ return None+ return _window_titles_are_visible(windows, os.getpid())+++def _window_titles_are_visible(windows: Any, own_pid: int) -> bool | None:+ """``True`` when another app's window title is readable, else ``None``."""+ try:+ entries = list(windows or ())+ except TypeError:+ return None+ for window in entries:+ try:+ # Layer 0 is the ordinary application layer. The Dock, the menu+ # bar and other system chrome sit above it and expose names+ # without the grant, so they would fake a positive result.+ if int(window.get("kCGWindowLayer", -1)) != 0:+ continue+ if int(window.get("kCGWindowOwnerPID", own_pid)) == own_pid:+ continue+ if str(window.get("kCGWindowName") or "").strip():+ return True+ except (AttributeError, TypeError, ValueError):+ continue+ return None++def _default_iohid_check(request_type: int) -> int | None:"""Query IOKit's tri-state HID access check; ``None`` when unavailable.@@ -302,12 +363,14 @@ class SystemPermissionPort:platform_name: PlatformName | None = None,module_loader: Callable[[str], Any] = importlib.import_module,iohid_check: Callable[[int], int | None] = _default_iohid_check,+ screen_capture_live_check: Callable[[], bool | None] = _default_screen_capture_live_check,credential_store_backend: Callable[[], str] = _default_credential_store_backend,credential_store_recover: Callable[[], bool] = _default_credential_store_recover,) -> None:self._platform_name = platform_nameself._module_loader = module_loaderself._iohid_check = iohid_check+ self._screen_capture_live_check = screen_capture_live_checkself._credential_store_backend = credential_store_backendself._credential_store_recover = credential_store_recover# This is operation state, not a cached permission probe. The set lives@@ -359,8 +422,11 @@ class SystemPermissionPort:canonical_path = Falseif 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()+ resolved = Path(bundle_path).resolve()+ canonical_path = any(+ resolved == (root / f"{APP_NAME}.app").resolve()+ for root in _canonical_app_roots()+ )except (OSError, ValueError):# A path that will not resolve is not the canonical bundle# location. False is the cautious reading and it feeds a@@ -450,6 +516,13 @@ class SystemPermissionPort:except Exception: # noqa: BLE001 - native probes never crash callersreturn PermissionState.UNAVAILABLE+ def _screen_capture_live(self) -> bool:+ """Whether a live probe proves the frozen Screen Recording preflight wrong."""+ try:+ return self._screen_capture_live_check() is True+ except Exception: # noqa: BLE001 - native probes never crash callers+ return False+def _iohid_state(self, request_type: int) -> PermissionState | None:"""Tri-state TCC probe that separates "denied" from "not asked yet"."""try:@@ -487,7 +560,14 @@ class SystemPermissionPort:if permission_id is PermissionId.MICROPHONE:return self._microphone_state()if permission_id is PermissionId.SCREEN_RECORDING:- return self._boolean_state("Quartz", "CGPreflightScreenCaptureAccess")+ preflight = self._boolean_state("Quartz", "CGPreflightScreenCaptureAccess")+ if preflight is PermissionState.GRANTED:+ return preflight+ # The preflight is frozen per process and can only go stale+ # NEGATIVE. Ask the window server whether the grant works right+ # now before telling the user a permission they just gave is+ # missing (BUG-161).+ return PermissionState.GRANTED if self._screen_capture_live() else preflightif permission_id is PermissionId.ACCESSIBILITY:return self._boolean_state("ApplicationServices", "AXIsProcessTrusted")if permission_id is PermissionId.INPUT_MONITORING:@@ -607,6 +687,10 @@ class SystemPermissionPort:eligible = (self.platform == "darwin" and identity.stable and identity.foreground and not headless)+ # Opening a System Settings pane is not a prompt: it works from the+ # background, so it must not disappear together with the request+ # button when the user is looking at another window.+ settings_reachable = self.platform == "darwin" and identity.stable and not headlessfor permission_id in PermissionId:state = self._live_state(permission_id)states[permission_id] = state@@ -688,7 +772,7 @@ class SystemPermissionPort:can_request=can_request,# 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_open_settings=settings_reachable and permission_id in _SETTINGS_URLS,can_reset=can_reset,restart_required=restart_pending,detail=detail,@@ -734,7 +818,9 @@ class SystemPermissionPort:"restart_required": bool(self._restart_required),}- def _eligibility_error(self, snapshot: dict[str, Any]) -> str | None:+ def _eligibility_error(+ self, snapshot: dict[str, Any], *, needs_foreground: bool = True+ ) -> str | None:if self.platform != "darwin":return "macOS permission requests are not required on this platform."if snapshot["headless"]:@@ -745,7 +831,12 @@ class SystemPermissionPort:"Relaunch Personal Jarvis from its installed app before requesting ""permissions; granting access to Terminal or Python is unsafe.")- if not identity["foreground"]:+ # Only the native PROMPT needs the foreground — a dialog raised behind+ # other windows is a dialog the user never answers. Opening a Settings+ # pane through LaunchServices does not, and refusing it in the+ # background left the browser surface with a permission banner that+ # offered no way out at all (BUG-161).+ if needs_foreground and not identity["foreground"]:return "Bring Personal Jarvis to the foreground and try again."return None@@ -1030,7 +1121,7 @@ class SystemPermissionPort:f"Would open {_LABELS[permission_id]} in System Settings.",before,)- error = self._eligibility_error(before)+ error = self._eligibility_error(before, needs_foreground=False)if error is not None:return PermissionOperation(False,diff --git a/jarvis/setup/macos_app_bundle.py b/jarvis/setup/macos_app_bundle.pyindex aacfaaa229..d5922d5317 100644--- a/jarvis/setup/macos_app_bundle.py+++ b/jarvis/setup/macos_app_bundle.py@@ -234,6 +234,70 @@ def _reset_stale_tcc_grants(runner=subprocess.run) -> None:log.warning("TCC reset for %s failed: %s", service, detail[-300:])+# Fingerprint of the last rebuild this install performed. A rebuild that does+# not satisfy the very probe that triggered it is not a repair — it is a loop+# that costs the user every macOS permission on every start (BUG-161).+_REBUILD_MARKER_FILENAME = "macos-bundle-rebuild.json"+++def _rebuild_marker_path() -> Path:+ from jarvis.core.paths import user_data_dir++ return user_data_dir() / _REBUILD_MARKER_FILENAME+++def _rebuild_fingerprint(bundle: Path, *, install_root: Path) -> dict[str, str | None]:+ """Everything that decides whether a fresh build could come out different."""+ return {+ "cdhash": _bundle_cdhash(bundle),+ "install_root": str(install_root),+ "python": f"{sys.version_info.major}.{sys.version_info.minor}",+ "machine": platform.machine(),+ }+++def _record_rebuild(bundle: Path, *, install_root: Path) -> None:+ """Note what this rebuild produced, so a repeat of it can be recognized."""+ marker = _rebuild_marker_path()+ try:+ marker.parent.mkdir(parents=True, exist_ok=True)+ marker.write_text(+ json.dumps(_rebuild_fingerprint(bundle, install_root=install_root), sort_keys=True),+ encoding="utf-8",+ )+ except OSError:+ # Best-effort: without the note the next start rebuilds once more,+ # which is the behaviour that existed before this guard.+ log.debug("Could not record the macOS bundle rebuild fingerprint.", exc_info=True)+++def _rebuild_would_repeat(bundle: Path, *, install_root: Path) -> bool:+ """Whether rebuilding now would reproduce the build that just failed a probe.++ Same sources, same interpreter, same machine, and the bundle on disk is+ still byte-identical to what the last rebuild signed: a fresh build can+ only produce the same app and fail the same probe again. Doing it anyway+ changes the ad-hoc signature, and macOS answers a changed signature by+ orphaning every recorded TCC grant — the "I allow everything, restart, and+ it asks again" loop (BUG-161). A launchable bundle is worth more than a+ probe verdict that no rebuild can satisfy.+ """+ try:+ recorded = json.loads(_rebuild_marker_path().read_text(encoding="utf-8"))+ except (OSError, ValueError):+ # Nothing recorded, unreadable, or not JSON: to this caller they all+ # mean the same thing — no previous rebuild to compare against.+ return False+ if not isinstance(recorded, dict):+ return False+ current = _rebuild_fingerprint(bundle, install_root=install_root)+ if current["cdhash"] is None:+ # Without a readable signature we cannot prove the bundle is the one+ # the last rebuild produced, so the guard must not suppress a repair.+ return False+ return recorded == current++def _launchable_issue(candidate: Path) -> str | None:"""Name the first reason ``candidate`` is not a usable app bundle.@@ -718,15 +782,29 @@ def _runtime_identity_valid(probe.unlink(missing_ok=True)-def _current_process_identity_valid(- bundle: Path,+def _running_managed_bundle(*,install_root: Path,diagnostics: list[str] | None = None,-) -> bool:- """Recognize the already-running canonical app without spawning a probe."""+) -> Path | None:+ """Return the bundle THIS process runs from, when it is our managed app.++ A running process is proof no probe can beat: if we are executing as a+ bundle that carries our id and imports the managed checkout, the install+ is valid and must be left alone — wherever the user keeps the app.++ The location is deliberately NOT part of the verdict (BUG-161). Dragging+ an app to ``/Applications`` is the most ordinary thing a Mac user does,+ and the old path equality turned it into a permanent loop: the canonical+ ``~/Applications`` slot looked empty, every start rebuilt a bundle there,+ the rebuild changed the ad-hoc signature shared by both copies, and+ ``tccutil reset`` then wiped the grants of the app that was running at+ that moment. The user re-granted everything and the next start did it+ again. TCC pins grants to the bundle id and signature, never to a path,+ so the path can never be the reason to rebuild.+ """if sys.platform != "darwin":- return False+ return Nonetry:from Foundation import NSBundle # type: ignore[import-not-found]@@ -740,19 +818,19 @@ def _current_process_identity_valid(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 current_bundle.suffix != ".app":+ reasons.append(f"not running from an app bundle: {current_bundle}")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+ return None if reasons else current_bundleexcept (ImportError, OSError, TypeError, ValueError) as exc:if diagnostics is not None:diagnostics.append(f"current process: probe failed: {type(exc).__name__}: {exc}")- return False+ return Nonedef _install_native_bundle(install_root: Path, bundle: Path) -> Path:@@ -847,14 +925,18 @@ def ensure_macos_app_bundle(try:install_root = (install_dir or _default_install_dir()).resolve()bundle = macos_app_bundle_path(applications_dir=applications_dir)+ diagnostics: list[str] = []+ # The app running right now IS the installed app — including when the+ # user keeps it in /Applications. Nothing to repair, and a rebuild+ # under our bundle id here would strip the grants of the very process+ # asking the question (BUG-161).+ running = _running_managed_bundle(install_root=install_root, diagnostics=diagnostics)+ if running is not None:+ register_with_launch_services(running)+ return runninglaunchable_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, diagnostics=diagnostics- ) or _runtime_identity_valid(- bundle, install_root=install_root, diagnostics=diagnostics- ):+ if _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@@ -862,6 +944,20 @@ def ensure_macos_app_bundle(register_with_launch_services(bundle)return bundlelaunchable_issue = "; ".join(diagnostics) or "identity probe failed without detail"+ if _rebuild_would_repeat(bundle, install_root=install_root):+ # The last rebuild already produced exactly this bundle and the+ # probe still refuses it. Building it again would only change+ # the signature and cost the user every permission, so keep the+ # launchable app and say what is really wrong.+ log.warning(+ "The macOS app bundle failed its identity probe again after a rebuild "+ "that produced the identical app — keeping it so its macOS permissions "+ "survive. Reason: %s [%s]",+ launchable_issue,+ bundle,+ )+ register_with_launch_services(bundle)+ return bundle# 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@@ -875,6 +971,7 @@ def ensure_macos_app_bundle(return _write_cross_platform_fixture_bundle(bundle)installed = _install_native_bundle(install_root, bundle)register_with_launch_services(installed)+ _record_rebuild(installed, install_root=install_root)log.info("Native macOS app bundle installed: %s", installed)return installedexcept Exception as exc: # noqa: BLE001 - installer consumes the None resultdiff --git a/tests/unit/platform/test_permissions.py b/tests/unit/platform/test_permissions.pyindex e33634c241..5e15c47319 100644--- a/tests/unit/platform/test_permissions.py+++ b/tests/unit/platform/test_permissions.py@@ -139,6 +139,7 @@ def _port(iohid_check: Callable[[int], int | None] = lambda _type: None,credential_backend: Callable[[], str] = lambda: "platform",credential_recover: Callable[[], bool] = lambda: True,+ screen_capture_live: Callable[[], bool | None] = lambda: None,) -> SystemPermissionPort:def load(name: str) -> object:if name not in modules:@@ -147,11 +148,13 @@ def _port(# iohid_check defaults to "unavailable" so unit runs stay hermetic even on# a real Mac, where the default probe would read the machine's TCC state;- # the credential stubs keep the host's real keyring untouched the same way.+ # the credential and window-server stubs keep the host's real keyring and+ # screen untouched the same way.return SystemPermissionPort(platform_name="darwin",module_loader=load,iohid_check=iohid_check,+ screen_capture_live_check=screen_capture_live,credential_store_backend=credential_backend,credential_store_recover=credential_recover,)@@ -816,3 +819,102 @@ def test_credential_store_probe_failure_reports_unavailable() -> None:assert item["status"] == "unavailable"assert item["can_request"] is False+++# --- BUG-161: the app insisted permissions were missing after they were given+++def test_the_app_in_the_shared_applications_folder_is_a_stable_identity() -> None:+ """Dragging the app to /Applications is normal, not a tampering signal.++ The old rule accepted only ~/Applications, so the ordinary move turned the+ installed app into an "unstable identity": every request button vanished,+ every feature reported not-ready, and the banner kept demanding grants the+ user had already given, with nothing left to click (BUG-161).+ """+ modules, _, _ = _native_modules()+ shared_copy = SimpleNamespace(+ bundleIdentifier=lambda: EXPECTED_BUNDLE_ID,+ bundlePath=lambda: "/Applications/Personal Jarvis.app",+ )+ modules["Foundation"].NSBundle = SimpleNamespace(mainBundle=lambda: shared_copy)++ snapshot = _port(modules).snapshot()++ assert snapshot["app_identity"]["stable"] is True+ assert _permission(snapshot, PermissionId.MICROPHONE)["can_request"] is False+ assert snapshot["features"]["voice"]["identity_ready"] is True+++def test_a_live_window_probe_beats_the_frozen_screen_recording_preflight() -> None:+ """A grant given in System Settings mid-session must be seen at once.++ ``CGPreflightScreenCaptureAccess`` answers from a value frozen when the+ process first asked, so without a live probe the app reports the grant as+ missing no matter how often the user gives it.+ """+ modules, screen, _ = _native_modules()+ screen["granted"] = False++ stale = _port(modules, screen_capture_live=lambda: None)+ healed = _port(modules, screen_capture_live=lambda: True)++ assert stale.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED+ assert healed.state(PermissionId.SCREEN_RECORDING) is PermissionState.GRANTED+ assert healed.runtime_access_granted(PermissionId.SCREEN_RECORDING) is True+++def test_a_live_window_probe_never_invents_a_grant_the_preflight_denies() -> None:+ """An empty window list proves nothing; only a title upgrades the verdict."""+ modules, screen, _ = _native_modules()+ screen["granted"] = False++ port = _port(modules, screen_capture_live=lambda: False)++ assert port.state(PermissionId.SCREEN_RECORDING) is PermissionState.NOT_GRANTED+++def test_a_crashing_live_probe_leaves_the_preflight_verdict_intact() -> None:+ def _explode() -> bool | None:+ raise RuntimeError("window server is gone")++ modules, screen, _ = _native_modules()+ screen["granted"] = False++ assert (+ _port(modules, screen_capture_live=_explode).state(PermissionId.SCREEN_RECORDING)+ is PermissionState.NOT_GRANTED+ )+++def test_window_titles_prove_the_grant_only_from_another_apps_own_layer() -> None:+ from jarvis.platform.permissions import _window_titles_are_visible++ own = [{"kCGWindowLayer": 0, "kCGWindowOwnerPID": 42, "kCGWindowName": "Jarvis"}]+ chrome = [{"kCGWindowLayer": 25, "kCGWindowOwnerPID": 7, "kCGWindowName": "Menubar"}]+ nameless = [{"kCGWindowLayer": 0, "kCGWindowOwnerPID": 7, "kCGWindowName": ""}]+ foreign = [{"kCGWindowLayer": 0, "kCGWindowOwnerPID": 7, "kCGWindowName": "Safari"}]++ assert _window_titles_are_visible(own, 42) is None+ assert _window_titles_are_visible(chrome, 42) is None+ assert _window_titles_are_visible(nameless, 42) is None+ assert _window_titles_are_visible(None, 42) is None+ assert _window_titles_are_visible(foreign, 42) is True+++def test_open_settings_works_while_the_app_sits_in_the_background() -> None:+ """The Settings deep link is not a prompt, so it needs no foreground.++ Refusing it in the background left every non-foreground surface (the app+ behind System Settings, the browser view) with a permission banner whose+ only control answered "bring the app to the front" (BUG-161).+ """+ modules, _, workspace = _native_modules(active=False)++ snapshot = _port(modules).snapshot()+ operation = _port(modules).open_settings(PermissionId.MICROPHONE)++ assert snapshot["app_identity"]["foreground"] is False+ assert _permission(snapshot, PermissionId.MICROPHONE)["can_open_settings"] is True+ assert operation.ok is True+ assert workspace.opened_urlsdiff --git a/tests/unit/setup/test_macos_app_bundle.py b/tests/unit/setup/test_macos_app_bundle.pyindex c1051fa329..efe93fce0a 100644--- a/tests/unit/setup/test_macos_app_bundle.py+++ b/tests/unit/setup/test_macos_app_bundle.py@@ -81,8 +81,8 @@ def test_failed_runtime_probe_rebuilds_instead_of_preserving(tmp_path: Path, monmonkeypatch.setattr(mab, "_codesign_issue", lambda _bundle: None)monkeypatch.setattr(mab,- "_current_process_identity_valid",- lambda _bundle, *, install_root, diagnostics=None: False,+ "_running_managed_bundle",+ lambda *, install_root, diagnostics=None: None,)monkeypatch.setattr(mab,@@ -118,8 +118,8 @@ def test_running_canonical_app_skips_second_launchservices_probe(monkeypatch.setattr(mab, "_codesign_issue", lambda _bundle: None)monkeypatch.setattr(mab,- "_current_process_identity_valid",- lambda _bundle, *, install_root, diagnostics=None: True,+ "_running_managed_bundle",+ lambda *, install_root, diagnostics=None: bundle,)monkeypatch.setattr(mab,@@ -628,3 +628,193 @@ def test_a_recurring_rebuild_wipes_the_grants_only_once(tmp_path: Path, monkeypaassert sweeps == [1]assert marker.is_file()+++# --- BUG-161: a rebuild loop that wiped the grants on every single start+++def test_a_rebuild_that_reproduces_the_same_app_is_not_repeated(+ tmp_path: Path, monkeypatch+) -> None:+ """The loop that made the app forget every permission on every start.++ The identity probe can keep refusing a bundle for a reason no rebuild+ touches. Building the identical app again changes only its ad-hoc+ signature, and macOS answers a changed signature by orphaning every TCC+ grant — so the user allows everything, restarts, and is asked again.+ """+ import jarvis.setup.macos_app_bundle as mab++ bundle = _build(tmp_path, monkeypatch)+ marker = tmp_path / "macos-bundle-rebuild.json"+ monkeypatch.setattr(mab, "_rebuild_marker_path", lambda: marker)+ monkeypatch.setattr(mab, "_bundle_cdhash", lambda _bundle: "cdhash-one")+ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "_codesign_issue", lambda _bundle: None)+ monkeypatch.setattr(mab, "_running_managed_bundle", lambda *, install_root, **_kw: None)+ monkeypatch.setattr(+ mab,+ "_runtime_identity_valid",+ lambda _bundle, *, install_root, diagnostics=None: False,+ )+ rebuilds: list[Path] = []++ def _rebuild(install_root: Path, destination: Path) -> Path:+ rebuilds.append(destination)+ return destination++ monkeypatch.setattr(mab, "_install_native_bundle", _rebuild)+ install_dir = tmp_path / "install"+ applications = tmp_path / "Applications"++ first = ensure_macos_app_bundle(install_dir=install_dir, applications_dir=applications)+ second = ensure_macos_app_bundle(install_dir=install_dir, applications_dir=applications)++ assert first == second == bundle+ assert rebuilds == [bundle]+++def test_a_changed_interpreter_still_earns_a_fresh_rebuild(tmp_path: Path, monkeypatch) -> None:+ """The guard suppresses a repeat, never a build that could come out different."""+ import jarvis.setup.macos_app_bundle as mab++ bundle = _build(tmp_path, monkeypatch)+ marker = tmp_path / "macos-bundle-rebuild.json"+ marker.write_text(+ json.dumps(+ {+ "cdhash": "cdhash-one",+ "install_root": str((tmp_path / "install").resolve()),+ "python": "3.11",+ "machine": platform.machine(),+ },+ sort_keys=True,+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(mab, "_rebuild_marker_path", lambda: marker)+ monkeypatch.setattr(mab, "_bundle_cdhash", lambda _bundle: "cdhash-one")+ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "_codesign_issue", lambda _bundle: None)+ monkeypatch.setattr(mab, "_running_managed_bundle", lambda *, install_root, **_kw: None)+ monkeypatch.setattr(+ mab,+ "_runtime_identity_valid",+ lambda _bundle, *, install_root, diagnostics=None: False,+ )+ rebuilds: list[Path] = []+ monkeypatch.setattr(+ mab,+ "_install_native_bundle",+ lambda install_root, destination: (rebuilds.append(destination), destination)[1],+ )++ # The recorded note carries Python 3.11; this interpreter is a different+ # minor version, so a fresh build genuinely can produce a different app.+ assert f"{sys.version_info.major}.{sys.version_info.minor}" != "3.11"+ ensure_macos_app_bundle(+ install_dir=tmp_path / "install",+ applications_dir=tmp_path / "Applications",+ )++ assert rebuilds == [bundle]+++def test_a_broken_bundle_is_always_rebuilt_however_often_it_recurs(+ tmp_path: Path, monkeypatch+) -> None:+ """A bundle that cannot launch is a real repair — the loop guard must not block it."""+ import jarvis.setup.macos_app_bundle as mab++ bundle = _build(tmp_path, monkeypatch)+ marker = tmp_path / "macos-bundle-rebuild.json"+ monkeypatch.setattr(mab, "_rebuild_marker_path", lambda: marker)+ monkeypatch.setattr(mab, "_bundle_cdhash", lambda _bundle: "cdhash-one")+ monkeypatch.setattr(mab.sys, "platform", "darwin")+ monkeypatch.setattr(mab, "_launchable_issue", lambda _candidate: "executable is missing")+ monkeypatch.setattr(mab, "_running_managed_bundle", lambda *, install_root, **_kw: None)+ rebuilds: list[Path] = []+ monkeypatch.setattr(+ mab,+ "_install_native_bundle",+ lambda install_root, destination: (rebuilds.append(destination), destination)[1],+ )+ install_dir = tmp_path / "install"+ applications = tmp_path / "Applications"++ ensure_macos_app_bundle(install_dir=install_dir, applications_dir=applications)+ ensure_macos_app_bundle(install_dir=install_dir, applications_dir=applications)++ assert rebuilds == [bundle, bundle]+++def test_the_running_app_is_accepted_wherever_the_user_keeps_it(+ tmp_path: Path, monkeypatch+) -> None:+ """A copy in /Applications must never trigger a rebuild of the ~ slot.++ Both copies share our bundle id, so the rebuild's ``tccutil reset`` strips+ the permissions of the app that is running at that moment (BUG-161).+ """+ import jarvis.setup.macos_app_bundle as mab++ monkeypatch.setattr(mab.sys, "platform", "darwin")+ shared_copy = tmp_path / "SharedApplications" / APP_DIR_NAME+ monkeypatch.setattr(+ mab, "_running_managed_bundle", lambda *, install_root, **_kw: shared_copy+ )+ monkeypatch.setattr(+ mab,+ "_install_native_bundle",+ lambda *_args: pytest.fail("a running managed app must never be rebuilt"),+ )+ registered: list[Path] = []+ monkeypatch.setattr(mab, "register_with_launch_services", registered.append)++ result = ensure_macos_app_bundle(+ install_dir=tmp_path / "install",+ applications_dir=tmp_path / "Applications",+ )++ assert result == shared_copy+ assert registered == [shared_copy]+++def test_the_running_bundle_probe_ignores_the_install_location(monkeypatch) -> None:+ """Only the bundle id and the managed checkout decide — never the path."""+ import jarvis.setup.macos_app_bundle as mab+ import jarvis.ui.web.launcher as launcher++ install_root = Path(launcher.__file__).resolve().parents[3]+ running = Path("/Applications") / APP_DIR_NAME+ foundation = ModuleType("Foundation")+ foundation.NSBundle = SimpleNamespace( # type: ignore[attr-defined]+ mainBundle=lambda: SimpleNamespace(+ bundlePath=lambda: str(running),+ bundleIdentifier=lambda: mab.BUNDLE_ID,+ )+ )+ monkeypatch.setitem(sys.modules, "Foundation", foundation)+ monkeypatch.setattr(mab.sys, "platform", "darwin")++ assert mab._running_managed_bundle(install_root=install_root) == running.resolve()+++def test_a_foreign_bundle_id_is_never_taken_for_the_managed_app(monkeypatch) -> None:+ import jarvis.setup.macos_app_bundle as mab++ foundation = ModuleType("Foundation")+ foundation.NSBundle = SimpleNamespace( # type: ignore[attr-defined]+ mainBundle=lambda: SimpleNamespace(+ bundlePath=lambda: "/Applications/Terminal.app",+ bundleIdentifier=lambda: "com.apple.Terminal",+ )+ )+ monkeypatch.setitem(sys.modules, "Foundation", foundation)+ monkeypatch.setattr(mab.sys, "platform", "darwin")+ diagnostics: list[str] = []++ assert (+ mab._running_managed_bundle(install_root=Path.cwd(), diagnostics=diagnostics) is None+ )+ assert any("bundle id" in reason for reason in diagnostics)