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): stop silent background failures in TextEdit and Finder on macOS (#5057)
Francesco Bonacci309380889019
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/keys-and-shortcuts.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/keys-and-shortcuts.mdxindex cd1f0b64f9..3d3ef6ad02 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools/keys-and-shortcuts.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools/keys-and-shortcuts.mdx@@ -119,7 +119,7 @@ Effect: destructive. Platforms: macOS, Linux, Windows.<Tab value="macOS">Press a key combination: e.g. `["cmd", "c"]` for Copy, `["cmd", "shift", "4"]` for screenshot selection. Follows the same `delivery_mode` ladder as click/type_text: it does NOT raise the window by default:-• `background` (default): post the combo to the target pid WITHOUT fronting or raising it; uses the macOS 14+ auth-message envelope so Chromium/Electron accept it as trusted live input. With an AX target, focus that exact element first. No top-level focus steal. `window_id` here only targets the combo; it does not raise.+• `background` (default): post the combo to the target pid WITHOUT fronting or raising it; uses the macOS 14+ auth-message envelope so Chromium/Electron accept it as trusted live input. With an AX target, focus that exact element first. No top-level focus steal. `window_id` here only targets the combo; it does not raise. Background key events never reach a native app's menus, so when the combo is a menu item's key equivalent (cmd+s, cmd+w, ...) and the app is not in front, that menu item runs through accessibility instead (a disabled Save is saved through the app's scripting interface and verified on disk); a menu item macOS keeps disabled in the background is refused with `background_unavailable`, and no keys are sent.• `foreground`: briefly front the window (NSMenu path, < 1 ms via SLPSSetFrontProcessWithOptions) so native menu key-equivalents (Cmd+Z, Cmd+W) dispatch, then restore the prior frontmost; the explicit escalation for menu-bar shortcuts on non-Chromium apps that ignore a background combo. With an AX target or x,y, the focused field receives the chord through the foreground HID queue (needed by native Chromium fields such as the omnibox). Requires window_id.A combo is never driver-verifiable (no read-back) → effect:"unverifiable"; confirm via screenshot. NOTE: a keyboard combo does NOT focus a text field; to type into a backgrounded Electron input, establish real renderer focus with a PIXEL click first, then `type_text`. If an app only accepts paste, call `clipboard_write`, then `clipboard_read` and verify its types (and text when applicable) before selecting or replacing editor content; only then send Cmd+V.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 1dbe5a7e2d..3af30e1aab 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@@ -29,7 +29,7 @@ Effect: destructive, idempotent. Platforms: macOS, Linux, Windows.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 (in the background the user's front window keeps key focus). 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.+A Finder file name cell (list or icon view, not being edited) is renamed through Finder's scripting interface with Finder left in the background, and the new name is read back from disk; the value is the full new name with its extension. macOS asks the user once to allow Cua Driver to control Finder. Finder's Get Info `Name` field is refused with `file_name_needs_rename`. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.**macOS parameters**diff --git a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md b/libs/cua-driver/rust/Skills/cua-driver/MACOS.mdindex f01f7e3f96..9f271ecf74 100644--- a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md+++ b/libs/cua-driver/rust/Skills/cua-driver/MACOS.md@@ -87,6 +87,15 @@ for a known application-menu path. With the app in the background it resolvesthe whole path without opening a menu and never activates the app; if macOSkeeps the item unavailable to a background app it refuses with`background_unavailable` (then, if the user allows it, `bring_to_front` first).+One exception: a disabled Save (the ⌘S item) of a document window is saved+through the app's scripting interface instead, still in the background, and the+result says so; TextEdit disables Save whenever it is behind the user's window.+A Save is verified on disk. A background `hotkey` whose combo is a menu item's+key equivalent (⌘S, ⌘W, ⌘C, ...) in a native app takes the same route, because+background key events never reach an app's menus; no keys are sent. macOS asks+the user once to allow Cua Driver to control the app (Automation) the first+time a scripting route runs; when that is off, the call refuses and nothing is+saved.With the app already in front it resolves every AX level live. Prefer an in-windowelement action when the same command has an ordinary control, and prefer`set_window_frame` for exact geometry. Full rationale is in “Navigating native@@ -596,8 +605,8 @@ starting point for new browser workflows.| `Accessibility permission not granted` | TCC not granted | Stop; tell user to grant in System Settings || `Screen Recording permission not granted` | TCC not granted for capture | Screenshots and pixel actions are unavailable. If the task is AX-completable, use `get_window_state({include_screenshot:false})` and `element_token` actions; otherwise stop and ask the user to run `cua-driver permissions grant` || `AX action failed: ... returned -25200` (or -25205, -25206) | The app may have acted anyway: some AppKit controls return these after a press they performed | Re-read with `get_window_state` before retrying; a second press on a checkbox toggles it back. A radio button or checkbox whose AXValue settles on the pressed state is reported as performed, naming the error |-| `set_value refused (file_name_needs_rename)` | A file's name as Finder lists it: an AXValue write changes only the list, never the file | `click` the item, then with Finder frontmost send `press_key` return, `hotkey` cmd+a, `type_text` the full new name, `press_key` return, each with `scope:"desktop"`; re-read to confirm |-| `set_value refused (file_name_needs_rename)` | A file's name in Finder's Get Info window (AXIdentifier `Name`): an AXValue write changes only the field | foreground `click` at the field's centre in screenshot pixels (with its `capture_id`), then `hotkey` cmd+a, `type_text` the full new name with its extension, `press_key` return, each with `delivery_mode:"foreground"`; a changed extension asks for confirmation first; check the folder listing |+| `set_value refused (file_name_needs_rename)` | A file's name in Finder's Get Info window (AXIdentifier `Name`): an AXValue write changes only the field | `set_value` the full new name on the file's name cell in a Finder window that lists it (renamed through Finder in the background and read back from disk) |+| `Background input refused (no_focused_text_input)` | Untargeted background `type_text` while the window's focused element is not a text input; keys would drive the view (Finder type-to-select) | pass the field's `element_token`, or `x,y` to pixel-focus it first; to rename a Finder file, `set_value` its name cell |## Example end-to-end task (macOS)diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rsindex a84b9a93ff..83da49a9fb 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs@@ -64,6 +64,9 @@ pub enum ActionTransport {MacosAxWindowFrame,MacosCgEventPid,MacosCgEventHid,+ /// An Apple Event to the target app's scripting interface (Finder+ /// rename, a document save), which never activates the app.+ MacosAppleEvent,WindowsUiaInvoke,WindowsUiaToggle,WindowsUiaSelection,@@ -106,6 +109,7 @@ impl ActionTransport {Self::MacosAxWindowFrame,Self::MacosCgEventPid,Self::MacosCgEventHid,+ Self::MacosAppleEvent,Self::WindowsUiaInvoke,Self::WindowsUiaToggle,Self::WindowsUiaSelection,@@ -169,7 +173,9 @@ impl ActionTransport {| Self::LinuxWaylandVirtualPointer| Self::LinuxHyprlandForegroundInput| Self::LinuxCuaCompositorInject => ActionRoute::GlobalInput,- Self::WindowsSetWindowPos | Self::LinuxX11ConfigureWindow => ActionRoute::SystemApi,+ Self::WindowsSetWindowPos | Self::LinuxX11ConfigureWindow | Self::MacosAppleEvent => {+ ActionRoute::SystemApi+ }Self::BrowserCdpRuntimeFunction => ActionRoute::Dom,Self::BrowserCdpInputMouse | Self::BrowserCdpInputKey => ActionRoute::TrustedInput,}@@ -1104,6 +1110,7 @@ fn transport_name(transport: ActionTransport) -> &'static str {ActionTransport::MacosAxWindowFrame => "macos_ax_window_frame",ActionTransport::MacosCgEventPid => "macos_cg_event_pid",ActionTransport::MacosCgEventHid => "macos_cg_event_hid",+ ActionTransport::MacosAppleEvent => "macos_apple_event",ActionTransport::WindowsUiaInvoke => "windows_uia_invoke",ActionTransport::WindowsUiaToggle => "windows_uia_toggle",ActionTransport::WindowsUiaSelection => "windows_uia_selection",diff --git a/libs/cua-driver/rust/crates/platform-macos/src/apple_events.rs b/libs/cua-driver/rust/crates/platform-macos/src/apple_events.rsnew file mode 100644index 0000000000..b4ee2a43fb--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-macos/src/apple_events.rs@@ -0,0 +1,534 @@+//! Background routes through an app's scripting interface (Apple Events).+//!+//! Some commands cannot run in a background app through accessibility or key+//! events. TextEdit keeps File > Save disabled while it is not the active app+//! (AppKit validates Save against the main window, and a background app has+//! none), and background key events never reach a menu's key equivalents.+//! Finder closes an inline rename field when it is not active, and an AXValue+//! write to a file's name cell changes only the list. An Apple Event runs the+//! same command inside the app without activating it, raising a window, or+//! touching the pointer, so these routes keep the user's front app untouched.+//!+//! Apple Events need the user's Automation consent for each target app. The+//! permission is read first without asking. When macOS has never asked, it+//! shows its consent prompt once, on the first route that needs that app.+//! When the user has turned it off, the caller gets an honest refusal.++use std::ffi::c_void;+use std::io::Write;+use std::path::Path;+use std::process::{Command, Stdio};+use std::time::{Duration, Instant};++/// Whether this process may send Apple Events to an app.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AutomationPermission {+ Granted,+ /// macOS has not asked the user yet; the first event shows its prompt.+ NeedsConsent,+ /// The user turned it off in System Settings > Privacy & Security >+ /// Automation.+ Denied,+ /// The target app is not running.+ NotRunning,+ Unknown(i32),+}++#[repr(C)]+struct AeDesc {+ descriptor_type: u32,+ data_handle: *mut c_void,+}++#[link(name = "CoreServices", kind = "framework")]+extern "C" {+ fn AECreateDesc(+ type_code: u32,+ data_ptr: *const c_void,+ data_size: isize,+ result: *mut AeDesc,+ ) -> i16;+ fn AEDisposeDesc(desc: *mut AeDesc) -> i16;+ fn AEDeterminePermissionToAutomateTarget(+ target: *const AeDesc,+ event_class: u32,+ event_id: u32,+ ask_user_if_needed: u8,+ ) -> i32;+}++const TYPE_APPLICATION_BUNDLE_ID: u32 = u32::from_be_bytes(*b"bund");+const TYPE_WILDCARD: u32 = u32::from_be_bytes(*b"****");++fn permission_from_status(status: i32) -> AutomationPermission {+ match status {+ 0 => AutomationPermission::Granted,+ -1743 => AutomationPermission::Denied,+ -1744 => AutomationPermission::NeedsConsent,+ -600 => AutomationPermission::NotRunning,+ other => AutomationPermission::Unknown(other),+ }+}++/// Read this process's Automation permission for `bundle_id` without asking.+pub fn automation_permission(bundle_id: &str) -> AutomationPermission {+ let mut desc = AeDesc {+ descriptor_type: 0,+ data_handle: std::ptr::null_mut(),+ };+ let bytes = bundle_id.as_bytes();+ let created = unsafe {+ AECreateDesc(+ TYPE_APPLICATION_BUNDLE_ID,+ bytes.as_ptr().cast(),+ bytes.len() as isize,+ &mut desc,+ )+ };+ if created != 0 {+ return AutomationPermission::Unknown(created as i32);+ }+ let status =+ unsafe { AEDeterminePermissionToAutomateTarget(&desc, TYPE_WILDCARD, TYPE_WILDCARD, 0) };+ unsafe { AEDisposeDesc(&mut desc) };+ permission_from_status(status)+}++/// A route that did not run, in words a caller can act on.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ScriptRefusal {+ pub code: &'static str,+ pub reason: String,+}++/// Run `script` with `osascript`, passing `args` to its `on run argv`+/// handler. Arguments never become script source, so a file name cannot+/// inject AppleScript. Returns the script's result text.+pub fn run_script(script: &str, args: &[&str], timeout: Duration) -> Result<String, ScriptRefusal> {+ let mut child = Command::new("/usr/bin/osascript")+ .arg("-")+ .args(args)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|error| ScriptRefusal {+ code: "automation_failed",+ reason: format!("osascript could not start: {error}"),+ })?;+ if let Some(mut stdin) = child.stdin.take() {+ let _ = stdin.write_all(script.as_bytes());+ }+ let deadline = Instant::now() + timeout;+ loop {+ match child.try_wait() {+ Ok(Some(_)) => break,+ Ok(None) if Instant::now() >= deadline => {+ let _ = child.kill();+ let _ = child.wait();+ return Err(ScriptRefusal {+ code: "automation_timeout",+ reason: format!(+ "the app did not answer within {} s (a macOS Automation prompt may be \+ waiting for the user)",+ timeout.as_secs()+ ),+ });+ }+ Ok(None) => std::thread::sleep(Duration::from_millis(25)),+ Err(error) => {+ return Err(ScriptRefusal {+ code: "automation_failed",+ reason: format!("osascript wait failed: {error}"),+ })+ }+ }+ }+ let output = child.wait_with_output().map_err(|error| ScriptRefusal {+ code: "automation_failed",+ reason: format!("osascript output could not be read: {error}"),+ })?;+ if output.status.success() {+ return Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned());+ }+ let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();+ Err(script_error_refusal(&stderr))+}++/// Map an osascript error line ("... (-1743)") to a refusal.+fn script_error_refusal(stderr: &str) -> ScriptRefusal {+ if stderr.contains("(-1743)") {+ ScriptRefusal {+ code: "automation_denied",+ reason: "macOS does not allow Cua Driver to control this app (System Settings > \+ Privacy & Security > Automation)"+ .into(),+ }+ } else {+ // osascript prints "<offset>: execution error: <message> (<code>)".+ let message = stderr+ .split_once("execution error: ")+ .map(|(_, rest)| rest)+ .unwrap_or(stderr);+ ScriptRefusal {+ code: "automation_failed",+ reason: message.to_owned(),+ }+ }+}++/// Check the permission before a route runs: refuse when the user turned it+/// off, so no event is sent.+fn ensure_permitted(bundle_id: &str, app_name: &str) -> Result<(), ScriptRefusal> {+ match automation_permission(bundle_id) {+ AutomationPermission::Denied => Err(ScriptRefusal {+ code: "automation_denied",+ reason: format!(+ "macOS does not allow Cua Driver to control {app_name}. The user can allow it in \+ System Settings > Privacy & Security > Automation"+ ),+ }),+ AutomationPermission::NotRunning => Err(ScriptRefusal {+ code: "automation_failed",+ reason: format!("{app_name} is not running"),+ }),+ // NeedsConsent: macOS shows its prompt once, on this event.+ _ => Ok(()),+ }+}++const FINDER_BUNDLE_ID: &str = "com.apple.finder";++const FINDER_RENAME_SCRIPT: &str = r#"on run argv+ set theItem to (POSIX file (item 1 of argv)) as alias+ tell application id "com.apple.finder"+ set name of theItem to (item 2 of argv)+ end tell+ return "ok"+end run+"#;++/// Whether `name` can be a single file name (no path separators, not empty+/// or a dot entry).+pub fn valid_file_name(name: &str) -> bool {+ !name.is_empty() && name != "." && name != ".." && !name.contains('/') && !name.contains('\0')+}++/// Rename the file or folder at `path` to `new_name` through Finder, then+/// read the folder back. Returns the new path once it exists and the old+/// name is gone.+pub fn finder_rename(path: &Path, new_name: &str) -> Result<std::path::PathBuf, ScriptRefusal> {+ if !valid_file_name(new_name) {+ return Err(ScriptRefusal {+ code: "invalid_file_name",+ reason: format!("\"{new_name}\" is not a single file name"),+ });+ }+ let parent = path.parent().ok_or_else(|| ScriptRefusal {+ code: "automation_failed",+ reason: "the item has no parent folder".into(),+ })?;+ let target = parent.join(new_name);+ let same_item = path.file_name().and_then(|n| n.to_str()) == Some(new_name);+ if same_item {+ return Ok(target);+ }+ // A name that differs only in case is the same entry on a case-+ // insensitive volume; anything else must not exist yet.+ let case_only = path+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|old| old.eq_ignore_ascii_case(new_name));+ if !case_only && target.exists() {+ return Err(ScriptRefusal {+ code: "name_taken",+ reason: format!(+ "\"{new_name}\" already exists in {}; nothing was renamed",+ parent.display()+ ),+ });+ }+ ensure_permitted(FINDER_BUNDLE_ID, "Finder")?;+ let path_text = path.to_string_lossy();+ run_script(+ FINDER_RENAME_SCRIPT,+ &[&path_text, new_name],+ Duration::from_secs(30),+ )?;+ // Read the folder back: the new name is listed and the old one is gone.+ let deadline = Instant::now() + Duration::from_secs(2);+ loop {+ if folder_lists(parent, new_name) && (case_only || !path.exists()) {+ return Ok(target);+ }+ if Instant::now() >= deadline {+ return Err(ScriptRefusal {+ code: "rename_unconfirmed",+ reason: format!(+ "Finder accepted the rename, but {} does not list \"{new_name}\"",+ parent.display()+ ),+ });+ }+ std::thread::sleep(Duration::from_millis(50));+ }+}++fn folder_lists(folder: &Path, name: &str) -> bool {+ std::fs::read_dir(folder).is_ok_and(|entries| {+ entries+ .flatten()+ .any(|entry| entry.file_name().to_str() == Some(name))+ })+}++/// Save the open document whose file is `path` in the app `bundle_id`+/// through the Cocoa Standard Suite `save` command, then read its modified+/// flag back. Raw codes keep the script independent of the app's+/// terminology: `docu` document, `ppth` its path (TextEdit) or `file` its+/// file (the Standard Suite), `imod` modified, `core/save` save. Returns `false` when the app still reports unsaved+/// changes.+const SAVE_DOCUMENT_SCRIPT: &str = r#"on run argv+ set thePath to item 1 of argv+ tell application id (item 2 of argv)+ repeat with theDocument in (every «class docu»)+ set theDocumentPath to missing value+ try+ set theDocumentPath to «property ppth» of theDocument+ end try+ if theDocumentPath is missing value then+ try+ set theDocumentPath to POSIX path of ((«property file» of theDocument) as alias)+ end try+ end if+ if theDocumentPath is thePath then+ «event coresave» theDocument+ return («property imod» of theDocument) as text+ end if+ end repeat+ end tell+ return "no-document"+end run+"#;++/// Read the modified flag of the open document whose file is `path`, the+/// same document lookup as [`SAVE_DOCUMENT_SCRIPT`] without saving.+const DOCUMENT_MODIFIED_SCRIPT: &str = r#"on run argv+ set thePath to item 1 of argv+ tell application id (item 2 of argv)+ repeat with theDocument in (every «class docu»)+ set theDocumentPath to missing value+ try+ set theDocumentPath to «property ppth» of theDocument+ end try+ if theDocumentPath is missing value then+ try+ set theDocumentPath to POSIX path of ((«property file» of theDocument) as alias)+ end try+ end if+ if theDocumentPath is thePath then+ return («property imod» of theDocument) as text+ end if+ end repeat+ end tell+ return "no-document"+end run+"#;++/// Whether the app reports unsaved changes in the document at `path`.+/// Only reads when Automation is already granted, so a readback never shows+/// the consent prompt; `None` when it cannot tell.+pub fn document_modified(bundle_id: &str, path: &Path) -> Option<bool> {+ if automation_permission(bundle_id) != AutomationPermission::Granted {+ return None;+ }+ let path_text = path.to_string_lossy();+ match run_script(+ DOCUMENT_MODIFIED_SCRIPT,+ &[&path_text, bundle_id],+ Duration::from_secs(5),+ )+ .ok()?+ .as_str()+ {+ "true" => Some(true),+ "false" => Some(false),+ _ => None,+ }+}++/// Outcome of a background save.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct SavedDocument {+ /// The file's modification time moved during the save.+ pub file_written: bool,+}++pub fn save_document(+ bundle_id: &str,+ app_name: &str,+ path: &Path,+) -> Result<SavedDocument, ScriptRefusal> {+ ensure_permitted(bundle_id, app_name)?;+ let before = modified_time(path);+ let path_text = path.to_string_lossy();+ let result = run_script(+ SAVE_DOCUMENT_SCRIPT,+ &[&path_text, bundle_id],+ Duration::from_secs(30),+ )?;+ match result.as_str() {+ "false" => {}+ "true" => {+ return Err(ScriptRefusal {+ code: "save_unconfirmed",+ reason: format!(+ "{app_name} accepted the save, but still reports unsaved changes in {}",+ path.display()+ ),+ })+ }+ "no-document" => {+ return Err(ScriptRefusal {+ code: "automation_failed",+ reason: format!("{app_name} lists no open document for {}", path.display()),+ })+ }+ other => {+ return Err(ScriptRefusal {+ code: "save_unconfirmed",+ reason: format!("{app_name} answered \"{other}\" to the save"),+ })+ }+ }+ let file_written = wait_for_new_mtime(path, before, Duration::from_millis(1500));+ Ok(SavedDocument { file_written })+}++pub fn modified_time(path: &Path) -> Option<std::time::SystemTime> {+ std::fs::metadata(path).and_then(|m| m.modified()).ok()+}++/// Wait up to `timeout` for `path`'s modification time to move past+/// `before`.+pub fn wait_for_new_mtime(+ path: &Path,+ before: Option<std::time::SystemTime>,+ timeout: Duration,+) -> bool {+ let deadline = Instant::now() + timeout;+ loop {+ let now = modified_time(path);+ if now.is_some() && now != before {+ return true;+ }+ if Instant::now() >= deadline {+ return false;+ }+ std::thread::sleep(Duration::from_millis(50));+ }+}++/// The file path of a `file://` URL string, as `AXDocument` and `AXURL`+/// report them.+pub fn file_url_to_path(url: &str) -> Option<std::path::PathBuf> {+ use core_foundation::{base::TCFType, string::CFString, url::CFURL};+ if !url.starts_with("file://") {+ return None;+ }+ let text = CFString::new(url);+ let raw = unsafe {+ core_foundation::url::CFURLCreateWithString(+ std::ptr::null(),+ text.as_concrete_TypeRef(),+ std::ptr::null(),+ )+ };+ if raw.is_null() {+ return None;+ }+ let url = unsafe { CFURL::wrap_under_create_rule(raw) };+ url.to_path()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn permission_codes_map_to_states() {+ assert_eq!(permission_from_status(0), AutomationPermission::Granted);+ assert_eq!(permission_from_status(-1743), AutomationPermission::Denied);+ assert_eq!(+ permission_from_status(-1744),+ AutomationPermission::NeedsConsent+ );+ assert_eq!(+ permission_from_status(-600),+ AutomationPermission::NotRunning+ );+ assert_eq!(+ permission_from_status(-50),+ AutomationPermission::Unknown(-50)+ );+ }++ #[test]+ fn script_errors_name_a_denied_permission() {+ let denied = script_error_refusal(+ "0:120: execution error: Not authorized to send Apple events to Finder. (-1743)",+ );+ assert_eq!(denied.code, "automation_denied");+ let other = script_error_refusal(+ "0:98: execution error: Finder got an error: The name \"b.txt\" is already taken. (-48)",+ );+ assert_eq!(other.code, "automation_failed");+ assert!(other.reason.starts_with("Finder got an error"));+ }++ #[test]+ fn file_names_are_single_path_components() {+ assert!(valid_file_name("renamed.txt"));+ assert!(valid_file_name("with space é.md"));+ for bad in ["", ".", "..", "a/b", "x\0y"] {+ assert!(!valid_file_name(bad), "{bad:?}");+ }+ }++ #[test]+ fn file_urls_decode_to_paths() {+ assert_eq!(+ file_url_to_path("file:///Users/lume/xfb/te/a%20main.txt"),+ Some("/Users/lume/xfb/te/a main.txt".into())+ );+ assert_eq!(file_url_to_path("https://example.com/a"), None);+ }++ #[test]+ fn a_rename_onto_an_existing_name_is_refused_before_any_event() {+ let dir = std::env::temp_dir().join(format!("cua-ae-test-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("a.txt"), "a").unwrap();+ std::fs::write(dir.join("b.txt"), "b").unwrap();+ let refused = finder_rename(&dir.join("a.txt"), "b.txt").unwrap_err();+ assert_eq!(refused.code, "name_taken");+ assert_eq!(+ finder_rename(&dir.join("a.txt"), "x/y").unwrap_err().code,+ "invalid_file_name"+ );+ // Renaming to the current name is already done; nothing is sent.+ assert_eq!(+ finder_rename(&dir.join("a.txt"), "a.txt").unwrap(),+ dir.join("a.txt")+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn scripts_pass_values_as_arguments_only() {+ // Values reach the scripts through argv, never through the source.+ assert!(FINDER_RENAME_SCRIPT.contains("item 1 of argv"));+ assert!(SAVE_DOCUMENT_SCRIPT.contains("item 2 of argv"));+ assert!(!FINDER_RENAME_SCRIPT.contains('{'));+ }+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/document_edit.rs b/libs/cua-driver/rust/crates/platform-macos/src/document_edit.rsindex 674647e57c..dd919c71c2 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/document_edit.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/document_edit.rs@@ -116,9 +116,69 @@ pub unsafe fn ensure_marked_after_ax_write(if !in_document_window(element) {return DocumentEdited::NotADocument;}- if !keys_reach_element_window(pid, element) {+ if keys_reach_element_window(pid, element) {+ return send_net_zero_edit(pid, element, caret_to_end);+ }+ // With several windows open, the app's key window is another document,+ // and pid-routed keys go there. Make this window key inside the app+ // through its focus record (no activation, no raise; the user's window+ // keeps key status), send the net-zero edit, and hand key back. The+ // app's AXFocusedWindow does not follow a focus record, so the proof is+ // the document's own modified flag, read through the app's scripting+ // interface (only when Automation is already allowed).+ let Some(own) = element_window_id(element) else {+ return DocumentEdited::NotMarked;+ };+ let Some(path) = document_path(element) else {+ return DocumentEdited::NotMarked;+ };+ let Some(bundle_id) = crate::apps::bundle_id_for_pid(pid) else {+ return DocumentEdited::NotMarked;+ };+ // A document that already has unsaved changes autosaves its whole text,+ // the accessibility write included; no keys are needed.+ match crate::apple_events::document_modified(&bundle_id, &path) {+ Some(true) => return DocumentEdited::Marked,+ // Without the readback the edit cannot be proven; send nothing.+ None => return DocumentEdited::NotMarked,+ Some(false) => {}+ }+ let previous = crate::ax::bindings::focused_window_id_of_pid(pid);+ if !crate::input::skylight::activate_without_raise_with(pid, own, false) {return DocumentEdited::NotMarked;}+ std::thread::sleep(Duration::from_millis(120));+ let sent = send_net_zero_edit(pid, element, caret_to_end);+ if let Some(previous) = previous {+ crate::input::skylight::activate_without_raise_with(pid, previous, false);+ }+ if sent == DocumentEdited::Marked+ && crate::apple_events::document_modified(&bundle_id, &path) == Some(true)+ {+ DocumentEdited::Marked+ } else {+ DocumentEdited::NotMarked+ }+}++/// The file behind the element's document window.+///+/// # Safety+/// `element` must be a live `AXUIElementRef`.+unsafe fn document_path(element: AXUIElementRef) -> Option<std::path::PathBuf> {+ let window = copy_element_attr(element, "AXWindow")?;+ let url = copy_string_attr(window, "AXDocument");+ core_foundation::base::CFRelease(window as _);+ crate::apple_events::file_url_to_path(&url?)+}++/// Type a space and a backspace into `element` and check the text did not+/// move.+unsafe fn send_net_zero_edit(+ pid: i32,+ element: AXUIElementRef,+ caret_to_end: bool,+) -> DocumentEdited {if caret_to_end {caret_to_end_of(element);}@@ -138,6 +198,17 @@ pub unsafe fn ensure_marked_after_ax_write(}}+/// The CGWindowID of the window `element` sits in.+///+/// # Safety+/// `element` must be a live `AXUIElementRef`.+unsafe fn element_window_id(element: AXUIElementRef) -> Option<u32> {+ let window = copy_element_attr(element, "AXWindow")?;+ let id = crate::ax::bindings::ax_get_window_id(window);+ core_foundation::base::CFRelease(window as _);+ id+}+/// Collapse the selection to the end of the text.////// # Safetydiff --git a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs b/libs/cua-driver/rust/crates/platform-macos/src/lib.rsindex 76275f9eb3..376e3e90fb 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs@@ -11,6 +11,8 @@// clippy's result_large_err does not apply.#![allow(clippy::result_large_err)]+#[cfg(target_os = "macos")]+pub mod apple_events;#[cfg(target_os = "macos")]pub mod apps;#[cfg(target_os = "macos")]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rsindex 3b44e65bcd..438d8d21a9 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs@@ -39,7 +39,13 @@ fn def() -> &'static ToolDef {fronting or raising it — uses the macOS 14+ auth-message envelope so \Chromium/Electron accept it as trusted live input. With an AX target, \focus that exact element first. No top-level focus steal. \- `window_id` here only targets the combo; it does not raise.\n\+ `window_id` here only targets the combo; it does not raise. Background \+ key events never reach a native app's menus, so when the combo is a \+ menu item's key equivalent (cmd+s, cmd+w, ...) and the app is not in \+ front, that menu item runs through accessibility instead (a disabled \+ Save is saved through the app's scripting interface and verified on \+ disk); a menu item macOS keeps disabled in the background is refused \+ with `background_unavailable`, and no keys are sent.\n\• `foreground`: briefly front the window (NSMenu path, < 1 ms via \SLPSSetFrontProcessWithOptions) so native menu key-equivalents \(Cmd+Z, Cmd+W) dispatch, then restore the prior frontmost — the \@@ -272,6 +278,55 @@ impl Tool for HotkeyTool {return error;}+ // ── Menu key equivalents in a background app ──+ // Background key events reach a window's views but never its app's+ // menu key equivalents, so a background cmd+s to TextEdit saved+ // nothing while reporting "Pressed". When the combo is a menu item's+ // key equivalent in a native app that is not in front, run that menu+ // item in the background instead (verified for Save), or refuse when+ // macOS keeps it disabled. No key events are sent on this route.+ if !fg && px.is_none() {+ if let (Some(wid), Some(combo)) = (+ window_id,+ super::menu_equivalent::Combo::parse(&modifiers, &key),+ ) {+ let menu_item = tokio::task::spawn_blocking(move || {+ let native = !super::type_text::is_browser_pid(pid)+ && !crate::browser::electron_js::ElectronJs::is_electron(pid);+ let in_front = apps::frontmost_pid() == Some(pid);+ if native && !in_front {+ super::menu_equivalent::find(pid, &combo)+ } else {+ None+ }+ })+ .await+ .ok()+ .flatten();+ if let Some(item) = menu_item {+ if let Some(ptr) = element_ptr {+ // The menu command acts on the focused element.+ let focused =+ tokio::task::spawn_blocking(move || focus_hotkey_element(pid, ptr))+ .await;+ if !matches!(focused, Ok(Ok(()))) {+ return ToolResult::error(+ "hotkey: the requested element did not take focus, so its menu \+ command was not run.",+ );+ }+ }+ return super::invoke_menu::run_in_background(+ pid,+ wid,+ item.path,+ super::invoke_menu::MenuRequest::KeyEquivalent(key_display),+ )+ .await;+ }+ }+ }+// ── Exact-target background gate (macOS background input v1) ──// A window-addressed background combo is process-scoped transport: it// must prove exact delivery to the requested window (fresh AXWindowsdiff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/invoke_menu.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/invoke_menu.rsindex f6f7d90c94..352fe4c3dc 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/invoke_menu.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/invoke_menu.rs@@ -552,6 +552,31 @@ fn background_unavailable(reason: String) -> ToolResult {}))}+/// Why a background menu item could not be pressed.+#[derive(Debug)]+enum BackgroundPressError {+ /// macOS keeps the item disabled while the app is in the background.+ Disabled {+ message: String,+ is_save: bool,+ },+ Other(String),+}++/// What the background route knows about the pressed item.+#[derive(Debug, Clone, Copy)]+struct PressedItem {+ is_save: bool,+}++/// Whether a menu item's key equivalent is plain Command-S, the Save+/// shortcut in every language.+unsafe fn item_is_save(item: AXUIElementRef) -> bool {+ copy_string_attr(item, "AXMenuItemCmdChar").is_some_and(|ch| ch.eq_ignore_ascii_case("s"))+ && crate::ax::bindings::copy_number_attr(item, "AXMenuItemCmdModifiers").unwrap_or(0.0)+ == 0.0+}+/// Resolve the whole path from the app's live menu bar without opening any/// level, then perform the final item's action. Used for a background app:/// opening a menu-bar menu would take key focus and draw over the user's@@ -560,20 +585,25 @@ unsafe fn invoke_path_in_background(pid: i32,window_id: u32,path: &[String],-) -> Result<(), String> {+) -> Result<PressedItem, BackgroundPressError> {let app = AXUIElementCreateApplication(pid);if app.is_null() {- return Err("invoke_menu: target application is unavailable".into());+ return Err(BackgroundPressError::Other(+ "invoke_menu: target application is unavailable".into(),+ ));}set_messaging_timeout(app);let menu_bar = copy_element_attr(app, "AXMenuBar");CFRelease(app as CFTypeRef);- let menu_bar = menu_bar.ok_or_else(|| "invoke_menu: target exposes no AXMenuBar".to_owned())?;+ let menu_bar = menu_bar.ok_or_else(|| {+ BackgroundPressError::Other("invoke_menu: target exposes no AXMenuBar".to_owned())+ })?;set_messaging_timeout(menu_bar);let target = resolve_exact_prefix(menu_bar, path);CFRelease(menu_bar as CFTypeRef);- let target = target?;+ let target = target.map_err(BackgroundPressError::Other)?;set_messaging_timeout(target);+ let is_save = item_is_save(target);let result = (|| {// AppKit validates menu items against the key window. Make the target// window AppKit-key without raising it or touching the user's window@@ -584,27 +614,224 @@ unsafe fn invoke_path_in_background(std::thread::sleep(Duration::from_millis(120));}if copy_bool_attr(target, "AXEnabled") == Some(false) {- return Err(format!(- "invoke_menu: path segment {} is disabled while the app is in the background",- path.len().saturating_sub(1)- ));+ return Err(BackgroundPressError::Disabled {+ message: format!(+ "invoke_menu: path segment {} is disabled while the app is in the background",+ path.len().saturating_sub(1)+ ),+ is_save,+ });}let actions = copy_action_names(target);let action = choose_action(&actions, true).ok_or_else(|| {- "invoke_menu: the final menu item has no usable native menu action".to_owned()+ BackgroundPressError::Other(+ "invoke_menu: the final menu item has no usable native menu action".to_owned(),+ )})?;let error = perform_action(target, action);if error != kAXErrorSuccess {- return Err(format!(+ return Err(BackgroundPressError::Other(format!("invoke_menu: native action for the final menu item failed with AX error {error}"- ));+ )));}- Ok(())+ Ok(PressedItem { is_save })})();CFRelease(target as CFTypeRef);result}+/// The file behind a document window (its `AXDocument` URL), if any.+fn document_path_of_window(pid: i32, window_id: u32) -> Option<std::path::PathBuf> {+ unsafe {+ let app = AXUIElementCreateApplication(pid);+ if app.is_null() {+ return None;+ }+ set_messaging_timeout(app);+ let mut url = None;+ for window in copy_ax_windows(app) {+ if url.is_none() && ax_get_window_id(window) == Some(window_id) {+ url = copy_string_attr(window, "AXDocument");+ }+ CFRelease(window as CFTypeRef);+ }+ CFRelease(app as CFTypeRef);+ url.as_deref()+ .and_then(crate::apple_events::file_url_to_path)+ }+}++/// How a background menu command was asked for, so the result can say it.+#[derive(Debug, Clone)]+pub(super) enum MenuRequest {+ /// `invoke_menu` with a path.+ Path,+ /// `hotkey` with this combo, which is the item's key equivalent.+ KeyEquivalent(String),+}++impl MenuRequest {+ fn preface(&self, path: &[String]) -> String {+ match self {+ MenuRequest::Path => String::new(),+ MenuRequest::KeyEquivalent(combo) => format!(+ "{combo} is the key equivalent of {}. Key events do not reach a background \+ app's menus, so no keys were sent. ",+ path.join(" > ")+ ),+ }+ }+}++/// Run a menu command in a background app without activating it. Presses+/// the item through accessibility when macOS keeps it enabled; a disabled+/// Save of a document window goes through the app's scripting interface+/// instead (TextEdit disables Save while it is behind the user's window).+/// A Save is verified on disk. Anything else that is disabled is refused+/// with `background_unavailable`.+pub(super) async fn run_in_background(+ pid: i32,+ window_id: u32,+ path: Vec<String>,+ request: MenuRequest,+) -> ToolResult {+ let document = tokio::task::spawn_blocking(move || document_path_of_window(pid, window_id))+ .await+ .ok()+ .flatten();+ let before = document+ .as_deref()+ .and_then(crate::apple_events::modified_time);+ let press_path = path.clone();+ let outcome = tokio::task::spawn_blocking(move || {+ let _key_focus = crate::key_focus_guard::protect(pid);+ unsafe { invoke_path_in_background(pid, window_id, &press_path) }+ })+ .await;+ let preface = request.preface(&path);+ match outcome {+ Ok(Ok(PressedItem { is_save: true })) if document.is_some() => {+ let file = document.clone().expect("checked");+ let written = tokio::task::spawn_blocking(move || {+ crate::apple_events::wait_for_new_mtime(&file, before, Duration::from_secs(2))+ })+ .await+ .unwrap_or(false);+ let file = document.expect("checked");+ if written {+ background_success(+ format!(+ "{preface}Pressed {} through accessibility with the app in the \+ background (not activated). Verified: {} was written to disk.",+ path.join(" > "),+ file.display()+ ),+ ActionEffect::Confirmed,+ ActionTransport::MacosAxAction,+ "The document's file modification time moved after the press",+ )+ } else {+ background_success(+ format!(+ "{preface}Pressed {} through accessibility with the app in the \+ background (not activated), but {} did not change on disk within 2 s. \+ The document may have had no unsaved changes, or the save did not run; \+ verify from fresh state.",+ path.join(" > "),+ file.display()+ ),+ ActionEffect::Unverifiable,+ ActionTransport::MacosAxAction,+ "AX accepted the press; the file modification time did not move",+ )+ }+ }+ Ok(Ok(_)) => background_success(+ format!(+ "{preface}Invoked {} through accessibility with the app in the background (not \+ activated); verify the command's semantic effect from fresh state.",+ path.join(" > ")+ ),+ ActionEffect::Unverifiable,+ ActionTransport::MacosAxAction,+ "Every menu hop resolved uniquely without opening it and AX accepted the final action",+ ),+ Ok(Err(BackgroundPressError::Disabled {+ is_save: true,+ message,+ })) if document.is_some() => {+ let file = document.expect("checked");+ let bundle_id = crate::apps::bundle_id_for_pid(pid).unwrap_or_default();+ let app_name =+ crate::apps::get_app_name_for_pid(pid).unwrap_or_else(|| "the app".into());+ let save_file = file.clone();+ let save_app = app_name.clone();+ let saved = tokio::task::spawn_blocking(move || {+ crate::apple_events::save_document(&bundle_id, &save_app, &save_file)+ })+ .await;+ match saved {+ Ok(Ok(saved)) => background_success(+ format!(+ "{preface}{} is disabled while {app_name} is in the background, so the \+ document was saved through {app_name}'s scripting interface instead \+ (not activated). Verified: {app_name} reports no unsaved changes{}.",+ path.join(" > "),+ if saved.file_written {+ format!(" and {} was written to disk", file.display())+ } else {+ format!(+ "; {} did not change on disk because it already held the \+ document's content",+ file.display()+ )+ }+ ),+ ActionEffect::Confirmed,+ ActionTransport::MacosAppleEvent,+ "The app's scripting interface reported the document saved",+ ),+ Ok(Err(refusal)) => background_unavailable(format!(+ "{preface}{message}, and saving through {app_name}'s scripting interface did not \+ complete ({}: {}). Nothing was saved",+ refusal.code, refusal.reason+ )),+ Err(error) => refusal(format!("invoke_menu: blocking task failed: {error}")),+ }+ }+ Ok(Err(BackgroundPressError::Disabled { message, .. })) => {+ background_unavailable(format!("{preface}{message}"))+ }+ Ok(Err(BackgroundPressError::Other(error))) => refusal(error),+ Err(error) => refusal(format!("invoke_menu: blocking task failed: {error}")),+ }+}++fn background_success(+ text: String,+ effect: ActionEffect,+ transport: ActionTransport,+ detail: &str,+) -> ToolResult {+ // A confirmed result rests on a readback of the effect (the file on disk+ // or the app's own saved state), not on the AX return code.+ let kind = if matches!(effect, ActionEffect::Confirmed) {+ EvidenceKind::ValueReadback+ } else {+ EvidenceKind::NativeApiResult+ };+ ToolResult::text(text).with_action_record(+ ActionExecutionRecord::builder(effect, transport, RequestedDelivery::Background)+ .actual_delivery(ActualDelivery::Background)+ .evidence(ActionEvidence {+ kind,+ detail: detail.into(),+ })+ .build()+ .expect("invoke_menu record is valid"),+ )+}+fn refusal(message: String) -> ToolResult {ToolResult::error(message.clone()).with_structured(serde_json::json!({"status": "refused",@@ -656,38 +883,7 @@ impl Tool for InvokeMenuTool {.await.unwrap_or(false);if !target_in_front {- let background_path = path.clone();- let outcome = tokio::task::spawn_blocking(move || {- let _key_focus = crate::key_focus_guard::protect(pid);- unsafe { invoke_path_in_background(pid, window_id, &background_path) }- })- .await;- return match outcome {- Ok(Ok(())) => ToolResult::text(- "Invoked the native menu item through accessibility with the app in the background (not activated); verify the command's semantic effect from fresh state.",- )- .with_action_record(- ActionExecutionRecord::builder(- ActionEffect::Unverifiable,- ActionTransport::MacosAxAction,- RequestedDelivery::Background,- )- .actual_delivery(ActualDelivery::Background)- .evidence(ActionEvidence {- kind: EvidenceKind::NativeApiResult,- detail: "Every menu hop resolved uniquely without opening it and AX accepted the final action".into(),- })- .build()- .expect("invoke_menu record is valid"),- ),- // Only a disabled item is a background limit; a missing or- // ambiguous path is the same refusal as in the foreground.- Ok(Err(error)) if error.contains("while the app is in the background") => {- background_unavailable(error)- }- Ok(Err(error)) => refusal(error),- Err(error) => refusal(format!("invoke_menu: blocking task failed: {error}")),- };+ return run_in_background(pid, window_id, path, MenuRequest::Path).await;}let outcome = tokio::task::spawn_blocking(move || {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/menu_equivalent.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/menu_equivalent.rsnew file mode 100644index 0000000000..638204710b--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/menu_equivalent.rs@@ -0,0 +1,206 @@+//! Find the menu item a key combination stands for.+//!+//! Background key events reach a window's views but never its app's menu key+//! equivalents (see `input::keyboard::hotkey_no_auth`). A background+//! `cmd+s` to TextEdit was reported as "Pressed" and saved nothing. When a+//! combo is a menu item's key equivalent, `hotkey` acts on that menu item+//! through accessibility instead, or refuses when macOS keeps the item+//! disabled in the background.++use core_foundation::base::{CFRelease, CFTypeRef};++use crate::ax::bindings::{+ copy_bool_attr, copy_children, copy_element_attr, copy_number_attr, copy_string_attr,+ AXUIElementCreateApplication, AXUIElementRef, AXUIElementSetMessagingTimeout,+};++/// `kAXMenuItemModifier*` bits of `AXMenuItemCmdModifiers`.+const MOD_SHIFT: i64 = 1 << 0;+const MOD_OPTION: i64 = 1 << 1;+const MOD_CONTROL: i64 = 1 << 2;+const MOD_NO_COMMAND: i64 = 1 << 3;++/// Upper bound on menu items read per lookup, so a huge dynamic menu cannot+/// stall the call.+const MAX_ITEMS: usize = 2000;++/// A hotkey as a menu key equivalent compares it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(super) struct Combo {+ shift: bool,+ option: bool,+ control: bool,+ /// The uppercase character of the base key.+ character: String,+}++impl Combo {+ /// A combo with Command and one printable base key; `None` for anything+ /// else (no Command, a named key such as `return`), which keeps today's+ /// key-event route.+ pub(super) fn parse(modifiers: &[String], key: &str) -> Option<Self> {+ let mut cmd = false;+ let mut combo = Combo {+ shift: false,+ option: false,+ control: false,+ character: String::new(),+ };+ for modifier in modifiers {+ match modifier.to_ascii_lowercase().as_str() {+ "cmd" | "command" | "super" | "meta" | "win" => cmd = true,+ "shift" => combo.shift = true,+ "option" | "alt" => combo.option = true,+ "ctrl" | "control" => combo.control = true,+ _ => return None,+ }+ }+ let mut chars = key.chars();+ let (Some(ch), None) = (chars.next(), chars.next()) else {+ return None;+ };+ if !cmd || ch.is_whitespace() || ch.is_control() {+ return None;+ }+ combo.character = ch.to_uppercase().collect();+ Some(combo)+ }++ /// Whether a menu item with this `AXMenuItemCmdChar` and+ /// `AXMenuItemCmdModifiers` fires on this combo.+ fn matches(&self, cmd_char: &str, modifiers: i64) -> bool {+ modifiers & MOD_NO_COMMAND == 0+ && cmd_char.to_uppercase() == self.character+ && (modifiers & MOD_SHIFT != 0) == self.shift+ && (modifiers & MOD_OPTION != 0) == self.option+ && (modifiers & MOD_CONTROL != 0) == self.control+ }+}++/// A menu item found for a combo.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(super) struct MenuMatch {+ /// Titles from the menu bar item down to the item.+ pub path: Vec<String>,+ pub enabled: bool,+}++/// Find the item in `pid`'s menu bar whose key equivalent is `combo`. An+/// enabled match wins over a disabled one with the same equivalent. The+/// Apple menu is skipped: its commands belong to the system.+pub(super) fn find(pid: i32, combo: &Combo) -> Option<MenuMatch> {+ unsafe {+ let app = AXUIElementCreateApplication(pid);+ if app.is_null() {+ return None;+ }+ let _ = AXUIElementSetMessagingTimeout(app, 1.0);+ let bar = copy_element_attr(app, "AXMenuBar");+ CFRelease(app as CFTypeRef);+ let bar = bar?;+ let mut found: Option<MenuMatch> = None;+ let mut budget = MAX_ITEMS;+ for (index, top) in semantic_items(bar).into_iter().enumerate() {+ let title = copy_string_attr(top, "AXTitle").unwrap_or_default();+ if index > 0 || title != "Apple" {+ search(top, vec![title], combo, &mut found, &mut budget, 0);+ }+ CFRelease(top as CFTypeRef);+ if found.as_ref().is_some_and(|m| m.enabled) {+ break;+ }+ }+ CFRelease(bar as CFTypeRef);+ found+ }+}++/// The items under a menu bar item or submenu item (through the untitled+/// `AXMenu` container AppKit puts between them).+unsafe fn semantic_items(parent: AXUIElementRef) -> Vec<AXUIElementRef> {+ let mut out = Vec::new();+ for child in copy_children(parent) {+ if copy_string_attr(child, "AXRole").as_deref() == Some("AXMenu") {+ out.extend(copy_children(child));+ CFRelease(child as CFTypeRef);+ } else {+ out.push(child);+ }+ }+ out+}++unsafe fn search(+ parent: AXUIElementRef,+ path: Vec<String>,+ combo: &Combo,+ found: &mut Option<MenuMatch>,+ budget: &mut usize,+ depth: usize,+) {+ for item in semantic_items(parent) {+ if *budget == 0 || found.as_ref().is_some_and(|m| m.enabled) {+ CFRelease(item as CFTypeRef);+ continue;+ }+ *budget -= 1;+ let title = copy_string_attr(item, "AXTitle").unwrap_or_default();+ let cmd_char = copy_string_attr(item, "AXMenuItemCmdChar").unwrap_or_default();+ if !cmd_char.is_empty() {+ let modifiers = copy_number_attr(item, "AXMenuItemCmdModifiers").unwrap_or(0.0) as i64;+ if combo.matches(&cmd_char, modifiers) {+ let enabled = copy_bool_attr(item, "AXEnabled") != Some(false);+ if found.is_none() || enabled {+ let mut item_path = path.clone();+ item_path.push(title.clone());+ *found = Some(MenuMatch {+ path: item_path,+ enabled,+ });+ }+ }+ } else if depth < 2 && !title.is_empty() {+ let mut sub_path = path.clone();+ sub_path.push(title);+ search(item, sub_path, combo, found, budget, depth + 1);+ }+ CFRelease(item as CFTypeRef);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn combo(modifiers: &[&str], key: &str) -> Option<Combo> {+ let modifiers: Vec<String> = modifiers.iter().map(|m| m.to_string()).collect();+ Combo::parse(&modifiers, key)+ }++ #[test]+ fn only_command_combos_with_one_printable_key_are_menu_candidates() {+ assert!(combo(&["cmd"], "s").is_some());+ assert!(combo(&["command", "shift"], "S").is_some());+ assert!(combo(&["cmd"], ",").is_some());+ assert_eq!(combo(&["ctrl"], "a"), None);+ assert_eq!(combo(&["cmd"], "return"), None);+ assert_eq!(combo(&["cmd"], "up"), None);+ assert_eq!(combo(&["cmd", "hyper"], "s"), None);+ }++ #[test]+ fn modifiers_must_match_exactly() {+ let save = combo(&["cmd"], "s").unwrap();+ assert!(save.matches("S", 0));+ assert!(save.matches("s", 0));+ assert!(!save.matches("S", MOD_SHIFT), "Save As is cmd+shift+s");+ assert!(!save.matches("S", MOD_NO_COMMAND));+ assert!(!save.matches("A", 0));+ let save_as = combo(&["cmd", "shift"], "s").unwrap();+ assert!(save_as.matches("S", MOD_SHIFT));+ assert!(!save_as.matches("S", 0));+ let minimize_all = combo(&["cmd", "option"], "m").unwrap();+ assert!(minimize_all.matches("M", MOD_OPTION));+ assert!(!minimize_all.matches("M", MOD_OPTION | MOD_CONTROL));+ }+}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 5c2b457340..234d04b49b 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@@ -13,6 +13,7 @@ mod kill_app;mod launch_app;mod list_apps;mod list_windows;+mod menu_equivalent;mod press_key;mod right_click;mod scroll;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 26f6785580..e16e87ceb4 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@@ -48,7 +48,7 @@ fn def() -> &'static ToolDef {name: "set_value".into(),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 (in the background the user's front window keeps key focus). 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(),+ A Finder file name cell (list or icon view, not being edited) is renamed through Finder's scripting interface with Finder left in the background, and the new name is read back from disk; the value is the full new name with its extension. macOS asks the user once to allow Cua Driver to control Finder. Finder's Get Info `Name` field is refused with `file_name_needs_rename`. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.".into(),input_schema: serde_json::json!({"type": "object","required": ["value"],@@ -130,20 +130,45 @@ impl Tool for SetValueTool {// 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.// Finder's Get Info Name field does the same.+ // In Finder, the file is renamed through Finder's scripting interface+ // instead, with Finder left in the background, and read back from+ // disk.let name_guard = element_guard.clone();- if let Ok(Some(reason)) = tokio::task::spawn_blocking(move || unsafe {+ let name_target = tokio::task::spawn_blocking(move || unsafe {let element = name_guard.as_ptr() as AXUIElementRef;if file_name_cell(element) {- Some(LIST_RENAME_ROUTE)+ let finder =+ crate::apps::bundle_id_for_pid(pid).as_deref() == Some("com.apple.finder");+ match copy_url_attr(element)+ .as_deref()+ .and_then(crate::apple_events::file_url_to_path)+ {+ Some(path) if finder => Some(NameTarget::FinderItem(path)),+ _ => Some(NameTarget::Refuse(LIST_RENAME_ROUTE)),+ }} else if get_info_name_field(pid, element) {- Some(GET_INFO_RENAME_ROUTE)+ Some(NameTarget::Refuse(GET_INFO_RENAME_ROUTE))} else {None}}).await- {- return file_name_needs_rename(pid, window_id, reason);+ .ok()+ .flatten();+ match name_target {+ Some(NameTarget::Refuse(reason)) => {+ return file_name_needs_rename(pid, window_id, reason)+ }+ Some(NameTarget::FinderItem(path)) => {+ let new_name = value.clone();+ let rename_path = path.clone();+ let renamed = tokio::task::spawn_blocking(move || {+ crate::apple_events::finder_rename(&rename_path, &new_name)+ })+ .await;+ return finder_rename_result(pid, window_id, &path, &value, renamed);+ }+ None => {}}let cursor_key = super::cursor_tools::resolve_cursor_key(&args);@@ -288,6 +313,82 @@ fn is_get_info_name_field(&& focused != Some(true)}+/// What a write to a file-name element turns into.+enum NameTarget {+ /// A Finder item at this path: rename it through Finder.+ FinderItem(std::path::PathBuf),+ /// Refuse with this route.+ Refuse(&'static str),+}++/// A rename read back from disk: the new name is listed, the old one gone.+fn rename_record() -> cua_driver_core::action_record::ActionExecutionRecord {+ use cua_driver_core::action_record::{+ ActionEffect, ActionEvidence, ActionExecutionRecord, ActionTransport, ActualDelivery,+ EvidenceKind, RequestedDelivery,+ };+ ActionExecutionRecord::builder(+ ActionEffect::Confirmed,+ ActionTransport::MacosAppleEvent,+ RequestedDelivery::Background,+ )+ .actual_delivery(ActualDelivery::Background)+ .evidence(ActionEvidence {+ kind: EvidenceKind::ValueReadback,+ detail: "The folder on disk lists the new name and not the old one".into(),+ })+ .build()+ .expect("rename record is valid")+}++fn finder_rename_result(+ pid: i32,+ window_id: u32,+ path: &std::path::Path,+ new_name: &str,+ renamed: Result<+ Result<std::path::PathBuf, crate::apple_events::ScriptRefusal>,+ tokio::task::JoinError,+ >,+) -> ToolResult {+ let old_name = path+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_default();+ match renamed {+ Ok(Ok(new_path)) => ToolResult::text(format!(+ "✅ Renamed \"{old_name}\" to \"{new_name}\" through Finder's scripting interface, \+ with Finder left in the background (not activated). Verified on disk: {} exists \+ and the old name is gone. Take a fresh get_window_state before addressing the \+ item again.",+ new_path.display()+ ))+ .with_structured(serde_json::json!({+ "path": "apple_events",+ "verified": true,+ "effect": "confirmed",+ "renamed_from": path.display().to_string(),+ "renamed_to": new_path.display().to_string(),+ }))+ .with_action_record(rename_record()),+ Ok(Err(refusal)) => ToolResult::error(format!(+ "set_value refused ({FILE_NAME_NEEDS_RENAME}): renaming \"{old_name}\" through \+ Finder did not complete ({}: {}). The file keeps its name; nothing else was sent.",+ refusal.code, refusal.reason+ ))+ .with_structured(serde_json::json!({+ "code": FILE_NAME_NEEDS_RENAME,+ "effect": "refused",+ "path": "apple_events",+ "pid": pid,+ "window_id": window_id,+ "reason": refusal.reason,+ "cause": refusal.code,+ })),+ Err(error) => ToolResult::error(format!("set_value rename task failed: {error}")),+ }+}+const LIST_RENAME_ROUTE: &str = "This is a file's name as the list shows it. Writing its AXValue \changes only what the list shows, never the file, so nothing was written. To rename the \file: click this element to select the item, then with Finder frontmost send press_key \@@ -297,8 +398,9 @@ const LIST_RENAME_ROUTE: &str = "This is a file's name as the list shows it. Wriconst GET_INFO_RENAME_ROUTE: &str = "This is the Name & Extension field of Finder's Get Info \window. Writing its AXValue changes only what the field shows, never the file, so nothing \- was written. To rename the file: take a fresh get_window_state of this window and click the \- field's centre in its screenshot pixels (pass its capture_id), then hotkey cmd+a, type_text \+ was written. To rename the file in the background, call set_value with the new name on the \+ file's name cell in a Finder window that lists it. Otherwise take a fresh get_window_state \+ of this window and click the field's centre in its screenshot pixels (pass its capture_id), then hotkey cmd+a, type_text \the full new name with its extension, and press_key return, each with \delivery_mode:\"foreground\" on this window. A changed extension makes Finder ask for \confirmation in a dialog first. Then check the new name in a fresh listing of the folder; \@@ -1049,6 +1151,30 @@ mod tests {assert!(is_file_name_cell(Some("charlie.bin"), url, None));}+ #[test]+ fn a_finder_rename_publishes_a_confirmed_system_api_record() {+ let record = super::rename_record();+ assert!(record.validate().is_ok());+ let path = std::path::Path::new("/tmp/a.txt");+ let ok = super::finder_rename_result(7, 42, path, "b.txt", Ok(Ok("/tmp/b.txt".into())));+ assert_eq!(ok.is_error, None);+ assert!(ok.action_record.is_some());+ let refused = super::finder_rename_result(+ 7,+ 42,+ path,+ "b.txt",+ Ok(Err(crate::apple_events::ScriptRefusal {+ code: "automation_denied",+ reason: "off".into(),+ })),+ );+ assert_eq!(refused.is_error, Some(true));+ let data = refused.structured_content.unwrap();+ assert_eq!(data["code"], "file_name_needs_rename");+ assert_eq!(data["cause"], "automation_denied");+ }+#[test]fn rename_editor_and_ordinary_fields_stay_writable() {let url = Some("file:///Users/me/lab/charlie.bin");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 fd2455e193..41069d7610 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@@ -377,6 +377,7 @@ impl Tool for TypeTextTool {delivery_mode,window_id,keyboard_policy: blocking_policy,+ explicit_target: element_ptr.is_some() || used_pixel_focus,},)})@@ -1097,7 +1098,7 @@ fn classify_target_web_area(/// Whether `pid` is a web browser whose omnibox and pages the foreground/// typing rung must activate fully (see the browser branch of the rung).-fn is_browser_pid(pid: i32) -> bool {+pub(super) fn is_browser_pid(pid: i32) -> bool {let bundle_id = apps::bundle_id_for_pid(pid).unwrap_or_default();crate::browser::browser_js::BrowserJs::supports(&bundle_id) || is_chromium_identity(&bundle_id)}@@ -1267,6 +1268,9 @@ struct KeyboardRoute {delivery_mode: super::DeliveryMode,window_id: Option<u32>,keyboard_policy: BackgroundKeyboardPolicy,+ /// The caller chose where the text goes: an `element_token`, or `x,y`+ /// that pixel-focused a field first.+ explicit_target: bool,}/// Best-effort-background ladder for `type_text`.@@ -1291,6 +1295,7 @@ fn type_text_blocking(delivery_mode,window_id,keyboard_policy,+ explicit_target,} = route;// Original field value before any rung drives read-back verification only.// An unreadable value is not evidence that the field is empty — and for a@@ -1507,6 +1512,26 @@ fn type_text_blocking(}},};+ // Untargeted background text goes to whatever the window has focused.+ // When that is not a text input (a Finder list, say), key events do not+ // type: they drive the view instead (Finder's type-to-select moved the+ // selection to another file, and the next Return renamed the wrong+ // item). Refuse before anything is sent.+ if !explicit_target && window_id.is_some() {+ let accepts_text = ax_target.is_some_and(|(element, _, _)| unsafe {+ focused_accepts_text(element)+ || target_in_web_area(pid, Some((element as usize, None)), window_id)+ });+ if !accepts_text {+ if let Some((element, true, _)) = ax_target {+ unsafe { CFRelease(element as _) };+ }+ return Ok(TypeTextDelivery::Refused(no_focused_text_input_refusal(+ ax_target.is_some(),+ )));+ }+ }+let mut ax_attempt = AxAttempt::NotAttempted;if let Some((element, owns, idx_opt)) = ax_target {let role = unsafe { copy_string_attr(element, "AXRole") }.unwrap_or_default();@@ -1615,6 +1640,49 @@ fn type_text_blocking(}))}+/// Whether a focused element takes typed text: a text role, or any element+/// that exposes a text selection (custom text views do).+///+/// # Safety+/// `element` must be a live `AXUIElementRef`.+unsafe fn focused_accepts_text(element: AXUIElementRef) -> bool {+ let role = copy_string_attr(element, "AXRole").unwrap_or_default();+ is_text_input_role(&role)+ || copy_raw_attr(element, SELECTED_RANGE).is_some_and(|range| {+ CFRelease(range);+ true+ })+}++fn is_text_input_role(role: &str) -> bool {+ matches!(+ role,+ "AXTextField" | "AXTextArea" | "AXComboBox" | "AXSearchField"+ )+}++const NO_FOCUSED_TEXT_INPUT: &str = "no_focused_text_input";++fn no_focused_text_input_refusal(+ something_focused: bool,+) -> cua_driver_core::background_input::BackgroundRefusal {+ let what = if something_focused {+ "the focused element in this window is not a text input"+ } else {+ "no element in this window has keyboard focus"+ };+ cua_driver_core::background_input::BackgroundRefusal {+ code: NO_FOCUSED_TEXT_INPUT,+ reason: format!(+ "{what}, so typed keys would act on the window instead (in Finder they move the \+ selection by type-to-select). Nothing was sent. Pass the field's element_token, or \+ x,y to focus it by pixel first. To rename a file in Finder, use set_value on its \+ name cell."+ ),+ advice: Some("px"),+ }+}+#[cfg(test)]mod tests {#[test]@@ -1674,6 +1742,7 @@ mod tests {delivery_mode: super::super::DeliveryMode::Background,window_id: Some(7),keyboard_policy: BackgroundKeyboardPolicy::SemanticOnly(refusal.clone()),+ explicit_target: false,},);match r {@@ -1682,6 +1751,50 @@ mod tests {}}+ /// Untargeted background text with nothing text-like focused in the+ /// window is refused before any key event (Finder type-to-select).+ #[test]+ fn untargeted_text_without_a_focused_text_input_is_refused() {+ let result = type_text_blocking(+ -1,+ "renamed.txt",+ None,+ 0,+ /*is_terminal_target=*/ false,+ KeyboardRoute {+ delivery_mode: super::super::DeliveryMode::Background,+ window_id: Some(7),+ keyboard_policy: BackgroundKeyboardPolicy::Allowed,+ explicit_target: false,+ },+ )+ .expect("the refusal is a delivery outcome");+ match result {+ TypeTextDelivery::Refused(refusal) => {+ assert_eq!(refusal.code, NO_FOCUSED_TEXT_INPUT);+ assert!(refusal.reason.contains("Nothing was sent"));+ assert_eq!(refusal.advice, Some("px"));+ }+ _ => panic!("expected the no_focused_text_input refusal"),+ }+ }++ #[test]+ fn text_roles_take_typed_text() {+ for role in ["AXTextField", "AXTextArea", "AXComboBox", "AXSearchField"] {+ assert!(is_text_input_role(role), "{role}");+ }+ for role in ["AXOutline", "AXList", "AXRow", "AXWindow", "AXGroup", ""] {+ assert!(!is_text_input_role(role), "{role}");+ }+ assert!(no_focused_text_input_refusal(true)+ .reason+ .starts_with("the focused element in this window is not a text input"));+ assert!(no_focused_text_input_refusal(false)+ .reason+ .starts_with("no element in this window has keyboard focus"));+ }+#[test]fn oversized_synthesis_is_refused_before_the_terminal_event_path() {let text = "x".repeat(6_500);@@ -1695,6 +1808,7 @@ mod tests {delivery_mode: super::super::DeliveryMode::Background,window_id: None,keyboard_policy: BackgroundKeyboardPolicy::Allowed,+ explicit_target: false,},).expect("preflight refusal must not attempt the invalid pid");diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.jsonindex 3b8f52415e..9a3eaf2e0a 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json@@ -1039,7 +1039,7 @@"read_only": false},{- "description": "Press a key combination — e.g. `[\"cmd\", \"c\"]` for Copy, `[\"cmd\", \"shift\", \"4\"]` for screenshot selection. Follows the same `delivery_mode` ladder as click/type_text — it does NOT raise the window by default:\n• `background` (default): post the combo to the target pid WITHOUT fronting or raising it — uses the macOS 14+ auth-message envelope so Chromium/Electron accept it as trusted live input. With an AX target, focus that exact element first. No top-level focus steal. `window_id` here only targets the combo; it does not raise.\n• `foreground`: briefly front the window (NSMenu path, < 1 ms via SLPSSetFrontProcessWithOptions) so native menu key-equivalents (Cmd+Z, Cmd+W) dispatch, then restore the prior frontmost — the explicit escalation for menu-bar shortcuts on non-Chromium apps that ignore a background combo. With an AX target or x,y, the focused field receives the chord through the foreground HID queue (needed by native Chromium fields such as the omnibox). Requires window_id.\n\nA combo is never driver-verifiable (no read-back) → effect:\"unverifiable\"; confirm via screenshot. NOTE: a keyboard combo does NOT focus a text field — to type into a backgrounded Electron input, establish real renderer focus with a PIXEL click first, then `type_text`. If an app only accepts paste, call `clipboard_write`, then `clipboard_read` and verify its types (and text when applicable) before selecting or replacing editor content; only then send Cmd+V.\n\nRecognized modifiers: cmd/command, shift, option/alt, ctrl/control, fn. Non-modifier keys use the same vocabulary as `press_key`. Order: modifiers first, one non-modifier last.",+ "description": "Press a key combination — e.g. `[\"cmd\", \"c\"]` for Copy, `[\"cmd\", \"shift\", \"4\"]` for screenshot selection. Follows the same `delivery_mode` ladder as click/type_text — it does NOT raise the window by default:\n• `background` (default): post the combo to the target pid WITHOUT fronting or raising it — uses the macOS 14+ auth-message envelope so Chromium/Electron accept it as trusted live input. With an AX target, focus that exact element first. No top-level focus steal. `window_id` here only targets the combo; it does not raise. Background key events never reach a native app's menus, so when the combo is a menu item's key equivalent (cmd+s, cmd+w, ...) and the app is not in front, that menu item runs through accessibility instead (a disabled Save is saved through the app's scripting interface and verified on disk); a menu item macOS keeps disabled in the background is refused with `background_unavailable`, and no keys are sent.\n• `foreground`: briefly front the window (NSMenu path, < 1 ms via SLPSSetFrontProcessWithOptions) so native menu key-equivalents (Cmd+Z, Cmd+W) dispatch, then restore the prior frontmost — the explicit escalation for menu-bar shortcuts on non-Chromium apps that ignore a background combo. With an AX target or x,y, the focused field receives the chord through the foreground HID queue (needed by native Chromium fields such as the omnibox). Requires window_id.\n\nA combo is never driver-verifiable (no read-back) → effect:\"unverifiable\"; confirm via screenshot. NOTE: a keyboard combo does NOT focus a text field — to type into a backgrounded Electron input, establish real renderer focus with a PIXEL click first, then `type_text`. If an app only accepts paste, call `clipboard_write`, then `clipboard_read` and verify its types (and text when applicable) before selecting or replacing editor content; only then send Cmd+V.\n\nRecognized modifiers: cmd/command, shift, option/alt, ctrl/control, fn. Non-modifier keys use the same vocabulary as `press_key`. Order: modifiers first, one non-modifier last.","destructive": true,"idempotent": false,"input_schema": {@@ -1137,7 +1137,7 @@"read_only": false},{- "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 (in the background the user's front window keeps key focus). 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.",+ "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 (in the background the user's front window keeps key focus). An unknown value lists the options. Any other element: writes AXValue (sliders, steppers, date pickers, native text fields).\n\nA Finder file name cell (list or icon view, not being edited) is renamed through Finder's scripting interface with Finder left in the background, and the new name is read back from disk; the value is the full new name with its extension. macOS asks the user once to allow Cua Driver to control Finder. Finder's Get Info `Name` field is refused with `file_name_needs_rename`. For free-form text in web inputs use `type_text_chars`: WebKit ignores AXValue writes.","destructive": true,"idempotent": true,"input_schema": {