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): Windows type_text posts UTF-16 units in order and repairs dropped tails (CUA-3122) (#6341)

Francesco Bonacci290552c6374d
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rs b/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rs
index 63d8ef5e7e..021e6b7344 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/input/keyboard.rs
@@ -301,40 +301,75 @@ pub fn post_type_text_with_delay(hwnd: u64, text: &str, inter_char_ms: u64) -> R
// race with text-insertion side effects on the focus.
let h = focused_descendant(h_parent).unwrap_or(h_parent);
- let mut prev_was_cr = false;
- for ch in text.chars() {
- match ch {
- // `\r\n` (Windows-style line ending) → single Enter. The `\r`
- // does the Enter; the following `\n` is consumed silently.
- '\n' if prev_was_cr => {
- prev_was_cr = false;
- }
- '\n' | '\r' => {
+ let units = text_units(text);
+ let mut since_barrier = 0usize;
+ for unit in &units {
+ match unit {
+ // The Enter keystroke makes the target's TranslateMessage append a
+ // WM_CHAR(0x0D) to ITS queue when it dispatches the WM_KEYDOWN.
+ // Anything we post before that lands ahead of the Return and the
+ // text is reordered. Wait for the target to pump (twice, because a
+ // sent message can overtake the posted keydown) before moving on.
+ TextUnit::Return => {
unsafe {
post_enter_keystroke(h)?;
}
- prev_was_cr = ch == '\r';
- // Extra settle after Enter — paragraph creation in rich
+ wait_for_target_pump(h);
+ // Extra settle after Enter: paragraph creation in rich
// editors (VCL Writer, Scintilla, RichEdit) is heavier than
- // a single-character insert, so the baseline KEY_DELAY_MS +
- // inter_char_ms is not enough on slower hosts. The extra
- // 20 ms covers the queue drain without noticeably slowing
- // multi-line typing.
+ // a single-character insert.
sleep(Duration::from_millis(KEY_DELAY_MS + inter_char_ms + 20));
+ since_barrier = 0;
}
- _ => {
- prev_was_cr = false;
- let code = ch as u32 as usize;
+ // One UTF-16 unit per WM_CHAR. A supplementary scalar (emoji) is a
+ // high then a low surrogate; posting the scalar value in a single
+ // WM_CHAR is truncated by the target and shows up as garbage.
+ TextUnit::Packet(code) => {
unsafe {
- PostMessageW(h, WM_CHAR, WPARAM(code), LPARAM(1))?;
+ PostMessageW(h, WM_CHAR, WPARAM(*code as usize), LPARAM(1))?;
}
+ since_barrier += 1;
sleep(Duration::from_millis(KEY_DELAY_MS + inter_char_ms));
+ // Bound the target's backlog so the read-back after the call
+ // sees a settled field, and so a hung target aborts the call.
+ if since_barrier >= POST_CHUNK_UNITS {
+ wait_for_target_pump(h);
+ since_barrier = 0;
+ }
}
}
}
+ wait_for_target_pump(h);
Ok(())
}
+/// Posted characters between two pump barriers.
+const POST_CHUNK_UNITS: usize = 32;
+
+/// Round-trip `WM_NULL` to `h`'s thread twice. Sent messages are serviced
+/// whenever the target's message loop next retrieves a message, so this
+/// returns once the target has gone around its loop after everything posted
+/// so far. Bounded and best effort: a hung target just times out.
+fn wait_for_target_pump(h: HWND) {
+ use windows::Win32::UI::WindowsAndMessaging::{
+ SendMessageTimeoutW, SMTO_ABORTIFHUNG, SMTO_BLOCK, WM_NULL,
+ };
+ for _ in 0..2 {
+ let mut out = 0usize;
+ let _ = unsafe {
+ SendMessageTimeoutW(
+ h,
+ WM_NULL,
+ WPARAM(0),
+ LPARAM(0),
+ SMTO_ABORTIFHUNG | SMTO_BLOCK,
+ 250,
+ Some(&mut out),
+ )
+ };
+ }
+}
+
/// Press a named key (and optional modifiers) via WM_KEYDOWN/WM_KEYUP.
pub fn post_key(hwnd: u64, key: &str, modifiers: &[&str]) -> Result<()> {
if let Some(msg) = crate::input::post_message_blocked_by_uipi(hwnd) {
@@ -1153,3 +1188,31 @@ mod text_unit_tests {
}
}
}
+
+#[cfg(test)]
+mod post_text_unit_tests {
+ use super::*;
+
+ fn packets(text: &str) -> Vec<Option<u16>> {
+ text_units(text)
+ .into_iter()
+ .map(|u| match u {
+ TextUnit::Packet(c) => Some(c),
+ TextUnit::Return => None,
+ })
+ .collect()
+ }
+
+ #[test]
+ fn supplementary_scalar_is_two_surrogate_units() {
+ assert_eq!(packets("\u{1F600}"), vec![Some(0xD83D), Some(0xDE00)]);
+ }
+
+ #[test]
+ fn crlf_is_one_return_and_symbols_survive() {
+ assert_eq!(
+ packets("a\r\nb\n~é"),
+ vec![Some(97), None, Some(98), None, Some(126), Some(0xE9)]
+ );
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/type_text.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/type_text.rs
index 6bf63fecf7..e1190b103e 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/type_text.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/type_text.rs
@@ -199,7 +199,7 @@ impl Tool for TypeTextTool {
)),
_ => None,
};
- let _delay_ms = args.u64_or("delay_ms", 30);
+ let _delay_ms = args.u64_or("delay_ms", 30).min(200);
let hwnd = match hwnd_opt {
Some(h) => h,
None => {
@@ -543,6 +543,7 @@ impl Tool for TypeTextTool {
let text_for_post = text.clone();
let verify_pid = pid;
let verify_idx = elem_idx.map(|i| i as usize);
+ let delay_ms = _delay_ms;
let result = tokio::task::spawn_blocking({
let admitted = admitted.clone();
move || {
@@ -556,9 +557,32 @@ impl Tool for TypeTextTool {
None => read_focused_value_uia(verify_pid),
};
let before = read(verify_idx);
- let post_res = crate::input::post_type_text(hwnd, &text_for_post);
+ let mut post_res =
+ crate::input::post_type_text_with_delay(hwnd, &text_for_post, delay_ms);
std::thread::sleep(std::time::Duration::from_millis(40));
- let after = read(verify_idx);
+ let mut after = read(verify_idx);
+ // Read the field back, wait for it to settle, and retype only
+ // the tail the target dropped. Bounded; never retypes unless a
+ // non-empty strict prefix of the text is proven to be there.
+ for _ in 0..MAX_TAIL_RETRIES {
+ if post_res.is_err() {
+ break;
+ }
+ let settled = settle_value(|| read(verify_idx), after.clone());
+ after = settled;
+ let (Some(b), Some(a)) = (before.as_deref(), after.as_deref()) else {
+ break;
+ };
+ match plan_tail_retry(b, a, &text_for_post) {
+ TailPlan::Retype(tail) => {
+ post_res =
+ crate::input::post_type_text_with_delay(hwnd, &tail, delay_ms);
+ std::thread::sleep(std::time::Duration::from_millis(40));
+ after = read(verify_idx);
+ }
+ TailPlan::Done => break,
+ }
+ }
let observed = post_message_readback_observed(
before.as_deref(),
after.as_deref(),
@@ -739,6 +763,95 @@ mod focused_document_result_tests {
}
}
+const MAX_TAIL_RETRIES: usize = 2;
+
+#[derive(Debug, PartialEq, Eq)]
+enum TailPlan {
+ /// Nothing provable to repair (complete, nothing landed, or garbled).
+ Done,
+ /// The target dropped the end of the text; type exactly this tail.
+ Retype(String),
+}
+
+fn normalize_newlines(s: &str) -> String {
+ s.chars().filter(|c| *c != '\r').collect()
+}
+
+/// The text `after` has that `before` did not: strip the common prefix and
+/// suffix of the two values. Newlines are normalized (Edit controls store
+/// Enter as CRLF).
+fn inserted_segment(before: &str, after: &str) -> String {
+ let b: Vec<char> = normalize_newlines(before).chars().collect();
+ let a: Vec<char> = normalize_newlines(after).chars().collect();
+ let p = b.iter().zip(a.iter()).take_while(|(x, y)| x == y).count();
+ let s = b[p..]
+ .iter()
+ .rev()
+ .zip(a[p..].iter().rev())
+ .take_while(|(x, y)| x == y)
+ .count();
+ a[p..a.len() - s].iter().collect()
+}
+
+/// Decide whether a typing diff can be repaired by retyping a tail. Only a
+/// non-empty strict prefix of the requested text counts: an empty insert means
+/// the target ignores WM_CHAR (retrying cannot help), and a non-prefix insert
+/// is reordered or garbled (retyping would make it worse).
+fn plan_tail_retry(before: &str, after: &str, requested: &str) -> TailPlan {
+ let want = normalize_newlines(requested);
+ let got = inserted_segment(before, after);
+ if got.is_empty() || got.len() >= want.len() || !want.starts_with(&got) {
+ return TailPlan::Done;
+ }
+ TailPlan::Retype(want[got.len()..].to_string())
+}
+
+/// Poll `read` until two consecutive reads agree (or ~600 ms pass), so the
+/// diff is taken after the target has drained its queue.
+fn settle_value(read: impl Fn() -> Option<String>, mut last: Option<String>) -> Option<String> {
+ for _ in 0..20 {
+ std::thread::sleep(std::time::Duration::from_millis(30));
+ let now = read();
+ if now == last {
+ return now;
+ }
+ last = now;
+ }
+ last
+}
+
+#[cfg(test)]
+mod tail_retry_tests {
+ use super::*;
+
+ #[test]
+ fn complete_insert_needs_no_retry() {
+ assert_eq!(plan_tail_retry("ab", "abXY\r\nZ", "XY\nZ"), TailPlan::Done);
+ }
+
+ #[test]
+ fn dropped_tail_is_retyped() {
+ assert_eq!(
+ plan_tail_retry("", "hello wo", "hello world!"),
+ TailPlan::Retype("rld!".into())
+ );
+ }
+
+ #[test]
+ fn insert_in_the_middle_is_diffed() {
+ assert_eq!(
+ plan_tail_retry("ad", "abcd", "bcXY"),
+ TailPlan::Retype("XY".into())
+ );
+ }
+
+ #[test]
+ fn nothing_landed_or_garbled_is_not_retyped() {
+ assert_eq!(plan_tail_retry("x", "x", "abc"), TailPlan::Done);
+ assert_eq!(plan_tail_retry("", "acb", "abc"), TailPlan::Done);
+ }
+}
+
fn post_message_readback_observed(
before: Option<&str>,
after: Option<&str>,