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): one macOS focus arbiter decides every activation undo (#6803)

injaneity14ae717630ae
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 9371f5de94..49db6c696a 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
@@ -961,13 +961,19 @@ pub fn frontmost_pid() -> Option<i32> {
crate::input::skylight::front_process_pid()
}
-/// Re-activate the app with `pid` via
-/// `NSRunningApplication.runningApplicationWithProcessIdentifier(pid)?.activateWithOptions([])`.
-/// Returns `true` if the app was found and activate was attempted.
-/// Used as the belt-and-braces step in `LaunchAppTool` when the target
-/// has self-activated despite the focus-steal observer.
+/// Activate the app with `pid` at the driver's request (see
+/// [`crate::focus_arbiter::note_intentional`]). Returns `true` if the app was
+/// found and activate was attempted.
pub fn activate_pid(pid: i32) -> bool {
- crate::window_change_detector::end_tail();
+ crate::focus_arbiter::note_intentional();
+ reactivate_app(pid)
+}
+
+/// Put the user's app `pid` back in front after a target took it. Not a
+/// driver activation: the watcher that undoes the target's change keeps
+/// running. Best effort: macOS may refuse an activation requested by a
+/// background process.
+pub fn reactivate_app(pid: i32) -> bool {
use objc2_app_kit::{NSApplicationActivationOptions, NSRunningApplication};
unsafe {
match NSRunningApplication::runningApplicationWithProcessIdentifier(pid) {
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs
index ccaddf9011..b0095ecd54 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs
@@ -327,6 +327,7 @@ impl Drop for SelfActivationGuard {
}
fn watch_self_activation(pid: i32, front: i32, stop: &std::sync::atomic::AtomicBool) {
+ use crate::focus_arbiter::{Decision, UndoWatch};
use std::sync::atomic::Ordering;
use std::time::Instant;
// Read before anything happens: after a key loss the user's app may
@@ -334,17 +335,20 @@ fn watch_self_activation(pid: i32, front: i32, stop: &std::sync::atomic::AtomicB
let user_key_window = crate::input::skylight::key_window_of_pid(front);
// A Chrome window the user had placed above their own stays there.
let above_before = crate::key_focus_guard::target_window_above_front(pid, front);
- let rekey = || {
- user_key_window.is_some_and(|wid| crate::input::skylight::make_exact_window_key(front, wid))
- };
+ let rekey =
+ || user_key_window.is_some_and(|wid| crate::input::skylight::return_key_to(front, wid));
let mut last_rekey = Instant::now();
let mut last_order_check = Instant::now();
- let mut epoch = crate::window_change_detector::intentional_epoch();
+ // The watch outlives single driver activations and user switches: once
+ // the driver or the user has put Chrome in front, it leaves Chrome alone
+ // until Chrome is no longer in front, then holds off briefly and re-arms.
+ let mut undo = UndoWatch::arm();
let mut quiet_until = Instant::now();
while !stop.load(Ordering::SeqCst) {
- let now_epoch = crate::window_change_detector::intentional_epoch();
- if now_epoch != epoch {
- epoch = now_epoch;
+ if (undo.has_left() || !undo.epoch().is_current())
+ && crate::input::skylight::front_process_pid() != Some(pid)
+ {
+ undo = UndoWatch::arm();
quiet_until = Instant::now() + Duration::from_millis(400);
}
let calm = !crate::input::skylight::foreground_turn_active()
@@ -353,8 +357,9 @@ fn watch_self_activation(pid: i32, front: i32, stop: &std::sync::atomic::AtomicB
if calm {
let front_now = crate::input::skylight::front_process_pid();
if front_now == Some(pid) {
- if !rekey() {
- crate::key_focus_guard::revert_now(pid, front);
+ // Not when the user switched to Chrome themselves.
+ if undo.decide() == Decision::Undo && !rekey() {
+ crate::key_focus_guard::revert_now(pid, front, &undo);
}
last_rekey = Instant::now();
} else if front_now == Some(front) {
@@ -391,7 +396,7 @@ fn restore_front_app_if_browser_front(previous_pid: i64, browser_pid: i64) -> bo
if previous == browser || crate::apps::frontmost_pid() != Some(browser) {
return false;
}
- crate::apps::activate_pid(previous)
+ crate::apps::reactivate_app(previous)
}
fn is_chromium(name: &str, bundle_id: &str) -> bool {
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/focus_arbiter.rs b/libs/cua-driver/rust/crates/platform-macos/src/focus_arbiter.rs
new file mode 100644
index 0000000000..1823ae8f75
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-macos/src/focus_arbiter.rs
@@ -0,0 +1,229 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! One rule for whether the driver may undo an app's activation.
+//!
+//! Several watchers put the user's app back in front: the activation
+//! observer ([`crate::focus_steal`]), the key-focus guard's revert and order
+//! watch ([`crate::key_focus_guard`]), launch_app's late-activation watchdog
+//! and the browser attach watcher. Each action arms one [`UndoWatch`] and
+//! asks [`UndoWatch::decide`] before it undoes anything. It must leave the change
+//! alone when the driver itself has made an app frontmost since then
+//! ([`note_intentional`]), or when the user just pressed a mouse button or
+//! a modifier key and may have switched apps themselves. A watch that left a
+//! change alone stays that way, so a later check does not undo the user's
+//! switch once the input is a second old.
+//!
+//! The arbiter also holds the one lease an action leaves armed after its
+//! result returns (the window-change detector's detached watch). A driver
+//! activation ends it, and so does the next action ([`end_detached`]).
+//!
+//! Every driver activation (bring_to_front, launch_app, foreground delivery,
+//! `apps::activate_pid`, `skylight::make_exact_window_key`) calls
+//! [`note_intentional`]. Putting the user's app back (`apps::reactivate_app`,
+//! `skylight::return_key_to`) does not, so an undo never cancels the watcher
+//! that made it, or another watcher armed for the same action.
+
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex};
+
+use crate::focus_steal::SuppressionLease;
+
+static EPOCH: AtomicU64 = AtomicU64::new(0);
+
+/// The count of driver activations when a watcher was armed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Epoch(u64);
+
+impl Epoch {
+ pub fn now() -> Self {
+ Self(EPOCH.load(Ordering::SeqCst))
+ }
+
+ /// No driver activation since this epoch was taken.
+ pub fn is_current(self) -> bool {
+ self == Self::now()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn next(self) -> Self {
+ Self(self.0 + 1)
+ }
+}
+
+/// Record an activation the driver asked for. Watchers armed before it no
+/// longer undo anything, and the detached lease is released.
+pub fn note_intentional() {
+ EPOCH.fetch_add(1, Ordering::SeqCst);
+ end_detached();
+}
+
+/// The lease an action keeps after its result returned, and its id.
+static DETACHED: Mutex<Option<(u64, Option<SuppressionLease>)>> = Mutex::new(None);
+static NEXT_DETACHED: AtomicU64 = AtomicU64::new(1);
+
+fn detached() -> std::sync::MutexGuard<'static, Option<(u64, Option<SuppressionLease>)>> {
+ DETACHED
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+/// Keep `lease` armed after its action returned, replacing any earlier one.
+/// Returns the id [`holds_detached`] and [`release_detached`] take.
+pub fn detach(lease: Option<SuppressionLease>) -> u64 {
+ let id = NEXT_DETACHED.fetch_add(1, Ordering::Relaxed);
+ let previous = detached().replace((id, lease));
+ drop(previous);
+ id
+}
+
+/// Whether the lease detached as `id` is still held.
+pub fn holds_detached(id: u64) -> bool {
+ detached().as_ref().is_some_and(|(held, _)| *held == id)
+}
+
+/// Release the lease detached as `id`, if it is still the one held.
+pub fn release_detached(id: u64) {
+ let mut slot = detached();
+ let released = slot.take_if(|(held, _)| *held == id);
+ drop(slot);
+ drop(released);
+}
+
+/// Release the detached lease. The driver's next action supersedes the
+/// previous one's watch.
+pub fn end_detached() {
+ let released = detached().take();
+ drop(released);
+}
+
+#[cfg(test)]
+pub(crate) fn has_detached() -> bool {
+ detached().is_some()
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Decision {
+ Undo,
+ Leave,
+}
+
+/// One action's right to undo activations, shared by all its leases and
+/// loops.
+#[derive(Clone, Debug)]
+pub struct UndoWatch(Arc<WatchState>);
+
+#[derive(Debug)]
+struct WatchState {
+ armed: Epoch,
+ /// Set by the first Leave. A lock, so two watchers of one action that
+ /// decide at once cannot see Undo after the other saw Leave.
+ left: Mutex<bool>,
+}
+
+impl UndoWatch {
+ pub fn arm() -> Self {
+ Self::armed_at(Epoch::now())
+ }
+
+ fn armed_at(armed: Epoch) -> Self {
+ Self(Arc::new(WatchState {
+ armed,
+ left: Mutex::new(false),
+ }))
+ }
+
+ pub fn epoch(&self) -> Epoch {
+ self.0.armed
+ }
+
+ /// Whether this watch has left a change alone.
+ pub fn has_left(&self) -> bool {
+ *self.left()
+ }
+
+ fn left(&self) -> std::sync::MutexGuard<'_, bool> {
+ self.0
+ .left
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ }
+
+ /// Whether the activation just observed may be undone. Call it only when
+ /// there is one to undo: a `Leave` is final for this watch.
+ pub fn decide(&self) -> Decision {
+ self.decide_with(Epoch::now, user_switched_recently)
+ }
+
+ fn decide_with(
+ &self,
+ now: impl FnOnce() -> Epoch,
+ user_switched: impl FnOnce() -> bool,
+ ) -> Decision {
+ let mut left = self.left();
+ if !*left && self.0.armed == now() && !user_switched() {
+ Decision::Undo
+ } else {
+ *left = true;
+ Decision::Leave
+ }
+ }
+}
+
+/// A hardware mouse-down or modifier change within this long before an
+/// activation means the user may have caused it.
+const USER_SWITCH_WINDOW_S: f64 = 1.0;
+
+#[link(name = "ApplicationServices", kind = "framework")]
+extern "C" {
+ fn CGEventSourceSecondsSinceLastEventType(state: i32, event_type: u32) -> f64;
+}
+
+/// Whether the user pressed a mouse button or a modifier key on the real
+/// hardware just now. Events the driver posts to a pid do not count.
+fn user_switched_recently() -> bool {
+ const HID_SYSTEM_STATE: i32 = 1;
+ const LEFT_MOUSE_DOWN: u32 = 1;
+ const RIGHT_MOUSE_DOWN: u32 = 3;
+ const FLAGS_CHANGED: u32 = 12;
+ [LEFT_MOUSE_DOWN, RIGHT_MOUSE_DOWN, FLAGS_CHANGED]
+ .into_iter()
+ .any(|kind| {
+ let since = unsafe { CGEventSourceSecondsSinceLastEventType(HID_SYSTEM_STATE, kind) };
+ since.is_finite() && since < USER_SWITCH_WINDOW_S
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn an_undo_needs_its_own_epoch_and_no_user_input() {
+ let armed = Epoch::now();
+ let watch = UndoWatch::armed_at(armed);
+ assert_eq!(watch.decide_with(|| armed, || false), Decision::Undo);
+ assert_eq!(watch.decide_with(|| armed, || false), Decision::Undo);
+ // The driver activated an app since the watcher was armed.
+ let watch = UndoWatch::armed_at(armed);
+ assert_eq!(
+ watch.decide_with(|| armed.next(), || false),
+ Decision::Leave
+ );
+ // The user clicked or held a modifier just now.
+ let watch = UndoWatch::armed_at(armed);
+ assert_eq!(watch.decide_with(|| armed, || true), Decision::Leave);
+ }
+
+ /// The user switched to the target while one lease watched; a later check
+ /// by another lease or loop of the same action, after the input is old,
+ /// must not undo that switch.
+ #[test]
+ fn a_left_change_stays_left_for_the_whole_action() {
+ let armed = Epoch::now();
+ let watch = UndoWatch::armed_at(armed);
+ let loop_after = watch.clone();
+ assert_eq!(watch.decide_with(|| armed, || true), Decision::Leave);
+ assert_eq!(loop_after.decide_with(|| armed, || false), Decision::Leave);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/focus_steal.rs b/libs/cua-driver/rust/crates/platform-macos/src/focus_steal.rs
index 39ba797dcf..54f04d2db1 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/focus_steal.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/focus_steal.rs
@@ -69,6 +69,8 @@ use objc2_app_kit::{
use objc2_foundation::NSOperationQueue;
use uuid::Uuid;
+use crate::focus_arbiter::{Decision, UndoWatch};
+
/// Per-entry deadline. After this much wall-clock time the dispatcher's
/// observer (and the janitor) treats the entry as leaked and prunes it
/// without firing. Mirrors Swift PR #1521.
@@ -103,6 +105,9 @@ struct Entry {
/// Monotonic deadline. After this, the entry is pruned without
/// firing.
deadline: Instant,
+ /// The action's right to undo; a driver activation since it was armed,
+ /// or a user switch, is never undone ([`UndoWatch::decide`]).
+ watch: UndoWatch,
/// Provenance for tracing — e.g. `"LaunchAppTool.pre"`.
#[allow(dead_code)]
origin: &'static str,
@@ -142,9 +147,23 @@ impl FocusStealPreventer {
target_pid: Option<i32>,
restore_to: i32,
origin: &'static str,
+ ) -> SuppressionLease {
+ Self::begin_suppression_for(target_pid, restore_to, origin, UndoWatch::arm())
+ }
+
+ /// [`Self::begin_suppression`] under an action's existing `watch`, so a
+ /// driver activation since the action began, or a user switch another of
+ /// its watchers saw, is not undone.
+ pub fn begin_suppression_for(
+ target_pid: Option<i32>,
+ restore_to: i32,
+ origin: &'static str,
+ watch: UndoWatch,
) -> SuppressionLease {
let shared = Self::shared();
- let handle = shared.dispatcher.add(target_pid, restore_to, origin);
+ let handle = shared
+ .dispatcher
+ .add_entry(target_pid, None, restore_to, origin, watch);
SuppressionLease {
handle,
dispatcher: Arc::clone(&shared.dispatcher),
@@ -163,9 +182,13 @@ impl FocusStealPreventer {
origin: &'static str,
) -> SuppressionLease {
let shared = Self::shared();
- let handle = shared
- .dispatcher
- .add_allowing(allowed_pid, restore_to, origin);
+ let handle = shared.dispatcher.add_entry(
+ None,
+ Some(allowed_pid),
+ restore_to,
+ origin,
+ UndoWatch::arm(),
+ );
SuppressionLease {
handle,
dispatcher: Arc::clone(&shared.dispatcher),
@@ -268,23 +291,31 @@ impl Dispatcher {
/// subsequent adds would skip the kick and the janitor never
/// started, leaving deadline-reaping entirely up to the
/// `snapshot_matches` reap fallback (only fires on an activation).
+ #[cfg(test)]
fn add(
self: &Arc<Self>,
target_pid: Option<i32>,
restore_to: i32,
origin: &'static str,
) -> SuppressionHandle {
- self.add_entry(target_pid, None, restore_to, origin)
+ self.add_entry(target_pid, None, restore_to, origin, UndoWatch::arm())
}
/// Add a wildcard entry that ignores one intentional target activation.
+ #[cfg(test)]
fn add_allowing(
self: &Arc<Self>,
allowed_pid: i32,
restore_to: i32,
origin: &'static str,
) -> SuppressionHandle {
- self.add_entry(None, Some(allowed_pid), restore_to, origin)
+ self.add_entry(
+ None,
+ Some(allowed_pid),
+ restore_to,
+ origin,
+ UndoWatch::arm(),
+ )
}
fn add_entry(
@@ -293,6 +324,7 @@ impl Dispatcher {
allowed_pid: Option<i32>,
restore_to: i32,
origin: &'static str,
+ watch: UndoWatch,
) -> SuppressionHandle {
let id = Uuid::new_v4();
let entry = Entry {
@@ -300,6 +332,7 @@ impl Dispatcher {
allowed_pid,
restore_to,
deadline: Instant::now() + ENTRY_DEADLINE,
+ watch,
origin,
};
{
@@ -329,8 +362,13 @@ impl Dispatcher {
/// Snapshot the entries (cloned to a small Vec) — used by tests
/// and the activation handler to evaluate matches without holding
- /// the lock across the restore call.
- fn snapshot_matches(&self, activated_pid: i32) -> Vec<i32> {
+ /// the lock across the restore call. A matching entry restores only when
+ /// `may_undo` allows it for the entry's watch.
+ fn snapshot_matches(
+ &self,
+ activated_pid: i32,
+ may_undo: impl Fn(&UndoWatch) -> bool,
+ ) -> Vec<i32> {
let mut guard = self.entries.lock().unwrap();
// Reap expired entries first — keeps the dispatcher honest even
// if the janitor hasn't ticked yet.
@@ -342,13 +380,14 @@ impl Dispatcher {
if e.allowed_pid == Some(activated_pid) {
return false;
}
- match e.target_pid {
+ let matched = match e.target_pid {
Some(p) => p == activated_pid,
// Wildcard: match any activation except the restore_to
// pid (don't fight ourselves when we re-activate the
// prior frontmost).
None => activated_pid != e.restore_to,
- }
+ };
+ matched && may_undo(&e.watch)
})
.map(|e| e.restore_to)
.collect()
@@ -518,7 +557,8 @@ fn handle_activation(dispatcher: &Arc<Dispatcher>, note: &objc2_foundation::NSNo
pid as i32
};
- let restore_pids = dispatcher.snapshot_matches(activated_pid);
+ let restore_pids =
+ dispatcher.snapshot_matches(activated_pid, |watch| watch.decide() == Decision::Undo);
for pid in restore_pids {
restore_focus(pid);
}
@@ -545,6 +585,22 @@ mod tests {
use super::*;
use std::sync::Arc;
+ /// Every entry may undo; the epoch rule has its own test.
+ const ANY: fn(&UndoWatch) -> bool = |_| true;
+
+ /// An entry armed before a driver activation never restores: the
+ /// activation is the driver's own (bring_to_front, foreground delivery).
+ #[test]
+ fn an_entry_armed_before_a_driver_activation_does_not_restore() {
+ let d = Arc::new(Dispatcher::new());
+ let _h = d.add(Some(42), 7, "test.epoch");
+ let armed = crate::focus_arbiter::Epoch::now();
+ assert_eq!(d.snapshot_matches(42, |w| w.epoch() == armed), vec![7]);
+ assert!(d
+ .snapshot_matches(42, |w| w.epoch() == armed.next())
+ .is_empty());
+ }
+
/// Dispatcher::add returns a handle, the entry is reachable by
/// match, and remove() drops it.
#[test]
@@ -552,10 +608,10 @@ mod tests {
let d = Arc::new(Dispatcher::new());
let h = d.add(Some(42), 7, "test.add");
assert_eq!(d.len(), 1);
- let matches = d.snapshot_matches(42);
+ let matches = d.snapshot_matches(42, ANY);
assert_eq!(matches, vec![7]);
// Non-matching pid: no restore candidates.
- assert!(d.snapshot_matches(99).is_empty());
+ assert!(d.snapshot_matches(99, ANY).is_empty());
d.remove(h);
assert_eq!(d.len(), 0);
}
@@ -567,9 +623,9 @@ mod tests {
let d = Arc::new(Dispatcher::new());
let _h = d.add(None, 7, "test.wild");
// pid 99 != restore_to 7 → should match.
- assert_eq!(d.snapshot_matches(99), vec![7]);
+ assert_eq!(d.snapshot_matches(99, ANY), vec![7]);
// pid 7 == restore_to → must NOT match (don't fight ourselves).
- assert!(d.snapshot_matches(7).is_empty());
+ assert!(d.snapshot_matches(7, ANY).is_empty());
}
/// A background pixel click intentionally makes its target AppKit-active
@@ -581,16 +637,16 @@ mod tests {
let _h = d.add_allowing(42, 7, "test.allow");
assert!(
- d.snapshot_matches(42).is_empty(),
+ d.snapshot_matches(42, ANY).is_empty(),
"intentional target activation must not be restored before the click"
);
assert_eq!(
- d.snapshot_matches(99),
+ d.snapshot_matches(99, ANY),
vec![7],
"unrelated activations must remain suppressed"
);
assert!(
- d.snapshot_matches(7).is_empty(),
+ d.snapshot_matches(7, ANY).is_empty(),
"restoring the original foreground must never recurse"
);
}
@@ -641,13 +697,14 @@ mod tests {
allowed_pid: None,
restore_to: 7,
deadline: Instant::now() - Duration::from_secs(1),
+ watch: UndoWatch::arm(),
origin: "test.leak",
},
);
}
assert_eq!(d.len(), 1);
// snapshot_matches reaps expired entries before matching.
- let matches = d.snapshot_matches(42);
+ let matches = d.snapshot_matches(42, ANY);
assert!(matches.is_empty(), "expired entry should not fire");
assert_eq!(d.len(), 0, "snapshot_matches should purge expired");
}
@@ -708,7 +765,7 @@ mod tests {
let d = Arc::new(Dispatcher::new());
let _a = d.add(Some(42), 1, "test.m1");
let _b = d.add(Some(42), 2, "test.m2");
- let matches = d.snapshot_matches(42);
+ let matches = d.snapshot_matches(42, ANY);
assert_eq!(matches.len(), 2);
// Set equality — order is HashMap-dependent.
assert!(matches.contains(&1));
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 0630b2b50f..7540627e6d 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
@@ -253,7 +253,7 @@ const KEY_RECORD_SETTLE: std::time::Duration = std::time::Duration::from_millis(
/// Returns `true` when every record was posted. Whether the app acted on them
/// is for the caller to confirm.
pub fn post_window_key_records(pid: pid_t, current: Option<u32>, target: u32) -> bool {
- crate::window_change_detector::end_tail();
+ crate::focus_arbiter::end_detached();
let Some(post) = post_event_record_to_fn() else {
return false;
};
@@ -985,7 +985,7 @@ pub fn activate_without_raise_with(
target_wid: u32,
defocus_front: bool,
) -> bool {
- crate::window_change_detector::end_tail();
+ crate::focus_arbiter::end_detached();
let post_fn = match post_event_record_to_fn() {
Some(f) => f,
None => return false,
@@ -1162,7 +1162,7 @@ pub fn front_process_matches(target_pid: libc::pid_t, target_wid: u32) -> Option
/// Returns `true` only when the target PSN resolved and WindowServer accepted
/// `SLPSSetFrontProcessWithOptions`.
pub fn set_front_process_persistently(target_pid: libc::pid_t, target_wid: u32) -> bool {
- crate::window_change_detector::note_intentional_activation();
+ crate::focus_arbiter::note_intentional();
let Some(set_front) = set_front_process_fn() else {
return false;
};
@@ -1196,6 +1196,18 @@ fn make_key_window_record(window_id: u32, event_kind: u8) -> [u8; 0xF8] {
/// make-key records for the requested WindowServer id, then let the caller
/// raise the matching AX window. No other application window is addressed.
pub fn make_exact_window_key(target_pid: libc::pid_t, target_wid: u32) -> bool {
+ crate::focus_arbiter::note_intentional();
+ exact_window_key(target_pid, target_wid)
+}
+
+/// Give the user's window `wid` of `pid` key and front back after a target
+/// took it, by the same sequence as [`make_exact_window_key`]. Not a driver
+/// activation: the watcher that undoes the target's change keeps running.
+pub fn return_key_to(pid: libc::pid_t, wid: u32) -> bool {
+ exact_window_key(pid, wid)
+}
+
+fn exact_window_key(target_pid: libc::pid_t, target_wid: u32) -> bool {
let Some(set_front) = set_front_process_fn() else {
return false;
};
@@ -1255,10 +1267,9 @@ pub fn foreground_turn_active() -> bool {
}
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();
- crate::window_change_detector::note_intentional_activation();
+ // Watchers armed before this, including the previous action's detached
+ // window watch, no longer undo an activation.
+ crate::focus_arbiter::note_intentional();
if HOLDS_FOREGROUND_LOCK.with(std::cell::Cell::get) {
return ForegroundTurn { _guard: None };
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/key_focus_guard.rs b/libs/cua-driver/rust/crates/platform-macos/src/key_focus_guard.rs
index b05f3422a9..6bbd4fbfd7 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/key_focus_guard.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/key_focus_guard.rs
@@ -47,6 +47,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
+use crate::focus_arbiter::{Decision, Epoch, UndoWatch};
use crate::input::skylight;
/// How long a guarded target's tap hides the driver's own theft after an id
@@ -154,18 +155,19 @@ fn target_self_activated(front_process: Option<i32>, target: i32, front: i32) ->
/// directly; `NSWorkspace` only learns of the activation once the daemon's run
/// loop processes the notice, which took about a second in Bench v2 CDB-G04.
/// Revert `target`'s self-activation right now, giving `front` its key
-/// window back (see [`revert_self_activation`]).
-pub fn revert_now(target: i32, front: i32) -> bool {
- revert_self_activation(target, front)
+/// window back, if `watch` allows it (see [`revert_self_activation`]).
+pub fn revert_now(target: i32, front: i32, watch: &UndoWatch) -> bool {
+ revert_self_activation(target, front, watch)
}
-fn revert_self_activation(target: i32, front: i32) -> bool {
+fn revert_self_activation(target: i32, front: i32, watch: &UndoWatch) -> bool {
if !target_self_activated(skylight::front_process_pid(), target, front) {
return false;
}
- // The user may have switched to the target themselves (a click on its
- // window, or Cmd-Tab). Leave that alone.
- if user_switched_recently() {
+ // The driver activated an app since `watch` was armed, or the user may
+ // have switched to the target themselves (a click on its window, or
+ // Cmd-Tab).
+ if watch.decide() == Decision::Leave {
return false;
}
let started = Instant::now();
@@ -175,7 +177,7 @@ fn revert_self_activation(target: i32, front: i32) -> bool {
// daemon is only a request under cooperative activation and can be
// ignored, so it is the fallback.
let restored = skylight::key_window_of_pid(front)
- .is_some_and(|wid| skylight::make_exact_window_key(front, wid))
+ .is_some_and(|wid| skylight::return_key_to(front, wid))
&& skylight::front_process_pid() == Some(front);
if !restored {
use objc2_app_kit::{NSApplicationActivationOptions, NSRunningApplication};
@@ -197,30 +199,6 @@ fn revert_self_activation(target: i32, front: i32) -> bool {
true
}
-/// A hardware mouse-down or modifier change within this long before an
-/// activation means the user may have caused it.
-const USER_SWITCH_WINDOW_S: f64 = 1.0;
-
-#[link(name = "ApplicationServices", kind = "framework")]
-extern "C" {
- fn CGEventSourceSecondsSinceLastEventType(state: i32, event_type: u32) -> f64;
-}
-
-/// Whether the user pressed a mouse button or a modifier key on the real
-/// hardware just now. Events the driver posts to a pid do not count.
-fn user_switched_recently() -> bool {
- const HID_SYSTEM_STATE: i32 = 1;
- const LEFT_MOUSE_DOWN: u32 = 1;
- const RIGHT_MOUSE_DOWN: u32 = 3;
- const FLAGS_CHANGED: u32 = 12;
- [LEFT_MOUSE_DOWN, RIGHT_MOUSE_DOWN, FLAGS_CHANGED]
- .into_iter()
- .any(|kind| {
- let since = unsafe { CGEventSourceSecondsSinceLastEventType(HID_SYSTEM_STATE, kind) };
- since.is_finite() && since < USER_SWITCH_WINDOW_S
- })
-}
-
/// How long the order stays watched after a guarded action ends. A target
/// can raise a window a moment after the call that caused it returns (a
/// banner, a sheet, or a menu that a renderer process opens later).
@@ -229,28 +207,28 @@ const ORDER_POLL: Duration = Duration::from_millis(20);
const MAX_RESTORES_PER_WATCH: u32 = 3;
/// One target's watch after a guarded action.
-#[derive(Clone, Copy)]
+#[derive(Clone)]
struct Watch {
until: Instant,
front: i32,
/// Also restore the window order (off when the user had put the target
/// above their window before the action).
order: bool,
- /// [`crate::window_change_detector::intentional_epoch`] when armed.
- epoch: u64,
+ /// The action's right to undo the target's changes.
+ undo: UndoWatch,
}
/// Keep restoring the user's window above `target`, and undoing the target's
/// self-activation, for a short while after the action. One watcher per
/// target; a later action extends it.
-fn watch_order_after_action(target: i32, front: i32, order: bool, epoch: u64) {
+fn watch_order_after_action(target: i32, front: i32, order: bool, undo: UndoWatch) {
static WATCHING: OnceLock<Mutex<HashMap<i32, Watch>>> = OnceLock::new();
let watching = WATCHING.get_or_init(|| Mutex::new(HashMap::new()));
let watch = Watch {
until: Instant::now() + ORDER_WATCH,
front,
order,
- epoch,
+ undo,
};
{
let mut map = watching
@@ -276,18 +254,16 @@ fn watch_order_after_action(target: i32, front: i32, order: bool, epoch: u64) {
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(&target)
- .copied();
+ .cloned();
let Some(current) = current else { return };
- // An activation the driver asked for since (bring_to_front,
- // foreground delivery) is not reverted.
if reverts < MAX_RESTORES_PER_WATCH
- && current.epoch == crate::window_change_detector::intentional_epoch()
- && revert_self_activation(target, current.front)
+ && revert_self_activation(target, current.front, &current.undo)
{
reverts += 1;
}
if current.order
&& restores < MAX_RESTORES_PER_WATCH
+ && current.undo.epoch().is_current()
&& restore_front_if_raised(target, current.front)
{
restores += 1;
@@ -392,8 +368,8 @@ struct State {
/// them (see [`target_tap_callback`]).
target_taps: HashMap<i32, Tap>,
/// Guarded pid -> (live leases, end of the tail after the last lease,
- /// intentional-activation epoch when last armed).
- guarded: HashMap<i32, (usize, Instant, u64)>,
+ /// epoch when last armed).
+ guarded: HashMap<i32, (usize, Instant, Epoch)>,
/// End of the window in which target taps drop the driver's own theft
/// notice (see [`release_target_theft`]).
lookup_until: Option<Instant>,
@@ -431,21 +407,18 @@ pub struct Lease {
/// A target window already sat above the user's window when the action
/// started (the user arranged it so); then nothing is restored.
above_before: bool,
- /// [`crate::window_change_detector::intentional_epoch`] when armed. If
- /// the driver activated an app itself since, the target's activation is
- /// not reverted.
- epoch: u64,
+ /// The action's right to undo. If the driver activated an app itself
+ /// since, or the user switched, the target's activation is not reverted.
+ undo: UndoWatch,
}
impl Drop for Lease {
fn drop(&mut self) {
- if self.epoch == crate::window_change_detector::intentional_epoch() {
- revert_self_activation(self.pid, self.front);
- }
- if !self.above_before {
+ revert_self_activation(self.pid, self.front, &self.undo);
+ if !self.above_before && self.undo.epoch().is_current() {
restore_front_if_raised(self.pid, self.front);
}
- watch_order_after_action(self.pid, self.front, !self.above_before, self.epoch);
+ watch_order_after_action(self.pid, self.front, !self.above_before, self.undo.clone());
let mut st = lock();
if let Some((leases, until, _)) = st.guarded.get_mut(&self.pid) {
*leases = leases.saturating_sub(1);
@@ -479,9 +452,10 @@ pub fn protect(target_pid: i32) -> Option<Lease> {
}
// Register first, so an idle teardown cannot remove the tap right after
// ensure_tap.
+ let undo = UndoWatch::arm();
{
let mut st = lock();
- let epoch = crate::window_change_detector::intentional_epoch();
+ let epoch = undo.epoch();
let entry = st
.guarded
.entry(target_pid)
@@ -494,7 +468,7 @@ pub fn protect(target_pid: i32) -> Option<Lease> {
pid: target_pid,
front,
above_before: target_above_front(target_pid, front),
- epoch: crate::window_change_detector::intentional_epoch(),
+ undo,
};
// Do not touch key focus here. This runs before every background action
// while the user may be typing, and any key event that reaches
@@ -518,7 +492,7 @@ pub fn protect(target_pid: i32) -> Option<Lease> {
/// of a refused background invoke_menu, then the foreground invoke_menu found
/// its key-window-gated item disabled).
fn is_guarded(pid: i32) -> bool {
- let epoch = crate::window_change_detector::intentional_epoch();
+ let epoch = Epoch::now();
let st = lock();
st.guarded.get(&pid).is_some_and(|&(leases, until, armed)| {
guard_applies(leases, until, armed, Instant::now(), epoch)
@@ -526,7 +500,7 @@ fn is_guarded(pid: i32) -> bool {
}
/// Pure part of [`is_guarded`], for tests.
-fn guard_applies(leases: usize, until: Instant, armed: u64, now: Instant, epoch: u64) -> bool {
+fn guard_applies(leases: usize, until: Instant, armed: Epoch, now: Instant, epoch: Epoch) -> bool {
armed == epoch && (leases > 0 || now < until)
}
@@ -884,15 +858,16 @@ mod tests {
fn an_intentional_activation_ends_the_guard() {
let now = Instant::now();
let later = now + Duration::from_secs(3);
+ let (e, next) = (Epoch::now(), Epoch::now().next());
// Live lease or tail, same epoch: guarded.
- assert!(guard_applies(1, now, 5, now, 5));
- assert!(guard_applies(0, later, 5, now, 5));
+ assert!(guard_applies(1, now, e, now, e));
+ assert!(guard_applies(0, later, e, now, e));
// The driver activated an app since (bring_to_front in the tail):
// the target's key-focus change is that activation, not a menu.
- assert!(!guard_applies(0, later, 5, now, 6));
- assert!(!guard_applies(1, later, 5, now, 6));
+ assert!(!guard_applies(0, later, e, now, next));
+ assert!(!guard_applies(1, later, e, now, next));
// Tail over.
- assert!(!guard_applies(0, now, 5, later, 5));
+ assert!(!guard_applies(0, now, e, later, e));
}
#[test]
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
index 4d68a95be9..4239156ae9 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
@@ -37,6 +37,8 @@ pub mod document_edit;
#[cfg(target_os = "macos")]
pub mod fast_path_guard;
#[cfg(target_os = "macos")]
+pub mod focus_arbiter;
+#[cfg(target_os = "macos")]
pub mod focus_guard;
#[cfg(target_os = "macos")]
pub mod focus_steal;
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 4a499af6db..4a13802b0c 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
@@ -337,8 +337,7 @@ impl Tool for BringToFrontTool {
}
async fn invoke(&self, args: Value) -> ToolResult {
- crate::window_change_detector::end_tail();
- crate::window_change_detector::note_intentional_activation();
+ crate::focus_arbiter::note_intentional();
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 eddeb4d720..38b7e20c0b 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
@@ -237,6 +237,7 @@ fn background_pixel_restore_pid(
/// different app here; the wildcard suppression lease handles genuine side
/// effects.
pub(super) async fn restore_user_focus_after_background_pixel(
+ undo: crate::focus_arbiter::UndoWatch,
pid: i32,
prior_front: Option<i32>,
prior_key_wid: Option<u32>,
@@ -252,8 +253,10 @@ pub(super) async fn restore_user_focus_after_background_pixel(
prior_front,
pid,
apps::frontmost_pid(),
- ) {
- let _ = apps::activate_pid(previous_pid);
+ )
+ .filter(|_| undo.decide() == crate::focus_arbiter::Decision::Undo)
+ {
+ let _ = apps::reactivate_app(previous_pid);
wait_until_frontmost(previous_pid, std::time::Duration::from_millis(300)).await;
true
} else {
@@ -1356,6 +1359,7 @@ impl ClickTool {
// or a Safari link that activates a new tab — same side-effect
// shape as the AX path, so we wrap identically.
let prior_front = apps::frontmost_pid();
+ let undo = crate::focus_arbiter::UndoWatch::arm();
let snapshot = match activation_policy {
PixelActivationPolicy::SuppressTarget => {
WindowChangeDetector::snapshot(prior_front)
@@ -1528,6 +1532,7 @@ impl ClickTool {
if activation_policy == PixelActivationPolicy::AllowTargetWithoutRaise {
restore_user_focus_after_background_pixel(
+ undo,
pid,
prior_front,
prior_key_wid,
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs
index e94314a4b0..89d832ac21 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs
@@ -354,6 +354,7 @@ impl Tool for DragTool {
// background the target itself may become AppKit-active without
// raising; anything else that takes focus is reported and undone.
let prior_front = apps::frontmost_pid();
+ let undo = crate::focus_arbiter::UndoWatch::arm();
let snapshot = if fg {
WindowChangeDetector::snapshot(prior_front)
} else {
@@ -512,6 +513,7 @@ impl Tool for DragTool {
if !fg {
super::click::restore_user_focus_after_background_pixel(
+ undo,
pid,
prior_front,
prior_key_wid,
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 e4a97b156e..b0a1bf0c98 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
@@ -91,8 +91,10 @@ impl Tool for LaunchAppTool {
async fn invoke(&self, args: Value) -> ToolResult {
use cua_driver_core::tool_args::ArgsExt;
- crate::window_change_detector::end_tail();
- crate::window_change_detector::note_intentional_activation();
+ crate::focus_arbiter::note_intentional();
+ // Every lease and demotion below belongs to this launch: a driver
+ // activation after this point is not undone.
+ let watch = crate::focus_arbiter::UndoWatch::arm();
let bundle_id = args.opt_str("bundle_id");
let name = args.opt_str("name");
let mut located = None;
@@ -208,10 +210,11 @@ impl Tool for LaunchAppTool {
let wildcard_lease = prior_frontmost
.filter(|_| !finder_folder_handoff)
.map(|prior| {
- crate::focus_steal::FocusStealPreventer::begin_suppression(
+ crate::focus_steal::FocusStealPreventer::begin_suppression_for(
None,
prior,
"LaunchAppTool.pre",
+ watch.clone(),
)
});
@@ -295,11 +298,13 @@ impl Tool for LaunchAppTool {
if let Ok(Ok((pid, _, _))) = &launch_result {
if let Some(prior) = prior_frontmost {
if *pid != prior {
- let targeted_lease = crate::focus_steal::FocusStealPreventer::begin_suppression(
- Some(*pid),
- prior,
- "LaunchAppTool.post",
- );
+ let targeted_lease =
+ crate::focus_steal::FocusStealPreventer::begin_suppression_for(
+ Some(*pid),
+ prior,
+ "LaunchAppTool.post",
+ watch.clone(),
+ );
// Now safe to drop the wildcard — targeted is armed.
drop(wildcard_lease);
// Hold the targeted lease long enough to cover the
@@ -335,7 +340,7 @@ impl Tool for LaunchAppTool {
// the same tokio tick the lease dropped), demote it.
// Loop 5x200ms = 1s of post-window coverage. Each
// iteration is cheap (one frontmost_pid + maybe one
- // activate_pid call) so this stays well under the
+ // reactivate_app call) so this stays well under the
// RPC budget even when the demote keeps working.
let mut demotion_succeeded = true;
for _ in 0..5 {
@@ -344,7 +349,11 @@ impl Tool for LaunchAppTool {
// Not frontmost — nothing to do this tick.
continue;
}
- let activated = crate::apps::activate_pid(prior);
+ // The driver or the user fronted it: stand down.
+ if watch.decide() == crate::focus_arbiter::Decision::Leave {
+ break;
+ }
+ let activated = crate::apps::reactivate_app(prior);
let still_frontmost = crate::apps::frontmost_pid() == Some(*pid);
if still_frontmost {
tracing::warn!(
@@ -411,19 +420,27 @@ impl Tool for LaunchAppTool {
let launched_pid = *pid;
let prior_pid = prior;
tokio::spawn(async move {
- let _lease = crate::focus_steal::FocusStealPreventer::begin_suppression(
- Some(launched_pid),
- prior_pid,
- "LaunchAppTool.watchdog",
- );
+ let _lease =
+ crate::focus_steal::FocusStealPreventer::begin_suppression_for(
+ Some(launched_pid),
+ prior_pid,
+ "LaunchAppTool.watchdog",
+ watch.clone(),
+ );
let mut late_activations = 0u32;
for _ in 0..32 {
// 32 × 250ms = 8s
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
- if crate::apps::frontmost_pid() == Some(launched_pid) {
- late_activations += 1;
- let _ = crate::apps::activate_pid(prior_pid);
+ if crate::apps::frontmost_pid() != Some(launched_pid) {
+ continue;
+ }
+ // The driver activated an app since, or the
+ // user just switched to it: stand down.
+ if watch.decide() == crate::focus_arbiter::Decision::Leave {
+ break;
}
+ late_activations += 1;
+ let _ = crate::apps::reactivate_app(prior_pid);
}
if late_activations > 0 {
tracing::warn!(
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 829cdd4c8e..6682b79db7 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
@@ -40,13 +40,15 @@
//! idempotent so explicit-detect + later-drop is safe.
use std::collections::HashSet;
-use std::sync::atomic::{AtomicU64, Ordering};
+#[cfg(test)]
+use std::sync::atomic::Ordering;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use cua_driver_core::window_observation::WindowObservationBounds;
use crate::apps;
+use crate::focus_arbiter;
use crate::focus_steal::{self, SuppressionLease};
use crate::windows::{self, WindowInfo};
@@ -230,25 +232,14 @@ 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
+/// detached (see [`Snapshot::continue_detached`]): 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 {
@@ -263,31 +254,6 @@ 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);
-}
-
-/// Advanced whenever the driver itself makes an app frontmost (bring_to_front,
-/// launch_app, any foreground delivery). The key-focus guard reverts a
-/// background target's self-activation only while this has not moved since
-/// the guard was armed, so it never undoes an activation the driver asked for.
-static INTENTIONAL_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
-
-/// Record an activation the driver asked for.
-pub fn note_intentional_activation() {
- INTENTIONAL_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
-}
-
-/// The current intentional-activation epoch.
-pub fn intentional_epoch() -> u64 {
- INTENTIONAL_EPOCH.load(std::sync::atomic::Ordering::SeqCst)
-}
-
/// Take a late change recorded by a detached tail, if it is recent.
fn take_late() -> Option<Late> {
lock(&LATE)
@@ -371,7 +337,7 @@ impl WindowChangeDetector {
allowed_pid: Option<i32>,
) -> Snapshot {
// A new action supersedes the previous action's detached observation.
- end_tail();
+ focus_arbiter::end_detached();
let window_ids: HashSet<u32> = host_windows().into_iter().map(|w| w.window_id).collect();
let mut snapshot = Self::capture_from(window_ids, prior_front, suppress_focus, allowed_pid);
snapshot.earlier = take_late();
@@ -433,10 +399,11 @@ impl Snapshot {
/// 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.
+ /// ends it ([`focus_arbiter::end_detached`]). 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())
}
@@ -556,8 +523,9 @@ impl Snapshot {
/// 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.
+ /// seen here is recorded for the next action's result. The next action, or
+ /// an intentional activation, ends it early
+ /// ([`focus_arbiter::end_detached`]).
fn continue_detached(
mut self,
deadline: Instant,
@@ -567,12 +535,8 @@ impl Snapshot {
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 id = focus_arbiter::detach(self._lease.take());
+ let still_mine = move || focus_arbiter::holds_detached(id);
let spawned = std::thread::Builder::new()
.name("cua-window-watch".into())
.spawn(move || {
@@ -602,14 +566,11 @@ impl Snapshot {
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();
- }
+ focus_arbiter::release_detached(id);
});
if spawned.is_err() {
// No thread: release the lease now rather than holding it forever.
- end_tail();
+ focus_arbiter::release_detached(id);
}
}
@@ -664,7 +625,7 @@ fn observe_host() -> (Vec<WindowInfo>, Option<i32>) {
pub(crate) fn observe_quiet_window_list(bounds: WindowObservationBounds, report_window: Duration) {
let snap = WindowChangeDetector::capture_from(HashSet::new(), Some(7), false, None);
let _ = snap.detect_bounded_reporting(bounds, report_window, || (Vec::new(), Some(7)));
- end_tail();
+ focus_arbiter::end_detached();
}
/// The report window of a direct call. Support for the step-latency benchmark.
@@ -941,7 +902,7 @@ mod tests {
#[test]
fn a_quiet_poll_returns_after_the_report_window_and_detaches_the_rest() {
let _serial = lock(&TAIL_TEST_LOCK);
- end_tail();
+ focus_arbiter::end_detached();
let snap = WindowChangeDetector::capture_from(HashSet::from([1]), Some(7), false, None);
let started = Instant::now();
let changes = snap
@@ -956,9 +917,9 @@ mod tests {
elapsed < Duration::from_millis(1500),
"returned after {elapsed:?}"
);
- assert!(lock(&TAIL).is_some(), "the remainder runs detached");
- end_tail();
- assert!(lock(&TAIL).is_none());
+ assert!(focus_arbiter::has_detached(), "the remainder runs detached");
+ focus_arbiter::end_detached();
+ assert!(!focus_arbiter::has_detached());
}
/// A step of a batch returns after the shorter batch report window, and
@@ -972,7 +933,7 @@ mod tests {
let _serial = lock(&TAIL_TEST_LOCK);
let mut elapsed = Duration::ZERO;
for _ in 0..5 {
- end_tail();
+ focus_arbiter::end_detached();
let snap = WindowChangeDetector::capture_from(HashSet::from([1]), Some(7), false, None);
let started = Instant::now();
let changes = snap.detect_bounded_reporting(
@@ -984,12 +945,12 @@ mod tests {
assert!(changes.polled);
assert!(!changes.needs_restore());
assert!(elapsed >= BATCH_REPORT_WINDOW, "returned after {elapsed:?}");
- assert!(lock(&TAIL).is_some(), "the remainder runs detached");
+ assert!(focus_arbiter::has_detached(), "the remainder runs detached");
if elapsed < REPORT_WINDOW {
break;
}
}
- end_tail();
+ focus_arbiter::end_detached();
assert!(
elapsed < REPORT_WINDOW,
"a batched step waited as long as a direct call: {elapsed:?}"
@@ -1001,7 +962,7 @@ mod tests {
fn a_batched_poll_still_reports_a_window_that_opens_quickly() {
use cua_driver_core::step_pacing::BATCH_REPORT_WINDOW;
let _serial = lock(&TAIL_TEST_LOCK);
- end_tail();
+ focus_arbiter::end_detached();
let started = Instant::now();
let snap = WindowChangeDetector::capture_from(HashSet::from([1]), Some(7), false, None);
let changes = snap.detect_bounded_reporting(
@@ -1027,7 +988,7 @@ mod tests {
#[test]
fn a_skipped_wait_returns_at_once_and_watches_detached() {
let _serial = lock(&TAIL_TEST_LOCK);
- end_tail();
+ focus_arbiter::end_detached();
lock(&LATE).take();
let opened = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let observed_opened = opened.clone();
@@ -1055,7 +1016,7 @@ mod tests {
"returned after {elapsed:?}"
);
assert_eq!(changes.result_suffix(), DEFERRED_NOTE);
- assert!(lock(&TAIL).is_some(), "the deadline runs detached");
+ assert!(focus_arbiter::has_detached(), "the deadline runs detached");
opened.store(true, Ordering::SeqCst);
let wait_until = Instant::now() + Duration::from_secs(2);
while lock(&LATE).is_none() && Instant::now() < wait_until {
@@ -1065,21 +1026,21 @@ mod tests {
take_late().is_some_and(|late| late.new_windows.len() == 1),
"the detached watch records the late window"
);
- end_tail();
+ focus_arbiter::end_detached();
}
/// 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();
+ focus_arbiter::end_detached();
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());
+ assert!(!focus_arbiter::has_detached());
}
/// A window that opens after the result returned is reported on the next
@@ -1087,7 +1048,7 @@ mod tests {
#[test]
fn a_late_window_is_reported_on_the_next_result() {
let _serial = lock(&TAIL_TEST_LOCK);
- end_tail();
+ focus_arbiter::end_detached();
lock(&LATE).take();
let opened = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let observed_opened = opened.clone();
@@ -1113,7 +1074,7 @@ mod tests {
}
let mut next =
WindowChangeDetector::capture_from(HashSet::from([1, 2]), Some(7), false, None);
- end_tail();
+ focus_arbiter::end_detached();
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")
@@ -1128,9 +1089,9 @@ mod tests {
/// 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() {
+ fn end_detached_stops_the_detached_observation() {
let _serial = lock(&TAIL_TEST_LOCK);
- end_tail();
+ focus_arbiter::end_detached();
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));
@@ -1142,7 +1103,7 @@ mod tests {
(vec![win(1, 7, "App", "Main")], Some(7))
},
);
- end_tail();
+ focus_arbiter::end_detached();
std::thread::sleep(Duration::from_millis(40));
let after_end = observations.load(Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(80));