Skip to content

armgit / cua

Public Imported from GitHub
0

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

fix(cua-driver): mark a document edited after an accessibility text write on macOS (Bench v2 DS-07) (#4989)

Francesco Bonacciadadbe2f53b9
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.rs
new file mode 100644
index 0000000000..674647e57c
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-macos/src/document_edit.rs
@@ -0,0 +1,177 @@
+//! Keep a document's edited state in step with accessibility text writes.
+//!
+//! An `AXValue` write, or an `AXSelectedText` insert, changes an `NSTextView`'s
+//! text without going through its edit model: no undo entry is registered and
+//! the `NSDocument` is not marked edited. TextEdit then never autosaves the
+//! change, and closing or saving keeps the old content on disk (Bench v2
+//! DS-07). Key events do go through the edit model.
+//!
+//! After an AX write that changed the text of a document window (one with an
+//! `AXDocument` URL), this sends one net-zero edit as key events (a space and
+//! a backspace), which registers the change with the document without
+//! changing its content, and checks that the text did not move. There is no
+//! accessibility readback of the edited state: `AXEdited` on the close button
+//! stays false for autosave-in-place documents even after a typed edit (VM
+//! check, TextEdit, 11 Oct 2026); TextEdit's autosave writing the new text is
+//! the evidence.
+
+use std::time::Duration;
+
+use crate::ax::bindings::{
+ copy_element_attr, copy_string_attr, AXUIElementRef, AXUIElementSetAttributeValue,
+};
+
+/// What the document's edited mark showed after an AX text write.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum DocumentEdited {
+ /// The element is not in a document window, so there is nothing to save.
+ NotADocument,
+ /// The driver sent a net-zero key edit and the text did not move.
+ Marked,
+ /// The key edit could not be sent to this window, or the text moved. A
+ /// save may keep the old content.
+ NotMarked,
+}
+
+impl DocumentEdited {
+ /// A sentence for the tool result, or nothing when there is nothing to say.
+ pub fn note(self) -> &'static str {
+ match self {
+ DocumentEdited::NotADocument => "",
+ DocumentEdited::Marked => {
+ " A net-zero key edit (space, backspace) was sent so the document registers the \
+ change and saves it; an accessibility write alone does not."
+ }
+ DocumentEdited::NotMarked => {
+ " Warning: the document is not marked edited, so saving or closing it may keep \
+ the old content. Type the text with key events instead (click the field, then \
+ type_text), or edit it in the foreground."
+ }
+ }
+ }
+
+ /// The structured value, `None` when the element is not in a document.
+ pub fn structured(self) -> Option<bool> {
+ match self {
+ DocumentEdited::NotADocument => None,
+ DocumentEdited::NotMarked => Some(false),
+ DocumentEdited::Marked => Some(true),
+ }
+ }
+}
+
+#[link(name = "ApplicationServices", kind = "framework")]
+extern "C" {
+ fn AXValueCreate(the_type: u32, value_ptr: *const std::ffi::c_void) -> *const std::ffi::c_void;
+}
+const AX_VALUE_CF_RANGE: u32 = 4;
+
+#[repr(C)]
+struct CfRange {
+ location: isize,
+ length: isize,
+}
+
+/// Whether `element` sits in a document window (its window has an
+/// `AXDocument` URL).
+///
+/// # Safety
+/// `element` must be a live `AXUIElementRef`.
+unsafe fn in_document_window(element: AXUIElementRef) -> bool {
+ let Some(window) = copy_element_attr(element, "AXWindow") else {
+ return false;
+ };
+ let document = copy_string_attr(window, "AXDocument");
+ core_foundation::base::CFRelease(window as _);
+ document.is_some_and(|url| !url.is_empty())
+}
+
+/// Whether the app's key window (its `AXFocusedWindow`) is the element's
+/// window, so pid-routed key events reach this text and not another window.
+///
+/// # Safety
+/// `element` must be a live `AXUIElementRef`.
+unsafe fn keys_reach_element_window(pid: i32, element: AXUIElementRef) -> bool {
+ let Some(window) = copy_element_attr(element, "AXWindow") else {
+ return false;
+ };
+ let own = crate::ax::bindings::ax_get_window_id(window);
+ core_foundation::base::CFRelease(window as _);
+ own.is_some() && crate::ax::bindings::focused_window_id_of_pid(pid) == own
+}
+
+/// After an AX text write on `element` (in `pid`) that changed its value, make
+/// sure its document is marked edited. See the module docs.
+///
+/// # Safety
+/// `element` must be a live `AXUIElementRef` for the duration of the call.
+/// `caret_to_end` puts the caret at the end first (after replacing the whole
+/// value); otherwise the edit happens at the caret, which an insert leaves
+/// collapsed just after the inserted text.
+pub unsafe fn ensure_marked_after_ax_write(
+ pid: i32,
+ element: AXUIElementRef,
+ caret_to_end: bool,
+) -> DocumentEdited {
+ if !in_document_window(element) {
+ return DocumentEdited::NotADocument;
+ }
+ if !keys_reach_element_window(pid, element) {
+ return DocumentEdited::NotMarked;
+ }
+ if caret_to_end {
+ caret_to_end_of(element);
+ }
+ let _ = crate::input::ax_actions::focus_element(element as usize);
+ let before = copy_string_attr(element, "AXValue");
+ if crate::input::keyboard::press_key(pid, "space", &[]).is_err()
+ || crate::input::keyboard::press_key(pid, "delete", &[]).is_err()
+ {
+ return DocumentEdited::NotMarked;
+ }
+ // Let the two keys land, then check they cancelled out.
+ std::thread::sleep(Duration::from_millis(150));
+ if copy_string_attr(element, "AXValue") == before {
+ DocumentEdited::Marked
+ } else {
+ DocumentEdited::NotMarked
+ }
+}
+
+/// Collapse the selection to the end of the text.
+///
+/// # Safety
+/// `element` must be a live `AXUIElementRef`.
+unsafe fn caret_to_end_of(element: AXUIElementRef) {
+ let len = copy_string_attr(element, "AXValue")
+ .map(|v| v.encode_utf16().count())
+ .unwrap_or(0);
+ let range = CfRange {
+ location: len as isize,
+ length: 0,
+ };
+ let value = AXValueCreate(AX_VALUE_CF_RANGE, &range as *const CfRange as *const _);
+ if !value.is_null() {
+ use core_foundation::{base::TCFType, string::CFString};
+ let attr = CFString::new("AXSelectedTextRange");
+ let _ = AXUIElementSetAttributeValue(element, attr.as_concrete_TypeRef(), value as _);
+ core_foundation::base::CFRelease(value as _);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::DocumentEdited;
+
+ #[test]
+ fn only_a_document_left_unedited_gets_a_warning() {
+ assert_eq!(DocumentEdited::NotADocument.note(), "");
+ assert!(DocumentEdited::Marked.note().contains("net-zero key edit"));
+ assert!(DocumentEdited::NotMarked
+ .note()
+ .contains("may keep the old content"));
+ assert_eq!(DocumentEdited::NotADocument.structured(), None);
+ assert_eq!(DocumentEdited::Marked.structured(), Some(true));
+ assert_eq!(DocumentEdited::NotMarked.structured(), Some(false));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
index 5d44298051..37ff1c41ce 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
@@ -23,6 +23,8 @@ pub mod browser;
pub mod capture;
#[cfg(target_os = "macos")]
pub mod cursor;
+
+pub mod document_edit;
#[cfg(target_os = "macos")]
pub mod focus_guard;
#[cfg(target_os = "macos")]
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.rs
index e3a9e002c6..03e10e7eb2 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
@@ -223,6 +223,9 @@ impl Tool for SetValueTool {
"verified": verified,
"effect": if verified { "confirmed" } else { "unverifiable" },
});
+ if let Some(edited) = outcome.document_edited {
+ structured["document_key_edit_sent"] = serde_json::json!(edited);
+ }
if ax_echo_surface {
structured["escalation"] = serde_json::json!({
"recommended": "px",
@@ -335,6 +338,9 @@ struct SetValueOutcome {
/// The read-back still showed the old value after a short settle: the app
/// took the accessibility write but did not apply it.
not_applied: bool,
+ /// The document's edited mark after the write; `None` outside a
+ /// document or when the value did not move.
+ document_edited: Option<bool>,
}
fn apply_surface_trust(outcome: &mut SetValueOutcome, ax_echo_surface: bool) {
@@ -375,6 +381,7 @@ fn set_value_blocking(
verified: None,
changed: None,
not_applied: false,
+ document_edited: None,
}
})
} else {
@@ -432,13 +439,24 @@ fn set_value_blocking(
(Some(false), _) => " Read-back did not confirm the value; verify via screenshot.",
(None, _) => " Value is not readable through AX; could not confirm.",
};
+ // An AX write bypasses NSTextView's edit model, so a document is
+ // not marked edited and would never save the new text (DS-07).
+ let document = if changed == Some(true) {
+ unsafe { crate::document_edit::ensure_marked_after_ax_write(pid, element, true) }
+ } else {
+ crate::document_edit::DocumentEdited::NotADocument
+ };
Ok(SetValueOutcome {
- detail: format!("✅ Set AXValue on [{element_index}] {role}.{suffix}"),
+ detail: format!(
+ "✅ Set AXValue on [{element_index}] {role}.{suffix}{}",
+ document.note()
+ ),
verified,
changed,
// A secure text field reads back empty or masked, so its
// read-back proves nothing either way.
not_applied: !secure && write_not_applied(verified, changed),
+ document_edited: document.structured(),
})
} else if let Some(target) = numeric_target {
// Both direct writes failed for a numeric target — fall back to
@@ -454,6 +472,7 @@ fn set_value_blocking(
verified,
changed,
not_applied: false,
+ document_edited: None,
})
} else {
anyhow::bail!("AXUIElementSetAttributeValue(AXValue) failed with error {err}")
@@ -1225,6 +1244,7 @@ mod tests {
verified: Some(true),
changed: Some(true),
not_applied: false,
+ document_edited: None,
};
apply_surface_trust(&mut outcome, true);
assert_eq!(outcome.verified, Some(false));
@@ -1239,6 +1259,7 @@ mod tests {
verified: Some(true),
changed: Some(true),
not_applied: false,
+ document_edited: None,
};
apply_surface_trust(&mut outcome, false);
assert_eq!(outcome.verified, Some(true));
@@ -1253,6 +1274,7 @@ mod tests {
verified: Some(false),
changed: Some(false),
not_applied: false,
+ document_edited: None,
};
apply_verification_label(&mut outcome);
assert_eq!(
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.rs
index 3df1b9e6d6..fd2455e193 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
@@ -1528,6 +1528,13 @@ fn type_text_blocking(
// unsafe even though no synthesis has run yet.
let unchanged_web_readback = ax_progress == Some(TypedProgress::Unchanged)
&& target_in_web_area(pid, Some((element as usize, idx_opt)), window_id);
+ // An AX insert bypasses NSTextView's edit model, so a document is
+ // not marked edited and would never save the new text (DS-07).
+ let document = if ax_progress == Some(TypedProgress::Complete) {
+ unsafe { crate::document_edit::ensure_marked_after_ax_write(pid, element, false) }
+ } else {
+ crate::document_edit::DocumentEdited::NotADocument
+ };
if owns {
unsafe {
CFRelease(element as _);
@@ -1536,7 +1543,10 @@ fn type_text_blocking(
if ax_progress == Some(TypedProgress::Complete) {
let idx_str = idx_opt.map(|i| format!(" [{i}]")).unwrap_or_default();
return Ok(TypeTextDelivery::Typed(TypeTextOutcome {
- detail: format!(" into{idx_str} {role} \"{title}\""),
+ detail: format!(
+ " into{idx_str} {role} \"{title}\"{}",
+ document.note().trim_end_matches('.')
+ ),
path: PATH_AX,
verified: true,
delivered_chars: Some(text.chars().count()),