Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver-rs): re-exec daemon to refresh TCC trust cache (macOS) (#1567)

Francesco Bonacci831255fbf31c
diff --git a/libs/cua-driver-rs/Cargo.lock b/libs/cua-driver-rs/Cargo.lock
index 9a829995db..30de63309a 100644
--- a/libs/cua-driver-rs/Cargo.lock
+++ b/libs/cua-driver-rs/Cargo.lock
@@ -242,7 +242,7 @@ dependencies = [
[[package]]
name = "cua-driver"
-version = "0.2.4"
+version = "0.2.5"
dependencies = [
"anyhow",
"async-trait",
@@ -270,7 +270,7 @@ dependencies = [
[[package]]
name = "cursor-overlay"
-version = "0.2.4"
+version = "0.2.5"
dependencies = [
"anyhow",
"image",
@@ -407,7 +407,7 @@ checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
[[package]]
name = "focus-monitor-win"
-version = "0.2.4"
+version = "0.2.5"
dependencies = [
"windows",
]
@@ -844,7 +844,7 @@ dependencies = [
[[package]]
name = "mcp-server"
-version = "0.2.4"
+version = "0.2.5"
dependencies = [
"anyhow",
"async-trait",
@@ -1130,7 +1130,7 @@ checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
[[package]]
name = "platform-linux"
-version = "0.2.4"
+version = "0.2.5"
dependencies = [
"anyhow",
"async-trait",
@@ -1149,7 +1149,7 @@ dependencies = [
[[package]]
name = "platform-macos"
-version = "0.2.4"
+version = "0.2.5"
dependencies = [
"anyhow",
"async-trait",
@@ -1179,7 +1179,7 @@ dependencies = [
[[package]]
name = "platform-windows"
-version = "0.2.4"
+version = "0.2.5"
dependencies = [
"anyhow",
"async-trait",
diff --git a/libs/cua-driver-rs/crates/platform-macos/src/permissions/gate.rs b/libs/cua-driver-rs/crates/platform-macos/src/permissions/gate.rs
index c11df4a9c2..a96f69bee1 100644
--- a/libs/cua-driver-rs/crates/platform-macos/src/permissions/gate.rs
+++ b/libs/cua-driver-rs/crates/platform-macos/src/permissions/gate.rs
@@ -341,10 +341,28 @@ fn present_panel_if_available(initial: PermissionsStatus) -> PanelPresentation {
///
/// Exposed separately from [`run_if_needed`] for callers that want to
/// drive the wait phase manually (e.g. tests that pre-skip the banner).
+///
+/// macOS quirk: `AXIsProcessTrusted()` and `CGPreflightScreenCaptureAccess()`
+/// cache their results per-process. The cache survives both
+/// `tccutil reset` and live `System Settings` toggle flips — once a
+/// process has seen `false`, polling will keep returning `false`
+/// forever for that process even after the user grants the permission.
+///
+/// Pumping the AppKit run loop (which we tried first) does not flush
+/// the cache. The only reliable fix is to **re-execute the binary**
+/// (`execvp` the current image with the same argv): the new process
+/// image gets a fresh TCC client and re-queries tccd cleanly.
+///
+/// Strategy: after every `EXEC_AFTER_POLLS` polls without progress,
+/// we exec ourselves. Light enough (process start is fast) that this
+/// is invisible to the user — they just see a "rechecking" status
+/// line. If the grant has been given the new process picks it up
+/// instantly; otherwise it falls back into the same wait loop.
pub fn wait_for_grants(opts: &GateOpts) -> Result<()> {
let start = Instant::now();
let mut last_status_print = start;
let mut last_missing: Vec<MissingPermission> = check_required_permissions();
+ let mut polls_without_change: u32 = 0;
loop {
if last_missing.is_empty() {
@@ -363,6 +381,28 @@ pub fn wait_for_grants(opts: &GateOpts) -> Result<()> {
}
}
+ // On macOS, when polling has gone several iterations without
+ // any change, re-exec the binary to invalidate the per-process
+ // TCC cache. See the function-level doc for the rationale.
+ // Threshold of 5 polls (~5s) is tuned to feel snappy without
+ // exec-spinning when the user is mid-grant.
+ #[cfg(target_os = "macos")]
+ {
+ const EXEC_AFTER_POLLS: u32 = 5;
+ if polls_without_change >= EXEC_AFTER_POLLS {
+ println!(
+ "[cua-driver] rechecking permissions (still missing: {})",
+ fmt_missing(&last_missing)
+ );
+ let _ = std::io::stdout().flush();
+ reexec_self();
+ // `reexec_self` only returns on failure; if it does,
+ // continue the loop with a reset counter so we don't
+ // spin-exec.
+ polls_without_change = 0;
+ }
+ }
+
std::thread::sleep(opts.poll_interval);
let new_missing = check_required_permissions();
@@ -378,8 +418,10 @@ pub fn wait_for_grants(opts: &GateOpts) -> Result<()> {
}
last_status_print = Instant::now();
last_missing = new_missing;
+ polls_without_change = 0;
continue;
}
+ polls_without_change = polls_without_change.saturating_add(1);
if last_status_print.elapsed() >= opts.status_interval {
println!(
@@ -393,6 +435,61 @@ pub fn wait_for_grants(opts: &GateOpts) -> Result<()> {
}
}
+/// Replace the current process image with a fresh copy of the same
+/// binary + argv via `execvp(2)`. Used by [`wait_for_grants`] on
+/// macOS to invalidate the per-process TCC trust cache after the
+/// user has granted permissions in System Settings — `AXIsProcessTrusted`
+/// won't see the grant inside the original process otherwise.
+///
+/// `execvp` only returns on failure; on success, control transfers to
+/// the new process image at the C `main` entry and the rest of this
+/// function is never executed. Caller continues if the call fails so
+/// the gate keeps polling rather than aborting hard.
+#[cfg(target_os = "macos")]
+fn reexec_self() {
+ use std::ffi::CString;
+ use std::os::unix::ffi::OsStringExt;
+
+ // Resolve the path to ourselves. `current_exe` returns the actual
+ // binary path (e.g. /Applications/CuaDriver.app/Contents/MacOS/
+ // cua-driver) which is what we want — execvp searches PATH for
+ // bare names, and we don't want a stale `~/.local/bin/cua-driver`
+ // symlink to win.
+ let Ok(exe) = std::env::current_exe() else {
+ eprintln!("[cua-driver] re-exec failed: cannot resolve current_exe");
+ return;
+ };
+ let argv: Vec<CString> = std::env::args_os()
+ .filter_map(|a| CString::new(a.into_vec()).ok())
+ .collect();
+ if argv.is_empty() {
+ eprintln!("[cua-driver] re-exec failed: empty argv");
+ return;
+ }
+
+ // execvp takes a NULL-terminated argv. Build pointers + sentinel.
+ let mut argv_ptrs: Vec<*const libc::c_char> =
+ argv.iter().map(|s| s.as_ptr()).collect();
+ argv_ptrs.push(std::ptr::null());
+
+ let exe_c = match CString::new(exe.into_os_string().into_vec()) {
+ Ok(c) => c,
+ Err(e) => {
+ eprintln!("[cua-driver] re-exec failed: exe path contains NUL ({e})");
+ return;
+ }
+ };
+
+ // execvp returns -1 on failure; on success it does not return.
+ // SAFETY: argv_ptrs is NULL-terminated; exe_c outlives the call.
+ unsafe {
+ libc::execvp(exe_c.as_ptr(), argv_ptrs.as_ptr());
+ }
+ // If we get here the exec failed.
+ let err = std::io::Error::last_os_error();
+ eprintln!("[cua-driver] re-exec failed: {err}");
+}
+
fn print_banner(missing: &[MissingPermission], open_settings: bool) {
println!();
println!("──────────────────────────────────────────────────────────────");
diff --git a/libs/cua-driver-rs/crates/platform-macos/src/permissions/panel.rs b/libs/cua-driver-rs/crates/platform-macos/src/permissions/panel.rs
index 189ba5ea7a..d83363d6eb 100644
--- a/libs/cua-driver-rs/crates/platform-macos/src/permissions/panel.rs
+++ b/libs/cua-driver-rs/crates/platform-macos/src/permissions/panel.rs
@@ -140,6 +140,57 @@ pub fn show_modal(opts: PanelOpts) -> PanelOutcome {
unsafe { show_modal_unsafe(&opts) }
}
+/// Block the current (main) thread for `seconds` while letting the
+/// AppKit run loop process events.
+///
+/// The terminal-flow gate (`gate::wait_for_grants`) used to use
+/// `std::thread::sleep` between TCC probes. That works on every other
+/// platform but on macOS it starves the AppKit run loop, which is
+/// where `AXIsProcessTrusted()`'s per-process trust cache gets
+/// invalidated when tccd posts notifications about grant changes.
+/// Net effect: a daemon that called `AXIsProcessTrusted()` once at
+/// startup and got `false` would keep getting `false` forever even
+/// after the user granted accessibility in System Settings — the
+/// poll loop never saw the grant flip.
+///
+/// Pumping the run loop here (instead of `nanosleep`) gives AppKit a
+/// chance to handle the TCC change-notification XPC message, which
+/// invalidates the trust cache. The next iteration's
+/// `AXIsProcessTrusted()` call then sees the fresh truth.
+///
+/// Falls back to `thread::sleep` if anything in the AppKit setup
+/// looks off (not main thread, NSRunLoop class unavailable) so this
+/// function is safe to call from any context — it just degrades to
+/// the old behaviour in those cases.
+pub fn pump_run_loop_briefly(seconds: f64) {
+ if MainThreadMarker::new().is_none() {
+ // Not the main thread — pumping someone else's run loop is
+ // wrong. Just sleep.
+ std::thread::sleep(std::time::Duration::from_secs_f64(seconds.max(0.0)));
+ return;
+ }
+ unsafe {
+ let run_loop: *mut AnyObject =
+ msg_send![class!(NSRunLoop), currentRunLoop];
+ if run_loop.is_null() {
+ std::thread::sleep(std::time::Duration::from_secs_f64(seconds.max(0.0)));
+ return;
+ }
+ // `[NSDate dateWithTimeIntervalSinceNow:seconds]` builds the
+ // deadline. `[NSRunLoop runMode:beforeDate:]` blocks up to
+ // that deadline while dispatching pending input sources +
+ // timers — including TCC notification taps.
+ let date: *mut AnyObject =
+ msg_send![class!(NSDate), dateWithTimeIntervalSinceNow: seconds];
+ if date.is_null() {
+ std::thread::sleep(std::time::Duration::from_secs_f64(seconds.max(0.0)));
+ return;
+ }
+ let default_mode = ns_string("NSDefaultRunLoopMode");
+ let _: bool = msg_send![run_loop, runMode: default_mode beforeDate: date];
+ }
+}
+
// ── Implementation ──────────────────────────────────────────────────────
fn env_on(key: &str) -> bool {