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.

perf(cua-driver): return quiet actions after 300 ms instead of the full 1 s window watch (#4915)

Francesco Bonaccifb83f9848cd5
diff --git a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
index a00eba98be..428d32cbab 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
@@ -204,8 +204,13 @@ daemon child.
After an input action, the driver watches the window list for a short time so
it can report a menu, dialog, or new window that the action opened. On macOS,
-that watch lasts up to 1000 ms for an action that opens nothing, which makes it
-the largest part of a background click's latency. A host that already observes
+the watch lasts up to 1000 ms. The action's result waits for at most the first
+300 ms of it; when nothing has changed by then, the result returns and the rest
+of the watch runs detached, still holding the focus-steal lease. A window that
+opens during that remainder is reported on the next action's result as
+`After the previous action returned, it opened new window(s): …`. The next
+action, or any activation the driver performs, ends the detached remainder
+first. On Linux X11 the result waits for the whole watch. A host that already observes
its target continuously can shorten it through two variables set at trusted
launch, in the environment of the `serve --embedded` child (or of the host
process when you use the same-process runtime). `EmbeddedCuaDriverHost` starts
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs
index 9af669f438..8c9d098be6 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs
@@ -972,6 +972,7 @@ pub fn frontmost_pid() -> Option<i32> {
/// Used as the belt-and-braces step in `LaunchAppTool` when the target
/// has self-activated despite the focus-steal observer.
pub fn activate_pid(pid: i32) -> bool {
+ crate::window_change_detector::end_tail();
use objc2_app_kit::{NSApplicationActivationOptions, NSRunningApplication};
unsafe {
match NSRunningApplication::runningApplicationWithProcessIdentifier(pid) {
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs
index 4f36d47afd..452d8dc77e 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs
@@ -508,6 +508,7 @@ impl SpaceQuery {
///
/// Returns `true` when all SPIs resolved and both posts succeeded.
pub fn activate_without_raise(target_pid: pid_t, target_wid: u32) -> bool {
+ crate::window_change_detector::end_tail();
let post_fn = match post_event_record_to_fn() {
Some(f) => f,
None => return false,
@@ -764,6 +765,9 @@ impl Drop for ForegroundTurn {
}
fn foreground_turn() -> ForegroundTurn {
+ // An intentional activation ends the previous action's detached window
+ // watch, whose wildcard lease would otherwise revert it.
+ crate::window_change_detector::end_tail();
if HOLDS_FOREGROUND_LOCK.with(std::cell::Cell::get) {
return ForegroundTurn { _guard: None };
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs
index db0770bcd4..b1ad983a95 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs
@@ -365,6 +365,7 @@ impl Tool for BringToFrontTool {
}
async fn invoke(&self, args: Value) -> ToolResult {
+ crate::window_change_detector::end_tail();
let pid = match args.get("pid").and_then(Value::as_i64) {
Some(p) => match libc::pid_t::try_from(p) {
Ok(pid) => pid,
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs
index 52b59c5df4..4bb7ab33f7 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs
@@ -775,6 +775,7 @@ impl Tool for ClickTool {
.await;
// Drop the wildcard lease + detect window/foreground side-effects.
+ let acted_at = std::time::Instant::now();
let changes = super::finish_window_observation(snapshot).await;
match result {
@@ -790,8 +791,11 @@ impl Tool for ClickTool {
))) => {
// For text inputs, wait 800ms for WebKit DOM focus to settle
// before returning — matches the Swift reference behaviour.
+ // The window watch above already used part of it.
if needs_webkit_delay {
- tokio::time::sleep(std::time::Duration::from_millis(800)).await;
+ let settle = std::time::Duration::from_millis(800)
+ .saturating_sub(acted_at.elapsed());
+ tokio::time::sleep(settle).await;
}
msg.push_str(&changes.result_suffix());
// AX dispatch went through, but AXPerformAction returning
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs
index a493497ab3..0f0574ce30 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs
@@ -87,6 +87,7 @@ impl Tool for LaunchAppTool {
async fn invoke(&self, args: Value) -> ToolResult {
use cua_driver_core::tool_args::ArgsExt;
+ crate::window_change_detector::end_tail();
let bundle_id = args.opt_str("bundle_id");
let name = args.opt_str("name");
let mut response_bundle_id = bundle_id.clone();
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs b/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs
index 551c4e4f08..4ecaed91cf 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/window_change_detector.rs
@@ -37,6 +37,8 @@
//! idempotent so explicit-detect + later-drop is safe.
use std::collections::HashSet;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Mutex;
use std::time::{Duration, Instant};
use cua_driver_core::window_observation::WindowObservationBounds;
@@ -71,6 +73,9 @@ pub struct Snapshot {
window_ids: HashSet<u32>,
front_pid: Option<i32>,
_lease: Option<SuppressionLease>,
+ /// A change the previous action's detached tail saw after that action
+ /// had returned; reported on this action's result.
+ earlier: Option<Late>,
}
/// Result of `detect()` — what changed during the action window.
@@ -78,6 +83,10 @@ pub struct Snapshot {
pub struct Changes {
pub new_windows: Vec<WindowEvent>,
pub foreground_changed: bool,
+ /// Windows the previous action opened after its result had returned.
+ pub earlier_new_windows: Vec<WindowEvent>,
+ /// The previous action made another app frontmost after it returned.
+ pub earlier_foreground_changed: bool,
/// Whether the post-action window poll ran. `false` when the host bound
/// skipped it or the poll task was lost: an empty `new_windows` then means
/// nothing was watched, not that nothing opened.
@@ -89,10 +98,20 @@ impl Changes {
Self {
new_windows: Vec::new(),
foreground_changed: false,
+ earlier_new_windows: Vec::new(),
+ earlier_foreground_changed: false,
polled: true,
}
}
+ fn with_earlier(mut self, earlier: Option<Late>) -> Self {
+ if let Some(late) = earlier {
+ self.earlier_new_windows = late.new_windows;
+ self.earlier_foreground_changed = late.foreground_changed;
+ }
+ self
+ }
+
pub fn not_polled() -> Self {
Self {
polled: false,
@@ -114,42 +133,57 @@ impl Changes {
/// **verbatim** so MCP callers that key off the suffix wording
/// don't need a per-binary special case.
pub fn result_suffix(&self) -> String {
+ let mut suffix = String::new();
+ if !self.earlier_new_windows.is_empty() {
+ suffix.push_str(&format!(
+ "\n\n🪟 After the previous action returned, it opened new window(s): {}.",
+ window_summaries(&self.earlier_new_windows)
+ ));
+ } else if self.earlier_foreground_changed {
+ suffix.push_str(
+ "\n\n🔀 After the previous action returned, a different app became frontmost.",
+ );
+ }
if !self.needs_restore() {
- return String::new();
+ return suffix;
}
if !self.new_windows.is_empty() {
- // Group by app name (stable order), join titles per app.
- let mut by_app: std::collections::BTreeMap<&str, Vec<&str>> =
- std::collections::BTreeMap::new();
- for w in &self.new_windows {
- by_app.entry(&w.app_name).or_default().push(&w.title);
- }
- let summaries: Vec<String> = by_app
- .into_iter()
- .map(|(app, titles)| {
- let titles: Vec<String> = titles
- .into_iter()
- .filter(|t| !t.is_empty())
- .map(|t| format!("\"{t}\""))
- .collect();
- if titles.is_empty() {
- app.to_string()
- } else {
- format!("{app} ({})", titles.join(", "))
- }
- })
- .collect();
- format!(
+ suffix.push_str(&format!(
"\n\n🪟 Action opened new window(s): {}.",
- summaries.join("; ")
- )
+ window_summaries(&self.new_windows)
+ ));
} else {
- "\n\n🔀 Action caused a different app to become frontmost.".to_string()
+ suffix.push_str("\n\n🔀 Action caused a different app to become frontmost.");
}
+ suffix
}
}
+/// `App ("Title", …); Other` for a result suffix, grouped by app name.
+fn window_summaries(windows: &[WindowEvent]) -> String {
+ let mut by_app: std::collections::BTreeMap<&str, Vec<&str>> = std::collections::BTreeMap::new();
+ for w in windows {
+ by_app.entry(&w.app_name).or_default().push(&w.title);
+ }
+ by_app
+ .into_iter()
+ .map(|(app, titles)| {
+ let titles: Vec<String> = titles
+ .into_iter()
+ .filter(|t| !t.is_empty())
+ .map(|t| format!("\"{t}\""))
+ .collect();
+ if titles.is_empty() {
+ app.to_string()
+ } else {
+ format!("{app} ({})", titles.join(", "))
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("; ")
+}
+
/// Returns true when a window belongs to this cua-driver process, including
/// transient UI such as the agent cursor overlay. Those windows are internal
/// implementation details rather than action-triggered application windows.
@@ -157,13 +191,65 @@ fn is_daemon_window(window: &WindowInfo) -> bool {
window.pid == std::process::id() as i32
}
-/// Default poll deadline — new windows triggered by a click typically
-/// appear within ~200ms on macOS; 1.0s gives the wildcard suppressor
-/// time to fire and settle.
+/// Default observation deadline. New windows triggered by a click
+/// typically appear within ~200ms on macOS; 1.0s gives the wildcard
+/// suppressor time to fire and settle.
const DEFAULT_TIMEOUT: Duration = Duration::from_millis(1000);
-/// Default inter-poll interval. Matches Swift's 50ms.
-const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(50);
+/// Default inter-poll interval.
+const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(25);
+
+/// How long the action result itself waits for a window change. Menus,
+/// popovers and sheets map well inside this. When nothing has changed by
+/// then the result returns, and the rest of the observation deadline runs
+/// detached (see [`Tail`]): the focus-steal lease stays armed and a late
+/// window is reported on the next action's result. Before this, every
+/// action that opened nothing paid the whole deadline.
+const REPORT_WINDOW: Duration = Duration::from_millis(300);
+
+/// A late change older than this is not reported on a later result.
+const LATE_REPORT_MAX_AGE: Duration = Duration::from_secs(10);
+
+/// The detached remainder of the last quiet observation: its focus-steal
+/// lease, held until the deadline, until a change shows, or until the driver
+/// starts its next action or intentional activation ([`end_tail`]).
+struct Tail {
+ id: u64,
+ _lease: Option<SuppressionLease>,
+}
+
+static TAIL: Mutex<Option<Tail>> = Mutex::new(None);
+static NEXT_TAIL_ID: AtomicU64 = AtomicU64::new(1);
+
+/// A change a detached tail saw after its action had returned.
+#[derive(Debug, Clone)]
+struct Late {
+ at: Instant,
+ new_windows: Vec<WindowEvent>,
+ foreground_changed: bool,
+}
+
+static LATE: Mutex<Option<Late>> = Mutex::new(None);
+
+fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
+ m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+/// End the detached observation of the previous action, releasing its
+/// focus-steal lease now. Called before the driver's next action and before
+/// any intentional activation, so a lingering wildcard lease never reverts
+/// an activation the driver itself asked for.
+pub fn end_tail() {
+ let tail = lock(&TAIL).take();
+ drop(tail);
+}
+
+/// Take a late change recorded by a detached tail, if it is recent.
+fn take_late() -> Option<Late> {
+ lock(&LATE)
+ .take()
+ .filter(|late| late.at.elapsed() <= LATE_REPORT_MAX_AGE)
+}
/// Resolve the post-action observation bounds from raw host values against
/// the macOS defaults. Pure; `cua_driver_core::window_observation` owns the
@@ -240,8 +326,12 @@ impl WindowChangeDetector {
suppress_focus: bool,
allowed_pid: Option<i32>,
) -> Snapshot {
+ // A new action supersedes the previous action's detached observation.
+ end_tail();
let window_ids: HashSet<u32> = host_windows().into_iter().map(|w| w.window_id).collect();
- Self::capture_from(window_ids, prior_front, suppress_focus, allowed_pid)
+ let mut snapshot = Self::capture_from(window_ids, prior_front, suppress_focus, allowed_pid);
+ snapshot.earlier = take_late();
+ snapshot
}
/// `capture` over an already-read window set.
@@ -275,6 +365,7 @@ impl WindowChangeDetector {
window_ids,
front_pid: prior_front,
_lease: lease,
+ earlier: None,
}
}
}
@@ -295,11 +386,13 @@ impl Snapshot {
/// Unset or unparsable values keep the defaults, so public callers see
/// no behavior change.
///
- /// Consumes the snapshot — the wildcard suppression lease is
- /// dropped when this returns (covers the full action + detection
- /// window). A shorter timeout therefore also shortens the wildcard
- /// focus-steal protection, and a zero timeout releases it as soon as
- /// the action returns and reports no change.
+ /// The result waits at most [`REPORT_WINDOW`] when nothing changes; the
+ /// rest of the deadline runs detached with the wildcard suppression lease
+ /// still held, until the driver's next action or intentional activation
+ /// ends it ([`end_tail`]). A window that shows during that remainder is
+ /// reported on the next action's result. A shorter timeout therefore also
+ /// shortens the wildcard focus-steal protection, and a zero timeout
+ /// releases it as soon as the action returns and reports no change.
pub fn detect(self) -> Changes {
self.detect_bounded(host_observation_bounds())
}
@@ -314,15 +407,26 @@ impl Snapshot {
/// `detect_bounded` over an explicit observer of the current layer-0
/// windows and frontmost pid.
fn detect_bounded_with(
- self,
+ mut self,
bounds: WindowObservationBounds,
- observe: impl FnMut() -> (Vec<WindowInfo>, Option<i32>),
+ observe: impl FnMut() -> (Vec<WindowInfo>, Option<i32>) + Send + 'static,
) -> Changes {
+ let earlier = self.earlier.take();
if bounds.skips_observation() {
drop(self);
- return Changes::not_polled();
+ return Changes::not_polled().with_earlier(earlier);
}
- self.detect_with(bounds.timeout, bounds.poll, observe)
+ let started = Instant::now();
+ let report = REPORT_WINDOW.min(bounds.timeout);
+ let mut observe = observe;
+ let changes = match self.poll_until(started + report, bounds.poll, &mut observe) {
+ Ok(changes) => changes,
+ Err(quiet) => {
+ quiet.continue_detached(started + bounds.timeout, bounds.poll, observe);
+ Changes::no_change()
+ }
+ };
+ changes.with_earlier(earlier)
}
/// Async wrapper around `detect()` — runs the synchronous poll
@@ -337,40 +441,104 @@ impl Snapshot {
.unwrap_or_else(|_| Changes::not_polled())
}
- /// Same as `detect()` but with configurable timing.
- fn detect_with(
+ /// One observation against the snapshot: the change it shows, if any.
+ fn observe_once(
+ &self,
+ observe: &mut impl FnMut() -> (Vec<WindowInfo>, Option<i32>),
+ ) -> Option<Changes> {
+ let (current, current_front) = observe();
+ // Keep the live detector and the pure regression tests on the same
+ // diff path so daemon-window filtering cannot drift between them.
+ let (new_windows, _closed) = Self::diff(&self.window_ids, &current);
+ let foreground_changed = match (self.front_pid, current_front) {
+ (Some(orig), Some(cur)) => orig != cur,
+ _ => false,
+ };
+ (!new_windows.is_empty() || foreground_changed).then(|| Changes {
+ new_windows,
+ foreground_changed,
+ ..Changes::no_change()
+ })
+ }
+
+ /// Poll until a change shows (`Ok`, the lease is dropped) or `deadline`
+ /// passes with none (`Err`, the snapshot and its lease handed back).
+ fn poll_until(
self,
- timeout: Duration,
+ deadline: Instant,
poll_interval: Duration,
- mut observe: impl FnMut() -> (Vec<WindowInfo>, Option<i32>),
- ) -> Changes {
- let deadline = Instant::now() + timeout;
+ observe: &mut impl FnMut() -> (Vec<WindowInfo>, Option<i32>),
+ ) -> Result<Changes, Self> {
loop {
std::thread::sleep(poll_interval);
-
- let (current, current_front) = observe();
- // Keep the live detector and the pure regression tests on the same
- // diff path so daemon-window filtering cannot drift between them.
- let (new_windows, _closed) = Self::diff(&self.window_ids, &current);
-
- let foreground_changed = match (self.front_pid, current_front) {
- (Some(orig), Some(cur)) => orig != cur,
- _ => false,
- };
-
- if !new_windows.is_empty() || foreground_changed {
- return Changes {
- new_windows,
- foreground_changed,
- polled: true,
- };
+ if let Some(changes) = self.observe_once(observe) {
+ return Ok(changes);
}
if Instant::now() >= deadline {
- return Changes::no_change();
+ return Err(self);
}
}
}
+ /// Keep observing on a background thread until `deadline`, holding the
+ /// focus-steal lease, after the action's result has returned. A change
+ /// seen here is recorded for the next action's result. [`end_tail`] (the
+ /// next action, or an intentional activation) ends it early.
+ fn continue_detached(
+ mut self,
+ deadline: Instant,
+ poll_interval: Duration,
+ mut observe: impl FnMut() -> (Vec<WindowInfo>, Option<i32>) + Send + 'static,
+ ) {
+ if Instant::now() >= deadline {
+ return;
+ }
+ let id = NEXT_TAIL_ID.fetch_add(1, Ordering::Relaxed);
+ *lock(&TAIL) = Some(Tail {
+ id,
+ _lease: self._lease.take(),
+ });
+ let still_mine = move || lock(&TAIL).as_ref().is_some_and(|tail| tail.id == id);
+ let spawned = std::thread::Builder::new()
+ .name("cua-window-watch".into())
+ .spawn(move || {
+ loop {
+ std::thread::sleep(poll_interval);
+ if !still_mine() {
+ return;
+ }
+ if let Some(changes) = self.observe_once(&mut observe) {
+ if !still_mine() {
+ return;
+ }
+ *lock(&LATE) = Some(Late {
+ at: Instant::now(),
+ new_windows: changes.new_windows,
+ foreground_changed: changes.foreground_changed,
+ });
+ // Keep the lease until the deadline: the change may be
+ // an activation it is still reverting.
+ break;
+ }
+ if Instant::now() >= deadline {
+ break;
+ }
+ }
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if !remaining.is_zero() {
+ std::thread::sleep(remaining);
+ }
+ let mut tail = lock(&TAIL);
+ if tail.as_ref().is_some_and(|tail| tail.id == id) {
+ tail.take();
+ }
+ });
+ if spawned.is_err() {
+ // No thread: release the lease now rather than holding it forever.
+ end_tail();
+ }
+ }
+
// ── Internal helpers — also used by unit tests so the diff logic can be
// exercised without driving the live window enumerator. ──────────────
@@ -484,6 +652,7 @@ mod tests {
title: "New Tab".into(),
}],
foreground_changed: false,
+ ..Changes::no_change()
};
assert!(c.needs_restore());
assert_eq!(
@@ -517,6 +686,7 @@ mod tests {
},
],
foreground_changed: true,
+ ..Changes::no_change()
};
let suffix = c.result_suffix();
// BTreeMap sort order is alphabetical by app name → Chrome before Mail.
@@ -532,6 +702,7 @@ mod tests {
polled: true,
new_windows: vec![],
foreground_changed: true,
+ ..Changes::no_change()
};
assert!(c.needs_restore());
assert_eq!(
@@ -551,6 +722,7 @@ mod tests {
title: "".into(),
}],
foreground_changed: false,
+ ..Changes::no_change()
};
// No title → just the app name, no parentheses.
assert_eq!(
@@ -621,14 +793,15 @@ mod tests {
#[test]
fn a_poll_that_ran_is_polled_even_when_it_times_out() {
let snap = WindowChangeDetector::capture_from(HashSet::from([1]), Some(7), false, None);
- let mut observations = 0;
+ let observations = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let counter = observations.clone();
let changes =
- snap.detect_bounded_with(observation_bounds_from(Some("30"), Some("10")), || {
- observations += 1;
+ snap.detect_bounded_with(observation_bounds_from(Some("30"), Some("10")), move || {
+ counter.fetch_add(1, Ordering::SeqCst);
(vec![win(1, 7, "App", "Main")], Some(7))
});
assert!(changes.polled);
- assert!(observations >= 1);
+ assert!(observations.load(Ordering::SeqCst) >= 1);
assert!(changes.new_windows.is_empty());
assert!(!changes.foreground_changed);
}
@@ -675,4 +848,112 @@ mod tests {
"no frontmost pid means no lease"
);
}
+
+ /// The tail state is process-wide; tests that touch it run one at a time.
+ static TAIL_TEST_LOCK: Mutex<()> = Mutex::new(());
+
+ /// A quiet action returns after the report window, not the whole
+ /// deadline, and the remainder keeps running detached.
+ #[test]
+ fn a_quiet_poll_returns_after_the_report_window_and_detaches_the_rest() {
+ let _serial = lock(&TAIL_TEST_LOCK);
+ end_tail();
+ let snap = WindowChangeDetector::capture_from(HashSet::from([1]), Some(7), false, None);
+ let started = Instant::now();
+ let changes = snap
+ .detect_bounded_with(observation_bounds_from(Some("3000"), Some("10")), || {
+ (vec![win(1, 7, "App", "Main")], Some(7))
+ });
+ let elapsed = started.elapsed();
+ assert!(changes.polled);
+ assert!(!changes.needs_restore());
+ assert!(elapsed >= REPORT_WINDOW, "returned after {elapsed:?}");
+ assert!(
+ elapsed < Duration::from_millis(1500),
+ "returned after {elapsed:?}"
+ );
+ assert!(lock(&TAIL).is_some(), "the remainder runs detached");
+ end_tail();
+ assert!(lock(&TAIL).is_none());
+ }
+
+ /// A deadline inside the report window behaves as before: no tail.
+ #[test]
+ fn a_short_deadline_leaves_no_detached_tail() {
+ let _serial = lock(&TAIL_TEST_LOCK);
+ end_tail();
+ let snap = WindowChangeDetector::capture_from(HashSet::from([1]), Some(7), false, None);
+ let changes = snap
+ .detect_bounded_with(observation_bounds_from(Some("40"), Some("10")), || {
+ (vec![win(1, 7, "App", "Main")], Some(7))
+ });
+ assert!(!changes.needs_restore());
+ assert!(lock(&TAIL).is_none());
+ }
+
+ /// A window that opens after the result returned is reported on the next
+ /// action's result, then not again.
+ #[test]
+ fn a_late_window_is_reported_on_the_next_result() {
+ let _serial = lock(&TAIL_TEST_LOCK);
+ end_tail();
+ lock(&LATE).take();
+ let opened_at = Instant::now() + REPORT_WINDOW + Duration::from_millis(60);
+ let snap = WindowChangeDetector::capture_from(HashSet::from([1]), Some(7), false, None);
+ let first = snap.detect_bounded_with(
+ observation_bounds_from(Some("2000"), Some("10")),
+ move || {
+ if Instant::now() >= opened_at {
+ (
+ vec![win(1, 7, "App", "Main"), win(2, 7, "App", "Save")],
+ Some(7),
+ )
+ } else {
+ (vec![win(1, 7, "App", "Main")], Some(7))
+ }
+ },
+ );
+ assert!(!first.needs_restore());
+ let wait_until = Instant::now() + Duration::from_secs(2);
+ while lock(&LATE).is_none() && Instant::now() < wait_until {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let mut next =
+ WindowChangeDetector::capture_from(HashSet::from([1, 2]), Some(7), false, None);
+ end_tail();
+ next.earlier = take_late();
+ let second = next.detect_bounded_with(observation_bounds_from(Some("0"), None), || {
+ panic!("a zero timeout must not observe the host")
+ });
+ assert_eq!(
+ second.result_suffix(),
+ "\n\n🪟 After the previous action returned, it opened new window(s): App (\"Save\")."
+ );
+ assert!(take_late().is_none(), "reported once");
+ }
+
+ /// The next action ends the previous tail before it acts, so a lingering
+ /// wildcard lease cannot revert an activation the driver asked for.
+ #[test]
+ fn end_tail_stops_the_detached_observation() {
+ let _serial = lock(&TAIL_TEST_LOCK);
+ end_tail();
+ lock(&LATE).take();
+ let snap = WindowChangeDetector::capture_from(HashSet::from([1]), Some(7), false, None);
+ let observations = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let counter = observations.clone();
+ let _ = snap.detect_bounded_with(
+ observation_bounds_from(Some("3000"), Some("10")),
+ move || {
+ counter.fetch_add(1, Ordering::SeqCst);
+ (vec![win(1, 7, "App", "Main")], Some(7))
+ },
+ );
+ end_tail();
+ std::thread::sleep(Duration::from_millis(40));
+ let after_end = observations.load(Ordering::SeqCst);
+ std::thread::sleep(Duration::from_millis(80));
+ assert_eq!(observations.load(Ordering::SeqCst), after_end);
+ assert!(lock(&LATE).is_none());
+ }
}