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(get_window_state): 30s timeout + 2000-node cap for heavy webview apps (#1754)

Francesco Bonacci73a84f5d1f20
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 fdeeb33483..a05f0924ca 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
@@ -18,6 +18,13 @@ use core_foundation::base::{CFRelease, CFRetain, CFTypeRef};
/// pathological trees (mirrors Swift reference implementation).
const MAX_DEPTH: usize = 25;
+/// Maximum total nodes visited during a single AX walk. Chromium-family apps
+/// (Arc, VS Code, Chrome) can expose thousands of nodes; capping at 2 000
+/// keeps the walk bounded while still covering realistic app chrome.
+/// When the cap is hit the walk stops early and the partial tree is returned
+/// with a warning line appended (mirrors Swift reference implementation).
+const MAX_ELEMENTS: usize = 2_000;
+
/// A single node in the AX tree.
#[derive(Debug, Clone)]
pub struct AXNode {
@@ -42,6 +49,8 @@ pub struct AXNode {
pub struct TreeWalkResult {
pub tree_markdown: String,
pub nodes: Vec<AXNode>,
+ /// True when the walk was cut short by the MAX_ELEMENTS cap.
+ pub truncated: bool,
}
/// Walk the AX tree of `pid`, optionally filtered to a specific window.
@@ -62,11 +71,16 @@ pub fn walk_tree(pid: i32, window_id: Option<u32>, query: Option<&str>) -> TreeW
let mut nodes: Vec<AXNode> = Vec::new();
let mut lines: Vec<(usize, String)> = Vec::new(); // (depth, line)
let mut index_counter = 0usize;
+ // Shared visited-node counter passed into walk_element to enforce MAX_ELEMENTS.
+ let mut visited_count = 0usize;
+ // Set to true only when walk_element actually stops early due to the cap —
+ // avoids a false-positive when the tree naturally ends on exactly MAX_ELEMENTS.
+ let mut truncated = false;
unsafe {
let app_elem = AXUIElementCreateApplication(pid);
if app_elem.is_null() {
- return TreeWalkResult { tree_markdown: String::new(), nodes };
+ return TreeWalkResult { tree_markdown: String::new(), nodes, truncated: false };
}
// Union AXChildren + AXWindows — the only way to see background windows.
@@ -102,7 +116,7 @@ pub fn walk_tree(pid: i32, window_id: Option<u32>, query: Option<&str>) -> TreeW
// Walk each top-level child at depth 0.
for child in walk_these {
- walk_element(child, 0, &mut nodes, &mut lines, &mut index_counter);
+ walk_element(child, 0, &mut nodes, &mut lines, &mut index_counter, &mut visited_count, &mut truncated);
}
// Release all top-level elements (copy_children / copy_ax_windows both retain).
@@ -113,14 +127,24 @@ pub fn walk_tree(pid: i32, window_id: Option<u32>, query: Option<&str>) -> TreeW
CFRelease(app_elem as CFTypeRef);
}
+ let truncated_flag = truncated;
let raw_markdown = render_lines(&lines);
- let tree_markdown = if let Some(q) = query {
+ let mut tree_markdown = if let Some(q) = query {
filter_tree(&raw_markdown, q)
} else {
raw_markdown
};
- TreeWalkResult { tree_markdown, nodes }
+ if truncated_flag {
+ tree_markdown.push_str(&format!(
+ "\n⚠️ AX tree truncated at {MAX_ELEMENTS} nodes \
+ (app has a very large accessibility tree — Arc, Electron, or similar). \
+ Element indices above are still valid. Use pixel clicks for elements \
+ not visible in this partial tree."
+ ));
+ }
+
+ TreeWalkResult { tree_markdown, nodes, truncated: truncated_flag }
}
unsafe fn walk_element(
@@ -129,8 +153,17 @@ unsafe fn walk_element(
nodes: &mut Vec<AXNode>,
lines: &mut Vec<(usize, String)>,
counter: &mut usize,
+ visited_count: &mut usize,
+ truncated: &mut bool,
) {
if depth > MAX_DEPTH { return; }
+ // Enforce total-node cap — mirrors Swift's maxElements guard.
+ // Set the truncated flag only when we actually stop early.
+ if *visited_count >= MAX_ELEMENTS {
+ *truncated = true;
+ return;
+ }
+ *visited_count += 1;
let role = copy_string_attr(element, "AXRole")
.unwrap_or_else(|| "AXUnknown".into());
@@ -140,7 +173,7 @@ unsafe fn walk_element(
// Still recurse — children may be interesting.
let children = copy_children(element);
for child in children {
- walk_element(child, depth, nodes, lines, counter);
+ walk_element(child, depth, nodes, lines, counter, visited_count, truncated);
CFRelease(child as CFTypeRef);
}
return;
@@ -173,7 +206,7 @@ unsafe fn walk_element(
if !is_actionable && !has_content && role != "AXWindow" && role != "AXSheet" {
let children = copy_children(element);
for child in children {
- walk_element(child, depth + 1, nodes, lines, counter);
+ walk_element(child, depth + 1, nodes, lines, counter, visited_count, truncated);
CFRelease(child as CFTypeRef);
}
return;
@@ -217,7 +250,7 @@ unsafe fn walk_element(
let children = copy_children(element);
for child in children {
- walk_element(child, depth + 1, nodes, lines, counter);
+ walk_element(child, depth + 1, nodes, lines, counter, visited_count, truncated);
CFRelease(child as CFTypeRef);
}
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
index aa824e6120..addcb5cf2e 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
@@ -78,12 +78,25 @@ impl Tool for GetWindowStateTool {
let capture_mode = if capture_mode == "tree" { "ax".to_owned() } else { capture_mode };
let tree_result = if capture_mode != "vision" {
let q = query.clone();
- let result = tokio::task::spawn_blocking(move || {
+ // Wrap the blocking AX walk in a 30-second timeout. Heavy webview apps
+ // (Arc, Safari with many tabs, Electron) can block
+ // AXUIElementCopyAttributeValue indefinitely via XPC — without a
+ // deadline the MCP server hangs forever (issue #1537).
+ let walk_future = tokio::task::spawn_blocking(move || {
crate::ax::tree::walk_tree(pid, Some(window_id), q.as_deref())
- }).await;
- match result {
- Ok(r) => Some(r),
- Err(e) => return ToolResult::error(format!("AX tree walk failed: {e}")),
+ });
+ match tokio::time::timeout(std::time::Duration::from_secs(30), walk_future).await {
+ Ok(Ok(r)) => Some(r),
+ Ok(Err(e)) => return ToolResult::error(format!("AX tree walk failed: {e}")),
+ Err(_elapsed) => {
+ return ToolResult::error(format!(
+ "AX tree walk for pid={pid} timed out after 30 s. \
+ The app (likely Arc, Electron, or Safari with many tabs) has a \
+ pathologically large accessibility tree. \
+ Workarounds: switch to capture_mode=vision for pixel-click \
+ workflows, or use capture_mode=ax with a depth-limited scan."
+ ));
+ }
}
} else {
None