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
feat(cua-driver): add persistent macOS interactive input sessions
Francesco Bonacci2dad3e519e17
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdxindex 5bc2e5ded3..78b3511142 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx@@ -179,7 +179,7 @@ Force-terminate a process by pid (kill -9 equivalent on macOS / Linux; taskkill### `bring_to_front`-Persistently activate an app so it genuinely holds macOS foreground, then leave it there. Most input does NOT need this — every macOS dispatch reaches backgrounded windows, and `dispatch:"foreground"` does its own brief front→act→restore. Reach for `bring_to_front` only for a focus-proxy surface that re-arms its own input channel on activation and must stay frontmost across the interaction — chiefly a remote-desktop client (Microsoft Windows App / RDP), where the brief flash drops keystrokes. Activates the owning app by pid (`NSRunningApplication.activate`); `window_id` is accepted for parity but activation is app-level. This DOES steal foreground — explicit opt-in, never used by the input ladder.+Persistently activate an app so it genuinely holds macOS foreground, then leave it there. Most input does NOT need this — every macOS dispatch reaches backgrounded windows, and `dispatch:"foreground"` does its own brief front→act→restore. Reach for `bring_to_front` only for a focus-proxy surface that re-arms its own input channel on activation and must stay frontmost across the interaction — chiefly a remote-desktop client (Microsoft Windows App / RDP), where the brief flash drops keystrokes. Fronts the exact macOS window through WindowServer when `window_id` is present, with app-level Cocoa activation as a fallback. This DOES steal foreground — explicit opt-in, never used by the input ladder.**Arguments:**diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/interactive.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/interactive.rsnew file mode 100644index 0000000000..38c8404850--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/interactive.rs@@ -0,0 +1,786 @@+//! Low-latency, stateful input delivery to one macOS window.+//!+//! Automation tools intentionally trade latency for verification, focus+//! containment, and human-readable results. Interactive remoting has a+//! different contract: preserve the source device's event ordering and+//! semantics while doing as little work as possible between receipt and+//! native dispatch. This module provides that lower-level contract without+//! changing the existing one-shot tools.++use std::{+ sync::{+ mpsc::{self, Receiver, SyncSender, TrySendError},+ Mutex,+ },+ thread::{self, JoinHandle},+ time::{Duration, Instant},+};++use core_graphics::{+ event::{+ CGEvent, CGEventFlags, CGEventTapLocation, CGEventType, CGMouseButton, EventField,+ ScrollEventUnit,+ },+ event_source::{CGEventSource, CGEventSourceStateID},+ geometry::CGPoint,+};+use foreign_types::ForeignType;++const MAX_BATCH_EVENTS: usize = 256;+const TEXT_EVENT_UTF16_UNITS: usize = 20;+const SCROLL_PHASE_FIELD: u32 = 99;+const SCROLL_MOMENTUM_PHASE_FIELD: u32 = 123;++/// Controls whether events remain PID-routed or use the foreground HID queue.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum InteractiveDeliveryMode {+ Background,+ /// Keep the target frontmost for the lifetime of the input session and+ /// deliver through the same global HID queue as physical input.+ PersistentForeground,+}++#[derive(Debug, Clone)]+pub struct InteractiveInputConfig {+ pub pid: i32,+ pub window_id: u32,+ pub delivery_mode: InteractiveDeliveryMode,+ /// Number of batches waiting for the native worker. A full queue returns+ /// backpressure to the caller instead of silently dropping input.+ pub queue_capacity: usize,+}++impl InteractiveInputConfig {+ pub fn persistent_foreground(pid: i32, window_id: u32) -> Self {+ Self {+ pid,+ window_id,+ delivery_mode: InteractiveDeliveryMode::PersistentForeground,+ queue_capacity: 32,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Modifier {+ Command,+ Shift,+ Option,+ Control,+ Function,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum KeyState {+ Down,+ Up,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PointerButton {+ Left,+ Right,+ Middle,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PointerPhase {+ Move,+ Down,+ Up,+ Cancel,+}++/// Native macOS scroll gesture phase. Keeping phase and momentum distinct is+/// important for inertial scrolling and overscroll behavior.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum GesturePhase {+ None,+ MayBegin,+ Began,+ Changed,+ Ended,+ Cancelled,+}++#[derive(Debug, Clone, PartialEq)]+pub enum InteractiveInputEvent {+ /// Commit already-composed Unicode text. This is intentionally distinct+ /// from physical key events so IME/dead-key composition is not replayed.+ TextCommit { text: String },+ Key {+ key: String,+ state: KeyState,+ modifiers: Vec<Modifier>,+ repeat: bool,+ },+ Pointer {+ phase: PointerPhase,+ button: Option<PointerButton>,+ x_normalized: f64,+ y_normalized: f64,+ modifiers: Vec<Modifier>,+ },+ Scroll {+ x_normalized: f64,+ y_normalized: f64,+ delta_x: f64,+ delta_y: f64,+ phase: GesturePhase,+ momentum_phase: GesturePhase,+ precise: bool,+ },+}++#[derive(Debug, Clone, PartialEq)]+pub struct InteractiveInputBatch {+ pub first_sequence: u64,+ pub events: Vec<InteractiveInputEvent>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct InteractiveInputReceipt {+ pub through_sequence: u64,+ pub event_count: usize,+ pub dispatch_micros: u64,+}++#[derive(Debug, thiserror::Error)]+pub enum InteractiveInputError {+ #[error("interactive input target is invalid: {0}")]+ InvalidTarget(String),+ #[error("interactive input batch is invalid: {0}")]+ InvalidBatch(String),+ #[error("interactive input queue is full")]+ Backpressure,+ #[error("interactive input session is closed")]+ Closed,+ #[error("native input delivery failed: {0}")]+ Native(String),+}++type Result<T> = std::result::Result<T, InteractiveInputError>;++struct WorkItem {+ batch: InteractiveInputBatch,+ reply: mpsc::Sender<Result<InteractiveInputReceipt>>,+}++/// A persistent, thread-safe handle to one native input worker.+///+/// The worker owns and reuses one `CGEventSource`, pointer-button state, click+/// grouping, and fractional scroll residuals. Native CoreGraphics objects+/// never cross threads.+pub struct InteractiveInputSession {+ sender: Option<SyncSender<WorkItem>>,+ worker: Mutex<Option<JoinHandle<()>>>,+}++impl InteractiveInputSession {+ pub fn open(config: InteractiveInputConfig) -> Result<Self> {+ validate_config(&config)?;+ let capacity = config.queue_capacity.max(1);+ let (sender, receiver) = mpsc::sync_channel(capacity);+ let (ready_tx, ready_rx) = mpsc::channel();+ let worker = thread::Builder::new()+ .name(format!("cua-input-{}-{}", config.pid, config.window_id))+ .spawn(move || run_worker(config, receiver, ready_tx))+ .map_err(|e| InteractiveInputError::Native(e.to_string()))?;++ match ready_rx.recv() {+ Ok(Ok(())) => Ok(Self {+ sender: Some(sender),+ worker: Mutex::new(Some(worker)),+ }),+ Ok(Err(error)) => {+ let _ = worker.join();+ Err(error)+ }+ Err(_) => {+ let _ = worker.join();+ Err(InteractiveInputError::Closed)+ }+ }+ }++ /// Deliver one ordered batch and wait only until CoreGraphics has accepted+ /// every event. This is a native-dispatch acknowledgement, not application+ /// state verification.+ pub fn dispatch(&self, batch: InteractiveInputBatch) -> Result<InteractiveInputReceipt> {+ validate_batch(&batch)?;+ let (reply, receipt) = mpsc::channel();+ let item = WorkItem { batch, reply };+ let sender = self.sender.as_ref().ok_or(InteractiveInputError::Closed)?;+ match sender.try_send(item) {+ Ok(()) => receipt.recv().map_err(|_| InteractiveInputError::Closed)?,+ Err(TrySendError::Full(_)) => Err(InteractiveInputError::Backpressure),+ Err(TrySendError::Disconnected(_)) => Err(InteractiveInputError::Closed),+ }+ }+}++impl Drop for InteractiveInputSession {+ fn drop(&mut self) {+ // Disconnecting the final sender lets the worker drain accepted input+ // before exiting. No accepted key-up or pointer-up is discarded.+ self.sender.take();+ if let Ok(mut worker) = self.worker.lock() {+ if let Some(worker) = worker.take() {+ let _ = worker.join();+ }+ }+ }+}++fn validate_config(config: &InteractiveInputConfig) -> Result<()> {+ if config.pid <= 0 {+ return Err(InteractiveInputError::InvalidTarget(+ "pid must be positive".to_owned(),+ ));+ }+ if config.window_id == 0 {+ return Err(InteractiveInputError::InvalidTarget(+ "window_id must be non-zero".to_owned(),+ ));+ }+ target_window_bounds(config)?;+ Ok(())+}++fn target_window_bounds(config: &InteractiveInputConfig) -> Result<crate::windows::WindowBounds> {+ crate::windows::all_windows()+ .into_iter()+ .find(|window| window.window_id == config.window_id && window.pid == config.pid)+ .map(|window| window.bounds)+ .ok_or_else(|| {+ InteractiveInputError::InvalidTarget(format!(+ "window {} is not owned by pid {}",+ config.window_id, config.pid+ ))+ })+}++fn validate_batch(batch: &InteractiveInputBatch) -> Result<()> {+ if batch.events.is_empty() {+ return Err(InteractiveInputError::InvalidBatch(+ "events must not be empty".to_owned(),+ ));+ }+ if batch.events.len() > MAX_BATCH_EVENTS {+ return Err(InteractiveInputError::InvalidBatch(format!(+ "at most {MAX_BATCH_EVENTS} events are allowed"+ )));+ }+ batch+ .first_sequence+ .checked_add(batch.events.len() as u64 - 1)+ .ok_or_else(|| InteractiveInputError::InvalidBatch("sequence overflow".to_owned()))?;++ for event in &batch.events {+ match event {+ InteractiveInputEvent::TextCommit { text } if text.is_empty() => {+ return Err(InteractiveInputError::InvalidBatch(+ "text commits must not be empty".to_owned(),+ ));+ }+ InteractiveInputEvent::Pointer {+ x_normalized,+ y_normalized,+ ..+ }+ | InteractiveInputEvent::Scroll {+ x_normalized,+ y_normalized,+ ..+ } if !normalized(*x_normalized) || !normalized(*y_normalized) => {+ return Err(InteractiveInputError::InvalidBatch(+ "pointer coordinates must be finite and within [0, 1]".to_owned(),+ ));+ }+ InteractiveInputEvent::Scroll {+ delta_x, delta_y, ..+ } if !delta_x.is_finite() || !delta_y.is_finite() => {+ return Err(InteractiveInputError::InvalidBatch(+ "scroll deltas must be finite".to_owned(),+ ));+ }+ _ => {}+ }+ }+ Ok(())+}++fn normalized(value: f64) -> bool {+ value.is_finite() && (0.0..=1.0).contains(&value)+}++fn run_worker(+ config: InteractiveInputConfig,+ receiver: Receiver<WorkItem>,+ ready: mpsc::Sender<Result<()>>,+) {+ let source = match CGEventSource::new(CGEventSourceStateID::HIDSystemState) {+ Ok(source) => source,+ Err(_) => {+ let _ = ready.send(Err(InteractiveInputError::Native(+ "CGEventSource::new failed".to_owned(),+ )));+ return;+ }+ };+ let bounds = match target_window_bounds(&config) {+ Ok(bounds) => bounds,+ Err(error) => {+ let _ = ready.send(Err(error));+ return;+ }+ };+ let mut state = NativeInputState::new(config, source, bounds);+ if let Err(error) = state.prepare_target() {+ let _ = ready.send(Err(error));+ return;+ }+ if ready.send(Ok(())).is_err() {+ return;+ }++ for item in receiver {+ let started = Instant::now();+ let result = state+ .dispatch_batch(&item.batch)+ .map(|()| InteractiveInputReceipt {+ through_sequence: item.batch.first_sequence + item.batch.events.len() as u64 - 1,+ event_count: item.batch.events.len(),+ dispatch_micros: started.elapsed().as_micros().min(u64::MAX as u128) as u64,+ });+ let _ = item.reply.send(result);+ }+}++struct NativeInputState {+ config: InteractiveInputConfig,+ source: CGEventSource,+ pressed_button: Option<PointerButton>,+ click_group_id: i64,+ scroll_residual_x: f64,+ scroll_residual_y: f64,+ bounds: crate::windows::WindowBounds,+ last_bounds_refresh: Instant,+}++impl NativeInputState {+ fn new(+ config: InteractiveInputConfig,+ source: CGEventSource,+ bounds: crate::windows::WindowBounds,+ ) -> Self {+ Self {+ config,+ source,+ pressed_button: None,+ click_group_id: 1,+ scroll_residual_x: 0.0,+ scroll_residual_y: 0.0,+ bounds,+ last_bounds_refresh: Instant::now(),+ }+ }++ fn prepare_target(&self) -> Result<()> {+ if self.config.delivery_mode == InteractiveDeliveryMode::PersistentForeground+ && crate::apps::frontmost_pid() != Some(self.config.pid)+ {+ if !crate::input::skylight::set_front_process_persistently(+ self.config.pid as libc::pid_t,+ self.config.window_id,+ ) {+ crate::apps::activate_pid(self.config.pid);+ }+ // Paid once when opening the session, never on the event hot path.+ thread::sleep(std::time::Duration::from_millis(40));+ }+ Ok(())+ }++ fn dispatch_batch(&mut self, batch: &InteractiveInputBatch) -> Result<()> {+ if self.config.delivery_mode == InteractiveDeliveryMode::PersistentForeground+ && crate::apps::frontmost_pid() != Some(self.config.pid)+ {+ self.prepare_target()?;+ }+ self.refresh_bounds_if_due()?;+ for event in &batch.events {+ self.dispatch_event(event)?;+ }+ Ok(())+ }++ fn dispatch_event(&mut self, event: &InteractiveInputEvent) -> Result<()> {+ match event {+ InteractiveInputEvent::TextCommit { text } => self.commit_text(text),+ InteractiveInputEvent::Key {+ key,+ state,+ modifiers,+ repeat,+ } => self.key(key, *state, modifiers, *repeat),+ InteractiveInputEvent::Pointer {+ phase,+ button,+ x_normalized,+ y_normalized,+ modifiers,+ } => self.pointer(*phase, *button, *x_normalized, *y_normalized, modifiers),+ InteractiveInputEvent::Scroll {+ x_normalized,+ y_normalized,+ delta_x,+ delta_y,+ phase,+ momentum_phase,+ precise,+ } => self.scroll(+ *x_normalized,+ *y_normalized,+ *delta_x,+ *delta_y,+ *phase,+ *momentum_phase,+ *precise,+ ),+ }+ }++ fn commit_text(&self, text: &str) -> Result<()> {+ for chunk in text_event_chunks(text) {+ let down = CGEvent::new_keyboard_event(self.source.clone(), 0, true)+ .map_err(|_| native("keyboard down creation failed"))?;+ down.set_string_from_utf16_unchecked(&chunk);+ down.set_flags(CGEventFlags::CGEventFlagNull);+ self.post_keyboard(&down);++ let up = CGEvent::new_keyboard_event(self.source.clone(), 0, false)+ .map_err(|_| native("keyboard up creation failed"))?;+ up.set_string_from_utf16_unchecked(&chunk);+ up.set_flags(CGEventFlags::CGEventFlagNull);+ self.post_keyboard(&up);+ }+ Ok(())+ }++ fn key(&self, key: &str, state: KeyState, modifiers: &[Modifier], repeat: bool) -> Result<()> {+ let key_code = super::keyboard::key_name_to_code(key)+ .map_err(|error| InteractiveInputError::InvalidBatch(error.to_string()))?;+ let event =+ CGEvent::new_keyboard_event(self.source.clone(), key_code, state == KeyState::Down)+ .map_err(|_| native("keyboard event creation failed"))?;+ event.set_flags(modifier_flags(modifiers));+ event.set_integer_value_field(EventField::KEYBOARD_EVENT_AUTOREPEAT, i64::from(repeat));+ self.post_keyboard(&event);+ Ok(())+ }++ fn pointer(+ &mut self,+ phase: PointerPhase,+ button: Option<PointerButton>,+ x_normalized: f64,+ y_normalized: f64,+ modifiers: &[Modifier],+ ) -> Result<()> {+ let (point, window_local) = self.resolve_point(x_normalized, y_normalized)?;+ let effective_button = button+ .or(self.pressed_button)+ .unwrap_or(PointerButton::Left);+ let (event_type, cg_button) =+ if phase == PointerPhase::Move && button.is_none() && self.pressed_button.is_none() {+ (CGEventType::MouseMoved, CGMouseButton::Left)+ } else {+ pointer_event_type(phase, effective_button)+ };+ let event = CGEvent::new_mouse_event(self.source.clone(), event_type, point, cg_button)+ .map_err(|_| native("pointer event creation failed"))?;+ event.set_flags(modifier_flags(modifiers));++ if phase == PointerPhase::Down {+ self.pressed_button = Some(effective_button);+ self.click_group_id = self.click_group_id.wrapping_add(1).max(1);+ }+ self.post_pointer(+ &event,+ window_local,+ effective_button,+ matches!(phase, PointerPhase::Down | PointerPhase::Up),+ );+ if matches!(phase, PointerPhase::Up | PointerPhase::Cancel) {+ self.pressed_button = None;+ }+ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ fn scroll(+ &mut self,+ x_normalized: f64,+ y_normalized: f64,+ delta_x: f64,+ delta_y: f64,+ phase: GesturePhase,+ momentum_phase: GesturePhase,+ precise: bool,+ ) -> Result<()> {+ let (point, window_local) = self.resolve_point(x_normalized, y_normalized)?;+ self.scroll_residual_x += delta_x;+ self.scroll_residual_y += delta_y;+ let integral_x = extract_integral(&mut self.scroll_residual_x);+ let integral_y = extract_integral(&mut self.scroll_residual_y);++ // Preserve zero-delta phase transitions. AppKit uses the ended/cancelled+ // event to stop momentum and rubber-banding even when its delta is zero.+ if integral_x == 0+ && integral_y == 0+ && phase == GesturePhase::None+ && momentum_phase == GesturePhase::None+ {+ return Ok(());+ }++ let units = if precise {+ ScrollEventUnit::PIXEL+ } else {+ ScrollEventUnit::LINE+ };+ let event =+ CGEvent::new_scroll_event(self.source.clone(), units, 2, integral_y, integral_x, 0)+ .map_err(|_| native("scroll event creation failed"))?;+ event.set_integer_value_field(+ EventField::SCROLL_WHEEL_EVENT_IS_CONTINUOUS,+ i64::from(precise),+ );+ event.set_integer_value_field(SCROLL_PHASE_FIELD, scroll_phase_value(phase));+ event.set_integer_value_field(+ SCROLL_MOMENTUM_PHASE_FIELD,+ momentum_phase_value(momentum_phase),+ );+ unsafe { CGEventSetLocation(event.as_ptr().cast(), point.x, point.y) };++ if self.is_foreground() {+ event.post(CGEventTapLocation::HID);+ } else {+ super::mouse::post_mouse_event(+ self.config.pid,+ &event,+ Some(window_local),+ Some(self.config.window_id),+ Some(self.click_group_id),+ 0,+ 0,+ 0,+ );+ }+ Ok(())+ }++ fn resolve_point(&self, x: f64, y: f64) -> Result<(CGPoint, (f64, f64))> {+ let local = (x * self.bounds.width, y * self.bounds.height);+ Ok((+ CGPoint::new(self.bounds.x + local.0, self.bounds.y + local.1),+ local,+ ))+ }++ fn refresh_bounds_if_due(&mut self) -> Result<()> {+ // Window enumeration is substantially more expensive than event+ // creation. A short cache preserves resize responsiveness without+ // putting a WindowServer round trip on every pointer sample.+ if self.last_bounds_refresh.elapsed() >= Duration::from_millis(100) {+ self.bounds = target_window_bounds(&self.config)?;+ self.last_bounds_refresh = Instant::now();+ }+ Ok(())+ }++ fn post_keyboard(&self, event: &CGEvent) {+ if self.is_foreground() {+ event.post(CGEventTapLocation::HID);+ } else {+ super::keyboard::post_keyboard_event(self.config.pid, event);+ }+ }++ fn post_pointer(+ &self,+ event: &CGEvent,+ window_local: (f64, f64),+ button: PointerButton,+ click: bool,+ ) {+ if self.is_foreground() {+ event.post(CGEventTapLocation::HID);+ } else {+ super::mouse::post_mouse_event(+ self.config.pid,+ event,+ Some(window_local),+ Some(self.config.window_id),+ Some(self.click_group_id),+ i64::from(click),+ pointer_button_number(button),+ if click { 3 } else { 0 },+ );+ }+ }++ fn is_foreground(&self) -> bool {+ self.config.delivery_mode == InteractiveDeliveryMode::PersistentForeground+ }+}++fn modifier_flags(modifiers: &[Modifier]) -> CGEventFlags {+ modifiers+ .iter()+ .fold(CGEventFlags::CGEventFlagNull, |flags, modifier| {+ flags+ | match modifier {+ Modifier::Command => CGEventFlags::CGEventFlagCommand,+ Modifier::Shift => CGEventFlags::CGEventFlagShift,+ Modifier::Option => CGEventFlags::CGEventFlagAlternate,+ Modifier::Control => CGEventFlags::CGEventFlagControl,+ Modifier::Function => CGEventFlags::CGEventFlagSecondaryFn,+ }+ })+}++fn pointer_event_type(phase: PointerPhase, button: PointerButton) -> (CGEventType, CGMouseButton) {+ match (phase, button) {+ (PointerPhase::Down, PointerButton::Left) => {+ (CGEventType::LeftMouseDown, CGMouseButton::Left)+ }+ (PointerPhase::Up | PointerPhase::Cancel, PointerButton::Left) => {+ (CGEventType::LeftMouseUp, CGMouseButton::Left)+ }+ (PointerPhase::Move, PointerButton::Left) => {+ (CGEventType::LeftMouseDragged, CGMouseButton::Left)+ }+ (PointerPhase::Down, PointerButton::Right) => {+ (CGEventType::RightMouseDown, CGMouseButton::Right)+ }+ (PointerPhase::Up | PointerPhase::Cancel, PointerButton::Right) => {+ (CGEventType::RightMouseUp, CGMouseButton::Right)+ }+ (PointerPhase::Move, PointerButton::Right) => {+ (CGEventType::RightMouseDragged, CGMouseButton::Right)+ }+ (PointerPhase::Down, PointerButton::Middle) => {+ (CGEventType::OtherMouseDown, CGMouseButton::Center)+ }+ (PointerPhase::Up | PointerPhase::Cancel, PointerButton::Middle) => {+ (CGEventType::OtherMouseUp, CGMouseButton::Center)+ }+ (PointerPhase::Move, PointerButton::Middle) => {+ (CGEventType::OtherMouseDragged, CGMouseButton::Center)+ }+ }+}++fn pointer_button_number(button: PointerButton) -> i64 {+ match button {+ PointerButton::Left => 0,+ PointerButton::Right => 1,+ PointerButton::Middle => 2,+ }+}++fn extract_integral(residual: &mut f64) -> i32 {+ let value = residual.trunc().clamp(i32::MIN as f64, i32::MAX as f64) as i32;+ *residual -= f64::from(value);+ value+}++fn text_event_chunks(text: &str) -> Vec<Vec<u16>> {+ let mut chunks = Vec::new();+ let mut current = Vec::with_capacity(TEXT_EVENT_UTF16_UNITS);+ for character in text.chars() {+ let mut encoded = [0_u16; 2];+ let units = character.encode_utf16(&mut encoded);+ if !current.is_empty() && current.len() + units.len() > TEXT_EVENT_UTF16_UNITS {+ chunks.push(std::mem::take(&mut current));+ current = Vec::with_capacity(TEXT_EVENT_UTF16_UNITS);+ }+ current.extend_from_slice(units);+ }+ if !current.is_empty() {+ chunks.push(current);+ }+ chunks+}++fn scroll_phase_value(phase: GesturePhase) -> i64 {+ match phase {+ GesturePhase::None => 0,+ GesturePhase::MayBegin => 128,+ GesturePhase::Began => 1,+ GesturePhase::Changed => 2,+ GesturePhase::Ended => 4,+ GesturePhase::Cancelled => 8,+ }+}++fn momentum_phase_value(phase: GesturePhase) -> i64 {+ match phase {+ GesturePhase::None => 0,+ GesturePhase::Began | GesturePhase::MayBegin => 1,+ GesturePhase::Changed => 2,+ GesturePhase::Ended | GesturePhase::Cancelled => 3,+ }+}++fn native(message: &str) -> InteractiveInputError {+ InteractiveInputError::Native(message.to_owned())+}++extern "C" {+ fn CGEventSetLocation(event: *mut std::ffi::c_void, x: f64, y: f64);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn preserves_fractional_scroll_until_it_forms_pixels() {+ let mut residual = 0.0;+ residual += 0.4;+ assert_eq!(extract_integral(&mut residual), 0);+ residual += 0.8;+ assert_eq!(extract_integral(&mut residual), 1);+ assert!((residual - 0.2).abs() < f64::EPSILON * 4.0);+ }++ #[test]+ fn maps_native_scroll_phases() {+ assert_eq!(scroll_phase_value(GesturePhase::MayBegin), 128);+ assert_eq!(scroll_phase_value(GesturePhase::Began), 1);+ assert_eq!(scroll_phase_value(GesturePhase::Changed), 2);+ assert_eq!(scroll_phase_value(GesturePhase::Ended), 4);+ assert_eq!(momentum_phase_value(GesturePhase::Changed), 2);+ assert_eq!(momentum_phase_value(GesturePhase::Ended), 3);+ }++ #[test]+ fn rejects_non_finite_or_out_of_range_coordinates() {+ for value in [f64::NAN, f64::INFINITY, -0.01, 1.01] {+ assert!(!normalized(value));+ }+ assert!(normalized(0.0));+ assert!(normalized(1.0));+ }++ #[test]+ fn text_chunks_do_not_split_surrogate_pairs() {+ let chunks = text_event_chunks(&format!("{}😀", "a".repeat(19)));+ assert_eq!(chunks.len(), 2);+ assert_eq!(chunks[0].len(), 19);+ assert_eq!(chunks[1], "😀".encode_utf16().collect::<Vec<_>>());+ }+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/keyboard.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/keyboard.rsindex f4aef93504..be0366cc41 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/keyboard.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/keyboard.rs@@ -174,7 +174,7 @@ pub fn type_text_global(text: &str, inter_char_delay_ms: u64) -> anyhow::Result</// Post a keyboard event to `pid` via SLEventPostToPid (with auth message for/// Chromium/Electron support) or fall back to CGEvent::post_to_pid.-fn post_keyboard_event(pid: i32, event: &CGEvent) {+pub(super) fn post_keyboard_event(pid: i32, event: &CGEvent) {let event_ptr = event.as_ptr() as *mut std::ffi::c_void;// attachAuthMessage = true: required for Chromium keyboard on macOS 14+.if !crate::input::skylight::post_to_pid(pid as libc::pid_t, event_ptr, true) {@@ -229,7 +229,7 @@ fn modifier_flags(modifiers: &[&str]) -> CGEventFlags {flags}-fn key_name_to_code(key: &str) -> anyhow::Result<u16> {+pub(super) fn key_name_to_code(key: &str) -> anyhow::Result<u16> {let code = match key.to_lowercase().as_str() {"return" | "enter" => 36,"tab" => 48,diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/mod.rsindex b4b311a723..7411233b96 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/mod.rs@@ -9,10 +9,16 @@//! the activity-monitor tickle required for live-input detection.pub mod ax_actions;+pub mod interactive;pub mod keyboard;pub mod mouse;pub mod skylight;pub use ax_actions::perform_ax_action;+pub use interactive::{+ GesturePhase, InteractiveDeliveryMode, InteractiveInputBatch, InteractiveInputConfig,+ InteractiveInputError, InteractiveInputEvent, InteractiveInputReceipt, InteractiveInputSession,+ KeyState, Modifier, PointerButton, PointerPhase,+};pub use keyboard::{hotkey, press_key, type_text};pub use mouse::click_at_xy;diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rsindex 9a8fe09680..4c8df07f19 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs@@ -842,7 +842,7 @@ fn right_click_at_xy_inner(/// `button_number` MUST match the button encoded in the event type (right-down/// stamped with f3=0 routes as a left-click on the receiving side — this was the/// right-click-lands-as-nothing bug). Left=0, Right=1, Middle=2.-fn post_mouse_event(+pub(super) fn post_mouse_event(pid: i32,event: &CGEvent,window_local: Option<(f64, f64)>,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.rsindex 538e61d156..97a41a1854 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@@ -425,6 +425,28 @@ pub fn get_process_psn_for_window(window_id: u32, pid: libc::pid_t, out_psn: &mufalse}+/// Make `target_pid` and `target_wid` WindowServer-frontmost and leave them+/// there. Unlike [`with_foreground_assist`], this deliberately does not save or+/// restore the previous process. It is the persistent counterpart required by+/// focus-proxy surfaces whose input channel is armed only while genuinely+/// frontmost.+///+/// Returns `true` only when the target PSN resolved and WindowServer accepted+/// `SLPSSetFrontProcessWithOptions`.+pub fn set_front_process_persistently(target_pid: libc::pid_t, target_wid: u32) -> bool {+ let Some(set_front) = set_front_process_fn() else {+ return false;+ };+ let mut target_psn = [0u8; 8];+ if !get_process_psn_for_window(target_wid, target_pid, &mut target_psn) {+ return false;+ }++ // kCPSNoWindows = 0x400. Supplying the exact target window still makes+ // that window's process frontmost while avoiding a broad all-window raise.+ unsafe { set_front(target_psn.as_ptr() as *const c_void, target_wid, 0x400) == 0 }+}+/// Tool-agnostic foreground-assist: briefly front `window_id`, run `body` (which/// posts the synthetic input), then restore the prior frontmost process.///diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rsindex 7c2ac6c10f..75f5908165 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs@@ -12,12 +12,11 @@//! — not flashed and restored. `bring_to_front` is that explicit, persistent//! activation.//!-//! It activates the owning app by pid via `-[NSRunningApplication-//! activateWithOptions:]` (the same Cocoa call `focus_steal::restore_focus`-//! uses, and the same effect as `open -b <bundle-id>`). `window_id` is accepted-//! for cross-platform parity but activation is app-level: the app's key window-//! comes forward. Unlike the rest of the macOS driver this DOES steal-//! foreground — it is an explicit opt-in, never called by the input ladder.+//! It fronts the exact window through WindowServer's+//! `SLPSSetFrontProcessWithOptions` and falls back to+//! `-[NSRunningApplication activateWithOptions:]` when that SPI is unavailable.+//! Unlike the rest of the macOS driver this DOES steal foreground — it is an+//! explicit opt-in, never called by the input ladder.use async_trait::async_trait;use cua_driver_core::{@@ -41,9 +40,9 @@ fn def() -> &'static ToolDef {for a focus-proxy surface that re-arms its own input channel on \activation and must stay frontmost across the interaction — chiefly a \remote-desktop client (Microsoft Windows App / RDP), where the brief \- flash drops keystrokes. Activates the owning app by pid (\- `NSRunningApplication.activate`); `window_id` is accepted for parity \- but activation is app-level. This DOES steal foreground — explicit \+ flash drops keystrokes. Fronts the exact macOS window through \+ WindowServer when `window_id` is present, with app-level Cocoa \+ activation as a fallback. This DOES steal foreground — explicit \opt-in, never used by the input ladder.".into(),input_schema: serde_json::json!({@@ -86,18 +85,23 @@ impl Tool for BringToFrontTool {};let window_id = args.get("window_id").and_then(Value::as_i64);- // `-[NSRunningApplication activateWithOptions:]` is documented- // thread-safe. ActivateAllWindows brings the app's windows forward (not- // just the key one) so a multi-window target lands fully frontmost.- // The BOOL return tells us whether Cocoa actually accepted the swap —- // `None` here means the pid has no running app at all.- let activation = unsafe {+ let skylight_activated = window_id+ .and_then(|value| u32::try_from(value).ok())+ .is_some_and(|window_id| {+ crate::input::skylight::set_front_process_persistently(pid, window_id)+ });++ // Cocoa activation is the public fallback. On recent macOS it may+ // accept a request from a background process without actually changing+ // WindowServer ownership, which is why the exact-window SkyLight path+ // runs first.+ let activation = skylight_activated.then_some(true).or_else(|| unsafe {NSRunningApplication::runningApplicationWithProcessIdentifier(pid).map(|app| {app.activateWithOptions(NSApplicationActivationOptions::NSApplicationActivateAllWindows,)})- };+ });let activated = match activation {None => {@@ -131,6 +135,7 @@ impl Tool for BringToFrontTool {"pid": pid,"window_id": window_id,"activated": true,+ "path": if skylight_activated { "skylight" } else { "cocoa" },}),)}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rsindex 7cef8a554f..e418027e54 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs@@ -470,7 +470,7 @@ impl Tool for ClickTool {.await;// Drop the wildcard lease + detect window/foreground side-effects.- let changes = snapshot.detect_async().await;+ let changes = super::finish_window_observation(snapshot, &args).await;match result {Ok(Ok(((mut msg, needs_webkit_delay, suspected_noop), fronted))) => {@@ -791,7 +791,7 @@ impl Tool for ClickTool {).await;- let changes = snapshot.detect_async().await;+ let changes = super::finish_window_observation(snapshot, &args).await;let button_label = match button_str.as_str() {"right" => "right-click",diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rsindex b7ba4d1859..1e88ae09b8 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs@@ -397,7 +397,7 @@ impl Tool for DragTool {).await;- let changes = snapshot.detect_async().await;+ let changes = super::finish_window_observation(snapshot, &args).await;// Animate cursor to end position.crate::cursor::overlay::animate_cursor_to(cursor_key.clone(), to_sx, to_sy).await;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.rsindex 6a4398048d..e9a68a79b7 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@@ -246,7 +246,7 @@ impl Tool for HotkeyTool {).await;- let changes = snapshot.detect_async().await;+ let changes = super::finish_window_observation(snapshot, &args).await;match result {Ok(Ok(())) => {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.rsindex 874133e993..6f4961ee52 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@@ -95,6 +95,42 @@ impl DeliveryMode {}}+/// Finish the post-action observation window. Embedded interactive clients+/// that already observe the target continuously may opt out through the+/// private registry argument to avoid adding a one-second acknowledgement+/// delay to every input event. Regular MCP callers retain the full observer.+pub(crate) async fn finish_window_observation(+ snapshot: crate::window_change_detector::Snapshot,+ args: &serde_json::Value,+) -> crate::window_change_detector::Changes {+ if args+ .get("_skip_window_change_detection")+ .and_then(serde_json::Value::as_bool)+ .unwrap_or(false)+ {+ drop(snapshot);+ crate::window_change_detector::Changes::no_change()+ } else {+ snapshot.detect_async().await+ }+}++#[cfg(test)]+mod interactive_observation_tests {+ use super::*;++ #[tokio::test]+ async fn embedded_interactive_input_can_finish_without_polling() {+ let snapshot = crate::window_change_detector::WindowChangeDetector::snapshot(None);+ let changes = finish_window_observation(+ snapshot,+ &serde_json::json!({"_skip_window_change_detection": true}),+ )+ .await;+ assert!(!changes.needs_restore());+ }+}+/// 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 coordinatediff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rsindex 59b697de6a..0dbebddd8c 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rs@@ -254,7 +254,7 @@ impl Tool for PressKeyTool {).await;- let changes = snapshot.detect_async().await;+ let changes = super::finish_window_observation(snapshot, &args).await;match result {Ok(Ok(())) => {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rsindex beb7d0cb8a..05235e9de8 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs@@ -504,7 +504,7 @@ impl Tool for ScrollTool {).await;- let changes = snapshot.detect_async().await;+ let changes = super::finish_window_observation(snapshot, &args).await;let mode_label = if fg {" (delivery_mode:foreground)"} else {@@ -576,7 +576,7 @@ impl Tool for ScrollTool {).await;- let changes = snapshot.detect_async().await;+ let changes = super::finish_window_observation(snapshot, &args).await;match result {Ok(Ok(())) => ToolResult::text(format!(diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rsindex aa0fb4cca5..f8dc939af6 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs@@ -300,7 +300,7 @@ impl Tool for TypeTextTool {).await;- let changes = snapshot.detect_async().await;+ let changes = super::finish_window_observation(snapshot, &args).await;match result {Ok(Ok((detail, path, verified))) => {@@ -423,6 +423,14 @@ const PATH_AX: &str = "ax";const PATH_KEY_EVENTS: &str = "key_events";const PATH_KEY_EVENTS_FG: &str = "key_events_fg";+fn foreground_settle_ms(pid: i32, frontmost_pid: Option<i32>) -> u64 {+ if frontmost_pid == Some(pid) {+ 20+ } else {+ 200+ }+}+/// Read-back verification for a keystroke rung: did the typed text actually land?////// `before`/`after` are `AXValue` read from the target field before and after@@ -517,20 +525,14 @@ fn target_in_web_area(pid: i32, element_ptr_and_idx: Option<(usize, Option<usize}}-/// Type via CGEvent keystrokes, optionally clearing the field first (idempotent-/// retype), then verify by read-back.-///-/// `clear_first` is the idempotency guard for escalation: when the field was-/// empty/unreadable at capture, `Cmd+A`+`Delete` makes the retype land exactly-/// `text` regardless of what a prior unverified rung may have done — avoiding-/// double-type. It is NOT used when the field had readable pre-existing content-/// (that would clobber it).+/// Type via CGEvent keystrokes at the current insertion point, then verify by+/// read-back. `type_text` is deliberately non-idempotent: it must never clear+/// an existing value merely because AX cannot read that value back.fn cgevent_type_verified(pid: i32,text: &str,delay_ms: u64,before: Option<&str>,- clear_first: bool,element_ptr_and_idx: Option<(usize, Option<usize>)>,settle_ms: u64,) -> anyhow::Result<bool> {@@ -551,17 +553,6 @@ fn cgevent_type_verified(if settle_ms > 0 {std::thread::sleep(std::time::Duration::from_millis(settle_ms));}- if clear_first {- if settle_ms > 0 {- // Some renderer focus proxies discard the first printable event- // after activation even after their AX focus is visible. Prime- // that channel with disposable text, then clear it before the- // requested payload. Never do this for a nonempty field.- let _ = crate::input::keyboard::type_text_with_delay(pid, " ", delay_ms);- }- let _ = crate::input::keyboard::press_key(pid, "a", &["cmd"]);- let _ = crate::input::keyboard::press_key(pid, "delete", &[]);- }crate::input::keyboard::type_text_with_delay(pid, text, delay_ms)?;let after = read_axvalue(pid, element_ptr_and_idx);Ok(verify_typed(before, after.as_deref(), text))@@ -572,8 +563,7 @@ fn cgevent_type_verified(/// - `delivery_mode == Background` (default): AX insert → read-back; on a/// silent/unreadable accept, CGEvent keystrokes → read-back. Never fronts./// - `delivery_mode == Foreground`: the agent's explicit last resort — briefly-/// front `window_id`, type (clear-first when the field was empty/unreadable so-/// the retype is idempotent), restore, then read-back.+/// front `window_id`, insert at the current cursor, restore, then read-back.////// Returns `(detail, path, verified)`. `verified` is `true` only when a/// read-back positively confirmed the text; `false` means the agent must@@ -587,32 +577,29 @@ fn type_text_blocking(delivery_mode: super::DeliveryMode,window_id: Option<u32>,) -> anyhow::Result<(String, &'static str, bool)> {- // Original field value before ANY rung — drives both the read-back delta and- // the clear-then-type idempotency decision.+ // Original field value before any rung drives read-back verification only.+ // An unreadable value is not evidence that the field is empty.let before = read_axvalue(pid, element_ptr_and_idx);- // Clear-then-type only when we can't see existing content to preserve- // (empty or unreadable). A readable non-empty value is left intact.- let clear_first = !matches!(before.as_deref(), Some(b) if !b.is_empty());// --- Foreground rung: explicit agent request (skip AX/background ladder). ---if delivery_mode.is_foreground() {// Settle between front+focus and the first keystroke — see the// "i love u" -> "love u" first-char-drop note in cgevent_type_verified.- // 60ms covers native Cocoa/Catalyst surfaces, but focus-proxy clients- // that re-establish their own input channel on activation need longer:+ // A target that was already frontmost pays only 20ms for element-focus+ // settling. Focus-proxy clients that were just activated need longer:// an RDP client (Microsoft Windows App) re-arms its keyboard grab with// the remote host over hundreds of ms, so at 60ms every keystroke was- // dropped. 200ms covers that re-grab without being perceptible.- const FOREGROUND_SETTLE_MS: u64 = 200;+ // dropped. 200ms covers that re-grab without penalizing an already+ // armed interactive stream on every text chunk.+ let foreground_settle_ms = foreground_settle_ms(pid, apps::frontmost_pid());let do_type = || {cgevent_type_verified(pid,text,delay_ms,before.as_deref(),- clear_first,element_ptr_and_idx,- FOREGROUND_SETTLE_MS,+ foreground_settle_ms,)};let (verified, fronted) = match window_id {@@ -660,7 +647,6 @@ fn type_text_blocking(text,delay_ms,before.as_deref(),- /*clear_first=*/ false,element_ptr_and_idx,/*settle_ms=*/ 0,)?;@@ -707,15 +693,13 @@ fn type_text_blocking(}// --- Background rung 2: CGEvent keystrokes with read-back. ---- // No clear-first here: a partial AX write is rare and clearing on every- // background fallback would change insert-at-cursor semantics. The- // foreground rung owns the idempotent clear-then-type.+ // Never clear here: a partial AX write is rare, and clearing would violate+ // insert-at-cursor semantics.let verified = cgevent_type_verified(pid,text,delay_ms,before.as_deref(),- /*clear_first=*/ false,element_ptr_and_idx,/*settle_ms=*/ 0,)?;@@ -796,4 +780,11 @@ mod tests {assert_eq!(PATH_KEY_EVENTS, "key_events");assert_eq!(PATH_KEY_EVENTS_FG, "key_events_fg");}++ #[test]+ fn foreground_typing_skips_long_rearm_when_target_is_already_frontmost() {+ assert_eq!(foreground_settle_ms(42, Some(42)), 20);+ assert_eq!(foreground_settle_ms(42, Some(7)), 200);+ assert_eq!(foreground_settle_ms(42, None), 200);+ }}