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): set_value selects options of native and Chromium popups (#4740)
Francesco Bonacci848116252c5f
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/click.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/click.mdxindex 0936c963d6..182f2eb406 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools/click.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools/click.mdx@@ -26,7 +26,7 @@ Click a target pid. Prefer `element_token` (from get_window_state): it identifie- element_token: AX action path. Tokens are scoped to (pid, window_id) and stale once the window is snapshotted again.- x, y: window-local pixels of the get_window_state screenshot, sent as CGEvent mouse events. Needs a visible window. `modifier` takes cmd/shift/option/ctrl.-`button` defaults to left; on the AX path "right" maps to AXShowMenu and "middle" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call.+`button` defaults to left; on the AX path "right" maps to AXShowMenu and "middle" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call. Pressing a popup button opens its menu and leaves it open (holding key focus) until dismissed; to choose an option use `set_value`.**macOS parameters**diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/values-and-clipboard.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/values-and-clipboard.mdxindex 84e942e4e1..17718dcede 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools/values-and-clipboard.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools/values-and-clipboard.mdx@@ -27,7 +27,7 @@ Effect: destructive, idempotent. Platforms: macOS, Linux, Windows.<Tabs items={['macOS', 'Linux', 'Windows']} groupId="platform" persist><Tab value="macOS">-Set an element's value by `element_token`. A popup button / select dropdown: presses the child option whose title or value matches `value` (case-insensitive) without opening the menu or stealing focus. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).+Set an element's value by `element_token`. A popup button / select dropdown: selects the menu item whose title or value matches `value` (case-insensitive). Safari `<select>` is set through the DOM; AppKit and Chromium popups list items only while open, so the menu is opened, the item pressed and the menu closed again (the front window loses key focus for ~0.4 s). An unknown value lists the options. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).A Finder file name (list row or Get Info `Name` field, not being edited) is refused with `file_name_needs_rename`; the refusal names the keyboard route. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.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 28696c3ae0..bb1ed790c6 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@@ -230,7 +230,7 @@ fn def() -> &'static ToolDef {- element_token: AX action path. Tokens are scoped to (pid, window_id) and stale once the window is snapshotted again.\n\- x, y: window-local pixels of the get_window_state screenshot, sent as CGEvent mouse events. Needs a visible window. `modifier` takes cmd/shift/option/ctrl.\n\\n\- `button` defaults to left; on the AX path \"right\" maps to AXShowMenu and \"middle\" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call.".into(),+ `button` defaults to left; on the AX path \"right\" maps to AXShowMenu and \"middle\" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call. Pressing a popup button opens its menu and leaves it open (holding key focus) until dismissed; to choose an option use `set_value`.".into(),input_schema: serde_json::json!({"type": "object",// `pid` is conditionally required — needed for window/element clicksdiff --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 ac0a6d969f..58a8423456 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@@ -2,11 +2,12 @@//!//! Two modes, determined by the element's AXRole://!-//! * **AXPopUpButton**: Find the child option whose AXTitle or AXValue matches-//! `value` (case-insensitive) and AXPress it directly. The native macOS popup-//! menu is never opened, so focus is never stolen. Falls back to Safari-//! `osascript do JavaScript` for WebKit `<select>` elements that expose no AX-//! children when the popup is closed.+//! * **AXPopUpButton**: Find the option (a child, or an `AXMenuItem` under the+//! popup's `AXMenu`) whose AXTitle or AXValue matches `value`+//! (case-insensitive) and AXPress it. AppKit and Chromium popups publish+//! their items only while the menu is open, so the menu is opened for the+//! selection and closed again. Safari `<select>` elements are set through+//! `osascript do JavaScript` instead.//!//! * **Everything else**: Write `AXValue` directly (sliders, steppers, native//! text fields that expose a settable AXValue).@@ -45,7 +46,7 @@ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();fn def() -> &'static ToolDef {DEF.get_or_init(|| ToolDef {name: "set_value".into(),- description: "Set an element's value by `element_token`. A popup button / select dropdown: presses the child option whose title or value matches `value` (case-insensitive) without opening the menu or stealing focus. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).\n\+ description: "Set an element's value by `element_token`. A popup button / select dropdown: selects the menu item whose title or value matches `value` (case-insensitive). Safari `<select>` is set through the DOM; AppKit and Chromium popups list items only while open, so the menu is opened, the item pressed and the menu closed again (the front window loses key focus for ~0.4 s). An unknown value lists the options. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).\n\\n\A Finder file name (list row or Get Info `Name` field, not being edited) is refused with `file_name_needs_rename`; the refusal names the keyboard route. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.".into(),input_schema: serde_json::json!({@@ -538,6 +539,133 @@ fn step_to_value(element: AXUIElementRef, target: f64) -> bool {// ── AXPopUpButton path ───────────────────────────────────────────────────────+/// How long to wait for a popup's menu to publish its items after AXPress.+const POPUP_OPEN_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(2500);+/// Consecutive unchanged polls that mean the menu has finished filling in.+const POPUP_STABLE_POLLS: u32 = 3;+/// How long a dismissed menu may take to close before Escape is sent.+const POPUP_CLOSE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(300);+const POPUP_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50);+/// AX messaging timeout while opening the menu. The target app enters its+/// menu-tracking loop inside the AXPress, so the call would otherwise block+/// for the full default timeout (~1.5 s) with the menu already open.+const POPUP_PRESS_TIMEOUT_SECONDS: f32 = 0.5;++/// One selectable entry of a popup: the retained AX element plus the title+/// and value it reports.+struct PopupOption {+ element: AXUIElementRef,+ title: String,+ value: String,+}++/// Release every retained option.+fn release_options(options: &[PopupOption]) {+ for option in options {+ unsafe { CFRelease(option.element as _) };+ }+}++/// The popup's options as AX exposes them: its direct children, or, when a+/// child is an `AXMenu` (AppKit `NSPopUpButton`, Chromium `<select>`), that+/// menu's `AXMenuItem` children. Menus without items yield nothing, so an+/// unopened popup reads as empty instead of as one untitled option.+fn popup_options(popup: AXUIElementRef) -> Vec<PopupOption> {+ let mut options = Vec::new();+ for child in unsafe { copy_children(popup) } {+ let role = unsafe { copy_string_attr(child, "AXRole") }.unwrap_or_default();+ if role == "AXMenu" {+ for item in unsafe { copy_children(child) } {+ options.push(describe_option(item));+ }+ unsafe { CFRelease(child as _) };+ } else {+ options.push(describe_option(child));+ }+ }+ options.retain(|option| !(option.title.is_empty() && option.value.is_empty()));+ options+}++fn describe_option(element: AXUIElementRef) -> PopupOption {+ PopupOption {+ element,+ title: unsafe { copy_string_attr(element, "AXTitle") }.unwrap_or_default(),+ value: unsafe { copy_string_attr(element, "AXValue") }.unwrap_or_default(),+ }+}++/// Index of the option whose title or value equals `value`, ignoring case and+/// surrounding whitespace.+fn matching_option(options: &[(String, String)], value: &str) -> Option<usize> {+ let wanted = value.trim().to_lowercase();+ options.iter().position(|(title, option_value)| {+ title.trim().to_lowercase() == wanted || option_value.trim().to_lowercase() == wanted+ })+}++fn option_pairs(options: &[PopupOption]) -> Vec<(String, String)> {+ options+ .iter()+ .map(|option| (option.title.clone(), option.value.clone()))+ .collect()+}++fn describe_available(options: &[PopupOption]) -> String {+ options+ .iter()+ .map(|option| {+ let label = if option.title.is_empty() {+ &option.value+ } else {+ &option.title+ };+ format!("\"{label}\"")+ })+ .collect::<Vec<_>>()+ .join(", ")+}++/// Whether the popup's menu is open right now: an `AXMenu` child that already+/// lists items. A closed AppKit popup has an empty `AXMenu` (or none), and a+/// closed Chromium popup lists only its selected item directly.+fn popup_menu_is_open(popup: AXUIElementRef) -> bool {+ let mut open = false;+ for child in unsafe { copy_children(popup) } {+ if unsafe { copy_string_attr(child, "AXRole") }.as_deref() == Some("AXMenu") {+ let items = unsafe { copy_children(child) };+ open |= !items.is_empty();+ for item in items {+ unsafe { CFRelease(item as _) };+ }+ }+ unsafe { CFRelease(child as _) };+ }+ open+}++/// Close a menu this call opened, without choosing anything. `AXCancel` is+/// enough for AppKit; Chromium's menu ignores it, so fall back to Escape sent+/// to the app (the open menu is what receives it).+fn dismiss_popup_menu(popup: AXUIElementRef, pid: i32) {+ for child in unsafe { copy_children(popup) } {+ let role = unsafe { copy_string_attr(child, "AXRole") }.unwrap_or_default();+ if role == "AXMenu" {+ let _ = unsafe { perform_action(child, "AXCancel") };+ }+ unsafe { CFRelease(child as _) };+ }+ let deadline = std::time::Instant::now() + POPUP_CLOSE_TIMEOUT;+ while popup_menu_is_open(popup) {+ if std::time::Instant::now() >= deadline {+ let _ = crate::input::keyboard::press_key_no_auth(pid, "escape", &[]);+ std::thread::sleep(POPUP_CLOSE_TIMEOUT);+ return;+ }+ std::thread::sleep(POPUP_POLL_INTERVAL);+ }+}+fn select_popup_option(element: AXUIElementRef,element_index: usize,@@ -545,73 +673,165 @@ fn select_popup_option(value: &str,element_title: &str,) -> anyhow::Result<String> {- let children = unsafe { copy_children(element) };-- if !children.is_empty() {- // Strategy 1: AX children (native AppKit NSPopUpButton).- let value_lower = value.to_lowercase();- let mut matched_idx: Option<usize> = None;- let mut available: Vec<String> = Vec::with_capacity(children.len());-- for (i, &child) in children.iter().enumerate() {- let child_title = unsafe { copy_string_attr(child, "AXTitle") }.unwrap_or_default();- let child_value = unsafe { copy_string_attr(child, "AXValue") }.unwrap_or_default();- available.push(child_title.clone());- if child_title.to_lowercase() == value_lower- || child_value.to_lowercase() == value_lower- {- matched_idx = Some(i);+ let mut options = popup_options(element);+ let mut opened_menu = false;+ let mut press_thread = None;++ if matching_option(&option_pairs(&options), value).is_none() {+ // Safari/WebKit: no AX children while the popup is closed. Set the+ // <select> through the DOM instead of opening a menu.+ if options.is_empty() {+ let app_name = crate::apps::get_app_name_for_pid(pid).unwrap_or_default();+ if app_name == "Safari" {+ return set_select_via_js(element_index, element_title, value);+ }+ }+ // AppKit NSPopUpButton and Chromium <select> publish their items only+ // while the menu is open (a closed Chromium popup lists just the+ // selected one). Open it, wait for the full list, press the match,+ // and close the menu again whatever happens. While the menu is open+ // the app's menu tracking holds key focus, so the window that was key+ // loses it until the menu closes.+ //+ // The AXPress returns only once the app's menu tracking lets it (or+ // the messaging timeout fires), so run it on its own thread and read+ // the items as soon as they appear: the menu, and with it the key+ // focus it holds, stays open for the shortest time.+ let already_open = popup_menu_is_open(element);+ let closed_titles = if already_open {+ Vec::new()+ } else {+ option_pairs(&options)+ };+ release_options(&options);+ opened_menu = true;+ // A menu left open by an earlier click is already showing its items;+ // pressing again would close it.+ if !already_open {+ let popup_address = element as usize;+ press_thread = Some(std::thread::spawn(move || unsafe {+ let popup = popup_address as AXUIElementRef;+ crate::ax::bindings::AXUIElementSetMessagingTimeout(+ popup,+ POPUP_PRESS_TIMEOUT_SECONDS,+ );+ let _ = perform_action(popup, "AXPress");+ crate::ax::bindings::AXUIElementSetMessagingTimeout(popup, 0.0);+ }));+ }+ let deadline = std::time::Instant::now() + POPUP_OPEN_TIMEOUT;+ let mut last_seen: Vec<(String, String)> = Vec::new();+ let mut stable_polls = 0;+ loop {+ options = popup_options(element);+ let seen = option_pairs(&options);+ if matching_option(&seen, value).is_some() {+ break;+ }+ // The menu is open once the list differs from the closed one; it+ // is complete once the list stops changing.+ if !seen.is_empty() && seen != closed_titles {+ stable_polls = if seen == last_seen {+ stable_polls + 1+ } else {+ 0+ };+ if stable_polls >= POPUP_STABLE_POLLS {+ break;+ }+ }+ last_seen = seen;+ if std::time::Instant::now() >= deadline {break;}+ release_options(&options);+ std::thread::sleep(POPUP_POLL_INTERVAL);}+ if options.is_empty() {+ dismiss_popup_menu(element, pid);+ if let Some(press) = press_thread.take() {+ let _ = press.join();+ }+ anyhow::bail!(+ "AXPopUpButton [{element_index}] \"{element_title}\" exposed no options even \+ after its menu was opened, so nothing was selected. Click the popup, then \+ choose the option with press_key (down, return) or a pixel click on the item."+ )+ }+ }- let result = if let Some(i) = matched_idx {- let child = children[i];- let opt_title =- unsafe { copy_string_attr(child, "AXTitle") }.unwrap_or_else(|| value.to_string());- let err = unsafe { perform_action(child, "AXPress") };+ let result = match matching_option(&option_pairs(&options), value) {+ Some(i) => {+ let option = &options[i];+ let err = unsafe { perform_action(option.element, "AXPress") };if err == kAXErrorSuccess {+ let label = if option.title.is_empty() {+ &option.value+ } else {+ &option.title+ };Ok(format!(- "✅ Selected '{opt_title}' in AXPopUpButton [{element_index}] \- \"{element_title}\" via AX child AXPress."+ "✅ Selected '{label}' in AXPopUpButton [{element_index}] \+ \"{element_title}\" via AX menu item AXPress{}.",+ if opened_menu {+ " (the popup's menu was opened for the selection and closed again)"+ } else {+ ""+ }))} else {- anyhow::bail!("AXPress on child option failed with error {err}")+ if opened_menu {+ dismiss_popup_menu(element, pid);+ }+ Err(anyhow::anyhow!(+ "AXPress on menu item failed with error {err}"+ ))}- } else {- let avail = available- .iter()- .map(|t| format!("\"{t}\""))- .collect::<Vec<_>>()- .join(", ");- anyhow::bail!(- "No AX child matching '{value}' in AXPopUpButton [{element_index}] \- \"{element_title}\". Available: [{avail}]"- )- };-- // Release children (copy_children retains each one).- for &child in &children {- unsafe {- CFRelease(child as _);+ }+ None => {+ if opened_menu {+ dismiss_popup_menu(element, pid);}+ Err(anyhow::anyhow!(+ "No option matching '{value}' in AXPopUpButton [{element_index}] \+ \"{element_title}\". Available: [{}]",+ describe_available(&options)+ ))}-- return result;+ };+ // The opening AXPress returns once the menu is closed or its timeout+ // fires; wait for it so no AX call outlives this tool call.+ if let Some(press) = press_thread {+ let _ = press.join();}+ release_options(&options);+ result+}- // Strategy 2: Safari/WebKit — no AX children when popup is closed.- // Use osascript do JavaScript to set the <select> element's DOM value.- let app_name = crate::apps::get_app_name_for_pid(pid).unwrap_or_default();+#[cfg(test)]+mod popup_option_tests {+ use super::matching_option;++ fn pairs(titles: &[&str]) -> Vec<(String, String)> {+ titles+ .iter()+ .map(|title| ((*title).to_owned(), String::new()))+ .collect()+ }- if app_name != "Safari" {- anyhow::bail!(- "AXPopUpButton [{element_index}] '{element_title}' has no AX children and \- target is '{app_name}' (not Safari) — no fallback available."- )+ #[test]+ fn matches_title_ignoring_case_and_whitespace() {+ let options = pairs(&["Open", "Duplicate", "Closed"]);+ assert_eq!(matching_option(&options, "duplicate"), Some(1));+ assert_eq!(matching_option(&options, " Closed "), Some(2));+ assert_eq!(matching_option(&options, "Pending"), None);}- set_select_via_js(element_index, element_title, value)+ #[test]+ fn matches_value_when_title_differs() {+ let options = vec![("Duplicate of".to_owned(), "dup".to_owned())];+ assert_eq!(matching_option(&options, "DUP"), Some(0));+ }}// ── Safari JavaScript fallback ───────────────────────────────────────────────diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.jsonindex 22174142d4..68dbcffc03 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json@@ -480,7 +480,7 @@"read_only": false},{- "description": "Click a target pid. Prefer `element_token` (from get_window_state): it identifies one snapshot element, works on backgrounded, minimized or off-Space windows, and moves no cursor or focus. Use `x, y` only for canvas / video / WebGL / custom-drawn surfaces missing from the AX tree.\n\n- element_token: AX action path. Tokens are scoped to (pid, window_id) and stale once the window is snapshotted again.\n- x, y: window-local pixels of the get_window_state screenshot, sent as CGEvent mouse events. Needs a visible window. `modifier` takes cmd/shift/option/ctrl.\n\n`button` defaults to left; on the AX path \"right\" maps to AXShowMenu and \"middle\" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call.",+ "description": "Click a target pid. Prefer `element_token` (from get_window_state): it identifies one snapshot element, works on backgrounded, minimized or off-Space windows, and moves no cursor or focus. Use `x, y` only for canvas / video / WebGL / custom-drawn surfaces missing from the AX tree.\n\n- element_token: AX action path. Tokens are scoped to (pid, window_id) and stale once the window is snapshotted again.\n- x, y: window-local pixels of the get_window_state screenshot, sent as CGEvent mouse events. Needs a visible window. `modifier` takes cmd/shift/option/ctrl.\n\n`button` defaults to left; on the AX path \"right\" maps to AXShowMenu and \"middle\" falls back to a pixel click at the element center. `action`: press (default), show_menu, pick, confirm, cancel, open. `from_zoom:true` translates zoom-image pixels after a `zoom` call. Pressing a popup button opens its menu and leaves it open (holding key focus) until dismissed; to choose an option use `set_value`.","destructive": true,"idempotent": false,"input_schema": {@@ -1232,7 +1232,7 @@"read_only": false},{- "description": "Set an element's value by `element_token`. A popup button / select dropdown: presses the child option whose title or value matches `value` (case-insensitive) without opening the menu or stealing focus. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).\n\nA Finder file name (list row or Get Info `Name` field, not being edited) is refused with `file_name_needs_rename`; the refusal names the keyboard route. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.",+ "description": "Set an element's value by `element_token`. A popup button / select dropdown: selects the menu item whose title or value matches `value` (case-insensitive). Safari `<select>` is set through the DOM; AppKit and Chromium popups list items only while open, so the menu is opened, the item pressed and the menu closed again (the front window loses key focus for ~0.4 s). An unknown value lists the options. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).\n\nA Finder file name (list row or Get Info `Name` field, not being edited) is refused with `file_name_needs_rename`; the refusal names the keyboard route. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.","destructive": true,"idempotent": true,"input_schema": {