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): scope the Linux AT-SPI walk to the requested window (#2895)

Francesco Bonacci8c515ca74d7f
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
index 6a0976edf2..faf7d32845 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
@@ -54,6 +54,12 @@ pub struct AtspiTreeResult {
/// Machine-readable reason when a native walk failed in a way that is more
/// specific than ordinary AT-SPI unavailability.
pub degraded_reason: Option<String>,
+ /// True when a caller-supplied `xid` was proven to correspond to exactly one
+ /// of the application's top-levels, so these nodes are that window's and no
+ /// other's. AT-SPI publishes one tree per process, so an application-scoped
+ /// snapshot of a multi-window app carries every window's controls; callers
+ /// that act on behalf of an exact native window must require this.
+ pub window_scoped: bool,
}
/// Walk the AT-SPI tree for a window identified by (pid, xid).
@@ -73,16 +79,16 @@ pub(crate) fn walk_tree_for_recording(
xid: u64,
timeout: std::time::Duration,
) -> AtspiTreeResult {
- if let Ok(Some((tree_markdown, nodes, bounds))) =
- native::walk_tree_bounded_with_timeout(pid, xid, None, None, timeout)
+ if let Ok(Some(walked)) = native::walk_tree_bounded_with_timeout(pid, xid, None, None, timeout)
{
- if !tree_markdown.is_empty() {
+ if !walked.markdown.is_empty() {
return AtspiTreeResult {
- tree_markdown,
- nodes,
- bounds,
+ tree_markdown: walked.markdown,
+ nodes: walked.nodes,
+ bounds: walked.bounds,
trusted: true,
degraded_reason: None,
+ window_scoped: walked.window_scoped,
};
}
}
@@ -111,23 +117,26 @@ pub fn walk_tree_bounded(
let mut native_failure = None;
for attempt in 0..MAX_ATTEMPTS {
match native::walk_tree_bounded(pid, xid, max_elements, max_depth) {
- Ok(Some((raw_md, nodes, bounds))) => {
+ Ok(Some(walked)) => {
// `nodes.len() <= 1` == only the root window resolved: the
// cold-registry symptom. Accept any real tree immediately; only
// keep waiting on the degenerate case, and accept it anyway on the
// final attempt rather than discarding a (minimal) valid result.
- if !raw_md.is_empty() && (nodes.len() > 1 || attempt == MAX_ATTEMPTS - 1) {
+ if !walked.markdown.is_empty()
+ && (walked.nodes.len() > 1 || attempt == MAX_ATTEMPTS - 1)
+ {
let md = if let Some(q) = query {
- filter_tree(&raw_md, q)
+ filter_tree(&walked.markdown, q)
} else {
- raw_md
+ walked.markdown
};
return AtspiTreeResult {
tree_markdown: md,
- nodes,
- bounds,
+ nodes: walked.nodes,
+ bounds: walked.bounds,
trusted: true,
degraded_reason: None,
+ window_scoped: walked.window_scoped,
};
}
}
@@ -252,6 +261,7 @@ fn walk_via_x11_properties(xid: u64, query: Option<&str>) -> AtspiTreeResult {
bounds: vec![],
trusted: false,
degraded_reason: None,
+ window_scoped: false,
}
}
};
@@ -308,6 +318,10 @@ fn walk_via_x11_properties(xid: u64, query: Option<&str>) -> AtspiTreeResult {
nodes,
bounds: vec![],
trusted: false,
+ // Built by reading this exact window's X11 properties, so it describes
+ // one window by construction — but `trusted: false` still bars it from
+ // proving anything a caller acts on.
+ window_scoped: true,
degraded_reason: None,
}
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
index 8a326b20d2..1310c9e200 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
@@ -250,6 +250,12 @@ struct Visited<'a> {
/// Chromium keeps its document on the application's ordinary AT-SPI bus,
/// where descendant Window extents already include the document origin.
on_web_process_bus: bool,
+ /// Position of the application top-level (frame/window) this node descends
+ /// from, in `app.get_children()` order. AT-SPI exposes one application per
+ /// process, so a multi-window app publishes every window's controls in one
+ /// tree; this is what lets a caller that named an exact native window prove
+ /// which of those windows a node actually lives in.
+ frame_ordinal: usize,
acc: AccessibleProxy<'a>,
}
@@ -523,7 +529,128 @@ async fn collect_visited<'a>(
conn: &'a AccessibilityConnection,
pid: u32,
) -> Result<Option<Vec<Visited<'a>>>> {
- collect_visited_bounded(conn, pid, None, None).await
+ collect_visited_bounded(conn, pid, 0, None, None)
+ .await
+ .map(|walked| walked.map(|(visited, _)| visited))
+}
+
+/// Screen-space distance between an AT-SPI frame's extents and a native
+/// window's geometry. Lower is a better correspondence; `None` when the frame
+/// reports no usable extents.
+fn frame_geometry_distance(
+ frame: (i32, i32, i32, i32),
+ window: &crate::x11::WindowInfo,
+) -> Option<u64> {
+ let (fx, fy, fw, fh) = frame;
+ if fw <= 0 || fh <= 0 {
+ return None;
+ }
+ let dx = i64::from(fx) - i64::from(window.x);
+ let dy = i64::from(fy) - i64::from(window.y);
+ let dw = i64::from(fw) - i64::from(window.width);
+ let dh = i64::from(fh) - i64::from(window.height);
+ Some(dx.unsigned_abs() + dy.unsigned_abs() + dw.unsigned_abs() + dh.unsigned_abs())
+}
+
+/// Server-side decorations offset a frame's reported origin from the native
+/// window's outer geometry, so an exact match is not required. The correlation
+/// must still be unambiguous: the best candidate has to be within this budget
+/// AND beat the runner-up by [`FRAME_MATCH_MARGIN_PX`].
+const FRAME_MATCH_TOLERANCE_PX: u64 = 160;
+
+/// How decisively the best frame must beat the second-best. Two windows of
+/// genuinely similar geometry are not disambiguated by this heuristic, and a
+/// caller that needs proof of window identity must get a refusal instead of a
+/// coin flip.
+const FRAME_MATCH_MARGIN_PX: u64 = 24;
+
+/// Pick the unique application top-level that corresponds to native window
+/// `xid`, or `None` when the correspondence cannot be proven.
+///
+/// AT-SPI publishes one application per process: every window of a multi-window
+/// app shares a single tree, and the protocol exposes no window handle to join
+/// on. Geometry is the available bridge — `Component.GetExtents` in screen
+/// coordinates against the X11 outer geometry the caller already named. This
+/// refuses ties rather than guessing, because callers use the result to decide
+/// which window they are about to act inside.
+fn correlate_frame_to_window(
+ candidates: &[(usize, (i32, i32, i32, i32))],
+ window: &crate::x11::WindowInfo,
+) -> Option<usize> {
+ let mut scored: Vec<(u64, usize)> = candidates
+ .iter()
+ .filter_map(|(ordinal, extents)| {
+ frame_geometry_distance(*extents, window).map(|distance| (distance, *ordinal))
+ })
+ .collect();
+ scored.sort_by_key(|(distance, ordinal)| (*distance, *ordinal));
+ let (best_distance, best_ordinal) = *scored.first()?;
+ if best_distance > FRAME_MATCH_TOLERANCE_PX {
+ return None;
+ }
+ if let Some((runner_up, _)) = scored.get(1) {
+ if runner_up.saturating_sub(best_distance) < FRAME_MATCH_MARGIN_PX {
+ return None;
+ }
+ }
+ Some(best_ordinal)
+}
+
+/// Resolve native window `xid` to the ordinal of the application top-level that
+/// renders it, or `None` when that cannot be proven. `None` means the walk stays
+/// application-wide: callers that merely want a tree carry on, and callers that
+/// need window identity must refuse.
+async fn resolve_window_frame(
+ conn: &AccessibilityConnection,
+ pid: u32,
+ xid: u64,
+ seeds: &[RawObjectRef],
+) -> Option<usize> {
+ if seeds.len() == 1 {
+ // One top-level: the caller's window is the only thing this
+ // application could be showing, and no geometry round-trip can make
+ // that more certain.
+ return Some(0);
+ }
+ let window = crate::x11::list_windows(Some(pid))
+ .into_iter()
+ .find(|candidate| candidate.xid == xid)?;
+ let mut candidates: Vec<(usize, (i32, i32, i32, i32))> = Vec::new();
+ for (ordinal, oref) in seeds.iter().enumerate() {
+ let Some(Ok(acc)) = call(accessible_for(conn, oref)).await else {
+ continue;
+ };
+ // Menus, tooltips and other transients are top-level accessibles too;
+ // only real windows can correspond to a native window id.
+ let role = match call(acc.get_role_name()).await {
+ Some(Ok(role)) => role,
+ _ => continue,
+ };
+ if !matches!(
+ role.as_str(),
+ "frame" | "window" | "dialog" | "alert" | "file chooser"
+ ) {
+ continue;
+ }
+ let Some(Ok(proxies)) = call(acc.proxies()).await else {
+ continue;
+ };
+ let Some(Ok(component)) = call(proxies.component()).await else {
+ continue;
+ };
+ if let Some(Ok(extents)) = call(component.get_extents(CoordType::Screen)).await {
+ candidates.push((ordinal, extents));
+ }
+ }
+ let resolved = correlate_frame_to_window(&candidates, &window);
+ if resolved.is_none() {
+ dlog!(
+ "could not correlate xid {xid} to one of pid {pid}'s {} top-level frame(s); \
+ walk stays application-scoped",
+ candidates.len()
+ );
+ }
+ resolved
}
/// `collect_visited` with caller-supplied caps.
@@ -535,29 +662,48 @@ async fn collect_visited<'a>(
async fn collect_visited_bounded<'a>(
conn: &'a AccessibilityConnection,
pid: u32,
+ xid: u64,
max_elements: Option<usize>,
max_depth: Option<usize>,
-) -> Result<Option<Vec<Visited<'a>>>> {
+) -> Result<Option<(Vec<Visited<'a>>, Option<usize>)>> {
let app = match app_for_pid(conn, pid).await? {
Some(a) => a,
None => return Ok(None),
};
let zconn = conn.connection();
- // Stack of (object ref, depth, in_web_doc). Seed with the app's windows;
- // push children reversed so siblings pop left-to-right and each subtree
- // completes before the next sibling (pre-order). `in_web_doc` is inherited
- // from ancestors so editables in page content can be told from chrome.
- let mut stack: Vec<(RawObjectRef, usize, bool)> = match call(app.get_children()).await {
+ // Stack of (object ref, depth, in_web_doc, frame_ordinal). Seed with the
+ // app's windows; push children reversed so siblings pop left-to-right and
+ // each subtree completes before the next sibling (pre-order). `in_web_doc`
+ // is inherited from ancestors so editables in page content can be told from
+ // chrome. `frame_ordinal` is the seed's position in `get_children()` order
+ // and is likewise inherited, so every node carries the identity of the
+ // top-level window it belongs to.
+ let seeds: Vec<RawObjectRef> = match call(app.get_children()).await {
Some(Ok(children)) => children
.into_iter()
.filter_map(|child| RawObjectRef::from_atspi(&child))
- .rev()
- .map(|r| (r, 0usize, false))
.collect(),
_ => Vec::new(),
};
+ // Resolve which seed is the caller's window before walking, from the same
+ // child list the walk is about to seed from. Re-reading `get_children()`
+ // later could observe a different window set, and an ordinal resolved
+ // against one list but applied to another names the wrong window.
+ let scoped_frame = if xid == 0 {
+ None
+ } else {
+ resolve_window_frame(conn, pid, xid, &seeds).await
+ };
+
+ let mut stack: Vec<(RawObjectRef, usize, bool, usize)> = seeds
+ .into_iter()
+ .enumerate()
+ .map(|(ordinal, r)| (r, 0usize, false, ordinal))
+ .rev()
+ .collect();
+
let mut visited: Vec<Visited<'a>> = Vec::new();
// Guard against pathological/looping trees. Defaults to 5 000 (the
// historical hard-coded budget); callers can override via max_elements.
@@ -578,7 +724,7 @@ async fn collect_visited_bounded<'a>(
// few seconds rather than ~25s.
let mut consecutive_timeouts = 0u32;
- while let Some((oref, depth, inherited_web_doc)) = stack.pop() {
+ while let Some((oref, depth, inherited_web_doc, frame_ordinal)) = stack.pop() {
if budget == 0 {
dlog!("node budget exhausted; truncating walk");
break;
@@ -770,7 +916,7 @@ async fn collect_visited_bounded<'a>(
match children_r {
Some(Ok(children)) => {
for c in children.into_iter().rev() {
- stack.push((c, depth + 1, child_in_web_doc));
+ stack.push((c, depth + 1, child_in_web_doc, frame_ordinal));
}
}
Some(Err(error)) => dlog!(" get_children failed: {error:#}"),
@@ -794,12 +940,13 @@ async fn collect_visited_bounded<'a>(
focused,
in_web_doc,
on_web_process_bus: is_web_process_bus(&oref.name),
+ frame_ordinal,
acc,
});
}
dlog!("walked pid {pid}: {} node(s)", visited.len());
- Ok(Some(visited))
+ Ok(Some((visited, scoped_frame)))
}
/// Render visited nodes into the markdown + node list `walk_tree` returns.
@@ -809,10 +956,18 @@ async fn collect_visited_bounded<'a>(
/// `parent_at_depth` tracks the most recently emitted actionable index at
/// each depth, so descendants can look up their parent_element_index without
/// a second pass.
-fn render(visited: &[Visited<'_>]) -> (String, Vec<AtspiNode>) {
+///
+/// `only_frame` restricts what is *emitted* to one application top-level while
+/// leaving the index space application-wide. Element indices are the contract
+/// between a snapshot and every actuator that later takes one
+/// (`perform_action`, `focus_element`, `set_value`, …), and those resolve an
+/// index against the whole application. Renumbering per window would make a
+/// window-scoped snapshot's indices name different elements at actuation time.
+fn render(visited: &[Visited<'_>], only_frame: Option<usize>) -> (String, Vec<AtspiNode>) {
let mut md = String::new();
let mut nodes = Vec::new();
let mut idx = 0usize;
+ let mut current_frame: Option<usize> = None;
// Sparse stack: parent_at_depth[d] = Some(idx) for the actionable node
// most recently emitted at depth d. When a new node appears at depth d,
// its parent_element_index is the closest ancestor at depth < d that has
@@ -821,6 +976,14 @@ fn render(visited: &[Visited<'_>]) -> (String, Vec<AtspiNode>) {
let mut parent_at_depth: Vec<Option<usize>> = Vec::new();
for v in visited {
+ // Ancestry never spans two top-levels, so a frame change retires every
+ // recorded parent. Without this a window's first descendants could
+ // inherit a parent index from the previous window's subtree.
+ if current_frame != Some(v.frame_ordinal) {
+ current_frame = Some(v.frame_ordinal);
+ parent_at_depth.clear();
+ }
+ let emit = only_frame.is_none_or(|frame| frame == v.frame_ordinal);
let indent = " ".repeat(v.depth);
// Resolve parent: walk parent_at_depth from v.depth-1 down to 0.
let parent_element_index = if v.depth == 0 {
@@ -832,6 +995,12 @@ fn render(visited: &[Visited<'_>]) -> (String, Vec<AtspiNode>) {
};
if is_indexable(v) {
+ if !emit {
+ // Consume the index without emitting: indices stay aligned with
+ // the application-wide walk the actuators perform.
+ idx += 1;
+ continue;
+ }
let act_str = v.actions.join(",");
let val_part = match &v.value {
Some(val) if !val.is_empty() => format!(" value=\"{val}\""),
@@ -871,7 +1040,7 @@ fn render(visited: &[Visited<'_>]) -> (String, Vec<AtspiNode>) {
parent_at_depth[deeper] = None;
}
idx += 1;
- } else if !v.name.is_empty() {
+ } else if emit && !v.name.is_empty() {
md.push_str(&format!(
"{indent}- {role} = \"{name}\"\n",
role = v.role,
@@ -953,7 +1122,19 @@ fn is_indexable_capabilities(
pub fn walk_tree(pid: u32) -> Result<Option<(String, Vec<AtspiNode>)>> {
walk_tree_bounded(pid, 0, None, None)
- .map(|snapshot| snapshot.map(|(markdown, nodes, _)| (markdown, nodes)))
+ .map(|snapshot| snapshot.map(|walked| (walked.markdown, walked.nodes)))
+}
+
+/// One accessibility snapshot, plus whether it was provably narrowed to the
+/// caller's window.
+pub struct WalkedTree {
+ pub markdown: String,
+ pub nodes: Vec<AtspiNode>,
+ pub bounds: Vec<(usize, i32, i32, u32, u32)>,
+ /// True when a non-zero `xid` was resolved to exactly one application
+ /// top-level and the snapshot contains only that window's nodes. False
+ /// means the snapshot spans every window the application publishes.
+ pub window_scoped: bool,
}
/// Walk the AT-SPI tree with caller-supplied node + depth caps.
@@ -964,7 +1145,7 @@ pub fn walk_tree_bounded(
xid: u64,
max_elements: Option<usize>,
max_depth: Option<usize>,
-) -> Result<Option<(String, Vec<AtspiNode>, Vec<(usize, i32, i32, u32, u32)>)>> {
+) -> Result<Option<WalkedTree>> {
walk_tree_bounded_with_timeout(pid, xid, max_elements, max_depth, OP_TIMEOUT)
}
@@ -974,7 +1155,7 @@ pub(super) fn walk_tree_bounded_with_timeout(
max_elements: Option<usize>,
max_depth: Option<usize>,
timeout: Duration,
-) -> Result<Option<(String, Vec<AtspiNode>, Vec<(usize, i32, i32, u32, u32)>)>> {
+) -> Result<Option<WalkedTree>> {
runtime().block_on(async {
// Tree traversal and bounds collection form one snapshot. Keep one
// deadline for both phases so a dead AT-SPI peer cannot outlive the
@@ -982,19 +1163,19 @@ pub(super) fn walk_tree_bounded_with_timeout(
let deadline = tokio::time::Instant::now() + timeout;
let walk = async {
let conn = shared_connection().await?;
- collect_visited_bounded(conn, pid, max_elements, max_depth).await
+ collect_visited_bounded(conn, pid, xid, max_elements, max_depth).await
};
- let visited = match before_snapshot_deadline(deadline, walk).await {
+ let walked = match before_snapshot_deadline(deadline, walk).await {
Ok(result) => result?,
Err(_) => {
dlog!("walk_tree timed out for pid {pid}");
return Ok(None);
}
};
- let Some(visited) = visited else {
+ let Some((visited, scoped_frame)) = walked else {
return Ok(None);
};
- let (markdown, nodes) = render(&visited);
+ let (markdown, nodes) = render(&visited, scoped_frame);
let bounds = match before_snapshot_deadline(
deadline,
element_bounds_for_visited(&visited, pid, xid),
@@ -1007,7 +1188,24 @@ pub(super) fn walk_tree_bounded_with_timeout(
Vec::new()
}
};
- Ok(Some((markdown, nodes, bounds)))
+ // Bounds are keyed by the application-wide element index, so drop the
+ // entries for windows this snapshot no longer shows.
+ let bounds = if scoped_frame.is_some() {
+ let emitted: std::collections::HashSet<usize> =
+ nodes.iter().filter_map(|node| node.element_index).collect();
+ bounds
+ .into_iter()
+ .filter(|(index, ..)| emitted.contains(index))
+ .collect()
+ } else {
+ bounds
+ };
+ Ok(Some(WalkedTree {
+ markdown,
+ nodes,
+ bounds,
+ window_scoped: scoped_frame.is_some(),
+ }))
})
}
@@ -2703,6 +2901,109 @@ async fn element_bounds_for_visited(
out
}
+#[cfg(test)]
+mod frame_correlation_tests {
+ use super::{correlate_frame_to_window, FRAME_MATCH_TOLERANCE_PX};
+ use crate::x11::WindowInfo;
+
+ fn window(x: i32, y: i32, width: u32, height: u32) -> WindowInfo {
+ WindowInfo {
+ xid: 4242,
+ pid: Some(99),
+ app_name: "Google-chrome".to_owned(),
+ title: "Cua - Google Chrome".to_owned(),
+ is_on_screen: true,
+ z_index: Some(3),
+ x,
+ y,
+ width,
+ height,
+ }
+ }
+
+ /// The configuration that made the existing-profile route unreachable: one
+ /// browser process publishing three windows.
+ #[test]
+ fn picks_the_frame_matching_the_named_window_among_siblings() {
+ let candidates = [
+ (0usize, (144, 51, 1244, 953)),
+ (1, (438, 80, 1050, 953)),
+ (2, (550, 225, 500, 584)),
+ ];
+ assert_eq!(
+ correlate_frame_to_window(&candidates, &window(438, 80, 1050, 953)),
+ Some(1)
+ );
+ assert_eq!(
+ correlate_frame_to_window(&candidates, &window(550, 225, 500, 584)),
+ Some(2)
+ );
+ }
+
+ /// Server-side decorations shift a frame's reported origin; a small offset
+ /// must still resolve rather than fall back to an application-wide walk.
+ #[test]
+ fn tolerates_decoration_offsets() {
+ let candidates = [(0usize, (440, 108, 1050, 925)), (1, (144, 51, 1244, 953))];
+ assert_eq!(
+ correlate_frame_to_window(&candidates, &window(438, 80, 1050, 953)),
+ Some(0)
+ );
+ }
+
+ /// Two windows of the same geometry cannot be told apart this way, and the
+ /// caller needs a refusal rather than a coin flip.
+ #[test]
+ fn refuses_when_two_frames_are_equally_plausible() {
+ let candidates = [(0usize, (438, 80, 1050, 953)), (1, (438, 80, 1050, 953))];
+ assert_eq!(
+ correlate_frame_to_window(&candidates, &window(438, 80, 1050, 953)),
+ None
+ );
+ }
+
+ #[test]
+ fn refuses_when_no_frame_is_close_enough() {
+ let candidates = [(0usize, (0, 0, 200, 200))];
+ assert_eq!(
+ correlate_frame_to_window(&candidates, &window(438, 80, 1050, 953)),
+ None
+ );
+ }
+
+ #[test]
+ fn refuses_when_the_application_publishes_no_frame_extents() {
+ assert_eq!(
+ correlate_frame_to_window(&[], &window(438, 80, 1050, 953)),
+ None
+ );
+ }
+
+ /// Zero-area extents are what a frame reports before it has been mapped;
+ /// they must never be treated as a match for a real window.
+ #[test]
+ fn ignores_frames_without_usable_extents() {
+ let candidates = [(0usize, (0, 0, 0, 0)), (1, (438, 80, 1050, 953))];
+ assert_eq!(
+ correlate_frame_to_window(&candidates, &window(438, 80, 1050, 953)),
+ Some(1)
+ );
+ }
+
+ /// Being the only candidate is not evidence of correspondence. (The walk
+ /// does short-circuit a genuinely single-top-level application before it
+ /// reaches this function — see `resolve_window_frame`.)
+ #[test]
+ fn a_sole_candidate_still_has_to_be_close_enough() {
+ let far_away = i32::try_from(FRAME_MATCH_TOLERANCE_PX).unwrap() + 500;
+ let candidates = [(0usize, (far_away, far_away, 1050, 953))];
+ assert_eq!(
+ correlate_frame_to_window(&candidates, &window(438, 80, 1050, 953)),
+ None
+ );
+ }
+}
+
#[cfg(test)]
mod coord_tests {
use super::parse_gtk_frame_extents;
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
index 9e29eaa6a6..6ad9713d20 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
@@ -762,16 +762,16 @@ impl BrowserPlatform for LinuxBrowserPlatform {
"the approved browser pid is outside the Linux process-id range",
)
})?;
- if self
- .is_only_exact_native_window(request.pid, request.window_id)
- .await?
- != Some(true)
- {
- return Err(refusal(
- BrowserRefusalCode::BrowserBindingAmbiguous,
- "existing-profile setup on Linux requires exactly one PID-owned native window; generic Wayland and multi-window processes are refused",
- ));
- }
+ // Window cardinality is deliberately NOT a precondition here. Setup acts
+ // inside one named window, and `browser_setup_ui` proves that window's
+ // identity directly by resolving the native window to exactly one
+ // accessibility top-level before it matches or actuates any control. A
+ // process owning several windows is the ordinary case for a browser and
+ // says nothing about whether the driver can act precisely; refusing on
+ // it made the whole existing-profile route unreachable for most real
+ // sessions. Where identity genuinely cannot be established — a generic
+ // Wayland session with no compositor window list — that same proof fails
+ // and setup refuses with a reason that names the cause.
let window_id = request.window_id;
let listeners_before =
tokio::task::spawn_blocking(move || loopback_ports_for_pid(request.pid))
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
index 171240b152..237fbe57d4 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
@@ -97,39 +97,6 @@ fn exact_setup_checkbox<'a>(
}
}
-fn exact_setup_navigation<'a>(
- nodes: &'a [AtspiNode],
- descriptor: &BrowserSetupDescriptor,
-) -> Result<Option<&'a AtspiNode>, BrowserRefusal> {
- let exact_page = nodes.iter().any(|node| {
- role_is(node, &["document web", "document frame"])
- && descriptor
- .page_titles
- .iter()
- .any(|title| field_equals(node, title))
- });
- if !exact_page {
- return Ok(None);
- }
- let matches = nodes
- .iter()
- .filter(|node| {
- role_is(node, &["push button", "button"])
- && field_equals(node, descriptor.page_heading)
- && !node.actions.is_empty()
- && node.element_index.is_some()
- })
- .collect::<Vec<_>>();
- match matches.as_slice() {
- [] => Ok(None),
- [node] => Ok(Some(*node)),
- _ => Err(refusal(
- BrowserRefusalCode::BrowserWrongTargetRefused,
- "multiple exact remote-debugging navigation controls were exposed",
- )),
- }
-}
-
fn setup_not_ready_message(descriptor: &BrowserSetupDescriptor) -> String {
format!(
"the exact {} remote-debugging setup page did not become ready; on Linux, existing-profile setup requires the browser's complete AT-SPI tree (launch Chromium-family browsers with --force-renderer-accessibility, or use a screen reader that enables full renderer accessibility)",
@@ -165,56 +132,224 @@ fn close_tab(pid: u32, window_id: u64) -> anyhow::Result<()> {
})
}
-fn trusted_keyboard_setup_navigation(
+/// The exact address-and-search field of the approved window, or `None` while
+/// the freshly created tab has not exposed one yet. More than one is refused:
+/// the field is where the setup URL is about to be written, so the wrong pick
+/// navigates a surface the caller never approved.
+fn exact_omnibox<'a>(
+ nodes: &'a [AtspiNode],
+ descriptor: &BrowserSetupDescriptor,
+) -> Result<Option<&'a AtspiNode>, BrowserRefusal> {
+ let matches = nodes
+ .iter()
+ .filter(|node| {
+ role_is(node, &["entry", "text"])
+ && field_equals(node, "Address and search bar")
+ && node.element_index.is_some()
+ })
+ .collect::<Vec<_>>();
+ match matches.as_slice() {
+ [] => Ok(None),
+ [node] => Ok(Some(*node)),
+ _ => Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ format!(
+ "{} exposed multiple exact address-and-search fields",
+ descriptor.product_name
+ ),
+ )),
+ }
+}
+
+/// Whether the omnibox currently holds exactly the fixed setup URL.
+fn omnibox_holds_setup_url(node: &AtspiNode, descriptor: &BrowserSetupDescriptor) -> bool {
+ node.value
+ .as_deref()
+ .or(node.name.as_deref())
+ .is_some_and(|value| value.trim().eq_ignore_ascii_case(descriptor.setup_url))
+}
+
+/// Navigate the approved window to its fixed setup page.
+///
+/// This mirrors the macOS and Windows adapters rather than synthesizing the URL
+/// keystroke by keystroke: write the whole URL into the address field through
+/// the accessibility API, read it back to prove it landed, and only then commit
+/// with a single Enter. `set_text_contents` is the AT-SPI counterpart of UIA's
+/// `ValuePattern::SetValue` and AppKit's `AXValue`.
+///
+/// Per-character synthesis was the wrong primitive here. XTEST keysym lookup is
+/// keyboard-layout dependent and wlroots virtual-keyboard seats drop
+/// punctuation, so `chrome://inspect` could arrive as `inspect` — which the
+/// omnibox treats as a search term, silently navigating to a search-engine
+/// results page. Nothing downstream could tell that apart from a slow-loading
+/// setup page, so the flow reported a readiness timeout while leaving the user
+/// on someone else's website. Writing the value whole removes the layout
+/// dependency, and the read-back turns any residual mangling into an immediate,
+/// accurate refusal.
+fn trusted_setup_navigation(
pid: u32,
window_id: u64,
descriptor: &BrowserSetupDescriptor,
) -> anyhow::Result<()> {
- let (base, _fragment) = descriptor
- .setup_url
- .split_once("/#")
- .ok_or_else(|| anyhow::anyhow!("the fixed setup URL has no /# delimiter"))?;
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some();
+
+ // A fresh tab, so the setup page never displaces a page the user was on.
+ // `ctrl+l` then focuses the address field. Both are single letters, so
+ // neither depends on the keyboard layout the way punctuation does.
+ let focus_omnibox = || -> anyhow::Result<()> {
+ with_target_foreground(pid, window_id, || {
+ if wayland {
+ crate::wayland::hotkey_focused(&["ctrl".to_owned(), "l".to_owned()])
+ } else {
+ crate::input::send_key_xtest("l", &["ctrl"])
+ }
+ })
+ };
+
with_target_foreground(pid, window_id, || {
if wayland {
- crate::wayland::hotkey_focused(&["ctrl".to_owned(), "t".to_owned()])?;
- std::thread::sleep(Duration::from_millis(100));
- crate::wayland::hotkey_focused(&["ctrl".to_owned(), "l".to_owned()])?;
- crate::wayland::type_text_then_key_focused(base, "enter")
+ crate::wayland::hotkey_focused(&["ctrl".to_owned(), "t".to_owned()])
} else {
- crate::input::send_key_xtest("t", &["ctrl"])?;
- std::thread::sleep(Duration::from_millis(100));
- crate::input::send_key_xtest("l", &["ctrl"])?;
- crate::input::send_type_text_xtest(base)?;
- crate::input::send_key_xtest("enter", &[])
+ crate::input::send_key_xtest("t", &["ctrl"])
}
})?;
+ std::thread::sleep(Duration::from_millis(100));
+ focus_omnibox()?;
- // Avoid keyboard-layout-dependent `/#` synthesis on X11 and punctuation
- // loss on fresh wlroots virtual-keyboard seats. Open the fixed base page,
- // then invoke its unique semantic navigation control in the exact PID.
+ // Wait for the new tab to publish its address field before writing to it.
let deadline = Instant::now() + EXISTING_PROFILE_SETUP_READY_TIMEOUT;
loop {
- let tree = crate::atspi::walk_tree(pid, window_id, None);
- let navigation = exact_setup_navigation(&tree.nodes, descriptor)
- .map_err(|error| anyhow::anyhow!(error.message))?;
- match navigation {
- Some(node) => {
- return crate::atspi::perform_action(
- pid,
- node.element_index.expect("actionable navigation index"),
- )
- .map(|_| ())
- }
- None if Instant::now() < deadline => {
- std::thread::sleep(Duration::from_millis(100));
- }
- None => anyhow::bail!(
- "the exact {} setup navigation control did not become ready",
+ let tree =
+ window_scoped_tree(pid, window_id).map_err(|error| anyhow::anyhow!(error.message))?;
+ if exact_omnibox(&tree.nodes, descriptor)
+ .map_err(|error| anyhow::anyhow!(error.message))?
+ .is_some()
+ {
+ break;
+ }
+ if Instant::now() >= deadline {
+ anyhow::bail!(
+ "the approved {} window never exposed an exact address-and-search field",
descriptor.product_name
- ),
+ );
}
+ std::thread::sleep(Duration::from_millis(150));
}
+
+ // Transfer the URL through the clipboard rather than the keyboard.
+ //
+ // Chromium's AT-SPI bridge does not honour EditableText writes on the
+ // omnibox, so the accessibility set-value that macOS (`AXValue`) and
+ // Windows (`ValuePattern::SetValue`) rely on has no working counterpart
+ // here. A paste keeps the property that actually matters: the exact string
+ // arrives in one operation, with no per-keysym synthesis to be mistranslated
+ // by the active layout or dropped by a virtual-keyboard seat. `ctrl+a` and
+ // `ctrl+v` are plain letters, so they carry no layout dependency of their own.
+ use cua_driver_core::clipboard::ClipboardBackend;
+ let clipboard = crate::clipboard::LinuxClipboard::new();
+ let restore = clipboard.read_text().ok().flatten();
+ clipboard
+ .write_text(descriptor.setup_url.to_owned())
+ .map_err(|error| anyhow::anyhow!("could not stage the fixed setup URL: {error}"))?;
+ let paste = with_target_foreground(pid, window_id, || {
+ if wayland {
+ crate::wayland::hotkey_focused(&["ctrl".to_owned(), "a".to_owned()])?;
+ std::thread::sleep(Duration::from_millis(60));
+ crate::wayland::hotkey_focused(&["ctrl".to_owned(), "v".to_owned()])
+ } else {
+ crate::input::send_key_xtest("a", &["ctrl"])?;
+ std::thread::sleep(Duration::from_millis(60));
+ crate::input::send_key_xtest("v", &["ctrl"])
+ }
+ });
+ // The user's clipboard is theirs; put it back whether or not the paste took.
+ std::thread::sleep(Duration::from_millis(120));
+ if let Some(previous) = restore {
+ let _ = clipboard.write_text(previous);
+ }
+ paste?;
+
+ // Commit. Enter is the one synthesized keystroke left, and it carries no
+ // layout dependency.
+ with_target_foreground(pid, window_id, || {
+ if wayland {
+ crate::wayland::hotkey_focused(&["enter".to_owned()])
+ } else {
+ crate::input::send_key_xtest("enter", &[])
+ }
+ })?;
+
+ // Verify the destination, not the input. Chromium exposes no readable text
+ // on its omnibox over AT-SPI — no Value interface and no Text content even
+ // while the field holds a URL — so the read-back that the Windows and macOS
+ // adapters perform against the address field has no counterpart here.
+ // Proving the tab actually arrived at the fixed setup page is the stronger
+ // check anyway: it fails for a mistyped URL, a hijacked search, and a
+ // redirect alike, and it names what was reached instead of timing out.
+ let deadline = Instant::now() + EXISTING_PROFILE_SETUP_READY_TIMEOUT;
+ loop {
+ let tree =
+ window_scoped_tree(pid, window_id).map_err(|error| anyhow::anyhow!(error.message))?;
+ if tree.nodes.iter().any(|node| {
+ role_is(node, &["document web", "document frame"])
+ && descriptor
+ .page_titles
+ .iter()
+ .any(|title| field_equals(node, title))
+ }) {
+ return Ok(());
+ }
+ if Instant::now() >= deadline {
+ let landed = tree
+ .nodes
+ .iter()
+ .find(|node| role_is(node, &["document web", "document frame"]))
+ .and_then(|node| node.name.clone())
+ .unwrap_or_else(|| "no document".to_owned());
+ anyhow::bail!(
+ "the approved {} window did not reach its fixed setup page; it is showing {:?}. \
+ The address field is written through the clipboard, so this means the browser \
+ rejected or redirected the URL rather than that a keystroke was dropped",
+ descriptor.product_name,
+ landed
+ );
+ }
+ std::thread::sleep(Duration::from_millis(150));
+ }
+}
+
+/// Walk the target window's accessibility tree, refusing unless the snapshot is
+/// provably confined to that one window.
+///
+/// AT-SPI publishes a single tree per process, so a browser showing several
+/// windows exposes all of their controls together — including one "Allow remote
+/// debugging for this browser instance" checkbox per open setup page. Matching a
+/// control by label across that tree can therefore find a control the caller did
+/// not name. Requiring proven window scope is what makes the exact-window
+/// contract real rather than assumed.
+fn window_scoped_tree(
+ pid: u32,
+ window_id: u64,
+) -> Result<crate::atspi::AtspiTreeResult, BrowserRefusal> {
+ let tree = crate::atspi::walk_tree(pid, window_id, None);
+ if !tree.trusted {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ "no trusted AT-SPI tree for the approved browser window; \
+ the accessibility bus must be reachable to prove which window a control belongs to",
+ ));
+ }
+ if !tree.window_scoped {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserBindingAmbiguous,
+ format!(
+ "could not prove which of pid {pid}'s accessibility top-levels renders window \
+ {window_id}, so a matched control cannot be attributed to the approved window; \
+ relaunch the browser with --remote-debugging-port to skip setup entirely"
+ ),
+ ));
+ }
+ Ok(tree)
}
pub struct SetupUiHandle {
@@ -361,7 +496,7 @@ pub fn enable(
window_id: u64,
descriptor: &'static BrowserSetupDescriptor,
) -> Result<SetupUiHandle, BrowserRefusal> {
- let initial = crate::atspi::walk_tree(pid, window_id, None);
+ let initial = window_scoped_tree(pid, window_id)?;
let initial_checkbox = exact_setup_checkbox(&initial.nodes, descriptor, false)?;
let mut handle = if initial_checkbox.is_some() {
SetupUiHandle {
@@ -391,7 +526,7 @@ pub fn enable(
foregrounded_window: true,
injected_global_input: true,
};
- if let Err(error) = trusted_keyboard_setup_navigation(pid, window_id, descriptor) {
+ if let Err(error) = trusted_setup_navigation(pid, window_id, descriptor) {
return Err(handle.abort(refusal(
BrowserRefusalCode::BrowserWrongTargetRefused,
format!(
@@ -405,7 +540,10 @@ pub fn enable(
let deadline = Instant::now() + EXISTING_PROFILE_SETUP_READY_TIMEOUT;
loop {
- let tree = crate::atspi::walk_tree(pid, window_id, None);
+ let tree = match window_scoped_tree(pid, window_id) {
+ Ok(tree) => tree,
+ Err(error) => return Err(handle.abort(error)),
+ };
match exact_setup_checkbox(&tree.nodes, descriptor, handle.trusted_setup_navigation) {
Ok(Some(node)) => match node.checked {
Some(true) => {
@@ -604,27 +742,58 @@ mod tests {
assert!(message.contains("--force-renderer-accessibility"));
}
+ fn omnibox(value: Option<&str>) -> AtspiNode {
+ node("entry", "Address and search bar", value, &["activate"])
+ }
+
#[test]
- fn setup_navigation_requires_one_actionable_control_on_the_exact_page() {
+ fn omnibox_selection_is_exact_or_refused() {
let nodes = vec![
- node("document web", descriptor().page_titles[0], None, &[]),
- node("push button", descriptor().page_heading, None, &["press"]),
- node("heading", descriptor().page_heading, None, &[]),
+ node("push button", "Reload", None, &["press"]),
+ omnibox(Some("about:blank")),
];
- assert!(exact_setup_navigation(&nodes, descriptor())
- .unwrap()
- .is_some());
- assert!(exact_setup_navigation(&nodes[1..], descriptor())
- .unwrap()
- .is_none());
+ assert!(exact_omnibox(&nodes, descriptor()).unwrap().is_some());
+ assert!(exact_omnibox(&nodes[..1], descriptor()).unwrap().is_none());
+ // Two address fields means two candidate destinations; writing the
+ // setup URL into a guess could navigate a surface nobody approved.
let mut ambiguous = nodes;
- ambiguous.push(node(
- "push button",
- descriptor().page_heading,
- None,
- &["press"],
+ ambiguous.push(omnibox(None));
+ assert!(exact_omnibox(&ambiguous, descriptor()).is_err());
+ }
+
+ /// The regression that motivated the rewrite: XTEST dropped characters and
+ /// `chrome://inspect` reached the omnibox as `inspect`, which Chrome
+ /// submitted as a search query. The read-back has to reject that before it
+ /// is ever committed.
+ #[test]
+ fn partially_applied_setup_url_is_not_accepted() {
+ assert!(!omnibox_holds_setup_url(
+ &omnibox(Some("inspect")),
+ descriptor()
+ ));
+ assert!(!omnibox_holds_setup_url(
+ &omnibox(Some("chrome://inspect")),
+ descriptor()
+ ));
+ assert!(!omnibox_holds_setup_url(&omnibox(None), descriptor()));
+ assert!(!omnibox_holds_setup_url(
+ &omnibox(Some("https://www.google.com/search?q=inspect")),
+ descriptor()
+ ));
+ }
+
+ #[test]
+ fn fully_applied_setup_url_is_accepted() {
+ assert!(omnibox_holds_setup_url(
+ &omnibox(Some(descriptor().setup_url)),
+ descriptor()
+ ));
+ // Chromium reports the omnibox value with surrounding whitespace on
+ // some toolkit versions, and case is not significant in a scheme.
+ assert!(omnibox_holds_setup_url(
+ &omnibox(Some(" CHROME://inspect/#remote-debugging ")),
+ descriptor()
));
- assert!(exact_setup_navigation(&ambiguous, descriptor()).is_err());
}
}