Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): bound Linux snapshots after app exit (#2822)
Saatvik Aryad1c5a7a90b23
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rsindex f612f27ad0..e753251960 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs@@ -238,6 +238,86 @@ fn run_case(case: CaseSpec, test: impl FnOnce(u32, u64, &mut McpDriver) -> Obser});}+#[test]+#[ignore]+fn harness_gtk3_rejects_exited_target_and_recovers_with_fresh_app() {+ let case: CaseSpec = native_readonly_case(+ "gtk3",+ "stale_target_recovery",+ Targeting::Ax,+ DriverRoute::AxRead,+ vec![OracleKind::AxState],+ );+ let cell_id = case.cell_id.clone();+ execute_case(case, |evidence| {+ let mut driver = McpDriver::spawn_named(&cell_id).expect("start source-built Linux driver");+ *evidence = recording_evidence(driver.recording_dir());+ let (stale_pid, stale_window_id) = launch(&mut driver);+ assert!(+ !snapshot(&mut driver, stale_pid, stale_window_id).is_error(),+ "initial GTK3 snapshot failed"+ );++ let killed = driver.call("kill_app", serde_json::json!({ "pid": stale_pid as i64 }));+ assert!(!killed.is_error(), "kill_app failed: {}", killed.text());++ let exit_deadline = Instant::now() + Duration::from_secs(5);+ while Instant::now() < exit_deadline {+ let windows = driver.call(+ "list_windows",+ serde_json::json!({ "pid": stale_pid as i64 }),+ );+ let still_listed = windows.structured()["windows"]+ .as_array()+ .is_some_and(|windows| !windows.is_empty());+ if !still_listed {+ break;+ }+ std::thread::sleep(Duration::from_millis(50));+ }++ let started = Instant::now();+ let stale = driver.call(+ "get_window_state",+ serde_json::json!({+ "pid": stale_pid as i64,+ "window_id": stale_window_id,+ "include_screenshot": false+ }),+ );+ assert!(+ stale.is_error(),+ "exited target unexpectedly snapshot: {}",+ stale.text()+ );+ assert!(+ stale.text().contains("stale or no longer running"),+ "unexpected stale-target error: {}",+ stale.text()+ );+ assert!(+ started.elapsed() < Duration::from_secs(1),+ "stale target did not fail fast: {:?}",+ started.elapsed()+ );++ let (fresh_pid, fresh_window_id) = launch(&mut driver);+ driver.start_behavior_recording();+ let fresh = snapshot(&mut driver, fresh_pid, fresh_window_id);+ assert!(+ !fresh.is_error(),+ "fresh GTK3 snapshot failed: {}",+ fresh.text()+ );+ assert!(+ fresh.tree_text().contains("btn-increment"),+ "fresh GTK3 accessibility tree did not recover:\n{}",+ fresh.tree_text()+ );+ Observation::delivered(vec![OracleKind::AxState], Evidence::default())+ });+}+#[test]#[ignore]fn harness_gtk3_query_projects_structured_elements() {diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.tomlindex 61a0af8c9b..171ced08db 100644--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml@@ -132,6 +132,7 @@ portal-capture = [portal-libei = ["portal-input", "portal-capture"][dev-dependencies]+tokio = { workspace = true, features = ["test-util"] }# Used by the `screenshot_cascade` example to surface the# `tracing::debug!` lines emitted by each tier of the dispatch as it# falls through.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.rsindex 35fac5ca7c..8a326b20d2 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@@ -41,6 +41,13 @@ async fn call<T>(fut: impl std::future::Future<Output = T>) -> Option<T> {tokio::time::timeout(CALL_TIMEOUT, fut).await.ok()}+async fn before_snapshot_deadline<T>(+ deadline: tokio::time::Instant,+ work: impl std::future::Future<Output = T>,+) -> std::result::Result<T, tokio::time::error::Elapsed> {+ tokio::time::timeout_at(deadline, work).await+}+/// Drive an AT-SPI op `work` on the runtime, bounded by [`OP_TIMEOUT`].////// Individual interface calls are each bounded by [`call`], and `app_for_pid` /@@ -969,11 +976,15 @@ pub(super) fn walk_tree_bounded_with_timeout(timeout: Duration,) -> Result<Option<(String, Vec<AtspiNode>, Vec<(usize, i32, i32, u32, u32)>)>> {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+ // operation timeout while resolving geometry.+ 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};- let visited = match tokio::time::timeout(timeout, walk).await {+ let visited = match before_snapshot_deadline(deadline, walk).await {Ok(result) => result?,Err(_) => {dlog!("walk_tree timed out for pid {pid}");@@ -984,7 +995,18 @@ pub(super) fn walk_tree_bounded_with_timeout(return Ok(None);};let (markdown, nodes) = render(&visited);- let bounds = element_bounds_for_visited(&visited, pid, xid).await;+ let bounds = match before_snapshot_deadline(+ deadline,+ element_bounds_for_visited(&visited, pid, xid),+ )+ .await+ {+ Ok(bounds) => bounds,+ Err(_) => {+ dlog!("element bounds timed out for pid {pid}");+ Vec::new()+ }+ };Ok(Some((markdown, nodes, bounds)))})}@@ -2685,12 +2707,13 @@ async fn element_bounds_for_visited(mod coord_tests {use super::parse_gtk_frame_extents;use super::{- activation_index, combine_wayland_content_offsets, is_activation_action, is_enabled_state,- is_indexable_capabilities, is_passive_role, is_web_process_bus,- prefer_authoritative_wayland_origin, rebase_renderer_window_offset, screen_extent_rebase,- select_click_target, ApplicationSelection,+ activation_index, before_snapshot_deadline, combine_wayland_content_offsets,+ is_activation_action, is_enabled_state, is_indexable_capabilities, is_passive_role,+ is_web_process_bus, prefer_authoritative_wayland_origin, rebase_renderer_window_offset,+ screen_extent_rebase, select_click_target, ApplicationSelection,};use atspi::{State, StateSet};+ use std::time::Duration;#[test]fn duplicate_pid_prefers_populated_application_after_empty_registration() {@@ -2746,6 +2769,20 @@ mod coord_tests {assert_eq!(selection.into_selected(), Err(2));}+ #[tokio::test(start_paused = true)]+ async fn one_absolute_deadline_spans_traversal_and_bounds() {+ let deadline = tokio::time::Instant::now() + Duration::from_millis(100);++ before_snapshot_deadline(deadline, tokio::time::sleep(Duration::from_millis(60)))+ .await+ .expect("traversal should fit the shared budget");+ before_snapshot_deadline(deadline, tokio::time::sleep(Duration::from_millis(60)))+ .await+ .expect_err("bounds must receive only the traversal's remaining budget");++ assert_eq!(tokio::time::Instant::now(), deadline);+ }+#[test]fn operable_nodes_are_addressable() {assert!(is_indexable_capabilities(diff --git a/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rs b/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rsindex d1bd686f35..0935afa975 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rs@@ -13,6 +13,30 @@ pub struct ProcessInfo {pub cmdline: String,}+fn is_process_live_state(status: &str) -> bool {+ status+ .lines()+ .find_map(|line| {+ line.strip_prefix("State:")+ .and_then(|state| state.trim().chars().next())+ })+ .is_some_and(|state| !matches!(state, 'Z' | 'X'))+}++/// Return whether a PID still represents a live process.+///+/// A zombie remains visible under `/proc` until its parent reaps it, so an+/// existence check alone is not enough for callers that may query AT-SPI or+/// X11 state for the process. Treat zombies and dead processes as gone.+pub fn is_process_live(pid: u32) -> bool {+ let status = match fs::read_to_string(format!("/proc/{pid}/status")) {+ Ok(status) => status,+ Err(_) => return false,+ };++ is_process_live_state(&status)+}+/// Return all running processes by reading /proc/<pid>/status.pub fn list_processes() -> Vec<ProcessInfo> {let mut result = Vec::new();@@ -36,6 +60,10 @@ pub fn list_processes() -> Vec<ProcessInfo> {Err(_) => continue,};+ if !is_process_live_state(&status) {+ continue;+ }+let proc_name = status.lines().find(|l| l.starts_with("Name:"))@@ -62,3 +90,53 @@ pub fn list_processes() -> Vec<ProcessInfo> {result.sort_by_key(|p| p.pid);result}++#[cfg(test)]+mod tests {+ #[test]+ fn process_states_fail_closed() {+ assert!(super::is_process_live_state(+ "Name:\ttest\nState:\tR (running)\n"+ ));+ assert!(super::is_process_live_state("State:\tS (sleeping)"));+ assert!(!super::is_process_live_state("State:\tZ (zombie)"));+ assert!(!super::is_process_live_state("State:\tX (dead)"));+ assert!(!super::is_process_live_state("Name:\ttest\n"));+ assert!(!super::is_process_live_state("State:\t"));+ }++ #[test]+ fn real_zombie_is_not_live_and_disappears_after_reaping() {+ let child = unsafe { libc::fork() };+ assert!(+ child >= 0,+ "fork failed: {}",+ std::io::Error::last_os_error()+ );+ if child == 0 {+ unsafe { libc::_exit(0) };+ }++ let pid = child as u32;+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);+ let mut observed_zombie = false;+ while std::time::Instant::now() < deadline {+ if std::fs::read_to_string(format!("/proc/{pid}/status"))+ .ok()+ .is_some_and(|status| status.contains("State:\tZ"))+ {+ observed_zombie = true;+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ let live_while_zombie = super::is_process_live(pid);+ let mut status = 0;+ let reaped = unsafe { libc::waitpid(child, &mut status, 0) };++ assert!(observed_zombie, "child never entered zombie state");+ assert!(!live_while_zombie, "zombie pid was reported live");+ assert_eq!(reaped, child, "failed to reap child");+ assert!(!super::is_process_live(pid), "reaped pid was reported live");+ }+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rsindex 966044b699..3710fe51ff 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs@@ -443,6 +443,9 @@ impl Tool for ListWindowsTool {tokio::task::spawn_blocking(move || crate::wayland::list_windows_dispatch(filter_pid)).await.unwrap_or_default();+ // Exited applications can remain visible in AT-SPI/X11 as zombies;+ // never return those stale targets to callers.+ windows.retain(|window| window.pid.map_or(true, crate::proc_fs::is_process_live));if on_screen_only {windows.retain(|window| window.is_on_screen);}@@ -662,6 +665,20 @@ impl Tool for GetWindowStateTool {.and_then(|v| v.as_u64()).map(|v| v.max(1) as usize);+ let process_is_live = crate::proc_fs::is_process_live(pid);+ let window_matches = if crate::wayland::is_wayland() {+ crate::wayland::list_windows_dispatch(Some(pid))+ .iter()+ .any(|window| window.xid == xid && window.pid == Some(pid))+ } else {+ crate::x11::window_belongs_to_pid(xid, pid)+ };+ if !process_is_live || !window_matches {+ return ToolResult::error(format!(+ "Window target pid {pid}, window_id {xid} is stale or no longer running; refresh list_windows."+ ));+ }+// Always walk the AT-SPI tree; capture the screenshot by default. The// tree+screenshot pair is the default so the agent grounds on both and// cross-checks the (sometimes-lying) tree against the frame — only thediff --git a/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rsindex 9bbe7f25cf..e276f8a443 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rs@@ -31,6 +31,25 @@ pub fn list_windows(filter_pid: Option<u32>) -> Vec<WindowInfo> {}}+/// Verify that an X11 window still exists and belongs to the requested process.+///+/// Checking `/proc/<pid>` alone is insufficient because Linux may recycle the+/// PID after the original application exits. The XID owner binds the two parts+/// of a `get_window_state` target and fails closed when either is stale.+pub fn window_belongs_to_pid(xid: u64, pid: u32) -> bool {+ let Ok(xid) = u32::try_from(xid) else {+ return false;+ };+ let Ok((conn, _)) = RustConnection::connect(None) else {+ return false;+ };+ window_owner_matches(get_window_pid(&conn, xid).ok().flatten(), pid)+}++fn window_owner_matches(owner: Option<u32>, requested_pid: u32) -> bool {+ owner == Some(requested_pid)+}+fn list_windows_inner(filter_pid: Option<u32>) -> Result<Vec<WindowInfo>> {let (conn, screen_num) = RustConnection::connect(None)?;let screen = &conn.setup().roots[screen_num];@@ -296,6 +315,13 @@ mod tests {assert_eq!(client_list_property(x11rb::NONE, &[]), None);}+ #[test]+ fn stale_or_reused_pid_window_owner_fails_closed() {+ assert!(window_owner_matches(Some(42), 42));+ assert!(!window_owner_matches(Some(43), 42));+ assert!(!window_owner_matches(None, 42));+ }+#[test]fn query_tree_fallback_only_lists_viewable_windows() {assert!(fallback_window_is_listable(MapState::VIEWABLE));