From 05b42e109280b5899d7e4835c4f5a14e9b165b0d Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 11:30:14 +0800 Subject: [PATCH 1/6] fix(desktop): route macOS AX messages by serving process --- .../desktop_host/ax_orchestration.rs | 10 +- .../src/computer_use/desktop_host/macos.rs | 30 +- .../src/computer_use/desktop_host/mod.rs | 4 +- .../computer_use/desktop_host/observation.rs | 12 +- .../src/computer_use/macos_ax_dispatch.rs | 256 ++++++++++++++++++ .../desktop/src/computer_use/macos_ax_dump.rs | 23 +- .../src/computer_use/macos_ax_shortcuts.rs | 6 +- .../desktop/src/computer_use/macos_ax_ui.rs | 44 +-- .../src/computer_use/macos_ax_write.rs | 18 +- src/apps/desktop/src/computer_use/mod.rs | 2 + 10 files changed, 307 insertions(+), 98 deletions(-) create mode 100644 src/apps/desktop/src/computer_use/macos_ax_dispatch.rs diff --git a/src/apps/desktop/src/computer_use/desktop_host/ax_orchestration.rs b/src/apps/desktop/src/computer_use/desktop_host/ax_orchestration.rs index 04c2da2219..ad15755e18 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/ax_orchestration.rs +++ b/src/apps/desktop/src/computer_use/desktop_host/ax_orchestration.rs @@ -426,7 +426,7 @@ impl DesktopComputerUseHost { && params.modifier_keys.is_empty(); node_coordinates = crate::computer_use::control_session::spawn_blocking(move || { - macos::catch_objc(|| resolve_macos_node_click(pid, idx, semantic)) + macos::catch_objc_local(|| resolve_macos_node_click(pid, idx, semantic)) }) .await .map_err(|error| OpenBitFunError::tool(error.to_string()))??; @@ -450,7 +450,7 @@ impl DesktopComputerUseHost { )?; image_coordinates = Some((x, y)); crate::computer_use::control_session::spawn_blocking(move || { - macos::catch_objc(|| try_macos_point_press(pid, x, y)) + macos::catch_objc_local(|| try_macos_point_press(pid, x, y)) }) .await .map_err(|error| OpenBitFunError::tool(error.to_string()))?? @@ -670,7 +670,7 @@ impl DesktopComputerUseHost { if point.is_none() && index.is_none() { return Ok(false); } - crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc(|| { + crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc_local(|| { let element = if let Some(index) = index { Some(crate::computer_use::macos_ax_dump::retained_cached_target(pid, index) .ok_or_else(|| OpenBitFunError::tool("AX_NODE_STALE: text focus target is no longer in the observed snapshot"))?) @@ -726,7 +726,7 @@ impl DesktopComputerUseHost { .flatten() .map(|point| (point.x, point.y)); if let Some((x, y)) = intended_point { - let mismatch = crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc(|| + let mismatch = crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc_local(|| crate::computer_use::macos_ax_dump::focused_text_target_mismatch(pid, x, y) )).await.map_err(|error| OpenBitFunError::tool(error.to_string()))??; if mismatch { @@ -865,7 +865,7 @@ impl DesktopComputerUseHost { None => { let idx = *idx; crate::computer_use::control_session::spawn_blocking(move || { - macos::catch_objc(|| resolve_macos_node_click(pid, idx, false)) + macos::catch_objc_local(|| resolve_macos_node_click(pid, idx, false)) }) .await .map_err(|error| OpenBitFunError::tool(error.to_string()))?? diff --git a/src/apps/desktop/src/computer_use/desktop_host/macos.rs b/src/apps/desktop/src/computer_use/desktop_host/macos.rs index 88af914da6..1568c5a58a 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/macos.rs +++ b/src/apps/desktop/src/computer_use/desktop_host/macos.rs @@ -53,22 +53,11 @@ where } } -/// Run a closure on the main dispatch queue under an Objective-C -/// `@try/@catch`. This is the correct wrapper for calls that may reach -/// AppKit / HIToolbox / Accessibility code paths from a background -/// (`tokio::spawn_blocking`) worker thread. -/// -/// Two failure modes are defended against simultaneously: -/// -/// 1. `NSException` thrown by the framework (caught and converted into -/// `OpenBitFunError`). -/// 2. AppKit's `__assert_rtn` "Must only be used from the main thread" -/// `SIGTRAP` which fires when AX cross-process callbacks (e.g. -/// `AXUIElementCopyActionNames` → `_NSThemeWidgetCell.accessibility…` -/// → `_WMWindow performUpdatesUsingBlock:`) are evaluated off the -/// main thread. `objc2::exception::catch` cannot intercept this -/// trap; the only fix is to actually run the closure on the main -/// thread, which is what this helper does. +/// Run AppKit / HIToolbox input work on main under an Objective-C catch. +/// Never wrap AX traversal or cached-node actions here: a same-process tree +/// also contains WebKit subprocess elements whose IPC needs main to stay free. +/// Use `catch_objc_local` for AX work; `macos_ax_dispatch` sends each individual +/// same-process message to main to preserve AppKit's thread requirement. /// /// If we're already on the main thread we run inline (avoids /// `dispatch_sync(main)` deadlock). @@ -89,10 +78,8 @@ where } /// Run a closure under an Objective-C `@try/@catch` **on the current -/// thread** (no main-queue dispatch). Use this for closures that borrow -/// non-`Send` data and that are guaranteed not to reach AppKit's -/// main-thread-only AX callbacks (e.g. Vision OCR on an in-memory -/// screenshot buffer). +/// thread** (no main-queue dispatch). AX work routes individual messages through +/// `macos_ax_dispatch`; Vision OCR can also run here with borrowed image data. pub(super) fn catch_objc_local(f: F) -> OpenBitFunResult where F: FnOnce() -> OpenBitFunResult, @@ -166,7 +153,8 @@ pub(super) fn request_screen_capture() -> bool { /// owns the explicit request and the OS owns its outcome. pub(super) fn require_ax_trust_for(retry_hint: &str) -> OpenBitFunResult<()> { if ax_trusted() { - return Ok(()); + return crate::computer_use::macos_ax_dispatch::require_process_routing() + .map_err(OpenBitFunError::tool); } Err(OpenBitFunError::tool(format!( "[PERMISSION_DENIED] macOS Accessibility permission not granted to OpenBitFun. \ diff --git a/src/apps/desktop/src/computer_use/desktop_host/mod.rs b/src/apps/desktop/src/computer_use/desktop_host/mod.rs index 9e0c804f9f..cabf73095b 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/mod.rs +++ b/src/apps/desktop/src/computer_use/desktop_host/mod.rs @@ -817,7 +817,7 @@ impl DesktopComputerUseHost { let pid = resolve_pid_macos(self, &app).await?; let (shortcuts, menu_items_without_shortcut) = crate::computer_use::control_session::spawn_blocking(move || { - macos::catch_objc(|| { + macos::catch_objc_local(|| { crate::computer_use::macos_ax_shortcuts::dump_app_menu_shortcuts(pid) }) }) @@ -1402,7 +1402,7 @@ impl ComputerUseHost for DesktopComputerUseHost { // AX tree traversal can throw `NSException` from a misbehaving // frontmost app; the @try/@catch wrapper turns that into a // missing UI-tree text rather than crashing the whole process. - macos::catch_objc(|| { + macos::catch_objc_local(|| { Ok( crate::computer_use::macos_ax_ui::enumerate_ui_tree_text_for_pid( pid, diff --git a/src/apps/desktop/src/computer_use/desktop_host/observation.rs b/src/apps/desktop/src/computer_use/desktop_host/observation.rs index aa962d53f1..8638aa7cb6 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/observation.rs +++ b/src/apps/desktop/src/computer_use/desktop_host/observation.rs @@ -69,12 +69,18 @@ impl DesktopComputerUseHost { return Err(OpenBitFunError::tool("[SHARED_TARGET_ONLY] Accessibility observation requires the shared application")); } let focus_window_only = focus_window_only || shared.sharing.is_some(); + debug!( + "Computer Use AX observation started: pid={pid}, same_process={}", + pid == std::process::id() as i32 + ); let mut snap = crate::computer_use::control_session::spawn_blocking(move || { // Wrap in @try/@catch — AX APIs can throw NSException for // sandboxed / partially-loaded / dying processes, and an // unwound foreign exception aborts the whole openbitfun process // (`Rust cannot catch foreign exceptions, aborting`). - macos::catch_objc(|| { + // Only individual same-process AX messages go to main. The + // walk must remain off-main to serve WebKit's synchronous IPC. + macos::catch_objc_local(|| { crate::computer_use::macos_ax_dump::dump_app_ax( pid, crate::computer_use::macos_ax_dump::DumpOpts { @@ -87,6 +93,10 @@ impl DesktopComputerUseHost { }) .await .map_err(|e| OpenBitFunError::tool(e.to_string()))??; + debug!( + "Computer Use AX observation completed: pid={pid}, node_count={}", + snap.nodes.len() + ); // Auto-attach focused-window screenshot. Failures are non-fatal — // worst case the model still has the AX tree. diff --git a/src/apps/desktop/src/computer_use/macos_ax_dispatch.rs b/src/apps/desktop/src/computer_use/macos_ax_dispatch.rs new file mode 100644 index 0000000000..3bc78d4187 --- /dev/null +++ b/src/apps/desktop/src/computer_use/macos_ax_dispatch.rs @@ -0,0 +1,256 @@ +//! Dispatch individual AX messages, never an entire tree walk. +//! +//! Same-process AX calls invoke AppKit directly and must run on main. A tree +//! rooted in our process can contain elements owned by a WebKit subprocess: +//! those messages must stay on the calling worker so main can answer WebKit's +//! synchronous IPC (including AX client authentication during AXPosition reads). + +use core_foundation::{array::CFArrayRef, base::CFTypeRef, string::CFStringRef}; +use std::{ffi::c_void, panic::AssertUnwindSafe}; + +type Element = *const c_void; + +mod ffi { + use super::*; + #[link(name = "ApplicationServices", kind = "framework")] + unsafe extern "C" { + pub(super) fn AXUIElementCopyAttributeValue( + element: Element, + attr: CFStringRef, + out: *mut CFTypeRef, + ) -> i32; + pub(super) fn AXUIElementCopyActionNames(element: Element, out: *mut CFArrayRef) -> i32; + pub(super) fn AXUIElementCopyElementAtPosition( + element: Element, + x: f32, + y: f32, + out: *mut Element, + ) -> i32; + pub(super) fn AXUIElementIsAttributeSettable( + element: Element, + attr: CFStringRef, + out: *mut u8, + ) -> i32; + pub(super) fn AXUIElementSetAttributeValue( + element: Element, + attr: CFStringRef, + value: CFTypeRef, + ) -> i32; + pub(super) fn AXUIElementPerformAction(element: Element, action: CFStringRef) -> i32; + } +} + +type GetWindow = unsafe extern "C" fn(Element, *mut u32) -> i32; +type GetActualPid = unsafe extern "C" fn(Element, *mut i32) -> i32; + +fn actual_pid_lookup() -> Option { + static LOOKUP: std::sync::OnceLock> = std::sync::OnceLock::new(); + *LOOKUP.get_or_init(|| { + let symbol = + unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"_AXUIElementGetActualPid".as_ptr()) }; + if symbol.is_null() { + None + } else { + Some(unsafe { std::mem::transmute::<*mut c_void, GetActualPid>(symbol) }) + } + }) +} + +pub(super) fn require_process_routing() -> Result<(), &'static str> { + actual_pid_lookup().map(|_| ()).ok_or( + "[AX_DISPATCH_UNAVAILABLE] Native Accessibility process routing is unavailable on this macOS version" + ) +} + +/// AXUIElementGetPid reports the *presenting* application for WebKit children, +/// even when their messages are served by WebContent. Use the serving PID only +/// for thread routing; target/permission validation must keep the presenter PID. +/// WebKit's TestController.cpp declares this same AXError(AXUIElementRef,pid_t*) +/// SPI. Resolve it dynamically and fail explicitly when unavailable. +pub(super) unsafe fn actual_pid(element: Element) -> Result { + let lookup = actual_pid_lookup().ok_or(-25212)?; // kAXErrorNotImplemented + let mut pid = 0; + let status = unsafe { lookup(element, &mut pid) }; + if status == 0 { + Ok(pid) + } else { + Err(status) + } +} + +enum Operation { + Attribute(CFStringRef, *mut CFTypeRef), + Actions(*mut CFArrayRef), + HitTest(f32, f32, *mut Element), + Settable(CFStringRef, *mut u8), + Set(CFStringRef, CFTypeRef), + SetInput(CFStringRef, CFTypeRef), + Perform(CFStringRef), + Window(GetWindow, *mut u32), +} + +struct Request { + element: Element, + operation: Operation, +} + +// SAFETY: dispatch is synchronous. The unsafe entry points require all input +// references and output storage to remain valid until return. The caller is +// blocked while main uses that storage; neither pointers nor closures escape. +unsafe impl Send for Request {} + +impl Request { + fn invoke(self) -> i32 { + // Stop can revoke the token while a same-process message waits for + // main. Check again on the executing thread before native input starts. + if matches!( + self.operation, + Operation::SetInput(..) | Operation::Perform(..) + ) && super::control_session::input_allowed().is_err() + { + return -25200; // kAXErrorFailure; input was not submitted. + } + // Catch on the executing thread: an exception must never unwind through + // libdispatch, even when the caller has its own Objective-C catch. + let result = objc2::exception::catch(AssertUnwindSafe(|| unsafe { + match self.operation { + Operation::Attribute(attr, out) => { + ffi::AXUIElementCopyAttributeValue(self.element, attr, out) + } + Operation::Actions(out) => ffi::AXUIElementCopyActionNames(self.element, out), + Operation::HitTest(x, y, out) => { + ffi::AXUIElementCopyElementAtPosition(self.element, x, y, out) + } + Operation::Settable(attr, out) => { + ffi::AXUIElementIsAttributeSettable(self.element, attr, out) + } + Operation::Set(attr, value) | Operation::SetInput(attr, value) => { + ffi::AXUIElementSetAttributeValue(self.element, attr, value) + } + Operation::Perform(action) => ffi::AXUIElementPerformAction(self.element, action), + Operation::Window(lookup, out) => lookup(self.element, out), + } + })); + match result { + Ok(status) => status, + Err(exception) => { + log::warn!("Computer Use AX call raised an Objective-C exception: {exception:?}"); + -25200 // kAXErrorFailure; never claim success or retry input. + } + } + } + + fn dispatch(self) -> i32 { + let pid = match unsafe { actual_pid(self.element) } { + Ok(pid) => pid, + Err(status) => return status, + }; + if pid == std::process::id() as i32 && objc2::MainThreadMarker::new().is_none() { + let token = super::control_session::dispatch_token(); + dispatch::Queue::main() + .exec_sync(move || super::control_session::with_token(token, || self.invoke())) + } else { + self.invoke() + } + } +} + +// These wrappers preserve the native AX error/ownership contract. Like the C +// APIs, callers own all inputs and must provide valid writable output pointers. +pub(super) unsafe fn copy_attribute_value( + element: Element, + attr: CFStringRef, + out: *mut CFTypeRef, +) -> i32 { + Request { + element, + operation: Operation::Attribute(attr, out), + } + .dispatch() +} + +pub(super) unsafe fn copy_action_names(element: Element, out: *mut CFArrayRef) -> i32 { + Request { + element, + operation: Operation::Actions(out), + } + .dispatch() +} + +pub(super) unsafe fn copy_element_at_position( + element: Element, + x: f32, + y: f32, + out: *mut Element, +) -> i32 { + Request { + element, + operation: Operation::HitTest(x, y, out), + } + .dispatch() +} + +pub(super) unsafe fn is_attribute_settable( + element: Element, + attr: CFStringRef, + out: *mut u8, +) -> i32 { + Request { + element, + operation: Operation::Settable(attr, out), + } + .dispatch() +} + +pub(super) unsafe fn set_attribute_value( + element: Element, + attr: CFStringRef, + value: CFTypeRef, +) -> i32 { + Request { + element, + operation: Operation::Set(attr, value), + } + .dispatch() +} + +/// User input needs a final revocation check after crossing the main queue. +/// Observation-only AX enablement continues to use `set_attribute_value`. +pub(super) unsafe fn set_input_attribute_value( + element: Element, + attr: CFStringRef, + value: CFTypeRef, +) -> i32 { + Request { + element, + operation: Operation::SetInput(attr, value), + } + .dispatch() +} + +pub(super) unsafe fn perform_action(element: Element, action: CFStringRef) -> i32 { + Request { + element, + operation: Operation::Perform(action), + } + .dispatch() +} + +pub(super) unsafe fn window_id(element: Element) -> Option { + static LOOKUP: std::sync::OnceLock> = std::sync::OnceLock::new(); + let lookup = (*LOOKUP.get_or_init(|| { + let symbol = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"_AXUIElementGetWindow".as_ptr()) }; + if symbol.is_null() { + None + } else { + Some(unsafe { std::mem::transmute::<*mut c_void, GetWindow>(symbol) }) + } + }))?; + let mut window = 0; + let status = Request { + element, + operation: Operation::Window(lookup, &mut window), + } + .dispatch(); + (status == 0).then_some(window) +} diff --git a/src/apps/desktop/src/computer_use/macos_ax_dump.rs b/src/apps/desktop/src/computer_use/macos_ax_dump.rs index 9e20406629..c34d25649b 100644 --- a/src/apps/desktop/src/computer_use/macos_ax_dump.rs +++ b/src/apps/desktop/src/computer_use/macos_ax_dump.rs @@ -18,6 +18,12 @@ #![allow(dead_code)] use super::ax_snapshot_digest::compute_digest; +use super::macos_ax_dispatch::{ + copy_action_names as AXUIElementCopyActionNames, + copy_attribute_value as AXUIElementCopyAttributeValue, + copy_element_at_position as AXUIElementCopyElementAtPosition, + set_attribute_value as AXUIElementSetAttributeValue, +}; use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::{CFGetTypeID, CFTypeRef, TCFType}; use core_foundation::boolean::{CFBoolean, CFBooleanGetTypeID, CFBooleanRef}; @@ -44,23 +50,6 @@ unsafe extern "C" { fn AXUIElementCreateApplication(pid: i32) -> AXUIElementRef; fn AXUIElementGetPid(element: AXUIElementRef, pid: *mut i32) -> i32; fn AXUIElementSetMessagingTimeout(element: AXUIElementRef, timeout: f32) -> i32; - fn AXUIElementCopyElementAtPosition( - element: AXUIElementRef, - x: f32, - y: f32, - result: *mut AXUIElementRef, - ) -> i32; - fn AXUIElementCopyAttributeValue( - element: AXUIElementRef, - attribute: CFStringRef, - value: *mut CFTypeRef, - ) -> i32; - fn AXUIElementCopyActionNames(element: AXUIElementRef, names: *mut CFArrayRef) -> i32; - fn AXUIElementSetAttributeValue( - element: AXUIElementRef, - attribute: CFStringRef, - value: CFTypeRef, - ) -> i32; fn AXValueGetType(value: AXValueRef) -> u32; fn AXValueGetValue(value: AXValueRef, the_type: u32, ptr: *mut c_void) -> bool; fn AXUIElementGetTypeID() -> CFTypeID; diff --git a/src/apps/desktop/src/computer_use/macos_ax_shortcuts.rs b/src/apps/desktop/src/computer_use/macos_ax_shortcuts.rs index 2b3926403c..04669356ce 100644 --- a/src/apps/desktop/src/computer_use/macos_ax_shortcuts.rs +++ b/src/apps/desktop/src/computer_use/macos_ax_shortcuts.rs @@ -13,6 +13,7 @@ #![allow(dead_code)] +use super::macos_ax_dispatch::copy_attribute_value as AXUIElementCopyAttributeValue; use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::{CFGetTypeID, CFTypeRef, TCFType}; use core_foundation::boolean::{CFBooleanGetTypeID, CFBooleanRef}; @@ -30,11 +31,6 @@ type AXUIElementRef = *const c_void; #[link(name = "ApplicationServices", kind = "framework")] unsafe extern "C" { fn AXUIElementCreateApplication(pid: i32) -> AXUIElementRef; - fn AXUIElementCopyAttributeValue( - element: AXUIElementRef, - attribute: CFStringRef, - value: *mut CFTypeRef, - ) -> i32; } #[link(name = "CoreFoundation", kind = "framework")] diff --git a/src/apps/desktop/src/computer_use/macos_ax_ui.rs b/src/apps/desktop/src/computer_use/macos_ax_ui.rs index 981c20b04f..a479cd71bb 100644 --- a/src/apps/desktop/src/computer_use/macos_ax_ui.rs +++ b/src/apps/desktop/src/computer_use/macos_ax_ui.rs @@ -2,6 +2,13 @@ //! //! Coordinates match CoreGraphics global space used by [`crate::computer_use::DesktopComputerUseHost`]. +use super::macos_ax_dispatch::{ + copy_action_names as AXUIElementCopyActionNames, + copy_attribute_value as AXUIElementCopyAttributeValue, + copy_element_at_position as AXUIElementCopyElementAtPosition, + perform_action as AXUIElementPerformAction, + set_input_attribute_value as AXUIElementSetAttributeValue, +}; use crate::computer_use::ui_locate_common; use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::{CFGetTypeID, CFTypeRef, TCFType}; @@ -22,25 +29,7 @@ unsafe extern "C" { fn AXUIElementCreateSystemWide() -> AXUIElementRef; fn AXUIElementCreateApplication(pid: i32) -> AXUIElementRef; fn AXUIElementGetPid(element: AXUIElementRef, pid: *mut i32) -> i32; - fn AXUIElementCopyAttributeValue( - element: AXUIElementRef, - attribute: CFStringRef, - value: *mut CFTypeRef, - ) -> i32; - fn AXUIElementCopyActionNames(element: AXUIElementRef, names: *mut CFArrayRef) -> i32; - fn AXUIElementPerformAction(element: AXUIElementRef, action: CFStringRef) -> i32; - fn AXUIElementSetAttributeValue( - element: AXUIElementRef, - attribute: CFStringRef, - value: CFTypeRef, - ) -> i32; fn AXUIElementSetMessagingTimeout(element: AXUIElementRef, timeout: f32) -> i32; - fn AXUIElementCopyElementAtPosition( - element: AXUIElementRef, - x: f32, - y: f32, - out_elem: *mut AXUIElementRef, - ) -> i32; fn AXValueGetType(value: AXValueRef) -> u32; fn AXValueGetValue(value: AXValueRef, the_type: u32, ptr: *mut c_void) -> bool; } @@ -1161,22 +1150,7 @@ pub(super) fn window_bounds_global_for_pid(pid: i32) -> OpenBitFunResult<(i32, i /// private lookup is optional: if unavailable, return no match rather than /// substituting another same-app window with similar bounds or title. pub(super) unsafe fn ax_window_id(element: AXUIElementRef) -> Option { - type GetWindow = unsafe extern "C" fn(AXUIElementRef, *mut u32) -> i32; - static LOOKUP: std::sync::OnceLock> = std::sync::OnceLock::new(); - let lookup = (*LOOKUP.get_or_init(|| { - let symbol = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"_AXUIElementGetWindow".as_ptr()) }; - if symbol.is_null() { - None - } else { - Some(unsafe { std::mem::transmute::<*mut c_void, GetWindow>(symbol) }) - } - }))?; - let mut window_id = 0; - if unsafe { lookup(element, &mut window_id) } == 0 { - Some(window_id) - } else { - None - } + unsafe { super::macos_ax_dispatch::window_id(element) } } pub(super) unsafe fn try_window_element_by_id( @@ -1349,7 +1323,7 @@ pub(super) fn minimize_window_for_fixture(pid: i32, window: u32) -> Result<(), S ax_release(app); let element = element.ok_or("fixture window is unavailable")?; let attribute = CFString::new("AXMinimized"); - let status = AXUIElementSetAttributeValue( + let status = super::macos_ax_dispatch::set_attribute_value( element, attribute.as_concrete_TypeRef(), core_foundation::boolean::CFBoolean::true_value().as_CFTypeRef(), diff --git a/src/apps/desktop/src/computer_use/macos_ax_write.rs b/src/apps/desktop/src/computer_use/macos_ax_write.rs index 2a3b6931e8..128f613c1d 100644 --- a/src/apps/desktop/src/computer_use/macos_ax_write.rs +++ b/src/apps/desktop/src/computer_use/macos_ax_write.rs @@ -12,27 +12,21 @@ #![allow(dead_code)] +use super::macos_ax_dispatch::{ + is_attribute_settable as AXUIElementIsAttributeSettable, + perform_action as AXUIElementPerformAction, + set_input_attribute_value as AXUIElementSetAttributeValue, +}; use crate::computer_use::macos_ax_dump::AxRef; use core_foundation::base::{CFTypeRef, TCFType}; use core_foundation::boolean::CFBoolean; -use core_foundation::string::{CFString, CFStringRef}; +use core_foundation::string::CFString; type AXUIElementRef = *const std::ffi::c_void; #[link(name = "ApplicationServices", kind = "framework")] unsafe extern "C" { fn AXUIElementGetPid(element: AXUIElementRef, pid: *mut i32) -> i32; - fn AXUIElementIsAttributeSettable( - element: AXUIElementRef, - attribute: CFStringRef, - settable: *mut u8, - ) -> i32; - fn AXUIElementPerformAction(element: AXUIElementRef, action: CFStringRef) -> i32; - fn AXUIElementSetAttributeValue( - element: AXUIElementRef, - attribute: CFStringRef, - value: CFTypeRef, - ) -> i32; } /// Result of an AX-first attempt. diff --git a/src/apps/desktop/src/computer_use/mod.rs b/src/apps/desktop/src/computer_use/mod.rs index e4b66bbe2c..412cdafb40 100644 --- a/src/apps/desktop/src/computer_use/mod.rs +++ b/src/apps/desktop/src/computer_use/mod.rs @@ -13,6 +13,8 @@ mod linux_control; #[cfg(target_os = "linux")] mod linux_control_ax; #[cfg(target_os = "macos")] +mod macos_ax_dispatch; +#[cfg(target_os = "macos")] mod macos_ax_dump; #[cfg(target_os = "macos")] mod macos_ax_shortcuts; From 6392941973f8b1634ad33a17875e073636aaa511 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 11:30:14 +0800 Subject: [PATCH 2/6] test(desktop): cover native WebView self-control and revoked writes --- scripts/test-macos-computer-use-self.mjs | 28 +++ src/apps/desktop/src/computer_use/AGENTS.md | 19 ++ .../native_control_roundtrip_tests.rs | 168 ++++++++++++++++++ .../tests/computer_use_native_roundtrip.rs | 23 ++- .../fixtures/computer_use_self_webview.rs | 39 ++++ 5 files changed, 276 insertions(+), 1 deletion(-) create mode 100644 scripts/test-macos-computer-use-self.mjs create mode 100644 src/apps/desktop/tests/fixtures/computer_use_self_webview.rs diff --git a/scripts/test-macos-computer-use-self.mjs b/scripts/test-macos-computer-use-self.mjs new file mode 100644 index 0000000000..f9db0c9456 --- /dev/null +++ b/scripts/test-macos-computer-use-self.mjs @@ -0,0 +1,28 @@ +// The target is a disposable native window owned by the ComputerUse host itself. +// An external watchdog also catches deadlocks that stop the main run loop. +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +assert.equal(process.platform, 'darwin', 'Self WebView fixture requires macOS'); +const root = fileURLToPath(new URL('../', import.meta.url)); +const run = (command, args, options = {}) => new Promise((resolve, reject) => { + const child = spawn(command, args, { cwd: root, windowsHide: true, stdio: 'inherit', ...options }); + let output = ''; + child.stdout?.on('data', chunk => { output += String(chunk); }); + child.once('error', reject); + child.once('exit', (code, signal) => code === 0 ? resolve(output) : reject(new Error(`${command} failed: code=${code} signal=${signal}`))); +}); +const args = ['test', '--locked', '-p', 'openbitfun-desktop', '--features', 'devtools', '--test', 'computer_use_native_roundtrip']; +let executable = process.env.OPENBITFUN_TEST_BINARY; +if (!executable) { + const output = await run('cargo', [...args, '--no-run', '--message-format=json'], { stdio: ['ignore', 'pipe', 'inherit'] }); + executable = output.split('\n').filter(Boolean).map(line => JSON.parse(line)) + .find(record => record.target?.name === 'computer_use_native_roundtrip' && record.executable)?.executable; + assert.ok(executable, 'Cargo must report the native harness executable'); +} +await run(executable, [], { + env: { ...process.env, OPENBITFUN_CUA_SELF_TEST: '1' }, + timeout: 60_000, + killSignal: 'SIGKILL', +}); diff --git a/src/apps/desktop/src/computer_use/AGENTS.md b/src/apps/desktop/src/computer_use/AGENTS.md index 9d0e0a59dc..3747b75dd9 100644 --- a/src/apps/desktop/src/computer_use/AGENTS.md +++ b/src/apps/desktop/src/computer_use/AGENTS.md @@ -61,6 +61,7 @@ remaining native acceptance scenarios separately. - `desktop_host/observation.rs`, `observation_cache.rs` — observation identity and bounded screenshot geometry; never input authority - `desktop_host/state.rs` — derived host feedback and view caches - `macos_*` / `windows_*` — platform AX, capture, list-apps, shortcuts +- `macos_ax_dispatch` — per-element AX thread routing and native exception boundary - `windows_capture.rs` — WGC frame conversion and authoritative window bounds - `windows_wgc_capture.rs` — Windows.Graphics.Capture (Direct3D11) - `windows_window_target.rs` — Win32 window facts and portable default-target policy @@ -111,6 +112,21 @@ inputs that can name a screenshot_id require one after a zoom. ## Target-local macOS focus acceptance +AX walks and cached-node operations run on a blocking worker. Route each native +message by the element's serving PID through `macos_ax_dispatch`: same-process +AppKit callbacks require main, while WebKit subprocess messages need main free +to answer synchronous IPC, including AX client authentication. Never dispatch an +entire walk based on its root PID; a single tree spans both processes. +`AXUIElementGetPid` reports the presenter for WebKit descendants; thread routing +uses dynamically resolved `_AXUIElementGetActualPid`. Keep the presenter PID for +target/permission validation. If the serving-PID SPI is unavailable, report an +explicit unsupported state instead of guessing a thread. Keep the +control token across same-process dispatch and catch Objective-C exceptions on +the executing thread. Recheck input authority there before actions or user +attribute writes, because Stop may revoke a queued message. Observation-only +AX enablement does not acquire input authority. Enigo / HIToolbox input retains +its main-thread wrapper. + The directed-input route can change a target application's internal focus without changing the human foreground application. Its window-addressed focus pair at local `(-8,-8)` must remain outside content; the requested gesture @@ -187,6 +203,9 @@ node scripts/test-macos-input-controls.mjs --latency node scripts/test-macos-input-controls.mjs # Full Tool -> provider -> native loop on a dedicated window, with main-thread runloop. node scripts/test-macos-control-roundtrip.mjs +# Same-process AppKit + real WebKit subtree: observe, capture, click once, +# observe the actual DOM result, read shortcuts and Stop; external deadlock watchdog. +node scripts/test-macos-computer-use-self.mjs # Same-process popup panel over a dedicated window, once as an attached child # window (inherits layer 0) and once at the pop-up menu level: composited pixels # and auxiliary metadata, popup-routed press without focus preparation diff --git a/src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs b/src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs index 4c823746cf..c94f1fee5a 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs +++ b/src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs @@ -5,6 +5,7 @@ use openbitfun_core::agentic::tools::framework::{Tool, ToolResult, ToolUseContex use openbitfun_core::agentic::tools::implementations::ComputerUseTool; use serde_json::{json, Value}; use std::sync::Arc; +use std::time::Duration; #[path = "native_control_probe.rs"] mod probe; @@ -218,6 +219,10 @@ async fn wait_for_observer(path: &str) -> Value { } pub(crate) async fn run() { + if std::env::var_os("OPENBITFUN_CUA_SELF_TEST").is_some() { + self_webview_roundtrip().await; + return; + } if std::env::var_os("OPENBITFUN_CUA_PROBE_PID").is_some() { probe::run().await; return; @@ -511,6 +516,169 @@ pub(crate) async fn run() { eprintln!("PASS native tool pipeline: observation, semantic click, image click, Unicode input, Return, OCR verification and stop; binding/generation/foreground stayed stable"); } +async fn self_webview_roundtrip() { + let pid = std::process::id(); + let host = Arc::new(DesktopComputerUseHost::new()); + let mut context = ToolUseContext::for_tool_listing(None, None); + context.session_id = Some(OWNER.into()); + context.computer_use_host = Some(host.clone()); + context.primary_model_facts.supports_image_inputs = true; + context.primary_model_facts.api_format = "anthropic".into(); + let tool = ComputerUseTool::new(); + let _cleanup = StopOnExit; + let ready_deadline = std::time::Instant::now() + Duration::from_secs(10); + let window = loop { + let windows = call(&tool, &context, json!({"action":"list_windows"})).await; + if let Some(window) = windows["windows"] + .as_array() + .unwrap() + .iter() + .find(|window| { + window["pid"] == pid && window["title"] == "Computer Use Self WebView Fixture" + }) + { + break window.clone(); + } + assert!( + std::time::Instant::now() < ready_deadline, + "own fixture window must be discoverable" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + }; + let app = json!({"pid":pid,"window_id":window["window_id"]}); + call( + &tool, + &context, + json!({"action":"start_control","app":app,"mode":"background"}), + ) + .await; + let deadline = std::time::Instant::now() + Duration::from_secs(15); + let observation = loop { + let state = call( + &tool, + &context, + json!({"action":"get_app_state","app":app,"include_image":false}), + ) + .await; + if state["app_state"]["tree_text"] + .as_str() + .unwrap() + .contains("Self test button") + { + break state; + } + assert!( + std::time::Instant::now() < deadline, + "WebKit AX subtree never arrived: {state}" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + }; + assert!(observation["app_state"]["tree_text"] + .as_str() + .unwrap() + .contains("Self click count 0")); + assert!(observation["app_state"]["node_count"].as_u64().unwrap() > 7); + assert_eq!(observation["app_state"]["has_screenshot"], false); + let image = + call_observation(&tool, &context, json!({"action":"get_app_state","app":app})).await; + let id = assert_app_observation( + &image, + true, + observation["app_state"]["observation_id"].as_str(), + ); + let idx = observed_node_index(&image.data, "Self test button"); + // Use the actual observed element geometry to address the screenshot. The + // tool still validates the screenshot and dispatches the input itself. + let (left, top, width, height) = tokio::task::spawn_blocking(move || { + let target = + crate::computer_use::macos_ax_dump::retained_cached_target(pid as i32, idx).unwrap(); + assert_ne!( + unsafe { crate::computer_use::macos_ax_dispatch::actual_pid(target.reference().0) } + .unwrap(), + pid as i32, + "The fixture must exercise a real WebKit subprocess element" + ); + target + .frame_global() + .expect("WebKit button must expose real geometry") + }) + .await + .unwrap(); + let meta = &image.data["app_state"]["screenshot_meta"]; + let global = &meta["image_global_bounds"]; + let content = &meta["image_content_rect"]; + let x = content["left"].as_f64().unwrap() + + (left + width / 2.0 - global["left"].as_f64().unwrap()) + * content["width"].as_f64().unwrap() + / global["width"].as_f64().unwrap(); + let y = content["top"].as_f64().unwrap() + + (top + height / 2.0 - global["top"].as_f64().unwrap()) + * content["height"].as_f64().unwrap() + / global["height"].as_f64().unwrap(); + let clicked = call( + &tool, + &context, + json!({"action":"app_click", "app":app, "observation_id":id, + "target":{"kind":"image_xy","x":x.round() as i32,"y":y.round() as i32,"screenshot_id":meta["screenshot_id"]}}), + ) + .await; + assert!( + clicked["app_state"]["tree_text"] + .as_str() + .unwrap() + .contains("Self click count 1"), + "{clicked}" + ); + call( + &tool, + &context, + json!({"action":"get_app_shortcuts","app":app}), + ) + .await; + let native_idx = observed_node_index(&clicked, "Computer Use Self WebView Fixture"); + let native_target = + crate::computer_use::macos_ax_dump::retained_cached_target(pid as i32, native_idx).unwrap(); + let lease = crate::computer_use::control_session::acquire(OWNER, "app_click").unwrap(); + let stale_token = crate::computer_use::control_session::capture_token().unwrap(); + crate::computer_use::control_session::stop(Some(OWNER), "fixture_revoke_queued_input").unwrap(); + drop(lease); + tokio::task::spawn_blocking(move || { + use crate::computer_use::{control_session, macos_ax_dispatch}; + use core_foundation::{base::TCFType, string::CFString}; + assert_eq!( + unsafe { macos_ax_dispatch::actual_pid(native_target.reference().0) }.unwrap(), + pid as i32, + "Revocation must exercise a same-process main-queue message" + ); + control_session::with_token(stale_token, || unsafe { + let action = CFString::new("AXRaise"); + assert_eq!( + macos_ax_dispatch::perform_action( + native_target.reference().0, + action.as_concrete_TypeRef() + ), + -25200, + "Stopped input must be rejected on main before AXRaise" + ); + let attr = CFString::new("AXTitle"); + let value = CFString::new("Revoked write must not arrive"); + assert_eq!( + macos_ax_dispatch::set_input_attribute_value( + native_target.reference().0, + attr.as_concrete_TypeRef(), + value.as_CFTypeRef() + ), + -25200, + "Stopped input must be rejected on main before attribute writes" + ); + }); + }) + .await + .unwrap(); + call(&tool, &context, json!({"action":"stop_control"})).await; + eprintln!("PASS same-process AppKit/WebKit observations, screenshot, one button click, shortcuts and Stop with stale-input rejection through ComputerUse"); +} + async fn run_covered_semantic() { let pid: i32 = std::env::var("OPENBITFUN_INPUT_FIXTURE_PID") .unwrap() diff --git a/src/apps/desktop/tests/computer_use_native_roundtrip.rs b/src/apps/desktop/tests/computer_use_native_roundtrip.rs index a187072831..617bf039e1 100644 --- a/src/apps/desktop/tests/computer_use_native_roundtrip.rs +++ b/src/apps/desktop/tests/computer_use_native_roundtrip.rs @@ -7,6 +7,7 @@ fn main() { if std::env::var_os("OPENBITFUN_ROUNDTRIP_FIXTURE_PID").is_none() && std::env::var_os("OPENBITFUN_INPUT_FIXTURE_PID").is_none() && std::env::var_os("OPENBITFUN_CUA_PROBE_PID").is_none() + && std::env::var_os("OPENBITFUN_CUA_SELF_TEST").is_none() { eprintln!( "Run node scripts/test-macos-control-roundtrip.mjs, or set OPENBITFUN_CUA_PROBE_PID for the scoped JSONL probe" @@ -25,9 +26,15 @@ fn main() { let app: *mut objc2::runtime::AnyObject = unsafe { objc2::msg_send![objc2::class!(NSApplication), sharedApplication] }; let _: bool = unsafe { objc2::msg_send![app, setActivationPolicy: 2isize] }; + let _self_window = std::env::var_os("OPENBITFUN_CUA_SELF_TEST").map(|_| { + let _: bool = unsafe { objc2::msg_send![app, setActivationPolicy: 1isize] }; + let _: () = unsafe { objc2::msg_send![app, finishLaunching] }; + self_webview::create() + }); if let Some(path) = std::env::var_os("OPENBITFUN_INPUT_HOST_READY") { std::fs::write(path, b"ready").unwrap(); } + let self_test = _self_window.is_some(); std::thread::spawn(move || { let result = std::panic::catch_unwind(|| { tokio::runtime::Builder::new_multi_thread() @@ -37,8 +44,18 @@ fn main() { .unwrap() .block_on(openbitfun_desktop_lib::run_native_computer_use_roundtrip_fixture()); }); - let _ = sender.send(result.is_ok()); + let ok = result.is_ok(); + if self_test { + // Own-process accessibility and input need a real AppKit event + // loop. Exit only this disposable fixture after control cleanup. + dispatch::Queue::main().exec_async(move || std::process::exit(if ok { 0 } else { 1 })); + } + let _ = sender.send(ok); }); + if self_test { + let _: () = unsafe { objc2::msg_send![app, run] }; + return; + } let limit = if std::env::var_os("OPENBITFUN_CUA_PROBE_PID").is_some() { std::env::var("OPENBITFUN_CUA_PROBE_TIMEOUT_SECS") .ok() @@ -66,6 +83,10 @@ fn main() { std::thread::sleep(Duration::from_millis(1)); } } + +#[cfg(target_os = "macos")] +#[path = "fixtures/computer_use_self_webview.rs"] +mod self_webview; #[cfg(not(target_os = "macos"))] fn main() { eprintln!("Native Computer Use roundtrip requires macOS"); diff --git a/src/apps/desktop/tests/fixtures/computer_use_self_webview.rs b/src/apps/desktop/tests/fixtures/computer_use_self_webview.rs new file mode 100644 index 0000000000..458e128a09 --- /dev/null +++ b/src/apps/desktop/tests/fixtures/computer_use_self_webview.rs @@ -0,0 +1,39 @@ +//! Real same-process AppKit chrome and a separate WebKit accessibility subtree. +use objc2::{msg_send, rc::Retained, runtime::AnyObject, MainThreadMarker, MainThreadOnly}; +use objc2_app_kit::{NSBackingStoreType, NSWindow, NSWindowStyleMask}; +use objc2_foundation::{NSPoint, NSRect, NSSize, NSString}; + +#[link(name = "WebKit", kind = "framework")] +unsafe extern "C" {} + +pub(super) fn create() -> Retained { + let mtm = MainThreadMarker::new().unwrap(); + let frame = NSRect::new(NSPoint::new(100.0, 100.0), NSSize::new(640.0, 480.0)); + unsafe { + let window = NSWindow::initWithContentRect_styleMask_backing_defer( + NSWindow::alloc(mtm), + frame, + NSWindowStyleMask::Titled | NSWindowStyleMask::Closable | NSWindowStyleMask::Resizable, + NSBackingStoreType::Buffered, + false, + ); + window.setReleasedWhenClosed(false); + window.setTitle(&NSString::from_str("Computer Use Self WebView Fixture")); + let view: *mut AnyObject = msg_send![objc2::class!(WKWebView), alloc]; + let view: *mut AnyObject = msg_send![view, initWithFrame: frame]; + let view = Retained::from_raw(view).expect("WKWebView initialization"); + let _: () = msg_send![&*window, setContentView: &*view]; + let html = NSString::from_str( + r#" +

Self observation ready

+ + +

Self click count 0

+ "#, + ); + let _: *mut AnyObject = + msg_send![&*view, loadHTMLString: &*html, baseURL: std::ptr::null::()]; + window.orderFrontRegardless(); + window + } +} From eafa25da7ee6ca6b17876fbf5b12082495ff38c0 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 11:43:58 +0800 Subject: [PATCH 3/6] test(web-ui): retain session navigation scroll-root contract --- .../src/app/components/NavPanel/unifiedSessionCreation.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web-ui/src/app/components/NavPanel/unifiedSessionCreation.test.ts b/src/web-ui/src/app/components/NavPanel/unifiedSessionCreation.test.ts index 7b1d84f58e..e079549be2 100644 --- a/src/web-ui/src/app/components/NavPanel/unifiedSessionCreation.test.ts +++ b/src/web-ui/src/app/components/NavPanel/unifiedSessionCreation.test.ts @@ -95,7 +95,7 @@ describe('unified project session creation', () => { expect(mainNav).toContain("activateProductAction('surface.todos.open')"); expect(mainNav).not.toContain("new Set(['sessions'])"); expect(mainNav).toContain('label={t(\'nav.items.sessions\')}'); - expect(mainNav).toContain(''); + expect(mainNav).toContain(''); expect(workspaceList).toContain('variant: SessionNavigationScope'); expect(workspaceList).toContain("variant === 'all'"); expect(workspaceList).toContain('openedWorkspacesList'); From 839badb0632422e68d184b30f760e0983015bc4b Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 11:46:14 +0800 Subject: [PATCH 4/6] fix(desktop): avoid no-op selected-text writes on AX proxies --- scripts/test-macos-computer-use-self.mjs | 2 +- src/apps/desktop/src/computer_use/AGENTS.md | 9 ++++- .../native_control_roundtrip_tests.rs | 38 ++++++++++++++++++- .../src/computer_use/macos_ax_write.rs | 27 +++++++++++-- .../fixtures/computer_use_self_webview.rs | 10 ++++- 5 files changed, 76 insertions(+), 10 deletions(-) diff --git a/scripts/test-macos-computer-use-self.mjs b/scripts/test-macos-computer-use-self.mjs index f9db0c9456..56c27c7b92 100644 --- a/scripts/test-macos-computer-use-self.mjs +++ b/scripts/test-macos-computer-use-self.mjs @@ -11,7 +11,7 @@ const run = (command, args, options = {}) => new Promise((resolve, reject) => { let output = ''; child.stdout?.on('data', chunk => { output += String(chunk); }); child.once('error', reject); - child.once('exit', (code, signal) => code === 0 ? resolve(output) : reject(new Error(`${command} failed: code=${code} signal=${signal}`))); + child.once('close', (code, signal) => code === 0 ? resolve(output) : reject(new Error(`${command} failed: code=${code} signal=${signal}`))); }); const args = ['test', '--locked', '-p', 'openbitfun-desktop', '--features', 'devtools', '--test', 'computer_use_native_roundtrip']; let executable = process.env.OPENBITFUN_TEST_BINARY; diff --git a/src/apps/desktop/src/computer_use/AGENTS.md b/src/apps/desktop/src/computer_use/AGENTS.md index 3747b75dd9..f96ba34800 100644 --- a/src/apps/desktop/src/computer_use/AGENTS.md +++ b/src/apps/desktop/src/computer_use/AGENTS.md @@ -127,6 +127,11 @@ attribute writes, because Stop may revoke a queued message. Observation-only AX enablement does not acquire input authority. Enigo / HIToolbox input retains its main-thread wrapper. +Cross-process AX proxies can advertise a writable `AXSelectedText` whose setter +does nothing (WebKit). Select the existing directed-keyboard route before +submission for these proxies; native controls retain AX insertion at the current +selection. Never retry a submitted text write based only on unchanged AX state. + The directed-input route can change a target application's internal focus without changing the human foreground application. Its window-addressed focus pair at local `(-8,-8)` must remain outside content; the requested gesture @@ -203,8 +208,8 @@ node scripts/test-macos-input-controls.mjs --latency node scripts/test-macos-input-controls.mjs # Full Tool -> provider -> native loop on a dedicated window, with main-thread runloop. node scripts/test-macos-control-roundtrip.mjs -# Same-process AppKit + real WebKit subtree: observe, capture, click once, -# observe the actual DOM result, read shortcuts and Stop; external deadlock watchdog. +# Same-process AppKit + real WebKit subtree: observe, capture, image/node clicks, +# exact text, actual DOM results, shortcuts and Stop; external deadlock watchdog. node scripts/test-macos-computer-use-self.mjs # Same-process popup panel over a dedicated window, once as an attached child # window (inherits layer 0) and once at the pop-up menu level: composited pixels diff --git a/src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs b/src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs index c94f1fee5a..af8cfd7b9c 100644 --- a/src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs +++ b/src/apps/desktop/src/computer_use/desktop_host/native_control_roundtrip_tests.rs @@ -629,13 +629,47 @@ async fn self_webview_roundtrip() { .contains("Self click count 1"), "{clicked}" ); + let button_idx = observed_node_index(&clicked, "Self test button"); + let clicked = call( + &tool, + &context, + json!({"action":"app_click", "app":app, + "observation_id":clicked["app_state"]["observation_id"], + "target":{"kind":"node_idx", "idx":button_idx}}), + ) + .await; + assert!( + clicked["app_state"]["tree_text"] + .as_str() + .unwrap() + .contains("Self click count 2"), + "{clicked}" + ); + let field_idx = observed_node_index(&clicked, "text field title=\"Self test field\""); + let typed = call( + &tool, + &context, + json!({"action":"app_type_text", "app":app, "text":"Self input ✓", + "observation_id":clicked["app_state"]["observation_id"], + "focus":{"kind":"node_idx", "idx":field_idx}}), + ) + .await; + let typed_tree = typed["app_state"]["tree_text"].as_str().unwrap(); + assert!( + typed_tree.contains("Self input value: Self input ✓"), + "The DOM must contain the exact inserted text: {typed}" + ); + assert!( + typed_tree.contains("Self click count 2"), + "Text focus must not activate the button again: {typed}" + ); call( &tool, &context, json!({"action":"get_app_shortcuts","app":app}), ) .await; - let native_idx = observed_node_index(&clicked, "Computer Use Self WebView Fixture"); + let native_idx = observed_node_index(&typed, "Computer Use Self WebView Fixture"); let native_target = crate::computer_use::macos_ax_dump::retained_cached_target(pid as i32, native_idx).unwrap(); let lease = crate::computer_use::control_session::acquire(OWNER, "app_click").unwrap(); @@ -676,7 +710,7 @@ async fn self_webview_roundtrip() { .await .unwrap(); call(&tool, &context, json!({"action":"stop_control"})).await; - eprintln!("PASS same-process AppKit/WebKit observations, screenshot, one button click, shortcuts and Stop with stale-input rejection through ComputerUse"); + eprintln!("PASS same-process AppKit/WebKit observations, screenshot, exact image/node clicks, Unicode text, shortcuts and Stop with stale-input rejection through ComputerUse"); } async fn run_covered_semantic() { diff --git a/src/apps/desktop/src/computer_use/macos_ax_write.rs b/src/apps/desktop/src/computer_use/macos_ax_write.rs index 128f613c1d..58f31de082 100644 --- a/src/apps/desktop/src/computer_use/macos_ax_write.rs +++ b/src/apps/desktop/src/computer_use/macos_ax_write.rs @@ -5,8 +5,8 @@ //! 1. Resolve `(pid, idx)` to a live `AxRef` via `macos_ax_dump::cached_ref`. //! 2. Try the AX path here without activating the target. The target owns //! the semantic action's effects; dispatch alone does not verify them. -//! 3. On failure (`Err(AxWriteUnavailable)`): the dispatch layer falls back -//! to `macos_bg_input` (background `CGEvent` injection to the pid). +//! 3. Only preflight/unsupported outcomes may select `macos_bg_input`. +//! An attempted mutation with an unknown outcome must never be replayed. //! //! Target applications decide which semantic operations they accept. @@ -34,8 +34,8 @@ unsafe extern "C" { pub(super) enum AxWriteOutcome { /// The AX call succeeded — no fallback needed. Ok, - /// AX rejected the call (status non-zero or unsupported). Caller should - /// fall through to event injection. + /// AX rejected the call. Only an explicitly unsupported operation permits + /// event injection; other failures may have an unknown mutation outcome. Unavailable(i32), } @@ -119,6 +119,25 @@ pub(super) fn insert_selected_text( "[CONTROL_TARGET_CHANGED] Text target is outside the active capture", )); } + // Cross-process accessibility proxies (notably WebKit content) can report + // AXSelectedText as settable while its implementation is a no-op. Do not + // submit that write and then retry: choose directed keyboard input during + // preflight. Native controls keep the selection-preserving AX fast path. + let mut presenter = 0; + let status = unsafe { AXUIElementGetPid(target.0, &mut presenter) }; + if status != 0 { + return Err(OpenBitFunError::tool(format!( + "[AX_TEXT_PREFLIGHT_FAILED] Cannot resolve the text target process (status={status}); no text was submitted" + ))); + } + let serving = unsafe { super::macos_ax_dispatch::actual_pid(target.0) }.map_err(|status| { + OpenBitFunError::tool(format!( + "[AX_TEXT_PREFLIGHT_FAILED] Cannot resolve the text provider process (status={status}); no text was submitted" + )) + })?; + if serving != presenter { + return Ok(false); + } let attr = CFString::new("AXSelectedText"); let mut settable = 0u8; let status = unsafe { diff --git a/src/apps/desktop/tests/fixtures/computer_use_self_webview.rs b/src/apps/desktop/tests/fixtures/computer_use_self_webview.rs index 458e128a09..e890b8d18d 100644 --- a/src/apps/desktop/tests/fixtures/computer_use_self_webview.rs +++ b/src/apps/desktop/tests/fixtures/computer_use_self_webview.rs @@ -28,7 +28,15 @@ pub(super) fn create() -> Retained {

Self observation ready

-

Self click count 0

+

Self click count 0

Self input value:

+ "#, ); let _: *mut AnyObject = From 9e750ce8c01b46d58816d65531fde062e931e15c Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 11:48:19 +0800 Subject: [PATCH 5/6] test(cli): tolerate closed SSE transport after completion --- src/apps/cli/tests/support/mod.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/apps/cli/tests/support/mod.rs b/src/apps/cli/tests/support/mod.rs index a413b4732c..f3d1b2bbd9 100644 --- a/src/apps/cli/tests/support/mod.rs +++ b/src/apps/cli/tests/support/mod.rs @@ -573,10 +573,11 @@ fn serve_model_response( ) .expect("write scripted tool response"); write_chunk(stream, b"data: [DONE]\n\n").expect("finish scripted tool SSE"); - stream - .write_all(b"0\r\n\r\n") - .expect("finish scripted response"); - stream.flush().expect("flush scripted response"); + // The client may close as soon as it consumes [DONE]. A Windows + // ConnectionAborted here must not kill the server for the next tool + // response; all required SSE data was already written successfully. + let _ = stream.write_all(b"0\r\n\r\n"); + let _ = stream.flush(); return; } @@ -771,10 +772,9 @@ fn serve_product_control_response(stream: &mut TcpStream, attempt: usize) { } write_chunk(stream, b"data: [DONE]\n\n").expect("finish product-control SSE"); - stream - .write_all(b"0\r\n\r\n") - .expect("finish product-control chunked response"); - stream.flush().expect("flush product-control response"); + // Match the ordinary streaming response: EOF after [DONE] is normal. + let _ = stream.write_all(b"0\r\n\r\n"); + let _ = stream.flush(); } fn write_http_403(stream: &mut TcpStream, reason: &str) -> std::io::Result<()> { From d013823a6b68039c736e9ccd47bf78a574593bc3 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 29 Oct 2026 11:49:13 +0800 Subject: [PATCH 6/6] test(cli): keep scripted server alive after completed streams --- src/apps/cli/tests/support/mod.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/apps/cli/tests/support/mod.rs b/src/apps/cli/tests/support/mod.rs index f3d1b2bbd9..63b64d7980 100644 --- a/src/apps/cli/tests/support/mod.rs +++ b/src/apps/cli/tests/support/mod.rs @@ -572,10 +572,12 @@ fn serve_model_response( .to_string(), ) .expect("write scripted tool response"); - write_chunk(stream, b"data: [DONE]\n\n").expect("finish scripted tool SSE"); - // The client may close as soon as it consumes [DONE]. A Windows + // The client may close as soon as it consumes the finish reason. A Windows // ConnectionAborted here must not kill the server for the next tool // response; all required SSE data was already written successfully. + if write_chunk(stream, b"data: [DONE]\n\n").is_err() { + return; + } let _ = stream.write_all(b"0\r\n\r\n"); let _ = stream.flush(); return; @@ -771,8 +773,10 @@ fn serve_product_control_response(stream: &mut TcpStream, attempt: usize) { .expect("write product-control completion chunk"); } - write_chunk(stream, b"data: [DONE]\n\n").expect("finish product-control SSE"); - // Match the ordinary streaming response: EOF after [DONE] is normal. + // Match the ordinary streaming response: EOF after completion is normal. + if write_chunk(stream, b"data: [DONE]\n\n").is_err() { + return; + } let _ = stream.write_all(b"0\r\n\r\n"); let _ = stream.flush(); }