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-rs)(windows): suppress UWP self-foreground during UIA Invoke / Expand / Toggle (#1690)
Francesco Bonacci8137a3d7cf34
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools.mdx b/docs/content/docs/cua-driver/reference/mcp-tools.mdxindex e7b6077f56..4f4bf10d72 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools.mdx@@ -1173,6 +1173,16 @@ The `x, y` dispatch tries UIA Invoke first (no focus steal), then falls throughFor canvases, paint surfaces, image maps, and custom widgets (control types `Image` / `Pane` / `Custom` / `Document` / `Group`), `click(x, y)` skips UIA Invoke even when the element advertises `InvokePattern` — invoking those fires the element's default action at the geometric centre, ignoring the requested coords. The click falls through to PostMessage or (for Chromium targets) SendInput, preserving pixel precision.+### `click` on UWP / WinUI / XAML targets — foreground-steal bypass++UWP, WinUI, and XAML-hosted apps (Calculator, Clock, Settings, Microsoft Photos, modern Notepad, etc.) self-foreground during UIA `InvokePattern.Invoke`. The XAML host calls `SetForegroundWindow(self)` unconditionally when its message-loop processes an input-like event — including UIA Invoke. Without mitigation, every `click` against a UWP target hidden behind the user's window steals focus and pulls the UWP app on top.++The driver wraps `Invoke`, `ExpandCollapse.Expand`, and `Toggle.Toggle` calls in `EnableWindow(host, FALSE) / call / EnableWindow(host, TRUE)` when the target's top-level HWND identifies as an XAML host (window class `ApplicationFrameWindow` / `Windows.UI.Core.CoreWindow` / `WinUIDesktopWin32WindowClass` / `Microsoft.UI.Content.DesktopChildSiteBridge`, OR a known XAML-hosted exe). A disabled HWND silently rejects `SetForegroundWindow(self)`, but UIA pattern delivery still routes through (it uses the kernel accessibility channel, not the input queue gated by `EnableWindow`), so the click action still runs.++Empirically: 91% of plain-Invoke samples saw the user's window drop below the target in z-order; with the bypass that drops to 0%. State changes (Calc digits, Clock tabs, Settings nav) are confirmed via UIA probes after the call.++Classic Win32 / WPF / WinForms apps (Notepad legacy, charmap, mmc) don't self-foreground during Invoke and don't need the bypass — verified empirically. The wrap is therefore gated on `is_xaml_host_hwnd`; non-XAML targets call `Invoke` unwrapped.+### `click(x, y)` on Chromium — SendInput with brief foreground swap`PostMessage(WM_LBUTTONDOWN/UP)` on a Chromium HWND doesn't reach the DOM input pipeline (Chromium's input thread requires SendInput-queue origin). When the target HWND class is `Chrome_WidgetWin_*` or `CefBrowser*`, `click(x, y)` routes through `SendInput` with a brief `SetForegroundWindow(target)` + `SetCursorPos(x, y)` + restore-previous-foreground dance.diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rsindex 511158e6ba..1515781681 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs@@ -1569,7 +1569,14 @@ impl Tool for ClickTool {std::mem::forget(elem);if let Ok(pattern) = invoke_result {if let Ok(inv) = pattern.cast::<IUIAutomationInvokePattern>() {- match unsafe { inv.Invoke() } {+ // UWP foreground-steal bypass: wrap Invoke so+ // XAML hosts don't self-foreground and steal+ // user focus. See crate::uia::fg_bypass.+ let invoke_outcome = crate::uia::fg_bypass::run_with_uwp_bypass(+ hwnd as isize,+ || unsafe { inv.Invoke() },+ );+ match invoke_outcome {Ok(()) => {return Ok(format!("✅ Performed UIA Invoke on [{idx}] (screen ({cx},{cy}))."diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/fg_bypass.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/fg_bypass.rsnew file mode 100644index 0000000000..a757d02dcf--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/fg_bypass.rs@@ -0,0 +1,91 @@+//! Foreground-steal bypass for UWP / XAML / WinUI UIA activation calls.+//!+//! UWP/XAML/WinUI apps self-foreground during UIA `InvokePattern.Invoke`+//! (and `ExpandCollapse.Expand`, `Toggle.Toggle`, `SelectionItem.Select` —+//! anything the XAML message-loop processes as an input-like event). The+//! XAML host unconditionally calls `SetForegroundWindow(self)` when handling+//! those, stealing focus from whatever the user had on top.+//!+//! Wrapping the call in `EnableWindow(host, FALSE) / call / EnableWindow(host, TRUE)`+//! silently suppresses the self-activation while letting the UIA pattern call+//! still execute — UIA pattern delivery uses the kernel accessibility channel,+//! not the input queue gated by `EnableWindow`.+//!+//! Empirical evidence (`flash-repro/14-multi-uwp-v3.ps1`, 2026-05-24):+//! - Baseline UIA Invoke against UWP Calculator num5 button: user's+//! foreground window dropped below the target in 91% of poller samples.+//! - With this bypass: 0/507 z-drops across Calculator, Clock, Settings.+//!+//! Non-UWP / classic Win32 apps don't exhibit the bug+//! (`flash-repro/15-non-uwp.ps1`, Notepad: 0/45 baseline z-drops). The bypass+//! is therefore gated on `crate::input::is_xaml_host_hwnd` and is a no-op+//! for non-XAML hosts.++use windows::Win32::Foundation::HWND;+use windows::Win32::UI::Input::KeyboardAndMouse::EnableWindow;+use windows::Win32::UI::WindowsAndMessaging::{GA_ROOT, GetAncestor};++/// RAII guard that disables a window on construction and restores its+/// previous enabled-state on Drop. Always re-arms on Drop even if the+/// wrapped action panics.+pub struct DisabledHwndGuard {+ hwnd: HWND,+ was_enabled: bool,+ armed: bool,+}++impl DisabledHwndGuard {+ /// Disable `hwnd` for the lifetime of the guard. No-op for null HWND.+ pub fn disable(hwnd: HWND) -> Self {+ if hwnd.0.is_null() {+ return Self { hwnd, was_enabled: false, armed: false };+ }+ // `EnableWindow` returns nonzero iff the window was *previously+ // disabled* — invert to get the "was enabled" state we want to+ // restore at Drop time.+ let was_disabled = unsafe { EnableWindow(hwnd, false).as_bool() };+ Self { hwnd, was_enabled: !was_disabled, armed: true }+ }+}++impl Drop for DisabledHwndGuard {+ fn drop(&mut self) {+ if self.armed {+ unsafe {+ let _ = EnableWindow(self.hwnd, self.was_enabled);+ }+ }+ }+}++/// Wrap an activation closure (Invoke / Expand / Toggle / SelectionItem.Select)+/// in a UWP foreground-steal bypass.+///+/// `host_hwnd` is the top-level HWND of the window that contains the target+/// UIA element. When it identifies as an XAML host (`is_xaml_host_hwnd`), the+/// HWND is disabled for the duration of `action`. For non-XAML / classic+/// Win32 hosts the closure runs unmodified — empirically those don't+/// self-foreground.+///+/// The guard restores the previous enabled-state at Drop, so a panic in+/// `action` still leaves the window in a usable state.+pub fn run_with_uwp_bypass<T>(host_hwnd: isize, action: impl FnOnce() -> T) -> T {+ let _guard = make_guard(host_hwnd);+ action()+}++fn make_guard(host_hwnd: isize) -> Option<DisabledHwndGuard> {+ if host_hwnd == 0 {+ return None;+ }+ if !crate::input::is_xaml_host_hwnd(host_hwnd as u64) {+ return None;+ }+ let h = HWND(host_hwnd as *mut _);+ // Defensive: walk up to the root in case the caller handed us a child+ // HWND inside the XAML host's HWND tree. UWP elements always disable+ // cleanly via the AppFrame root.+ let root = unsafe { GetAncestor(h, GA_ROOT) };+ let target = if root.0.is_null() { h } else { root };+ Some(DisabledHwndGuard::disable(target))+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rsindex d82bc4fb2d..1a58886f7c 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rs@@ -24,6 +24,7 @@ use windows::Win32::UI::Accessibility::{};pub mod cache;+pub mod fg_bypass;pub mod windows_enum;pub use cache::ElementCache;pub use windows_enum::enumerate_top_level_windows;diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/windows_enum.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/windows_enum.rsindex 12cb2603dd..5973f34789 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/uia/windows_enum.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/windows_enum.rs@@ -319,47 +319,52 @@ pub fn try_invoke_in_window_at_point(hwnd: isize, sx: i32, sy: i32) -> bool {).is_ok();let winner_has_invoke = winner.GetCurrentPattern(UIA_InvokePatternId).is_ok();- if winner_has_expand && winner_has_invoke {- // Try Expand first, fall back to Invoke if Expand fails.- if let Ok(pat) = winner.GetCurrentPattern(- windows::Win32::UI::Accessibility::UIA_ExpandCollapsePatternId,- ) {- if let Ok(ec) = pat- .cast::<windows::Win32::UI::Accessibility::IUIAutomationExpandCollapsePattern>()- {- if ec.Expand().is_ok() {- return true;+ // UWP foreground-steal bypass: gate the entire activation block on+ // `is_xaml_host_hwnd(hwnd)`. For non-XAML hosts the closure is a+ // straight passthrough.+ crate::uia::fg_bypass::run_with_uwp_bypass(hwnd, || {+ if winner_has_expand && winner_has_invoke {+ // Try Expand first, fall back to Invoke if Expand fails.+ if let Ok(pat) = winner.GetCurrentPattern(+ windows::Win32::UI::Accessibility::UIA_ExpandCollapsePatternId,+ ) {+ if let Ok(ec) = pat+ .cast::<windows::Win32::UI::Accessibility::IUIAutomationExpandCollapsePattern>()+ {+ if ec.Expand().is_ok() {+ return true;+ }}}- }- // Expand failed — fall through to Invoke as best-effort.- } else if winner_has_expand && !winner_has_invoke {- if let Ok(pat) = winner.GetCurrentPattern(- windows::Win32::UI::Accessibility::UIA_ExpandCollapsePatternId,- ) {- if let Ok(ec) = pat- .cast::<windows::Win32::UI::Accessibility::IUIAutomationExpandCollapsePattern>()- {- return ec.Expand().is_ok();+ // Expand failed — fall through to Invoke as best-effort.+ } else if winner_has_expand && !winner_has_invoke {+ if let Ok(pat) = winner.GetCurrentPattern(+ windows::Win32::UI::Accessibility::UIA_ExpandCollapsePatternId,+ ) {+ if let Ok(ec) = pat+ .cast::<windows::Win32::UI::Accessibility::IUIAutomationExpandCollapsePattern>()+ {+ return ec.Expand().is_ok();+ }}+ return false;}- return false;- }- let pattern = match winner.GetCurrentPattern(UIA_InvokePatternId) {- Ok(p) => p,- Err(_) => return false,- };- let inv: IUIAutomationInvokePattern = match pattern.cast() {- Ok(i) => i,- Err(_) => return false,- };- match inv.Invoke() {- Ok(()) => true,- Err(e) => {- tracing::debug!(target: "click", "UIA Invoke (windowed) at ({sx},{sy}) failed: {e}");- false+ let pattern = match winner.GetCurrentPattern(UIA_InvokePatternId) {+ Ok(p) => p,+ Err(_) => return false,+ };+ let inv: IUIAutomationInvokePattern = match pattern.cast() {+ Ok(i) => i,+ Err(_) => return false,+ };+ match inv.Invoke() {+ Ok(()) => true,+ Err(e) => {+ tracing::debug!(target: "click", "UIA Invoke (windowed) at ({sx},{sy}) failed: {e}");+ false+ }}- }+ })}}@@ -439,7 +444,7 @@ pub fn try_invoke_accelerator_in_window(// as a TogglePattern button — calling .Invoke on it returns the// misleading "operation completed successfully (0x00000000)"// error because Invoke isn't supported on the element.- match try_invoke_via_patterns(&elem) {+ match try_invoke_via_patterns(&elem, hwnd) {Ok(true) => return Ok((true, count as usize)),Ok(false) => {matched_failure = Some(format!(@@ -547,21 +552,36 @@ fn accelerator_modifier_rank(value: &str) -> Option<usize> {/// order: InvokePattern (for buttons / menu items that fire an action), then/// TogglePattern (for Bold / Italic / etc. that flip a binary state).///+/// `host_hwnd` is the top-level HWND containing the element; it gates the+/// UWP foreground-steal bypass (see `crate::uia::fg_bypass`). Pass `0` if+/// unknown — the bypass becomes a no-op and Invoke/Toggle run unwrapped.+////// Returns `Ok(true)` if a pattern was found AND its Invoke/Toggle call/// succeeded. `Ok(false)` means the element exposes neither pattern (caller/// should surface an actionable error). `Err` means a pattern was found but/// its call failed (caller should surface the underlying error).-unsafe fn try_invoke_via_patterns(elem: &IUIAutomationElement) -> anyhow::Result<bool> {+unsafe fn try_invoke_via_patterns(+ elem: &IUIAutomationElement,+ host_hwnd: isize,+) -> anyhow::Result<bool> {// Invoke first — that's what most accelerator-targeted controls advertise.if let Ok(pattern) = elem.GetCurrentPattern(UIA_InvokePatternId) {if let Ok(inv) = pattern.cast::<IUIAutomationInvokePattern>() {- return inv.Invoke().map(|()| true).map_err(|e| anyhow::anyhow!("InvokePattern.Invoke: {e}"));+ return crate::uia::fg_bypass::run_with_uwp_bypass(host_hwnd, || {+ inv.Invoke()+ .map(|()| true)+ .map_err(|e| anyhow::anyhow!("InvokePattern.Invoke: {e}"))+ });}}// Toggle next — Bold/Italic/Underline-style toolbar buttons sit here.if let Ok(pattern) = elem.GetCurrentPattern(UIA_TogglePatternId) {if let Ok(tog) = pattern.cast::<IUIAutomationTogglePattern>() {- return tog.Toggle().map(|()| true).map_err(|e| anyhow::anyhow!("TogglePattern.Toggle: {e}"));+ return crate::uia::fg_bypass::run_with_uwp_bypass(host_hwnd, || {+ tog.Toggle()+ .map(|()| true)+ .map_err(|e| anyhow::anyhow!("TogglePattern.Toggle: {e}"))+ });}}Ok(false)