Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): refuse disabled macOS controls on every token writer (#6503)
injaneity6c78994788f4
diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rsindex 684c391666..ad0ee9d0d3 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/harness_appkit_test.rs@@ -1934,12 +1934,39 @@ fn harness_appkit_disabled_control_is_published_and_its_press_refused() {"{}",refused.raw);+ assert_eq!(+ refused.structured()["code"],+ "element_disabled",+ "{}",+ refused.raw+ );++ // Every other token writer refuses the same control the same way.+ let token = &element["element_token"];+ let writers = [+ ("set_value", serde_json::json!({ "value": "1" })),+ ("right_click", serde_json::json!({})),+ ("double_click", serde_json::json!({})),+ ("click", serde_json::json!({ "button": "middle" })),+ ("type_text", serde_json::json!({ "text": "x" })),+ ];+ for (tool, mut args) in writers {+ args["pid"] = serde_json::json!(pid as i64);+ args["window_id"] = serde_json::json!(wid);+ args["element_token"] = token.clone();+ let refused = driver.call(tool, args);+ assert!(+ refused.is_error() && refused.structured()["code"] == "element_disabled",+ "{tool} on a disabled control was not refused as element_disabled: {}",+ refused.raw+ );+ }std::thread::sleep(Duration::from_millis(200));let after = snapshot_elements(driver, pid, wid);assert!(after.tree_text().contains("disabled_checked=false"),- "the refused press changed the disabled checkbox:\n{}",+ "a refused action changed the disabled checkbox:\n{}",after.tree_text());},diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rsindex 88dbbde273..bcc2772722 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs@@ -536,9 +536,9 @@ unsafe fn walk_element(// A disabled control is still indexed and published with `enabled: false`:// enablement is state the caller needs to read (a form's Save button, a// toolbar item in a window that is not key), not a reason to hide the row.- // `click` re-reads AXEnabled and refuses a disabled target- // (`input::ax_actions::ensure_ax_action_enabled`). Other token writers- // (set_value, right_click, double_click, type_text) do not check it.+ // click, right_click, double_click, set_value and type_text re-read+ // AXEnabled before dispatch and refuse a disabled token target with+ // `element_disabled` (`tools::refuse_if_disabled`).let enabled = if !actions.is_empty() || value_settable {copy_bool_attr(element, "AXEnabled")} else {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/ax_actions.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/ax_actions.rsindex 097871afa6..253725bfbe 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/ax_actions.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/ax_actions.rs@@ -191,12 +191,27 @@ pub fn capture_nearest_container_selection(element_ptr: usize) -> Option<SelectiNone}+/// The live `AXEnabled` read said the target is disabled, so nothing was sent.+/// Tools turn this into a structured `element_disabled` refusal.+#[derive(Debug, thiserror::Error)]+#[error(+ "refusing {action}: the target reports AXEnabled=false, so the app would ignore it. \+ Nothing was sent. Snapshot again and act once the element reports enabled"+)]+pub struct ElementDisabled {+ pub action: String,+}++impl ElementDisabled {+ pub const CODE: &'static str = "element_disabled";+}+fn ensure_ax_enabled(enabled: Option<bool>, action: &str) -> anyhow::Result<()> {if enabled == Some(false) {- anyhow::bail!(- "refusing {action}: the target reports AXEnabled=false. \- Retry this action with delivery_mode:\"foreground\" or call bring_to_front first"- );+ return Err(ElementDisabled {+ action: action.to_owned(),+ }+ .into());}Ok(())}@@ -321,10 +336,15 @@ mod tests {#[test]fn disabled_elements_are_refused_before_dispatch() {let error = ensure_ax_enabled(Some(false), "AXPick").unwrap_err();+ let disabled = error+ .downcast_ref::<ElementDisabled>()+ .expect("a disabled target is a typed refusal");+ assert_eq!(disabled.action, "AXPick");let message = error.to_string();assert!(message.contains("AXEnabled=false"));- assert!(message.contains("delivery_mode:\"foreground\""));- assert!(message.contains("bring_to_front"));+ // A foreground retry does not enable a disabled control.+ assert!(!message.contains("foreground"));+ assert!(!message.contains("bring_to_front"));}#[test]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rsindex 6be1c987b8..b20d4419eb 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs@@ -694,6 +694,17 @@ impl ClickTool {// close, autoscroll, etc.). If we can't resolve a center, error rather// than silently degrade to AXPress.if button_str == "middle" {+ if let Some(refusal) = super::refuse_if_disabled(+ pid,+ wid,+ &element_guard,+ "middle_click",+ delivery_mode.is_foreground(),+ )+ .await+ {+ return refusal;+ }let (cx, cy) = match center {Some(c) => c,None => {@@ -968,7 +979,12 @@ impl ClickTool {}ToolResult::text(msg).with_structured(structured)}- Ok(Err(e)) => ToolResult::error(format!("AX action failed: {e}")),+ Ok(Err(e)) => match e.downcast_ref::<crate::input::ax_actions::ElementDisabled>() {+ Some(disabled) => {+ super::element_disabled_result(pid, wid, disabled, foreground)+ }+ None => ToolResult::error(format!("AX action failed: {e}")),+ },Err(e) => ToolResult::error(format!("Task error: {e}")),}} else if let (Some(mut cx), Some(mut cy)) = (x, y) {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rsindex 715434e485..2e079ab6f8 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs@@ -125,6 +125,17 @@ impl Tool for DoubleClickTool {} else {None};+ if let Some(refusal) = super::refuse_if_disabled(+ pid,+ wid,+ &element_guard,+ "double_click",+ delivery_mode.is_foreground(),+ )+ .await+ {+ return refusal;+ }// Thread the resolved session cursor key into the blocking AX path// so its ClickPulse lands on THIS session's cursor, not "default".diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rsindex 9bc79d38c9..c1223871cd 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs@@ -307,6 +307,74 @@ pub(crate) fn background_refusal_result(.with_structured(structured)}+/// Structured `element_disabled` refusal: the control reported+/// `AXEnabled=false` immediately before dispatch and nothing was sent.+///+/// Some controls (menu and toolbar items) are disabled only while their app is+/// in the background, so a background call into an app that is not frontmost+/// gets a foreground escalation. Otherwise fronting cannot help.+pub(crate) fn element_disabled_result(+ pid: i32,+ window_id: u32,+ disabled: &crate::input::ax_actions::ElementDisabled,+ foreground: bool,+) -> cua_driver_core::protocol::ToolResult {+ let suggest_foreground = !foreground && crate::apps::frontmost_pid() != Some(pid);+ disabled_refusal(pid, window_id, disabled, suggest_foreground)+}++fn disabled_refusal(+ pid: i32,+ window_id: u32,+ disabled: &crate::input::ax_actions::ElementDisabled,+ suggest_foreground: bool,+) -> cua_driver_core::protocol::ToolResult {+ let mut text = disabled.to_string();+ let mut structured = serde_json::json!({+ "code": crate::input::ax_actions::ElementDisabled::CODE,+ "effect": "refused",+ "pid": pid,+ "window_id": window_id,+ "action": disabled.action,+ });+ if suggest_foreground {+ let reason = "the app is in the background, which disables some controls";+ text.push_str(&format!(+ ". If {reason}, retry with delivery_mode:\"foreground\""+ ));+ structured["escalation"] =+ serde_json::json!({ "recommended": "foreground", "reason": reason });+ }+ cua_driver_core::protocol::ToolResult::error(text).with_structured(structured)+}++/// Re-read `AXEnabled` on a token target and refuse a disabled one before any+/// cursor or input work. The snapshot's `enabled` can be stale. A foreground+/// call into an app that is not frontmost skips the read: activation can+/// enable the control, so a read before activation would refuse a live target.+pub(crate) async fn refuse_if_disabled(+ pid: i32,+ window_id: u32,+ element: &crate::ax::snapshot::RetainedElement,+ action: &'static str,+ foreground: bool,+) -> Option<cua_driver_core::protocol::ToolResult> {+ if foreground && crate::apps::frontmost_pid() != Some(pid) {+ return None;+ }+ let element = element.clone();+ let checked = tokio::task::spawn_blocking(move || {+ crate::input::ax_actions::ensure_ax_action_enabled(element.as_ptr(), action)+ })+ .await+ .ok()?;+ let error = checked.err()?;+ let disabled = error.downcast_ref::<crate::input::ax_actions::ElementDisabled>()?;+ Some(element_disabled_result(+ pid, window_id, disabled, foreground,+ ))+}+/// Hint shown with every `windowserver_connection_invalid` refusal.pub(crate) const WINDOWSERVER_INVALID_HINT: &str = "This daemon runs without its own app-bundle identity (a bare `cua-driver serve`), so macOS gives it no valid WindowServer connection and every no-raise focus step fails. Run the app-bundle daemon: `cua-driver permissions grant`.";@@ -1435,3 +1503,36 @@ mod windowserver_refusal_tests {.contains("cua-driver permissions grant"));}}++#[cfg(test)]+mod element_disabled_tests {+ use super::*;+ use crate::input::ax_actions::ElementDisabled;++ fn disabled() -> ElementDisabled {+ ElementDisabled {+ action: "set_value".into(),+ }+ }++ #[test]+ fn background_app_refusal_is_coded_and_escalates_to_foreground() {+ let result = disabled_refusal(42, 7, &disabled(), true);+ assert_eq!(result.is_error, Some(true));+ let structured = result.structured_content.expect("structured");+ assert_eq!(structured["code"], "element_disabled");+ assert_eq!(structured["effect"], "refused");+ assert_eq!(structured["action"], "set_value");+ assert_eq!(structured["window_id"], 7);+ // run_steps' foreground_fallback keys off this field.+ assert_eq!(structured["escalation"]["recommended"], "foreground");+ }++ #[test]+ fn frontmost_app_refusal_does_not_suggest_fronting() {+ let result = disabled_refusal(42, 7, &disabled(), false);+ let structured = result.structured_content.expect("structured");+ assert_eq!(structured["code"], "element_disabled");+ assert!(structured.get("escalation").is_none(), "{structured}");+ }+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rsindex 5cccbf7cb1..9831763ffa 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs@@ -141,6 +141,11 @@ impl Tool for RightClickTool {Ok(lease) => lease,Err(refusal_result) => return refusal_result,};+ if let Some(refusal) =+ super::refuse_if_disabled(pid, wid, &element_guard, "AXShowMenu", false).await+ {+ return refusal;+ }// The context menu steals key focus from the user's app when the// target is in the background; the guard hands it back.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rsindex 337a440be8..36cdae90d9 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs@@ -129,6 +129,11 @@ impl Tool for SetValueTool {Ok(lease) => lease,Err(refusal_result) => return refusal_result,};+ if let Some(refusal) =+ super::refuse_if_disabled(pid, window_id, &element_guard, "set_value", false).await+ {+ return refusal;+ }// A file's name as Finder lists it takes an AXValue write and reads it// back, but the file is never renamed. Refuse before anything moves.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rsindex 9035b98b38..402032b4e8 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs@@ -231,6 +231,19 @@ impl Tool for TypeTextTool {}_ => (None, BackgroundKeyboardPolicy::Allowed),};+ if let (Some((element, _)), Some(wid)) = (element_guard.as_ref(), window_id) {+ if let Some(refusal) = super::refuse_if_disabled(+ pid,+ wid,+ element,+ "type_text",+ delivery_mode.is_foreground(),+ )+ .await+ {+ return refusal;+ }+ }// ── px form: focus by pixel-click, then type into the focused element ──// Pass x,y (no element_token) for an *element px action*: pixel-click the