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): refuse unproven Wayland window capture (#3200)

Francesco Bonaccic78c1d873b5c
diff --git a/.github/workflows/e2e-rust-linux-wayland.yml b/.github/workflows/e2e-rust-linux-wayland.yml
index 0fd94fa537..9d030df332 100644
--- a/.github/workflows/e2e-rust-linux-wayland.yml
+++ b/.github/workflows/e2e-rust-linux-wayland.yml
@@ -14,6 +14,7 @@ on:
default: sway
options:
- sway
+ - sway-xwayland
- cua-compositor
lane:
description: "Diagnostic lane; canonical dispatches use all"
@@ -81,12 +82,12 @@ jobs:
ref: ${{ needs.source.outputs.sha }}
- uses: dtolnay/rust-toolchain@stable
- name: Install Sway and Rust build dependencies
- if: inputs.environment == 'sway'
+ if: startsWith(inputs.environment, 'sway')
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
- sway wf-recorder grim wtype dbus dbus-x11 at-spi2-core libglib2.0-bin \
+ sway xwayland x11-utils wf-recorder grim wtype dbus dbus-x11 at-spi2-core libglib2.0-bin \
python3-gi gir1.2-gtk-3.0 gir1.2-gtk-4.0 libgtk-3-dev clang pkg-config \
libdbus-1-dev libpipewire-0.3-dev libspa-0.2-dev libei-dev \
libwayland-dev libxkbcommon-dev libx11-dev libxi-dev libxtst-dev \
@@ -123,7 +124,7 @@ jobs:
summary:
if: always()
needs: [source, wayland]
- name: "Linux / pure Wayland summary"
+ name: "Linux / Wayland summary"
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/capture_contract_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/capture_contract_test.rs
index 01b0c936c6..574a01adc6 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/capture_contract_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/capture_contract_test.rs
@@ -27,7 +27,7 @@ use cua_driver_testkit::e2e::{
use cua_driver_testkit::e2e::{CaseSpec, Delivery, Scope};
#[cfg(target_os = "windows")]
use cua_driver_testkit::observer::TargetWindow;
-#[cfg(target_os = "windows")]
+#[cfg(any(target_os = "windows", target_os = "linux"))]
use cua_driver_testkit::sentinel::ForegroundSentinel;
use cua_driver_testkit::{harness_app, Driver, McpDriver, ToolResponse};
@@ -157,6 +157,83 @@ fn snapshot_settled_tree_only(driver: &mut McpDriver, pid: u32, wid: u64) -> Too
resp
}
+#[cfg(target_os = "linux")]
+fn sway_json(args: &[&str]) -> serde_json::Value {
+ let output = Command::new("swaymsg")
+ .args(["-r"])
+ .args(args)
+ .stdin(Stdio::null())
+ .output()
+ .expect("run external Sway oracle");
+ assert!(
+ output.status.success(),
+ "Sway oracle {:?} failed: {}",
+ args,
+ String::from_utf8_lossy(&output.stderr)
+ );
+ serde_json::from_slice(&output.stdout).expect("parse Sway oracle JSON")
+}
+
+#[cfg(target_os = "linux")]
+fn focused_workspace() -> String {
+ sway_json(&["-t", "get_workspaces"])
+ .as_array()
+ .and_then(|workspaces| {
+ workspaces
+ .iter()
+ .find(|workspace| workspace["focused"] == true)
+ })
+ .and_then(|workspace| workspace["name"].as_str())
+ .expect("Sway must report one focused workspace")
+ .to_owned()
+}
+
+#[cfg(target_os = "linux")]
+fn workspace_for_pid(
+ node: &serde_json::Value,
+ pid: u32,
+ workspace: Option<&str>,
+) -> Option<String> {
+ let workspace = if node["type"].as_str() == Some("workspace") {
+ node["name"].as_str()
+ } else {
+ workspace
+ };
+ if node["pid"].as_u64() == Some(pid as u64) {
+ return workspace.map(str::to_owned);
+ }
+ node["nodes"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .chain(node["floating_nodes"].as_array().into_iter().flatten())
+ .find_map(|child| workspace_for_pid(child, pid, workspace))
+}
+
+#[cfg(target_os = "linux")]
+fn switch_sway_workspace(name: &str) {
+ let output = Command::new("swaymsg")
+ .args(["workspace", name])
+ .stdin(Stdio::null())
+ .output()
+ .expect("switch Sway workspace");
+ assert!(
+ output.status.success(),
+ "could not switch to Sway workspace {name}: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(focused_workspace(), name);
+}
+
+#[cfg(target_os = "linux")]
+fn response_has_screenshot_metadata(response: &ToolResponse) -> bool {
+ has_image(response)
+ || response.structured()["screenshot_png_b64"].is_string()
+ || response.structured()["screenshot_file_path"].is_string()
+ || response.structured()["screenshot_width"].is_number()
+ || response.structured()["screenshot_height"].is_number()
+}
+
// ── per-platform harness launch → (pid, window_id) ──────────────────────────────
//
// Each `launch` records the harness window pids that already exist, spawns its
@@ -381,6 +458,173 @@ fn deprecated_capture_mode_is_ignored() {
);
}
+/// Representative #2962 topology: a real XWayland GTK fixture remains on an
+/// inactive Sway workspace while an unrelated Electron sentinel owns the
+/// active output. The source-built public driver must preserve the truthful
+/// AT-SPI tree but return the stable typed screenshot refusal without bytes,
+/// a file, desktop mutation, or fixture mutation.
+#[cfg(target_os = "linux")]
+#[test]
+#[ignore]
+fn off_workspace_xwayland_capture_refuses_unbound_pixels() {
+ if std::env::var("CUA_E2E_WAYLAND_XWAYLAND_REGRESSION").as_deref() != Ok("1") {
+ return;
+ }
+ assert_eq!(
+ std::env::var("XDG_SESSION_TYPE").as_deref(),
+ Ok("wayland"),
+ "the XWayland regression must run inside a native Wayland session"
+ );
+ let xwayland_display = std::env::var("CUA_E2E_XWAYLAND_DISPLAY")
+ .expect("the regression runner must expose its private XWayland display");
+ std::env::set_var("DISPLAY", &xwayland_display);
+ println!(
+ "[xwayland-capture-preflight] source_sha={} session={} compositor={} sway={} xwayland=available",
+ std::env::var("CUA_E2E_SOURCE_SHA").unwrap_or_else(|_| "unknown".to_owned()),
+ std::env::var("XDG_SESSION_TYPE").unwrap_or_else(|_| "unknown".to_owned()),
+ std::env::var("CUA_E2E_COMPOSITOR").unwrap_or_else(|_| "unknown".to_owned()),
+ sway_json(&["-t", "get_version"])["human_readable"].as_str().unwrap_or("unknown")
+ );
+ assert!(
+ std::env::var_os("WAYLAND_DISPLAY").is_some() && std::env::var_os("DISPLAY").is_some(),
+ "the regression requires both Wayland and XWayland display sockets"
+ );
+
+ let case = native_readonly_case(
+ "gtk3-xwayland",
+ "off_workspace_surface_identity_refusal",
+ Targeting::NotApplicable,
+ DriverRoute::WindowState,
+ vec![
+ OracleKind::Protocol,
+ OracleKind::AxState,
+ OracleKind::FixtureState,
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::NoLeakedInput,
+ ],
+ );
+ let cell_id = case.cell_id.clone();
+ execute_case(case, |evidence| {
+ let mut driver = test_driver(&cell_id).expect("start exact source-built driver");
+ *evidence = recording_evidence(driver.recording_dir());
+ switch_sway_workspace("98");
+
+ let before = harness_pids(&mut driver, "CuaTestHarness GTK3");
+ let exe = std::env::var("HARNESS_GTK3_EXE")
+ .map(std::path::PathBuf::from)
+ .ok()
+ .filter(|path| path.exists())
+ .unwrap_or_else(|| harness_app("harness-gtk3", "CuaTestHarness.Gtk3"));
+ driver
+ .reaper()
+ .spawn(
+ Command::new(&exe)
+ .env("GDK_BACKEND", "x11")
+ .stdout(Stdio::null())
+ .stderr(Stdio::null()),
+ )
+ .unwrap_or_else(|error| panic!("launch real XWayland fixture {exe:?}: {error}"));
+ let (pid, wid) = resolve_new_window(&mut driver, "CuaTestHarness GTK3", &before)
+ .expect("resolve real XWayland fixture through public list_windows");
+ let sway_tree = sway_json(&["-t", "get_tree"]);
+ let target_workspace = workspace_for_pid(&sway_tree, pid, None);
+ assert_eq!(target_workspace.as_deref(), Some("98"));
+
+ let tree_before = snapshot_settled_tree_only(&mut driver, pid, wid);
+ assert!(
+ !tree_before.is_error(),
+ "tree-only precondition failed: {}",
+ tree_before.text()
+ );
+ assert!(tree_has_marker(&tree_before));
+ assert!(tree_before.tree_text().contains("counter=0"));
+
+ switch_sway_workspace("1");
+ let sentinel = ForegroundSentinel::launch(&mut driver);
+ driver.start_behavior_recording();
+ let active_workspace_before = focused_workspace();
+ let full_display = driver.call("get_desktop_state", serde_json::json!({}));
+ assert!(
+ !full_display.is_error() && has_image(&full_display),
+ "explicit active-output capture must remain available: {}",
+ full_display.text()
+ );
+
+ let output_dir = tempfile::Builder::new()
+ .prefix("cua-xwayland-refusal-")
+ .tempdir()
+ .expect("create refusal output directory");
+ let requested_path = output_dir.path().join("must-not-exist.png");
+ let ((first, second), mut passed) = sentinel
+ .observe_desktop(|| {
+ let first = driver.call(
+ "get_window_state",
+ serde_json::json!({"pid": pid as i64, "window_id": wid}),
+ );
+ let second = driver.call(
+ "get_window_state",
+ serde_json::json!({
+ "pid": pid as i64,
+ "window_id": wid,
+ "screenshot_out_file": requested_path
+ }),
+ );
+ (first, second)
+ })
+ .unwrap_or_else(|error| panic!("capture refusal disturbed active workspace: {error}"));
+
+ for response in [&first, &second] {
+ assert!(
+ !response.is_error(),
+ "tree-bearing refusal must be usable: {}",
+ response.text()
+ );
+ assert!(
+ tree_has_marker(response),
+ "refusal lost truthful accessibility output"
+ );
+ assert_eq!(response.structured()["screenshot_frame_valid"], false);
+ assert_eq!(
+ response.structured()["screenshot_error"]["code"],
+ "surface_identity_unproven"
+ );
+ assert_eq!(response.structured()["screenshot_error"]["window_id"], wid);
+ assert!(
+ !response_has_screenshot_metadata(response),
+ "refusal leaked screenshot bytes, dimensions, or a path: {}",
+ response.raw
+ );
+ }
+ assert_eq!(
+ first.structured()["screenshot_error"]["code"],
+ second.structured()["screenshot_error"]["code"],
+ "the typed refusal must be stable across repeated calls"
+ );
+ assert!(
+ !requested_path.exists(),
+ "refusal wrote unbound active-workspace pixels"
+ );
+ assert_eq!(focused_workspace(), active_workspace_before);
+ assert_eq!(
+ workspace_for_pid(&sway_json(&["-t", "get_tree"]), pid, None).as_deref(),
+ Some("98")
+ );
+
+ let tree_after = snapshot_settled_tree_only(&mut driver, pid, wid);
+ assert!(tree_after.tree_text().contains("counter=0"));
+ assert_eq!(tree_before.tree_text(), tree_after.tree_text());
+ passed.extend([
+ OracleKind::Protocol,
+ OracleKind::AxState,
+ OracleKind::FixtureState,
+ ]);
+ passed.sort();
+ passed.dedup();
+ Observation::delivered(passed, Evidence::default())
+ });
+}
+
/// Capturing an occluded background window is a read-only operation: it must
/// return pixels without disturbing the user's foreground desktop.
#[cfg(target_os = "windows")]
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.rs
index 0935afa975..e08cadada0 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
@@ -37,6 +37,24 @@ pub fn is_process_live(pid: u32) -> bool {
is_process_live_state(&status)
}
+fn process_start_time_from_stat(stat: &str) -> Option<u64> {
+ // `comm` is parenthesized and may contain spaces. Fields after its closing
+ // parenthesis begin with state (field 3); starttime is field 22.
+ stat.rsplit_once(") ")?
+ .1
+ .split_whitespace()
+ .nth(19)?
+ .parse()
+ .ok()
+}
+
+/// Kernel start-time token for one PID. Unlike the numeric PID alone, this
+/// distinguishes a live process from a later process that reused its PID.
+pub fn process_instance_id(pid: u32) -> Option<u64> {
+ let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
+ process_start_time_from_stat(&stat)
+}
+
/// Return all running processes by reading /proc/<pid>/status.
pub fn list_processes() -> Vec<ProcessInfo> {
let mut result = Vec::new();
@@ -93,6 +111,15 @@ pub fn list_processes() -> Vec<ProcessInfo> {
#[cfg(test)]
mod tests {
+ #[test]
+ fn process_start_time_handles_spaces_in_comm() {
+ let mut fields = vec!["S".to_owned()];
+ fields.extend((4..=21).map(|field| field.to_string()));
+ fields.push("987654".to_owned());
+ let stat = format!("42 (fixture with spaces) {}", fields.join(" "));
+ assert_eq!(super::process_start_time_from_stat(&stat), Some(987654));
+ }
+
#[test]
fn process_states_fail_closed() {
assert!(super::is_process_live_state(
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_.rs
index 514b0d1812..e71a9c8f34 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
@@ -594,7 +594,10 @@ impl Tool for GetWindowStateTool {
modality at ACTION time: an element ax action \
(element_index/element_token → accessibility rung) or an element px \
action (x,y → pixel rung off this screenshot). capture_mode is \
- deprecated and ignored.\n\n\
+ deprecated and ignored. On Wayland, where output capture cannot prove \
+ the requested surface's identity, the truthful tree is returned without \
+ a screenshot and `screenshot_error.code` is \
+ `surface_identity_unproven`.\n\n\
Optional `max_elements` / `max_depth` bound the AT-SPI walk to \
mitigate context-window blow-up on Electron / large web apps \
that produce 10k+ element trees. When applied, BOTH \
@@ -603,7 +606,7 @@ impl Tool for GetWindowStateTool {
input_schema: json!({"type":"object","required":["pid","window_id"],"properties":{
"session": cua_driver_core::tool_schema::session_schema(),
"pid":{"type":"integer"},
- "window_id":{"type":"integer","description":"X11 XID from list_windows."},
+ "window_id":{"type":"integer","description":"Native window identifier from list_windows."},
"capture_mode": cua_driver_core::capture_mode::capture_mode_schema(),
"include_screenshot":{"type":"boolean",
"description":"Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return tree only (the cheap path for re-indexing before an element ax action)."},
@@ -670,6 +673,7 @@ impl Tool for GetWindowStateTool {
crate::wayland::list_windows_dispatch(Some(pid))
.iter()
.any(|window| window.xid == xid && window.pid == Some(pid))
+ || crate::wayland::window_was_listed_for_pid(pid, xid)
} else {
crate::x11::window_belongs_to_pid(xid, pid)
};
@@ -681,9 +685,9 @@ impl Tool for GetWindowStateTool {
// 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 the
- // explicit `include_screenshot:false` opt-out (with no screenshot_out_file)
- // skips the grab to return tree only.
+ // cross-checks the (sometimes-lying) tree against the frame. An explicit
+ // `include_screenshot:false` skips the grab; an unproven Wayland surface
+ // returns the tree with a typed screenshot error instead of unrelated pixels.
let should_capture = include_screenshot != Some(false) || screenshot_out_file.is_some();
let observation_only = args
.get("_observation_only")
@@ -713,6 +717,7 @@ impl Tool for GetWindowStateTool {
// of embedding base64; otherwise embed base64. Skipped only when
// include_screenshot:false and no disk path was requested.
// Tuple: (Option<b64>, Option<file_path>, w, h, Option<original_w>).
+ let mut screenshot_error = None;
let screenshot = if should_capture {
match crate::wayland::screenshot_dispatch(xid) {
Ok(raw) => {
@@ -730,6 +735,10 @@ impl Tool for GetWindowStateTool {
Some((Some(B64.encode(&png)), None, w, h, original_w))
}
}
+ Err(error) if crate::wayland::is_surface_identity_unproven(&error) => {
+ screenshot_error = Some(error.to_string());
+ None
+ }
Err(error) => {
return Err(anyhow::anyhow!(
"window screenshot failed for window {xid}: {error}"
@@ -739,12 +748,12 @@ impl Tool for GetWindowStateTool {
} else {
None
};
- Ok((tree_result, screenshot, bounds))
+ Ok((tree_result, screenshot, bounds, screenshot_error))
})
.await;
match result {
- Ok(Ok((tree_opt, shot_opt, bounds))) => {
+ Ok(Ok((tree_opt, shot_opt, bounds, screenshot_error))) => {
let mut content = Vec::new();
let mut structured = json!({ "window_id": xid, "pid": pid });
@@ -927,6 +936,10 @@ impl Tool for GetWindowStateTool {
structured["screenshot_file_path"] = json!(fp);
}
}
+ if let Some(reason) = screenshot_error {
+ structured["screenshot_frame_valid"] = json!(false);
+ structured["screenshot_error"] = surface_identity_unproven_error(xid, reason);
+ }
ToolResult {
content,
@@ -941,8 +954,36 @@ impl Tool for GetWindowStateTool {
}
}
+fn surface_identity_unproven_error(xid: u64, reason: String) -> Value {
+ json!({
+ "code": "surface_identity_unproven",
+ "window_id": xid,
+ "reason": reason,
+ "suggestion": "capture the full output explicitly, or retry on a compositor backend that supports identified per-window capture"
+ })
+}
+
// ── launch_app ───────────────────────────────────────────────────────────────
+#[cfg(test)]
+mod get_window_state_capture_tests {
+ use super::*;
+
+ #[test]
+ fn surface_identity_failure_is_a_typed_screenshot_error() {
+ let error = surface_identity_unproven_error(
+ 0x2962,
+ "surface_identity_unproven: fixture".to_owned(),
+ );
+
+ assert_eq!(error["code"], "surface_identity_unproven");
+ assert_eq!(error["window_id"], 0x2962);
+ assert!(error["reason"]
+ .as_str()
+ .is_some_and(|reason| reason.contains("surface_identity_unproven")));
+ }
+}
+
pub struct LaunchAppTool;
static LAUNCH_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs
index 8982c0eda9..3432293834 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs
@@ -5,10 +5,9 @@
//! staging `ext_foreign_toplevel_list_v1`, captures per-output screenshots via
//! `zwlr_screencopy_manager_v1` + `wl_shm` (native — `grim` remains a
//! fallback), and synthesises pointer / scroll / drag input via
-//! `zwlr_virtual_pointer_v1`. Per-window image capture is deferred until
-//! `ext-foreign-toplevel-image-capture-source-v1` lands in
-//! `wayland-protocols-wlr`; until then `screenshot_window_dispatch` returns a
-//! typed error on pure Wayland.
+//! `zwlr_virtual_pointer_v1`. Until identified per-toplevel capture is broadly
+//! available, window-scoped screenshots use output crops only for visible,
+//! compositor-attested surfaces and return a typed identity error otherwise.
pub mod ext_screencopy;
pub mod ext_toplevel;
@@ -227,6 +226,38 @@ fn observed_origin_registry() -> &'static Mutex<HashMap<u32, (i32, i32)>> {
REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}
+fn listed_window_registry() -> &'static Mutex<HashMap<(u32, u64), u64>> {
+ static REGISTRY: OnceLock<Mutex<HashMap<(u32, u64), u64>>> = OnceLock::new();
+ REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+fn remember_listed_windows(windows: &[WindowInfo]) {
+ if let Ok(mut registry) = listed_window_registry().lock() {
+ for window in windows {
+ if let Some((pid, instance_id)) = window.pid.and_then(|pid| {
+ crate::proc_fs::process_instance_id(pid).map(|instance_id| (pid, instance_id))
+ }) {
+ registry.insert((pid, window.xid), instance_id);
+ }
+ }
+ }
+}
+
+pub fn window_was_listed_for_pid(pid: u32, window_id: u64) -> bool {
+ let current_instance = crate::proc_fs::process_instance_id(pid);
+ listed_window_registry()
+ .lock()
+ .ok()
+ .and_then(|registry| registry.get(&(pid, window_id)).copied())
+ == current_instance
+ && current_instance.is_some()
+}
+
+fn listed_windows(windows: Vec<WindowInfo>) -> Vec<WindowInfo> {
+ remember_listed_windows(&windows);
+ windows
+}
+
pub fn remember_observed_window_origins(windows: &[WindowInfo]) {
if let Ok(mut registry) = observed_origin_registry().lock() {
for window in windows {
@@ -872,27 +903,138 @@ pub(crate) unsafe fn borrowed_fd(fd: i32) -> std::os::fd::OwnedFd {
std::os::fd::OwnedFd::from_raw_fd(dup)
}
-/// Capture dispatcher: native Wayland (screencopy with grim fallback) when
-/// applicable, else X11. Mirrors `screenshot_window_dispatch` for the
-/// output-level path used by `get_window_state`'s vision payload.
-pub fn screenshot_dispatch(xid: u64) -> anyhow::Result<Vec<u8>> {
- if is_wayland() {
- let bytes = screenshot_display_dispatch()?;
- if let Some((x, y, width, height)) = window_geometry(xid) {
- crop_png_to_rect(
- &bytes,
- x,
- y,
- width,
- height,
- &format!("Wayland window {xid}"),
- )
- } else {
- Ok(bytes)
- }
- } else {
- crate::capture::screenshot_window_bytes(xid)
+/// A Wayland output crop cannot prove which surface supplied its pixels. This
+/// is especially unsafe for off-workspace XWayland windows: their X11 geometry
+/// can crop the active workspace at the requested coordinates.
+#[derive(Debug)]
+pub struct SurfaceIdentityUnproven {
+ window_id: u64,
+ reason: &'static str,
+}
+
+impl std::fmt::Display for SurfaceIdentityUnproven {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ formatter,
+ "surface_identity_unproven: Wayland capture cannot prove pixels belong to window {}: {}",
+ self.window_id, self.reason
+ )
+ }
+}
+
+impl std::error::Error for SurfaceIdentityUnproven {}
+
+pub fn is_surface_identity_unproven(error: &anyhow::Error) -> bool {
+ error.downcast_ref::<SurfaceIdentityUnproven>().is_some()
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+struct WaylandWindowCrop {
+ x: i32,
+ y: i32,
+ width: u32,
+ height: u32,
+}
+
+fn surface_identity_unproven(window_id: u64, reason: &'static str) -> anyhow::Error {
+ SurfaceIdentityUnproven { window_id, reason }.into()
+}
+
+fn attested_wayland_crop(
+ xid: u64,
+ x: i32,
+ y: i32,
+ width: u32,
+ height: u32,
+ visible: bool,
+) -> anyhow::Result<WaylandWindowCrop> {
+ if !visible {
+ return Err(surface_identity_unproven(
+ xid,
+ "the compositor reports the surface is not visible on the active workspace",
+ ));
+ }
+ if width == 0 || height == 0 {
+ return Err(surface_identity_unproven(
+ xid,
+ "the compositor reports empty surface geometry",
+ ));
+ }
+ Ok(WaylandWindowCrop {
+ x,
+ y,
+ width,
+ height,
+ })
+}
+
+/// Resolve a crop only from compositor-owned metadata that also proves the
+/// surface is present on the currently rendered workspace. X11 geometry and
+/// AT-SPI bounds are intentionally insufficient: an off-workspace XWayland
+/// window retains both while the output contains another application's pixels.
+fn wayland_window_crop(xid: u64) -> anyhow::Result<WaylandWindowCrop> {
+ if let Some(window) = sway_ipc::window_for_id(xid) {
+ return attested_wayland_crop(
+ xid,
+ window.x,
+ window.y,
+ window.width,
+ window.height,
+ window.visible,
+ );
+ }
+ if let Some(window) = shell_helper::list_windows(None)
+ .and_then(|windows| windows.into_iter().find(|window| window.xid == xid))
+ {
+ return attested_wayland_crop(
+ xid,
+ window.x,
+ window.y,
+ window.width,
+ window.height,
+ window.is_on_screen,
+ );
}
+ Err(surface_identity_unproven(
+ xid,
+ "no compositor-attested window geometry is available",
+ ))
+}
+
+fn screenshot_window_bytes_with_dispatch(
+ wayland: bool,
+ xid: u64,
+ wayland_crop: impl FnOnce(u64) -> anyhow::Result<WaylandWindowCrop>,
+ display_capture: impl FnOnce() -> anyhow::Result<Vec<u8>>,
+ x11_capture: impl FnOnce(u64) -> anyhow::Result<Vec<u8>>,
+) -> anyhow::Result<Vec<u8>> {
+ if wayland {
+ let crop = wayland_crop(xid)?;
+ let output = display_capture()?;
+ return crop_png_to_rect(
+ &output,
+ crop.x,
+ crop.y,
+ crop.width,
+ crop.height,
+ &format!("Wayland window {xid}"),
+ );
+ }
+ x11_capture(xid)
+}
+
+/// Window capture dispatcher. X11 uses its per-window capture path. Wayland
+/// crops output pixels only when compositor metadata proves that the requested
+/// surface is currently rendered; otherwise it fails closed. Output-level
+/// capture remains available through [`screenshot_display_dispatch`].
+pub fn screenshot_dispatch(xid: u64) -> anyhow::Result<Vec<u8>> {
+ screenshot_window_bytes_with_dispatch(
+ is_wayland(),
+ xid,
+ wayland_window_crop,
+ screenshot_display_dispatch,
+ crate::capture::screenshot_window_bytes,
+ )
}
fn crop_png_to_rect(
@@ -989,31 +1131,17 @@ fn checked_shell_helper_capture(
.then(|| capture().ok_or_else(|| anyhow::anyhow!("GNOME compositor helper capture failed")))
}
-/// Per-window capture dispatcher. On X11 forwards to the existing window
-/// capture path; on pure Wayland returns a typed error pointing at the
-/// staging `ext-image-copy-capture-v1` protocol — wlr-screencopy is
-/// output-only, and `foreign-toplevel` exposes no per-window geometry to
-/// crop with.
+/// Per-window capture dispatcher. Kept as the explicit window-capture entry
+/// point for callers outside `get_window_state`; it shares the same fail-closed
+/// Wayland contract as [`screenshot_dispatch`].
pub fn screenshot_window_dispatch(xid: u64) -> anyhow::Result<Vec<u8>> {
- if is_wayland() {
- if let Some((x, y, width, height)) = window_geometry(xid) {
- return crop_png_to_rect(
- &screenshot_display_dispatch()?,
- x,
- y,
- width,
- height,
- &format!("Wayland window {xid}"),
- );
- }
- anyhow::bail!(
- "per-window screenshot is not yet supported on native Wayland — \
- zwlr_screencopy_manager_v1 is output-only and ext-image-copy-capture-v1 \
- is not yet shipped in wayland-protocols-wlr. Run under XWayland to crop \
- to a single window, or capture the full output instead."
- );
- }
- crate::capture::screenshot_window_bytes(xid)
+ screenshot_window_bytes_with_dispatch(
+ is_wayland(),
+ xid,
+ wayland_window_crop,
+ screenshot_display_dispatch,
+ crate::capture::screenshot_window_bytes,
+ )
}
// ── Input session helper ─────────────────────────────────────────────────────
@@ -2947,26 +3075,26 @@ pub fn list_windows_dispatch(filter_pid: Option<u32>) -> Vec<WindowInfo> {
Ok(ws) if !ws.is_empty() => {
if let Some(pid) = filter_pid {
if let Some(filtered) = native_windows_for_pid(ws, pid) {
- return filtered;
+ return listed_windows(filtered);
}
} else {
- return ws;
+ return listed_windows(ws);
}
// A compositor window without pid metadata cannot satisfy a
// pid-scoped request. Continue to the AT-SPI registry.
let ws = wayland_atspi_windows(filter_pid);
if !ws.is_empty() {
- return ws;
+ return listed_windows(ws);
}
}
Ok(_) => {
if let Some(ws) = shell_helper::list_windows(filter_pid).filter(|ws| !ws.is_empty())
{
- return ws;
+ return listed_windows(ws);
}
let ws = wayland_atspi_windows(filter_pid);
if !ws.is_empty() {
- return ws;
+ return listed_windows(ws);
}
}
Err(e) => {
@@ -2975,12 +3103,12 @@ pub fn list_windows_dispatch(filter_pid: Option<u32>) -> Vec<WindowInfo> {
tracing::debug!(
"native Wayland protocols unavailable ({e}); using compositor helper"
);
- return ws;
+ return listed_windows(ws);
}
tracing::warn!("native Wayland list_windows failed: {e}; trying AT-SPI registry");
let ws = wayland_atspi_windows(filter_pid);
if !ws.is_empty() {
- return ws;
+ return listed_windows(ws);
}
}
}
@@ -3008,7 +3136,7 @@ pub fn list_windows_dispatch(filter_pid: Option<u32>) -> Vec<WindowInfo> {
merge_atspi_windows(&mut ws, &seen, wayland_atspi_windows(filter_pid));
}
}
- ws
+ listed_windows(ws)
}
fn merge_atspi_windows(
@@ -3349,7 +3477,80 @@ mod tests {
}
#[test]
- fn sway_window_capture_is_cropped_to_compositor_geometry() {
+ fn wayland_window_capture_fails_closed_without_using_x11_pixels() {
+ let display_called = std::cell::Cell::new(false);
+ let x11_called = std::cell::Cell::new(false);
+ let error = screenshot_window_bytes_with_dispatch(
+ true,
+ 0x2962,
+ |xid| {
+ Err(surface_identity_unproven(
+ xid,
+ "fixture surface is off-workspace",
+ ))
+ },
+ || {
+ display_called.set(true);
+ Ok(vec![9, 9, 9])
+ },
+ |_| {
+ x11_called.set(true);
+ Ok(vec![1, 2, 3])
+ },
+ )
+ .expect_err("Wayland output pixels cannot prove a window surface");
+
+ assert!(is_surface_identity_unproven(&error));
+ assert!(error.to_string().contains("window 10594"));
+ assert!(!display_called.get());
+ assert!(!x11_called.get());
+ }
+
+ #[test]
+ fn x11_window_capture_keeps_the_existing_per_window_path() {
+ let captured_xid = std::cell::Cell::new(None);
+ let bytes = screenshot_window_bytes_with_dispatch(
+ false,
+ 42,
+ |_| panic!("X11 must not resolve a Wayland crop"),
+ || panic!("X11 must not capture the Wayland output"),
+ |xid| {
+ captured_xid.set(Some(xid));
+ Ok(vec![1, 2, 3])
+ },
+ )
+ .expect("X11 per-window capture should remain available");
+
+ assert_eq!(captured_xid.get(), Some(42));
+ assert_eq!(bytes, vec![1, 2, 3]);
+ }
+
+ #[test]
+ fn listed_wayland_identity_remains_valid_when_current_enumeration_hides_it() {
+ let pid = std::process::id();
+ let window_id = 0xf2962_0001;
+ assert!(!window_was_listed_for_pid(pid, window_id));
+
+ remember_listed_windows(&[WindowInfo {
+ xid: window_id,
+ pid: Some(pid),
+ app_name: String::new(),
+ title: String::new(),
+ is_on_screen: false,
+ z_index: None,
+ x: 0,
+ y: 0,
+ width: 0,
+ height: 0,
+ }]);
+
+ assert!(window_was_listed_for_pid(pid, window_id));
+ assert!(!window_was_listed_for_pid(pid + 1, window_id));
+ assert!(!window_was_listed_for_pid(pid, window_id + 1));
+ }
+
+ #[test]
+ fn compositor_attested_visible_wayland_surface_keeps_window_capture() {
let source = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
8,
6,
@@ -3359,8 +3560,21 @@ mod tests {
source
.write_to(&mut encoded, image::ImageFormat::Png)
.expect("encode fixture PNG");
- let cropped =
- crop_png_to_rect(encoded.get_ref(), 2, 1, 3, 4, "fixture").expect("crop fixture PNG");
+ let cropped = screenshot_window_bytes_with_dispatch(
+ true,
+ 42,
+ |_| {
+ Ok(WaylandWindowCrop {
+ x: 2,
+ y: 1,
+ width: 3,
+ height: 4,
+ })
+ },
+ || Ok(encoded.into_inner()),
+ |_| panic!("Wayland must not use the X11 capture path"),
+ )
+ .expect("visible compositor-attested Wayland surface should capture");
let decoded = image::load_from_memory(&cropped).expect("decode cropped PNG");
assert_eq!((decoded.width(), decoded.height()), (3, 4));
}
diff --git a/scripts/ci/README.md b/scripts/ci/README.md
index 010469c010..84573c036d 100644
--- a/scripts/ci/README.md
+++ b/scripts/ci/README.md
@@ -111,6 +111,14 @@ Run the Wayland wrapper through `nix develop .#cua-driver-wayland-e2e`. It
creates a pure Wayland session with Xwayland disabled and delegates every
scenario to `run-rust-e2e.sh`.
+The manually dispatched `sway-xwayland` capture lane uses the same wrapper with
+XWayland forced on. Its capture contract places a real repo-owned GTK3 X11
+fixture on inactive workspace 98, keeps an unrelated Wayland sentinel on the
+active output, and requires `get_window_state` to return
+`surface_identity_unproven` without screenshot bytes or a file. Sway IPC and
+the fixture accessibility state are external focus, workspace, and mutation
+oracles for that targeted regression.
+
Run the nested compositor wrapper through
`nix develop .#cua-driver-inject-e2e`. This environment is experimental and
proves only the private compositor-owned route. Use `run-rust-e2e-desktop.sh`
diff --git a/scripts/ci/linux/run-rust-e2e-wayland.sh b/scripts/ci/linux/run-rust-e2e-wayland.sh
index e0e15a5499..4958d3a34a 100755
--- a/scripts/ci/linux/run-rust-e2e-wayland.sh
+++ b/scripts/ci/linux/run-rust-e2e-wayland.sh
@@ -8,6 +8,12 @@ RUNTIME_DIR="$(mktemp -d)"
SWAY_CONFIG="$(mktemp)"
SESSION_KIND="${CUA_E2E_WAYLAND_SESSION:-sway}"
export CUA_E2E_WAYLAND_SESSION="${SESSION_KIND}"
+if [[ "${SESSION_KIND}" == sway-xwayland ]]; then
+ # The testkit's compositor contract is still canonical Sway. Keep the
+ # orchestration label separate so focus, z-order, and sentinel observers use
+ # their established Sway paths while this wrapper additionally enables XWayland.
+ export CUA_E2E_WAYLAND_SESSION=sway
+fi
COMPOSITOR_LOG="${REPO_ROOT}/artifacts/cua-driver/linux/${SESSION_KIND}.log"
ATSPI_LOG="${REPO_ROOT}/artifacts/cua-driver/linux/at-spi-bus.log"
COMPOSITOR_PID=""
@@ -42,6 +48,9 @@ default_floating_border none
for_window [title="^CuaTestHarness"] floating enable, resize set 940 780, move position 0 0
for_window [title="CuaTestHarness Sentinel"] fullscreen enable
EOF
+if [[ "${SESSION_KIND}" == sway-xwayland ]]; then
+ sed -i 's/^xwayland disable$/xwayland force/' "${SWAY_CONFIG}"
+fi
unset DISPLAY
unset WAYLAND_DISPLAY
@@ -63,6 +72,9 @@ if [[ "${SESSION_KIND}" == cua-compositor ]]; then
else
export CUA_E2E_COMPOSITOR=sway
export CUA_E2E_INPUT_BACKENDS=atspi,wlr-virtual-pointer
+ if [[ "${SESSION_KIND}" == sway-xwayland ]]; then
+ export CUA_E2E_WAYLAND_XWAYLAND_REGRESSION=1
+ fi
fi
export CUA_WAYLAND_RECORDING_OUTPUT=HEADLESS-1
export ELECTRON_OZONE_PLATFORM_HINT=wayland
@@ -239,6 +251,31 @@ else
cat "${COMPOSITOR_LOG}" >&2
exit 1
fi
+ if [[ "${SESSION_KIND}" == sway-xwayland ]]; then
+ deadline=$((SECONDS + 15))
+ while ((SECONDS < deadline)); do
+ xwayland_socket="$(find /tmp/.X11-unix -maxdepth 1 -type s -name 'X*' -newer "${SWAY_CONFIG}" -print -quit 2>/dev/null || true)"
+ if [[ -n "${xwayland_socket}" ]]; then
+ export CUA_E2E_XWAYLAND_DISPLAY=":${xwayland_socket##*/X}"
+ break
+ fi
+ sleep 0.2
+ done
+ if [[ -z "${CUA_E2E_XWAYLAND_DISPLAY:-}" ]] || ! xdpyinfo -display "${CUA_E2E_XWAYLAND_DISPLAY}" >/dev/null 2>&1; then
+ echo "Sway did not expose a usable XWayland display within 15 seconds" >&2
+ cat "${COMPOSITOR_LOG}" >&2
+ exit 1
+ fi
+ jq -n \
+ --arg source_sha "${CUA_E2E_SOURCE_SHA:-unknown}" \
+ --arg session_type "${XDG_SESSION_TYPE}" \
+ --arg compositor "${CUA_E2E_COMPOSITOR}" \
+ --arg wayland_display "${WAYLAND_DISPLAY}" \
+ --arg xwayland_display "${CUA_E2E_XWAYLAND_DISPLAY}" \
+ --argjson sway "$(swaymsg -r -t get_version)" \
+ '{source_sha:$source_sha,session_type:$session_type,compositor:$compositor,wayland_display:$wayland_display,xwayland_display:$xwayland_display,sway:$sway}' \
+ > "${REPO_ROOT}/artifacts/cua-driver/linux/wayland-xwayland-preflight.json"
+ fi
fi
echo "Native Wayland E2E session: ${SESSION_KIND} on ${WAYLAND_DISPLAY}"
@@ -251,7 +288,7 @@ set +e
"${SESSION_RUNNER}" "$@"
status=$?
set -e
-if [[ "${status}" != 0 && "${SESSION_KIND}" == sway ]]; then
+if [[ "${status}" != 0 && "${SESSION_KIND}" == sway* ]]; then
swaymsg -t get_tree > "${REPO_ROOT}/artifacts/cua-driver/linux/sway-tree.json" 2>/dev/null || true
fi
exit "${status}"