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): persist macOS direct capture verification (#2904)

injaneity605ce1aec80e
diff --git a/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx b/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx
index ab967a541f..cb1881b7b6 100644
--- a/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx
+++ b/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx
@@ -163,8 +163,11 @@ import json
with open('/tmp/cua-driver-permissions-live.json') as source:
status = json.load(source)
-assert status['screen_recording_capturable'] is True
-assert status['direct_capture_status'] == 'ready'
+assert status['screen_recording_capturable'] is None
+assert status['direct_capture_status'] == 'not_checked'
+assert status['direct_capture_verification']['source'] == 'permissions_grant'
+assert status['direct_capture_verification']['verified_at'].endswith('Z')
+assert status['direct_capture_verification']['bundle_id'] == 'com.trycua.driver'
PY
/Users/lume/.local/bin/cua-driver call get_accessibility_tree '{}'
/Users/lume/.local/bin/cua-driver call get_desktop_state '{}' \
diff --git a/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx b/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx
index 1871dd7d75..0976606c6f 100644
--- a/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx
+++ b/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx
@@ -225,8 +225,11 @@ Verify the app-owned grants, signature, capture result, and SIP state:
"$DRIVER" permissions grant
"$DRIVER" permissions status --json | jq -e '
- .screen_recording_capturable == true
- and .direct_capture_status == "ready"
+ .screen_recording_capturable == null
+ and .direct_capture_status == "not_checked"
+ and .direct_capture_verification.source == "permissions_grant"
+ and (.direct_capture_verification.verified_at | endswith("Z"))
+ and .direct_capture_verification.bundle_id == "com.trycua.driver"
'
jq -e '
diff --git a/docs/content/docs/reference/cua-driver/macos-permissions.mdx b/docs/content/docs/reference/cua-driver/macos-permissions.mdx
index 62b05410a4..2ab52143da 100644
--- a/docs/content/docs/reference/cua-driver/macos-permissions.mdx
+++ b/docs/content/docs/reference/cua-driver/macos-permissions.mdx
@@ -33,7 +33,17 @@ private-window-picker bypass dialog when ScreenCaptureKit is queried,
`permissions status` never runs that probe: it returns
`screen_recording_capturable: null` and
`direct_capture_status: "not_checked"`. This preserves the command's read-only,
-no-prompt contract.
+no-prompt contract. After `permissions grant` completes a successful live
+probe, status also returns `direct_capture_verification` with the
+`permissions_grant` source, the UTC verification time, and the macOS bundle ID
+whose probe succeeded. ScreenCaptureKit confirms that the explicit probe
+succeeded but does not report whether consent was newly granted or already
+present. The permission service validates the
+stored schema, source, timestamp, and bundle ID, and only loads the record when
+the live status belongs to the driver daemon identity. The CLI only renders the
+complete live and historical observation. Historical evidence does not turn the
+read-only status call into a claim about current
+ScreenCaptureKit readiness.
`permissions grant` never sends a prompt-capable request over the daemon
socket. It launches a short-lived instance of the installed CuaDriver app
@@ -46,6 +56,13 @@ Cua Driver's current ScreenCaptureKit recorder captures screen video only and
does not enable audio capture. The consent is limited to macOS capture; it does
not authorize browser-profile access, browser data, or CDP attachment.
+The LaunchServices-hosted process records successful verification before it
+returns because that process owns the probed macOS identity. Records are stored
+separately for the release and local identities and contain the matching bundle
+ID. A failed explicit probe clears the matching prior record. If the record
+cannot be written, `permissions grant` reports the live success but exits with
+an error instead of claiming that later status calls can corroborate it.
+
If the installed app is not listed under **Screen & System Audio Recording**
after the prompt, click **+**, add `/Applications/CuaDriver.app` (or
`/Applications/CuaDriverLocal.app` for a local build), enable it, and run
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index a59b284d79..638759ee0c 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -736,7 +736,7 @@ Configure only movement physics and visibility timing for a session cursor.
Report TCC permission status for Accessibility and Screen Recording. By default also raises the system permission dialogs for any missing grants — Apple's request APIs are no-ops when the grant is already active, so this is safe to call repeatedly. Pass {"prompt": false} for a purely read-only status check.
-Returns: `accessibility` + `screen_recording` (booleans from the TCC preflight APIs), `screen_recording_capturable` (a live ScreenCaptureKit probe when `prompt` is true; null on read-only calls), `direct_capture_status` (`ready`, `unavailable`, `timed_out`, `probe_failed`, `blocked_by_screen_recording`, or `not_checked`), `direct_capture_error` (a structured timeout/probe failure when applicable), and `source` (which TCC identity the booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). macOS attributes grants to the responsible process, so a standalone call from a terminal reports the terminal's grants, not the driver's. The prompt-capable ScreenCaptureKit probe never runs when `prompt` is false. Pass `probe_direct_capture:false` with `prompt:true` to register/request only the two required TCC grants before separately explaining Tahoe's direct-capture consent.
+Returns: `accessibility` + `screen_recording` (booleans from the TCC preflight APIs), `screen_recording_capturable` (a live ScreenCaptureKit probe when `prompt` is true; null on read-only calls), `direct_capture_status` (`ready`, `unavailable`, `timed_out`, `probe_failed`, `blocked_by_screen_recording`, or `not_checked`), `direct_capture_error` (a structured timeout/probe failure when applicable), `direct_capture_verification` (validated source, UTC time, and bundle identity from an explicit grant probe), and `source` (which TCC identity the booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). macOS attributes grants to the responsible process, so a standalone call from a terminal reports the terminal's grants, not the driver's. The prompt-capable ScreenCaptureKit probe never runs when `prompt` is false. Pass `probe_direct_capture:false` with `prompt:true` to register/request only the two required TCC grants before separately explaining Tahoe's direct-capture consent.
**Arguments:**
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index e7f9e4fd54..dbccdb19a4 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -3283,7 +3283,9 @@ dependencies = [
"security-framework",
"serde",
"serde_json",
+ "tempfile",
"thiserror 1.0.69",
+ "time",
"tiny-skia",
"tokio",
"tokio-tungstenite",
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index f3e021b74e..47eea7d4cb 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -3274,6 +3274,7 @@ fn run_permissions_status(json: bool) {
let cap = structured
.get("screen_recording_capturable")
.and_then(|v| v.as_bool());
+ let direct_capture_verification = structured.get("direct_capture_verification");
let attribution = structured
.get("source")
.and_then(|s| s.get("attribution"))
@@ -3298,9 +3299,27 @@ fn run_permissions_status(json: bool) {
);
}
}
- None => println!(
- "Direct Capture: ❓ not checked (status is read-only; run `{cli_name} permissions grant`)"
- ),
+ None => {
+ if let Some(verification) = direct_capture_verification {
+ let source = verification["source"].as_str().unwrap_or("unknown source");
+ let verified_at = verification["verified_at"]
+ .as_str()
+ .unwrap_or("unknown time");
+ let bundle_id = verification["bundle_id"]
+ .as_str()
+ .unwrap_or("unknown identity");
+ println!(
+ "Direct Capture: ✅ previously verified ({source}, {verified_at}, {bundle_id})"
+ );
+ println!(
+ " ℹ️ historical observation; this read-only status did not run a live probe."
+ );
+ } else {
+ println!(
+ "Direct Capture: ❓ not checked (status is read-only; run `{cli_name} permissions grant`)"
+ );
+ }
+ }
}
println!("Source: {attribution}");
if !(ax && sr) {
@@ -3319,6 +3338,12 @@ fn permission_grant_is_ready(structured: &serde_json::Value) -> bool {
permission_flag(structured, "accessibility")
&& permission_flag(structured, "screen_recording")
&& permission_flag(structured, "screen_recording_capturable")
+ && structured
+ .get("direct_capture_verification_error")
+ .is_none()
+ && structured
+ .get("direct_capture_verification")
+ .is_some_and(serde_json::Value::is_object)
}
fn permission_grant_needs_direct_capture(structured: &serde_json::Value) -> bool {
@@ -3623,6 +3648,25 @@ fn run_permissions_grant() {
println!("Choose Allow to request and verify direct capture now…");
let direct_status = request_permissions_via_launchservices(true).ok();
+ if let Some((status, error)) = direct_status.as_ref().and_then(|status| {
+ status
+ .get("direct_capture_verification_error")
+ .and_then(|error| error.get("message"))
+ .and_then(serde_json::Value::as_str)
+ .map(|error| (status, error))
+ }) {
+ if permission_flag(status, "screen_recording_capturable") {
+ eprintln!(
+ "\n❌ Direct capture worked, but its verification could not be recorded: {error}"
+ );
+ } else {
+ eprintln!(
+ "\n❌ Direct capture failed, and the previous verification could not be cleared: {error}"
+ );
+ }
+ process::exit(1);
+ }
+
if direct_status
.as_ref()
.is_some_and(permission_grant_is_ready)
@@ -3630,6 +3674,9 @@ fn run_permissions_grant() {
println!(
"\n✅ {app_name} has Accessibility, Screen Recording, and direct capture access. You're set."
);
+ println!(
+ "macOS verified the explicit request but does not report whether consent was newly granted or already present."
+ );
return;
}
@@ -4910,13 +4957,30 @@ mod tests {
let ready = serde_json::json!({
"accessibility": true,
"screen_recording": true,
- "screen_recording_capturable": true
+ "screen_recording_capturable": true,
+ "direct_capture_verification": {}
});
assert!(permission_grant_is_ready(&ready));
assert!(!permission_grant_needs_direct_capture(&ready));
}
+ #[test]
+ fn permission_grant_rejects_verification_errors_with_stale_evidence() {
+ let failed = serde_json::json!({
+ "accessibility": true,
+ "screen_recording": true,
+ "screen_recording_capturable": true,
+ "direct_capture_verification": {},
+ "direct_capture_verification_error": {
+ "code": "direct_capture_verification_store_failed",
+ "message": "read-only evidence store"
+ }
+ });
+
+ assert!(!permission_grant_is_ready(&failed));
+ }
+
#[test]
fn permission_grant_missing_live_probe_is_not_ready() {
let incomplete = serde_json::json!({
diff --git a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
index 52aff5d4fe..d53bfe4c7a 100644
--- a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
@@ -14,6 +14,7 @@ base64 = { workspace = true }
image = { workspace = true }
async-trait = "0.1"
uuid = { workspace = true }
+time = { workspace = true }
# Insertion-ordered map for the keyed per-session cursor render collection.
# IndexMap gives deterministic iteration order = stable cursor z-order frame
# to frame (a plain HashMap would flicker overlapping cursors).
@@ -70,3 +71,6 @@ tiny-skia = { version = "0.11", default-features = false, features = ["std"] }
# WebSocket CDP client (used by browser/cdp_client.rs for the page tool)
tokio-tungstenite = { version = "0.24", features = ["native-tls"] }
futures-util = "0.3"
+
+[dev-dependencies]
+tempfile = "3"
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
index c1a426c2a7..f27237357e 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
@@ -27,6 +27,8 @@ pub mod history;
#[cfg(target_os = "macos")]
pub mod input;
#[cfg(target_os = "macos")]
+mod permission_observation;
+#[cfg(target_os = "macos")]
pub mod permissions;
#[cfg(target_os = "macos")]
pub mod pip;
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/permission_observation.rs b/libs/cua-driver/rust/crates/platform-macos/src/permission_observation.rs
new file mode 100644
index 0000000000..eb2856c860
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-macos/src/permission_observation.rs
@@ -0,0 +1,193 @@
+use serde::{Deserialize, Serialize};
+use std::io::Write as _;
+use std::path::{Path, PathBuf};
+
+const SCHEMA_VERSION: u8 = 1;
+const SOURCE: &str = "permissions_grant";
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub(crate) struct DirectCaptureVerification {
+ pub source: String,
+ pub verified_at: String,
+ pub bundle_id: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+struct PersistedVerification {
+ schema_version: u8,
+ source: String,
+ verified_at_unix_seconds: i64,
+ bundle_id: String,
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct DirectCaptureEvidenceStore {
+ path: PathBuf,
+ bundle_id: String,
+}
+
+impl DirectCaptureEvidenceStore {
+ pub(crate) fn new(path: PathBuf, bundle_id: impl Into<String>) -> Self {
+ Self {
+ path,
+ bundle_id: bundle_id.into(),
+ }
+ }
+
+ pub(crate) fn record_now(&self) -> Result<DirectCaptureVerification, String> {
+ self.record_at(time::OffsetDateTime::now_utc().unix_timestamp())?;
+ self.load()
+ .ok_or_else(|| "recorded direct-capture verification did not validate".to_owned())
+ }
+
+ pub(crate) fn load(&self) -> Option<DirectCaptureVerification> {
+ let bytes = std::fs::read(&self.path).ok()?;
+ let record: PersistedVerification = serde_json::from_slice(&bytes).ok()?;
+ if record.schema_version != SCHEMA_VERSION
+ || record.source != SOURCE
+ || record.verified_at_unix_seconds <= 0
+ || record.bundle_id != self.bundle_id
+ {
+ return None;
+ }
+ let verified_at =
+ time::OffsetDateTime::from_unix_timestamp(record.verified_at_unix_seconds)
+ .ok()?
+ .format(&time::format_description::well_known::Rfc3339)
+ .ok()?;
+ Some(DirectCaptureVerification {
+ source: record.source,
+ verified_at,
+ bundle_id: record.bundle_id,
+ })
+ }
+
+ pub(crate) fn clear(&self) -> Result<(), String> {
+ match std::fs::remove_file(&self.path) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(format!("remove {}: {error}", self.path.display())),
+ }
+ }
+
+ fn record_at(&self, verified_at_unix_seconds: i64) -> Result<(), String> {
+ if verified_at_unix_seconds <= 0 {
+ return Err("verification timestamp is unavailable".to_owned());
+ }
+ let parent = self
+ .path
+ .parent()
+ .ok_or_else(|| "direct-capture verification path has no parent".to_owned())?;
+ std::fs::create_dir_all(parent)
+ .map_err(|error| format!("create {}: {error}", parent.display()))?;
+ let record = PersistedVerification {
+ schema_version: SCHEMA_VERSION,
+ source: SOURCE.to_owned(),
+ verified_at_unix_seconds,
+ bundle_id: self.bundle_id.clone(),
+ };
+ write_json_atomic(&self.path, &record)
+ }
+}
+
+fn write_json_atomic(path: &Path, value: &PersistedVerification) -> Result<(), String> {
+ let temporary = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4()));
+ let result = (|| {
+ let mut file = std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&temporary)
+ .map_err(|error| format!("create {}: {error}", temporary.display()))?;
+ let mut bytes = serde_json::to_vec_pretty(value)
+ .map_err(|error| format!("serialize direct-capture verification: {error}"))?;
+ bytes.push(b'\n');
+ file.write_all(&bytes)
+ .and_then(|_| file.sync_all())
+ .map_err(|error| format!("write {}: {error}", temporary.display()))?;
+ std::fs::rename(&temporary, path)
+ .map_err(|error| format!("replace {}: {error}", path.display()))
+ })();
+ if result.is_err() {
+ let _ = std::fs::remove_file(&temporary);
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const RELEASE_BUNDLE_ID: &str = "com.trycua.driver";
+ const VERIFIED_AT: i64 = 1_754_352_000;
+
+ fn store(path: PathBuf) -> DirectCaptureEvidenceStore {
+ DirectCaptureEvidenceStore::new(path, RELEASE_BUNDLE_ID)
+ }
+
+ #[test]
+ fn verification_round_trips_with_honest_consent_provenance() {
+ let temp = tempfile::tempdir().expect("tempdir");
+ let store = store(temp.path().join("verification.json"));
+ store.record_at(VERIFIED_AT).expect("record verification");
+
+ assert_eq!(
+ store.load(),
+ Some(DirectCaptureVerification {
+ source: SOURCE.to_owned(),
+ verified_at: "2025-08-05T00:00:00Z".to_owned(),
+ bundle_id: RELEASE_BUNDLE_ID.to_owned(),
+ })
+ );
+ }
+
+ #[test]
+ fn verification_rejects_wrong_identity_schema_source_and_timestamp() {
+ let temp = tempfile::tempdir().expect("tempdir");
+ let path = temp.path().join("verification.json");
+ let store = store(path.clone());
+ let valid = PersistedVerification {
+ schema_version: SCHEMA_VERSION,
+ source: SOURCE.to_owned(),
+ verified_at_unix_seconds: VERIFIED_AT,
+ bundle_id: RELEASE_BUNDLE_ID.to_owned(),
+ };
+ let invalid_records = [
+ PersistedVerification {
+ schema_version: SCHEMA_VERSION + 1,
+ ..valid.clone()
+ },
+ PersistedVerification {
+ source: "unknown".to_owned(),
+ ..valid.clone()
+ },
+ PersistedVerification {
+ verified_at_unix_seconds: 0,
+ ..valid.clone()
+ },
+ PersistedVerification {
+ bundle_id: "com.trycua.driver.local".to_owned(),
+ ..valid
+ },
+ ];
+
+ for record in invalid_records {
+ std::fs::write(
+ &path,
+ serde_json::to_vec(&record).expect("serialize record"),
+ )
+ .expect("write invalid record");
+ assert_eq!(store.load(), None);
+ }
+ }
+
+ #[test]
+ fn clear_removes_existing_evidence_and_tolerates_absence() {
+ let temp = tempfile::tempdir().expect("tempdir");
+ let store = store(temp.path().join("verification.json"));
+ store.record_at(VERIFIED_AT).expect("record verification");
+
+ store.clear().expect("clear verification");
+ store.clear().expect("clear absent verification");
+ assert_eq!(store.load(), None);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rs
index b9da038baa..280f81c164 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rs
@@ -4,9 +4,10 @@ use cua_driver_core::{
tool::{ProtectedResourceOwnership, Tool, ToolDef},
};
use serde_json::Value;
-use std::{future::Future, sync::Arc, time::Duration};
+use std::{future::Future, path::Path, sync::Arc, time::Duration};
use super::ToolState;
+use crate::permission_observation::{DirectCaptureEvidenceStore, DirectCaptureVerification};
use crate::permissions::status::{
accessibility_granted, request_accessibility, request_screen_recording,
screen_recording_granted,
@@ -49,6 +50,41 @@ fn driver_bundle_id_for_executable(executable: &str) -> Option<&'static str> {
}
}
+fn current_executable() -> String {
+ std::env::current_exe()
+ .ok()
+ .and_then(|path| std::fs::canonicalize(path).ok())
+ .and_then(|path| path.to_str().map(str::to_owned))
+ .unwrap_or_default()
+}
+
+fn direct_capture_evidence_store_for_identity(
+ executable: &str,
+ home: &Path,
+ attribution: Option<&str>,
+) -> Option<DirectCaptureEvidenceStore> {
+ if attribution != Some("driver-daemon") {
+ return None;
+ }
+ let bundle_id = driver_bundle_id_for_executable(executable)?;
+ let state_directory = match bundle_id {
+ "com.trycua.driver.local" => ".cua-driver-local",
+ "com.trycua.driver" => ".cua-driver",
+ _ => return None,
+ };
+ Some(DirectCaptureEvidenceStore::new(
+ home.join(state_directory)
+ .join("direct-capture-verification.json"),
+ bundle_id,
+ ))
+}
+
+fn current_direct_capture_evidence_store(source: &Value) -> Option<DirectCaptureEvidenceStore> {
+ let home = std::env::var_os("HOME")?;
+ let attribution = source.get("attribution").and_then(Value::as_str);
+ direct_capture_evidence_store_for_identity(&current_executable(), Path::new(&home), attribution)
+}
+
/// (A) Real ScreenCaptureKit capability probe — what THIS process can
/// actually capture right now, independent of the CGPreflight cache.
///
@@ -135,6 +171,46 @@ fn should_prompt_permissions(requested: bool, host_owns_permission_ux: bool) ->
requested && !cua_driver_core::embedded_mode() && !host_owns_permission_ux
}
+fn resolve_direct_capture_verification(
+ store: Option<&DirectCaptureEvidenceStore>,
+ probe: Option<DirectCaptureProbeResult>,
+) -> Result<Option<DirectCaptureVerification>, Value> {
+ match probe {
+ None => Ok(store.and_then(DirectCaptureEvidenceStore::load)),
+ Some(DirectCaptureProbeResult::Ready) => {
+ let Some(store) = store else {
+ return Err(serde_json::json!({
+ "code": "direct_capture_verification_store_unavailable",
+ "message": "the installed product identity or user home directory is unavailable",
+ }));
+ };
+ store.record_now().map(Some).map_err(|error| {
+ let message = match store.clear() {
+ Ok(()) => error,
+ Err(clear_error) => {
+ format!("{error}; clear prior direct-capture verification: {clear_error}")
+ }
+ };
+ serde_json::json!({
+ "code": "direct_capture_verification_store_failed",
+ "message": message,
+ })
+ })
+ }
+ Some(_) => {
+ let Some(store) = store else {
+ return Ok(None);
+ };
+ store.clear().map(|()| None).map_err(|error| {
+ serde_json::json!({
+ "code": "direct_capture_verification_store_failed",
+ "message": error,
+ })
+ })
+ }
+ }
+}
+
/// (B) Which TCC identity the booleans in this response reflect.
///
/// macOS attributes Accessibility / Screen-Recording to the *responsible
@@ -150,11 +226,7 @@ fn permission_source(
) -> serde_json::Value {
let pid = unsafe { libc::getpid() };
let ppid = unsafe { libc::getppid() };
- let exe = std::env::current_exe()
- .ok()
- .and_then(|p| std::fs::canonicalize(p).ok())
- .and_then(|p| p.to_str().map(str::to_owned))
- .unwrap_or_default();
+ let exe = current_executable();
let disclaimed = std::env::var_os(cua_driver_core::RESPONSIBILITY_DISCLAIMED_ENV).is_some();
// Embedded mode: the driver is a child in a host app's responsibility
// chain, so the probes already answer for the host's TCC identity.
@@ -242,7 +314,9 @@ fn def() -> &'static ToolDef {
probe when `prompt` is true; null on read-only calls), \
`direct_capture_status` (`ready`, `unavailable`, `timed_out`, `probe_failed`, \
`blocked_by_screen_recording`, or `not_checked`), `direct_capture_error` (a structured \
- timeout/probe failure when applicable), and `source` (which TCC identity the \
+ timeout/probe failure when applicable), `direct_capture_verification` (validated \
+ source, UTC time, and bundle identity from an explicit grant probe), and `source` \
+ (which TCC identity the \
booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). \
macOS attributes grants to the responsible process, so a standalone call \
from a terminal reports the terminal's grants, not the driver's. The \
@@ -319,27 +393,34 @@ impl Tool for CheckPermissionsTool {
// private-window-picker bypass consent. A status/read-only call must
// therefore never execute it. The explicit grant path opts in with
// `prompt:true`, explains the dialog first, and verifies the result.
+ let direct_capture_probe =
+ if should_probe_direct_capture(should_prompt, screen_recording, probe_direct_capture) {
+ Some(bounded_screen_recording_capturable().await)
+ } else {
+ None
+ };
let (screen_recording_capturable, direct_capture_status, direct_capture_error) =
- if !should_prompt {
+ if !should_prompt || (screen_recording && !probe_direct_capture) {
(None, "not_checked", None)
} else if !screen_recording {
(None, "blocked_by_screen_recording", None)
- } else if should_probe_direct_capture(
- should_prompt,
- screen_recording,
- probe_direct_capture,
- ) {
- bounded_screen_recording_capturable()
- .await
- .response_fields()
} else {
- (None, "not_checked", None)
+ direct_capture_probe
+ .expect("eligible direct-capture probe must run")
+ .response_fields()
};
// (B) Which identity the booleans above belong to.
let source = permission_source(
self.state.host_owns_permission_ux,
self.state.host_bundle_id.as_deref(),
);
+ let evidence_store = current_direct_capture_evidence_store(&source);
+ let (direct_capture_verification, direct_capture_verification_error) =
+ match resolve_direct_capture_verification(evidence_store.as_ref(), direct_capture_probe)
+ {
+ Ok(verification) => (verification, None),
+ Err(error) => (None, Some(error)),
+ };
let is_caller = source.get("attribution").and_then(|v| v.as_str()) == Some("caller");
// Text format mirrors Swift 1:1:
@@ -360,7 +441,9 @@ impl Tool for CheckPermissionsTool {
"{ax_prefix} Accessibility: {ax_state}.\n{sr_prefix} Screen Recording: {sr_state}."
);
// Flag a preflight/probe disagreement (the false-positive tell).
- if screen_recording_capturable == Some(false) {
+ if direct_capture_verification_error.is_some() {
+ summary.push_str("\n⚠️ Direct-capture verification evidence could not be updated.");
+ } else if screen_recording_capturable == Some(false) {
summary.push_str(
"\n⚠️ Screen Recording reads granted but a live capture probe failed — \
the grant likely belongs to a different process, not this one.",
@@ -399,14 +482,21 @@ impl Tool for CheckPermissionsTool {
);
}
- ToolResult::text(summary).with_structured(serde_json::json!({
+ let mut structured = serde_json::json!({
"accessibility": accessibility,
"screen_recording": screen_recording,
"screen_recording_capturable": screen_recording_capturable,
"direct_capture_status": direct_capture_status,
"direct_capture_error": direct_capture_error,
"source": source,
- }))
+ });
+ if let Some(verification) = direct_capture_verification {
+ structured["direct_capture_verification"] = serde_json::json!(verification);
+ }
+ if let Some(error) = direct_capture_verification_error {
+ structured["direct_capture_verification_error"] = error;
+ }
+ ToolResult::text(summary).with_structured(structured)
}
}
@@ -436,6 +526,15 @@ mod tests {
}
}
+ fn release_evidence_store(home: &Path) -> DirectCaptureEvidenceStore {
+ direct_capture_evidence_store_for_identity(
+ "/Applications/CuaDriver.app/Contents/MacOS/cua-driver",
+ home,
+ Some("driver-daemon"),
+ )
+ .expect("release store")
+ }
+
#[test]
fn recognizes_release_and_local_driver_bundles() {
assert_eq!(
@@ -456,6 +555,97 @@ mod tests {
);
}
+ #[test]
+ fn evidence_store_is_scoped_to_the_current_driver_identity() {
+ let home =
+ std::env::temp_dir().join(format!("cua-direct-capture-test-{}", uuid::Uuid::new_v4()));
+ let release = release_evidence_store(&home);
+ let local = direct_capture_evidence_store_for_identity(
+ "/Applications/CuaDriverLocal.app/Contents/MacOS/cua-driver-local",
+ &home,
+ Some("driver-daemon"),
+ )
+ .expect("local store");
+
+ release.record_now().expect("record release verification");
+ assert!(release.load().is_some());
+ assert!(local.load().is_none());
+ assert!(direct_capture_evidence_store_for_identity(
+ "/usr/local/bin/cua-driver",
+ &home,
+ Some("driver-daemon"),
+ )
+ .is_none());
+ for attribution in [Some("caller"), Some("host"), None] {
+ assert!(direct_capture_evidence_store_for_identity(
+ "/Applications/CuaDriver.app/Contents/MacOS/cua-driver",
+ &home,
+ attribution,
+ )
+ .is_none());
+ }
+ std::fs::remove_dir_all(home).expect("remove test home");
+ }
+
+ #[test]
+ fn explicit_probe_resolves_one_evidence_transition() {
+ let home =
+ std::env::temp_dir().join(format!("cua-direct-capture-test-{}", uuid::Uuid::new_v4()));
+ let store = release_evidence_store(&home);
+
+ assert!(resolve_direct_capture_verification(
+ Some(&store),
+ Some(DirectCaptureProbeResult::Ready)
+ )
+ .expect("record evidence")
+ .is_some());
+ assert!(resolve_direct_capture_verification(Some(&store), None)
+ .expect("load evidence")
+ .is_some());
+ assert_eq!(
+ resolve_direct_capture_verification(
+ Some(&store),
+ Some(DirectCaptureProbeResult::Unavailable)
+ )
+ .expect("clear evidence"),
+ None
+ );
+ assert!(store.load().is_none());
+ assert_eq!(
+ resolve_direct_capture_verification(None, Some(DirectCaptureProbeResult::Ready))
+ .expect_err("missing-store error")["code"],
+ "direct_capture_verification_store_unavailable"
+ );
+ std::fs::remove_dir_all(home).expect("remove test home");
+ }
+
+ #[test]
+ fn failed_record_and_clear_returns_only_error() {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ let home =
+ std::env::temp_dir().join(format!("cua-direct-capture-test-{}", uuid::Uuid::new_v4()));
+ let store = release_evidence_store(&home);
+ store.record_now().expect("record prior evidence");
+ let state_directory = home.join(".cua-driver");
+ std::fs::set_permissions(&state_directory, std::fs::Permissions::from_mode(0o500))
+ .expect("make evidence directory read-only");
+
+ let result = resolve_direct_capture_verification(
+ Some(&store),
+ Some(DirectCaptureProbeResult::Ready),
+ );
+
+ std::fs::set_permissions(&state_directory, std::fs::Permissions::from_mode(0o700))
+ .expect("restore evidence directory permissions");
+ assert_eq!(
+ result.expect_err("record and clear must fail")["code"],
+ "direct_capture_verification_store_failed"
+ );
+ assert!(store.load().is_some());
+ std::fs::remove_dir_all(home).expect("remove test home");
+ }
+
#[test]
fn read_only_checks_never_run_the_prompt_capable_direct_capture_probe() {
assert!(!should_probe_direct_capture(false, false, true));
diff --git a/libs/cua-driver/tests/runners/macos-lume/README.md b/libs/cua-driver/tests/runners/macos-lume/README.md
index d35d13d9c1..7585e94e99 100644
--- a/libs/cua-driver/tests/runners/macos-lume/README.md
+++ b/libs/cua-driver/tests/runners/macos-lume/README.md
@@ -261,6 +261,11 @@ the second is intentionally prompt-capable and must be run by the human:
~/.local/bin/cua-driver-local permissions status --json | jq -e '
.accessibility == true
and .screen_recording == true
+ and .screen_recording_capturable == null
+ and .direct_capture_status == "not_checked"
+ and .direct_capture_verification.source == "permissions_grant"
+ and (.direct_capture_verification.verified_at | endswith("Z"))
+ and .direct_capture_verification.bundle_id == "com.trycua.driver.local"
'
codesign -d -r- /Applications/CuaDriverLocal.app 2>&1 | grep 'certificate leaf'
csrutil status