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
feat(cua-driver): fast path with act-time target guards, behind a default-off flag (CUA-3102) (#6332)
cua-agents[bot]a0364e60f721
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/batch-recording-and-settings.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/batch-recording-and-settings.mdxindex 2d88456ac3..9f82a7dd84 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools/batch-recording-and-settings.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools/batch-recording-and-settings.mdx@@ -363,6 +363,7 @@ Returns the full updated config in the same shape as `get_config`.| <span id="set_config--cursor-motion-style"></span>`cursor.motion.style` | `"signature_arc" \| "spring_settle" \| "magnetic" \| "comet_swoop" \| "adaptive" \| "classic"` | | Saved default cursor motion style for new sessions. Overridden by start_session cursor_motion and set_agent_cursor_motion; reduced motion always wins. Built-in default: signature_arc. || <span id="set_config--cursor-motion-timing"></span>`cursor.motion.timing` | `"native" \| "fitts" \| "fixed" \| "relaxed" \| "steady" \| "calm" \| "deliberate"` | | Saved default cursor move timing for new sessions. Built-in default: steady (a 600 ms floor on every move). || <span id="set_config--cursor-rotate"></span>`cursor.rotate` | `"off" \| "lean" \| "heading" \| "on" \| "default"` | | Agent cursor rotation while it moves: heading (default) points the tip along the path; lean tilts the arrow at most 30 degrees toward where it is going (on is the same as heading). Both return upright before arrival, so clicks, typing and scrolling stay upright. off: the arrow always stays upright. Applies immediately to every cursor. |+| <span id="set_config--fast_path"></span>`fast_path` | `"off" \| "shadow" \| "guard" \| "on"` | | Experimental fast path (default off). shadow: check cached targets at act time and report would-refuse verdicts; guard: refuse an action whose target changed since it was read (target_changed); on: guard, plus a small delta in each action result and tree-only re-reads. Runtime only, not saved; env CUA_DRIVER_FAST_PATH seeds it at start. || <span id="set_config--max_image_dimension"></span>`max_image_dimension` | `integer` | | Max dimension for screenshot resizing (0 = no limit). || <span id="set_config--session"></span>`session` | `string` | | For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session. |diff --git a/libs/cua-driver/contract/manifest.json b/libs/cua-driver/contract/manifest.jsonindex 7fc22c7b29..a90b7e8953 100644--- a/libs/cua-driver/contract/manifest.json+++ b/libs/cua-driver/contract/manifest.json@@ -233,6 +233,9 @@"null"]},+ "fast_path": {+ "type": "object"+ },"hint": {"type": ["string",@@ -674,6 +677,9 @@"null"]},+ "fast_path": {+ "type": "object"+ },"hint": {"type": ["string",@@ -2226,6 +2232,9 @@"null"]},+ "fast_path": {+ "type": "object"+ },"hint": {"type": ["string",@@ -2457,6 +2466,9 @@"null"]},+ "fast_path": {+ "type": "object"+ },"hint": {"type": ["string",@@ -3087,6 +3099,9 @@"null"]},+ "fast_path": {+ "type": "object"+ },"hint": {"type": ["string",@@ -3830,6 +3845,9 @@"null"]},+ "fast_path": {+ "type": "object"+ },"hint": {"type": ["string",@@ -4105,6 +4123,9 @@"null"]},+ "fast_path": {+ "type": "object"+ },"hint": {"type": ["string",@@ -4753,6 +4774,9 @@"null"]},+ "fast_path": {+ "type": "object"+ },"hint": {"type": ["string",@@ -5399,6 +5423,9 @@"null"]},+ "fast_path": {+ "type": "object"+ },"hint": {"type": ["string",diff --git a/libs/cua-driver/python/src/cua_driver/_native_contract.py b/libs/cua-driver/python/src/cua_driver/_native_contract.pyindex 9f9abc657b..5d3017358b 100644--- a/libs/cua-driver/python/src/cua_driver/_native_contract.py+++ b/libs/cua-driver/python/src/cua_driver/_native_contract.py@@ -1537,7 +1537,7 @@ class _UniffiFfiConverterOptionalTypeActionNextCall(_UniffiConverterRustBuffer):@dataclassclass ActionResult:- def __init__(self, *, effect:ActionEffect, route:ActionRoute, delivery:typing.Optional[ActionDelivery], evidence:typing.Optional[typing.List[ActionEvidence]], escalation:typing.Optional[ActionEscalation], summary:typing.Optional[str], error:typing.Optional[ActionError], hint:typing.Optional[str], next_call:typing.Optional[ActionNextCall]):+ def __init__(self, *, effect:ActionEffect, route:ActionRoute, delivery:typing.Optional[ActionDelivery], evidence:typing.Optional[typing.List[ActionEvidence]], escalation:typing.Optional[ActionEscalation], summary:typing.Optional[str], error:typing.Optional[ActionError], hint:typing.Optional[str], next_call:typing.Optional[ActionNextCall], fast_path:typing.Optional[str]):self.effect = effectself.route = routeself.delivery = delivery@@ -1547,12 +1547,13 @@ class ActionResult:self.error = errorself.hint = hintself.next_call = next_call+ self.fast_path = fast_pathdef __str__(self):- return "ActionResult(effect={}, route={}, delivery={}, evidence={}, escalation={}, summary={}, error={}, hint={}, next_call={})".format(self.effect, self.route, self.delivery, self.evidence, self.escalation, self.summary, self.error, self.hint, self.next_call)+ return "ActionResult(effect={}, route={}, delivery={}, evidence={}, escalation={}, summary={}, error={}, hint={}, next_call={}, fast_path={})".format(self.effect, self.route, self.delivery, self.evidence, self.escalation, self.summary, self.error, self.hint, self.next_call, self.fast_path)def __eq__(self, other):if self.effect != other.effect:return False@@ -1572,6 +1573,8 @@ class ActionResult:return Falseif self.next_call != other.next_call:return False+ if self.fast_path != other.fast_path:+ return Falsereturn Trueclass _UniffiFfiConverterTypeActionResult(_UniffiConverterRustBuffer):@@ -1587,6 +1590,7 @@ class _UniffiFfiConverterTypeActionResult(_UniffiConverterRustBuffer):error=_UniffiFfiConverterOptionalTypeActionError.read(buf),hint=_UniffiFfiConverterOptionalString.read(buf),next_call=_UniffiFfiConverterOptionalTypeActionNextCall.read(buf),+ fast_path=_UniffiFfiConverterOptionalString.read(buf),)@staticmethod@@ -1600,6 +1604,7 @@ class _UniffiFfiConverterTypeActionResult(_UniffiConverterRustBuffer):_UniffiFfiConverterOptionalTypeActionError.check_lower(value.error)_UniffiFfiConverterOptionalString.check_lower(value.hint)_UniffiFfiConverterOptionalTypeActionNextCall.check_lower(value.next_call)+ _UniffiFfiConverterOptionalString.check_lower(value.fast_path)@staticmethoddef write(value, buf):@@ -1612,6 +1617,7 @@ class _UniffiFfiConverterTypeActionResult(_UniffiConverterRustBuffer):_UniffiFfiConverterOptionalTypeActionError.write(value.error, buf)_UniffiFfiConverterOptionalString.write(value.hint, buf)_UniffiFfiConverterOptionalTypeActionNextCall.write(value.next_call, buf)+ _UniffiFfiConverterOptionalString.write(value.fast_path, buf)class _UniffiFfiConverterBoolean:@classmethoddiff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rsindex de182f9142..cfa8e50143 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs@@ -707,6 +707,17 @@ pub struct ActionResult {/// or a call that keeps the user's window where it is).#[serde(default, skip_serializing_if = "Option::is_none")]pub next_call: Option<ActionNextCall>,+ /// Present only when the `fast_path` config key is `on`: the check cost,+ /// the target class and the changed regions since the last read, as one+ /// JSON object. Absent when the flag is off, so default results are+ /// unchanged.+ #[serde(+ default,+ skip_serializing_if = "Option::is_none",+ with = "optional_json_object_text"+ )]+ #[schemars(schema_with = "object_schema")]+ pub fast_path: Option<String>,}/// A call an agent can make next: `{tool, arguments}`.@@ -747,6 +758,33 @@ mod json_object_text {}}+/// Serde adapter: an optional JSON object on the wire, JSON text in the record.+mod optional_json_object_text {+ use serde::{Deserialize, Deserializer, Serializer};+ use serde_json::Value;++ pub fn serialize<S: Serializer>(+ text: &Option<String>,+ serializer: S,+ ) -> Result<S::Ok, S::Error> {+ match text {+ Some(text) => super::json_object_text::serialize(text, serializer),+ None => serializer.serialize_none(),+ }+ }++ pub fn deserialize<'de, D: Deserializer<'de>>(+ deserializer: D,+ ) -> Result<Option<String>, D::Error> {+ Ok(+ Option::<Value>::deserialize(deserializer)?.and_then(|v| match v {+ Value::Object(_) => Some(v.to_string()),+ _ => None,+ }),+ )+ }+}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ActionResultValidationError {ConfirmedRequiresEvidence,@@ -903,6 +941,7 @@ mod tests {error: None,hint: None,next_call: None,+ fast_path: None,}}@@ -963,6 +1002,7 @@ mod tests {"error","escalation","evidence",+ "fast_path","hint","next_call","route",diff --git a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.tomlindex 67f4be712a..1d25b9267a 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml+++ b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml@@ -82,3 +82,8 @@ windows = { version = "0.58", features = [[dev-dependencies]tokio = { workspace = true, features = ["test-util"] }++# `fast_path_standalone` lets the std-only fast_path checks compile alone+# with `rustc --test` (no workspace build needed); see fast_path/mod.rs.+[lints.rust]+unexpected_cfgs = { level = "warn", check-cfg = ["cfg(fast_path_standalone)"] }diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rsindex 424a9061cd..02120f2f53 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs@@ -460,6 +460,7 @@ impl ActionExecutionRecord {// The dispatch seam adds these after the record is projected.hint: None,next_call: None,+ fast_path: None,})}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/change.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/change.rsnew file mode 100644index 0000000000..72b263b510--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/change.rs@@ -0,0 +1,152 @@+//! What changed after a sparse-target action: compare low-resolution+//! thumbnails taken before and after, and return the padded box of the+//! changed tiles (in full-resolution window pixels).++use super::pixel::GrayImage;++#[derive(Clone, Copy, Debug, PartialEq)]+pub enum ChangeRegion {+ /// Nothing changed: the click may have done nothing.+ Unchanged,+ /// `[x, y, w, h]` in full-resolution window pixels.+ Region {+ x: usize,+ y: usize,+ w: usize,+ h: usize,+ },+ /// More than `whole_fraction` of the window changed.+ Whole,+}++#[derive(Clone, Copy, Debug)]+pub struct ChangeConfig {+ /// Thumbnail scale divisor (8 = one-eighth).+ pub divisor: usize,+ /// Tile side in thumbnail pixels.+ pub tile: usize,+ /// Mean per-tile difference (0 to 255) above which a tile changed.+ pub threshold: f64,+ /// Padding around the box, in full-resolution pixels.+ pub pad: usize,+ pub whole_fraction: f64,+}++impl Default for ChangeConfig {+ fn default() -> Self {+ Self {+ divisor: 8,+ tile: 4,+ threshold: 6.0,+ pad: 16,+ whole_fraction: 0.4,+ }+ }+}++/// Make the one-eighth thumbnail of a full window image.+pub fn thumbnail(full: &GrayImage, cfg: &ChangeConfig) -> GrayImage {+ full.resize(+ (full.width / cfg.divisor).max(1),+ (full.height / cfg.divisor).max(1),+ )+}++pub fn changed_region(+ before: &GrayImage,+ after: &GrayImage,+ full_w: usize,+ full_h: usize,+ cfg: &ChangeConfig,+) -> ChangeRegion {+ if before.width != after.width || before.height != after.height {+ return ChangeRegion::Whole;+ }+ let (w, h, t) = (before.width, before.height, cfg.tile.max(1));+ let (tiles_x, tiles_y) = (w.div_ceil(t), h.div_ceil(t));+ let mut changed = 0usize;+ let (mut min_x, mut min_y, mut max_x, mut max_y) = (usize::MAX, usize::MAX, 0usize, 0usize);+ for ty in 0..tiles_y {+ for tx in 0..tiles_x {+ let (x0, y0) = (tx * t, ty * t);+ let (x1, y1) = ((x0 + t).min(w), (y0 + t).min(h));+ let mut sum = 0u32;+ for y in y0..y1 {+ for x in x0..x1 {+ sum += (before.get(x, y) as i32 - after.get(x, y) as i32).unsigned_abs();+ }+ }+ if sum as f64 / ((x1 - x0) * (y1 - y0)) as f64 > cfg.threshold {+ changed += 1;+ min_x = min_x.min(x0);+ min_y = min_y.min(y0);+ max_x = max_x.max(x1);+ max_y = max_y.max(y1);+ }+ }+ }+ if changed == 0 {+ return ChangeRegion::Unchanged;+ }+ let sx = full_w as f64 / w as f64;+ let sy = full_h as f64 / h as f64;+ let x = ((min_x as f64 * sx) as usize).saturating_sub(cfg.pad);+ let y = ((min_y as f64 * sy) as usize).saturating_sub(cfg.pad);+ let x1 = ((max_x as f64 * sx) as usize + cfg.pad).min(full_w);+ let y1 = ((max_y as f64 * sy) as usize + cfg.pad).min(full_h);+ if ((x1 - x) * (y1 - y)) as f64 > cfg.whole_fraction * (full_w * full_h) as f64 {+ return ChangeRegion::Whole;+ }+ ChangeRegion::Region {+ x,+ y,+ w: x1 - x,+ h: y1 - y,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn nothing_changed() {+ let a = GrayImage::filled(100, 80, 120);+ assert_eq!(+ changed_region(&a, &a.clone(), 800, 640, &ChangeConfig::default()),+ ChangeRegion::Unchanged+ );+ }++ #[test]+ fn a_small_change_maps_back_to_full_resolution() {+ let a = GrayImage::filled(100, 80, 120);+ let mut b = a.clone();+ b.fill_rect(40, 20, 8, 8, 255);+ match changed_region(&a, &b, 800, 640, &ChangeConfig::default()) {+ ChangeRegion::Region { x, y, w, h } => {+ assert!(x <= 320 && x + w >= 384, "{x} {w}");+ assert!(y <= 160 && y + h >= 224, "{y} {h}");+ assert!(w < 200 && h < 200);+ }+ other => panic!("{other:?}"),+ }+ }++ #[test]+ fn a_page_change_is_whole() {+ let a = GrayImage::filled(100, 80, 120);+ let b = GrayImage::filled(100, 80, 10);+ assert_eq!(+ changed_region(&a, &b, 800, 640, &ChangeConfig::default()),+ ChangeRegion::Whole+ );+ }++ #[test]+ fn thumbnail_is_one_eighth() {+ let full = GrayImage::filled(800, 640, 1);+ let t = thumbnail(&full, &ChangeConfig::default());+ assert_eq!((t.width, t.height), (100, 80));+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/classify.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/classify.rsnew file mode 100644index 0000000000..d7d0293d03--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/classify.rs@@ -0,0 +1,200 @@+//! Per-target choice of guard: rich tree, sparse tree, or a remote surface.++use super::Rect;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TargetClass {+ /// The tree describes the target: AX guard.+ Rich,+ /// Little or no tree at the point: window guards plus the pixel check.+ Sparse,+ /// A whole-window image with no children (remote desktop, VNC): sparse,+ /// with the wider remote tolerance.+ Remote,+}++impl TargetClass {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Rich => "rich",+ Self::Sparse => "sparse",+ Self::Remote => "remote",+ }+ }+ pub fn needs_pixel_check(self) -> bool {+ self != Self::Rich+ }+}++/// The element a hit-test returned at the point.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct HitInfo {+ pub role: Option<String>,+ pub has_label: bool,+ pub has_value: bool,+ pub has_identifier: bool,+ pub frame: Option<Rect>,+ /// The hit-test returned the window element itself.+ pub is_window: bool,+ pub child_count: Option<usize>,+}++/// Cheap stats from the last walk of the window.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct TreeStats {+ pub elements: usize,+ /// Elements whose frame is 1 pt tall or less.+ pub thin_frames: usize,+}++const GENERIC_ROLES: &[&str] = &[+ "AXGroup",+ "AXUnknown",+ "AXImage",+ "AXScrollArea",+ "AXLayoutArea",+ "AXSplitGroup",+ // UIA / AT-SPI equivalents+ "Pane",+ "Custom",+ "Image",+ "Group",+ "panel",+ "filler",+ "canvas",+ "drawing area",+ "image",+ "unknown",+];++pub fn is_generic_role(role: &str) -> bool {+ GENERIC_ROLES.iter().any(|g| g.eq_ignore_ascii_case(role))+}++pub fn classify(hit: Option<&HitInfo>, stats: Option<&TreeStats>, window: Rect) -> TargetClass {+ let Some(hit) = hit else {+ return TargetClass::Sparse;+ };+ let covers = |fraction: f64| {+ hit.frame+ .map(|f| window.area() > 0.0 && f.area() / window.area() > fraction)+ .unwrap_or(false)+ };+ let role = hit.role.as_deref().unwrap_or("");+ let image_like = matches!(+ role,+ "AXImage" | "Image" | "image" | "canvas" | "AXGroup" | "Pane" | "Custom"+ );+ if image_like && hit.child_count == Some(0) && covers(0.6) && !hit.has_label {+ return TargetClass::Remote;+ }+ if let Some(stats) = stats {+ if stats.elements < 10 || (stats.elements > 0 && stats.thin_frames * 2 > stats.elements) {+ return TargetClass::Sparse;+ }+ }+ if hit.is_window || role.is_empty() {+ return TargetClass::Sparse;+ }+ let anonymous = !hit.has_label && !hit.has_value && !hit.has_identifier;+ if is_generic_role(role) && anonymous {+ return TargetClass::Sparse;+ }+ if covers(0.25) && is_generic_role(role) {+ return TargetClass::Sparse;+ }+ TargetClass::Rich+}++#[cfg(test)]+mod tests {+ use super::*;++ const WIN: Rect = Rect {+ x: 0.0,+ y: 0.0,+ w: 1000.0,+ h: 800.0,+ };+ const RICH: TreeStats = TreeStats {+ elements: 120,+ thin_frames: 3,+ };++ fn hit(role: &str) -> HitInfo {+ HitInfo {+ role: Some(role.into()),+ has_label: true,+ frame: Some(Rect::new(10.0, 10.0, 80.0, 24.0)),+ ..Default::default()+ }+ }++ #[test]+ fn labelled_button_is_rich() {+ assert_eq!(+ classify(Some(&hit("AXButton")), Some(&RICH), WIN),+ TargetClass::Rich+ );+ }++ #[test]+ fn no_hit_or_window_hit_is_sparse() {+ assert_eq!(classify(None, Some(&RICH), WIN), TargetClass::Sparse);+ let mut h = hit("AXWindow");+ h.is_window = true;+ assert_eq!(classify(Some(&h), Some(&RICH), WIN), TargetClass::Sparse);+ }++ #[test]+ fn anonymous_group_and_big_container_are_sparse() {+ let mut h = hit("AXGroup");+ h.has_label = false;+ assert_eq!(classify(Some(&h), Some(&RICH), WIN), TargetClass::Sparse);+ let mut h = hit("AXScrollArea");+ h.frame = Some(Rect::new(0.0, 0.0, 900.0, 700.0));+ assert_eq!(classify(Some(&h), Some(&RICH), WIN), TargetClass::Sparse);+ }++ #[test]+ fn tiny_or_degraded_trees_are_sparse_everywhere() {+ let small = TreeStats {+ elements: 6,+ thin_frames: 0,+ };+ assert_eq!(+ classify(Some(&hit("AXButton")), Some(&small), WIN),+ TargetClass::Sparse+ );+ let thin = TreeStats {+ elements: 50,+ thin_frames: 40,+ };+ assert_eq!(+ classify(Some(&hit("AXButton")), Some(&thin), WIN),+ TargetClass::Sparse+ );+ }++ #[test]+ fn whole_window_image_without_children_is_remote() {+ let h = HitInfo {+ role: Some("AXImage".into()),+ frame: Some(Rect::new(0.0, 0.0, 1000.0, 780.0)),+ child_count: Some(0),+ ..Default::default()+ };+ assert_eq!(+ classify(+ Some(&h),+ Some(&TreeStats {+ elements: 3,+ thin_frames: 0+ }),+ WIN+ ),+ TargetClass::Remote+ );+ assert!(TargetClass::Remote.needs_pixel_check());+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/fingerprint.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/fingerprint.rsnew file mode 100644index 0000000000..f94f3c214a--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/fingerprint.rs@@ -0,0 +1,274 @@+//! AX guard: a small fingerprint per element at read time, compared with the+//! live element right before acting.++use super::reason::{Reason, Verdict};+use super::Rect;++/// What the agent saw. Captured from the walk that minted the token, so it+/// costs nothing extra at read time.+#[derive(Clone, Debug, PartialEq, Default)]+pub struct ElementFingerprint {+ pub role: String,+ pub subrole: Option<String>,+ /// Title, or description when the title is empty.+ pub label: Option<String>,+ pub identifier: Option<String>,+ pub frame: Option<Rect>,+ /// Index of the nearest actionable ancestor in the same snapshot.+ pub parent_index: Option<usize>,+ /// The parent's label, so two "Delete" buttons in different rows differ.+ pub parent_label: Option<String>,+}++/// The same attributes read from the live element at act time.+#[derive(Clone, Debug, PartialEq, Default)]+pub struct ElementObservation {+ /// The retained reference still answers (not `kAXErrorInvalidUIElement`).+ pub valid: bool,+ pub role: Option<String>,+ pub subrole: Option<String>,+ pub label: Option<String>,+ pub identifier: Option<String>,+ pub frame: Option<Rect>,+ /// `None` when the parent was not read (cheap path).+ pub parent_label: Option<Option<String>>,+}++/// How the action reaches the element.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Delivery {+ /// AXPress / UIA Invoke / AT-SPI action on the reference: position does+ /// not matter, identity does.+ Semantic,+ /// A pointer event at a point: position matters too.+ Pixel,+}++/// The outcome of a hit-test at the click point (pixel delivery).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum HitOutcome {+ /// The target or one of its descendants (within 5 ancestors).+ Target,+ Other,+ Nothing,+}++/// Frame tolerance: 2 pt, or 10% of the element's size, whichever is larger.+pub fn tolerance(extent: f64) -> f64 {+ (extent.abs() * 0.10).max(2.0)+}++fn norm(s: &Option<String>) -> Option<String> {+ s.as_deref()+ .map(|v| v.split_whitespace().collect::<Vec<_>>().join(" "))+ .filter(|v| !v.is_empty())+}++pub fn verify_element(+ fp: &ElementFingerprint,+ now: &ElementObservation,+ delivery: Delivery,+ hit: Option<HitOutcome>,+) -> Verdict {+ if !now.valid {+ return Verdict::refuse(Reason::Gone, "the element reference is no longer valid");+ }+ if let Some(role) = now.role.as_deref() {+ if role != fp.role {+ return Verdict::refuse(+ Reason::RoleChanged,+ format!("role was {} and is now {role}", fp.role),+ );+ }+ }+ if fp.subrole.is_some() && now.subrole.is_some() && fp.subrole != now.subrole {+ return Verdict::refuse(Reason::RoleChanged, "subrole changed");+ }+ if let (Some(a), Some(b)) = (&fp.identifier, &now.identifier) {+ if a != b {+ return Verdict::refuse(+ Reason::Relabelled,+ format!("identifier was {a:?} and is now {b:?}"),+ );+ }+ }+ let (was, is) = (norm(&fp.label), norm(&now.label));+ if was != is {+ return Verdict::refuse(+ Reason::Relabelled,+ format!(+ "label was {:?} and is now {:?}",+ was.unwrap_or_default(),+ is.unwrap_or_default()+ ),+ );+ }+ if let Some(parent) = &now.parent_label {+ if norm(parent) != norm(&fp.parent_label) {+ return Verdict::refuse(+ Reason::Relabelled,+ "the element now sits in another container",+ );+ }+ }+ if delivery == Delivery::Semantic {+ return Verdict::Ok;+ }++ let (Some(old), Some(new)) = (fp.frame, now.frame) else {+ return Verdict::refuse(Reason::Offscreen, "the element has no frame now");+ };+ if new.w <= 0.0 || new.h <= 0.0 {+ return Verdict::refuse(Reason::Offscreen, "the element has an empty frame now");+ }+ if (new.w - old.w).abs() > tolerance(old.w) || (new.h - old.h).abs() > tolerance(old.h) {+ return Verdict::refuse(+ Reason::Resized,+ format!(+ "size was {:.0}x{:.0} and is now {:.0}x{:.0}",+ old.w, old.h, new.w, new.h+ ),+ );+ }+ let dx = new.x - old.x;+ let dy = new.y - old.y;+ if dx.abs() > tolerance(old.w) || dy.abs() > tolerance(old.h) {+ // Identity is proven above; only the position changed.+ return Verdict::Relocated { dx, dy };+ }+ match hit {+ Some(HitOutcome::Other) => {+ Verdict::refuse(Reason::HitMismatch, "another element is at the click point")+ }+ Some(HitOutcome::Nothing) => {+ Verdict::refuse(Reason::HitMismatch, "nothing is at the click point")+ }+ _ => Verdict::Ok,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn fp() -> ElementFingerprint {+ ElementFingerprint {+ role: "AXButton".into(),+ label: Some("Save".into()),+ frame: Some(Rect::new(100.0, 100.0, 80.0, 24.0)),+ parent_label: Some("Toolbar".into()),+ ..Default::default()+ }+ }++ fn same() -> ElementObservation {+ ElementObservation {+ valid: true,+ role: Some("AXButton".into()),+ label: Some("Save".into()),+ frame: Some(Rect::new(100.0, 100.0, 80.0, 24.0)),+ ..Default::default()+ }+ }++ #[test]+ fn unchanged_element_passes_both_deliveries() {+ assert!(verify_element(&fp(), &same(), Delivery::Semantic, None).is_ok());+ assert!(verify_element(&fp(), &same(), Delivery::Pixel, Some(HitOutcome::Target)).is_ok());+ }++ #[test]+ fn each_reason_is_reported() {+ let mut o = same();+ o.valid = false;+ assert_eq!(+ verify_element(&fp(), &o, Delivery::Semantic, None).reason(),+ Some(Reason::Gone)+ );+ let mut o = same();+ o.role = Some("AXCheckBox".into());+ assert_eq!(+ verify_element(&fp(), &o, Delivery::Semantic, None).reason(),+ Some(Reason::RoleChanged)+ );+ let mut o = same();+ o.label = Some("Delete".into());+ assert_eq!(+ verify_element(&fp(), &o, Delivery::Semantic, None).reason(),+ Some(Reason::Relabelled)+ );+ let mut o = same();+ o.frame = Some(Rect::new(100.0, 100.0, 160.0, 24.0));+ assert_eq!(+ verify_element(&fp(), &o, Delivery::Pixel, None).reason(),+ Some(Reason::Resized)+ );+ let mut o = same();+ o.frame = None;+ assert_eq!(+ verify_element(&fp(), &o, Delivery::Pixel, None).reason(),+ Some(Reason::Offscreen)+ );+ assert_eq!(+ verify_element(&fp(), &same(), Delivery::Pixel, Some(HitOutcome::Other)).reason(),+ Some(Reason::HitMismatch)+ );+ }++ #[test]+ fn whitespace_only_label_differences_are_ignored() {+ let mut o = same();+ o.label = Some(" Save ".into());+ assert!(verify_element(&fp(), &o, Delivery::Semantic, None).is_ok());+ }++ #[test]+ fn tolerance_edges() {+ // 10% of 80 = 8 pt horizontally, 2.4 pt vertically.+ let mut o = same();+ o.frame = Some(Rect::new(107.9, 102.3, 80.0, 24.0));+ assert!(verify_element(&fp(), &o, Delivery::Pixel, Some(HitOutcome::Target)).is_ok());+ o.frame = Some(Rect::new(108.1, 100.0, 80.0, 24.0));+ assert!(matches!(+ verify_element(&fp(), &o, Delivery::Pixel, None),+ Verdict::Relocated { .. }+ ));+ // Tiny elements still get 2 pt.+ assert_eq!(tolerance(5.0), 2.0);+ }++ #[test]+ fn semantic_delivery_ignores_moves() {+ let mut o = same();+ o.frame = Some(Rect::new(300.0, 100.0, 80.0, 24.0));+ assert!(verify_element(&fp(), &o, Delivery::Semantic, None).is_ok());+ assert_eq!(+ verify_element(&fp(), &o, Delivery::Pixel, None),+ Verdict::Relocated { dx: 200.0, dy: 0.0 }+ );+ }++ #[test]+ fn identical_labels_are_told_apart_by_parent() {+ let mut o = same();+ o.parent_label = Some(Some("Row 4".into()));+ assert_eq!(+ verify_element(&fp(), &o, Delivery::Semantic, None).reason(),+ Some(Reason::Relabelled)+ );+ o.parent_label = Some(Some("Toolbar".into()));+ assert!(verify_element(&fp(), &o, Delivery::Semantic, None).is_ok());+ }++ #[test]+ fn identifier_change_is_relabelled_even_with_same_label() {+ let mut f = fp();+ f.identifier = Some("row-3".into());+ let mut o = same();+ o.identifier = Some("row-9".into());+ assert_eq!(+ verify_element(&f, &o, Delivery::Semantic, None).reason(),+ Some(Reason::Relabelled)+ );+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/mod.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/mod.rsnew file mode 100644index 0000000000..683d23d39b--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/mod.rs@@ -0,0 +1,243 @@+//! Fast path: act on cached targets with act-time guards instead of a fresh+//! full window snapshot before every action (CUA-3102).+//!+//! Everything in this module is platform-free and std-only. Platforms read+//! the live state (AX/UIA/AT-SPI attributes, window list, pixel crops) and+//! hand it to these checks; the checks decide whether acting is safe.+//!+//! Modes (`fast_path` config key, env `CUA_DRIVER_FAST_PATH`):+//! - `off` (default): no checks, no behaviour change.+//! - `shadow`: run the checks and report would-refuse verdicts in the result,+//! never refuse.+//! - `guard`: enforce the checks; refuse with `target_changed` on mismatch.+//! - `on`: `guard`, plus a small delta in each action result and tree-only+//! re-reads unless a screenshot is asked for.++pub mod change;+pub mod classify;+pub mod fingerprint;+pub mod pixel;+pub mod pixel_guard;+pub mod reason;+pub mod store;+pub mod window;+#[cfg(not(fast_path_standalone))]+pub mod wire;++#[cfg(test)]+mod race_tests;++/// Serialises tests that change the daemon-wide mode.+#[cfg(test)]+pub(crate) fn tests_lock() -> std::sync::MutexGuard<'static, ()> {+ static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+ LOCK.lock().unwrap_or_else(|e| e.into_inner())+}++use std::sync::atomic::{AtomicU8, Ordering};++/// Axis-aligned rectangle `[x, y, w, h]` in points (or pixels where noted).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Rect {+ pub x: f64,+ pub y: f64,+ pub w: f64,+ pub h: f64,+}++impl Rect {+ pub fn new(x: f64, y: f64, w: f64, h: f64) -> Self {+ Self { x, y, w, h }+ }+ pub fn from_array(a: [f64; 4]) -> Self {+ Self::new(a[0], a[1], a[2], a[3])+ }+ pub fn center(&self) -> (f64, f64) {+ (self.x + self.w / 2.0, self.y + self.h / 2.0)+ }+ pub fn contains(&self, x: f64, y: f64) -> bool {+ x >= self.x && y >= self.y && x < self.x + self.w && y < self.y + self.h+ }+ pub fn area(&self) -> f64 {+ self.w.max(0.0) * self.h.max(0.0)+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FastPathMode {+ Off,+ Shadow,+ Guard,+ On,+}++impl FastPathMode {+ pub fn parse(raw: &str) -> Option<Self> {+ match raw.trim().to_ascii_lowercase().as_str() {+ "" | "off" | "false" | "0" => Some(Self::Off),+ "shadow" => Some(Self::Shadow),+ "guard" => Some(Self::Guard),+ "on" | "true" | "1" => Some(Self::On),+ _ => None,+ }+ }+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Off => "off",+ Self::Shadow => "shadow",+ Self::Guard => "guard",+ Self::On => "on",+ }+ }+ /// Checks run (shadow, guard, on).+ pub fn checks(self) -> bool {+ self != Self::Off+ }+ /// A mismatch refuses the action (guard, on).+ pub fn enforces(self) -> bool {+ matches!(self, Self::Guard | Self::On)+ }+ /// Action results carry a delta and re-reads skip screenshots (on).+ pub fn deltas(self) -> bool {+ self == Self::On+ }+ fn code(self) -> u8 {+ match self {+ Self::Off => 1,+ Self::Shadow => 2,+ Self::Guard => 3,+ Self::On => 4,+ }+ }+ fn from_code(code: u8) -> Option<Self> {+ match code {+ 1 => Some(Self::Off),+ 2 => Some(Self::Shadow),+ 3 => Some(Self::Guard),+ 4 => Some(Self::On),+ _ => None,+ }+ }+}++/// 0 = not initialised yet (read the env var on first use).+static MODE: AtomicU8 = AtomicU8::new(0);++pub const ENV_VAR: &str = "CUA_DRIVER_FAST_PATH";++/// The daemon-wide mode. Defaults to `off`; the env var seeds it once and+/// `set_config {fast_path}` changes it at runtime.+pub fn mode() -> FastPathMode {+ if let Some(mode) = FastPathMode::from_code(MODE.load(Ordering::Relaxed)) {+ return mode;+ }+ let seeded = std::env::var(ENV_VAR)+ .ok()+ .and_then(|raw| FastPathMode::parse(&raw))+ .unwrap_or(FastPathMode::Off);+ let _ = MODE.compare_exchange(0, seeded.code(), Ordering::Relaxed, Ordering::Relaxed);+ FastPathMode::from_code(MODE.load(Ordering::Relaxed)).unwrap_or(FastPathMode::Off)+}++pub fn set_mode(mode: FastPathMode) {+ MODE.store(mode.code(), Ordering::Relaxed);+}++/// Per-call `verify_target` override.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum VerifyTarget {+ /// Follow the daemon mode.+ Default,+ /// Enforce every applicable check, whatever the mode.+ Strict,+ /// Window guards only (live video, charts): result says `window_only`.+ Window,+ /// No checks for this call.+ Off,+}++impl VerifyTarget {+ pub fn parse(raw: Option<&str>) -> Result<Self, String> {+ match raw.map(|s| s.trim().to_ascii_lowercase()) {+ None => Ok(Self::Default),+ Some(s) if s.is_empty() || s == "default" => Ok(Self::Default),+ Some(s) if s == "strict" => Ok(Self::Strict),+ Some(s) if s == "window" => Ok(Self::Window),+ Some(s) if s == "off" => Ok(Self::Off),+ Some(other) => Err(format!(+ "verify_target must be one of default, strict, window, off (got \"{other}\")"+ )),+ }+ }+}++/// What a call should do, after combining the daemon mode and the override.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Effective {+ pub run_checks: bool,+ pub enforce: bool,+ pub pixel_check: bool,+ pub deltas: bool,+}++pub fn effective(mode: FastPathMode, verify: VerifyTarget) -> Effective {+ match verify {+ VerifyTarget::Off => Effective {+ run_checks: false,+ enforce: false,+ pixel_check: false,+ deltas: mode.deltas(),+ },+ VerifyTarget::Strict => Effective {+ run_checks: true,+ enforce: true,+ pixel_check: true,+ deltas: mode.deltas(),+ },+ VerifyTarget::Window => Effective {+ run_checks: true,+ enforce: mode.enforces() || mode == FastPathMode::Off,+ pixel_check: false,+ deltas: mode.deltas(),+ },+ VerifyTarget::Default => Effective {+ run_checks: mode.checks(),+ enforce: mode.enforces(),+ pixel_check: mode.checks(),+ deltas: mode.deltas(),+ },+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn mode_parses_and_defaults_off() {+ assert_eq!(FastPathMode::parse(""), Some(FastPathMode::Off));+ assert_eq!(FastPathMode::parse("Guard"), Some(FastPathMode::Guard));+ assert_eq!(FastPathMode::parse("on"), Some(FastPathMode::On));+ assert_eq!(FastPathMode::parse("shadow"), Some(FastPathMode::Shadow));+ assert_eq!(FastPathMode::parse("fast"), None);+ assert!(!FastPathMode::Off.checks());+ assert!(FastPathMode::Shadow.checks() && !FastPathMode::Shadow.enforces());+ assert!(FastPathMode::On.deltas() && !FastPathMode::Guard.deltas());+ }++ #[test]+ fn off_mode_runs_nothing_by_default() {+ let e = effective(FastPathMode::Off, VerifyTarget::Default);+ assert!(!e.run_checks && !e.enforce && !e.pixel_check && !e.deltas);+ }++ #[test]+ fn overrides_combine_with_mode() {+ assert!(effective(FastPathMode::Off, VerifyTarget::Strict).enforce);+ let w = effective(FastPathMode::On, VerifyTarget::Window);+ assert!(w.run_checks && w.enforce && !w.pixel_check && w.deltas);+ assert!(!effective(FastPathMode::On, VerifyTarget::Off).run_checks);+ assert!(VerifyTarget::parse(Some("bogus")).is_err());+ assert_eq!(VerifyTarget::parse(None).unwrap(), VerifyTarget::Default);+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/pixel.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/pixel.rsnew file mode 100644index 0000000000..834eef0b90--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/pixel.rs@@ -0,0 +1,450 @@+//! Greyscale crops, a perceptual hash, a normalised difference and a+//! template match. Small and allocation-light: crops are about 64 to 96 pt.++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct GrayImage {+ pub width: usize,+ pub height: usize,+ pub pixels: Vec<u8>,+}++impl GrayImage {+ pub fn new(width: usize, height: usize, pixels: Vec<u8>) -> Option<Self> {+ (width > 0 && height > 0 && pixels.len() == width * height).then_some(Self {+ width,+ height,+ pixels,+ })+ }++ pub fn filled(width: usize, height: usize, value: u8) -> Self {+ Self {+ width,+ height,+ pixels: vec![value; width * height],+ }+ }++ /// From tightly packed RGBA or BGRA (luma ignores the R/B order to+ /// within a few levels, which the tolerances absorb).+ pub fn from_rgba(width: usize, height: usize, rgba: &[u8]) -> Option<Self> {+ Self::from_strided(width, height, rgba, width * 4)+ }++ /// From 4-byte pixels with a row stride (CGImage, BGRA DIBs, XImage).+ pub fn from_strided(width: usize, height: usize, data: &[u8], stride: usize) -> Option<Self> {+ if width == 0+ || height == 0+ || stride < width * 4+ || data.len() < stride * (height - 1) + width * 4+ {+ return None;+ }+ let mut pixels = Vec::with_capacity(width * height);+ for y in 0..height {+ let row = &data[y * stride..y * stride + width * 4];+ for px in row.chunks_exact(4) {+ let l = (px[0] as u32 * 77 + px[1] as u32 * 150 + px[2] as u32 * 29) >> 8;+ pixels.push(l as u8);+ }+ }+ Some(Self {+ width,+ height,+ pixels,+ })+ }++ #[inline]+ pub fn get(&self, x: usize, y: usize) -> u8 {+ self.pixels[y * self.width + x]+ }++ /// Crop `w`x`h` at `(x, y)`; `None` unless the whole rect is inside.+ pub fn crop(&self, x: i64, y: i64, w: usize, h: usize) -> Option<GrayImage> {+ if x < 0 || y < 0 || w == 0 || h == 0 {+ return None;+ }+ let (x, y) = (x as usize, y as usize);+ if x + w > self.width || y + h > self.height {+ return None;+ }+ let mut pixels = Vec::with_capacity(w * h);+ for row in y..y + h {+ pixels.extend_from_slice(&self.pixels[row * self.width + x..row * self.width + x + w]);+ }+ Some(GrayImage {+ width: w,+ height: h,+ pixels,+ })+ }++ /// Crop a square of `size` centred on `(cx, cy)`, clamped into the image.+ pub fn crop_centered(&self, cx: f64, cy: f64, size: usize) -> Option<(GrayImage, i64, i64)> {+ let size = size.min(self.width).min(self.height);+ let x = ((cx - size as f64 / 2.0).round() as i64).clamp(0, (self.width - size) as i64);+ let y = ((cy - size as f64 / 2.0).round() as i64).clamp(0, (self.height - size) as i64);+ if !(0.0..self.width as f64).contains(&cx) || !(0.0..self.height as f64).contains(&cy) {+ return None;+ }+ self.crop(x, y, size, size).map(|c| (c, x, y))+ }++ /// Area-average resize.+ pub fn resize(&self, w: usize, h: usize) -> GrayImage {+ let mut out = Vec::with_capacity(w * h);+ for oy in 0..h {+ let y0 = oy * self.height / h;+ let y1 = ((oy + 1) * self.height / h).max(y0 + 1).min(self.height);+ for ox in 0..w {+ let x0 = ox * self.width / w;+ let x1 = ((ox + 1) * self.width / w).max(x0 + 1).min(self.width);+ let mut sum = 0u32;+ for y in y0..y1 {+ for x in x0..x1 {+ sum += self.get(x, y) as u32;+ }+ }+ out.push((sum / ((y1 - y0) * (x1 - x0)) as u32) as u8);+ }+ }+ GrayImage {+ width: w,+ height: h,+ pixels: out,+ }+ }++ /// Paint a rect (used to mask an in-content cursor before comparing).+ pub fn fill_rect(&mut self, x: i64, y: i64, w: usize, h: usize, value: u8) {+ let x0 = x.max(0) as usize;+ let y0 = y.max(0) as usize;+ let x1 = ((x + w as i64).max(0) as usize).min(self.width);+ let y1 = ((y + h as i64).max(0) as usize).min(self.height);+ for row in y0..y1 {+ for col in x0..x1 {+ self.pixels[row * self.width + col] = value;+ }+ }+ }+}++/// 64-bit difference hash (9x8 resize, compare horizontal neighbours).+pub fn dhash(img: &GrayImage) -> u64 {+ let small = img.resize(9, 8);+ let mut hash = 0u64;+ for y in 0..8 {+ for x in 0..8 {+ hash <<= 1;+ if small.get(x, y) > small.get(x + 1, y) {+ hash |= 1;+ }+ }+ }+ hash+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct CropDiff {+ pub hash_distance: u32,+ /// Mean absolute difference at 32x32, 0 to 1.+ pub mean_diff: f64,+ /// Fraction of 32x32 cells whose difference is above the cell threshold.+ pub changed_fraction: f64,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Tolerance {+ pub cell_threshold: u8,+ pub max_changed_fraction: f64,+ pub max_mean_diff: f64,+ pub max_hash_distance: u32,+}++impl Tolerance {+ /// Native windows: a blinking caret or a focus ring is under 3% of the area.+ pub const NATIVE: Tolerance = Tolerance {+ cell_threshold: 40,+ max_changed_fraction: 0.03,+ max_mean_diff: 0.03,+ max_hash_distance: 14,+ };+ /// Lossy remote-desktop streams: wider, to absorb compression noise.+ pub const REMOTE: Tolerance = Tolerance {+ cell_threshold: 56,+ max_changed_fraction: 0.06,+ max_mean_diff: 0.06,+ max_hash_distance: 22,+ };+}++pub const COMPARE_SIZE: usize = 32;++pub fn diff(a: &GrayImage, b: &GrayImage, tol: &Tolerance) -> CropDiff {+ let sa = a.resize(COMPARE_SIZE, COMPARE_SIZE);+ let sb = b.resize(COMPARE_SIZE, COMPARE_SIZE);+ let mut total = 0u64;+ let mut changed = 0usize;+ for (pa, pb) in sa.pixels.iter().zip(&sb.pixels) {+ let d = (*pa as i32 - *pb as i32).unsigned_abs();+ total += d as u64;+ if d > tol.cell_threshold as u32 {+ changed += 1;+ }+ }+ let n = (COMPARE_SIZE * COMPARE_SIZE) as f64;+ CropDiff {+ hash_distance: (dhash(a) ^ dhash(b)).count_ones(),+ mean_diff: total as f64 / n / 255.0,+ changed_fraction: changed as f64 / n,+ }+}++impl CropDiff {+ /// Same within tolerance. The hash only counts when cells also changed,+ /// so flat areas whose hash bits flip on noise do not trip it.+ pub fn same(&self, tol: &Tolerance) -> bool {+ self.changed_fraction <= tol.max_changed_fraction+ && self.mean_diff <= tol.max_mean_diff+ && !(self.hash_distance > tol.max_hash_distance+ && self.changed_fraction > tol.max_changed_fraction / 3.0)+ }+}++pub fn similar(a: &GrayImage, b: &GrayImage, tol: &Tolerance) -> bool {+ diff(a, b, tol).same(tol)+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Match {+ /// One clear match: top-left offset inside the search image and score.+ Unique { x: i64, y: i64, score: f64 },+ /// Two near-equal matches (repeated tiles, grid cells).+ Ambiguous,+ /// Nothing above the threshold, or a flat template.+ None,+}++/// NCC scores of `template` at every top-left offset in `[x0, x1] x [y0, y1]`.+fn ncc_scores(+ template: &GrayImage,+ search: &GrayImage,+ range: (usize, usize, usize, usize),+) -> Vec<(f64, i64, i64)> {+ let (tw, th) = (template.width, template.height);+ let n = (tw * th) as f64;+ let t_mean = template.pixels.iter().map(|p| *p as f64).sum::<f64>() / n;+ let t_dev: Vec<f64> = template.pixels.iter().map(|p| *p as f64 - t_mean).collect();+ let t_norm = t_dev.iter().map(|d| d * d).sum::<f64>().sqrt();+ let (x0, y0, x1, y1) = range;+ let mut scores = Vec::new();+ for oy in y0..=y1 {+ for ox in x0..=x1 {+ let (mut s_sum, mut s_sq, mut cross) = (0.0, 0.0, 0.0);+ for y in 0..th {+ let row =+ &search.pixels[(oy + y) * search.width + ox..(oy + y) * search.width + ox + tw];+ let trow = &t_dev[y * tw..(y + 1) * tw];+ for (p, t) in row.iter().zip(trow) {+ let v = *p as f64;+ s_sum += v;+ s_sq += v * v;+ cross += v * t;+ }+ }+ // sum((s - mean_s) * t_dev) == sum(s * t_dev) because sum(t_dev) == 0.+ let var = (s_sq - s_sum * s_sum / n).max(0.0);+ let denom = t_norm * var.sqrt();+ scores.push((+ if denom > 0.0 { cross / denom } else { 0.0 },+ ox as i64,+ oy as i64,+ ));+ }+ }+ scores+}++fn flat(template: &GrayImage) -> bool {+ let n = template.pixels.len() as f64;+ let mean = template.pixels.iter().map(|p| *p as f64).sum::<f64>() / n;+ let var = template+ .pixels+ .iter()+ .map(|p| (*p as f64 - mean).powi(2))+ .sum::<f64>()+ / n;+ var.sqrt() < 4.0+}++/// Normalised cross-correlation of `template` over `search`. Coarse at half+/// resolution (and the uniqueness test there), then refined at full+/// resolution around the best coarse hit, so a 96 pt search stays a few ms.+pub fn template_match(template: &GrayImage, search: &GrayImage, min_score: f64) -> Match {+ let (tw, th) = (template.width, template.height);+ if tw > search.width || th > search.height || flat(template) {+ return Match::None;+ }+ let coarse = tw >= 24 && th >= 24;+ let (t, s, f) = if coarse {+ (+ template.resize(tw / 2, th / 2),+ search.resize(search.width / 2, search.height / 2),+ 2i64,+ )+ } else {+ (template.clone(), search.clone(), 1i64)+ };+ if t.width > s.width || t.height > s.height {+ return Match::None;+ }+ let mut scores = ncc_scores(&t, &s, (0, 0, s.width - t.width, s.height - t.height));+ scores.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));+ let Some(&(best, bx, by)) = scores.first() else {+ return Match::None;+ };+ if best < min_score - 0.1 {+ return Match::None;+ }+ let min_sep = (t.width.min(t.height) as i64 / 4).max(3);+ let rival = scores+ .iter()+ .skip(1)+ .find(|(_, x, y)| (x - bx).abs() > min_sep || (y - by).abs() > min_sep);+ if let Some(&(second, _, _)) = rival {+ if second >= best - 0.05 && second >= min_score - 0.1 {+ return Match::Ambiguous;+ }+ }+ let (cx, cy) = (bx * f, by * f);+ let r = f + 1;+ let x0 = (cx - r).max(0) as usize;+ let y0 = (cy - r).max(0) as usize;+ let x1 = ((cx + r) as usize).min(search.width - tw);+ let y1 = ((cy + r) as usize).min(search.height - th);+ let mut fine = ncc_scores(template, search, (x0, y0, x1.max(x0), y1.max(y0)));+ fine.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));+ match fine.first() {+ Some(&(score, x, y)) if score >= min_score => Match::Unique { x, y, score },+ _ => Match::None,+ }+}++#[cfg(test)]+pub(crate) mod test_images {+ use super::GrayImage;++ /// A textured background (so nothing is flat) with deterministic noise.+ pub fn background(w: usize, h: usize, seed: u32) -> GrayImage {+ let mut img = GrayImage::filled(w, h, 200);+ let mut s = seed.wrapping_mul(2654435761).max(1);+ for y in 0..h {+ for x in 0..w {+ s ^= s << 13;+ s ^= s >> 17;+ s ^= s << 5;+ let grain = (s % 9) as i32 - 4;+ let stripe = if (x / 16 + y / 16) % 2 == 0 { 0 } else { 12 };+ img.pixels[y * w + x] = (200 + grain - stripe) as u8;+ }+ }+ img+ }++ /// A "button": dark rounded-ish box with a light glyph bar, at (x, y).+ pub fn draw_button(img: &mut GrayImage, x: i64, y: i64) {+ img.fill_rect(x, y, 40, 20, 40);+ img.fill_rect(x + 6, y + 8, 18, 4, 230);+ img.fill_rect(x + 28, y + 4, 6, 12, 150);+ }++ /// A different shape at the same spot.+ pub fn draw_circle_like(img: &mut GrayImage, x: i64, y: i64) {+ img.fill_rect(x + 10, y, 20, 20, 90);+ img.fill_rect(x + 4, y + 6, 32, 8, 90);+ }+}++#[cfg(test)]+mod tests {+ use super::test_images::*;+ use super::*;++ #[test]+ fn identical_crops_are_same_and_hash_is_stable() {+ let a = background(80, 80, 1);+ let d = diff(&a, &a.clone(), &Tolerance::NATIVE);+ assert_eq!(d.hash_distance, 0);+ assert!(d.same(&Tolerance::NATIVE));+ }++ #[test]+ fn a_new_shape_is_different() {+ let mut a = background(80, 80, 1);+ draw_button(&mut a, 20, 30);+ let mut b = background(80, 80, 1);+ draw_circle_like(&mut b, 20, 30);+ assert!(!similar(&a, &b, &Tolerance::NATIVE));+ }++ #[test]+ fn a_blinking_caret_is_absorbed() {+ let a = background(80, 80, 3);+ let mut b = a.clone();+ b.fill_rect(50, 30, 2, 16, 0);+ assert!(+ similar(&a, &b, &Tolerance::NATIVE),+ "{:?}",+ diff(&a, &b, &Tolerance::NATIVE)+ );+ }++ #[test]+ fn a_thin_focus_ring_is_absorbed() {+ let a = background(96, 96, 4);+ let mut b = a.clone();+ b.fill_rect(20, 20, 56, 1, 90);+ b.fill_rect(20, 75, 56, 1, 90);+ assert!(similar(&a, &b, &Tolerance::NATIVE));+ }++ #[test]+ fn template_match_finds_a_shift() {+ let mut search = background(144, 144, 5);+ draw_button(&mut search, 70, 50);+ let mut read = background(144, 144, 5);+ draw_button(&mut read, 30, 50);+ let tpl = read.crop(24, 44, 52, 32).unwrap();+ match template_match(&tpl, &search, 0.9) {+ Match::Unique { x, y, .. } => assert_eq!((x, y), (64, 44)),+ other => panic!("{other:?}"),+ }+ }++ #[test]+ fn repeated_tiles_are_ambiguous() {+ let mut search = background(160, 60, 6);+ search.pixels.iter_mut().for_each(|p| *p = 200);+ draw_button(&mut search, 10, 20);+ draw_button(&mut search, 90, 20);+ let tpl = search.crop(6, 16, 48, 28).unwrap();+ assert_eq!(template_match(&tpl, &search, 0.9), Match::Ambiguous);+ }++ #[test]+ fn flat_template_matches_nothing() {+ let flat = GrayImage::filled(20, 20, 128);+ let search = background(60, 60, 7);+ assert_eq!(template_match(&flat, &search, 0.9), Match::None);+ }++ #[test]+ fn rgba_and_resize() {+ let rgba = vec![255u8; 4 * 4 * 4];+ let img = GrayImage::from_rgba(4, 4, &rgba).unwrap();+ assert!(img.pixels.iter().all(|p| *p >= 254));+ assert_eq!(img.resize(2, 2).pixels.len(), 4);+ assert!(GrayImage::from_rgba(4, 4, &rgba[..10]).is_none());+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/pixel_guard.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/pixel_guard.rsnew file mode 100644index 0000000000..edb49cf940--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/pixel_guard.rs@@ -0,0 +1,336 @@+//! Pixel guard for sparse or no-tree targets (design note section 3).+//!+//! Compare a crop around the point from the read-time window image with+//! crops captured right before acting. Two act-time crops 50 ms apart tell+//! animation apart from a real change; a template match recovers a pure+//! shift.++use super::pixel::{diff, similar, template_match, CropDiff, GrayImage, Match, Tolerance};+use super::reason::{Reason, Verdict};++/// Captures pixels of the target window only (never the screen, so another+/// window on top cannot fool the check). Coordinates are window pixels.+pub trait CropSource {+ fn capture(&mut self, x: i64, y: i64, w: usize, h: usize) -> Option<GrayImage>;+ fn sleep_ms(&mut self, ms: u64);+}++#[derive(Clone, Debug)]+pub struct PixelGuardConfig {+ /// Crop side in window pixels (64 to 96 pt times the scale).+ pub crop: usize,+ /// Template-match search radius in window pixels (about 48 pt).+ pub search_radius: usize,+ pub stability_gap_ms: u64,+ pub settle_budget_ms: u64,+ pub tolerance: Tolerance,+ pub min_match: f64,+ /// A cursor drawn in the content, masked in every crop (window pixels).+ pub cursor_mask: Option<(i64, i64, usize, usize)>,+}++impl PixelGuardConfig {+ pub fn for_scale(scale: f64, remote: bool) -> Self {+ let s = scale.max(1.0);+ Self {+ crop: (80.0 * s).round() as usize,+ search_radius: (48.0 * s).round() as usize,+ stability_gap_ms: 50,+ settle_budget_ms: 300,+ tolerance: if remote {+ Tolerance::REMOTE+ } else {+ Tolerance::NATIVE+ },+ min_match: 0.9,+ cursor_mask: None,+ }+ }+}++#[derive(Clone, Debug, PartialEq)]+pub struct PixelCheck {+ /// `Relocated` offsets are in window pixels.+ pub verdict: Verdict,+ pub captures: u32,+ pub waited_ms: u64,+ pub diff: Option<CropDiff>,+}++fn masked(+ mut img: GrayImage,+ origin: (i64, i64),+ mask: Option<(i64, i64, usize, usize)>,+) -> GrayImage {+ if let Some((mx, my, mw, mh)) = mask {+ img.fill_rect(mx - origin.0, my - origin.1, mw, mh, 128);+ }+ img+}++pub fn check(+ read_image: &GrayImage,+ point: (f64, f64),+ cfg: &PixelGuardConfig,+ src: &mut dyn CropSource,+) -> PixelCheck {+ let mut out = PixelCheck {+ verdict: Verdict::Ok,+ captures: 0,+ waited_ms: 0,+ diff: None,+ };+ let Some((read_crop, x0, y0)) = read_image.crop_centered(point.0, point.1, cfg.crop) else {+ out.verdict = Verdict::refuse(Reason::Offscreen, "the point is outside the window image");+ return out;+ };+ let size = read_crop.width;+ let read_crop = masked(read_crop, (x0, y0), cfg.cursor_mask);++ let grab = |src: &mut dyn CropSource, out: &mut PixelCheck| {+ out.captures += 1;+ src.capture(x0, y0, size, size)+ .map(|c| masked(c, (x0, y0), cfg.cursor_mask))+ };++ let Some(mut a) = grab(src, &mut out) else {+ out.verdict = Verdict::refuse(Reason::NotVisible, "the window could not be captured");+ return out;+ };+ loop {+ src.sleep_ms(cfg.stability_gap_ms);+ out.waited_ms += cfg.stability_gap_ms;+ let Some(b) = grab(src, &mut out) else {+ out.verdict = Verdict::refuse(Reason::NotVisible, "the window could not be captured");+ return out;+ };+ if similar(&a, &b, &cfg.tolerance) {+ a = b;+ break;+ }+ if out.waited_ms >= cfg.settle_budget_ms {+ out.verdict = Verdict::refuse(+ Reason::Animating,+ format!(+ "the target area did not settle within {} ms",+ cfg.settle_budget_ms+ ),+ );+ return out;+ }+ a = b;+ }++ let d = diff(&read_crop, &a, &cfg.tolerance);+ out.diff = Some(d);+ if d.same(&cfg.tolerance) {+ return out;+ }++ // Stable but different: was it only shifted?+ let quarter = (size / 4) as i64;+ let tpl = read_crop+ .crop(quarter, quarter, size / 2, size / 2)+ .expect("centre half is inside the crop");+ let r = cfg.search_radius as i64;+ let sx = (x0 + quarter - r).max(0);+ let sy = (y0 + quarter - r).max(0);+ let sx1 = (x0 + quarter + tpl.width as i64 + r).min(read_image.width as i64);+ let sy1 = (y0 + quarter + tpl.height as i64 + r).min(read_image.height as i64);+ let search = if sx1 > sx && sy1 > sy {+ out.captures += 1;+ src.capture(sx, sy, (sx1 - sx) as usize, (sy1 - sy) as usize)+ .map(|c| masked(c, (sx, sy), cfg.cursor_mask))+ } else {+ None+ };+ let detail = format!(+ "{:.0}% of the area changed (mean difference {:.2})",+ d.changed_fraction * 100.0,+ d.mean_diff+ );+ out.verdict = match search.map(|s| template_match(&tpl, &s, cfg.min_match)) {+ Some(Match::Unique { x, y, .. }) => {+ let dx = (sx + x - (x0 + quarter)) as f64;+ let dy = (sy + y - (y0 + quarter)) as f64;+ if dx == 0.0 && dy == 0.0 {+ Verdict::refuse(Reason::RegionChanged, detail)+ } else {+ Verdict::Relocated { dx, dy }+ }+ }+ Some(Match::Ambiguous) => Verdict::refuse(+ Reason::RegionChanged,+ format!("{detail}; the target matches more than one place nearby"),+ ),+ _ => Verdict::refuse(Reason::RegionChanged, detail),+ };+ out+}++/// A `CropSource` over a sequence of whole-window frames, for tests and the+/// shadow replay: each capture reads the current frame, then advances.+#[cfg(test)]+pub(crate) struct FrameSequence {+ pub frames: Vec<GrayImage>,+ pub index: usize,+ pub slept: u64,+ /// Advance one frame every N ms of sleep (0 = advance per capture).+ pub frame_ms: u64,+}++#[cfg(test)]+impl CropSource for FrameSequence {+ fn capture(&mut self, x: i64, y: i64, w: usize, h: usize) -> Option<GrayImage> {+ let i = if self.frame_ms == 0 {+ let i = self.index.min(self.frames.len() - 1);+ self.index += 1;+ i+ } else {+ ((self.slept / self.frame_ms) as usize).min(self.frames.len() - 1)+ };+ self.frames[i].crop(x, y, w, h)+ }+ fn sleep_ms(&mut self, ms: u64) {+ self.slept += ms;+ }+}++#[cfg(test)]+mod tests {+ use super::super::pixel::test_images::*;+ use super::*;++ fn seq(frames: Vec<GrayImage>, frame_ms: u64) -> FrameSequence {+ FrameSequence {+ frames,+ index: 0,+ slept: 0,+ frame_ms,+ }+ }++ fn canvas_with_button(x: i64) -> GrayImage {+ let mut img = background(400, 300, 11);+ draw_button(&mut img, x, 140);+ img+ }++ #[test]+ fn unchanged_canvas_passes_with_two_captures() {+ let read = canvas_with_button(100);+ let mut src = seq(vec![read.clone()], 0);+ let r = check(+ &read,+ (120.0, 150.0),+ &PixelGuardConfig::for_scale(1.0, false),+ &mut src,+ );+ assert_eq!(r.verdict, Verdict::Ok);+ assert_eq!(r.captures, 2);+ assert_eq!(r.waited_ms, 50);+ }++ #[test]+ fn moving_canvas_target_is_relocated_not_clicked_at_old_spot() {+ let read = canvas_with_button(100);+ let now = canvas_with_button(140); // redrawn 40 px away+ let mut src = seq(vec![now], 0);+ let r = check(+ &read,+ (120.0, 150.0),+ &PixelGuardConfig::for_scale(1.0, false),+ &mut src,+ );+ assert_eq!(r.verdict, Verdict::Relocated { dx: 40.0, dy: 0.0 });+ }++ #[test]+ fn redrawn_as_another_shape_is_region_changed() {+ let read = canvas_with_button(100);+ let mut now = background(400, 300, 11);+ draw_circle_like(&mut now, 100, 140);+ let mut src = seq(vec![now], 0);+ let r = check(+ &read,+ (120.0, 150.0),+ &PixelGuardConfig::for_scale(1.0, false),+ &mut src,+ );+ assert_eq!(r.verdict.reason(), Some(Reason::RegionChanged));+ }++ #[test]+ fn a_spinner_that_never_settles_is_animating() {+ let read = canvas_with_button(100);+ let frames: Vec<GrayImage> = (0..20)+ .map(|i| {+ let mut f = canvas_with_button(100);+ f.fill_rect(+ 104 + (i % 4) * 8,+ 120,+ 8,+ 8,+ if i % 2 == 0 { 0 } else { 255 },+ );+ f.fill_rect(80, 100 + (i % 3) * 20, 60, 20, (i * 50 % 255) as u8);+ f+ })+ .collect();+ let mut src = seq(frames, 0);+ let r = check(+ &read,+ (120.0, 150.0),+ &PixelGuardConfig::for_scale(1.0, false),+ &mut src,+ );+ assert_eq!(r.verdict.reason(), Some(Reason::Animating));+ assert!(r.waited_ms <= 300);+ }++ #[test]+ fn an_animation_that_settles_is_checked_after_it_settles() {+ let read = canvas_with_button(100);+ // Moving for 3 frames, then at rest 40 px right.+ let frames = vec![+ canvas_with_button(110),+ canvas_with_button(120),+ canvas_with_button(130),+ canvas_with_button(140),+ ];+ let mut src = seq(frames, 50);+ let r = check(+ &read,+ (120.0, 150.0),+ &PixelGuardConfig::for_scale(1.0, false),+ &mut src,+ );+ assert_eq!(r.verdict, Verdict::Relocated { dx: 40.0, dy: 0.0 });+ }++ #[test]+ fn uncapturable_window_is_not_visible() {+ struct Nothing;+ impl CropSource for Nothing {+ fn capture(&mut self, _: i64, _: i64, _: usize, _: usize) -> Option<GrayImage> {+ None+ }+ fn sleep_ms(&mut self, _: u64) {}+ }+ let read = canvas_with_button(100);+ let r = check(+ &read,+ (120.0, 150.0),+ &PixelGuardConfig::for_scale(1.0, false),+ &mut Nothing,+ );+ assert_eq!(r.verdict.reason(), Some(Reason::NotVisible));+ }++ #[test]+ fn hidpi_crop_scales_with_the_window() {+ let cfg = PixelGuardConfig::for_scale(2.0, false);+ assert_eq!(cfg.crop, 160);+ assert_eq!(cfg.search_radius, 96);+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/race_tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/race_tests.rsnew file mode 100644index 0000000000..72ba68a52b--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/race_tests.rs@@ -0,0 +1,507 @@+//! Race tests over a simulated window: the UI changes between the read and+//! the act, and the guards must refuse or relocate, never act on the wrong+//! target. Platform fixtures repeat these cases against real apps.++use super::fingerprint::{+ verify_element, Delivery, ElementFingerprint, ElementObservation, HitOutcome,+};+use super::pixel::{GrayImage, Tolerance};+use super::pixel_guard::{check, CropSource, PixelGuardConfig};+use super::reason::{Reason, Verdict};+use super::Rect;++/// xorshift, so the tests are deterministic.+struct Rng(u64);+impl Rng {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 << 13;+ self.0 ^= self.0 >> 7;+ self.0 ^= self.0 << 17;+ self.0+ }+ fn below(&mut self, n: u64) -> u64 {+ self.next() % n+ }+}++#[derive(Clone, Debug)]+struct Elem {+ /// Identity of the live reference (what AXPress acts on).+ id: u32,+ /// What it shows (what the agent meant to click).+ content: u32,+ frame: Rect,+ alive: bool,+}++#[derive(Clone, Debug)]+struct Ui {+ elems: Vec<Elem>,+}++impl Ui {+ fn new() -> Self {+ let elems = (0..6)+ .map(|i| Elem {+ id: i,+ content: 100 + i,+ frame: Rect::new(+ 20.0 + (i % 3) as f64 * 120.0,+ 40.0 + (i / 3) as f64 * 60.0,+ 80.0,+ 24.0,+ ),+ alive: true,+ })+ .collect();+ Self { elems }+ }+ fn label(content: u32) -> String {+ format!("Button {content}")+ }+ fn fingerprint(&self, i: usize) -> ElementFingerprint {+ let e = &self.elems[i];+ ElementFingerprint {+ role: "AXButton".into(),+ label: Some(Self::label(e.content)),+ frame: Some(e.frame),+ ..Default::default()+ }+ }+ fn observe(&self, i: usize) -> ElementObservation {+ let e = &self.elems[i];+ ElementObservation {+ valid: e.alive,+ role: e.alive.then(|| "AXButton".into()),+ label: e.alive.then(|| Self::label(e.content)),+ frame: e.alive.then_some(e.frame),+ ..Default::default()+ }+ }+ fn at(&self, x: f64, y: f64) -> Option<usize> {+ self.elems+ .iter()+ .rposition(|e| e.alive && e.frame.contains(x, y))+ }+ fn hit(&self, target: usize, x: f64, y: f64) -> HitOutcome {+ match self.at(x, y) {+ Some(i) if i == target => HitOutcome::Target,+ Some(_) => HitOutcome::Other,+ None => HitOutcome::Nothing,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq)]+enum Change {+ None,+ Move,+ SmallMove,+ Swap,+ Remove,+ RowReuse,+ Cover,+}++fn apply(ui: &mut Ui, target: usize, change: Change, rng: &mut Rng) {+ let other = (target + 1 + rng.below(5) as usize) % 6;+ match change {+ Change::None => {}+ Change::Move => {+ ui.elems[target].frame.x += 40.0 + rng.below(80) as f64;+ ui.elems[target].frame.y += rng.below(30) as f64;+ }+ Change::SmallMove => ui.elems[target].frame.x += 1.0,+ Change::Swap => {+ let a = ui.elems[target].frame;+ ui.elems[target].frame = ui.elems[other].frame;+ ui.elems[other].frame = a;+ }+ Change::Remove => ui.elems[target].alive = false,+ Change::RowReuse => ui.elems[target].content += 1000,+ Change::Cover => {+ // Another element is moved on top of the target.+ ui.elems[other].frame = ui.elems[target].frame;+ let moved = ui.elems.remove(other);+ ui.elems.push(moved);+ }+ }+}++const CHANGES: [Change; 7] = [+ Change::None,+ Change::Move,+ Change::SmallMove,+ Change::Swap,+ Change::Remove,+ Change::RowReuse,+ Change::Cover,+];++#[derive(Default, Debug)]+struct Tally {+ acted: u32,+ refused: u32,+ relocated: u32,+ wrong: u32,+ static_refusals: u32,+}++/// Act as the driver would: check, retry once on a pure move, then act.+fn act(+ ui: &Ui,+ target_id: u32,+ fp: &ElementFingerprint,+ delivery: Delivery,+ intended: u32,+ tally: &mut Tally,+) {+ let Some(target) = ui.elems.iter().position(|e| e.id == target_id) else {+ tally.refused += 1;+ return;+ };+ let (mut px, mut py) = fp.frame.unwrap().center();+ let hit = (delivery == Delivery::Pixel).then(|| ui.hit(target, px, py));+ let mut verdict = verify_element(fp, &ui.observe(target), delivery, hit);+ if let Verdict::Relocated { dx, dy } = verdict {+ tally.relocated += 1;+ px += dx;+ py += dy;+ // Re-check at the new point with a fresh hit-test; the moved frame+ // is the new reference frame.+ let mut moved = fp.clone();+ moved.frame = ui.observe(target).frame;+ verdict = verify_element(+ &moved,+ &ui.observe(target),+ delivery,+ Some(ui.hit(target, px, py)),+ );+ if !verdict.is_ok() {+ tally.refused += 1;+ return;+ }+ }+ if !verdict.is_ok() {+ tally.refused += 1;+ return;+ }+ tally.acted += 1;+ let pressed = match delivery {+ Delivery::Semantic => ui.elems[target].content,+ Delivery::Pixel => match ui.at(px, py) {+ Some(i) => ui.elems[i].content,+ None => 0,+ },+ };+ if pressed != intended {+ tally.wrong += 1;+ }+}++#[test]+fn randomized_race_never_acts_on_the_wrong_target() {+ let mut rng = Rng(0x5eed_cafe);+ for delivery in [Delivery::Semantic, Delivery::Pixel] {+ let mut tally = Tally::default();+ for _ in 0..1000 {+ let mut ui = Ui::new();+ let target = rng.below(6) as usize;+ let fp = ui.fingerprint(target);+ let intended = ui.elems[target].content;+ let id = ui.elems[target].id;+ let change = CHANGES[rng.below(CHANGES.len() as u64) as usize];+ apply(&mut ui, target, change, &mut rng);+ let before = tally.refused;+ act(&ui, id, &fp, delivery, intended, &mut tally);+ if matches!(change, Change::None | Change::SmallMove) && tally.refused > before {+ tally.static_refusals += 1;+ }+ }+ assert_eq!(tally.wrong, 0, "{delivery:?}: {tally:?}");+ assert_eq!(tally.static_refusals, 0, "{delivery:?}: {tally:?}");+ assert!(tally.refused > 0 && tally.acted > 0, "{tally:?}");+ if delivery == Delivery::Pixel {+ assert!(tally.relocated > 0, "{tally:?}");+ }+ }+}++#[test]+fn moved_button_semantic_presses_the_right_one_pixel_relocates() {+ let mut ui = Ui::new();+ let fp = ui.fingerprint(0);+ ui.elems[0].frame.y += 200.0; // into empty space below the grid+ let mut t = Tally::default();+ act(&ui, 0, &fp, Delivery::Semantic, 100, &mut t);+ act(&ui, 0, &fp, Delivery::Pixel, 100, &mut t);+ assert_eq!((t.acted, t.wrong, t.relocated), (2, 0, 1));+}++#[test]+fn swapped_buttons_pixel_refuses_semantic_presses_a() {+ let mut ui = Ui::new();+ let fp = ui.fingerprint(0);+ let a = ui.elems[0].frame;+ ui.elems[0].frame = ui.elems[3].frame;+ ui.elems[3].frame = a;+ // Swapped frames differ in y, so the guard sees a move of A and+ // relocates to A's new spot; it never clicks B at the old point.+ let mut t = Tally::default();+ act(&ui, 0, &fp, Delivery::Pixel, 100, &mut t);+ act(&ui, 0, &fp, Delivery::Semantic, 100, &mut t);+ assert_eq!(t.wrong, 0);+ // Same-frame swap (B now exactly where A was, A hidden under it).+ let mut ui = Ui::new();+ let fp = ui.fingerprint(0);+ apply(&mut ui, 0, Change::Cover, &mut Rng(1));+ let hit = ui.hit(+ 0,+ fp.frame.unwrap().center().0,+ fp.frame.unwrap().center().1,+ );+ let v = verify_element(&fp, &ui.observe(0), Delivery::Pixel, Some(hit));+ assert_eq!(v.reason(), Some(Reason::HitMismatch));+}++#[test]+fn row_reuse_and_removal_refuse() {+ let mut ui = Ui::new();+ let fp = ui.fingerprint(2);+ ui.elems[2].content = 999;+ assert_eq!(+ verify_element(&fp, &ui.observe(2), Delivery::Semantic, None).reason(),+ Some(Reason::Relabelled)+ );+ ui.elems[2].alive = false;+ assert_eq!(+ verify_element(&fp, &ui.observe(2), Delivery::Semantic, None).reason(),+ Some(Reason::Gone)+ );+}++// ── Pixel-only (no tree) races ───────────────────────────────────────────++/// Renders tiles whose pattern encodes their content, on a textured canvas.+fn render(tiles: &[(i64, i64, u32)], seed: u32) -> GrayImage {+ let mut img = super::pixel::test_images::background(480, 320, seed);+ for &(x, y, content) in tiles {+ img.fill_rect(x, y, 48, 28, 30);+ for bit in 0..6 {+ if content >> bit & 1 == 1 {+ img.fill_rect(x + 4 + bit as i64 * 7, y + 4, 5, 20, 235);+ } else {+ img.fill_rect(x + 4 + bit as i64 * 7, y + 18, 5, 6, 140);+ }+ }+ }+ img+}++struct Static(GrayImage);+impl CropSource for Static {+ fn capture(&mut self, x: i64, y: i64, w: usize, h: usize) -> Option<GrayImage> {+ self.0.crop(x, y, w, h)+ }+ fn sleep_ms(&mut self, _: u64) {}+}++fn tile_at(tiles: &[(i64, i64, u32)], x: f64, y: f64) -> Option<u32> {+ tiles+ .iter()+ .rev()+ .find(|(tx, ty, _)| {+ x >= *tx as f64 && x < (*tx + 48) as f64 && y >= *ty as f64 && y < (*ty + 28) as f64+ })+ .map(|t| t.2)+}++#[test]+fn randomized_canvas_race_never_clicks_the_wrong_tile() {+ let mut rng = Rng(0xfeed_f00d);+ let cfg = PixelGuardConfig::for_scale(1.0, false);+ let (mut wrong, mut refused, mut relocated, mut static_refused) = (0, 0, 0, 0);+ for _ in 0..300 {+ let tiles: Vec<(i64, i64, u32)> =+ vec![(60, 60, 5), (220, 60, 9), (60, 200, 22), (300, 200, 41)];+ let target = rng.below(4) as usize;+ let read = render(&tiles, 3);+ let intended = tiles[target].2;+ let mut now = tiles.clone();+ let kind = rng.below(5);+ match kind {+ 0 => {}+ 1 => now[target].0 += 10 + rng.below(20) as i64, // shift within radius+ 2 => now[target].2 ^= 0b1011, // redrawn as other content+ 3 => now.swap(0, 1), // content order changes+ _ => {+ now[target].0 += 120; // moved far away+ }+ }+ // `swap` moves contents: positions stay, contents trade places.+ if kind == 3 {+ let (a, b) = (now[0].2, now[1].2);+ now[0] = (tiles[0].0, tiles[0].1, a);+ now[1] = (tiles[1].0, tiles[1].1, b);+ }+ let image = render(&now, 3);+ let point = (tiles[target].0 as f64 + 24.0, tiles[target].1 as f64 + 14.0);+ let r = check(&read, point, &cfg, &mut Static(image));+ let click = match r.verdict {+ Verdict::Ok => Some(point),+ Verdict::Relocated { dx, dy } => {+ relocated += 1;+ Some((point.0 + dx, point.1 + dy))+ }+ Verdict::Refuse { .. } => {+ refused += 1;+ if kind == 0 {+ static_refused += 1;+ }+ None+ }+ };+ if let Some((x, y)) = click {+ if tile_at(&now, x, y) != Some(intended) {+ wrong += 1;+ }+ }+ }+ assert_eq!(wrong, 0);+ assert_eq!(static_refused, 0);+ assert!(refused > 0 && relocated > 0);+}++/// Alternates frames with and without a caret next to the target.+struct Blinking {+ base: GrayImage,+ rng: Rng,+}+impl CropSource for Blinking {+ fn capture(&mut self, x: i64, y: i64, w: usize, h: usize) -> Option<GrayImage> {+ let mut f = self.base.clone();+ if self.rng.below(2) == 0 {+ f.fill_rect(118, 62, 2, 18, 0);+ }+ f.crop(x, y, w, h)+ }+ fn sleep_ms(&mut self, _: u64) {}+}++#[test]+fn blinking_caret_does_not_cause_false_refusals() {+ let base = render(&[(60, 60, 5)], 9);+ let cfg = PixelGuardConfig::for_scale(1.0, false);+ let mut src = Blinking {+ base: base.clone(),+ rng: Rng(42),+ };+ let mut refusals = 0;+ for i in 0..1000 {+ // Half the reads were taken with the caret visible.+ let mut read = base.clone();+ if i % 2 == 0 {+ read.fill_rect(118, 62, 2, 18, 0);+ }+ if !check(&read, (84.0, 74.0), &cfg, &mut src).verdict.is_ok() {+ refusals += 1;+ }+ }+ assert!(refusals < 20, "{refusals} refusals in 1000 static clicks");+}++/// A remote-desktop stream: compression noise on every frame and a remote+/// cursor drawn in the content that wanders across the target.+struct RemoteStream {+ base: GrayImage,+ rng: Rng,+ cursor: (i64, i64),+}+impl CropSource for RemoteStream {+ fn capture(&mut self, x: i64, y: i64, w: usize, h: usize) -> Option<GrayImage> {+ let mut f = self.base.clone();+ for p in f.pixels.iter_mut() {+ let n = (self.rng.below(13) as i32) - 6;+ *p = (*p as i32 + n).clamp(0, 255) as u8;+ }+ // 8x8 block artefacts.+ for _ in 0..6 {+ let bx = self.rng.below(60) as i64 * 8;+ let by = self.rng.below(40) as i64 * 8;+ let shift = self.rng.below(20) as u8;+ for yy in by..by + 8 {+ for xx in bx..bx + 8 {+ let i = yy as usize * f.width + xx as usize;+ if i < f.pixels.len() {+ f.pixels[i] = f.pixels[i].saturating_add(shift);+ }+ }+ }+ }+ f.fill_rect(self.cursor.0, self.cursor.1, 12, 18, 0);+ f.crop(x, y, w, h)+ }+ fn sleep_ms(&mut self, _: u64) {}+}++#[test]+fn remote_desktop_noise_and_cursor_do_not_refuse_static_clicks() {+ let base = render(&[(200, 140, 13)], 21);+ let mut src = RemoteStream {+ base: base.clone(),+ rng: Rng(7),+ cursor: (210, 146),+ };+ let mut refusals = 0;+ for i in 0..200 {+ src.cursor = (190 + (i % 7) * 6, 136 + (i % 5) * 4);+ let mut cfg = PixelGuardConfig::for_scale(1.0, true);+ cfg.cursor_mask = Some((src.cursor.0 - 2, src.cursor.1 - 2, 16, 22));+ if !check(&base, (224.0, 154.0), &cfg, &mut src).verdict.is_ok() {+ refusals += 1;+ }+ }+ assert_eq!(refusals, 0);+}++#[test]+fn remote_desktop_real_change_still_refuses() {+ let read = render(&[(200, 140, 13)], 21);+ let changed = render(&[(200, 140, 50)], 21);+ let mut src = RemoteStream {+ base: changed,+ rng: Rng(8),+ cursor: (10, 10),+ };+ let cfg = PixelGuardConfig {+ tolerance: Tolerance::REMOTE,+ ..PixelGuardConfig::for_scale(1.0, true)+ };+ assert_eq!(+ check(&read, (224.0, 154.0), &cfg, &mut src)+ .verdict+ .reason(),+ Some(Reason::RegionChanged)+ );+}++#[test]+fn no_tree_window_gets_window_guard_and_pixel_check() {+ use super::classify::{classify, HitInfo, TargetClass, TreeStats};+ let win = Rect::new(0.0, 0.0, 480.0, 320.0);+ let hit = HitInfo {+ role: Some("AXWindow".into()),+ is_window: true,+ ..Default::default()+ };+ let class = classify(+ Some(&hit),+ Some(&TreeStats {+ elements: 1,+ thin_frames: 0,+ }),+ win,+ );+ assert_eq!(class, TargetClass::Sparse);+ assert!(class.needs_pixel_check());+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/reason.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/reason.rsnew file mode 100644index 0000000000..7175ebbb93--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/reason.rs@@ -0,0 +1,106 @@+//! Why a guard refused, in the wire vocabulary of the design note.++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Reason {+ /// The element no longer exists.+ Gone,+ /// Its label or identifier changed (row reuse, swapped content).+ Relabelled,+ RoleChanged,+ /// The frame moved beyond tolerance (pixel delivery only).+ Moved,+ Resized,+ /// Another element is under the click point.+ HitMismatch,+ Offscreen,+ /// The target kept changing for the whole settle budget.+ Animating,+ /// Sparse target: the pixels around the point are stable but different.+ RegionChanged,+ WindowChanged,+ Occluded,+ NotVisible,+}++impl Reason {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Gone => "gone",+ Self::Relabelled => "relabelled",+ Self::RoleChanged => "role_changed",+ Self::Moved => "moved",+ Self::Resized => "resized",+ Self::HitMismatch => "hit_mismatch",+ Self::Offscreen => "offscreen",+ Self::Animating => "animating",+ Self::RegionChanged => "region_changed",+ Self::WindowChanged => "window_changed",+ Self::Occluded => "occluded",+ Self::NotVisible => "not_visible",+ }+ }++ /// The wire `code` of the refusal.+ pub fn code(self) -> &'static str {+ match self {+ Self::WindowChanged | Self::Occluded | Self::NotVisible => "window_changed",+ _ => "target_changed",+ }+ }++ /// Plain-words message for the model.+ pub fn message(self) -> &'static str {+ match self {+ Self::Gone => "The element is gone since you read it. Act on a token from the fresh state.",+ Self::Relabelled => "The element now shows different content than when you read it. Act on a token from the fresh state.",+ Self::RoleChanged => "The element changed type since you read it. Act on a token from the fresh state.",+ Self::Moved => "The element moved since you read it. Act on the new token or the new point.",+ Self::Resized => "The element changed size since you read it. Act on a token from the fresh state.",+ Self::HitMismatch => "Another element is now at that point. Act on a token from the fresh state.",+ Self::Offscreen => "The target is off screen now.",+ Self::Animating => "The target area kept changing (animation or live content). Wait, or pass verify_target:\"window\" for live content.",+ Self::RegionChanged => "The target area changed since you read it. Look at the fresh screenshot and pick the point again.",+ Self::WindowChanged => "The window changed since you read it (closed, resized or replaced). Read it again.",+ Self::Occluded => "Another window covers the target point.",+ Self::NotVisible => "The window is not visible (minimized or on another Space), so the target cannot be checked.",+ }+ }++ /// Auto-retry once is allowed only for a pure move with proven identity.+ pub fn retryable(self) -> bool {+ matches!(self, Self::Moved)+ }+}++/// The verdict every guard returns.+#[derive(Clone, Debug, PartialEq)]+pub enum Verdict {+ Ok,+ /// Identity proven, only the position changed: act at the new point once.+ Relocated {+ dx: f64,+ dy: f64,+ },+ Refuse {+ reason: Reason,+ detail: String,+ },+}++impl Verdict {+ pub fn refuse(reason: Reason, detail: impl Into<String>) -> Self {+ Self::Refuse {+ reason,+ detail: detail.into(),+ }+ }+ pub fn is_ok(&self) -> bool {+ matches!(self, Self::Ok)+ }+ pub fn reason(&self) -> Option<Reason> {+ match self {+ Self::Refuse { reason, .. } => Some(*reason),+ _ => None,+ }+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/store.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/store.rsnew file mode 100644index 0000000000..e1603be7bb--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/store.rs@@ -0,0 +1,267 @@+//! In-memory read-time state for the guards: element fingerprints per+//! snapshot, and the latest window image plus window fingerprint per window.+//! Nothing goes to disk. Fingerprints of retired snapshots stay for the same+//! bounded window so an older token can be checked instead of refused.++use super::fingerprint::ElementFingerprint;+use super::pixel::GrayImage;+use super::window::WindowFingerprint;+use std::collections::{HashMap, VecDeque};+use std::sync::{Mutex, OnceLock};++/// Snapshots whose fingerprints are kept (8 per pid in the snapshot LRU,+/// times a few busy pids).+pub const SNAPSHOT_CAPACITY: usize = 64;+/// Windows whose read-time image is kept.+pub const IMAGE_CAPACITY: usize = 16;++#[derive(Clone, Debug)]+pub struct SnapshotFingerprints {+ pub pid: i32,+ pub window_id: u64,+ pub elements: Vec<ElementFingerprint>,+ /// Cheap stats for target classification.+ pub element_count: usize,+ pub thin_frames: usize,+}++#[derive(Clone, Debug)]+pub struct ReadImage {+ pub snapshot_id: u32,+ pub image: GrayImage,+ pub window: WindowFingerprint,+}++#[derive(Default)]+struct State {+ snapshots: HashMap<u32, SnapshotFingerprints>,+ snapshot_order: VecDeque<u32>,+ images: HashMap<(i32, u64), ReadImage>,+ image_order: VecDeque<(i32, u64)>,+ /// Latest window fingerprint even when no image was kept.+ windows: HashMap<(i32, u64), WindowFingerprint>,+}++#[derive(Default)]+pub struct GuardStore {+ inner: Mutex<State>,+}++impl GuardStore {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn put_snapshot(&self, snapshot_id: u32, fps: SnapshotFingerprints) {+ let mut s = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ if s.snapshots.insert(snapshot_id, fps).is_none() {+ s.snapshot_order.push_back(snapshot_id);+ }+ while s.snapshot_order.len() > SNAPSHOT_CAPACITY {+ if let Some(old) = s.snapshot_order.pop_front() {+ s.snapshots.remove(&old);+ }+ }+ }++ pub fn element(+ &self,+ snapshot_id: u32,+ index: usize,+ ) -> Option<(i32, u64, ElementFingerprint)> {+ let s = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ let snap = s.snapshots.get(&snapshot_id)?;+ snap.elements+ .get(index)+ .map(|fp| (snap.pid, snap.window_id, fp.clone()))+ }++ pub fn stats(&self, snapshot_id: u32) -> Option<(usize, usize)> {+ let s = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ s.snapshots+ .get(&snapshot_id)+ .map(|f| (f.element_count, f.thin_frames))+ }++ pub fn latest_stats(&self, pid: i32, window_id: u64) -> Option<(usize, usize)> {+ let s = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ s.snapshot_order+ .iter()+ .rev()+ .filter_map(|id| s.snapshots.get(id))+ .find(|f| f.pid == pid && f.window_id == window_id)+ .map(|f| (f.element_count, f.thin_frames))+ }++ /// The smallest element of the window's latest snapshot whose read-time+ /// frame contains the screen point: what the agent saw there.+ pub fn element_at(+ &self,+ pid: i32,+ window_id: u64,+ x: f64,+ y: f64,+ ) -> Option<ElementFingerprint> {+ let s = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ let snap = s+ .snapshot_order+ .iter()+ .rev()+ .filter_map(|id| s.snapshots.get(id))+ .find(|f| f.pid == pid && f.window_id == window_id)?;+ snap.elements+ .iter()+ .filter(|fp| fp.frame.is_some_and(|f| f.contains(x, y) && f.area() > 0.0))+ .min_by(|a, b| {+ let (a, b) = (a.frame.unwrap().area(), b.frame.unwrap().area());+ a.partial_cmp(&b).unwrap_or(std::cmp::Ordering::Equal)+ })+ .cloned()+ }++ pub fn put_window(&self, pid: i32, window: WindowFingerprint) {+ let mut s = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ s.windows.insert((pid, window.window_id), window);+ if s.windows.len() > 4 * IMAGE_CAPACITY {+ let keep: Vec<_> = s.image_order.iter().copied().collect();+ s.windows.retain(|k, _| keep.contains(k));+ s.windows.insert((pid, window.window_id), window);+ }+ }++ pub fn window(&self, pid: i32, window_id: u64) -> Option<WindowFingerprint> {+ let s = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ s.windows.get(&(pid, window_id)).copied()+ }++ pub fn put_image(&self, pid: i32, image: ReadImage) {+ let key = (pid, image.window.window_id);+ let mut s = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ s.windows.insert(key, image.window);+ if s.images.insert(key, image).is_none() {+ s.image_order.push_back(key);+ } else {+ s.image_order.retain(|k| *k != key);+ s.image_order.push_back(key);+ }+ while s.image_order.len() > IMAGE_CAPACITY {+ if let Some(old) = s.image_order.pop_front() {+ s.images.remove(&old);+ }+ }+ }++ pub fn image(&self, pid: i32, window_id: u64) -> Option<ReadImage> {+ let s = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ s.images.get(&(pid, window_id)).cloned()+ }++ pub fn forget_window(&self, pid: i32, window_id: u64) {+ let mut s = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ s.images.remove(&(pid, window_id));+ s.image_order.retain(|k| *k != (pid, window_id));+ s.windows.remove(&(pid, window_id));+ }+}++/// The daemon-wide store.+pub fn global() -> &'static GuardStore {+ static STORE: OnceLock<GuardStore> = OnceLock::new();+ STORE.get_or_init(GuardStore::new)+}++#[cfg(test)]+mod tests {+ use super::super::Rect;+ use super::*;++ fn win(id: u64) -> WindowFingerprint {+ WindowFingerprint {+ window_id: id,+ pid: 1,+ frame: Rect::new(0.0, 0.0, 10.0, 10.0),+ scale: 1.0,+ }+ }++ #[test]+ fn retired_snapshot_fingerprints_stay_until_capacity() {+ let store = GuardStore::new();+ for id in 0..(SNAPSHOT_CAPACITY as u32 + 5) {+ store.put_snapshot(+ id,+ SnapshotFingerprints {+ pid: 1,+ window_id: 2,+ elements: vec![ElementFingerprint {+ role: format!("r{id}"),+ ..Default::default()+ }],+ element_count: 1,+ thin_frames: 0,+ },+ );+ }+ assert!(store.element(0, 0).is_none());+ assert_eq!(store.element(10, 0).unwrap().2.role, "r10");+ assert!(store.element(10, 1).is_none());+ assert_eq!(store.latest_stats(1, 2), Some((1, 0)));+ }++ #[test]+ fn element_at_picks_the_smallest_containing_frame() {+ let store = GuardStore::new();+ let el = |role: &str, f: Rect| ElementFingerprint {+ role: role.into(),+ frame: Some(f),+ ..Default::default()+ };+ store.put_snapshot(+ 1,+ SnapshotFingerprints {+ pid: 1,+ window_id: 2,+ elements: vec![+ el("AXGroup", Rect::new(0.0, 0.0, 500.0, 500.0)),+ el("AXButton", Rect::new(10.0, 10.0, 80.0, 24.0)),+ ],+ element_count: 2,+ thin_frames: 0,+ },+ );+ assert_eq!(store.element_at(1, 2, 20.0, 20.0).unwrap().role, "AXButton");+ assert_eq!(+ store.element_at(1, 2, 300.0, 300.0).unwrap().role,+ "AXGroup"+ );+ assert!(store.element_at(1, 2, 900.0, 900.0).is_none());+ assert!(store.element_at(1, 3, 20.0, 20.0).is_none());+ }++ #[test]+ fn images_are_bounded_and_latest_wins() {+ let store = GuardStore::new();+ for id in 0..(IMAGE_CAPACITY as u64 + 3) {+ store.put_image(+ 1,+ ReadImage {+ snapshot_id: 1,+ image: GrayImage::filled(2, 2, 0),+ window: win(id),+ },+ );+ }+ assert!(store.image(1, 0).is_none());+ store.put_image(+ 1,+ ReadImage {+ snapshot_id: 9,+ image: GrayImage::filled(2, 2, 0),+ window: win(5),+ },+ );+ assert_eq!(store.image(1, 5).unwrap().snapshot_id, 9);+ store.forget_window(1, 5);+ assert!(store.image(1, 5).is_none() && store.window(1, 5).is_none());+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/window.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/window.rsnew file mode 100644index 0000000000..5522ebfba9--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/window.rs@@ -0,0 +1,190 @@+//! Window guards: run for every pixel click, rich or sparse, with no tree.++use super::reason::{Reason, Verdict};+use super::Rect;++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct WindowFingerprint {+ pub window_id: u64,+ pub pid: i32,+ /// Screen frame in points.+ pub frame: Rect,+ /// Backing scale (pixels per point).+ pub scale: f64,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct WindowObservation {+ pub exists: bool,+ pub pid: i32,+ pub frame: Rect,+ pub scale: f64,+ /// On screen and capturable (not minimized, not on another Space).+ pub visible: bool,+ /// Owner pid of the window at the click point, if the platform can say.+ pub pid_at_point: Option<i32>,+ /// Another window covers the point in the front-to-back list.+ pub covered_at_point: Option<bool>,+}++/// How the pointer event reaches the window.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PointerDelivery {+ /// Posted to the window or pid (background): occlusion does not matter+ /// and window-relative coordinates survive a window move.+ Background,+ /// Global screen coordinates (foreground, or remote desktops that read+ /// the real pointer): the window must not move or be covered.+ Screen,+}++pub const FRAME_TOLERANCE: f64 = 2.0;++pub fn verify_window(+ fp: &WindowFingerprint,+ now: &WindowObservation,+ delivery: PointerDelivery,+) -> Verdict {+ if !now.exists {+ return Verdict::refuse(Reason::WindowChanged, "the window is gone");+ }+ if now.pid != fp.pid {+ return Verdict::refuse(+ Reason::WindowChanged,+ "the window belongs to another process now",+ );+ }+ if !now.visible {+ return Verdict::refuse(+ Reason::NotVisible,+ "the window is minimized or not on screen",+ );+ }+ if (now.scale - fp.scale).abs() > 0.01 {+ return Verdict::refuse(+ Reason::WindowChanged,+ "the window moved to a display with another scale",+ );+ }+ if (now.frame.w - fp.frame.w).abs() > FRAME_TOLERANCE+ || (now.frame.h - fp.frame.h).abs() > FRAME_TOLERANCE+ {+ return Verdict::refuse(+ Reason::WindowChanged,+ format!(+ "the window was {:.0}x{:.0} and is now {:.0}x{:.0}",+ fp.frame.w, fp.frame.h, now.frame.w, now.frame.h+ ),+ );+ }+ let moved = (now.frame.x - fp.frame.x).abs() > FRAME_TOLERANCE+ || (now.frame.y - fp.frame.y).abs() > FRAME_TOLERANCE;+ if delivery == PointerDelivery::Screen {+ if moved {+ return Verdict::refuse(Reason::WindowChanged, "the window moved");+ }+ if let Some(pid) = now.pid_at_point {+ if pid != fp.pid {+ return Verdict::refuse(Reason::Occluded, "another app's window is at the point");+ }+ }+ if now.covered_at_point == Some(true) {+ return Verdict::refuse(Reason::Occluded, "another window covers the point");+ }+ }+ Verdict::Ok+}++#[cfg(test)]+mod tests {+ use super::*;++ fn fp() -> WindowFingerprint {+ WindowFingerprint {+ window_id: 7,+ pid: 42,+ frame: Rect::new(0.0, 25.0, 800.0, 600.0),+ scale: 2.0,+ }+ }+ fn obs() -> WindowObservation {+ WindowObservation {+ exists: true,+ pid: 42,+ frame: Rect::new(0.0, 25.0, 800.0, 600.0),+ scale: 2.0,+ visible: true,+ pid_at_point: Some(42),+ covered_at_point: Some(false),+ }+ }++ #[test]+ fn same_window_passes() {+ assert!(verify_window(&fp(), &obs(), PointerDelivery::Screen).is_ok());+ }++ #[test]+ fn each_window_reason() {+ let mut o = obs();+ o.exists = false;+ assert_eq!(+ verify_window(&fp(), &o, PointerDelivery::Background).reason(),+ Some(Reason::WindowChanged)+ );+ let mut o = obs();+ o.pid = 1;+ assert_eq!(+ verify_window(&fp(), &o, PointerDelivery::Background).reason(),+ Some(Reason::WindowChanged)+ );+ let mut o = obs();+ o.visible = false;+ assert_eq!(+ verify_window(&fp(), &o, PointerDelivery::Background).reason(),+ Some(Reason::NotVisible)+ );+ let mut o = obs();+ o.scale = 1.0;+ assert_eq!(+ verify_window(&fp(), &o, PointerDelivery::Background).reason(),+ Some(Reason::WindowChanged)+ );+ let mut o = obs();+ o.frame.w = 1024.0;+ assert_eq!(+ verify_window(&fp(), &o, PointerDelivery::Background).reason(),+ Some(Reason::WindowChanged)+ );+ }++ #[test]+ fn occlusion_matters_only_for_screen_delivery() {+ let mut o = obs();+ o.pid_at_point = Some(99);+ assert!(verify_window(&fp(), &o, PointerDelivery::Background).is_ok());+ assert_eq!(+ verify_window(&fp(), &o, PointerDelivery::Screen).reason(),+ Some(Reason::Occluded)+ );+ let mut o = obs();+ o.covered_at_point = Some(true);+ assert_eq!(+ verify_window(&fp(), &o, PointerDelivery::Screen).reason(),+ Some(Reason::Occluded)+ );+ }++ #[test]+ fn a_window_move_breaks_only_screen_coordinates() {+ let mut o = obs();+ o.frame.x += 50.0;+ assert!(verify_window(&fp(), &o, PointerDelivery::Background).is_ok());+ assert_eq!(+ verify_window(&fp(), &o, PointerDelivery::Screen).reason(),+ Some(Reason::WindowChanged)+ );+ o.frame.x = fp().frame.x + 1.5; // within tolerance+ assert!(verify_window(&fp(), &o, PointerDelivery::Screen).is_ok());+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/wire.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/wire.rsnew file mode 100644index 0000000000..1d4cf0866a--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/fast_path/wire.rs@@ -0,0 +1,324 @@+//! JSON shapes for the fast path: the config key, refusal payloads, and the+//! check summary attached to action results. Kept apart from the checks so+//! those stay std-only.++use super::classify::TargetClass;+use super::pixel::GrayImage;+use super::reason::{Reason, Verdict};+use super::{mode, set_mode, FastPathMode};+use crate::protocol::ToolResult;+use serde_json::{json, Value};++pub const CONFIG_KEY: &str = "fast_path";++/// The `set_config` schema property.+pub fn config_schema() -> Value {+ json!({+ "type": "string",+ "enum": ["off", "shadow", "guard", "on"],+ "description": "Experimental fast path (default off). shadow: check cached \+ targets at act time and report would-refuse verdicts; guard: refuse an \+ action whose target changed since it was read (target_changed); on: guard, \+ plus a small delta in each action result and tree-only re-reads. Runtime \+ only, not saved; env CUA_DRIVER_FAST_PATH seeds it at start."+ })+}++/// Add the `fast_path` property to a `set_config` schema.+pub fn with_config_property(mut schema: Value) -> Value {+ if let Some(props) = schema.get_mut("properties").and_then(Value::as_object_mut) {+ props.insert(CONFIG_KEY.into(), config_schema());+ }+ schema+}++/// Apply `fast_path` from `set_config` args. `Ok(None)` when absent.+pub fn apply_config_args(args: &Value) -> Result<Option<FastPathMode>, String> {+ let Some(raw) = args.get(CONFIG_KEY) else {+ return Ok(None);+ };+ let parsed = match raw {+ Value::String(s) => FastPathMode::parse(s),+ Value::Bool(true) => Some(FastPathMode::On),+ Value::Bool(false) => Some(FastPathMode::Off),+ _ => None,+ };+ let Some(m) = parsed else {+ return Err(format!(+ "fast_path must be one of off, shadow, guard, on (got {raw})"+ ));+ };+ set_mode(m);+ Ok(Some(m))+}++/// The `get_config` field.+pub fn config_value() -> Value {+ Value::String(mode().as_str().into())+}++/// The summary attached to an action that passed (or, in shadow mode,+/// would have failed) its checks.+pub fn check_summary(+ verdict: &Verdict,+ class: Option<TargetClass>,+ verified: &str,+ check_ms: f64,+) -> Value {+ let mut out = json!({+ "mode": mode().as_str(),+ "verified": verified,+ "check_ms": (check_ms * 10.0).round() / 10.0,+ });+ if let Some(class) = class {+ out["target_class"] = json!(class.as_str());+ }+ match verdict {+ Verdict::Ok => {}+ Verdict::Relocated { dx, dy } => {+ out["relocated"] = json!(true);+ out["offset"] = json!([dx, dy]);+ }+ Verdict::Refuse { reason, detail } => {+ out["would_refuse"] = json!(reason.as_str());+ out["detail"] = json!(detail);+ }+ }+ out+}++/// A refusal: `target_changed` (or `window_changed`) with the reason, the+/// detail and a pointer to the fresh state.+pub fn refusal(+ tool: &str,+ reason: Reason,+ detail: &str,+ class: Option<TargetClass>,+ pid: i32,+ window_id: Option<u64>,+ check_ms: f64,+) -> ToolResult {+ let mut next = json!({ "tool": "get_window_state", "args": { "pid": pid } });+ if let Some(w) = window_id {+ next["args"]["window_id"] = json!(w);+ }+ if matches!(+ reason,+ Reason::RegionChanged | Reason::WindowChanged | Reason::Occluded | Reason::Animating+ ) {+ next["args"]["include_screenshot"] = json!(true);+ }+ let mut structured = json!({+ "code": reason.code(),+ "reason": reason.as_str(),+ "detail": detail,+ "effect": "refused",+ "fast_path": {+ "mode": mode().as_str(),+ "check_ms": (check_ms * 10.0).round() / 10.0,+ },+ "next_call": next,+ });+ if let Some(class) = class {+ structured["fast_path"]["target_class"] = json!(class.as_str());+ }+ ToolResult::error(format!(+ "{tool}: {} ({}: {detail}). Nothing was sent.",+ reason.message(),+ reason.as_str()+ ))+ .with_structured(structured)+}++/// Merge `extra` into the result's structured content under `fast_path`.+pub fn annotate(result: &mut ToolResult, summary: Value) {+ match result.structured_content.as_mut() {+ Some(Value::Object(map)) => {+ map.insert("fast_path".into(), summary);+ }+ _ => {+ result.structured_content = Some(json!({ "fast_path": summary }));+ }+ }+}++/// Greyscale copy of a capture, for the read-time image and act-time crops.+pub fn gray_from_captured(img: &crate::image_utils::CapturedImage) -> Option<GrayImage> {+ use crate::image_utils::CapturedImage;+ match img {+ CapturedImage::Rgba(f) => {+ GrayImage::from_rgba(f.width as usize, f.height as usize, &f.rgba)+ }+ CapturedImage::Png(bytes) => {+ let decoded = image::load_from_memory(bytes).ok()?.to_luma8();+ let (w, h) = decoded.dimensions();+ GrayImage::new(w as usize, h as usize, decoded.into_raw())+ }+ }+}++/// Design (e): with the mode `on`, a re-read (`since` given) that did not+/// ask for a screenshot is tree-only, unless the window's tree is sparse+/// (under 10 elements or mostly 1-pt frames), where the picture is the+/// only reliable state.+pub fn skip_reread_screenshot(args: &Value, pid: i32, window_id: u64) -> bool {+ if !mode().deltas()+ || args.get("include_screenshot").is_some()+ || args.get("screenshot_out_file").is_some()+ || args.get("since").is_none_or(Value::is_null)+ {+ return false;+ }+ match super::store::global().latest_stats(pid, window_id) {+ Some((elements, thin)) => elements >= 10 && thin * 2 <= elements,+ None => false,+ }+}++/// Tools whose direct (unbatched) result gets a delta when the mode is `on`.+pub fn returns_delta(tool: &str) -> bool {+ matches!(+ tool,+ "click"+ | "double_click"+ | "right_click"+ | "type_text"+ | "press_key"+ | "hotkey"+ | "set_value"+ | "scroll"+ | "drag"+ )+}++/// The window a direct action's delta is read from, when the mode is `on`.+/// From `pid`/`window_id`, or from the snapshot an `element_token` names.+pub fn delta_target(args: &Value) -> Option<(i32, u64)> {+ if !mode().deltas() {+ return None;+ }+ let pid = args.get("pid").and_then(Value::as_i64).map(|p| p as i32);+ let window = args.get("window_id").and_then(Value::as_u64);+ if let (Some(pid), Some(window)) = (pid, window) {+ return Some((pid, window));+ }+ let (snapshot, index) = args+ .get("element_token")+ .and_then(Value::as_str)+ .and_then(crate::element_token::parse_token)?;+ super::store::global()+ .element(snapshot, index)+ .map(|(pid, window, _)| (pid, window))+}++/// Append a delta read to an action result: its text after the action's,+/// and its structured content under `fast_path.delta`.+pub fn attach_delta(result: &mut ToolResult, delta: ToolResult) {+ if delta.is_error == Some(true) {+ annotate_delta(result, json!({ "error": true }));+ return;+ }+ let structured = delta.structured_content.clone().unwrap_or(Value::Null);+ let summary = json!({+ "snapshot_id": structured.get("snapshot_id").cloned().unwrap_or(Value::Null),+ "since_status": structured.get("since_status").cloned().unwrap_or(Value::Null),+ });+ result.content.extend(delta.content);+ annotate_delta(result, summary);+}++fn annotate_delta(result: &mut ToolResult, delta: Value) {+ let map = match result.structured_content.as_mut() {+ Some(Value::Object(map)) => map,+ _ => {+ result.structured_content = Some(json!({}));+ result+ .structured_content+ .as_mut()+ .unwrap()+ .as_object_mut()+ .unwrap()+ }+ };+ let entry = map+ .entry("fast_path")+ .or_insert_with(|| json!({ "mode": mode().as_str() }));+ if !entry.is_object() {+ *entry = json!({ "mode": mode().as_str() });+ }+ entry["delta"] = delta;+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn config_round_trip_and_rejects_junk() {+ let _guard = crate::fast_path::tests_lock();+ assert_eq!(apply_config_args(&json!({})).unwrap(), None);+ assert_eq!(+ apply_config_args(&json!({"fast_path": "guard"})).unwrap(),+ Some(FastPathMode::Guard)+ );+ assert_eq!(config_value(), json!("guard"));+ assert!(apply_config_args(&json!({"fast_path": 3})).is_err());+ apply_config_args(&json!({"fast_path": "off"})).unwrap();+ assert_eq!(mode(), FastPathMode::Off);+ }++ #[test]+ fn refusal_payload_names_reason_and_fresh_read() {+ let r = refusal(+ "click",+ Reason::Moved,+ "moved 40 pt",+ None,+ 7,+ Some(3),+ 1.23,+ );+ assert_eq!(r.is_error, Some(true));+ let s = r.structured_content.unwrap();+ assert_eq!(s["code"], "target_changed");+ assert_eq!(s["reason"], "moved");+ assert_eq!(s["next_call"]["args"]["window_id"], 3);+ let r = refusal(+ "click",+ Reason::RegionChanged,+ "x",+ Some(TargetClass::Sparse),+ 7,+ Some(3),+ 0.0,+ );+ let s = r.structured_content.unwrap();+ assert_eq!(s["next_call"]["args"]["include_screenshot"], true);+ assert_eq!(s["fast_path"]["target_class"], "sparse");+ }++ #[test]+ fn delta_is_attached_under_fast_path() {+ let mut result = ToolResult::text("clicked").with_structured(json!({"path": "ax"}));+ let delta = ToolResult::text("~ [3] AXButton \"Save\"")+ .with_structured(json!({"snapshot_id": "s00000002", "since_status": "delta"}));+ attach_delta(&mut result, delta);+ let s = result.structured_content.unwrap();+ assert_eq!(s["path"], "ax");+ assert_eq!(s["fast_path"]["delta"]["snapshot_id"], "s00000002");+ assert_eq!(result.content.len(), 2);+ }++ #[test]+ fn summary_reports_relocation_and_shadow_verdicts() {+ let s = check_summary(+ &Verdict::Relocated { dx: 4.0, dy: 0.0 },+ Some(TargetClass::Rich),+ "ax",+ 2.0,+ );+ assert_eq!(s["relocated"], true);+ let s = check_summary(&Verdict::refuse(Reason::Gone, "gone"), None, "ax", 2.0);+ assert_eq!(s["would_refuse"], "gone");+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rsindex 8580833866..e873f729b8 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs@@ -76,6 +76,7 @@ pub mod element_frame;pub mod element_query;pub mod element_token;pub mod expectation;+pub mod fast_path;pub mod ffmpeg_install;pub mod health_report;pub mod history;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rsindex 961e35dbc4..e0576a2844 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs@@ -1860,6 +1860,9 @@ impl ToolRegistry {} else {Ok(crate::post_action_wait::PostActionWait::Default)};+ let delta_target = (!in_batch && crate::fast_path::wire::returns_delta(tool))+ .then(|| crate::fast_path::wire::delta_target(&args))+ .flatten();let mut result = match wait {Ok(wait) => {crate::post_action_wait::scope(@@ -1870,6 +1873,21 @@ impl ToolRegistry {}Err((message, structured)) => ToolResult::error(message).with_structured(structured),};+ // Fast path `on` (CUA-3102): a direct action returns the window's+ // delta in the same result, so the agent needs no separate re-read.+ if let Some((pid, window_id)) = delta_target.filter(|_| result.is_error != Some(true)) {+ let mut read = serde_json::json!({+ "pid": pid,+ "window_id": window_id,+ "since": "latest",+ });+ if let Some(session) = session.as_deref() {+ read["session"] = Value::String(session.to_owned());+ }+ let delta =+ Box::pin(self.invoke_authorized("get_window_state", read, context, evidence)).await;+ crate::fast_path::wire::attach_delta(&mut result, delta);+ }crate::recovery_hint::annotate(tool, &seed, &mut result);crate::batch_nudge::annotate(tool, session.as_deref(), in_batch, &mut result);resultdiff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/get_config.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/get_config.rsindex d4951b3867..8b2c30504f 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/get_config.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/get_config.rs@@ -39,7 +39,8 @@ impl Tool for GetConfigTool {"max_image_dimension": cfg.max_image_dimension,"cursor": cursor_overlay::cursor_options::saved_config_json(),"experimental_pip": pip_enabled,- "experimental_pip_geometry": pip_geometry+ "experimental_pip_geometry": pip_geometry,+ "fast_path": cua_driver_core::fast_path::wire::config_value()}))}}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/set_config.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/set_config.rsindex fc194683c0..a19a381c6a 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/set_config.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/set_config.rs@@ -48,7 +48,8 @@ impl Tool for SetConfigTool {"capture_mode":{"type":"string","enum":["ax","vision"],"description":"Default capture mode for get_window_state. (\"som\"/\"screenshot\" still decode as deprecated aliases.)"},"max_image_dimension":{"type":"integer","description":"Max dimension for screenshot resizing (0 = no limit)."},"experimental_pip":{"type":"boolean","description":"Enable the experimental PiP preview window (applies next restart; Linux backend stubbed)."},- "experimental_pip_geometry":{"type":"string","description":"PiP window size + optional position in `WxH` or `WxH+X+Y` form."}+ "experimental_pip_geometry":{"type":"string","description":"PiP window size + optional position in `WxH` or `WxH+X+Y` form."},+ "fast_path": cua_driver_core::fast_path::wire::config_schema()},"additionalProperties":false})),read_only: false, destructive: false, idempotent: true, open_world: false,})@@ -97,6 +98,14 @@ impl Tool for SetConfigTool {parts.push(format!("capture_mode={mode}"));cfg.capture_mode = mode;}+ match cua_driver_core::fast_path::wire::apply_config_args(&args) {+ Ok(Some(mode)) => parts.push(format!(+ "fast_path={} (applies now, not saved)",+ mode.as_str()+ )),+ Ok(None) => {}+ Err(message) => return ToolResult::error(message),+ }if let Some(dim) = args.opt_u64("max_image_dimension") {cfg.max_image_dimension = dim as u32;if let Err(e) = pip_preview::write_config_key("max_image_dimension", Value::from(dim)) {@@ -137,7 +146,8 @@ impl Tool for SetConfigTool {"capture_mode": cfg.capture_mode,"max_image_dimension": cfg.max_image_dimension,"experimental_pip": pip_enabled,- "experimental_pip_geometry": pip_geometry+ "experimental_pip_geometry": pip_geometry,+ "fast_path": cua_driver_core::fast_path::wire::config_value()}))}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/fast_path_guard.rs b/libs/cua-driver/rust/crates/platform-macos/src/fast_path_guard.rsnew file mode 100644index 0000000000..35ea391d1d--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-macos/src/fast_path_guard.rs@@ -0,0 +1,576 @@+//! macOS side of the fast path (CUA-3102): record fingerprints and the+//! window image at read time, and read the live state at act time for the+//! shared checks in `cua_driver_core::fast_path`.+//!+//! With `fast_path` off (the default) every entry point returns at once and+//! nothing is recorded.++use crate::ax::bindings::{+ copy_children, copy_element_attr, copy_string_attr, element_screen_rect,+ kAXErrorInvalidUIElement, AXUIElementCopyAttributeValue, AXUIElementCopyElementAtPosition,+ AXUIElementCreateApplication, AXUIElementRef, AXUIElementSetMessagingTimeout,+};+use crate::ax::tree::AXNode;+use core_foundation::base::{CFEqual, CFRelease, CFTypeRef, TCFType};+use core_foundation::string::CFString;+use cua_driver_core::fast_path::{+ self as fp,+ classify::{classify, HitInfo, TargetClass, TreeStats},+ fingerprint::{verify_element, Delivery, ElementFingerprint, ElementObservation, HitOutcome},+ pixel::GrayImage,+ pixel_guard::{self, CropSource, PixelGuardConfig},+ reason::{Reason, Verdict},+ store::{global, ReadImage, SnapshotFingerprints},+ window::{verify_window, PointerDelivery, WindowFingerprint, WindowObservation},+ wire, Rect,+};+use cua_driver_core::protocol::ToolResult;+use serde_json::Value;+use std::time::Instant;++/// Per-element AX messaging timeout for the act-time hit-test, so a hung+/// app cannot stall the check for the 6 s default.+const CHECK_TIMEOUT_S: f32 = 0.25;+const MAX_ANCESTORS: usize = 5;++fn label_of(title: Option<&str>, description: Option<&str>) -> Option<String> {+ let t = title.map(str::trim).filter(|s| !s.is_empty());+ let d = description.map(str::trim).filter(|s| !s.is_empty());+ t.or(d).map(str::to_owned)+}++// ── Read time ────────────────────────────────────────────────────────────++/// Fingerprints for the actionable rows of a published snapshot, in token+/// index order (the same filter `AxSnapshot::from_nodes` uses).+pub fn record_snapshot(pid: i32, window_id: u64, snapshot_id: u32, nodes: &[AXNode]) {+ if !fp::mode().checks() {+ return;+ }+ let by_index: std::collections::HashMap<usize, &AXNode> = nodes+ .iter()+ .filter_map(|n| n.element_index.map(|i| (i, n)))+ .collect();+ let elements: Vec<ElementFingerprint> = nodes+ .iter()+ .filter(|n| n.element_index.is_some())+ .map(|n| ElementFingerprint {+ role: n.role.clone(),+ subrole: None,+ label: label_of(n.title.as_deref(), n.description.as_deref()),+ identifier: n.identifier.clone().filter(|s| !s.is_empty()),+ frame: n.frame.map(Rect::from_array),+ parent_index: n.parent_element_index,+ parent_label: n+ .parent_element_index+ .and_then(|p| by_index.get(&p))+ .and_then(|p| label_of(p.title.as_deref(), p.description.as_deref())),+ })+ .collect();+ let thin = nodes+ .iter()+ .filter(|n| n.frame.is_some_and(|f| f[3] <= 1.0))+ .count();+ global().put_snapshot(+ snapshot_id,+ SnapshotFingerprints {+ pid,+ window_id,+ elements,+ element_count: nodes.len(),+ thin_frames: thin,+ },+ );+}++/// Keep the read-time window image (greyscale, in memory) and the window+/// fingerprint for the pixel and window guards.+pub fn record_read_image(+ pid: i32,+ window_id: u32,+ raw: &cua_driver_core::image_utils::CapturedImage,+ bounds: &crate::windows::WindowBounds,+) {+ if !fp::mode().checks() {+ return;+ }+ let Some(image) = wire::gray_from_captured(raw) else {+ return;+ };+ let scale = if bounds.width > 0.0 {+ image.width as f64 / bounds.width+ } else {+ 1.0+ };+ global().put_image(+ pid,+ ReadImage {+ snapshot_id: 0,+ image,+ window: WindowFingerprint {+ window_id: u64::from(window_id),+ pid,+ frame: Rect::new(bounds.x, bounds.y, bounds.width, bounds.height),+ scale,+ },+ },+ );+}++/// Record only the window fingerprint (tree-only reads).+pub fn record_window(pid: i32, window_id: u32) {+ if !fp::mode().checks() {+ return;+ }+ if let Some(info) = crate::windows::window_info_by_id(window_id) {+ let scale = global()+ .window(pid, u64::from(window_id))+ .map(|w| w.scale)+ .unwrap_or(0.0);+ let b = info.bounds;+ global().put_window(+ pid,+ WindowFingerprint {+ window_id: u64::from(window_id),+ pid,+ frame: Rect::new(b.x, b.y, b.width, b.height),+ scale,+ },+ );+ }+}++// ── Act time: live reads ─────────────────────────────────────────────────++/// Read role, label, identifier and frame from the live element.+///+/// # Safety+/// `element` must be a retained, live-or-dead `AXUIElementRef`.+unsafe fn observe(element: AXUIElementRef) -> ElementObservation {+ let attr = CFString::new("AXRole");+ let mut value: CFTypeRef = std::ptr::null();+ let err = AXUIElementCopyAttributeValue(element, attr.as_concrete_TypeRef(), &mut value);+ if err == kAXErrorInvalidUIElement {+ return ElementObservation::default();+ }+ if !value.is_null() {+ CFRelease(value);+ }+ let role = copy_string_attr(element, "AXRole");+ let title = copy_string_attr(element, "AXTitle");+ let description = copy_string_attr(element, "AXDescription");+ ElementObservation {+ valid: true,+ role,+ subrole: None,+ label: label_of(title.as_deref(), description.as_deref()),+ identifier: copy_string_attr(element, "AXIdentifier").filter(|s| !s.is_empty()),+ frame: element_screen_rect(element).map(Rect::from_array),+ parent_label: None,+ }+}++/// Hit-test `pid` at a screen point with a short timeout. Retained result.+unsafe fn hit_test(pid: i32, x: f64, y: f64) -> Option<AXUIElementRef> {+ let app = AXUIElementCreateApplication(pid);+ if app.is_null() {+ return None;+ }+ AXUIElementSetMessagingTimeout(app, CHECK_TIMEOUT_S);+ let mut element = std::ptr::null_mut();+ let err = AXUIElementCopyElementAtPosition(app, x as f32, y as f32, &mut element);+ CFRelease(app as CFTypeRef);+ (err == 0 && !element.is_null()).then_some(element)+}++/// Whether `hit` is `target` or a descendant within a few ancestors.+unsafe fn is_self_or_ancestor(hit: AXUIElementRef, target: AXUIElementRef) -> bool {+ let mut current = hit;+ let mut owned: Vec<AXUIElementRef> = Vec::new();+ let mut found = false;+ for _ in 0..=MAX_ANCESTORS {+ if CFEqual(current as CFTypeRef, target as CFTypeRef) != 0 {+ found = true;+ break;+ }+ match copy_element_attr(current, "AXParent") {+ Some(parent) => {+ owned.push(parent);+ current = parent;+ }+ None => break,+ }+ }+ for p in owned {+ CFRelease(p as CFTypeRef);+ }+ found+}++/// Whether `hit` or one of its ancestors matches the fingerprint's role and+/// label (pixel clicks carry no reference, only what was seen there).+unsafe fn matches_fingerprint(hit: AXUIElementRef, want: &ElementFingerprint) -> bool {+ let mut current = hit;+ let mut owned: Vec<AXUIElementRef> = Vec::new();+ let mut found = false;+ for _ in 0..=MAX_ANCESTORS {+ let now = observe(current);+ if now.role.as_deref() == Some(want.role.as_str()) && now.label == want.label {+ found = true;+ break;+ }+ match copy_element_attr(current, "AXParent") {+ Some(parent) => {+ owned.push(parent);+ current = parent;+ }+ None => break,+ }+ }+ for p in owned {+ CFRelease(p as CFTypeRef);+ }+ found+}++unsafe fn hit_info(hit: AXUIElementRef) -> HitInfo {+ let o = observe(hit);+ let children = copy_children(hit);+ let child_count = children.len();+ for c in children {+ CFRelease(c as CFTypeRef);+ }+ HitInfo {+ is_window: o.role.as_deref() == Some("AXWindow"),+ role: o.role,+ has_label: o.label.is_some(),+ has_value: copy_string_attr(hit, "AXValue").is_some_and(|v| !v.trim().is_empty()),+ has_identifier: o.identifier.is_some(),+ frame: o.frame,+ child_count: Some(child_count),+ }+}++fn window_observation(+ pid: i32,+ window_id: u32,+ screen: (f64, f64),+ want: &WindowFingerprint,+) -> WindowObservation {+ let windows = crate::windows::all_windows();+ let Some(info) = windows.iter().find(|w| w.window_id == window_id) else {+ return WindowObservation {+ exists: false,+ pid,+ frame: want.frame,+ scale: want.scale,+ visible: false,+ pid_at_point: None,+ covered_at_point: None,+ };+ };+ let b = &info.bounds;+ // `z_index` grows toward the front (the frontmost window has the highest+ // value), so the window at the point is the one with the largest z_index.+ let front = windows+ .iter()+ .filter(|w| w.layer == 0 && w.is_on_screen)+ .filter(|w| {+ Rect::new(w.bounds.x, w.bounds.y, w.bounds.width, w.bounds.height)+ .contains(screen.0, screen.1)+ })+ .max_by_key(|w| w.z_index);+ WindowObservation {+ exists: true,+ pid: info.pid,+ frame: Rect::new(b.x, b.y, b.width, b.height),+ // A scale change shows as a size change in pixels; points are enough.+ scale: want.scale,+ visible: info.is_on_screen && info.on_current_space != Some(false),+ pid_at_point: front.map(|w| w.pid),+ covered_at_point: front.map(|w| w.window_id != window_id),+ }+}++/// Act-time crops from the window itself (never the screen).+struct WindowCrops {+ window_id: u32,+ /// Expected image size; a capture of another size means the window+ /// changed under us.+ size: (usize, usize),+}++impl CropSource for WindowCrops {+ fn capture(&mut self, x: i64, y: i64, w: usize, h: usize) -> Option<GrayImage> {+ let raw = crate::capture::screenshot_window_image(self.window_id).ok()?;+ let full = wire::gray_from_captured(&raw)?;+ if (full.width, full.height) != self.size {+ return None;+ }+ full.crop(x, y, w, h)+ }+ fn sleep_ms(&mut self, ms: u64) {+ std::thread::sleep(std::time::Duration::from_millis(ms));+ }+}++// ── Act time: guards ─────────────────────────────────────────────────────++/// What the caller does after a guard.+pub enum Outcome {+ /// Act. `summary` goes into the result under `fast_path`; `relocate` is+ /// a point offset in screen points for a proven pure move.+ Proceed {+ summary: Option<Value>,+ relocate: Option<(f64, f64)>,+ },+ Refuse(ToolResult),+}++#[allow(clippy::too_many_arguments)]+fn finish(+ tool: &str,+ verdict: Verdict,+ class: Option<TargetClass>,+ verified: &str,+ pid: i32,+ window_id: Option<u64>,+ started: Instant,+ relocate_scale: f64,+) -> Outcome {+ let ms = started.elapsed().as_secs_f64() * 1000.0;+ let enforce = fp::mode().enforces();+ tracing::debug!(+ target: "cua_driver::fast_path",+ tool, verified, check_ms = ms, verdict = ?verdict, "fast-path check"+ );+ match &verdict {+ Verdict::Refuse { reason, detail } if enforce => Outcome::Refuse(wire::refusal(+ tool, *reason, detail, class, pid, window_id, ms,+ )),+ Verdict::Relocated { dx, dy } if enforce => Outcome::Proceed {+ summary: Some(wire::check_summary(&verdict, class, verified, ms)),+ relocate: Some((dx / relocate_scale, dy / relocate_scale)),+ },+ _ => Outcome::Proceed {+ summary: Some(wire::check_summary(&verdict, class, verified, ms)),+ relocate: None,+ },+ }+}++/// The token path: check the cached element against its fingerprint.+/// `pixel` is true when the action is delivered as a pointer event at the+/// element's centre (button=middle) rather than an AX action.+pub async fn guard_element(+ tool: &str,+ pid: i32,+ window_id: u32,+ args: &Value,+ element_ptr: usize,+ pixel: bool,+) -> Outcome {+ if !fp::mode().checks() {+ return Outcome::Proceed {+ summary: None,+ relocate: None,+ };+ }+ let started = Instant::now();+ let token = args+ .get("element_token")+ .and_then(Value::as_str)+ .and_then(cua_driver_core::element_token::parse_token);+ let Some((snapshot_id, index)) = token else {+ return Outcome::Proceed {+ summary: None,+ relocate: None,+ };+ };+ let Some((_, _, want)) = global().element(snapshot_id, index) else {+ // Read before the flag was on: nothing to compare.+ return Outcome::Proceed {+ summary: Some(wire::check_summary(&Verdict::Ok, None, "none", 0.0)),+ relocate: None,+ };+ };+ let tool = tool.to_owned();+ let verdict = tokio::task::spawn_blocking(move || unsafe {+ let element = element_ptr as AXUIElementRef;+ let now = observe(element);+ let delivery = if pixel {+ Delivery::Pixel+ } else {+ Delivery::Semantic+ };+ let hit = if pixel {+ now.frame.map(|f| {+ let (cx, cy) = f.center();+ match hit_test(pid, cx, cy) {+ Some(h) => {+ let out = if is_self_or_ancestor(h, element) {+ HitOutcome::Target+ } else {+ HitOutcome::Other+ };+ CFRelease(h as CFTypeRef);+ out+ }+ None => HitOutcome::Nothing,+ }+ })+ } else {+ None+ };+ let mut verdict = verify_element(&want, &now, delivery, hit);+ // Pixel delivery recomputes the point from the live frame anyway, so+ // a proven pure move is fine once the new point hits the element.+ if let Verdict::Relocated { .. } = verdict {+ if hit == Some(HitOutcome::Target) {+ verdict = Verdict::Ok;+ } else {+ verdict = Verdict::refuse(+ Reason::Moved,+ "the element moved and is covered at its new spot",+ );+ }+ }+ verdict+ })+ .await+ .unwrap_or(Verdict::Ok);+ finish(+ &tool,+ verdict,+ Some(TargetClass::Rich),+ "ax",+ pid,+ Some(u64::from(window_id)),+ started,+ 1.0,+ )+}++/// The pixel path: window guards for every click, then the AX check where+/// the tree saw an element at the point, or the pixel check where it did+/// not (sparse, no tree, remote surfaces).+pub async fn guard_pixel(+ tool: &str,+ pid: i32,+ window_id: u32,+ local: (f64, f64),+ screen: (f64, f64),+ foreground: bool,+) -> Outcome {+ if !fp::mode().checks() {+ return Outcome::Proceed {+ summary: None,+ relocate: None,+ };+ }+ let started = Instant::now();+ let wid = u64::from(window_id);+ let tool_name = tool.to_owned();+ let (verdict, class, verified, scale) = tokio::task::spawn_blocking(move || unsafe {+ let store = global();+ let image = store.image(pid, wid);+ let window_fp = image+ .as_ref()+ .map(|i| i.window)+ .or_else(|| store.window(pid, wid));+ let delivery = if foreground {+ PointerDelivery::Screen+ } else {+ PointerDelivery::Background+ };+ if let Some(want) = window_fp.as_ref() {+ let now = window_observation(pid, window_id, screen, want);+ let v = verify_window(want, &now, delivery);+ if !v.is_ok() {+ return (v, None, "window", 1.0);+ }+ }+ let hit = hit_test(pid, screen.0, screen.1);+ let info = hit.map(|h| hit_info(h));+ let window_rect = window_fp+ .map(|w| w.frame)+ .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0));+ let stats = store+ .latest_stats(pid, wid)+ .map(|(elements, thin_frames)| TreeStats {+ elements,+ thin_frames,+ });+ let class = classify(info.as_ref(), stats.as_ref(), window_rect);+ let seen = store.element_at(pid, wid, screen.0, screen.1);++ // Rich target the agent saw in the tree: the element there now must+ // be the one it saw (or contain the hit).+ if class == TargetClass::Rich {+ if let (Some(want), Some(h)) = (seen.as_ref(), hit) {+ let ok = matches_fingerprint(h, want);+ CFRelease(h as CFTypeRef);+ let v = if ok {+ Verdict::Ok+ } else {+ Verdict::refuse(+ Reason::HitMismatch,+ format!(+ "you saw {} {:?} at this point; something else is there now",+ want.role,+ want.label.clone().unwrap_or_default()+ ),+ )+ };+ return (v, Some(class), "ax", 1.0);+ }+ }+ if let Some(h) = hit {+ CFRelease(h as CFTypeRef);+ }+ // Sparse, remote, or a rich point the tree never listed: pixels.+ let Some(read) = image else {+ return (Verdict::Ok, Some(class), "window_only", 1.0);+ };+ let scale = read.window.scale.max(1.0);+ let point = (local.0 * scale, local.1 * scale);+ let cfg = PixelGuardConfig::for_scale(scale, class == TargetClass::Remote);+ let mut src = WindowCrops {+ window_id,+ size: (read.image.width, read.image.height),+ };+ let check = pixel_guard::check(&read.image, point, &cfg, &mut src);+ (check.verdict, Some(class), "pixels", scale)+ })+ .await+ .unwrap_or((Verdict::Ok, None, "none", 1.0));+ finish(+ &tool_name,+ verdict,+ class,+ verified,+ pid,+ Some(wid),+ started,+ scale,+ )+}++/// Attach a check summary to a result.+pub fn annotate(result: &mut ToolResult, summary: Option<Value>) {+ if let Some(summary) = summary {+ wire::annotate(result, summary);+ }+}++#[cfg(test)]+mod tests {+ use super::label_of;++ #[test]+ fn label_prefers_title_then_description() {+ assert_eq!(label_of(Some(" Save "), Some("x")).as_deref(), Some("Save"));+ assert_eq!(label_of(Some(""), Some("2")).as_deref(), Some("2"));+ assert_eq!(label_of(None, Some(" ")), None);+ }+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs b/libs/cua-driver/rust/crates/platform-macos/src/lib.rsindex 6b847b452c..48187b4836 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs@@ -32,6 +32,8 @@ pub mod display_awake;#[cfg(target_os = "macos")]pub mod document_edit;#[cfg(target_os = "macos")]+pub mod fast_path_guard;+#[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/click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rsindex 847d036d19..e796bab5db 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@@ -383,6 +383,17 @@ impl Tool for ClickTool {}async fn invoke(&self, args: Value) -> ToolResult {+ // Fast path (CUA-3102): the guards below leave their check summary+ // here; it lands in the result under `fast_path`. Off by default.+ let mut fast_path = None;+ let mut result = self.invoke_guarded(args, &mut fast_path).await;+ crate::fast_path_guard::annotate(&mut result, fast_path);+ result+ }+}++impl ClickTool {+ async fn invoke_guarded(&self, args: Value, fast_path: &mut Option<Value>) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;// ── Window-less screen-absolute branch (scope="desktop") ──────@@ -614,6 +625,21 @@ impl Tool for ClickTool {None};+ // Fast path: check the cached element against what the agent saw.+ match crate::fast_path_guard::guard_element(+ "click",+ pid,+ wid,+ &args,+ element_ptr,+ button_str == "middle",+ )+ .await+ {+ crate::fast_path_guard::Outcome::Refuse(refusal) => return refusal,+ crate::fast_path_guard::Outcome::Proceed { summary, .. } => *fast_path = summary,+ }+// Surface 5: button=right on the AX path → AXShowMenu (the same surface// the dedicated `right_click` tool dispatches). Threads through the// identical perform_ax_click code path with the action remapped.@@ -1108,6 +1134,37 @@ impl Tool for ClickTool {None};+ // Fast path: window guards, then the AX or pixel check at the+ // point, before the cursor moves (so hover cannot change the crop).+ let (screen_x, screen_y, win_local_x, win_local_y) = if let Some(wid) = window_id {+ match crate::fast_path_guard::guard_pixel(+ "click",+ pid,+ wid,+ (win_local_x, win_local_y),+ (screen_x, screen_y),+ delivery_mode.is_foreground(),+ )+ .await+ {+ crate::fast_path_guard::Outcome::Refuse(refusal) => return refusal,+ crate::fast_path_guard::Outcome::Proceed { summary, relocate } => {+ *fast_path = summary;+ match relocate {+ Some((dx, dy)) => (+ screen_x + dx,+ screen_y + dy,+ win_local_x + dx,+ win_local_y + dy,+ ),+ None => (screen_x, screen_y, win_local_x, win_local_y),+ }+ }+ }+ } else {+ (screen_x, screen_y, win_local_x, win_local_y)+ };+// Pin the overlay above the target window BEFORE animating so// the cursor is already sandwiched correctly while it glides in.// Both PX deliveries below (AX hit-test and routed events) sharediff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rsindex a73c3d197c..7bea2c4420 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rs@@ -85,6 +85,7 @@ impl Tool for GetConfigTool {"cursor": cursor_overlay::cursor_options::saved_config_json(),"experimental_pip": pip_enabled,"experimental_pip_geometry": pip_geometry,+ "fast_path": cua_driver_core::fast_path::wire::config_value(),}))}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rsindex 034cb12088..655697e602 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs@@ -268,6 +268,13 @@ impl Tool for GetWindowStateTool {// still forces a capture (an explicit "write the frame to disk").let include_screenshot = args.get("include_screenshot").and_then(|v| v.as_bool());let should_capture = include_screenshot != Some(false) || screenshot_out_file.is_some();+ // Fast path `on`: re-reads skip the screenshot unless asked for one.+ let should_capture = should_capture+ && !cua_driver_core::fast_path::wire::skip_reread_screenshot(+ &args,+ pid,+ u64::from(window_id),+ );// `include_accessibility_tree` (default true) is the mirror image of// `include_screenshot`: set false to SKIP the AX walk (the expensive// part) and return just the screenshot + window metadata — the@@ -454,6 +461,7 @@ impl Tool for GetWindowStateTool {&bounds,|| crate::capture::screenshot_window_image(window_id),)?;+ crate::fast_path_guard::record_read_image(pid, window_id, &raw, &bounds);// Resize and encode once from the raw pixels; the PNG bytes// are identical to the former encode-decode-resize round trip.let (png, w, h) = raw.encode(max_dim, encoding).map_err(|e| {@@ -620,6 +628,19 @@ impl Tool for GetWindowStateTool {}).unzip(),};+ if let (Some(sid), Some(tree)) = (snapshot_id, tree_result.as_ref()) {+ if !observation_only {+ crate::fast_path_guard::record_snapshot(+ pid,+ u64::from(window_id),+ sid,+ &tree.nodes,+ );+ if screenshot.is_none() {+ crate::fast_path_guard::record_window(pid, window_id);+ }+ }+ }// The capture registry holds PNG captures only; a JPEG read mints none.let capture_id = match (snapshot_id, screenshot.as_ref().filter(|_| !jpeg)) {(Some(_), Some((png, _, width, height, native_width, native_height, _, _))) => {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rsindex 0db91885ae..8bb91ee2fb 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs@@ -26,7 +26,7 @@ fn with_cursor_motion_properties(mut schema: Value) -> Value {properties.extend(cursor_overlay::badge_mode::config_schema_properties());properties.extend(cursor_overlay::cursor_options::config_schema_properties());}- schema+ cua_driver_core::fast_path::wire::with_config_property(schema)}fn def() -> &'static ToolDef {@@ -122,6 +122,11 @@ impl Tool for SetConfigTool {Err(message) => return ToolResult::error(message),};+ let fast_path = match cua_driver_core::fast_path::wire::apply_config_args(&args) {+ Ok(mode) => mode,+ Err(message) => return ToolResult::error(message),+ };+let max_dim: Option<u32> = match args.opt_u64("max_image_dimension") {Some(dim) => match u32::try_from(dim) {Ok(d) => Some(d),@@ -195,6 +200,12 @@ impl Tool for SetConfigTool {motion_keys.join(", ")));}+ if let Some(mode) = fast_path {+ pip_note.push_str(&format!(+ " — fast_path={} (applies now, not saved)",+ mode.as_str()+ ));+ }for key in badge_key.into_iter().chain(option_keys) {pip_note.push_str(&format!(" — saved {key} (applies now)"));}@@ -211,6 +222,7 @@ impl Tool for SetConfigTool {"version": env!("CARGO_PKG_VERSION"),"platform": "macos","max_image_dimension": effective_dim,+ "fast_path": cua_driver_core::fast_path::wire::config_value(),}))}}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/get_config.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/get_config.rsindex e7eca6a9a4..5a7b45f804 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/get_config.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/get_config.rs@@ -58,6 +58,7 @@ impl Tool for GetConfigTool {"cursor": cursor_overlay::cursor_options::saved_config_json(),"experimental_pip": pip_enabled,"experimental_pip_geometry": pip_geometry,+ "fast_path": cua_driver_core::fast_path::wire::config_value(),});// Match Swift's text format 1:1: `"✅ <pretty JSON>"`.let pretty = serde_json::to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string());diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/set_config.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/set_config.rsindex 680e8bf450..0acfaf98d2 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/set_config.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/set_config.rs@@ -46,7 +46,8 @@ impl Tool for SetConfigTool {"capture_mode":{"type":"string","enum":["ax","vision"],"description":"DEPRECATED and ignored — get_window_state always returns both the UIA tree and a screenshot. Still accepted/persisted for back-compat but has no effect. (\"som\"/\"screenshot\" still decode as deprecated aliases.)"},"max_image_dimension":{"type":"integer","description":"Max dimension for screenshot resizing (0 = no limit)."},"experimental_pip":{"type":"boolean","description":"Enables PiP preview (applies next restart)."},- "experimental_pip_geometry":{"type":"string","description":"PiP window size + optional position."}+ "experimental_pip_geometry":{"type":"string","description":"PiP window size + optional position."},+ "fast_path": cua_driver_core::fast_path::wire::config_schema()},"additionalProperties":false})),read_only: false, destructive: false, idempotent: true, open_world: false,})@@ -92,6 +93,11 @@ impl Tool for SetConfigTool {}applied = true;}+ match cua_driver_core::fast_path::wire::apply_config_args(&args) {+ Ok(Some(_)) => applied = true,+ Ok(None) => {}+ Err(message) => return ToolResult::error(message),+ }if let Some(enabled) = args.get("experimental_pip").and_then(|v| v.as_bool()) {if let Err(e) = pip_preview::write_config_key("experimental_pip", Value::Bool(enabled)){@@ -141,6 +147,7 @@ impl Tool for SetConfigTool {"agent_cursor": { "enabled": cursor_enabled },"experimental_pip": pip_enabled,"experimental_pip_geometry": pip_geometry,+ "fast_path": cua_driver_core::fast_path::wire::config_value(),});let pretty = serde_json::to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string());ToolResult::text(format!("✅ {pretty}")).with_structured(payload)diff --git a/libs/cua-driver/scripts/fast-path-bench.py b/libs/cua-driver/scripts/fast-path-bench.pynew file mode 100755index 0000000000..cb36ffbf67--- /dev/null+++ b/libs/cua-driver/scripts/fast-path-bench.py@@ -0,0 +1,389 @@+#!/usr/bin/env python3+"""Fast-path A/B bench and race tests against FastPathFixture (CUA-3102).++Runs on macOS with a Cua Driver daemon and the fixture running:+ swiftc -O tests/fixtures/apps/macos/fast-path/FastPathFixture.swift -o /tmp/FastPathFixture+ /tmp/FastPathFixture /tmp/fpfix &+ python3 scripts/fast-path-bench.py --out /tmp/fast-path-results.json++Every tool call is one model-visible turn in a direct-call agent loop, so+`turns` counts calls. Tool wall time is measured per call; model time is+not included (the report adds an estimate per turn).+"""++import argparse+import json+import os+import random+import re+import statistics+import subprocess+import time++FIX = "/tmp/fpfix"+CLI = os.path.expanduser(os.environ.get("CUA_DRIVER_CLI", "~/.local/bin/cua-driver"))+SESSION = os.environ.get("FP_SESSION", "fast-path-bench")+WIN = {"x": 0.0, "y": 0.0, "scale": 1.0}+++def call(tool, args):+ t = time.perf_counter()+ # Snapshots are session-scoped and each CLI call is its own connection,+ # so a shared session label is what lets reads and actions chain.+ if tool not in ("set_config", "get_config"):+ args = dict(args, session=SESSION)+ p = subprocess.run([CLI, "call", tool, json.dumps(args)], capture_output=True, text=True, timeout=60)+ dt = (time.perf_counter() - t) * 1000+ out = p.stdout.strip()+ data = None+ try:+ data = json.loads(out)+ except ValueError:+ m = re.search(r"\{.*\}\s*$", out, re.S)+ if m:+ try:+ data = json.loads(m.group(0))+ except ValueError:+ data = None+ return {"tool": tool, "ms": dt, "text": out, "json": data or {}, "rc": p.returncode, "err": p.stderr.strip()}+++def structured(r):+ j = r["json"]+ return j.get("structuredContent") or j.get("structured_content") or j+++def is_error(r):+ j = r["json"]+ return bool(j.get("isError") or j.get("is_error")) or r["rc"] != 0+++def fixture(cmd):+ with open(os.path.join(FIX, "cmd"), "a") as f:+ f.write(cmd + "\n")+++def wait_ack(n, budget=2.0):+ end = time.time() + budget+ while time.time() < end:+ try:+ if open(os.path.join(FIX, "ack")).read().strip() == f"ack {n}":+ return True+ except OSError:+ pass+ time.sleep(0.01)+ return False+++class Fixture:+ def __init__(self):+ self.n = 0+ open(os.path.join(FIX, "log"), "a").close()++ def do(self, cmd, wait=True):+ fixture(cmd)+ self.n += 1+ if wait:+ wait_ack(self.n)++ def log_mark(self):+ return len(open(os.path.join(FIX, "log")).read().splitlines())++ def log_since(self, mark):+ time.sleep(0.25)+ lines = open(os.path.join(FIX, "log")).read().splitlines()[mark:]+ return [l for l in lines if not l.startswith("applied")]+++def target():+ r = call("list_windows", {"app": "FastPathFixture"})+ s = structured(r)+ wins = s.get("windows") or []+ for w in wins:+ if "FastPath" in (w.get("title") or ""):+ b = w.get("bounds") or w.get("frame") or {}+ WIN["x"], WIN["y"] = float(b.get("x", 0)), float(b.get("y", 0))+ return w["pid"], w["window_id"], b+ raise SystemExit(f"fixture window not found: {r['text'][:400]}")+++def read(pid, wid, screenshot=True, since=None):+ args = {"pid": pid, "window_id": wid, "tree_format": "elements", "include_screenshot": screenshot}+ if since:+ args["since"] = since+ r = call("get_window_state", args)+ st = structured(r)+ sw, wb = st.get("screenshot_width"), st.get("window_bounds") or {}+ if sw and wb.get("width"):+ WIN["scale"] = sw / wb["width"]+ return r, st+++def elements(s):+ return s.get("elements") or []+++def find(s, label, role=None):+ for e in elements(s):+ names = [e.get(k) for k in ("title", "label", "description", "name")]+ if label in [n for n in names if n] and (role is None or e.get("role") == role):+ return e+ return None+++def token(s, e):+ return e.get("element_token") or f"{s.get('snapshot_id')}:{e.get('element_index', e.get('index'))}"+++def center_local(e, win):+ f = e.get("frame") or e.get("window_frame")+ if isinstance(f, dict):+ x, y = f["x"], f["y"]+ w, h = f.get("w", f.get("width")), f.get("h", f.get("height"))+ else:+ x, y, w, h = f+ return x + w / 2 - WIN["x"], y + h / 2 - WIN["y"]+++def px(x, y):+ """Window-local points to screenshot pixels, the unit pixel clicks take."""+ args = {"x": int(round(x * WIN["scale"])), "y": int(round(y * WIN["scale"]))}+ # Pixel clicks are delivered in the foreground by default so the bench is+ # deterministic. Background pixel clicks were re-checked on the macOS 27.2+ # VM (two window origins, target behind another app, fast_path off, guard and on) and+ # land on the right element; set FP_PIXEL_DELIVERY=background to use them.+ mode = os.environ.get("FP_PIXEL_DELIVERY", "foreground")+ if mode != "background":+ args["delivery_mode"] = mode+ return args+++def set_mode(mode):+ call("set_config", {"fast_path": mode})+++# ── Bench tasks ─────────────────────────────────────────────────────────+++def task_form(pid, wid, mode, fx):+ fx.do("reset")+ calls = []+ r, s = read(pid, wid)+ calls.append(r)+ values = {"Name": "Ada", "Email": "[email protected]", "City": "Turin"}+ for label, value in values.items():+ if mode == "off":+ r, s = read(pid, wid)+ calls.append(r)+ e = find(s, label)+ if e is None:+ return calls, "field not found"+ r = call("type_text", {"pid": pid, "window_id": wid, "element_token": token(s, e), "text": value})+ calls.append(r)+ s = next_state(s, r)+ if mode == "off":+ r, s = read(pid, wid)+ calls.append(r)+ e = find(s, "Submit")+ r = call("click", {"pid": pid, "window_id": wid, "element_token": token(s, e)})+ calls.append(r)+ return calls, None+++def next_state(s, r):+ """After an action with fast_path=on, tokens move to the delta's snapshot."""+ d = (structured(r).get("fast_path") or {}).get("delta") or {}+ sid = d.get("snapshot_id")+ if not sid:+ return s+ s2 = dict(s)+ s2["snapshot_id"] = sid+ s2["elements"] = [dict(e, element_token=f"{sid}:{e.get('element_index', e.get('index'))}") for e in elements(s)]+ return s2+++def task_settings(pid, wid, mode, fx):+ fx.do("reset")+ calls = []+ r, s = read(pid, wid)+ calls.append(r)+ for i in range(1, 7):+ if mode == "off":+ r, s = read(pid, wid)+ calls.append(r)+ e = find(s, f"Option {i}")+ r = call("click", {"pid": pid, "window_id": wid, "element_token": token(s, e)})+ calls.append(r)+ s = next_state(s, r)+ return calls, None+++def task_canvas(pid, wid, mode, fx, canvas_origin):+ """Three pixel clicks on the canvas tile (no tree there)."""+ fx.do("reset")+ calls = []+ r, s = read(pid, wid)+ calls.append(r)+ cx, cy = canvas_origin[0] + 64, canvas_origin[1] + 54+ for _ in range(3):+ if mode == "off":+ r, s = read(pid, wid)+ calls.append(r)+ r = call("click", dict({"pid": pid, "window_id": wid}, **px(cx, cy)))+ calls.append(r)+ return calls, None+++def run_bench(pid, wid, fx, canvas_origin, reps):+ out = {}+ for mode in ("off", "on"):+ set_mode(mode)+ for name, fn in (("form", task_form), ("settings", task_settings), ("canvas", task_canvas)):+ rows = []+ for _ in range(reps):+ mark = fx.log_mark()+ t = time.perf_counter()+ calls, err = fn(pid, wid, mode, fx, canvas_origin) if name == "canvas" else fn(pid, wid, mode, fx)+ wall = (time.perf_counter() - t) * 1000+ refusals = sum(1 for c in calls if is_error(c) and "target_changed" in c["text"] + json.dumps(c["json"]))+ actions = sum(1 for c in calls if '"tool"' not in c["text"][:0]) - sum(1 for _ in [])+ rows.append({+ "wall_ms": wall,+ "turns": len(calls),+ "tool_ms": sum(c["ms"] for c in calls),+ "per_call": [(c["tool"], c["ms"]) for c in calls],+ "errors": sum(1 for c in calls if is_error(c)),+ "false_refusals": refusals,+ "err": err,+ "log": fx.log_since(mark),+ })+ out[f"{name}/{mode}"] = {+ "wall_ms_median": statistics.median(r["wall_ms"] for r in rows),+ "turns": rows[0]["turns"],+ "tool_ms_median": statistics.median(r["tool_ms"] for r in rows),+ "per_tool_ms_median": {+ t: statistics.median(ms for r in rows for (tt, ms) in r["per_call"] if tt == t)+ for t in sorted({tt for r in rows for (tt, _) in r["per_call"]})+ },+ "all_ok": all(not r["errors"] for r in rows),+ "errors": sum(r["errors"] for r in rows),+ "false_refusals": sum(r["false_refusals"] for r in rows),+ "sample_log": rows[0]["log"],+ "err": [r["err"] for r in rows if r["err"]],+ }+ set_mode("off")+ return out+++# ── Race tests (fast_path=guard) ───────────────────────────────────────+++def race_tests(pid, wid, fx, canvas_origin, iterations):+ set_mode("guard")+ res = {}++ def pixel_click_after(change, label):+ fx.do("reset")+ r, s = read(pid, wid)+ e = find(s, label)+ x, y = center_local(e, None)+ mark = fx.log_mark()+ fx.do(change)+ c = call("click", dict({"pid": pid, "window_id": wid}, **px(x, y)))+ return c, fx.log_since(mark)++ def token_click_after(change, label):+ fx.do("reset")+ r, s = read(pid, wid)+ e = find(s, label)+ mark = fx.log_mark()+ fx.do(change)+ c = call("click", {"pid": pid, "window_id": wid, "element_token": token(s, e)})+ return c, fx.log_since(mark)++ def summarize(c, log):+ st = structured(c)+ return {+ "refused": is_error(c),+ "reason": st.get("reason"),+ "fast_path": st.get("fast_path"),+ "log": log,+ }++ res["moved_pixel"] = summarize(*pixel_click_after("move_alpha 120", "Alpha"))+ res["moved_token"] = summarize(*token_click_after("move_alpha 120", "Alpha"))+ res["swap_pixel"] = summarize(*pixel_click_after("swap", "Alpha"))+ res["swap_token"] = summarize(*token_click_after("swap", "Alpha"))+ res["relabel_token"] = summarize(*token_click_after("relabel_alpha Gamma", "Alpha"))+ res["removed_token"] = summarize(*token_click_after("remove_beta", "Beta"))++ cx, cy = canvas_origin[0] + 64, canvas_origin[1] + 54+ for name, change in (("canvas_move", "canvas_move 40"), ("canvas_shape", "canvas_shape")):+ fx.do("reset")+ read(pid, wid)+ mark = fx.log_mark()+ fx.do(change)+ c = call("click", dict({"pid": pid, "window_id": wid}, **px(cx, cy)))+ res[name] = summarize(c, fx.log_since(mark))++ # Randomized race: a random change lands 0-50 ms after the read.+ wrong = refused = acted = 0+ changes = ["move_alpha 120", "swap", "relabel_alpha Gamma", "noop"]+ for i in range(iterations):+ fx.do("reset")+ r, s = read(pid, wid, screenshot=False)+ e = find(s, "Alpha")+ x, y = center_local(e, None)+ change = random.choice(changes)+ pixel = random.random() < 0.5+ mark = fx.log_mark()+ if change != "noop":+ fx.do(change, wait=False)+ time.sleep(random.uniform(0, 0.05))+ args = {"pid": pid, "window_id": wid}+ args.update(px(x, y) if pixel else {"element_token": token(s, e)})+ c = call("click", args)+ log = fx.log_since(mark)+ presses = [l for l in log if l.startswith("pressed")]+ if is_error(c):+ refused += 1+ else:+ acted += 1+ if any(l != "pressed Alpha" for l in presses):+ # Relabelled Alpha shows as "pressed Gamma": the agent meant Alpha.+ wrong += 1+ res["random_race"] = {"iterations": iterations, "acted": acted, "refused": refused, "wrong_target": wrong}++ # Static false refusals: no change at all.+ fx.do("reset")+ r, s = read(pid, wid)+ e = find(s, "Alpha")+ x, y = center_local(e, None)+ stat = {"alpha_pixel": 0, "canvas_pixel": 0, "n": iterations}+ for _ in range(iterations):+ if is_error(call("click", dict({"pid": pid, "window_id": wid}, **px(x, y)))):+ stat["alpha_pixel"] += 1+ if is_error(call("click", dict({"pid": pid, "window_id": wid}, **px(cx, cy)))):+ stat["canvas_pixel"] += 1+ res["static_false_refusals"] = stat+ set_mode("off")+ return res+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--out", default="/tmp/fast-path-results.json")+ ap.add_argument("--reps", type=int, default=5)+ ap.add_argument("--iterations", type=int, default=100)+ ap.add_argument("--canvas-origin", default="380,40", help="canvas top-left in window points")+ a = ap.parse_args()+ pid, wid, _ = target()+ fx = Fixture()+ origin = tuple(float(v) for v in a.canvas_origin.split(","))+ result = {"bench": run_bench(pid, wid, fx, origin, a.reps), "race": race_tests(pid, wid, fx, origin, a.iterations)}+ json.dump(result, open(a.out, "w"), indent=2)+ print(json.dumps(result, indent=2)[:6000])+++if __name__ == "__main__":+ main()diff --git a/libs/cua-driver/tests/fixtures/apps/macos/fast-path/FastPathFixture.swift b/libs/cua-driver/tests/fixtures/apps/macos/fast-path/FastPathFixture.swiftnew file mode 100644index 0000000000..56c69f6923--- /dev/null+++ b/libs/cua-driver/tests/fixtures/apps/macos/fast-path/FastPathFixture.swift@@ -0,0 +1,165 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 Cua AI, Inc.+//+// Fast-path race fixture (CUA-3102). A test, not a timer, decides when the+// UI changes: write one command per line to $DIR/cmd; the fixture applies it+// within 20 ms and appends "ack <n>" to $DIR/ack. Every press is logged to+// $DIR/log so a harness can tell a right click from a wrong one.+//+// Build: swiftc -O FastPathFixture.swift -o FastPathFixture+// Run: ./FastPathFixture /tmp/fpfix+//+// Commands: move_alpha <dx> | swap | relabel_alpha <name> | remove_beta |+// canvas_move <dx> | canvas_shape | reset++import AppKit++let dir = URL(fileURLWithPath: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "/tmp/fpfix")+try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)++func log(_ line: String) {+ let url = dir.appendingPathComponent("log")+ let data = (line + "\n").data(using: .utf8)!+ if let h = try? FileHandle(forWritingTo: url) {+ h.seekToEndOfFile(); h.write(data); try? h.close()+ } else {+ try? data.write(to: url)+ }+}++/// A canvas with no accessibility children: draws one tile.+final class Canvas: NSView {+ var tile = NSRect(x: 40, y: 40, width: 48, height: 28)+ var circle = false+ override var isFlipped: Bool { true }+ override func isAccessibilityElement() -> Bool { false }+ override func accessibilityChildren() -> [Any]? { [] }+ override func draw(_ dirtyRect: NSRect) {+ NSColor(white: 0.85, alpha: 1).setFill()+ bounds.fill()+ NSColor(white: 0.75, alpha: 1).setFill()+ for i in stride(from: 0, to: Int(bounds.width), by: 32) {+ NSRect(x: CGFloat(i), y: 0, width: 16, height: bounds.height).fill()+ }+ if circle {+ NSColor.systemOrange.setFill()+ NSBezierPath(ovalIn: tile.insetBy(dx: 8, dy: 0)).fill()+ } else {+ NSColor(white: 0.15, alpha: 1).setFill()+ tile.fill()+ NSColor.white.setFill()+ NSRect(x: tile.minX + 6, y: tile.minY + 10, width: 18, height: 6).fill()+ NSColor.systemBlue.setFill()+ NSRect(x: tile.minX + 30, y: tile.minY + 6, width: 10, height: 16).fill()+ }+ }+ override func mouseDown(with event: NSEvent) {+ let p = convert(event.locationInWindow, from: nil)+ if tile.contains(p) && !circle {+ log("canvas hit")+ } else {+ log("canvas miss \(Int(p.x)),\(Int(p.y))")+ }+ }+}++final class Fixture: NSObject, NSApplicationDelegate {+ let window = NSWindow(contentRect: NSRect(x: 120, y: 120, width: 720, height: 520),+ styleMask: [.titled, .closable], backing: .buffered, defer: false)+ let content = NSView(frame: NSRect(x: 0, y: 0, width: 720, height: 520))+ var alpha: NSButton!+ var beta: NSButton!+ var fields: [NSTextField] = []+ var checks: [NSButton] = []+ let canvas = Canvas(frame: NSRect(x: 380, y: 200, width: 320, height: 280))+ var seen = 0++ func button(_ title: String, _ frame: NSRect) -> NSButton {+ let b = NSButton(title: title, target: self, action: #selector(pressed(_:)))+ b.frame = frame+ content.addSubview(b)+ return b+ }++ @objc func pressed(_ sender: NSButton) {+ if sender.title == "Submit" {+ log("submit " + fields.map { $0.stringValue }.joined(separator: "|"))+ } else {+ log("pressed \(sender.title)")+ }+ }++ @objc func toggled(_ sender: NSButton) {+ log("toggled \(sender.title) \(sender.state == .on ? 1 : 0)")+ }++ func applicationDidFinishLaunching(_ notification: Notification) {+ window.title = "FastPath Fixture"+ window.contentView = content+ for (i, name) in ["Name", "Email", "City"].enumerated() {+ let label = NSTextField(labelWithString: name)+ label.frame = NSRect(x: 20, y: 470 - i * 40, width: 60, height: 22)+ content.addSubview(label)+ let field = NSTextField(frame: NSRect(x: 90, y: 470 - i * 40, width: 240, height: 24))+ field.placeholderString = name+ field.setAccessibilityLabel(name)+ content.addSubview(field)+ fields.append(field)+ }+ _ = button("Submit", NSRect(x: 90, y: 340, width: 100, height: 30))+ for i in 1...6 {+ let c = NSButton(checkboxWithTitle: "Option \(i)", target: self, action: #selector(toggled(_:)))+ c.frame = NSRect(x: 20, y: 290 - (i - 1) * 28, width: 160, height: 22)+ content.addSubview(c)+ checks.append(c)+ }+ alpha = button("Alpha", NSRect(x: 200, y: 260, width: 100, height: 30))+ beta = button("Beta", NSRect(x: 200, y: 200, width: 100, height: 30))+ content.addSubview(canvas)+ window.makeKeyAndOrderFront(nil)+ NSApp.activate(ignoringOtherApps: true)+ Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { [weak self] _ in self?.poll() }+ }++ func poll() {+ guard let text = try? String(contentsOf: dir.appendingPathComponent("cmd"), encoding: .utf8) else { return }+ let lines = text.split(separator: "\n").map(String.init)+ while seen < lines.count {+ apply(lines[seen])+ seen += 1+ let ack = dir.appendingPathComponent("ack")+ try? "ack \(seen)\n".data(using: .utf8)!.write(to: ack)+ }+ }++ func apply(_ line: String) {+ let parts = line.split(separator: " ").map(String.init)+ guard let cmd = parts.first else { return }+ let arg = parts.count > 1 ? parts[1] : ""+ switch cmd {+ case "move_alpha": alpha.frame.origin.x += CGFloat(Double(arg) ?? 80)+ case "swap":+ let f = alpha.frame; alpha.frame = beta.frame; beta.frame = f+ case "relabel_alpha": alpha.title = arg.isEmpty ? "Gamma" : arg+ case "remove_beta": beta.removeFromSuperview()+ case "canvas_move": canvas.tile.origin.x += CGFloat(Double(arg) ?? 40); canvas.needsDisplay = true+ case "canvas_shape": canvas.circle = true; canvas.needsDisplay = true+ case "reset":+ alpha.title = "Alpha"; alpha.frame = NSRect(x: 200, y: 260, width: 100, height: 30)+ if beta.superview == nil { content.addSubview(beta) }+ beta.frame = NSRect(x: 200, y: 200, width: 100, height: 30)+ canvas.tile = NSRect(x: 40, y: 40, width: 48, height: 28); canvas.circle = false+ canvas.needsDisplay = true+ fields.forEach { $0.stringValue = "" }+ checks.forEach { $0.state = .off }+ default: log("unknown command \(line)")+ }+ log("applied \(line)")+ }+}++let app = NSApplication.shared+let delegate = Fixture()+app.delegate = delegate+app.setActivationPolicy(.regular)+app.run()diff --git a/libs/cua-driver/typescript/src/native/cua_driver_contract.ts b/libs/cua-driver/typescript/src/native/cua_driver_contract.tsindex e4bcf4b4a2..0137a30bb5 100644--- a/libs/cua-driver/typescript/src/native/cua_driver_contract.ts+++ b/libs/cua-driver/typescript/src/native/cua_driver_contract.ts@@ -514,7 +514,14 @@ export type ActionResult = {* The call that moves the task forward, always safe to run as is (a read,* or a call that keeps the user's window where it is).*/- nextCall?: ActionNextCall+ nextCall?: ActionNextCall,+ /**+ * Present only when the `fast_path` config key is `on`: the check cost,+ * the target class and the changed regions since the last read, as one+ * JSON object. Absent when the flag is off, so default results are+ * unchanged.+ */+ fastPath?: string}/**@@ -546,7 +553,8 @@ const FfiConverterTypeActionResult = (() => {summary: FfiConverterOptionalString.read(from),error: FfiConverterOptionalTypeActionError.read(from),hint: FfiConverterOptionalString.read(from),- nextCall: FfiConverterOptionalTypeActionNextCall.read(from)+ nextCall: FfiConverterOptionalTypeActionNextCall.read(from),+ fastPath: FfiConverterOptionalString.read(from)};}write(value: TypeName, into: RustBuffer): void {@@ -559,6 +567,7 @@ const FfiConverterTypeActionResult = (() => {FfiConverterOptionalTypeActionError.write(value.error, into);FfiConverterOptionalString.write(value.hint, into);FfiConverterOptionalTypeActionNextCall.write(value.nextCall, into);+ FfiConverterOptionalString.write(value.fastPath, into);}allocationSize(value: TypeName): number {return FfiConverterTypeActionEffect.allocationSize(value.effect) +@@ -569,7 +578,8 @@ const FfiConverterTypeActionResult = (() => {FfiConverterOptionalString.allocationSize(value.summary) +FfiConverterOptionalTypeActionError.allocationSize(value.error) +FfiConverterOptionalString.allocationSize(value.hint) +- FfiConverterOptionalTypeActionNextCall.allocationSize(value.nextCall);+ FfiConverterOptionalTypeActionNextCall.allocationSize(value.nextCall) ++ FfiConverterOptionalString.allocationSize(value.fastPath);}};diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.jsonindex aea010729e..9556c6535b 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json@@ -2270,6 +2270,16 @@"description": "PiP window size + optional position in `WxH` or `WxH+X+Y` form.","type": "string"},+ "fast_path": {+ "description": "Experimental fast path (default off). shadow: check cached targets at act time and report would-refuse verdicts; guard: refuse an action whose target changed since it was read (target_changed); on: guard, plus a small delta in each action result and tree-only re-reads. Runtime only, not saved; env CUA_DRIVER_FAST_PATH seeds it at start.",+ "enum": [+ "off",+ "shadow",+ "guard",+ "on"+ ],+ "type": "string"+ },"max_image_dimension": {"description": "Max dimension for screenshot resizing (0 = no limit).","type": "integer"diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.jsonindex 7885b20235..71baa73494 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json@@ -1998,6 +1998,16 @@"description": "PiP window size + optional position in `WxH` or `WxH+X+Y` form (e.g. `320x200+24+24`). Applies on next daemon restart.","type": "string"},+ "fast_path": {+ "description": "Experimental fast path (default off). shadow: check cached targets at act time and report would-refuse verdicts; guard: refuse an action whose target changed since it was read (target_changed); on: guard, plus a small delta in each action result and tree-only re-reads. Runtime only, not saved; env CUA_DRIVER_FAST_PATH seeds it at start.",+ "enum": [+ "off",+ "shadow",+ "guard",+ "on"+ ],+ "type": "string"+ },"max_image_dimension": {"description": "Max dimension for screenshot resizing (0 = no limit).","type": "integer"diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.jsonindex 262daa5640..78ca75b102 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json@@ -1964,6 +1964,16 @@"description": "PiP window size + optional position.","type": "string"},+ "fast_path": {+ "description": "Experimental fast path (default off). shadow: check cached targets at act time and report would-refuse verdicts; guard: refuse an action whose target changed since it was read (target_changed); on: guard, plus a small delta in each action result and tree-only re-reads. Runtime only, not saved; env CUA_DRIVER_FAST_PATH seeds it at start.",+ "enum": [+ "off",+ "shadow",+ "guard",+ "on"+ ],+ "type": "string"+ },"max_image_dimension": {"description": "Max dimension for screenshot resizing (0 = no limit).","type": "integer"