Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): verify foreground Document text insertion

injaneity0525de1e6439
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/click-and-type.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/click-and-type.mdx
index ff6327e511..c682a9db88 100644
--- a/docs/content/docs/cua-driver/reference/mcp-tools/click-and-type.mdx
+++ b/docs/content/docs/cua-driver/reference/mcp-tools/click-and-type.mdx
@@ -351,7 +351,7 @@ Insert text into the target pid via character-by-character PostMessage(WM_CHAR)
Special keys (Return, Escape, arrows, Tab) go through `press_key` / `hotkey`: they are not text.
-**Routing on Windows.** When the target's owning EXE or top-level window class identifies it as a XAML / WinUI3 / UWP host (modern Notepad, Calculator, Photos, Settings, etc.), the tool requires `element_token` and routes through UI Automation's `ValuePattern.SetValue`: same backend as the `set_value` tool. PostMessage WM_CHAR doesn't reach those hosts (their CoreInput dispatcher only consumes events from the system input queue), so the fallback path silently dropped chars. If you call `type_text(pid, text)` on a XAML host without `element_token`, the tool returns an actionable error pointing you at `get_window_state` first. Native ConsoleHost on Windows ARM64 is hard-refused because it can accept synthesized Unicode events without delivering them; use a process or PTY setup channel instead. Legacy Win32 apps still use the PostMessage path, preserving the no-focus-steal property.
+**Routing on Windows.** `element_token` selects a specific UIA element and writes its ValuePattern value. For no-element foreground typing, a separate capability-gated path can use the exact focused UIA Document only when it is writable and empty. Eligibility depends on control capabilities and live focus, not app names. Chromium/Electron windows keep their existing boundary because a UIA value echo does not prove that the renderer accepted the text. The path reads the value and caret back; after SetValue starts, an unverifiable result requires a fresh observation before any retry and is never replayed through native input. This replaces the full ValuePattern value, so rich-text formatting and native undo behavior are not guaranteed; single-line Edit controls keep the existing input route. For other XAML / WinUI3 / UWP cases, use `element_token` from `get_window_state`; background WM_CHAR does not reach their CoreInput dispatcher. Native ConsoleHost on Windows ARM64 is hard-refused because it can accept synthesized Unicode events without delivering them; use a process or PTY setup channel instead. Legacy Win32 apps still use the PostMessage path, preserving the no-focus-steal property.
`delay_ms` (0–200, default 30) spaces successive characters on the PostMessage path so autocomplete and IME can keep up. Ignored on the UIA path (SetValue is atomic).
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_.rs
index 14e08e7329..0ecc1cb90b 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
@@ -4596,16 +4596,22 @@ impl Tool for TypeTextTool {
PostMessage(WM_CHAR) to the focused window. No focus steal.\n\n\
Special keys (Return, Escape, arrows, Tab) go through `press_key` / \
`hotkey` — they are not text.\n\n\
- **Routing on Windows.** When the target's owning EXE or top-level window \
- class identifies it as a XAML / WinUI3 / UWP host (modern Notepad, \
- Calculator, Photos, Settings, etc.), the tool requires `element_token` \
- and routes through UI Automation's `ValuePattern.SetValue` \
- — same backend as the `set_value` tool. PostMessage WM_CHAR doesn't \
- reach those hosts (their CoreInput dispatcher only consumes events from \
- the system input queue), so the fallback path silently dropped chars. \
- If you call `type_text(pid, text)` on a XAML host without `element_token`, \
- the tool returns an actionable error pointing you at `get_window_state` \
- first. Native ConsoleHost on Windows ARM64 is hard-refused because it can \
+ **Routing on Windows.** `element_token` selects a specific UIA element \
+ and writes its ValuePattern value. For no-element foreground typing, a \
+ separate capability-gated path can use the exact focused UIA Document \
+ only when it is writable and empty. \
+ Eligibility depends on control capabilities and live focus, not app names. \
+ Chromium/Electron windows keep their existing boundary because a UIA \
+ value echo does not prove that the renderer accepted the text. The \
+ path reads the value and caret back; after SetValue starts, an \
+ unverifiable result requires a fresh observation before any retry and \
+ is never replayed through native input. This replaces the full \
+ ValuePattern value, so rich-text formatting and native undo behavior \
+ are not guaranteed; single-line Edit controls \
+ keep the existing input route. For other XAML / WinUI3 / UWP cases, \
+ use `element_token` from `get_window_state`; background WM_CHAR does \
+ not reach their CoreInput dispatcher. Native ConsoleHost on Windows ARM64 is \
+ hard-refused because it can \
accept synthesized Unicode events without delivering them; use a process \
or PTY setup channel instead. Legacy Win32 apps still use the PostMessage \
path, preserving the no-focus-steal property.\n\n\
@@ -4650,6 +4656,15 @@ impl Tool for TypeTextTool {
Err(error) => return ToolResult::error(error.to_string()),
};
let text_len = text.chars().count();
+ if args.get("element_token").is_none()
+ && args.get("x").is_none()
+ && args.get("y").is_none()
+ {
+ if let Some(result) = try_focused_document_route(hwnd, None, &text, text_len).await
+ {
+ return result;
+ }
+ }
return match tokio::task::spawn_blocking(move || {
crate::input::send_text_synthesized(hwnd, &text)
})
@@ -4822,6 +4837,17 @@ impl Tool for TypeTextTool {
// rejected (daemon not at UIAccess integrity), it returns an error
// rather than a false success.
if delivery == DeliveryMode::Foreground {
+ if elem_idx.is_none()
+ && args.get("element_token").is_none()
+ && args.get("x").is_none()
+ && args.get("y").is_none()
+ {
+ if let Some(result) =
+ try_focused_document_route(hwnd, Some(pid), &text, text_len).await
+ {
+ return result;
+ }
+ }
// Resolve the optional click fallback before entering the atomic
// activation/focus/input transaction. The focus itself happens
// only after exact top-level foreground is confirmed.
@@ -5163,6 +5189,112 @@ impl Tool for TypeTextTool {
}
}
+async fn try_focused_document_route(
+ hwnd: u64,
+ expected_pid: Option<u32>,
+ text: &str,
+ text_len: usize,
+) -> Option<ToolResult> {
+ if crate::input::is_chromium_target_window(hwnd) {
+ return None;
+ }
+ let text = text.to_owned();
+ let outcome = tokio::task::spawn_blocking(move || {
+ crate::uia::focused_document::try_type_focused_document_append(hwnd, expected_pid, &text)
+ })
+ .await
+ .unwrap_or(
+ crate::uia::focused_document::FocusedDocumentTypeOutcome::Unknown(
+ "focused UIA task failed",
+ ),
+ );
+ focused_document_tool_result(outcome, text_len)
+}
+
+fn focused_document_tool_result(
+ outcome: crate::uia::focused_document::FocusedDocumentTypeOutcome,
+ text_len: usize,
+) -> Option<ToolResult> {
+ use crate::uia::focused_document::FocusedDocumentTypeOutcome;
+
+ match outcome {
+ FocusedDocumentTypeOutcome::NotApplicable => None,
+ FocusedDocumentTypeOutcome::Confirmed => Some(
+ ToolResult::text(format!(
+ "Wrote and verified {text_len} character(s) in the focused Document; caret is at the document end."
+ ))
+ .with_structured(json!({
+ "path": "ax",
+ "characters": text_len,
+ "verified": true,
+ "verify": "confirmed",
+ "effect": "confirmed",
+ })),
+ ),
+ FocusedDocumentTypeOutcome::Unknown(stage) => Some(
+ ToolResult::text(format!(
+ "Focused Document text may have been written but could not be verified ({stage}). Inspect the current document before retrying."
+ ))
+ .with_structured(json!({
+ "path": "ax",
+ "characters": text_len,
+ "verified": false,
+ "verify": "unverifiable",
+ "effect": "unverifiable",
+ "retryable": false,
+ })),
+ ),
+ }
+}
+
+#[cfg(test)]
+mod focused_document_result_tests {
+ use super::focused_document_tool_result;
+ use crate::uia::focused_document::FocusedDocumentTypeOutcome;
+ use cua_driver_contract::{ActionEffect, ActionRoute};
+ use cua_driver_core::action_record::{ActionExecutionRecord, ActionTransport};
+ use cua_driver_core::protocol::ToolResult;
+ use serde_json::json;
+
+ fn normalize(result: ToolResult) -> cua_driver_contract::ActionResult {
+ let structured = result
+ .structured_content
+ .expect("focused-document result includes structured evidence");
+ let record = ActionExecutionRecord::from_legacy(
+ "type_text",
+ &json!({"scope": "desktop"}),
+ &structured,
+ )
+ .expect("the action dispatcher recognizes the UIA value transport");
+ assert_eq!(record.transport, ActionTransport::WindowsUiaValue);
+ record
+ .public_result()
+ .expect("focused-document action result normalizes")
+ }
+
+ #[test]
+ fn focused_document_results_normalize_to_accessibility_with_truthful_effects() {
+ let confirmed = focused_document_tool_result(FocusedDocumentTypeOutcome::Confirmed, 12)
+ .expect("confirmed focused-document output");
+ let confirmed = normalize(confirmed);
+ assert_eq!(confirmed.route, ActionRoute::Accessibility);
+ assert_eq!(confirmed.effect, ActionEffect::Confirmed);
+
+ let unknown = focused_document_tool_result(
+ FocusedDocumentTypeOutcome::Unknown("value read-back failed"),
+ 12,
+ )
+ .expect("unknown focused-document output");
+ assert_eq!(
+ unknown.structured_content.as_ref().unwrap()["retryable"],
+ false
+ );
+ let unknown = normalize(unknown);
+ assert_eq!(unknown.route, ActionRoute::Accessibility);
+ assert_eq!(unknown.effect, ActionEffect::Unverifiable);
+ }
+}
+
fn post_message_readback_observed(
before: Option<&str>,
after: Option<&str>,
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/focused_document.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/focused_document.rs
new file mode 100644
index 0000000000..7057e1d443
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/focused_document.rs
@@ -0,0 +1,470 @@
+//! Conservative text insertion for the exact currently focused UIA Document.
+//!
+//! This is a capability probe for no-element foreground typing. It never
+//! activates a window or selects a target. Before the write, every failed
+//! predicate leaves the existing input route available. Once SetValue starts,
+//! failures are unverifiable and must not be retried through another route.
+
+use std::sync::{
+ atomic::{AtomicBool, AtomicU8, Ordering},
+ Arc,
+};
+
+use windows::core::Interface;
+use windows::Win32::Foundation::HWND;
+use windows::Win32::UI::Accessibility::{
+ IUIAutomationElement, IUIAutomationTextPattern, SupportedTextSelection_Single,
+ TextPatternRangeEndpoint_End, TextPatternRangeEndpoint_Start, UIA_DocumentControlTypeId,
+ UIA_TextPatternId, UIA_ValuePatternId,
+};
+use windows::Win32::UI::WindowsAndMessaging::{
+ GetAncestor, GetForegroundWindow, IsWindow, GA_ROOT,
+};
+
+use super::windows_enum::{run_focused_document_uia, UiaDeadlineError};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum FocusedDocumentTypeOutcome {
+ NotApplicable,
+ Confirmed,
+ Unknown(&'static str),
+}
+
+static PENDING_WRITE: AtomicBool = AtomicBool::new(false);
+
+pub(crate) fn try_type_focused_document_append(
+ target_hwnd: u64,
+ expected_pid: Option<u32>,
+ text: &str,
+) -> FocusedDocumentTypeOutcome {
+ if text.is_empty() {
+ return FocusedDocumentTypeOutcome::NotApplicable;
+ }
+
+ let text = text.to_owned();
+ let state = Arc::new(AtomicU8::new(0));
+ let worker_state = Arc::clone(&state);
+ match run_focused_document_uia(move |cancelled| {
+ let outcome = try_type_focused_document_append_unbounded(
+ target_hwnd,
+ expected_pid,
+ &text,
+ &cancelled,
+ &worker_state,
+ );
+ PENDING_WRITE.store(false, Ordering::Release);
+ outcome
+ }) {
+ Ok(outcome) => outcome,
+ Err(error) => focused_document_worker_error(
+ error,
+ state
+ .compare_exchange(0, 2, Ordering::AcqRel, Ordering::Acquire)
+ .unwrap_or_else(|state| state),
+ PENDING_WRITE.load(Ordering::Acquire),
+ ),
+ }
+}
+
+fn try_type_focused_document_append_unbounded(
+ target_hwnd: u64,
+ expected_pid: Option<u32>,
+ text: &str,
+ cancelled: &AtomicBool,
+ state: &AtomicU8,
+) -> FocusedDocumentTypeOutcome {
+ use windows::core::BSTR;
+ use windows::Win32::System::Com::{
+ CoCreateInstance, CoInitializeEx, CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED,
+ };
+ use windows::Win32::System::Threading::GetCurrentThreadId;
+ use windows::Win32::UI::Accessibility::{
+ CUIAutomation, IUIAutomation, IUIAutomationValuePattern,
+ };
+
+ let thread_id = unsafe { GetCurrentThreadId() };
+ let coinit = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
+ if coinit.is_err() {
+ return focused_document_not_applicable(thread_id, Some(coinit.0), "co_initialize_failed");
+ }
+ // Declared before UIA interfaces so they drop before CoUninitialize.
+ let _com = ComApartment;
+ if cancelled.load(Ordering::Acquire) {
+ return focused_document_not_applicable(
+ thread_id,
+ Some(coinit.0),
+ "cancelled_before_probe",
+ );
+ }
+
+ let not_applicable = |stage| focused_document_not_applicable(thread_id, Some(coinit.0), stage);
+ let outcome = (|| {
+ let target = HWND(target_hwnd as *mut _);
+ if !exact_foreground_target(target, expected_pid) {
+ return not_applicable("target_not_exact_foreground");
+ }
+ let Some(target_pid) = crate::win32::windows::window_owner_pid(target_hwnd) else {
+ return not_applicable("target_pid_unavailable");
+ };
+ if expected_pid.is_some_and(|pid| pid != target_pid) {
+ return not_applicable("target_pid_mismatch");
+ }
+
+ let Ok(uia) = (unsafe {
+ CoCreateInstance::<_, IUIAutomation>(&CUIAutomation, None, CLSCTX_INPROC_SERVER)
+ }) else {
+ return not_applicable("uia_create_failed");
+ };
+ let Ok(focused) = (unsafe { uia.GetFocusedElement() }) else {
+ return not_applicable("focused_element_unavailable");
+ };
+ if !focused_document_matches_target(&focused, target, target_pid) {
+ return not_applicable("focused_element_not_exact_document");
+ }
+
+ let Ok(value_pattern) = (unsafe { focused.GetCurrentPattern(UIA_ValuePatternId) }) else {
+ return not_applicable("value_pattern_unavailable");
+ };
+ let Ok(value_pattern) = value_pattern.cast::<IUIAutomationValuePattern>() else {
+ return not_applicable("value_pattern_cast_failed");
+ };
+ let Ok(initial_read_only) = (unsafe { value_pattern.CurrentIsReadOnly() }) else {
+ return not_applicable("value_read_only_state_unavailable");
+ };
+ let Ok(initial_value) = (unsafe { value_pattern.CurrentValue() }) else {
+ return not_applicable("value_unavailable");
+ };
+ let initial_value = initial_value.to_string();
+
+ let Ok(text_pattern) = (unsafe { focused.GetCurrentPattern(UIA_TextPatternId) }) else {
+ return not_applicable("text_pattern_unavailable");
+ };
+ let Ok(text_pattern) = text_pattern.cast::<IUIAutomationTextPattern>() else {
+ return not_applicable("text_pattern_cast_failed");
+ };
+ let single_text_selection = unsafe { text_pattern.SupportedTextSelection() }
+ .is_ok_and(|selection| selection == SupportedTextSelection_Single);
+ let document_matches = unsafe { text_pattern.DocumentRange() }
+ .and_then(|range| unsafe { range.GetText(-1) })
+ .is_ok_and(|value| value.to_string() == initial_value);
+ if !focused_document_eligible(
+ exact_foreground_target(target, Some(target_pid)),
+ !initial_read_only.as_bool(),
+ initial_value.is_empty(),
+ single_text_selection,
+ document_matches,
+ ) {
+ return not_applicable("initial_eligibility_not_met");
+ }
+
+ let Ok(focused_before_write) = (unsafe { uia.GetFocusedElement() }) else {
+ return not_applicable("focused_element_changed_before_write");
+ };
+ if !exact_foreground_target(target, Some(target_pid))
+ || !unsafe { uia.CompareElements(&focused, &focused_before_write) }
+ .is_ok_and(|same| same.as_bool())
+ || !focused_document_matches_target(&focused_before_write, target, target_pid)
+ {
+ return not_applicable("target_or_focus_changed_before_write");
+ }
+ let Ok(read_only_before_write) = (unsafe { value_pattern.CurrentIsReadOnly() }) else {
+ return not_applicable("value_read_only_state_unavailable_before_write");
+ };
+ let Ok(value_before_write) = (unsafe { value_pattern.CurrentValue() }) else {
+ return not_applicable("value_unavailable_before_write");
+ };
+ if read_only_before_write.as_bool() || value_before_write.to_string() != initial_value {
+ return not_applicable("value_changed_or_read_only_before_write");
+ }
+ if !unsafe { text_pattern.DocumentRange() }
+ .and_then(|range| unsafe { range.GetText(-1) })
+ .is_ok_and(|value| value.to_string() == initial_value)
+ {
+ return not_applicable("document_changed_before_write");
+ }
+ // If the UIA deadline fired during pre-write checks, do not start a
+ // write after the caller has already returned an unknown result.
+ PENDING_WRITE.store(true, Ordering::Release);
+ if cancelled.load(Ordering::Acquire)
+ || state
+ .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
+ .is_err()
+ {
+ return not_applicable("cancelled_before_write");
+ }
+
+ let expected_value = text.to_owned();
+ let write_result = (|| -> Result<(), &'static str> {
+ let value = BSTR::from(expected_value.as_str());
+ unsafe { value_pattern.SetValue(&value) }
+ .map_err(|_| "ValuePattern.SetValue failed after dispatch")?;
+ let actual_value = unsafe { value_pattern.CurrentValue() }
+ .map_err(|_| "ValuePattern read-back failed after dispatch")?;
+ if !normalized_text_matches(&expected_value, &actual_value.to_string()) {
+ return Err("ValuePattern read-back did not match after dispatch");
+ }
+
+ let document_range = unsafe { text_pattern.DocumentRange() }
+ .map_err(|_| "TextPattern DocumentRange failed after dispatch")?;
+ let caret_range = unsafe { document_range.Clone() }
+ .map_err(|_| "TextPattern range clone failed after dispatch")?;
+ unsafe {
+ caret_range.MoveEndpointByRange(
+ TextPatternRangeEndpoint_Start,
+ &document_range,
+ TextPatternRangeEndpoint_End,
+ )
+ }
+ .map_err(|_| "TextPattern caret collapse failed after dispatch")?;
+ unsafe { caret_range.Select() }
+ .map_err(|_| "TextPattern caret placement failed after dispatch")?;
+
+ let fresh_document_range = unsafe { text_pattern.DocumentRange() }
+ .map_err(|_| "TextPattern verification range failed after dispatch")?;
+ let selections = unsafe { text_pattern.GetSelection() }
+ .map_err(|_| "TextPattern selection read-back failed after dispatch")?;
+ if unsafe { selections.Length() }
+ .map_err(|_| "TextPattern selection count failed after dispatch")?
+ != 1
+ {
+ return Err("TextPattern did not report exactly one caret after dispatch");
+ }
+ let selection = unsafe { selections.GetElement(0) }
+ .map_err(|_| "TextPattern caret read-back failed after dispatch")?;
+ let start_at_end = unsafe {
+ selection.CompareEndpoints(
+ TextPatternRangeEndpoint_Start,
+ &fresh_document_range,
+ TextPatternRangeEndpoint_End,
+ )
+ }
+ .map_err(|_| "TextPattern caret start comparison failed after dispatch")?;
+ let end_at_end = unsafe {
+ selection.CompareEndpoints(
+ TextPatternRangeEndpoint_End,
+ &fresh_document_range,
+ TextPatternRangeEndpoint_End,
+ )
+ }
+ .map_err(|_| "TextPattern caret end comparison failed after dispatch")?;
+ if start_at_end != 0 || end_at_end != 0 {
+ return Err("TextPattern caret was not at the document end after dispatch");
+ }
+ let final_value = unsafe { value_pattern.CurrentValue() }
+ .map_err(|_| "Final ValuePattern read-back failed after dispatch")?;
+ if !normalized_text_matches(&expected_value, &final_value.to_string()) {
+ return Err("ValuePattern changed during caret placement");
+ }
+ if !exact_foreground_target(target, Some(target_pid)) {
+ return Err("Foreground identity changed after dispatch");
+ }
+ let focused_after = unsafe { uia.GetFocusedElement() }
+ .map_err(|_| "Focused element read-back failed after dispatch")?;
+ let same_element = unsafe { uia.CompareElements(&focused, &focused_after) }
+ .map_err(|_| "Focused element identity comparison failed after dispatch")?;
+ if !same_element.as_bool()
+ || !focused_document_matches_target(&focused_after, target, target_pid)
+ {
+ return Err("Focused Document target changed after dispatch");
+ }
+ Ok(())
+ })();
+ classify_focused_document_write(true, write_result)
+ })();
+
+ outcome
+}
+
+struct ComApartment;
+
+impl Drop for ComApartment {
+ fn drop(&mut self) {
+ unsafe { windows::Win32::System::Com::CoUninitialize() };
+ }
+}
+
+fn focused_document_not_applicable(
+ thread_id: u32,
+ coinit_hresult: Option<i32>,
+ stage: &'static str,
+) -> FocusedDocumentTypeOutcome {
+ tracing::debug!(
+ target: "focused_document_type",
+ thread_id,
+ coinit_hresult = ?coinit_hresult.map(|hr| format!("0x{:08X}", hr as u32)),
+ stage,
+ "focused UIA type path not applicable"
+ );
+ FocusedDocumentTypeOutcome::NotApplicable
+}
+
+fn focused_document_matches_target(
+ element: &IUIAutomationElement,
+ target: HWND,
+ target_pid: u32,
+) -> bool {
+ if unsafe { element.CurrentProcessId() }.ok() != Some(target_pid as i32)
+ || !unsafe { element.CurrentControlType() }
+ .is_ok_and(|control_type| control_type.0 == UIA_DocumentControlTypeId.0)
+ || !unsafe { element.CurrentIsEnabled() }.is_ok_and(|enabled| enabled.as_bool())
+ || !unsafe { element.CurrentHasKeyboardFocus() }.is_ok_and(|focused| focused.as_bool())
+ {
+ return false;
+ }
+ let Ok(element_hwnd) = (unsafe { element.CurrentNativeWindowHandle() }) else {
+ return false;
+ };
+ !element_hwnd.0.is_null()
+ && crate::win32::windows::window_owner_pid(element_hwnd.0 as usize as u64)
+ == Some(target_pid)
+ && unsafe { GetAncestor(element_hwnd, GA_ROOT) } == target
+}
+
+fn exact_foreground_target(target: HWND, expected_pid: Option<u32>) -> bool {
+ !target.0.is_null()
+ && unsafe { IsWindow(target) }.as_bool()
+ && unsafe { GetForegroundWindow() } == target
+ && crate::win32::windows::window_owner_pid(target.0 as usize as u64)
+ .is_some_and(|pid| expected_pid.is_none_or(|expected| expected == pid))
+}
+
+fn focused_document_eligible(
+ exact_target: bool,
+ writable_value: bool,
+ value_is_empty: bool,
+ single_text_selection: bool,
+ document_matches: bool,
+) -> bool {
+ exact_target && writable_value && single_text_selection && value_is_empty && document_matches
+}
+
+fn classify_focused_document_write(
+ set_value_attempted: bool,
+ result: Result<(), &'static str>,
+) -> FocusedDocumentTypeOutcome {
+ if !set_value_attempted {
+ return FocusedDocumentTypeOutcome::NotApplicable;
+ }
+ match result {
+ Ok(()) => FocusedDocumentTypeOutcome::Confirmed,
+ Err(stage) => FocusedDocumentTypeOutcome::Unknown(stage),
+ }
+}
+
+fn normalize_document_line_endings(text: &str) -> String {
+ text.replace("\r\n", "\n").replace('\r', "\n")
+}
+
+fn normalized_text_matches(expected: &str, actual: &str) -> bool {
+ normalize_document_line_endings(expected) == normalize_document_line_endings(actual)
+}
+
+fn focused_document_worker_error(
+ error: UiaDeadlineError,
+ state: u8,
+ pending_write: bool,
+) -> FocusedDocumentTypeOutcome {
+ if pending_write {
+ return FocusedDocumentTypeOutcome::Unknown("focused UIA write is still in flight");
+ }
+ if state == 0 {
+ return FocusedDocumentTypeOutcome::NotApplicable;
+ }
+ match error {
+ UiaDeadlineError::Busy => FocusedDocumentTypeOutcome::NotApplicable,
+ UiaDeadlineError::Timeout => {
+ FocusedDocumentTypeOutcome::Unknown("focused UIA call timed out")
+ }
+ UiaDeadlineError::Unavailable => {
+ FocusedDocumentTypeOutcome::Unknown("focused UIA worker ended without a result")
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ classify_focused_document_write, focused_document_eligible, focused_document_worker_error,
+ normalize_document_line_endings, normalized_text_matches, FocusedDocumentTypeOutcome,
+ };
+ use crate::uia::windows_enum::UiaDeadlineError;
+
+ #[test]
+ fn focused_document_requires_exact_target_and_safe_value_selection() {
+ assert!(focused_document_eligible(true, true, true, true, true));
+ assert!(!focused_document_eligible(false, true, true, true, true));
+ assert!(!focused_document_eligible(true, false, true, true, true));
+ assert!(!focused_document_eligible(true, true, true, false, true));
+ assert!(!focused_document_eligible(true, true, true, true, false));
+ assert!(!focused_document_eligible(true, true, false, true, true));
+ assert!(!focused_document_eligible(true, true, false, true, false));
+ assert!(!focused_document_eligible(true, true, false, false, true));
+ assert!(!focused_document_eligible(false, true, false, true, true));
+ assert!(!focused_document_eligible(true, false, false, true, true));
+ }
+
+ #[test]
+ fn only_fully_verified_post_write_state_is_confirmed() {
+ assert_eq!(
+ classify_focused_document_write(false, Err("probe failed")),
+ FocusedDocumentTypeOutcome::NotApplicable
+ );
+ assert_eq!(
+ classify_focused_document_write(true, Err("caret failed")),
+ FocusedDocumentTypeOutcome::Unknown("caret failed")
+ );
+ assert_eq!(
+ classify_focused_document_write(true, Ok(())),
+ FocusedDocumentTypeOutcome::Confirmed
+ );
+ }
+
+ #[test]
+ fn busy_during_pending_write_disallows_native_fallback() {
+ assert!(matches!(
+ focused_document_worker_error(UiaDeadlineError::Busy, 0, true),
+ FocusedDocumentTypeOutcome::Unknown(_)
+ ));
+ assert_eq!(
+ focused_document_worker_error(UiaDeadlineError::Busy, 0, false),
+ FocusedDocumentTypeOutcome::NotApplicable
+ );
+ }
+
+ #[test]
+ fn worker_errors_before_write_allow_native_fallback() {
+ for error in [
+ UiaDeadlineError::Busy,
+ UiaDeadlineError::Timeout,
+ UiaDeadlineError::Unavailable,
+ ] {
+ assert_eq!(
+ focused_document_worker_error(error, 0, false),
+ FocusedDocumentTypeOutcome::NotApplicable
+ );
+ }
+ }
+
+ #[test]
+ fn worker_errors_after_write_never_enable_a_second_input_route() {
+ for error in [UiaDeadlineError::Timeout, UiaDeadlineError::Unavailable] {
+ assert!(matches!(
+ focused_document_worker_error(error, 1, false),
+ FocusedDocumentTypeOutcome::Unknown(_)
+ ));
+ }
+ }
+
+ #[test]
+ fn line_ending_checks_preserve_blank_lines_and_non_ascii_text() {
+ assert_eq!(
+ normalize_document_line_endings("one\r\n\r\ntwo\rthree\n"),
+ "one\n\ntwo\nthree\n"
+ );
+ assert!(normalized_text_matches(
+ "one\r\n\r\ntwo\r\u{676d}\u{5dde}\u{4e1c}",
+ "one\n\ntwo\n\u{676d}\u{5dde}\u{4e1c}"
+ ));
+ assert!(!normalized_text_matches("one\n\ntwo", "one\ntwo"));
+ }
+}
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.rs
index 04b9f0f2e1..11c6b16ad9 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
@@ -29,6 +29,7 @@ use windows::Win32::UI::Accessibility::{
};
pub mod fg_bypass;
+pub(crate) mod focused_document;
pub mod scroll;
pub mod snapshot;
pub mod windows_enum;
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.rs
index 32cc32897b..d9221d7af2 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
@@ -62,7 +62,7 @@ const SUBTREE_OP_TIMEOUT: Duration = Duration::from_secs(4);
/// Health probes can tolerate the same budget without delaying window listing.
const HEALTH_PROBE_TIMEOUT: Duration = SUBTREE_OP_TIMEOUT;
-enum UiaDeadlineError {
+pub(crate) enum UiaDeadlineError {
Timeout,
Busy,
Unavailable,
@@ -163,6 +163,22 @@ where
run_uia_single_flight(uia_single_flight(), stage, timeout, fallback, f)
}
+pub(crate) fn run_focused_document_uia<T, F>(f: F) -> Result<T, UiaDeadlineError>
+where
+ T: Send + 'static,
+ F: FnOnce(Arc<AtomicBool>) -> T + Send + 'static,
+{
+ static GATE: OnceLock<Arc<SingleFlight>> = OnceLock::new();
+ const FOCUSED_DOCUMENT_PROBE_TIMEOUT: Duration = Duration::from_millis(200);
+ run_uia_single_flight(
+ GATE.get_or_init(|| Arc::new(SingleFlight::new(Duration::ZERO))),
+ "focused document typing",
+ FOCUSED_DOCUMENT_PROBE_TIMEOUT,
+ "native typing if no write started; otherwise an unknown-effect result without retry",
+ f,
+ )
+}
+
struct ComInit {
needs_uninit: bool,
}
diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
index 60205ec695..cb4614fc22 100644
--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
@@ -891,7 +891,7 @@
"read_only": false
},
{
- "description": "Insert text into the target pid via character-by-character PostMessage(WM_CHAR) to the focused window. No focus steal.\n\nSpecial keys (Return, Escape, arrows, Tab) go through `press_key` / `hotkey` — they are not text.\n\n**Routing on Windows.** When the target's owning EXE or top-level window class identifies it as a XAML / WinUI3 / UWP host (modern Notepad, Calculator, Photos, Settings, etc.), the tool requires `element_token` and routes through UI Automation's `ValuePattern.SetValue` — same backend as the `set_value` tool. PostMessage WM_CHAR doesn't reach those hosts (their CoreInput dispatcher only consumes events from the system input queue), so the fallback path silently dropped chars. If you call `type_text(pid, text)` on a XAML host without `element_token`, the tool returns an actionable error pointing you at `get_window_state` first. Native ConsoleHost on Windows ARM64 is hard-refused because it can accept synthesized Unicode events without delivering them; use a process or PTY setup channel instead. Legacy Win32 apps still use the PostMessage path, preserving the no-focus-steal property.\n\n`delay_ms` (0–200, default 30) spaces successive characters on the PostMessage path so autocomplete and IME can keep up. Ignored on the UIA path (SetValue is atomic).",
+ "description": "Insert text into the target pid via character-by-character PostMessage(WM_CHAR) to the focused window. No focus steal.\n\nSpecial keys (Return, Escape, arrows, Tab) go through `press_key` / `hotkey` — they are not text.\n\n**Routing on Windows.** `element_token` selects a specific UIA element and writes its ValuePattern value. For no-element foreground typing, a separate capability-gated path can use the exact focused UIA Document only when it is writable and empty. Eligibility depends on control capabilities and live focus, not app names. Chromium/Electron windows keep their existing boundary because a UIA value echo does not prove that the renderer accepted the text. The path reads the value and caret back; after SetValue starts, an unverifiable result requires a fresh observation before any retry and is never replayed through native input. This replaces the full ValuePattern value, so rich-text formatting and native undo behavior are not guaranteed; single-line Edit controls keep the existing input route. For other XAML / WinUI3 / UWP cases, use `element_token` from `get_window_state`; background WM_CHAR does not reach their CoreInput dispatcher. Native ConsoleHost on Windows ARM64 is hard-refused because it can accept synthesized Unicode events without delivering them; use a process or PTY setup channel instead. Legacy Win32 apps still use the PostMessage path, preserving the no-focus-steal property.\n\n`delay_ms` (0–200, default 30) spaces successive characters on the PostMessage path so autocomplete and IME can keep up. Ignored on the UIA path (SetValue is atomic).",
"destructive": true,
"idempotent": false,
"input_schema": {