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): honor modifiers during X11 drags (#3618)

usedhonda815788869898
diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/desktop_scope_linux_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/desktop_scope_linux_test.rs
index 1949de5324..260610d928 100644
--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/desktop_scope_linux_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/desktop_scope_linux_test.rs
@@ -154,6 +154,13 @@ fn marker_value(snap: &serde_json::Value, marker: &str) -> Option<u64> {
digits.parse().ok()
}
+fn tree_contains(snap: &serde_json::Value, marker: &str) -> bool {
+ snap["tree_markdown"]
+ .as_str()
+ .map(|tree| tree.contains(marker))
+ .unwrap_or(false)
+}
+
fn desktop_input_route() -> DriverRoute {
if std::env::var_os("CUA_INJECT_SOCKET").is_some() {
DriverRoute::LinuxCuaCompositorInject
@@ -448,6 +455,98 @@ fn desktop_scope_hotkey_releases_modifiers() {
});
}
+#[test]
+#[ignore]
+fn desktop_scope_drag_holds_and_releases_modifier() {
+ let cell_id = "linux-gtk3-desktop-drag-modifier-px-foreground";
+ let case = CaseSpec::delivered(
+ cell_id,
+ "gtk3",
+ "gtk3",
+ "drag",
+ Targeting::Px,
+ Delivery::Foreground,
+ Scope::Desktop,
+ desktop_input_route(),
+ vec![OracleKind::FixtureState],
+ );
+ 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 window_session = format!("{cell_id}-window");
+ let desktop_session = format!("{cell_id}-desktop");
+ start_scope(&mut driver, &window_session, "window");
+ start_scope(&mut driver, &desktop_session, "desktop");
+ let (pid, wid) = launch(&mut driver).expect("required GTK3 harness did not launch");
+ let posture = driver.call(
+ "bring_to_front",
+ serde_json::json!({"session": window_session, "pid": pid as i64, "window_id": wid}),
+ );
+ assert!(
+ !posture.is_error(),
+ "could not foreground GTK3 fixture: {}",
+ posture.text()
+ );
+ std::thread::sleep(Duration::from_millis(300));
+
+ let snap = ax_snapshot(&mut driver, &window_session, pid, wid);
+ let (x, y) = element_center_containing(&snap, "btn-clicktarget")
+ .expect("GTK3 drag target frame not found");
+ let before_keys = marker_value(&snap, "key_presses=").unwrap_or(0);
+ driver.start_behavior_recording();
+ let drag = driver.call(
+ "drag",
+ serde_json::json!({
+ "session": desktop_session, "scope": "desktop",
+ "from_x": x - 20, "from_y": y, "to_x": x + 20, "to_y": y,
+ "duration_ms": 250, "steps": 8, "modifier": ["ctrl"]
+ }),
+ );
+ assert!(
+ !drag.is_error(),
+ "modified desktop drag failed: {}",
+ drag.text()
+ );
+
+ let deadline = Instant::now() + Duration::from_secs(3);
+ loop {
+ let state = ax_snapshot(&mut driver, &window_session, pid, wid);
+ if tree_contains(&state, "drag_modifier=ctrl") {
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "GTK3 did not observe ctrl during drag: {}",
+ drag.text()
+ );
+ std::thread::sleep(Duration::from_millis(100));
+ }
+
+ let plain_key = driver.call(
+ "press_key",
+ serde_json::json!({"session": desktop_session, "scope": "desktop", "key": "f5"}),
+ );
+ assert!(
+ !plain_key.is_error(),
+ "post-drag plain F5 failed: {}",
+ plain_key.text()
+ );
+ let deadline = Instant::now() + Duration::from_secs(2);
+ loop {
+ let state = ax_snapshot(&mut driver, &window_session, pid, wid);
+ if marker_value(&state, "key_presses=").unwrap_or(before_keys) > before_keys {
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "plain F5 did not match after modified drag; modifier may be latched"
+ );
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ Observation::delivered_with_fixture_state(Vec::new())
+ });
+}
+
/// Negative gate: a window-less click under `capture_scope=window` is rejected.
#[test]
#[ignore]
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
index bebb301304..3d34fc0759 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
@@ -3744,61 +3744,140 @@ pub fn send_drag_xtest_desktop(
button: u8,
duration_ms: u64,
steps: usize,
+) -> Result<()> {
+ send_drag_xtest_desktop_with_modifiers(
+ from_x,
+ from_y,
+ to_x,
+ to_y,
+ button,
+ duration_ms,
+ steps,
+ &[],
+ )
+}
+
+/// Screen-absolute drag via XTest with physical modifier transitions around
+/// the complete press/motion/release gesture.
+pub fn send_drag_xtest_desktop_with_modifiers(
+ from_x: i32,
+ from_y: i32,
+ to_x: i32,
+ to_y: i32,
+ button: u8,
+ duration_ms: u64,
+ steps: usize,
+ modifiers: &[&str],
) -> Result<()> {
use x11rb::protocol::xtest::ConnectionExt as _;
let (conn, screen_num) = connect_x11_for_input()?;
let root = conn.setup().roots[screen_num].root;
+ let mapping = conn.get_keyboard_mapping(8, 248)?.reply()?;
+ let mut guards = Vec::new();
+ let mut modifier_keycodes = Vec::new();
+ for modifier in modifiers {
+ let keysym = key_name_to_keysym(modifier)?;
+ let (keycode, guard) = keycode_for_keysym(&conn, &mapping, keysym, modifier)?;
+ if let Some(guard) = guard {
+ guards.push(guard);
+ }
+ modifier_keycodes.push(keycode);
+ }
let steps = steps.max(1);
let delay = duration_ms / steps as u64;
+ let mut pressed_modifiers = Vec::new();
+ let mut button_pressed = false;
- conn.xtest_fake_input(
- MOTION_NOTIFY_EVENT,
- 0,
- 0,
- root,
- from_x as i16,
- from_y as i16,
- 0,
- )?;
- conn.xtest_fake_input(
- BUTTON_PRESS_EVENT,
- button,
- 0,
- root,
- from_x as i16,
- from_y as i16,
- 0,
- )?;
- conn.flush()?;
- for step in 1..=steps {
- let t = step as f64 / steps as f64;
- let x = from_x as f64 + (to_x - from_x) as f64 * t;
- let y = from_y as f64 + (to_y - from_y) as f64 * t;
+ let gesture_result = (|| -> Result<()> {
+ for &keycode in &modifier_keycodes {
+ conn.xtest_fake_input(KEY_PRESS_EVENT, keycode, 0, x11rb::NONE, 0, 0, 0)?;
+ pressed_modifiers.push(keycode);
+ }
conn.xtest_fake_input(
MOTION_NOTIFY_EVENT,
0,
0,
root,
- x.round() as i16,
- y.round() as i16,
+ from_x as i16,
+ from_y as i16,
0,
)?;
+ conn.xtest_fake_input(
+ BUTTON_PRESS_EVENT,
+ button,
+ 0,
+ root,
+ from_x as i16,
+ from_y as i16,
+ 0,
+ )?;
+ button_pressed = true;
conn.flush()?;
- if delay > 0 {
- sleep(Duration::from_millis(delay));
+ for step in 1..=steps {
+ let t = step as f64 / steps as f64;
+ let x = from_x as f64 + (to_x - from_x) as f64 * t;
+ let y = from_y as f64 + (to_y - from_y) as f64 * t;
+ conn.xtest_fake_input(
+ MOTION_NOTIFY_EVENT,
+ 0,
+ 0,
+ root,
+ x.round() as i16,
+ y.round() as i16,
+ 0,
+ )?;
+ conn.flush()?;
+ if delay > 0 {
+ sleep(Duration::from_millis(delay));
+ }
+ }
+ conn.xtest_fake_input(
+ BUTTON_RELEASE_EVENT,
+ button,
+ 0,
+ root,
+ to_x as i16,
+ to_y as i16,
+ 0,
+ )?;
+ button_pressed = false;
+ Ok(())
+ })();
+
+ // Always attempt to release the button and every modifier queued above,
+ // including when a later motion request fails.
+ let mut cleanup_result: Result<()> = Ok(());
+ if button_pressed {
+ if let Err(error) = conn.xtest_fake_input(
+ BUTTON_RELEASE_EVENT,
+ button,
+ 0,
+ root,
+ to_x as i16,
+ to_y as i16,
+ 0,
+ ) {
+ cleanup_result = Err(error.into());
+ }
+ }
+ for &keycode in pressed_modifiers.iter().rev() {
+ if let Err(error) =
+ conn.xtest_fake_input(KEY_RELEASE_EVENT, keycode, 0, x11rb::NONE, 0, 0, 0)
+ {
+ if cleanup_result.is_ok() {
+ cleanup_result = Err(error.into());
+ }
+ }
+ }
+ if let Err(error) = conn.flush() {
+ if cleanup_result.is_ok() {
+ cleanup_result = Err(error.into());
}
}
- conn.xtest_fake_input(
- BUTTON_RELEASE_EVENT,
- button,
- 0,
- root,
- to_x as i16,
- to_y as i16,
- 0,
- )?;
- conn.flush()?;
let _ = conn.get_input_focus()?.reply();
+ drop(guards);
+ gesture_result?;
+ cleanup_result?;
Ok(())
}
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 268179d499..fcc7de5655 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
@@ -10390,6 +10390,7 @@ impl Tool for DragTool {
}
async fn invoke(&self, args: Value) -> ToolResult {
let cursor_id = resolve_cursor_key(&args);
+ let modifiers: Vec<String> = args.str_array("modifier");
if args.opt_str("scope").as_deref() == Some("desktop")
&& args.get("pid").is_none()
&& args.get("window_id").is_none()
@@ -10403,7 +10404,13 @@ impl Tool for DragTool {
let button = parse_mouse_button(input.button.unwrap_or(ClickButton::Left).as_str());
let duration_ms = input.duration_ms.unwrap_or(500).min(10_000);
let steps = input.steps.unwrap_or(20).clamp(1, 200) as usize;
+ let modifiers = input.modifier.unwrap_or_default();
let wayland = crate::wayland::wayland_input_enabled();
+ if wayland && !modifiers.is_empty() {
+ return ToolResult::error(
+ "modified drags are unavailable on native Wayland: the pointer route cannot carry keyboard modifier state",
+ );
+ }
let path = if wayland { "wayland_desktop" } else { "xtest" };
let result = tokio::task::spawn_blocking(move || {
if wayland {
@@ -10417,7 +10424,8 @@ impl Tool for DragTool {
button,
)
} else {
- crate::input::send_drag_xtest_desktop(
+ let modifier_refs: Vec<&str> = modifiers.iter().map(String::as_str).collect();
+ crate::input::send_drag_xtest_desktop_with_modifiers(
from_x.round() as i32,
from_y.round() as i32,
to_x.round() as i32,
@@ -10425,6 +10433,7 @@ impl Tool for DragTool {
button,
duration_ms,
steps,
+ &modifier_refs,
)
}
});
@@ -10460,6 +10469,11 @@ impl Tool for DragTool {
let delivery = crate::input::delivery::DeliveryMode::from_args(&args);
let isolated_background = isolated_hyprland_background(delivery);
let native_refusal = if !isolated_background {
+ if crate::wayland::wayland_input_enabled() && !modifiers.is_empty() {
+ return ToolResult::error(
+ "modified drags are unavailable on native Wayland: the pointer route cannot carry keyboard modifier state",
+ );
+ }
if let Some(refusal) = unavailable_chromium_background(pid, delivery) {
return refusal;
}
@@ -10797,8 +10811,9 @@ impl Tool for DragTool {
Err(e) => return ToolResult::error(format!("Task error: {e}")),
};
let drag_result = tokio::task::spawn_blocking(move || {
+ let modifier_refs: Vec<&str> = modifiers.iter().map(String::as_str).collect();
crate::input::with_x11_foreground(xid, 80, || {
- crate::input::send_drag_xtest_desktop(
+ crate::input::send_drag_xtest_desktop_with_modifiers(
screen_from_x.round() as i32,
screen_from_y.round() as i32,
screen_to_x.round() as i32,
@@ -10806,6 +10821,7 @@ impl Tool for DragTool {
button,
duration_ms,
steps,
+ &modifier_refs,
)
})
});
diff --git a/libs/cua-driver/tests/fixtures/apps/linux/gtk3/main.py b/libs/cua-driver/tests/fixtures/apps/linux/gtk3/main.py
index aaaa225dd5..fa4b5ad328 100755
--- a/libs/cua-driver/tests/fixtures/apps/linux/gtk3/main.py
+++ b/libs/cua-driver/tests/fixtures/apps/linux/gtk3/main.py
@@ -49,6 +49,8 @@ class HarnessWindow(Gtk.Window):
self._menu_action = "none"
self.key_presses = 0
self.hotkeys = 0
+ self._drag_modifier_seen = False
+ self.drag_events = 0
# Top-level scroller so every control is reachable even on a short window.
scroller = Gtk.ScrolledWindow()
@@ -102,9 +104,16 @@ class HarnessWindow(Gtk.Window):
self.click_target = aid(Gtk.Button(label="Click target (left / right / double)"), "btn-clicktarget")
self.click_target.connect("clicked", self.on_click_target)
self.click_target.connect("button-press-event", self.on_click_target_press)
+ self.click_target.add_events(
+ Gdk.EventMask.POINTER_MOTION_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK
+ )
+ self.click_target.connect("motion-notify-event", self.on_drag_motion)
+ self.click_target.connect("button-release-event", self.on_drag_release)
root.pack_start(self.click_target, False, False, 0)
self.click_status = Gtk.Label(label="last_action=none clicks=0", xalign=0)
root.pack_start(self.click_status, False, False, 0)
+ self.drag_status = Gtk.Label(label="drag_modifier=none drag_events=0", xalign=0)
+ root.pack_start(self.drag_status, False, False, 0)
# ── keyboard delivery ─────────────────────────────────────────────
self.key_status = Gtk.Label(label="last_key=none key_presses=0", xalign=0)
@@ -221,6 +230,10 @@ class HarnessWindow(Gtk.Window):
self.click_status.set_text(f"last_action={self._last_action} clicks={self.clicks}")
def on_click_target_press(self, _w, ev):
+ if ev.button == 1:
+ self._drag_modifier_seen = bool(
+ ev.state & Gdk.ModifierType.CONTROL_MASK
+ )
if ev.type == Gdk.EventType.DOUBLE_BUTTON_PRESS:
self._double_click_pending = True
self._last_action = "double_click"
@@ -231,6 +244,20 @@ class HarnessWindow(Gtk.Window):
elif ev.button == 1:
self._double_click_pending = False
+ def on_drag_motion(self, _w, ev):
+ if ev.state & Gdk.ModifierType.BUTTON1_MASK and ev.state & Gdk.ModifierType.CONTROL_MASK:
+ self._drag_modifier_seen = True
+ return False
+
+ def on_drag_release(self, _w, ev):
+ if ev.button == 1:
+ self.drag_events += 1
+ modifier = "ctrl" if self._drag_modifier_seen else "none"
+ self.drag_status.set_text(
+ f"drag_modifier={modifier} drag_events={self.drag_events}"
+ )
+ return False
+
def on_scale(self, s):
self.scale_status.set_text(f"slider_value={int(s.get_value())}")