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): prevent Linux accessibility-bus deadlocks (#4903)

Ainesh Chatterjeee3ad8319a774
diff --git a/.github/workflows/ci-rust-linux.yml b/.github/workflows/ci-rust-linux.yml
index df6e476273..4baa26f7a4 100644
--- a/.github/workflows/ci-rust-linux.yml
+++ b/.github/workflows/ci-rust-linux.yml
@@ -145,7 +145,16 @@ jobs:
sudo apt-get install -y --no-install-recommends \
clang pkg-config libdbus-1-dev libpipewire-0.3-dev libspa-0.2-dev \
libei-dev libxkbcommon-dev libx11-dev libxi-dev libxtst-dev libxext-dev \
- imagemagick xvfb xauth x11-utils ffmpeg
+ imagemagick xvfb xauth x11-utils ffmpeg dbus-daemon
+ - name: Prove the AT-SPI connection graph excludes peer-to-peer
+ working-directory: libs/cua-driver/rust
+ run: |
+ set -euo pipefail
+ graph=$(cargo tree --locked -p cua-driver -e features -i atspi-connection --prefix none)
+ if grep -q '^atspi-connection feature "p2p"' <<<"$graph"; then
+ echo "::error::cua-driver resolves atspi-connection with its p2p feature; see the atspi-connection entry in crates/platform-linux/Cargo.toml"
+ exit 1
+ fi
- name: Run Linux Rust tests
working-directory: libs/cua-driver/rust
env:
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 707ed352b3..fad632ea9f 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -420,7 +420,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bf601cccedfffec598ec2db1f9d6745885458bccc0e8916d7023f017c94b3d0"
dependencies = [
"atspi-common",
- "atspi-connection",
"atspi-proxies",
"zbus",
]
@@ -1251,6 +1250,7 @@ dependencies = [
"ureq",
"uuid",
"windows 0.61.3",
+ "zbus",
"zeroize",
]
@@ -3528,6 +3528,7 @@ dependencies = [
"ashpd",
"async-trait",
"atspi",
+ "atspi-connection",
"base64",
"bitflags 2.11.1",
"calloop",
diff --git a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
index 8dc0840535..1ae75553a2 100644
--- a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
@@ -104,6 +104,12 @@ base64 = { workspace = true }
# never touch the developer's real `~/.cua-driver/version_check.json`.
tempfile = "3"
+[target.'cfg(target_os = "linux")'.dev-dependencies]
+# Private session and accessibility buses for the AT-SPI listener tests: the
+# test owns `org.a11y.Bus` and `org.a11y.atspi.Registry` itself and reads
+# the bus daemon's per-connection statistics.
+zbus = { version = "5", default-features = false, features = ["tokio"] }
+
[target.'cfg(target_os = "windows")'.dev-dependencies]
platform-windows = { path = "../platform-windows" }
windows = { version = "0.61", features = [
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/atspi_listener_startup_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/atspi_listener_startup_test.rs
index d538346e27..d3f7857076 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/atspi_listener_startup_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/atspi_listener_startup_test.rs
@@ -1,16 +1,55 @@
-//! Linux process-level readiness when AT-SPI accepts a connection but stalls.
+//! Linux process-level behavior of the AT-SPI listener against private buses:
+//! readiness when the bus accepts a connection but stalls, and liveness of the
+//! process-lifetime accessibility connection while applications come and go.
#![cfg(target_os = "linux")]
+use std::collections::HashMap;
+use std::io::BufRead;
use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::{
atomic::{AtomicBool, Ordering},
- Arc,
+ Arc, Mutex,
};
use std::time::{Duration, Instant};
-use cua_driver_testkit::{spawn_in_job, ChildReaper};
+use cua_driver_testkit::{
+ driver_binary_required, spawn_in_job, ChildReaper, IsolatedStateRoot, REQUIRE_DRIVER_BIN_ENV,
+};
+use zbus::message::Header;
+use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
+
+/// `cua-driver serve` on the private session bus at `session_bus_address`,
+/// with its per-user state under `state` (#4094). Keep `state` alive until the
+/// child is reaped.
+fn serve_command(
+ daemon_socket: &Path,
+ session_bus_address: &str,
+ state: &IsolatedStateRoot,
+) -> Command {
+ let mut command = Command::new(env!("CARGO_BIN_EXE_cua-driver"));
+ command
+ .args([
+ "serve",
+ "--socket",
+ daemon_socket.to_str().expect("UTF-8 daemon socket"),
+ "--no-overlay",
+ "--no-permissions-gate",
+ ])
+ .envs(state.env())
+ .env("DBUS_SESSION_BUS_ADDRESS", session_bus_address)
+ // A developer shell may export NO_AT_BRIDGE=1, which makes the driver
+ // skip AT-SPI startup entirely; these tests exist to exercise it.
+ .env_remove("NO_AT_BRIDGE")
+ .env("CUA_DRIVER_RS_DISABLE_A11Y_ADVERTISE", "1")
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped());
+ command
+}
#[test]
fn serve_binds_while_reachable_atspi_initialization_is_stalled() {
@@ -46,27 +85,14 @@ fn serve_binds_while_reachable_atspi_initialization_is_stalled() {
}
});
- let mut command = Command::new(env!("CARGO_BIN_EXE_cua-driver"));
- command
- .args([
- "serve",
- "--socket",
- daemon_socket.to_str().expect("UTF-8 daemon socket"),
- "--no-overlay",
- "--no-permissions-gate",
- ])
- .env(
- "DBUS_SESSION_BUS_ADDRESS",
- format!("unix:path={}", bus_path.display()),
- )
- .env("CUA_DRIVER_RS_DISABLE_A11Y_ADVERTISE", "1")
- .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
- .stdin(Stdio::null())
- .stdout(Stdio::null())
- .stderr(Stdio::piped());
-
+ let state = IsolatedStateRoot::new().expect("isolated driver state root");
let mut reaper = ChildReaper::new();
- let child = spawn_in_job(&mut command).expect("spawn cua-driver serve");
+ let child = spawn_in_job(&mut serve_command(
+ &daemon_socket,
+ &format!("unix:path={}", bus_path.display()),
+ &state,
+ ))
+ .expect("spawn cua-driver serve");
reaper.push(child);
let readiness_deadline = Instant::now() + Duration::from_secs(6);
@@ -89,3 +115,264 @@ fn serve_binds_while_reachable_atspi_initialization_is_stalled() {
"serve did not bind after the bounded AT-SPI readiness wait"
);
}
+
+/// Start one private `dbus-daemon` in `directory`, owned by `reaper`, and
+/// return its address. A missing binary skips the test, or panics under the
+/// same `CUA_TEST_REQUIRE_DRIVER_BIN=1` strictness CI applies to the driver
+/// binary. Explicit config: a sandbox (Nix) has no session.conf, and then the
+/// daemon exits without printing an address.
+fn start_private_bus(reaper: &mut ChildReaper, directory: &Path, name: &str) -> Option<String> {
+ let config = directory.join(format!("{name}-bus.conf"));
+ std::fs::write(
+ &config,
+ format!(
+ "<busconfig><type>session</type>\
+ <listen>unix:path={}</listen><auth>EXTERNAL</auth>\
+ <policy context=\"default\"><allow send_destination=\"*\" eavesdrop=\"true\"/>\
+ <allow eavesdrop=\"true\"/><allow own=\"*\"/></policy></busconfig>",
+ directory.join(format!("{name}-bus.sock")).display()
+ ),
+ )
+ .expect("write private bus config");
+ let mut command = Command::new("dbus-daemon");
+ command
+ .arg(format!("--config-file={}", config.display()))
+ .args(["--nofork", "--print-address=1"])
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null());
+ let mut child = match spawn_in_job(&mut command) {
+ Ok(child) => child,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ assert!(
+ !driver_binary_required(),
+ "dbus-daemon is not installed; {REQUIRE_DRIVER_BIN_ENV}=1 forbids skipping"
+ );
+ eprintln!("skipping: dbus-daemon is not installed");
+ return None;
+ }
+ Err(error) => panic!("private test bus: {error}"),
+ };
+ let mut address = String::new();
+ std::io::BufReader::new(child.stdout.take().expect("dbus-daemon stdout"))
+ .read_line(&mut address)
+ .expect("read private bus address");
+ reaper.push(child);
+ assert!(!address.trim().is_empty(), "dbus-daemon printed no address");
+ Some(address.trim().to_owned())
+}
+
+/// `org.a11y.Bus` on the private session bus: tells the driver where the
+/// private accessibility bus is.
+struct AccessibilityBusLauncher {
+ accessibility_bus_address: String,
+}
+
+#[zbus::interface(name = "org.a11y.Bus")]
+impl AccessibilityBusLauncher {
+ fn get_address(&self) -> String {
+ self.accessibility_bus_address.clone()
+ }
+}
+
+/// `org.a11y.atspi.Registry` on the private accessibility bus: remembers which
+/// connection registered for which event.
+struct Registry {
+ registrations: Arc<Mutex<Vec<(String, String)>>>,
+}
+
+#[zbus::interface(name = "org.a11y.atspi.Registry")]
+impl Registry {
+ fn register_event(&self, event: String, #[zbus(header)] header: Header<'_>) {
+ if let Some(sender) = header.sender() {
+ self.registrations
+ .lock()
+ .unwrap()
+ .push((sender.to_string(), event));
+ }
+ }
+}
+
+/// The registry's desktop root accessible, with no applications on it.
+struct DesktopRoot;
+
+#[zbus::interface(name = "org.a11y.atspi.Accessible")]
+impl DesktopRoot {
+ fn get_children(&self) -> Vec<(String, OwnedObjectPath)> {
+ Vec::new()
+ }
+}
+
+fn connect(address: &str) -> zbus::connection::Builder<'_> {
+ zbus::connection::Builder::address(address).expect("private bus address")
+}
+
+async fn connection_stats(bus: &zbus::Connection, name: &str) -> HashMap<String, OwnedValue> {
+ bus.call_method(
+ Some("org.freedesktop.DBus"),
+ "/org/freedesktop/DBus",
+ Some("org.freedesktop.DBus.Debug.Stats"),
+ "GetConnectionStats",
+ &(name,),
+ )
+ .await
+ .expect("GetConnectionStats (dbus-daemon built with statistics support)")
+ .body()
+ .deserialize()
+ .expect("decode connection statistics")
+}
+
+fn queued_messages(stats: &HashMap<String, OwnedValue>) -> u32 {
+ match stats.get("OutgoingMessages").map(|value| &**value) {
+ Some(Value::U32(count)) => *count,
+ other => panic!("OutgoingMessages missing from connection statistics: {other:?}"),
+ }
+}
+
+async fn match_rules(bus: &zbus::Connection, name: &str) -> Vec<String> {
+ let all: HashMap<String, Vec<String>> = bus
+ .call_method(
+ Some("org.freedesktop.DBus"),
+ "/org/freedesktop/DBus",
+ Some("org.freedesktop.DBus.Debug.Stats"),
+ "GetAllMatchRules",
+ &(),
+ )
+ .await
+ .expect("GetAllMatchRules (dbus-daemon built with statistics support)")
+ .body()
+ .deserialize()
+ .expect("decode match rules");
+ all.get(name).cloned().unwrap_or_default()
+}
+
+/// `object:state-changed:focused` for one accessible, as a toolkit emits it.
+fn focus_event(index: usize) -> zbus::Message {
+ let properties: HashMap<&str, Value<'_>> = HashMap::new();
+ zbus::Message::signal(
+ format!("/org/a11y/atspi/accessible/probe_{index}"),
+ "org.a11y.atspi.Event.Object",
+ "StateChanged",
+ )
+ .expect("focus event header")
+ .build(&("focused", 1_i32, 0_i32, Value::I32(0), properties))
+ .expect("focus event body")
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn accessibility_connection_keeps_draining_events_through_application_churn() {
+ let directory = tempfile::Builder::new()
+ .prefix("cua-atspi-churn-")
+ .tempdir_in("/tmp")
+ .expect("temporary churn-test directory");
+ let state = IsolatedStateRoot::new().expect("isolated driver state root");
+ let mut reaper = ChildReaper::new();
+ let Some(session_bus_address) = start_private_bus(&mut reaper, directory.path(), "session")
+ else {
+ return;
+ };
+ let accessibility_bus_address = start_private_bus(&mut reaper, directory.path(), "a11y")
+ .expect("second private bus starts once the first did");
+
+ let _session_bus = connect(&session_bus_address)
+ .name("org.a11y.Bus")
+ .expect("launcher name")
+ .serve_at(
+ "/org/a11y/bus",
+ AccessibilityBusLauncher {
+ accessibility_bus_address: accessibility_bus_address.clone(),
+ },
+ )
+ .expect("serve launcher")
+ .build()
+ .await
+ .expect("own org.a11y.Bus on the private session bus");
+ let registrations = Arc::new(Mutex::new(Vec::new()));
+ let accessibility_bus = connect(&accessibility_bus_address)
+ .name("org.a11y.atspi.Registry")
+ .expect("registry name")
+ .serve_at(
+ "/org/a11y/atspi/registry",
+ Registry {
+ registrations: registrations.clone(),
+ },
+ )
+ .expect("serve registry")
+ .serve_at("/org/a11y/atspi/accessible/root", DesktopRoot)
+ .expect("serve desktop root")
+ .build()
+ .await
+ .expect("own org.a11y.atspi.Registry on the private accessibility bus");
+
+ let daemon_socket = directory.path().join("driver.sock");
+ let child = spawn_in_job(&mut serve_command(
+ &daemon_socket,
+ &session_bus_address,
+ &state,
+ ))
+ .expect("spawn cua-driver serve");
+ reaper.push(child);
+
+ // The driver's unique name on the accessibility bus is the sender of its
+ // startup event registrations; its StateChanged match rule follows them.
+ let startup_deadline = Instant::now() + Duration::from_secs(15);
+ let driver = loop {
+ if let Some((sender, _)) = registrations.lock().unwrap().first().cloned() {
+ break sender;
+ }
+ assert!(
+ Instant::now() < startup_deadline,
+ "cua-driver never registered an AT-SPI event listener on the private accessibility bus"
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ };
+ loop {
+ let rules = match_rules(&accessibility_bus, &driver).await;
+ if rules
+ .iter()
+ .any(|rule| rule.contains("member='StateChanged'"))
+ {
+ break;
+ }
+ assert!(
+ Instant::now() < startup_deadline,
+ "cua-driver never subscribed to StateChanged on the accessibility bus: {rules:?}"
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+
+ // An application that joins the bus after the driver and never answers a
+ // method call (it serves no objects), then 100 applications appearing and
+ // leaving, then a burst of focus events for the driver's subscription.
+ let _silent_application = connect(&accessibility_bus_address)
+ .build()
+ .await
+ .expect("connect silent application");
+ for _ in 0..100 {
+ drop(
+ connect(&accessibility_bus_address)
+ .build()
+ .await
+ .expect("connect transient application"),
+ );
+ }
+ for index in 0..3000 {
+ accessibility_bus
+ .send(&focus_event(index))
+ .await
+ .expect("emit focus event");
+ }
+
+ let drain_deadline = Instant::now() + Duration::from_secs(5);
+ let queued = loop {
+ let queued = queued_messages(&connection_stats(&accessibility_bus, &driver).await);
+ if queued == 0 || Instant::now() >= drain_deadline {
+ break queued;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ };
+ assert_eq!(
+ queued, 0,
+ "{queued} messages stayed queued at the bus for cua-driver's accessibility connection: it stopped reading after application churn"
+ );
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
index e953271c8b..dfb5ec0fdc 100644
--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
@@ -39,12 +39,17 @@ libc = "0.2"
# subprocess bridge so accessibility input/readback needs no Python or GI
# typelibs at runtime. `tokio` matches the driver's async runtime; `zbus`
# re-exports the bus types we need (fdo::DBusProxy for pid resolution).
-# `p2p` (a default feature) opens a private socket to every application that
-# advertises one; LibreOffice advertises a socket its VCL main loop never
-# services, and the crate's peer bookkeeping then wedges every call on the
-# shared connection once LibreOffice registers. The session a11y bus is what
-# gdbus/pyatspi use and is the only route this crate takes.
-atspi = { version = "0.30", default-features = false, features = ["connection", "proxies", "wrappers", "tokio", "zbus"] }
+atspi = { version = "0.30", default-features = false, features = ["proxies", "wrappers", "tokio", "zbus"] }
+# Declared directly rather than through the facade's `connection` feature:
+# `atspi` forwards atspi-connection's default features, and `default-features
+# = false` on the facade does not reach them, so `p2p` stayed enabled. `p2p`
+# subscribes to every bus-name change and awaits a peer-discovery round trip
+# per application on the shared connection; 64 queued name changes stall the
+# socket reader and the connection never reads another event (#4894).
+# LibreOffice also advertises a private socket its VCL main loop never
+# services. The session a11y bus is what gdbus/pyatspi use and is the only
+# route this crate takes; the CI feature-graph guard keeps `p2p` out.
+atspi-connection = { version = "0.14", default-features = false, features = ["wrappers"] }
evdev = "0.12"
# Math-expression evaluator for parallel_mouse_drag `fn` paths (y = f(x)).
meval = "0.2"
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 10e9a52bd2..9b8bdf91c8 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
@@ -16,10 +16,10 @@ use std::sync::OnceLock;
use std::time::Duration;
use anyhow::{anyhow, Context, Result};
-use atspi::connection::AccessibilityConnection;
use atspi::proxy::accessible::AccessibleProxy;
use atspi::proxy::proxy_ext::ProxyExt;
use atspi::{CoordType, Interface, State, StateSet};
+use atspi_connection::AccessibilityConnection;
use super::{AtspiIdentity, AtspiNode};
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native/hit.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native/hit.rs
index 173d1af45b..8e7781c287 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native/hit.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native/hit.rs
@@ -11,6 +11,7 @@ use anyhow::Result;
use atspi::proxy::accessible::AccessibleProxy;
use atspi::proxy::proxy_ext::ProxyExt;
use atspi::{CoordType, State};
+use atspi_connection::AccessibilityConnection;
use super::{accessible_for, app_for_pid, call, runtime, shared_connection, RawObjectRef};
use crate::pointer_shape_map::RoleSample;
@@ -89,7 +90,7 @@ fn inside(extents: Option<(i32, i32, i32, i32)>, x: i32, y: i32) -> bool {
/// smallest showing child containing the point, else (in a page tab list)
/// the selected page, whose body the tab's own extents do not cover.
async fn child_under(
- conn: &atspi::connection::AccessibilityConnection,
+ conn: &AccessibilityConnection,
parent: &AccessibleProxy<'_>,
x: i32,
y: i32,
diff --git a/libs/cua-spacesd/Cargo.lock b/libs/cua-spacesd/Cargo.lock
index 089b8babf0..615c26c1fd 100644
--- a/libs/cua-spacesd/Cargo.lock
+++ b/libs/cua-spacesd/Cargo.lock
@@ -461,7 +461,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bf601cccedfffec598ec2db1f9d6745885458bccc0e8916d7023f017c94b3d0"
dependencies = [
"atspi-common",
- "atspi-connection",
"atspi-proxies",
"zbus",
]
@@ -4446,6 +4445,7 @@ dependencies = [
"ashpd",
"async-trait",
"atspi",
+ "atspi-connection",
"base64 0.22.1",
"bitflags 2.13.1",
"clipboard-rs",
diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
index 1698bab144..de842a07f2 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
@@ -493,7 +493,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bf601cccedfffec598ec2db1f9d6745885458bccc0e8916d7023f017c94b3d0"
dependencies = [
"atspi-common",
- "atspi-connection",
"atspi-proxies",
"zbus",
]
@@ -5917,6 +5916,7 @@ dependencies = [
"ashpd",
"async-trait",
"atspi",
+ "atspi-connection",
"base64 0.22.1",
"bitflags 2.13.2",
"clipboard-rs",
diff --git a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
index c6dbb84864..893cf8104c 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
@@ -422,7 +422,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bf601cccedfffec598ec2db1f9d6745885458bccc0e8916d7023f017c94b3d0"
dependencies = [
"atspi-common",
- "atspi-connection",
"atspi-proxies",
"zbus",
]
@@ -4045,6 +4044,7 @@ dependencies = [
"ashpd",
"async-trait",
"atspi",
+ "atspi-connection",
"base64 0.22.1",
"bitflags 2.13.1",
"clipboard-rs",