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): deliver foreground pixel hotkeys through HID (#2464)

Francesco Bonaccibc1a58d7926f
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index aa5ea92879..cf764f86d2 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -364,7 +364,7 @@ A key press is never driver-verifiable → effect:"unverifiable"; confirm via sc
Press a key combination — e.g. `["cmd", "c"]` for Copy, `["cmd", "shift", "4"]` for screenshot selection. Follows the same `delivery_mode` ladder as click/type_text — it does NOT raise the window by default:
• `background` (default): post the combo to the target pid WITHOUT fronting or raising it — uses the macOS 14+ auth-message envelope so Chromium/Electron accept it as trusted live input. No focus steal. `window_id` here only targets the combo; it does not raise.
-• `foreground`: briefly front the window (NSMenu path, < 1 ms via SLPSSetFrontProcessWithOptions) so native menu key-equivalents (Cmd+Z, Cmd+W) dispatch, then restore the prior frontmost — the explicit escalation for menu-bar shortcuts on non-Chromium apps that ignore a background combo. Requires window_id.
+• `foreground`: briefly front the window (NSMenu path, < 1 ms via SLPSSetFrontProcessWithOptions) so native menu key-equivalents (Cmd+Z, Cmd+W) dispatch, then restore the prior frontmost — the explicit escalation for menu-bar shortcuts on non-Chromium apps that ignore a background combo. With x,y, the focused field receives the chord through the foreground HID queue (needed by native Chromium fields such as the omnibox). Requires window_id.
A combo is never driver-verifiable (no read-back) → effect:"unverifiable"; confirm via screenshot. NOTE: a keyboard combo does NOT focus a text field — to type into a backgrounded Electron input, establish real renderer focus with a PIXEL click first, then `type_text` (do not reach for a clipboard + Cmd+V dance).
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs
index dc27536a48..66eade282a 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs
@@ -19,6 +19,8 @@
#![cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
use std::any::Any;
+#[cfg(target_os = "macos")]
+use std::io::Write as _;
use std::panic::{self, AssertUnwindSafe};
use std::path::PathBuf;
use std::process::{Command, Stdio};
@@ -885,10 +887,105 @@ fn run_hotkey_action(fixture: &mut Fixture, addressing: &str, delivery: &str) ->
response.text()
);
assert_fixture_contains(fixture, "key_state=hotkey");
+ #[cfg(target_os = "macos")]
+ if fixture.name == "electron" && addressing == "px" && delivery == "foreground" {
+ run_macos_selection_hotkeys(fixture);
+ }
let passed = unverified_background_protocol_oracle(&response, delivery);
Observation::delivered_with_fixture_state(passed)
}
+#[cfg(target_os = "macos")]
+struct TextClipboardGuard {
+ previous: Vec<u8>,
+}
+
+#[cfg(target_os = "macos")]
+impl TextClipboardGuard {
+ fn replace(text: &str) -> Self {
+ let previous = Command::new("/usr/bin/pbpaste")
+ .output()
+ .expect("read macOS text pasteboard")
+ .stdout;
+ write_text_clipboard(text.as_bytes());
+ Self { previous }
+ }
+}
+
+#[cfg(target_os = "macos")]
+impl Drop for TextClipboardGuard {
+ fn drop(&mut self) {
+ write_text_clipboard(&self.previous);
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn write_text_clipboard(contents: &[u8]) {
+ let mut child = Command::new("/usr/bin/pbcopy")
+ .stdin(Stdio::piped())
+ .spawn()
+ .expect("start macOS text pasteboard writer");
+ child
+ .stdin
+ .as_mut()
+ .expect("pbcopy stdin")
+ .write_all(contents)
+ .expect("write macOS text pasteboard");
+ assert!(
+ child.wait().expect("wait for pbcopy").success(),
+ "pbcopy failed"
+ );
+}
+
+#[cfg(target_os = "macos")]
+fn run_macos_selection_hotkeys(fixture: &mut Fixture) {
+ const INITIAL: &str = "cua-hotkey-initial";
+ const REPLACEMENT: &str = "cua-hotkey-replacement";
+ const PASTED: &str = "cua-hotkey-pasted";
+
+ let state = snapshot(fixture);
+ let mut type_args = action_target_args(fixture, &state, "keyboard-input", "px", "foreground");
+ type_args["text"] = serde_json::json!(INITIAL);
+ let typed = fixture.driver.call("type_text", type_args);
+ assert!(!typed.is_error(), "seed selection fixture: {}", typed.raw);
+ assert_fixture_value(fixture, "keyboard-input", INITIAL);
+
+ let select_all = |fixture: &mut Fixture| {
+ let state = snapshot(fixture);
+ let mut args = action_target_args(fixture, &state, "keyboard-input", "px", "foreground");
+ args["keys"] = serde_json::json!(["cmd", "a"]);
+ let response = fixture.driver.call("hotkey", args);
+ assert!(!response.is_error(), "Cmd+A failed: {}", response.raw);
+ assert_eq!(response.verified(), Some(false), "{}", response.raw);
+ assert_eq!(
+ response.structured()["effect"],
+ "unverifiable",
+ "generic hotkeys must retain the honest unverifiable contract: {}",
+ response.raw
+ );
+ };
+
+ select_all(fixture);
+ let state = snapshot(fixture);
+ let mut replace_args =
+ action_target_args(fixture, &state, "keyboard-input", "px", "foreground");
+ replace_args["text"] = serde_json::json!(REPLACEMENT);
+ let replaced = fixture.driver.call("type_text", replace_args);
+ assert!(!replaced.is_error(), "replace selection: {}", replaced.raw);
+ assert_fixture_value(fixture, "keyboard-input", REPLACEMENT);
+
+ select_all(fixture);
+ let _clipboard = TextClipboardGuard::replace(PASTED);
+ let state = snapshot(fixture);
+ let mut paste_args = action_target_args(fixture, &state, "keyboard-input", "px", "foreground");
+ paste_args["keys"] = serde_json::json!(["cmd", "v"]);
+ let pasted = fixture.driver.call("hotkey", paste_args);
+ assert!(!pasted.is_error(), "Cmd+V failed: {}", pasted.raw);
+ assert_eq!(pasted.verified(), Some(false), "{}", pasted.raw);
+ assert_eq!(pasted.structured()["effect"], "unverifiable");
+ assert_fixture_value(fixture, "keyboard-input", PASTED);
+}
+
fn run_scroll_action(fixture: &mut Fixture, addressing: &str, delivery: &str) -> Observation {
let pre = snapshot(fixture);
let journal_before = fixture.journal.snapshot();
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
index 448ba712c4..16f6935328 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
@@ -1519,6 +1519,148 @@ fn run_background_type(spec: &BrowserSpec) {
});
}
+#[cfg(target_os = "macos")]
+fn native_omnibox(snapshot: &ToolResponse) -> (u64, f64, f64, String) {
+ let index = element_index_containing(snapshot.tree_text(), "Address and search bar")
+ .unwrap_or_else(|| panic!("native browser omnibox missing: {}", snapshot.tree_text()));
+ let elements = snapshot.structured()["elements"]
+ .as_array()
+ .expect("native window snapshot elements");
+ let element = elements
+ .iter()
+ .find(|element| element["element_index"].as_u64() == Some(index))
+ .unwrap_or_else(|| panic!("omnibox element [{index}] missing: {}", snapshot.raw));
+ let frame = element["frame"]
+ .as_object()
+ .unwrap_or_else(|| panic!("omnibox [{index}] has no frame: {}", snapshot.raw));
+ let window = elements
+ .iter()
+ .find(|element| element["role"] == "AXWindow")
+ .and_then(|element| element["frame"].as_object())
+ .unwrap_or_else(|| panic!("native browser window frame missing: {}", snapshot.raw));
+ let window_width = window["w"].as_f64().expect("browser window width");
+ let scale = snapshot.structured()["screenshot_width"]
+ .as_f64()
+ .expect("browser screenshot width")
+ / window_width;
+ let x = (frame["x"].as_f64().expect("omnibox x") - window["x"].as_f64().expect("window x")
+ + frame["w"].as_f64().expect("omnibox width") / 2.0)
+ * scale;
+ let y = (frame["y"].as_f64().expect("omnibox y") - window["y"].as_f64().expect("window y")
+ + frame["h"].as_f64().expect("omnibox height") / 2.0)
+ * scale;
+ (
+ index,
+ x,
+ y,
+ element["value"].as_str().unwrap_or_default().to_owned(),
+ )
+}
+
+#[cfg(target_os = "macos")]
+fn wait_for_native_omnibox_value(fixture: &mut BrowserFixture, expected: &str) {
+ let deadline = Instant::now() + Duration::from_secs(3);
+ loop {
+ let snapshot = fixture.driver.call(
+ "get_window_state",
+ serde_json::json!({
+ "pid": fixture.pid as i64,
+ "window_id": fixture.window_id,
+ "capture_mode": "ax",
+ }),
+ );
+ let (_, _, _, value) = native_omnibox(&snapshot);
+ if value == expected {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "native omnibox value did not reach {expected:?}; actual={value:?}"
+ );
+ thread::sleep(Duration::from_millis(50));
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn run_native_omnibox_select_all(spec: &BrowserSpec) {
+ let scenario = format!("macos-{}-native-omnibox-select-all", spec.name);
+ let case = CaseSpec::delivered(
+ scenario.clone(),
+ spec.name.clone(),
+ "standalone-chromium-native-chrome",
+ "hotkey_cmd_a_replace",
+ Targeting::Px,
+ Delivery::Foreground,
+ Scope::Window,
+ DriverRoute::MacosCgEventHid,
+ vec![OracleKind::FixtureState],
+ );
+ execute_case(case, |evidence| {
+ let mut fixture = launch_browser(spec, &scenario);
+ *evidence = recording_evidence(fixture.driver.recording_dir());
+ let snapshot = fixture.driver.call(
+ "get_window_state",
+ serde_json::json!({
+ "pid": fixture.pid as i64,
+ "window_id": fixture.window_id,
+ "capture_mode": "ax",
+ }),
+ );
+ let (index, x, y, _) = native_omnibox(&snapshot);
+ let initial = "cua-hotkey-initial";
+ let replacement = "cua-hotkey-replacement";
+ let seeded = fixture.driver.call(
+ "set_value",
+ serde_json::json!({
+ "pid": fixture.pid as i64,
+ "window_id": fixture.window_id,
+ "element_index": index,
+ "value": initial,
+ }),
+ );
+ assert!(!seeded.is_error(), "seed native omnibox: {}", seeded.raw);
+ wait_for_native_omnibox_value(&mut fixture, initial);
+
+ let selected = fixture.driver.call(
+ "hotkey",
+ serde_json::json!({
+ "pid": fixture.pid as i64,
+ "window_id": fixture.window_id,
+ "x": x,
+ "y": y,
+ "keys": ["cmd", "a"],
+ "delivery_mode": "foreground",
+ }),
+ );
+ assert!(
+ !selected.is_error(),
+ "native omnibox Cmd+A: {}",
+ selected.raw
+ );
+ assert_eq!(selected.verified(), Some(false), "{}", selected.raw);
+ assert_eq!(selected.structured()["effect"], "unverifiable");
+
+ let replaced = fixture.driver.call(
+ "type_text",
+ serde_json::json!({
+ "pid": fixture.pid as i64,
+ "window_id": fixture.window_id,
+ "x": x,
+ "y": y,
+ "text": replacement,
+ "delivery_mode": "foreground",
+ }),
+ );
+ assert!(
+ !replaced.is_error(),
+ "replace native omnibox: {}",
+ replaced.raw
+ );
+ wait_for_native_omnibox_value(&mut fixture, replacement);
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())
+ });
+}
+
#[cfg(target_os = "macos")]
fn run_generic_type_text_completion(spec: &BrowserSpec) {
let scenario = format!(
@@ -3457,6 +3599,11 @@ standalone_browser_test!(standalone_browser_roundtrip, run_roundtrip);
standalone_browser_test!(standalone_browser_semantic_state, run_semantic_state);
standalone_browser_test!(standalone_browser_background_type, run_background_type);
#[cfg(target_os = "macos")]
+standalone_browser_test!(
+ standalone_browser_native_omnibox_select_all,
+ run_native_omnibox_select_all
+);
+#[cfg(target_os = "macos")]
standalone_browser_test!(
standalone_browser_generic_type_text_completion,
run_generic_type_text_completion
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs
index fea370b2f8..1979b724a1 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs
@@ -467,6 +467,47 @@ pub fn with_foreground_assist(
with_menu_shortcut_activation(target_pid, target_wid, body)
}
+/// Activate an exact target window for a global HID keyboard action.
+///
+/// Unlike [`with_menu_shortcut_activation`], this helper must not run `action`
+/// when the private foreground SPI is unavailable: a global HID event has no
+/// pid addressing and would otherwise land in whichever application is
+/// currently frontmost. The short settles keep the target frontmost until
+/// WindowServer has routed both sides of the key chord, then restore the prior
+/// process even when the action fails.
+pub fn with_foreground_hid_activation(
+ target_pid: libc::pid_t,
+ target_wid: u32,
+ action: impl FnOnce() -> anyhow::Result<()>,
+) -> anyhow::Result<()> {
+ let set_front = set_front_process_fn()
+ .ok_or_else(|| anyhow::anyhow!("foreground HID delivery is unavailable"))?;
+
+ let mut prev_psn = [0u8; 8];
+ let prev_ok = get_front_process_fn()
+ .map(|f| unsafe { f(prev_psn.as_mut_ptr() as *mut c_void) } == 0)
+ .unwrap_or(false);
+
+ let mut target_psn = [0u8; 8];
+ if !get_process_psn_for_window(target_wid, target_pid, &mut target_psn) {
+ anyhow::bail!("could not resolve target window for foreground HID delivery");
+ }
+ let activated = unsafe { set_front(target_psn.as_ptr() as *const c_void, target_wid, 0x400) };
+ if activated != 0 {
+ anyhow::bail!("WindowServer rejected foreground HID activation");
+ }
+
+ std::thread::sleep(std::time::Duration::from_millis(40));
+ let result = action();
+ std::thread::sleep(std::time::Duration::from_millis(40));
+
+ if prev_ok {
+ unsafe { set_front(prev_psn.as_ptr() as *const c_void, 0, 0x400) };
+ }
+
+ result
+}
+
/// Activate `target_pid`'s window `target_wid` for NSMenu key dispatch, run `action`,
/// then immediately restore the prior frontmost process.
///
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs
index 93c6ce6a99..1f74f3c63a 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs
@@ -43,7 +43,9 @@ fn def() -> &'static ToolDef {
SLPSSetFrontProcessWithOptions) so native menu key-equivalents \
(Cmd+Z, Cmd+W) dispatch, then restore the prior frontmost — the \
explicit escalation for menu-bar shortcuts on non-Chromium apps that \
- ignore a background combo. Requires window_id.\n\n\
+ ignore a background combo. With x,y, the focused field receives \
+ the chord through the foreground HID queue (needed by native \
+ Chromium fields such as the omnibox). Requires window_id.\n\n\
A combo is never driver-verifiable (no read-back) → effect:\"unverifiable\"; \
confirm via screenshot. NOTE: a keyboard combo does NOT focus a text \
field — to type into a backgrounded Electron input, establish real \
@@ -186,9 +188,9 @@ impl Tool for HotkeyTool {
let delivery_mode = super::DeliveryMode::parse(args.opt_str("delivery_mode").as_deref());
let fg = delivery_mode.is_foreground();
- // px form: pixel-click to focus, then the combo acts on the focused field
- // (e.g. Cmd+V into a Chromium input). After it, deliver the combo via the
- // plain background path (the focus-click already fronted if fg).
+ // px form: focus the field before sending the combo. Foreground delivery
+ // still needs to front the target for the chord itself: the focus helper
+ // restores the previous app before returning.
let px_focus = {
let px = args.get("x").and_then(|v| v.as_f64());
let py = args.get("y").and_then(|v| v.as_f64());
@@ -234,11 +236,22 @@ impl Tool for HotkeyTool {
|| async move {
tokio::task::spawn_blocking(move || {
let m: Vec<&str> = modifiers.iter().map(String::as_str).collect();
- // px-focus already clicked/fronted the target → deliver background.
- match (fg && !px_focus, window_id) {
+ match (fg, px_focus, window_id) {
+ // Chrome's native omnibox and Chromium/Electron inputs
+ // require a genuine foreground HID chord. Keep the exact
+ // target frontmost until both key events are consumed;
+ // otherwise Cmd+A/Cmd+V can be silently ignored.
+ (true, true, Some(wid)) => {
+ crate::input::skylight::with_foreground_hid_activation(
+ pid as libc::pid_t,
+ wid,
+ || crate::input::keyboard::press_key_global(&key, &m),
+ )?;
+ Ok(())
+ }
// foreground rung: briefly front the window so NSMenu key
// equivalents dispatch, then restore prior frontmost.
- (true, Some(wid)) => {
+ (true, false, Some(wid)) => {
crate::input::skylight::with_menu_shortcut_activation(
pid as libc::pid_t,
wid,
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
index 045c7d6517..19c4dfa63d 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
@@ -131,10 +131,11 @@ mod interactive_observation_tests {
}
}
-/// px-focus for the keyboard family (type_text / press_key / hotkey): pixel-click
-/// at (x,y) to establish real renderer focus before a keystroke — the *element px
-/// action* form of a keyboard tool. Reuses ClickTool's exact coordinate
-/// translation + delivery_mode so it lands on the same pixel a px-click would.
+/// px-focus for the keyboard family (type_text / press_key / hotkey): focus the
+/// element at (x,y) before a keystroke — the *element px action* form of a
+/// keyboard tool. Prefer non-destructive AX focus so an existing selection is
+/// retained; the foreground rung falls back to a real pixel click when needed.
+/// Reuses ClickTool's exact coordinate translation and delivery mode.
/// `Ok(())` on success; `Err(ToolResult)` short-circuits the caller.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn focus_by_pixel(
@@ -151,16 +152,51 @@ pub(crate) async fn focus_by_pixel(
use cua_driver_core::tool::Tool;
let mut click_args = serde_json::json!({
"pid": pid, "x": x, "y": y,
- "delivery_mode": if foreground { "foreground" } else { "background" },
- "action": if foreground { "press" } else { "focus" },
+ "delivery_mode": "background",
+ "action": "focus",
});
if let Some(wid) = window_id {
click_args["window_id"] = serde_json::json!(wid);
}
- if let Some(s) = session {
+ if let Some(ref s) = session {
click_args["session"] = serde_json::json!(s);
}
- if let Some(s) = session_id {
+ if let Some(ref s) = session_id {
+ click_args["_session_id"] = serde_json::json!(s);
+ }
+ if from_zoom {
+ click_args["from_zoom"] = serde_json::json!(true);
+ }
+ let focus = click::ClickTool::new(state.clone())
+ .invoke(click_args)
+ .await;
+ if focus.is_error != Some(true) {
+ // AXFocused is non-destructive: unlike a second real click, it keeps a
+ // Cmd+A selection intact before a follow-up type_text or Cmd+V.
+ tokio::time::sleep(std::time::Duration::from_millis(120)).await;
+ return Ok(());
+ }
+
+ if !foreground {
+ return Err(cua_driver_core::protocol::ToolResult::error(format!(
+ "focus pixel-click at ({x:.0},{y:.0}) failed."
+ )));
+ }
+
+ // Some renderer surfaces do not expose a usable AX focus action. The
+ // explicit foreground rung retains its real-click fallback for them.
+ let mut click_args = serde_json::json!({
+ "pid": pid, "x": x, "y": y,
+ "delivery_mode": "foreground",
+ "action": "press",
+ });
+ if let Some(wid) = window_id {
+ click_args["window_id"] = serde_json::json!(wid);
+ }
+ if let Some(ref s) = session {
+ click_args["session"] = serde_json::json!(s);
+ }
+ if let Some(ref s) = session_id {
click_args["_session_id"] = serde_json::json!(s);
}
if from_zoom {