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): expose legacy macOS page fallback (#5590)

injaneity6e1e070ab08b
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/pointer-cursor-and-browser.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/pointer-cursor-and-browser.mdx
index 39775c6ed7..a16aa917f0 100644
--- a/docs/content/docs/cua-driver/reference/mcp-tools/pointer-cursor-and-browser.mdx
+++ b/docs/content/docs/cua-driver/reference/mcp-tools/pointer-cursor-and-browser.mdx
@@ -486,8 +486,8 @@ Legacy browser compatibility tool. Prefer get_browser_state and the typed browse
Actions:
- execute_javascript: Run JS and return the result.
-- get_text: Extract visible text from the page.
-- query_dom: Find elements matching a CSS selector.
+- get_text: Extract visible text from the page. On macOS, structuredContent.source identifies javascript, cdp, or ax_fallback; a successful AX fallback preserves the triggering error and truncation state in structuredContent.
+- query_dom: Find elements matching a CSS selector, with the same macOS fallback metadata contract as get_text.
- click_element: Click a CSS-selected element AND animate the agent cursor to its on-screen center first (so the user sees what the agent is doing). Prefer over `execute_javascript('el.click()')` whenever you want visible cursor feedback.
- insert_text: Insert `text` at whatever currently holds DOM focus in one native operation (CDP Input.insertText); no synthesized key events, but more durable than a one-shot execute_javascript write since rich-text editors already have to treat it like an IME commit. Try this before type_keystrokes on a contenteditable that discarded an execute_javascript write. Click/focus the target field first.
- type_keystrokes: Type `text` via real per-character keystroke events into whatever currently holds DOM focus. Slower than insert_text but the most durable rung: use it when insert_text also gets discarded, or the editor's own keydown/keyup handlers need to see real keys. Click/focus the target field first.
diff --git a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
index 85166d4d40..7c7ef18006 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
@@ -521,6 +521,14 @@ operator can enable the temporary compatibility path with
Driver after changing the flag. It does not add typed endpoint ownership,
capabilities, or existing-profile consent.
+On macOS, legacy `page.get_text` and `page.query_dom` keep their original text
+payload but also report read provenance in `structuredContent.source`:
+`javascript`, `cdp`, or `ax_fallback`. When JavaScript or CDP fails and the AX
+fallback succeeds, `structuredContent.fallback_error` preserves the triggering
+error and `structuredContent.truncated` reports whether the bounded AX walk was
+cut short. A direct WKWebView/Tauri AX read has no `fallback_error` because no
+JavaScript or CDP route was attempted.
+
## Support boundaries
| Surface | Typed state and mutation | Important boundary |
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs
index dc0cb0a6f7..3bbdc8e9d0 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs
@@ -64,6 +64,8 @@ pub struct ClickElementResult {
pub message: String,
}
+pub type PageReadResult = ToolResult;
+
/// Platform-specific backend for the `page` tool.
///
/// All methods take `(pid, window_id)` for consistency across actions.
@@ -72,18 +74,18 @@ pub struct ClickElementResult {
#[async_trait]
pub trait PageBackend: Send + Sync {
/// Returns the visible text of the page (rough analog of
- /// `document.body.innerText`).
- async fn get_text(&self, pid: i32, window_id: u64) -> anyhow::Result<String>;
+ /// `document.body.innerText`) plus optional backend provenance.
+ async fn get_text(&self, pid: i32, window_id: u64) -> anyhow::Result<PageReadResult>;
- /// Find elements matching `css_selector` and return a formatted-text
- /// response (same human-readable shape macOS already emits).
+ /// Find elements matching `css_selector` and return the legacy formatted
+ /// text response plus optional backend provenance.
async fn query_dom(
&self,
pid: i32,
window_id: u64,
css_selector: &str,
attributes: &[String],
- ) -> anyhow::Result<String>;
+ ) -> anyhow::Result<PageReadResult>;
/// Evaluate `javascript` against the page and return the stringified
/// result. Backends without a JS path should return an actionable error.
@@ -266,8 +268,11 @@ fn def() -> &'static ToolDef {
--remote-debugging-port is set), and WKWebView/Tauri/AT-SPI fallbacks.\n\n\
Actions:\n\
- execute_javascript: Run JS and return the result.\n\
- - get_text: Extract visible text from the page.\n\
- - query_dom: Find elements matching a CSS selector.\n\
+ - get_text: Extract visible text from the page. On macOS, structuredContent.source \
+ identifies javascript, cdp, or ax_fallback; a successful AX fallback preserves \
+ the triggering error and truncation state in structuredContent.\n\
+ - query_dom: Find elements matching a CSS selector, with the same macOS fallback \
+ metadata contract as get_text.\n\
- click_element: Click a CSS-selected element AND animate the agent cursor \
to its on-screen center first (so the user sees what the agent is doing). \
Prefer over `execute_javascript('el.click()')` whenever you want visible \
@@ -459,7 +464,7 @@ impl Tool for PageTool {
}
"get_text" => match self.backend.get_text(pid, window_id).await {
- Ok(text) => ToolResult::text(text),
+ Ok(result) => result,
Err(e) => ToolResult::error(format!("Page text extraction failed: {e}")),
},
@@ -550,7 +555,7 @@ impl Tool for PageTool {
.query_dom(pid, window_id, &selector, &attributes)
.await
{
- Ok(text) => ToolResult::text(text),
+ Ok(result) => result,
Err(e) => ToolResult::error(format!("DOM query failed: {e}")),
}
}
@@ -588,8 +593,8 @@ mod tests {
#[async_trait]
impl PageBackend for RecordingBackend {
- async fn get_text(&self, _pid: i32, _window_id: u64) -> anyhow::Result<String> {
- Ok(String::new())
+ async fn get_text(&self, _pid: i32, _window_id: u64) -> anyhow::Result<PageReadResult> {
+ Ok(PageReadResult::text(String::new()))
}
async fn query_dom(
@@ -598,8 +603,8 @@ mod tests {
_window_id: u64,
_css_selector: &str,
_attributes: &[String],
- ) -> anyhow::Result<String> {
- Ok(String::new())
+ ) -> anyhow::Result<PageReadResult> {
+ Ok(PageReadResult::text(String::new()))
}
async fn execute_javascript(
@@ -630,6 +635,65 @@ mod tests {
}
}
+ struct ProvenanceBackend;
+
+ #[async_trait]
+ impl PageBackend for ProvenanceBackend {
+ async fn get_text(&self, _pid: i32, _window_id: u64) -> anyhow::Result<PageReadResult> {
+ Ok(
+ ToolResult::text("legacy payload".to_owned()).with_structured(serde_json::json!({
+ "source": "ax_fallback",
+ "fallback_error": "JavaScript from Apple Events is disabled",
+ "truncated": true
+ })),
+ )
+ }
+
+ async fn query_dom(
+ &self,
+ _pid: i32,
+ _window_id: u64,
+ _css_selector: &str,
+ _attributes: &[String],
+ ) -> anyhow::Result<PageReadResult> {
+ Ok(PageReadResult::text(String::new()))
+ }
+
+ async fn execute_javascript(
+ &self,
+ _pid: i32,
+ _window_id: u64,
+ _javascript: &str,
+ ) -> anyhow::Result<String> {
+ anyhow::bail!("unused")
+ }
+ }
+
+ #[tokio::test]
+ async fn read_preserves_text_and_attaches_backend_provenance() {
+ let tool = PageTool::new(Arc::new(ProvenanceBackend));
+ let result = tool
+ .invoke(serde_json::json!({
+ "pid": 42,
+ "window_id": 7,
+ "action": "get_text"
+ }))
+ .await;
+
+ assert!(matches!(
+ &result.content[0],
+ crate::protocol::Content::Text { text, .. } if text == "legacy payload"
+ ));
+ assert_eq!(
+ result.structured_content,
+ Some(serde_json::json!({
+ "source": "ax_fallback",
+ "fallback_error": "JavaScript from Apple Events is disabled",
+ "truncated": true
+ }))
+ );
+ }
+
#[tokio::test]
async fn execute_javascript_forwards_explicit_page_target() {
let backend = Arc::new(RecordingBackend::default());
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index 4f254a1c38..084ddcee47 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -2498,6 +2498,57 @@ mod daemon_compatibility_tests {
}
}
+fn call_text<'a>(
+ tool: &str,
+ args: Option<&serde_json::Value>,
+ result: &'a serde_json::Value,
+ printed: bool,
+) -> Vec<&'a str> {
+ let page_read = tool == "page"
+ && matches!(
+ args.and_then(|a| a["action"].as_str()),
+ Some("get_text" | "query_dom")
+ );
+ if printed && !page_read {
+ return Vec::new();
+ }
+ result["content"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter(|item| item["type"] == "text")
+ .filter_map(|item| item["text"].as_str())
+ .collect()
+}
+
+#[cfg(test)]
+mod call_tests {
+ use super::call_text;
+
+ #[test]
+ fn call_page_read_preserves_text_with_structured_content() {
+ let result = serde_json::json!({
+ "content": [{"type": "text", "text": "Page body"}],
+ "structuredContent": {"source": "ax"}
+ });
+ for action in ["get_text", "query_dom"] {
+ let args = serde_json::json!({"action": action});
+ assert_eq!(
+ call_text("page", Some(&args), &result, true),
+ vec!["Page body"]
+ );
+ }
+ assert!(call_text("other", None, &result, true).is_empty());
+ assert!(call_text(
+ "page",
+ Some(&serde_json::json!({"action": "click"})),
+ &result,
+ true
+ )
+ .is_empty());
+ }
+}
+
pub fn run_call(
tool: &str,
json_args: Option<serde_json::Value>,
@@ -2639,19 +2690,8 @@ pub fn run_call(
println!("{pretty}");
printed = true;
}
- if !printed {
- if let Some(content) = result.get("content").and_then(|v| v.as_array())
- {
- for item in content {
- if item.get("type").and_then(|v| v.as_str()) == Some("text") {
- if let Some(text) =
- item.get("text").and_then(|v| v.as_str())
- {
- println!("{text}");
- }
- }
- }
- }
+ for text in call_text(tool, json_args.as_ref(), &result, printed) {
+ println!("{text}");
}
if is_error {
process::exit(1);
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/page.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/page.rs
index 21176f6e64..77cd58aabc 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/page.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/page.rs
@@ -6,7 +6,7 @@
//! `--remote-debugging-port=N` for that to succeed.
use async_trait::async_trait;
-use cua_driver_core::page::PageBackend;
+use cua_driver_core::page::{PageBackend, PageReadResult};
pub struct LinuxPageBackend;
@@ -24,13 +24,15 @@ impl Default for LinuxPageBackend {
#[async_trait]
impl PageBackend for LinuxPageBackend {
- async fn get_text(&self, pid: i32, window_id: u64) -> anyhow::Result<String> {
+ async fn get_text(&self, pid: i32, window_id: u64) -> anyhow::Result<PageReadResult> {
let pid_u = pid as u32;
let xid = window_id;
let result = tokio::task::spawn_blocking(move || crate::atspi::walk_tree(pid_u, xid, None))
.await
.map_err(|e| anyhow::anyhow!("AT-SPI walk task failed: {e}"))?;
- Ok(extract_text_from_markdown(&result.tree_markdown))
+ Ok(PageReadResult::text(extract_text_from_markdown(
+ &result.tree_markdown,
+ )))
}
async fn query_dom(
@@ -39,7 +41,7 @@ impl PageBackend for LinuxPageBackend {
window_id: u64,
css_selector: &str,
_attributes: &[String],
- ) -> anyhow::Result<String> {
+ ) -> anyhow::Result<PageReadResult> {
let pid_u = pid as u32;
let xid = window_id;
let selector = css_selector.to_owned();
@@ -95,11 +97,12 @@ impl PageBackend for LinuxPageBackend {
})
.collect();
- if lines.is_empty() {
- Ok("No elements found.".to_owned())
+ let content = if lines.is_empty() {
+ "No elements found.".to_owned()
} else {
- Ok(lines.join("\n"))
- }
+ lines.join("\n")
+ };
+ Ok(PageReadResult::text(content))
}
async fn execute_javascript(
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs
index 681c636058..e8dd44ad09 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs
@@ -140,6 +140,8 @@ pub struct TreeWalkResult {
pub nodes: Vec<AXNode>,
/// True when the walk was cut short by its node or time budget.
pub truncated: bool,
+ /// True when nodes past `max_depth` were omitted, independently of budget `truncated`.
+ pub depth_truncated: bool,
/// Why and where the walk stopped (see [`cua_driver_core::walk_budget`]).
pub walk: WalkOutcome,
/// Whether the requested `window_id` actually resolved to an AX surface,
@@ -241,6 +243,7 @@ fn walk_tree_with_web_content(
let mut nodes: Vec<AXNode> = Vec::new();
let mut lines: Vec<(usize, String)> = Vec::new(); // (depth, line)
let mut index_counter = 0usize;
+ let mut depth_truncated = false;
let mut window_scope: Option<WindowScope> = None;
unsafe {
@@ -250,6 +253,7 @@ fn walk_tree_with_web_content(
tree_markdown: String::new(),
nodes,
truncated: false,
+ depth_truncated: false,
walk: budget.outcome(),
// No application AX element at all, so a requested window
// certainly did not resolve.
@@ -322,6 +326,7 @@ fn walk_tree_with_web_content(
&mut lines,
&mut index_counter,
&mut budget,
+ &mut depth_truncated,
max_depth,
include_web_content,
);
@@ -351,6 +356,7 @@ fn walk_tree_with_web_content(
tree_markdown,
nodes,
truncated: walk.truncated(),
+ depth_truncated,
walk,
window_scope,
}
@@ -438,10 +444,12 @@ unsafe fn walk_element(
lines: &mut Vec<(usize, String)>,
counter: &mut usize,
budget: &mut WalkBudget,
+ depth_truncated: &mut bool,
max_depth: usize,
include_web_content: bool,
) {
if depth > max_depth {
+ *depth_truncated = true;
return;
}
// Node and time budget: a refused node is counted as discovered but not
@@ -477,6 +485,7 @@ unsafe fn walk_element(
lines,
counter,
budget,
+ depth_truncated,
max_depth,
include_web_content,
);
@@ -544,6 +553,7 @@ unsafe fn walk_element(
lines,
counter,
budget,
+ depth_truncated,
max_depth,
include_web_content,
);
@@ -680,6 +690,7 @@ unsafe fn walk_element(
lines,
counter,
budget,
+ depth_truncated,
max_depth,
include_web_content,
);
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs
index a35e7c0864..5ea5145a9e 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs
@@ -635,6 +635,7 @@ mod tests {
nodes: vec![button],
tree_markdown: String::new(),
truncated: false,
+ depth_truncated: false,
walk: budget.outcome(),
window_scope: None,
})?;
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs
index 3fdda252d9..d6a0a78223 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs
@@ -2054,6 +2054,7 @@ mod tests {
tree_markdown: String::new(),
nodes,
truncated: false,
+ depth_truncated: false,
walk: cua_driver_core::walk_budget::WalkBudget::nodes_only(0).outcome(),
window_scope: Some(crate::ax::WindowScope::Matched),
}
@@ -2386,6 +2387,7 @@ mod tests {
tree_markdown: String::new(),
nodes: Vec::new(),
truncated: true,
+ depth_truncated: false,
walk: cua_driver_core::walk_budget::WalkOutcome::timed_out(
1000,
std::time::Duration::from_millis(1000),
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/page.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/page.rs
index 4fe5804934..a725ba5791 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/page.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/page.rs
@@ -10,8 +10,8 @@
//! `cua_driver_core::page` — this file only implements the backend.
use async_trait::async_trait;
-use cua_driver_core::page::{ClickElementResult, PageBackend};
-use std::sync::Arc;
+use cua_driver_core::page::{ClickElementResult, PageBackend, PageReadResult};
+use std::{future::Future, sync::Arc};
use super::ToolState;
use crate::browser::{is_wk_web_view_app, AXPageReader, BrowserJs, CdpClient, ElectronJs};
@@ -52,32 +52,17 @@ impl MacOsPageBackend {
#[async_trait]
impl PageBackend for MacOsPageBackend {
- async fn get_text(&self, pid: i32, window_id: u64) -> anyhow::Result<String> {
+ async fn get_text(&self, pid: i32, window_id: u64) -> anyhow::Result<PageReadResult> {
let bundle_id = Self::bundle_id_for(pid).await;
-
- let use_ax_fallback = !BrowserJs::supports(&bundle_id)
- && tokio::task::spawn_blocking(move || is_wk_web_view_app(pid))
- .await
- .unwrap_or(false);
-
- if use_ax_fallback {
- return ax_text_fallback(pid, window_id, false).await;
- }
-
- // Try JS path first; on error, use a CDP session the driver already
- // holds, then the window's web area.
- let js = "document.body.innerText";
- match execute_js(js, &bundle_id, pid, window_id).await {
- Ok(result) => Ok(result),
- Err(error) => {
- if let Some(result) = self.attached_cdp_evaluate(pid, js).await {
- return Ok(result);
- }
- ax_text_fallback(pid, window_id, BrowserJs::supports(&bundle_id))
- .await
- .map_err(|ax| anyhow::anyhow!("{ax} (JavaScript read failed first: {error})"))
- }
- }
+ read_page(
+ self,
+ &bundle_id,
+ pid,
+ window_id,
+ "document.body.innerText",
+ || ax_text_fallback(pid, window_id, BrowserJs::supports(&bundle_id)),
+ )
+ .await
}
async fn query_dom(
@@ -86,37 +71,18 @@ impl PageBackend for MacOsPageBackend {
window_id: u64,
css_selector: &str,
attributes: &[String],
- ) -> anyhow::Result<String> {
+ ) -> anyhow::Result<PageReadResult> {
let bundle_id = Self::bundle_id_for(pid).await;
-
- let use_ax_fallback = !BrowserJs::supports(&bundle_id)
- && tokio::task::spawn_blocking(move || is_wk_web_view_app(pid))
- .await
- .unwrap_or(false);
-
- if use_ax_fallback {
- let results = ax_query_fallback(pid, window_id, css_selector, false).await?;
- return Ok(format_ax_elements(&results));
- }
-
let js = build_query_selector_js(css_selector, attributes);
- match execute_js(&js, &bundle_id, pid, window_id).await {
- Ok(result) => Ok(result),
- Err(error) => {
- if let Some(result) = self.attached_cdp_evaluate(pid, &js).await {
- return Ok(result);
- }
- let results = ax_query_fallback(
- pid,
- window_id,
- css_selector,
- BrowserJs::supports(&bundle_id),
- )
- .await
- .map_err(|ax| anyhow::anyhow!("{ax} (JavaScript read failed first: {error})"))?;
- Ok(format_ax_elements(&results))
- }
- }
+ read_page(self, &bundle_id, pid, window_id, &js, || {
+ ax_query_fallback(
+ pid,
+ window_id,
+ css_selector,
+ BrowserJs::supports(&bundle_id),
+ )
+ })
+ .await
}
async fn execute_javascript(
@@ -354,29 +320,102 @@ fn page_rows(tree_markdown: String, require_web_area: bool) -> anyhow::Result<St
}
}
-/// Extract page text via the AX tree.
+async fn read_page<F, A>(
+ backend: &MacOsPageBackend,
+ bundle_id: &str,
+ pid: i32,
+ window_id: u64,
+ javascript: &str,
+ ax_fallback: F,
+) -> anyhow::Result<PageReadResult>
+where
+ F: FnOnce() -> A,
+ A: Future<Output = anyhow::Result<(String, bool)>>,
+{
+ let use_ax = !BrowserJs::supports(bundle_id)
+ && tokio::task::spawn_blocking(move || is_wk_web_view_app(pid))
+ .await
+ .unwrap_or(false);
+ let mut source = if BrowserJs::supports(bundle_id) {
+ "javascript"
+ } else {
+ "cdp"
+ };
+ let primary = if use_ax {
+ None
+ } else {
+ Some(execute_js(javascript, bundle_id, pid, window_id).await)
+ };
+ let mut error = None;
+ let content = match primary {
+ Some(Ok(content)) => Some(content),
+ Some(Err(failure)) => {
+ error = Some(failure.to_string());
+ source = "cdp";
+ backend.attached_cdp_evaluate(pid, javascript).await
+ }
+ None => None,
+ };
+ let fallback = if content.is_none() {
+ ax_fallback().await
+ } else {
+ Ok((String::new(), false))
+ };
+ finish_page_read(source, content, error, fallback)
+}
+
+fn finish_page_read(
+ mut source: &str,
+ content: Option<String>,
+ error: Option<String>,
+ fallback: anyhow::Result<(String, bool)>,
+) -> anyhow::Result<PageReadResult> {
+ let (content, truncated) = match content {
+ Some(content) => (content, None),
+ None => {
+ let (content, truncated) = fallback.map_err(|ax| match error.as_ref() {
+ Some(error) => anyhow::anyhow!("{ax} (JavaScript read failed first: {error})"),
+ None => ax,
+ })?;
+ source = "ax_fallback";
+ (content, Some(truncated))
+ }
+ };
+ let mut metadata = serde_json::json!({"source": source});
+ if let Some(truncated) = truncated {
+ if let Some(error) = error {
+ metadata["fallback_error"] = serde_json::json!(error);
+ }
+ metadata["truncated"] = serde_json::json!(truncated);
+ }
+ Ok(PageReadResult::text(content).with_structured(metadata))
+}
+
+/// Extract page text via the bounded AX tree.
async fn ax_text_fallback(
pid: i32,
window_id: u64,
require_web_area: bool,
-) -> anyhow::Result<String> {
+) -> anyhow::Result<(String, bool)> {
let window_id = u32::try_from(window_id)
.map_err(|_| anyhow::anyhow!("macOS window_id {window_id} is out of u32 range"))?;
let result =
tokio::task::spawn_blocking(move || crate::ax::tree::walk_tree(pid, Some(window_id), None))
.await
.map_err(|e| anyhow::anyhow!("AX walk task failed: {e}"))?;
- let rows = page_rows(result.tree_markdown, require_web_area)?;
- Ok(AXPageReader::extract_text(&rows))
+ Ok((
+ AXPageReader::extract_text(&page_rows(result.tree_markdown, require_web_area)?),
+ result.truncated || result.depth_truncated,
+ ))
}
-/// Query AX tree by CSS selector.
+/// Query the bounded AX tree by CSS selector.
async fn ax_query_fallback(
pid: i32,
window_id: u64,
selector: &str,
require_web_area: bool,
-) -> anyhow::Result<Vec<crate::browser::ax_page_reader::AXElement>> {
+) -> anyhow::Result<(String, bool)> {
let window_id = u32::try_from(window_id)
.map_err(|_| anyhow::anyhow!("macOS window_id {window_id} is out of u32 range"))?;
let sel = selector.to_owned();
@@ -384,8 +423,13 @@ async fn ax_query_fallback(
tokio::task::spawn_blocking(move || crate::ax::tree::walk_tree(pid, Some(window_id), None))
.await
.map_err(|e| anyhow::anyhow!("AX walk task failed: {e}"))?;
- let rows = page_rows(result.tree_markdown, require_web_area)?;
- Ok(AXPageReader::query(&sel, &rows))
+ Ok((
+ format_ax_elements(&AXPageReader::query(
+ &sel,
+ &page_rows(result.tree_markdown, require_web_area)?,
+ )),
+ result.truncated || result.depth_truncated,
+ ))
}
fn format_ax_elements(elements: &[crate::browser::ax_page_reader::AXElement]) -> String {
@@ -478,7 +522,7 @@ fn required_finite(value: &serde_json::Value, key: &str, raw: &str) -> anyhow::R
#[cfg(test)]
mod tests {
- use super::page_rows;
+ use super::*;
const MENU_ONLY: &str = "- [0] AXMenuBar\n - [1] AXMenuBarItem \"Apple\"\n";
@@ -502,4 +546,45 @@ mod tests {
fn web_view_apps_keep_the_whole_tree_without_a_web_area() {
assert_eq!(page_rows(MENU_ONLY.to_owned(), false).unwrap(), MENU_ONLY);
}
+
+ #[test]
+ fn page_read_decisions_preserve_provenance() {
+ for source in ["javascript", "cdp"] {
+ let page = finish_page_read(
+ source,
+ Some("page".into()),
+ Some("JS failed".into()),
+ Ok(("ax".into(), true)),
+ )
+ .unwrap();
+ assert_eq!(
+ page.structured_content.unwrap(),
+ serde_json::json!({"source": source})
+ );
+ }
+ for error in [None, Some("JS failed".to_owned())] {
+ let page =
+ finish_page_read("cdp", None, error.clone(), Ok(("ax".into(), true))).unwrap();
+ let mut expected = serde_json::json!({"source": "ax_fallback", "truncated": true});
+ if let Some(error) = error.as_ref() {
+ expected["fallback_error"] = serde_json::json!(error);
+ }
+ assert_eq!(page.structured_content.unwrap(), expected);
+ let failure = finish_page_read(
+ "cdp",
+ None,
+ error.clone(),
+ Err(anyhow::anyhow!("AX failed")),
+ )
+ .unwrap_err()
+ .to_string();
+ assert_eq!(
+ failure,
+ match error {
+ Some(error) => format!("AX failed (JavaScript read failed first: {error})"),
+ None => "AX failed".to_owned(),
+ }
+ );
+ }
+ }
}
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/page.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/page.rs
index 6d82874e37..83520af54b 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/page.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/page.rs
@@ -28,7 +28,7 @@
//! Returns an actionable error if neither path works.
use async_trait::async_trait;
-use cua_driver_core::page::{ClickElementResult, PageBackend};
+use cua_driver_core::page::{ClickElementResult, PageBackend, PageReadResult};
use windows::core::Interface;
use windows::Win32::Foundation::HWND;
@@ -60,11 +60,12 @@ impl Default for WindowsPageBackend {
#[async_trait]
impl PageBackend for WindowsPageBackend {
- async fn get_text(&self, _pid: i32, window_id: u64) -> anyhow::Result<String> {
+ async fn get_text(&self, _pid: i32, window_id: u64) -> anyhow::Result<PageReadResult> {
let hwnd = window_id;
- tokio::task::spawn_blocking(move || unsafe { get_text_blocking(hwnd) })
+ let content = tokio::task::spawn_blocking(move || unsafe { get_text_blocking(hwnd) })
.await
- .map_err(|e| anyhow::anyhow!("join error: {e}"))?
+ .map_err(|e| anyhow::anyhow!("join error: {e}"))??;
+ Ok(PageReadResult::text(content))
}
async fn query_dom(
@@ -73,13 +74,16 @@ impl PageBackend for WindowsPageBackend {
window_id: u64,
css_selector: &str,
attributes: &[String],
- ) -> anyhow::Result<String> {
+ ) -> anyhow::Result<PageReadResult> {
let hwnd = window_id;
let selector = css_selector.to_owned();
let attrs: Vec<String> = attributes.to_vec();
- tokio::task::spawn_blocking(move || unsafe { query_dom_blocking(hwnd, &selector, &attrs) })
- .await
- .map_err(|e| anyhow::anyhow!("join error: {e}"))?
+ let content = tokio::task::spawn_blocking(move || unsafe {
+ query_dom_blocking(hwnd, &selector, &attrs)
+ })
+ .await
+ .map_err(|e| anyhow::anyhow!("join error: {e}"))??;
+ Ok(PageReadResult::text(content))
}
async fn execute_javascript(
diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json
index 20121914df..b783441b23 100644
--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json
+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json
@@ -2360,7 +2360,7 @@
"read_only": true
},
{
- "description": "Legacy browser compatibility tool. Prefer get_browser_state and the typed browser_* tools for exact targeting, endpoint ownership, and consent. Read-only get_text and query_dom remain available by default. Mutating actions require the daemon operator to set CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1 before daemon startup (restart the daemon after changing it); this escape hatch does not provide the typed browser surface's exact binding or existing-profile grant guarantees. Supports Chrome, Brave, Edge, Safari (via AppleScript on macOS), Electron apps (via CDP), Chromium/Firefox on Windows (via UIA for read; CDP for execute_javascript when --remote-debugging-port is set), and WKWebView/Tauri/AT-SPI fallbacks.\n\nActions:\n- execute_javascript: Run JS and return the result.\n- get_text: Extract visible text from the page.\n- query_dom: Find elements matching a CSS selector.\n- click_element: Click a CSS-selected element AND animate the agent cursor to its on-screen center first (so the user sees what the agent is doing). Prefer over `execute_javascript('el.click()')` whenever you want visible cursor feedback.\n- insert_text: Insert `text` at whatever currently holds DOM focus in one native operation (CDP Input.insertText) — no synthesized key events, but more durable than a one-shot execute_javascript write since rich-text editors already have to treat it like an IME commit. Try this before type_keystrokes on a contenteditable that discarded an execute_javascript write. Click/focus the target field first.\n- type_keystrokes: Type `text` via real per-character keystroke events into whatever currently holds DOM focus. Slower than insert_text but the most durable rung — use it when insert_text also gets discarded, or the editor's own keydown/keyup handlers need to see real keys. Click/focus the target field first.\n- enable_javascript_apple_events: macOS-only — patch the browser's Preferences to allow JS from Apple Events (Chrome/Brave/Edge, requires user confirmation and a browser restart).",
+ "description": "Legacy browser compatibility tool. Prefer get_browser_state and the typed browser_* tools for exact targeting, endpoint ownership, and consent. Read-only get_text and query_dom remain available by default. Mutating actions require the daemon operator to set CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1 before daemon startup (restart the daemon after changing it); this escape hatch does not provide the typed browser surface's exact binding or existing-profile grant guarantees. Supports Chrome, Brave, Edge, Safari (via AppleScript on macOS), Electron apps (via CDP), Chromium/Firefox on Windows (via UIA for read; CDP for execute_javascript when --remote-debugging-port is set), and WKWebView/Tauri/AT-SPI fallbacks.\n\nActions:\n- execute_javascript: Run JS and return the result.\n- get_text: Extract visible text from the page. On macOS, structuredContent.source identifies javascript, cdp, or ax_fallback; a successful AX fallback preserves the triggering error and truncation state in structuredContent.\n- query_dom: Find elements matching a CSS selector, with the same macOS fallback metadata contract as get_text.\n- click_element: Click a CSS-selected element AND animate the agent cursor to its on-screen center first (so the user sees what the agent is doing). Prefer over `execute_javascript('el.click()')` whenever you want visible cursor feedback.\n- insert_text: Insert `text` at whatever currently holds DOM focus in one native operation (CDP Input.insertText) — no synthesized key events, but more durable than a one-shot execute_javascript write since rich-text editors already have to treat it like an IME commit. Try this before type_keystrokes on a contenteditable that discarded an execute_javascript write. Click/focus the target field first.\n- type_keystrokes: Type `text` via real per-character keystroke events into whatever currently holds DOM focus. Slower than insert_text but the most durable rung — use it when insert_text also gets discarded, or the editor's own keydown/keyup handlers need to see real keys. Click/focus the target field first.\n- enable_javascript_apple_events: macOS-only — patch the browser's Preferences to allow JS from Apple Events (Chrome/Brave/Edge, requires user confirmation and a browser restart).",
"destructive": false,
"idempotent": false,
"input_schema": {
diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json
index 0d3eda5fd5..a8aadb7ce8 100644
--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json
+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json
@@ -2088,7 +2088,7 @@
"read_only": true
},
{
- "description": "Legacy browser compatibility tool. Prefer get_browser_state and the typed browser_* tools for exact targeting, endpoint ownership, and consent. Read-only get_text and query_dom remain available by default. Mutating actions require the daemon operator to set CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1 before daemon startup (restart the daemon after changing it); this escape hatch does not provide the typed browser surface's exact binding or existing-profile grant guarantees. Supports Chrome, Brave, Edge, Safari (via AppleScript on macOS), Electron apps (via CDP), Chromium/Firefox on Windows (via UIA for read; CDP for execute_javascript when --remote-debugging-port is set), and WKWebView/Tauri/AT-SPI fallbacks.\n\nActions:\n- execute_javascript: Run JS and return the result.\n- get_text: Extract visible text from the page.\n- query_dom: Find elements matching a CSS selector.\n- click_element: Click a CSS-selected element AND animate the agent cursor to its on-screen center first (so the user sees what the agent is doing). Prefer over `execute_javascript('el.click()')` whenever you want visible cursor feedback.\n- insert_text: Insert `text` at whatever currently holds DOM focus in one native operation (CDP Input.insertText) — no synthesized key events, but more durable than a one-shot execute_javascript write since rich-text editors already have to treat it like an IME commit. Try this before type_keystrokes on a contenteditable that discarded an execute_javascript write. Click/focus the target field first.\n- type_keystrokes: Type `text` via real per-character keystroke events into whatever currently holds DOM focus. Slower than insert_text but the most durable rung — use it when insert_text also gets discarded, or the editor's own keydown/keyup handlers need to see real keys. Click/focus the target field first.\n- enable_javascript_apple_events: macOS-only — patch the browser's Preferences to allow JS from Apple Events (Chrome/Brave/Edge, requires user confirmation and a browser restart).",
+ "description": "Legacy browser compatibility tool. Prefer get_browser_state and the typed browser_* tools for exact targeting, endpoint ownership, and consent. Read-only get_text and query_dom remain available by default. Mutating actions require the daemon operator to set CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1 before daemon startup (restart the daemon after changing it); this escape hatch does not provide the typed browser surface's exact binding or existing-profile grant guarantees. Supports Chrome, Brave, Edge, Safari (via AppleScript on macOS), Electron apps (via CDP), Chromium/Firefox on Windows (via UIA for read; CDP for execute_javascript when --remote-debugging-port is set), and WKWebView/Tauri/AT-SPI fallbacks.\n\nActions:\n- execute_javascript: Run JS and return the result.\n- get_text: Extract visible text from the page. On macOS, structuredContent.source identifies javascript, cdp, or ax_fallback; a successful AX fallback preserves the triggering error and truncation state in structuredContent.\n- query_dom: Find elements matching a CSS selector, with the same macOS fallback metadata contract as get_text.\n- click_element: Click a CSS-selected element AND animate the agent cursor to its on-screen center first (so the user sees what the agent is doing). Prefer over `execute_javascript('el.click()')` whenever you want visible cursor feedback.\n- insert_text: Insert `text` at whatever currently holds DOM focus in one native operation (CDP Input.insertText) — no synthesized key events, but more durable than a one-shot execute_javascript write since rich-text editors already have to treat it like an IME commit. Try this before type_keystrokes on a contenteditable that discarded an execute_javascript write. Click/focus the target field first.\n- type_keystrokes: Type `text` via real per-character keystroke events into whatever currently holds DOM focus. Slower than insert_text but the most durable rung — use it when insert_text also gets discarded, or the editor's own keydown/keyup handlers need to see real keys. Click/focus the target field first.\n- enable_javascript_apple_events: macOS-only — patch the browser's Preferences to allow JS from Apple Events (Chrome/Brave/Edge, requires user confirmation and a browser restart).",
"destructive": false,
"idempotent": false,
"input_schema": {
diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
index 816f386afd..ccce45451a 100644
--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
@@ -2054,7 +2054,7 @@
"read_only": true
},
{
- "description": "Legacy browser compatibility tool. Prefer get_browser_state and the typed browser_* tools for exact targeting, endpoint ownership, and consent. Read-only get_text and query_dom remain available by default. Mutating actions require the daemon operator to set CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1 before daemon startup (restart the daemon after changing it); this escape hatch does not provide the typed browser surface's exact binding or existing-profile grant guarantees. Supports Chrome, Brave, Edge, Safari (via AppleScript on macOS), Electron apps (via CDP), Chromium/Firefox on Windows (via UIA for read; CDP for execute_javascript when --remote-debugging-port is set), and WKWebView/Tauri/AT-SPI fallbacks.\n\nActions:\n- execute_javascript: Run JS and return the result.\n- get_text: Extract visible text from the page.\n- query_dom: Find elements matching a CSS selector.\n- click_element: Click a CSS-selected element AND animate the agent cursor to its on-screen center first (so the user sees what the agent is doing). Prefer over `execute_javascript('el.click()')` whenever you want visible cursor feedback.\n- insert_text: Insert `text` at whatever currently holds DOM focus in one native operation (CDP Input.insertText) — no synthesized key events, but more durable than a one-shot execute_javascript write since rich-text editors already have to treat it like an IME commit. Try this before type_keystrokes on a contenteditable that discarded an execute_javascript write. Click/focus the target field first.\n- type_keystrokes: Type `text` via real per-character keystroke events into whatever currently holds DOM focus. Slower than insert_text but the most durable rung — use it when insert_text also gets discarded, or the editor's own keydown/keyup handlers need to see real keys. Click/focus the target field first.\n- enable_javascript_apple_events: macOS-only — patch the browser's Preferences to allow JS from Apple Events (Chrome/Brave/Edge, requires user confirmation and a browser restart).",
+ "description": "Legacy browser compatibility tool. Prefer get_browser_state and the typed browser_* tools for exact targeting, endpoint ownership, and consent. Read-only get_text and query_dom remain available by default. Mutating actions require the daemon operator to set CUA_DRIVER_ENABLE_LEGACY_PAGE_MUTATIONS=1 before daemon startup (restart the daemon after changing it); this escape hatch does not provide the typed browser surface's exact binding or existing-profile grant guarantees. Supports Chrome, Brave, Edge, Safari (via AppleScript on macOS), Electron apps (via CDP), Chromium/Firefox on Windows (via UIA for read; CDP for execute_javascript when --remote-debugging-port is set), and WKWebView/Tauri/AT-SPI fallbacks.\n\nActions:\n- execute_javascript: Run JS and return the result.\n- get_text: Extract visible text from the page. On macOS, structuredContent.source identifies javascript, cdp, or ax_fallback; a successful AX fallback preserves the triggering error and truncation state in structuredContent.\n- query_dom: Find elements matching a CSS selector, with the same macOS fallback metadata contract as get_text.\n- click_element: Click a CSS-selected element AND animate the agent cursor to its on-screen center first (so the user sees what the agent is doing). Prefer over `execute_javascript('el.click()')` whenever you want visible cursor feedback.\n- insert_text: Insert `text` at whatever currently holds DOM focus in one native operation (CDP Input.insertText) — no synthesized key events, but more durable than a one-shot execute_javascript write since rich-text editors already have to treat it like an IME commit. Try this before type_keystrokes on a contenteditable that discarded an execute_javascript write. Click/focus the target field first.\n- type_keystrokes: Type `text` via real per-character keystroke events into whatever currently holds DOM focus. Slower than insert_text but the most durable rung — use it when insert_text also gets discarded, or the editor's own keydown/keyup handlers need to see real keys. Click/focus the target field first.\n- enable_javascript_apple_events: macOS-only — patch the browser's Preferences to allow JS from Apple Events (Chrome/Brave/Edge, requires user confirmation and a browser restart).",
"destructive": false,
"idempotent": false,
"input_schema": {