Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(macos): heal orphaned TCC grants, stale Settings panes, and the dead Allow button (BUG-083)

Ruben Lütke47ed233b9b60
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 35060f1fb3..075122b984 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -5722,3 +5722,58 @@ history and the dedup ledger, and the two errors compound. And guard paths
that refuse an action must be OBSERVABLE (log + progress + recorder event):
a guard that only whispers to the model turns every interaction bug into an
unexplainable early abort.
+
+---
+
+## BUG-083: macOS permissions "auto-denied" after an app update, Settings deep links landing on the wrong pane, and a dead second Allow button (HIGH, FIXED 2026-07-18)
+
+**Symptom (live Intel test Mac, macOS 15.7, first run after the v1.0.11
+update).** The onboarding permissions view showed Input Monitoring and Input
+Control as DENIED although macOS never showed a prompt; Microphone had
+reverted to "not asked". "Open Settings" for those rows surfaced System
+Settings on an unrelated pane (the last-open Files & Folders pane with the
+Documents-folder rows) instead of the requested one. Screen Recording kept
+reading NOT ALLOWED after the user granted it, and a second click on Allow
+did nothing.
+
+**Root causes (three independent defects).**
+1. *Signature churn orphans TCC grants:* the app is ad-hoc signed, so macOS
+ pins every TCC grant to the executable's CDHash. The BUG-079 bundle-format
+ bump forced a rebuild → new CDHash → macOS treated the updated app as a
+ stranger: HID-class services (ListenEvent/PostEvent) report the orphaned
+ rows as DENIED — a state in which macOS suppresses every further prompt —
+ while AVFoundation reverts to "not determined". Nothing in the app ever
+ asked; the denial was inherited from a dead identity.
+2. *System Settings ignores pane anchors while running:* the
+ `x-apple.systempreferences:...?Privacy_*` URL only raises an already-open
+ System Settings window on whatever pane it last showed. Microphone/Screen
+ Recording "worked" earlier in the flow only because System Settings was
+ not running yet at that point.
+3. *Frozen Screen Recording preflight + one-shot prompts:*
+ `CGPreflightScreenCaptureAccess` is frozen per process, so a mid-session
+ grant stays invisible until relaunch, and macOS never re-prompts after the
+ first request — yet the UI kept showing the stale state AND a request
+ button that could never do anything again.
+
+**Fix (2026-07-18).** (a) `_install_native_bundle` records the CDHash before
+and after a rebuild; on a real signature change it resets the five TCC
+services scoped to `com.personal-jarvis.desktop` via `tccutil` so macOS can
+prompt fresh instead of inheriting orphaned denials; bundle format bumped to
+3 so affected installs go through exactly one healing rebuild. (b)
+`_open_settings` terminates a running System Settings (no TCC needed) before
+opening the anchor URL, so LaunchServices relaunches it on the requested
+pane. (c) While a restart is pending, `can_request` is false (the dead Allow
+button disappears), the detail explains the restart, and the frontend shows
+"Restart pending" instead of the stale state for the one frozen probe
+(screen recording). Guards: `tests/unit/platform/test_permissions.py::
+test_open_settings_quits_running_system_settings_before_navigating`,
+`::test_screen_capture_restart_pending_hides_the_dead_allow_button`, and the
+`_tcc_reset_*` tests in `tests/unit/setup/test_macos_app_bundle.py`.
+
+**Class rule.** An ad-hoc-signed app's TCC identity IS its CDHash: any forced
+rebuild silently voids every recorded grant, and the orphaned rows come back
+as invisible denials, not as fresh prompts — pair every identity-changing
+rebuild with a scoped `tccutil` reset (and long-term, a stable signing
+identity). Never surface a permission request control the OS will ignore:
+macOS prompts exactly once per TCC state, and reads some probes only at
+process start — the UI must model both or it gaslights the user.
diff --git a/jarvis/platform/permissions.py b/jarvis/platform/permissions.py
index add8d311a2..748264f115 100644
--- a/jarvis/platform/permissions.py
+++ b/jarvis/platform/permissions.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import importlib
import logging
import os
+import time
from collections.abc import Callable
from dataclasses import asdict, dataclass
from enum import StrEnum
@@ -23,6 +24,7 @@ log = logging.getLogger(__name__)
EXPECTED_BUNDLE_ID = "com.personal-jarvis.desktop"
APP_NAME = "Personal Jarvis"
+_SYSTEM_SETTINGS_BUNDLE_ID = "com.apple.systempreferences"
class PermissionId(StrEnum):
@@ -424,8 +426,14 @@ class SystemPermissionPort:
for feature, requirements in FEATURE_REQUIREMENTS.items()
if permission_id in requirements
)
+ restart_pending = permission_id in self._restart_required
+ # After the first request/settings visit macOS never re-prompts in
+ # this process (and the Screen Recording preflight stays frozen
+ # until relaunch), so a second request button would be a dead
+ # control — hide it and let the restart call-to-action take over.
can_request = (
eligible
+ and not restart_pending
and self._requester_available(permission_id)
and state
not in {
@@ -436,6 +444,12 @@ class SystemPermissionPort:
PermissionState.UNAVAILABLE,
}
)
+ detail = self._detail(state)
+ if restart_pending and state not in _READY_STATES:
+ detail = (
+ "Permission changes made in System Settings take effect "
+ "after Personal Jarvis restarts."
+ )
statuses.append(
PermissionStatus(
id=permission_id.value,
@@ -444,8 +458,8 @@ class SystemPermissionPort:
required=required,
can_request=can_request,
can_open_settings=eligible,
- restart_required=permission_id in self._restart_required,
- detail=self._detail(state),
+ restart_required=restart_pending,
+ detail=detail,
)
)
@@ -596,11 +610,41 @@ class SystemPermissionPort:
after,
)
+ def _quit_system_settings(self, appkit: Any) -> None:
+ """Close a running System Settings so the pane deep link can navigate.
+
+ System Settings ignores the ``x-apple.systempreferences`` anchor while
+ it is already running: the URL merely raises the existing window on
+ whatever pane it last showed (observed live on macOS 15.7 — the Input
+ Monitoring link surfaced the stale Files & Folders pane instead).
+ Terminating first makes LaunchServices relaunch it directly on the
+ requested pane. ``NSRunningApplication.terminate`` needs no TCC grant;
+ everything here is best-effort and never blocks the open call.
+ """
+ runner = getattr(appkit, "NSRunningApplication", None)
+ lookup = getattr(runner, "runningApplicationsWithBundleIdentifier_", None)
+ if not callable(lookup):
+ return
+ try:
+ running = list(lookup(_SYSTEM_SETTINGS_BUNDLE_ID) or [])
+ if not running:
+ return
+ for app in running:
+ app.terminate()
+ deadline = time.monotonic() + 2.0
+ while time.monotonic() < deadline:
+ if all(bool(app.isTerminated()) for app in running):
+ break
+ time.sleep(0.05)
+ except Exception: # noqa: BLE001 - closing Settings is best-effort
+ log.debug("Could not close a running System Settings.", exc_info=True)
+
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
+ self._quit_system_settings(appkit)
url = foundation.NSURL.URLWithString_(_SETTINGS_URLS[permission_id])
return bool(appkit.NSWorkspace.sharedWorkspace().openURL_(url))
diff --git a/jarvis/setup/macos_app_bundle.py b/jarvis/setup/macos_app_bundle.py
index 2e541c3dcb..23861c8b4f 100644
--- a/jarvis/setup/macos_app_bundle.py
+++ b/jarvis/setup/macos_app_bundle.py
@@ -10,9 +10,15 @@ AND non-framework interpreters (for example uv-managed standalone builds)
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.
+ordinary source updates so its local TCC identity does not churn. When a
+rebuild is unavoidable (format bump, broken bundle), the ad-hoc code signature
+changes and macOS orphans every previously recorded TCC grant — the old rows
+then read as silently DENIED for the "new" app and macOS never prompts again
+(BUG-083). After such a signature change this module therefore resets the
+stale TCC rows for our bundle id via ``tccutil`` so the app can prompt fresh.
+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
@@ -40,7 +46,19 @@ BUNDLE_ID = "com.personal-jarvis.desktop"
# 2: stub launcher sets only LC_CTYPE (BUG-079 — LC_ALL leaked a de_DE
# LC_NUMERIC into native libs; libvosk then emitted malformed JSON). Bumping
# forces existing bundles through a rebuild on the next ensure pass.
-_BUNDLE_FORMAT_VERSION = 2
+# 3: one forced rebuild so the new signature-change TCC reset (BUG-083) heals
+# bundles whose grants were orphaned by the version-2 rebuild.
+_BUNDLE_FORMAT_VERSION = 3
+
+# TCC service names this app ever requests; reset scope is always limited to
+# our own bundle id, never the whole service (BUG-083).
+_TCC_SERVICES: tuple[str, ...] = (
+ "Microphone",
+ "ScreenCapture",
+ "Accessibility",
+ "ListenEvent",
+ "PostEvent",
+)
_MACHO_MAGICS = frozenset(
{
b"\xfe\xed\xfa\xce",
@@ -69,8 +87,7 @@ _SCREEN_CAPTURE_USAGE = (
"Personal Jarvis captures the screen only when you ask it to see or control applications."
)
_APPLE_EVENTS_USAGE = (
- "Personal Jarvis lowers Music/Spotify volume while you dictate and "
- "restores it afterwards."
+ "Personal Jarvis lowers Music/Spotify volume while you dictate and restores it afterwards."
)
@@ -151,6 +168,67 @@ 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``.
+
+ An ad-hoc signature has no certificate chain, so macOS pins TCC grants to
+ the CDHash of the main executable. Two bundles with different CDHashes are
+ different apps to TCC even under the same bundle id.
+ """
+ if sys.platform != "darwin":
+ return None
+ try:
+ result = subprocess.run(
+ ["/usr/bin/codesign", "--display", "--verbose=4", str(bundle)],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ # codesign prints the display block on stderr.
+ match = re.search(r"^CDHash=([0-9a-f]+)", result.stderr or "", re.MULTILINE)
+ return match.group(1) if match else None
+
+
+def _tcc_reset_needed(previous_cdhash: str | None, current_cdhash: str | None) -> bool:
+ """A signature change (or an unknowable previous one) orphans TCC rows."""
+ return current_cdhash is not None and previous_cdhash != current_cdhash
+
+
+def _reset_stale_tcc_grants(runner=subprocess.run) -> None:
+ """Drop this app's orphaned TCC rows so macOS can prompt fresh (BUG-083).
+
+ After a signature change the recorded grants belong to the OLD CDHash: the
+ rebuilt app reads them as DENIED and macOS suppresses every further prompt,
+ so permissions appear "auto-rejected" without the user ever being asked.
+ Resetting is scoped to our bundle id, is best-effort per service, and never
+ raises — a failed reset leaves behavior no worse than before. The caller
+ (`_install_native_bundle`) only runs on macOS; the injectable runner keeps
+ this unit-testable on every OS.
+ """
+ for service in _TCC_SERVICES:
+ try:
+ result = runner(
+ ["/usr/bin/tccutil", "reset", service, BUNDLE_ID],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ log.warning("TCC reset for %s did not run: %s", service, exc)
+ continue
+ if result.returncode == 0:
+ log.info("Reset stale TCC rows for %s (%s).", service, BUNDLE_ID)
+ else:
+ detail = (result.stderr or result.stdout or "unknown error").strip()
+ log.warning("TCC reset for %s failed: %s", service, detail[-300:])
+
+
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()
@@ -311,18 +389,14 @@ def _runtime_link_info(venv_python: Path) -> dict:
creationflags=NO_WINDOW_CREATIONFLAGS,
)
except (OSError, subprocess.TimeoutExpired) as exc:
- raise RuntimeError(
- f"could not query the venv interpreter {venv_python}: {exc}"
- ) from exc
+ raise RuntimeError(f"could not query the venv interpreter {venv_python}: {exc}") from exc
if result.returncode != 0:
detail = (result.stderr or result.stdout or "unknown interpreter error").strip()
raise RuntimeError(f"venv runtime introspection failed: {detail[-1200:]}")
try:
return json.loads(result.stdout.strip().splitlines()[-1])
except (ValueError, IndexError) as exc:
- raise RuntimeError(
- f"venv runtime introspection returned invalid JSON: {exc}"
- ) from exc
+ raise RuntimeError(f"venv runtime introspection returned invalid JSON: {exc}") from exc
# A fully versioned uv/python-build-standalone prefix directory name, for
@@ -364,9 +438,7 @@ def _resolve_runtime_dylib(info: dict) -> Path:
if not ldlibrary:
raise RuntimeError("the venv interpreter reported no LDLIBRARY config variable")
roots = [
- Path(str(root))
- for root in (info.get("LIBDIR"), info.get("PYTHONFRAMEWORKPREFIX"))
- if root
+ Path(str(root)) for root in (info.get("LIBDIR"), info.get("PYTHONFRAMEWORKPREFIX")) if root
]
base_prefix = str(info.get("base_prefix") or "")
if base_prefix:
@@ -424,9 +496,7 @@ def _compile_stub(
raise RuntimeError(f"stub launcher compilation failed: {exc}; {hint}") from exc
if result.returncode != 0:
detail = (result.stderr or result.stdout or "unknown clang error").strip()
- raise RuntimeError(
- f"stub launcher compilation failed: {detail[-1200:]}; {hint}"
- )
+ raise RuntimeError(f"stub launcher compilation failed: {detail[-1200:]}; {hint}")
def _build_native_bundle(install_root: Path, work_dir: Path) -> Path:
@@ -475,9 +545,7 @@ def _build_native_bundle(install_root: Path, work_dir: Path) -> Path:
defines,
executable,
)
- executable.chmod(
- executable.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
- )
+ executable.chmod(executable.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
with (bundle / "Contents" / "Info.plist").open("wb") as stream:
plistlib.dump(plist, stream)
return bundle
@@ -536,8 +604,7 @@ def _runtime_identity_valid(
if diagnostics is not None:
stderr_tail = (result.stderr or "").strip()[-500:]
diagnostics.append(
- f"open returncode {result.returncode}, "
- f"stderr tail: {stderr_tail or '(empty)'}"
+ f"open returncode {result.returncode}, stderr tail: {stderr_tail or '(empty)'}"
)
if result.returncode != 0 or not probe.is_file():
if diagnostics is not None and not probe.is_file():
@@ -600,6 +667,7 @@ 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)
+ previous_cdhash = _bundle_cdhash(bundle) if bundle.exists() else None
with tempfile.TemporaryDirectory(prefix=".jarvis-native-", dir=parent) as raw_work:
work = Path(raw_work)
built = _build_native_bundle(install_root, work)
@@ -620,14 +688,17 @@ def _install_native_bundle(install_root: Path, bundle: Path) -> Path:
):
detail = "; ".join(diagnostics) or "no probe diagnostics captured"
raise RuntimeError(
- "the installed app reported an unexpected runtime identity "
- f"({detail})"
+ f"the installed app reported an unexpected runtime identity ({detail})"
)
except Exception:
_remove_path(bundle)
if previous.exists() or previous.is_symlink():
previous.rename(bundle)
raise
+ if _tcc_reset_needed(previous_cdhash, _bundle_cdhash(bundle)):
+ # The rebuild changed the app's TCC identity: every recorded grant is
+ # now orphaned and would read as silently DENIED (BUG-083).
+ _reset_stale_tcc_grants()
return bundle
diff --git a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsx b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsx
index 129f382558..75c14a232c 100644
--- a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.test.tsx
@@ -125,6 +125,31 @@ describe("PermissionsAlertBanner", () => {
expect(screen.getByRole("button", { name: "permissions.restart_now" })).toBeDefined();
});
+ it("labels a restart-pending screen recording honestly instead of the frozen state", () => {
+ // CGPreflightScreenCaptureAccess is frozen per process: after granting in
+ // System Settings the probe still reports not_granted until relaunch. The
+ // stale label plus a dead Allow button was the live 2026-07-18 Mac finding.
+ mockSnapshot = darwinSnapshot({
+ permissions: [
+ {
+ id: "screen_recording",
+ status: "not_granted",
+ required: ["computer_use"],
+ can_request: false,
+ can_open_settings: true,
+ restart_required: true,
+ },
+ ],
+ features: { computer_use: { ready: false, missing: ["screen_recording"] } },
+ restart_required: true,
+ });
+ render(<PermissionsAlertBanner />);
+
+ expect(screen.getByText("permissions.status.restart_pending")).toBeDefined();
+ expect(screen.queryByText("permissions.status.not_granted")).toBeNull();
+ expect(screen.queryByRole("button", { name: "permissions.request" })).toBeNull();
+ });
+
it("renders nothing on other platforms", () => {
mockSnapshot = darwinSnapshot({ platform: "win32" });
render(<PermissionsAlertBanner />);
diff --git a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx
index 49d77ab811..c259e0e72a 100644
--- a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx
@@ -186,6 +186,13 @@ function MissingPermissionRow({
// A newer backend may report a permission id this build does not know yet;
// fall back to the generic shield instead of rendering `undefined`.
const Icon = ICONS[item.id] ?? ShieldAlert;
+ // Screen Recording's probe is frozen per process (see PermissionsPanel):
+ // once a restart is pending, the stale "not granted" would gaslight the
+ // user who just granted it — show the honest pending label instead.
+ const statusKey =
+ item.restart_required && item.id === "screen_recording"
+ ? "restart_pending"
+ : item.status;
return (
<div className="flex flex-wrap items-center gap-3 rounded-lg border border-amber-500/30 bg-background/40 p-3">
@@ -199,7 +206,7 @@ function MissingPermissionRow({
</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.${item.status}`)}
+ {t(`permissions.status.${statusKey}`)}
</span>
{item.can_request && (
<Button size="sm" disabled={busy} onClick={onRequest}>
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index a20c6b1072..6932fc647b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1064,7 +1064,8 @@
"restricted": "Eingeschränkt",
"not_granted": "Nicht erlaubt",
"unavailable": "Nicht verfügbar",
- "not_required": "Nicht erforderlich"
+ "not_required": "Nicht erforderlich",
+ "restart_pending": "Neustart ausstehend"
},
"items": {
"microphone": { "title": "Mikrofon", "description": "Erforderlich für Aktivierungswort und lokale Spracheingabe." },
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 865e026164..4b2d5147cc 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1065,7 +1065,8 @@
"restricted": "Restricted",
"not_granted": "Not allowed",
"unavailable": "Unavailable",
- "not_required": "Not required"
+ "not_required": "Not required",
+ "restart_pending": "Restart pending"
},
"items": {
"microphone": { "title": "Microphone", "description": "Required for wake-word and local voice input." },
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index def3564459..8cbbc48eab 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1064,7 +1064,8 @@
"restricted": "Restringido",
"not_granted": "No permitido",
"unavailable": "No disponible",
- "not_required": "No requerido"
+ "not_required": "No requerido",
+ "restart_pending": "Reinicio pendiente"
},
"items": {
"microphone": { "title": "Micrófono", "description": "Necesario para la palabra de activación y la entrada de voz local." },
diff --git a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx
index e7d22e068c..1d220e102f 100644
--- a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx
@@ -160,6 +160,14 @@ function PermissionRow({
// "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;
+ // Screen Recording is the one probe macOS freezes per process: after the
+ // user grants it in System Settings, the live value stays stale until the
+ // app restarts. Show the honest pending label instead of the stale state;
+ // every other permission reads live TCC state and keeps its real status.
+ const statusKey =
+ !ready && item.restart_required && item.id === "screen_recording"
+ ? "restart_pending"
+ : item.status;
return (
<div className={`rounded-lg border border-border bg-background/40 ${compact ? "p-3" : "p-4"}`}>
@@ -180,7 +188,7 @@ function PermissionRow({
: "bg-amber-500/10 text-amber-500"
}`}
>
- {t(`permissions.status.${item.status}`)}
+ {t(`permissions.status.${statusKey}`)}
</span>
{showRequest && (
<Button size="sm" disabled={busy} onClick={onRequest}>
diff --git a/tests/unit/platform/test_permissions.py b/tests/unit/platform/test_permissions.py
index 57af4a8f9e..7b2f6c8030 100644
--- a/tests/unit/platform/test_permissions.py
+++ b/tests/unit/platform/test_permissions.py
@@ -464,6 +464,68 @@ def test_open_settings_uses_permission_specific_launchservices_url() -> None:
]
+def test_open_settings_quits_running_system_settings_before_navigating() -> None:
+ # System Settings ignores the pane anchor while already running: the URL
+ # only raises the stale window (live on macOS 15.7 the Input Monitoring
+ # link surfaced the last-open Files & Folders pane). The port must quit a
+ # running System Settings first so LaunchServices relaunches it on the
+ # requested pane.
+ modules, _, workspace = _native_modules()
+ order: list[str] = []
+
+ class _SettingsApp:
+ def __init__(self) -> None:
+ self._terminated = False
+
+ def terminate(self) -> None:
+ order.append("terminate")
+ self._terminated = True
+
+ def isTerminated(self) -> bool:
+ return self._terminated
+
+ lookups: list[str] = []
+
+ def lookup(bundle_id: str) -> list[_SettingsApp]:
+ lookups.append(bundle_id)
+ return [settings_app]
+
+ settings_app = _SettingsApp()
+ appkit = modules["AppKit"]
+ appkit.NSRunningApplication.runningApplicationsWithBundleIdentifier_ = lookup
+ original_open = workspace.openURL_
+
+ def open_url(url: str) -> bool:
+ order.append("open")
+ return original_open(url)
+
+ workspace.openURL_ = open_url
+
+ result = _port(modules).open_settings(PermissionId.INPUT_MONITORING)
+
+ assert result.ok is True
+ assert lookups == ["com.apple.systempreferences"]
+ assert order == ["terminate", "open"]
+
+
+def test_screen_capture_restart_pending_hides_the_dead_allow_button() -> None:
+ # CGPreflightScreenCaptureAccess stays frozen for the process lifetime, and
+ # macOS never re-prompts after the first request — a second visible Allow
+ # button could only ever do nothing (live Mac finding 2026-07-18).
+ modules, screen, _ = _native_modules()
+ port = _port(modules)
+
+ port.request(PermissionId.SCREEN_RECORDING)
+ # Mimic the real frozen preflight: the grant is invisible until relaunch.
+ screen["granted"] = False
+ item = _permission(port.snapshot(), PermissionId.SCREEN_RECORDING)
+
+ assert item["status"] == "not_granted"
+ assert item["restart_required"] is True
+ assert item["can_request"] is False
+ assert "restart" in (item["detail"] or "").lower()
+
+
def test_missing_framework_reports_unavailable_without_raising() -> None:
modules, _, _ = _native_modules()
del modules["Quartz"]
diff --git a/tests/unit/setup/test_macos_app_bundle.py b/tests/unit/setup/test_macos_app_bundle.py
index 574608e93b..9524542734 100644
--- a/tests/unit/setup/test_macos_app_bundle.py
+++ b/tests/unit/setup/test_macos_app_bundle.py
@@ -511,3 +511,57 @@ def test_launcher_identity_probe_uses_main_bundle(tmp_path: Path, monkeypatch) -
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}",
"machine": platform.machine(),
}
+
+
+def test_tcc_reset_needed_only_on_a_real_signature_change() -> None:
+ from jarvis.setup.macos_app_bundle import _tcc_reset_needed
+
+ # A rebuild that produced a NEW code signature orphans the recorded TCC
+ # rows (BUG-083) — including the fresh-install case with no prior bundle.
+ assert _tcc_reset_needed("aaaa", "bbbb") is True
+ assert _tcc_reset_needed(None, "bbbb") is True
+ # Identical signature or an unreadable new one must never trigger a reset.
+ assert _tcc_reset_needed("aaaa", "aaaa") is False
+ assert _tcc_reset_needed("aaaa", None) is False
+ assert _tcc_reset_needed(None, None) is False
+
+
+def test_reset_stale_tcc_grants_scopes_every_service_to_our_bundle_id() -> None:
+ import jarvis.setup.macos_app_bundle as mab
+
+ commands: list[list[str]] = []
+
+ def runner(command, **_kwargs):
+ commands.append(list(command))
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ mab._reset_stale_tcc_grants(runner=runner)
+
+ assert commands == [
+ ["/usr/bin/tccutil", "reset", service, mab.BUNDLE_ID]
+ for service in mab._TCC_SERVICES
+ ]
+ assert set(mab._TCC_SERVICES) == {
+ "Microphone",
+ "ScreenCapture",
+ "Accessibility",
+ "ListenEvent",
+ "PostEvent",
+ }
+
+
+def test_reset_stale_tcc_grants_survives_a_failing_tccutil() -> None:
+ import jarvis.setup.macos_app_bundle as mab
+
+ attempts: list[str] = []
+
+ def runner(command, **_kwargs):
+ attempts.append(command[2])
+ if command[2] == "ScreenCapture":
+ raise OSError("tccutil missing")
+ return SimpleNamespace(returncode=1, stdout="", stderr="denied")
+
+ # Best-effort contract: one broken service never aborts the sweep.
+ mab._reset_stale_tcc_grants(runner=runner)
+
+ assert attempts == list(mab._TCC_SERVICES)