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
fix(cua-driver): restore the Windows foreground only after typed input drained (#6779)
injaneity886c9ce30e02
diff --git a/libs/cua-driver/rust/crates/platform-windows/models/windows_typing.cfg b/libs/cua-driver/rust/crates/platform-windows/models/windows_typing.cfgnew file mode 100644index 0000000000..1cfe7a50cb--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/models/windows_typing.cfg@@ -0,0 +1,5 @@+\* SPDX-License-Identifier: MIT+SPECIFICATION Spec+CONSTANTS N = 3+ RestoreRule = "drained"+INVARIANTS TypeOK NoLateKeystroke NoSteal GivesWindowBackdiff --git a/libs/cua-driver/rust/crates/platform-windows/models/windows_typing.tla b/libs/cua-driver/rust/crates/platform-windows/models/windows_typing.tlanew file mode 100644index 0000000000..81c19feba3--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/models/windows_typing.tla@@ -0,0 +1,94 @@+\* SPDX-License-Identifier: MIT+\* Copyright (c) 2026 Cua AI, Inc.+---- MODULE windows_typing ----+\* One foreground input turn on Windows: with_confirmed_foreground in+\* src/input/keyboard.rs, after the target has been confirmed in front and the+\* input queue attached. src/typing_turn.rs holds the restore rule.+\* Windows: U (the user's window, foreground before the turn), T (the target),+\* O (any other window, such as a popup that takes the foreground).+\*+\* Assumption (#4477, #4500): input the target thread has not read yet is read+\* by whichever window is foreground when it is read, so a restore that runs+\* before the read hands the unread input to U.+\*+\* The unattached fallback (no queue attachment, 40 ms settle) has no read+\* signal and is not modelled.+\*+\* Check with TLC (tla2tools.jar):+\* java -cp tla2tools.jar tlc2.TLC -config windows_typing.cfg windows_typing.tla+\* the rule in typing_turn.rs: every invariant holds+\* java -cp tla2tools.jar tlc2.TLC -config windows_typing_always.cfg windows_typing.tla+\* the old rule (restore on every exit): NoLateKeystroke fails on a stall+EXTENDS Naturals+CONSTANTS N, \* events the turn will insert+ RestoreRule \* "always" (old) or "drained" (typing_turn.rs)+VARIABLES front, \* "U", "T" or "O"+ sent, \* events inserted so far+ pending, \* inserted events the target thread has not read+ reader, \* the target's input thread: "live" or "hung"+ turn, \* "sending", then how it ended: "drained", "notsent", "undrained" or "lost"+ done, \* the restore decision ran+ userGot, \* U read input the driver meant for T+ stolen \* the restore took the foreground from O+vars == <<front, sent, pending, reader, turn, done, userGot, stolen>>++Init == /\ front = "T" /\ sent = 0 /\ pending = 0 /\ reader = "live"+ /\ turn = "sending" /\ done = FALSE /\ userGot = FALSE /\ stolen = FALSE++\* SendInput of b events. Text sends one unit (b = 1) after checking the+\* foreground; a key chord sends all of its events at once (b = N).+Send(b) == /\ turn = "sending" /\ front = "T" /\ pending = 0 /\ sent + b <= N+ /\ sent' = sent + b /\ pending' = b+ /\ UNCHANGED <<front, reader, turn, done, userGot, stolen>>+\* SendInput inserts fewer events than asked (UIPI, secure desktop).+Short == /\ turn = "sending" /\ front = "T" /\ pending = 0 /\ sent < N+ /\ sent' = sent + 1 /\ pending' = 1 /\ turn' = "undrained"+ /\ UNCHANGED <<front, reader, done, userGot, stolen>>+\* SendInput inserts nothing, so nothing is pending.+ShortNone == /\ turn = "sending" /\ front = "T" /\ pending = 0 /\ turn' = "notsent"+ /\ UNCHANGED <<front, sent, pending, reader, done, userGot, stolen>>+\* A 2 s read wait (per text unit, or the final drain) runs out.+Timeout == /\ turn = "sending" /\ pending > 0 /\ turn' = "undrained"+ /\ UNCHANGED <<front, sent, pending, reader, done, userGot, stolen>>+\* The final drain sees every inserted event read.+Drained == /\ turn = "sending" /\ pending = 0 /\ sent = N /\ turn' = "drained"+ /\ UNCHANGED <<front, sent, pending, reader, done, userGot, stolen>>+\* foreground_lost: before the next text unit, the foreground is not the target.+Lost == /\ turn = "sending" /\ pending = 0 /\ 0 < sent /\ sent < N /\ front # "T"+ /\ turn' = "lost"+ /\ UNCHANGED <<front, sent, pending, reader, done, userGot, stolen>>+\* The target's input thread reads one event in whichever window is in front.+Read == /\ pending > 0 /\ reader = "live"+ /\ pending' = pending - 1 /\ userGot' = (userGot \/ front = "U")+ /\ UNCHANGED <<front, sent, reader, turn, done, stolen>>+Hang == reader = "live" /\ reader' = "hung"+ /\ UNCHANGED <<front, sent, pending, turn, done, userGot, stolen>>+Wake == reader = "hung" /\ reader' = "live"+ /\ UNCHANGED <<front, sent, pending, turn, done, userGot, stolen>>+OtherTakesFront == /\ ~done /\ front = "T" /\ front' = "O"+ /\ UNCHANGED <<sent, pending, reader, turn, done, userGot, stolen>>++Restores == IF RestoreRule = "always" THEN TRUE ELSE turn \in {"drained", "notsent"}+Finish == /\ turn # "sending" /\ ~done /\ done' = TRUE+ /\ front' = IF Restores THEN "U" ELSE front+ /\ stolen' = (Restores /\ front = "O")+ /\ UNCHANGED <<sent, pending, reader, turn, userGot>>+Idle == done /\ UNCHANGED vars++Next == \/ \E b \in 1..N : Send(b)+ \/ Short \/ ShortNone \/ Timeout \/ Drained \/ Lost \/ Read \/ Hang \/ Wake+ \/ OtherTakesFront \/ Finish \/ Idle+Spec == Init /\ [][Next]_vars++TypeOK == /\ front \in {"U", "T", "O"} /\ sent \in 0..N /\ pending \in 0..N+ /\ reader \in {"live", "hung"} /\ done \in BOOLEAN+ /\ turn \in {"sending", "drained", "notsent", "undrained", "lost"}+\* A keystroke meant for the target never lands in the user's window.+NoLateKeystroke == ~userGot+\* After foreground_lost the driver does not take the foreground back from the+\* window that took it. A window that takes it after the last read check is+\* not observed, and the restore still runs, as before.+NoSteal == ~(stolen /\ turn = "lost")+\* A turn with nothing left unread gives the user's window back.+GivesWindowBack == (done /\ turn \in {"drained", "notsent"}) => front = "U"+====diff --git a/libs/cua-driver/rust/crates/platform-windows/models/windows_typing_always.cfg b/libs/cua-driver/rust/crates/platform-windows/models/windows_typing_always.cfgnew file mode 100644index 0000000000..30a34e98f0--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/models/windows_typing_always.cfg@@ -0,0 +1,5 @@+\* SPDX-License-Identifier: MIT+SPECIFICATION Spec+CONSTANTS N = 3+ RestoreRule = "always"+INVARIANTS TypeOK NoLateKeystrokediff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rsindex 8f880edda7..8f90ba869c 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs@@ -297,12 +297,19 @@ unsafe fn invoke(element_ptr: usize, description: &str) -> Result<(), BrowserRef})}+fn input_may_be_unread(error: &anyhow::Error) -> bool {+ error+ .downcast_ref::<crate::typing_turn::ForegroundNotRestored>()+ .is_some()+}+fn confirm_setup_navigation(hwnd: u64,element_ptr: usize,foregrounded_window: &mut bool,injected_global_input: &mut bool,focused_setup_address_field: &mut bool,+ input_may_be_unread: &mut bool,) -> Result<(), BrowserRefusal> {use windows::Win32::Foundation::HWND;use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow;@@ -345,6 +352,7 @@ fn confirm_setup_navigation(*injected_global_input = true;crate::input::keyboard::send_key_synthesized(hwnd, "enter", &[]).map_err(|error| {+ *input_may_be_unread = self::input_may_be_unread(&error);BrowserRefusal::new(BrowserRefusalCode::BrowserWrongTargetRefused,format!("could not confirm the bounded setup navigation: {error}"),@@ -352,7 +360,8 @@ fn confirm_setup_navigation(})})();- let restored = if prior.0.is_null() || prior == target {+ // An unread Enter must not follow the user back to their window.+ let restored = if prior.0.is_null() || prior == target || *input_may_be_unread {true} else {let (restored, injected) = force_setup_foreground(prior);@@ -418,6 +427,9 @@ pub struct SetupUiHandle {pub focused_setup_address_field: bool,pub foregrounded_window: bool,pub injected_global_input: bool,+ /// A setup key was inserted but not confirmed read; cleanup sends no more+ /// input, so a late Enter or Ctrl+W cannot combine with another one.+ input_may_be_unread: bool,enable_attempted: bool,}@@ -448,7 +460,8 @@ impl SetupUiHandle {let focused_setup_address_field = self.focused_setup_address_field;let foregrounded_window = self.foregrounded_window;let injected_global_input = self.injected_global_input;- let closed_setup_page = self.close().unwrap_or(false);+ let closed_setup_page = self.close_setup_page().unwrap_or(false);+ let input_may_be_unread = self.input_may_be_unread;let mut error = error;let cause = error.detail.take();error.with_detail(serde_json::json!({@@ -459,6 +472,7 @@ impl SetupUiHandle {"enabled_remote_debugging": enabled_remote_debugging,"foregrounded_window": foregrounded_window,"injected_global_input": injected_global_input,+ "input_may_be_unread": input_may_be_unread,"restored_remote_debugging": restored_remote_debugging,},"cause": cause,@@ -483,6 +497,7 @@ impl SetupUiHandle {}if let Err(error) = crate::input::keyboard::send_key_synthesized(self.hwnd, "w", &["ctrl"]){+ self.input_may_be_unread |= input_may_be_unread(&error);let error = BrowserRefusal::new(BrowserRefusalCode::BrowserWrongTargetRefused,format!("could not close the exact temporary setup tab: {error}"),@@ -493,19 +508,30 @@ impl SetupUiHandle {Ok(Some(true))}- pub fn close(self) -> Option<bool> {+ pub fn close(mut self) -> Option<bool> {+ self.close_setup_page()+ }++ fn close_setup_page(&mut self) -> Option<bool> {if !self.opened_setup_page {return None;}+ if self.input_may_be_unread {+ return Some(false);+ }let proven = native_nodes(self.hwnd).is_ok_and(|nodes| {let proven = setup_page_proven(&nodes, self.descriptor);release_nodes(&nodes);proven});- Some(- proven- && crate::input::keyboard::send_key_synthesized(self.hwnd, "w", &["ctrl"]).is_ok(),- )+ if !proven {+ return Some(false);+ }+ let sent = crate::input::keyboard::send_key_synthesized(self.hwnd, "w", &["ctrl"]);+ if let Err(error) = &sent {+ self.input_may_be_unread |= input_may_be_unread(error);+ }+ Some(sent.is_ok())}}@@ -577,6 +603,7 @@ fn set_remote_debugging(focused_setup_address_field: false,foregrounded_window: false,injected_global_input: false,+ input_may_be_unread: false,enable_attempted: false,},Ok(None) => {@@ -591,6 +618,7 @@ fn set_remote_debugging(focused_setup_address_field: false,foregrounded_window: false,injected_global_input: false,+ input_may_be_unread: false,enable_attempted: false,};let tab_tree = match native_nodes(hwnd) {@@ -695,6 +723,7 @@ fn set_remote_debugging(&mut handle.foregrounded_window,&mut handle.injected_global_input,&mut handle.focused_setup_address_field,+ &mut handle.input_may_be_unread,) {release_nodes(&created);return Err(handle.abort(error));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.rsindex 021e6b7344..88c4dbbefa 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@@ -34,6 +34,7 @@ use windows::Win32::UI::WindowsAndMessaging::{};use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, SetForegroundWindow};+use crate::typing_turn::{restores_previous, ForegroundNotRestored, TypingTurn};use crate::win32::{foreground_matches_target_or_owned_window, windows::ForegroundTarget};// ── XAML / UWP host detection ────────────────────────────────────────────────@@ -515,8 +516,11 @@ pub fn send_key_synthesized_after_focus(events.push(key_input(*mvk, true));}- with_confirmed_foreground(target, "key delivery", focus, |_, _| unsafe {+ with_confirmed_foreground(target, "key delivery", focus, |_, _, turn| unsafe {let sent = SendInput(&events, std::mem::size_of::<INPUT>() as i32);+ if sent > 0 {+ *turn = TypingTurn::Undrained;+ }if sent as usize != events.len() {bail!("SendInput inserted only {sent} of {} events. Windows blocked the \@@ -573,11 +577,12 @@ pub fn send_text_synthesized_after_focus(}let n = units.len();- with_confirmed_foreground(target, "text delivery", focus, |att, ft| unsafe {+ with_confirmed_foreground(target, "text delivery", focus, |att, ft, turn| unsafe {if let Some(att) = att {for (k, unit) in units.iter().enumerate() {let actual = GetForegroundWindow();if !foreground_matches_target_or_owned_window(ft, actual.0 as usize as u64) {+ *turn = TypingTurn::Lost;bail!("foreground_lost: foreground moved to HWND {h:?} after {k} of {n} \text units were read; the remaining {remaining} were not sent. \@@ -586,7 +591,13 @@ pub fn send_text_synthesized_after_focus(remaining = n - k,);}- match att.send_and_await_read(&unit_events(unit), Duration::from_secs(2)) {+ let read = att.send_and_await_read(&unit_events(unit), Duration::from_secs(2));+ *turn = match read {+ UnitRead::Read => TypingTurn::Drained,+ UnitRead::Short(0) => *turn,+ UnitRead::Short(_) | UnitRead::Stalled => TypingTurn::Undrained,+ };+ match read {UnitRead::Read => {}UnitRead::Short(sent) => bail!("SendInput inserted only {sent} of 4 key events for text unit {} of {n} \@@ -599,8 +610,8 @@ pub fn send_text_synthesized_after_focus(UnitRead::Stalled => bail!("text_delivery_stalled: the target did not read text unit {} of {n} \within 2000 ms; {k} earlier units were read. Unit {} was inserted \- and may still appear, possibly in the previously foreground window. \- Nothing was retried; inspect the target before sending the rest.",+ and may still appear in the target. Nothing was retried; inspect \+ the target before sending the rest.",k + 1,k + 1),@@ -613,6 +624,9 @@ pub fn send_text_synthesized_after_focus(events.extend_from_slice(&unit_events(unit)[..2]);}let sent = SendInput(&events, std::mem::size_of::<INPUT>() as i32);+ if sent > 0 {+ *turn = TypingTurn::Undrained;+ }if sent as usize != events.len() {bail!("SendInput inserted only {sent} of {} key events. Windows blocked \@@ -644,13 +658,14 @@ fn wait_for_exact_foreground(target: HWND, timeout: Duration) -> bool {/// same-process window whose owner chain reaches `target`, is foreground./// Foreground and optional child focus are checked against/// external Win32/UIA state instead of inferred from API return values or a-/// fixed settle delay. The prior foreground is restored on every body/focus-/// result after activation succeeds.+/// fixed settle delay. The body records in `turn` what it inserted; the prior+/// foreground is restored only as [`restores_previous`] allows, and a failed+/// turn that keeps it returns [`ForegroundNotRestored`].fn with_confirmed_foreground<T>(target: HWND,operation: &str,focus: impl FnOnce() -> Result<()>,- body: impl FnOnce(Option<&InputQueueAttachment>, ForegroundTarget) -> Result<T>,+ body: impl FnOnce(Option<&InputQueueAttachment>, ForegroundTarget, &mut TypingTurn) -> Result<T>,) -> Result<T> {let previous = unsafe { GetForegroundWindow() };let _ = unsafe { crate::input::force_foreground_assisted(target) };@@ -682,7 +697,8 @@ fn with_confirmed_foreground<T>(};let mut attachment: Option<InputQueueAttachment> = None;- let result = (|| {+ let mut turn = TypingTurn::NotSent;+ let mut result = (|| {focus()?;let deadline = Instant::now() + Duration::from_millis(250);let actual = loop {@@ -710,19 +726,37 @@ fn with_confirmed_foreground<T>(// Attach before inserting anything: attaching resets the shared key// state, which must not race with modifiers the body is about to send.attachment = InputQueueAttachment::attach(actual);- body(attachment.as_ref(), foreground_target)+ body(attachment.as_ref(), foreground_target, &mut turn)})();// Keep the target foreground until its thread has read every inserted// event; restoring earlier hands the unread tail to another window (#4477).- match (&result, attachment.as_ref()) {- (Ok(_), Some(attachment)) => {- attachment.wait_for_drain(Duration::from_secs(2));- }- (Ok(_), None) => sleep(Duration::from_millis(40)),- _ => {}+ // Paced text already saw each unit read, so it skips the final drain.+ if result.is_ok() && turn != TypingTurn::Drained {+ turn = match attachment.as_ref() {+ Some(attachment) if attachment.wait_for_drain(Duration::from_secs(2)) => {+ TypingTurn::Drained+ }+ Some(_) => {+ result = Err(anyhow::anyhow!(+ "input_delivery_stalled: Windows did not confirm that the target read the \+ {operation} input within 2000 ms. It was inserted and may still appear in \+ the target. Nothing was retried; inspect the target before repeating it."+ ));+ TypingTurn::Undrained+ }+ None => {+ sleep(Duration::from_millis(40));+ TypingTurn::Settled+ }+ };}drop(attachment);+ if !restores_previous(turn) {+ // Marked even when the target was already in front: a caller that+ // fronted it (browser setup) must not restore its own prior window.+ return result.map_err(|error| ForegroundNotRestored { error, turn }.into());+ }if !previous.0.is_null() && previous != target {let _ = unsafe { SetForegroundWindow(previous) };}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs b/libs/cua-driver/rust/crates/platform-windows/src/lib.rsindex bab5949d38..75c8d8490e 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs@@ -76,6 +76,10 @@ pub fn install_pointer_shape_backend() -> bool {#[cfg(any(target_os = "windows", test))]mod process_selection;+// Pure restore rule for foreground input turns; runs its table test on any host.+#[cfg(any(target_os = "windows", test))]+mod typing_turn;+#[cfg(target_os = "windows")]pub mod win32;diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/hotkey.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/hotkey.rsindex 9636a52c48..d1eb3c7d99 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/hotkey.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/hotkey.rs@@ -132,7 +132,7 @@ impl Tool for HotkeyTool {"scope": "desktop", "path": "SendInput", "keys": full_keys,"effect": "unverifiable"})),- Ok(Err(error)) => ToolResult::error(error.to_string()),+ Ok(Err(error)) => crate::typing_turn::foreground_input_error(error),Err(error) => ToolResult::error(format!("desktop hotkey task failed: {error}")),};}@@ -394,7 +394,7 @@ impl Tool for HotkeyTool {"✅ Pressed {key_display} on pid {raw_pid} via {path} \(Win32 target).")),- Ok(Err(e)) => ToolResult::error(e.to_string()),+ Ok(Err(e)) => crate::typing_turn::foreground_input_error(e),Err(e) => ToolResult::error(format!("Task error: {e}")),}}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/press_key.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/press_key.rsindex 262cbafab5..c7b5fd12e7 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/press_key.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/press_key.rs@@ -95,7 +95,7 @@ impl Tool for PressKeyTool {"scope": "desktop", "path": "SendInput", "key": key_display,"effect": "unverifiable"})),- Ok(Err(error)) => ToolResult::error(error.to_string()),+ Ok(Err(error)) => crate::typing_turn::foreground_input_error(error),Err(error) => ToolResult::error(format!("desktop key task failed: {error}")),};}@@ -312,7 +312,7 @@ impl Tool for PressKeyTool {Ok(Ok(())) => ToolResult::text(format!("✅ Sent {key_display} via SendInput on pid {raw_pid} (delivery_mode:foreground).")),- Ok(Err(e)) => ToolResult::error(e.to_string()),+ Ok(Err(e)) => crate::typing_turn::foreground_input_error(e),Err(e) => ToolResult::error(format!("Task error: {e}")),};}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.rsindex e1190b103e..0c8ebed77a 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@@ -121,7 +121,7 @@ impl Tool for TypeTextTool {"scope": "desktop", "path": "SendInput", "characters": text_len,"effect": "unverifiable"})),- Ok(Err(error)) => ToolResult::error(error.to_string()),+ Ok(Err(error)) => crate::typing_turn::foreground_input_error(error),Err(error) => ToolResult::error(format!("desktop type task failed: {error}")),};}@@ -345,7 +345,7 @@ impl Tool for TypeTextTool {// foreground IS the escalated rung (mirrors macOS PATH_KEY_EVENTS_FG)."effect": "unverifiable",})),- Ok(Err(e)) => ToolResult::error(e.to_string()),+ Ok(Err(e)) => crate::typing_turn::foreground_input_error(e),Err(e) => ToolResult::error(format!("Task error: {e}")),};}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/typing_turn.rs b/libs/cua-driver/rust/crates/platform-windows/src/typing_turn.rsnew file mode 100644index 0000000000..194014d4d9--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/typing_turn.rs@@ -0,0 +1,130 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 Cua AI, Inc.++//! When one foreground input turn may give the user's window back.+//!+//! Input the target thread has not read yet is read by whichever window is+//! foreground at that moment (#4477), so restoring the previous window early+//! hands it the unread tail. A late keystroke in the user's window cannot be+//! undone; a target left in front costs one click. The rule is modelled in+//! `models/windows_typing.tla`. Pure, so the table test runs on every host.++/// How a foreground input turn ended, by what is known about inserted input.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum TypingTurn {+ /// Nothing was inserted.+ NotSent,+ /// The target thread read every inserted event.+ Drained,+ /// Inserted without a queue attachment, so the read cannot be observed;+ /// a short fixed settle stands in for the drain.+ Settled,+ /// Inserted events may still be unread: a stalled unit, a short+ /// `SendInput`, or a final drain that timed out.+ Undrained,+ /// Another window took the foreground between text units.+ Lost,+}++/// Whether to give the previous foreground back. Never while inserted input+/// may be unread, and never from a window that took the foreground itself.+pub(crate) fn restores_previous(turn: TypingTurn) -> bool {+ match turn {+ TypingTurn::NotSent | TypingTurn::Drained | TypingTurn::Settled => true,+ TypingTurn::Undrained | TypingTurn::Lost => false,+ }+}++/// A failed turn that did not give the previous foreground back. Callers+/// report `foreground_restored: false`.+#[derive(Debug, thiserror::Error)]+#[error("{error} Focus was not restored: {}", reason(*.turn))]+pub(crate) struct ForegroundNotRestored {+ pub(crate) error: anyhow::Error,+ pub(crate) turn: TypingTurn,+}++fn reason(turn: TypingTurn) -> &'static str {+ if turn == TypingTurn::Lost {+ "another window took the foreground during the call, and the driver does not take \+ it back."+ } else {+ "the target window stays in front so input it has not read yet cannot reach the \+ previously foreground window. Bring that window back once the target settles."+ }+}++/// The tool result for a failed foreground input call.+pub(crate) fn foreground_input_error(+ error: anyhow::Error,+) -> cua_driver_core::protocol::ToolResult {+ let kept = error.downcast_ref::<ForegroundNotRestored>().is_some();+ let result = cua_driver_core::protocol::ToolResult::error(error.to_string());+ if kept {+ result.with_structured(serde_json::json!({ "foreground_restored": false }))+ } else {+ result+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use TypingTurn::*;++ const RESTORE: bool = true;+ const LEAVE: bool = false;++ /// One row per exit of `with_confirmed_foreground` once the target is+ /// confirmed in front: the turn the exit produces and the expected outcome.+ #[test]+ fn each_exit_restores_or_leaves_the_target_in_front() {+ #[rustfmt::skip]+ let rows: &[(&str, TypingTurn, bool)] = &[+ ("focus step or owned-window check fails", NotSent, RESTORE),+ ("SendInput inserted nothing", NotSent, RESTORE),+ ("foreground_lost before a text unit", Lost, LEAVE),+ ("text unit SendInput short", Undrained, LEAVE),+ ("text_delivery_stalled", Undrained, LEAVE),+ ("key chord SendInput short", Undrained, LEAVE),+ ("unpaced text SendInput short", Undrained, LEAVE),+ ("final drain timed out", Undrained, LEAVE),+ ("every text unit read", Drained, RESTORE),+ ("final drain read the sentinel", Drained, RESTORE),+ ("no attachment, settle elapsed", Settled, RESTORE),+ ];+ for &(exit, turn, expected) in rows {+ assert_eq!(restores_previous(turn), expected, "{exit}");+ }+ }++ #[test]+ fn an_unrestored_turn_says_so_in_text_and_structure() {+ let stalled = anyhow::anyhow!("text_delivery_stalled: unit 3 of 5 was not read.");+ let result = foreground_input_error(+ ForegroundNotRestored {+ error: stalled,+ turn: Undrained,+ }+ .into(),+ );+ let text = serde_json::to_value(&result.content).unwrap().to_string();+ assert!(+ text.contains("text_delivery_stalled: unit 3 of 5"),+ "{text}"+ );+ assert!(+ text.contains("Focus was not restored: the target window stays in front"),+ "{text}"+ );+ assert_eq!(result.is_error, Some(true));+ assert_eq!(+ result.structured_content,+ Some(serde_json::json!({ "foreground_restored": false }))+ );++ let refused = foreground_input_error(anyhow::anyhow!("foreground_unavailable: no input"));+ assert_eq!(refused.is_error, Some(true));+ assert_eq!(refused.structured_content, None);+ }+}