Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat: rebuild the agent cursor overlay and fix seen-but-unactionable elements (#145)
Lahfir5ec2504bec0e
diff --git a/CONCEPTS.md b/CONCEPTS.mdindex ab0841ead..3815051e8 100644--- a/CONCEPTS.md+++ b/CONCEPTS.md@@ -110,7 +110,7 @@ Core owns those preconditions through `HeadedRequirement`: `FocusedWindow` for k### Agent Cursor Overlay-An optional presentation-only cursor driven by verified action destinations. Its configuration is enabled or disabled once in a session manifest with `cursor-overlay`; action and batch commands inherit it without cursor flags. Headed mode suppresses the overlay because the real pointer already represents the action. It never moves or replaces the OS pointer and never changes Interaction Policy, action delivery, or response semantics. Shared configuration and motion stay platform-neutral; macOS supplies the native renderer while other platforms inherit the adapter's default no-op.+An optional presentation-only cursor driven by verified action destinations. Its whole configuration — label, colours, size, and click effects — is set once per session with `session start --cursor` or `cursor-overlay enable`; action and batch commands inherit it and take no cursor flags. Motion models a human hand and the cursor never rotates or resizes. The renderer acknowledges arrival before the action dispatches, under a bounded timeout, so the picture and the real effect stay in step. A click plays a ripple and flashes an outline around the element. Headed mode suppresses the overlay. It never moves or replaces the OS pointer and never changes Interaction Policy, action delivery, or response semantics. Configuration, motion, and effect timing live in `agent-desktop-core`; macOS supplies the native renderer while other platforms inherit the adapter's default no-op.### Headless Ref ActionA ref-based action that uses semantic accessibility operations without implicit focus stealing, cursor movement, synthetic keyboard input, or pasteboard use. This is the default mode.diff --git a/README.md b/README.mdindex ffaa191b8..65aa42630 100644--- a/README.md+++ b/README.md@@ -101,7 +101,7 @@ Every GitHub Release ships a prebuilt C-ABI cdylib (`libagent_desktop_ffi`) for```pythonimport ctypeslib = ctypes.CDLL("./lib/libagent_desktop_ffi.dylib")-lib.ad_init(3) # verify ABI major (AD_ABI_VERSION_MAJOR) before any call+lib.ad_init(4) # verify ABI major (AD_ABI_VERSION_MAJOR) before any calladapter = lib.ad_adapter_create()# observe -> act: ad_snapshot -> parse a qualified ref -> ad_execute_by_ref ...lib.ad_adapter_destroy(adapter)@@ -176,16 +176,47 @@ agent-desktop session gc### Agent cursor overlay (macOS)-Enable the presentation-only cursor once for a session. Every eligible headless action in that session inherits the setting; action and batch entries do not take cursor-enable flags.+A presentation-only cursor that shows what the agent is about to do. Off by default.```bash-agent-desktop --session <session_id> cursor-overlay enable \- --label "Opening profile menu" --max-words 6-agent-desktop --session <session_id> click @s8f3k2p9:e9-agent-desktop --session <session_id> cursor-overlay disable+session_id=$(agent-desktop session start --cursor | jq -r '.data.session_id')+export AGENT_DESKTOP_SESSION="$session_id"+agent-desktop snapshot --app Finder -i+agent-desktop click <qualified-ref-from-snapshot>+agent-desktop cursor-overlay disable+```++`session start --cursor` turns it on with the default look. `cursor-overlay enable` does the same for a session that already exists.++**Style is session-global.** Set it once; every later command uses it. Never pass it per action.++```bash+agent-desktop --session "$session_id" cursor-overlay enable --label "Opening the menu"+export AGENT_DESKTOP_SESSION="$session_id"```-Enabling immediately shows the persistent cursor with “Hey, let's play with this computer!” The current card remains visible until its description changes; the old card then eases out and the new text eases in. Actions reuse the cursor's last position for the same eased, swinging glide and briefly switch to a hand pointer for click feedback. The solid white card has a 1.5px near-black border and stays at the cursor's bottom-right. The overlay never moves or intercepts the OS pointer and remains until `cursor-overlay disable` or session end. Headed actions temporarily hide it while the real cursor is in use. macOS renders the overlay natively; Windows and Linux inherit the platform adapter's presentation no-op and need only add their native renderer to support the same session contract.+| Flag | Meaning | Default |+|---|---|---|+| `--label TEXT` | Intent text beside the cursor | none |+| `--max-words N` | Label word limit, 1–12 | 6 |+| `--fill HEX` | Cursor body | `#FFFFFF` |+| `--rim HEX` | Cursor outline | `#111318` |+| `--accent HEX` | Ripple and element outline | `#4299FF` |+| `--size N` | Size multiplier, 0.5–4.0 | 1.0 |+| `--no-ripple` | No ripple on click | ripple on |+| `--no-highlight` | No element outline on click | outline on |++**Behaviour**++- The cursor travels a human path in 90–320 ms. It never rotates or resizes.+- The action waits for it to land, so a window never closes before the cursor arrives. The wait is capped at 900 ms and never blocks an action.+- A click plays a ripple, then flashes an accent outline around the element for 0.9 s. Both draw below the cursor.+- Idle for 6 s, it fades out. The next command brings it back.+- `cursor-overlay disable` removes it now. You do not have to end the session.+- Headed actions hide it. It never moves or intercepts the OS pointer.+- Overhead is about 150–300 ms per action, all of it the visible travel.++macOS renders it natively. Windows and Linux inherit the adapter's no-op and need only their own renderer against the same core contract.## Driving Chromium apps (CDP)@@ -347,12 +378,13 @@ agent-desktop --session run-a batch '[### System```bash-agent-desktop session start [--name LABEL] [--no-trace] # create session; pass returned ID explicitly+agent-desktop session start [--name LABEL] [--no-trace] [--cursor] # create session; pass returned ID explicitlyagent-desktop session end [id]agent-desktop session listagent-desktop session gc [--older-than SECS] [--ended]-agent-desktop --session <id> cursor-overlay enable [--label TEXT] [--max-words N]-agent-desktop --session <id> cursor-overlay disable+agent-desktop --session <id> cursor-overlay enable [--label TEXT] [--max-words N] [--fill HEX] [--rim HEX] [--accent HEX] [--size N] [--no-ripple] [--no-highlight]+export AGENT_DESKTOP_SESSION=<id>+agent-desktop cursor-overlay disableagent-desktop status # platform, permissions, session_id, tracing, latest snapshotagent-desktop permissions # check accessibility/screen-recording/automationagent-desktop permissions --request # request in the bounded isolated helperdiff --git a/crates/core/src/actionability/evaluate.rs b/crates/core/src/actionability/evaluate.rsindex 1b289998f..0d84addb8 100644--- a/crates/core/src/actionability/evaluate.rs+++ b/crates/core/src/actionability/evaluate.rs@@ -110,6 +110,7 @@ pub(super) fn check_with_stability(checks,verified_point,presentation_point,+ evidence.bounds,pointer_delivery,),);@@ -134,6 +135,7 @@ pub(super) fn check_with_stability(checks,verified_point,presentation_point,+ evidence.bounds,pointer_delivery,),)diff --git a/crates/core/src/actionability/receives_events.rs b/crates/core/src/actionability/receives_events.rsindex 4b62176ca..150fdf814 100644--- a/crates/core/src/actionability/receives_events.rs+++ b/crates/core/src/actionability/receives_events.rs@@ -102,7 +102,7 @@ pub(crate) fn require_receives_events(Ok(HitTestResult::InterceptedBy { role, name, bounds }) => occluded(role, name, bounds),};let report =- ActionabilityReport::from_checks(vec![check], None, None, PointerDelivery::Physical);+ ActionabilityReport::from_checks(vec![check], None, None, None, PointerDelivery::Physical);Err(AdapterError::new(ErrorCode::ActionFailed,format!("Target is not actionable: {}", report.failure_reasons()),diff --git a/crates/core/src/actionability/report.rs b/crates/core/src/actionability/report.rsindex 9a237775b..d82ce8124 100644--- a/crates/core/src/actionability/report.rs+++ b/crates/core/src/actionability/report.rs@@ -1,5 +1,5 @@use super::{PointerDelivery, check::ActionabilityCheck, status::ActionabilityStatus};-use crate::{ErrorCode, Point};+use crate::{ErrorCode, Point, Rect};use serde::Serialize;#[derive(Debug, Clone, Serialize, PartialEq)]@@ -11,6 +11,8 @@ pub(crate) struct ActionabilityReport {#[serde(skip)]pub(crate) presentation_point: Option<Point>,#[serde(skip)]+ pub(crate) presentation_bounds: Option<Rect>,+ #[serde(skip)]pub(crate) pointer_delivery: PointerDelivery,}@@ -19,6 +21,7 @@ impl ActionabilityReport {checks: Vec<ActionabilityCheck>,verified_point: Option<Point>,presentation_point: Option<Point>,+ presentation_bounds: Option<Rect>,pointer_delivery: PointerDelivery,) -> Self {let actionable = checks.iter().all(|check| !is_blocking(check));@@ -27,6 +30,7 @@ impl ActionabilityReport {checks,verified_point,presentation_point,+ presentation_bounds,pointer_delivery,}}@@ -86,6 +90,7 @@ mod tests {],None,None,+ None,PointerDelivery::NotApplicable,);diff --git a/crates/core/src/commands/cursor_overlay.rs b/crates/core/src/commands/cursor_overlay.rsindex d09b10fc4..0b6281f3d 100644--- a/crates/core/src/commands/cursor_overlay.rs+++ b/crates/core/src/commands/cursor_overlay.rs@@ -8,13 +8,24 @@ pub enum CursorOverlayAction {}pub fn execute(session_id: &str, action: CursorOverlayAction) -> Result<Value, AppError> {- let cursor_overlay = match action {- CursorOverlayAction::Enable(config) => config,- CursorOverlayAction::Disable => CursorOverlayConfig::default(),+ let (cursor_overlay, next) = match action {+ CursorOverlayAction::Enable(config) => {+ (config, Some(super::session::activation_export(session_id)))+ }+ CursorOverlayAction::Disable => (CursorOverlayConfig::default(), None),};let manifest = set_cursor_overlay(session_id, cursor_overlay)?;- Ok(json!({+ let mut response = json!({"session_id": manifest.id,"cursor_overlay": manifest.cursor_overlay,- }))+ });+ if let Some(next) = next {+ response["next"] = next.into();+ response["activation"] = super::session::activation(session_id);+ }+ Ok(response)}++#[cfg(test)]+#[path = "cursor_overlay_tests.rs"]+mod tests;diff --git a/crates/core/src/commands/cursor_overlay_tests.rs b/crates/core/src/commands/cursor_overlay_tests.rsnew file mode 100644index 000000000..2e89c289a--- /dev/null+++ b/crates/core/src/commands/cursor_overlay_tests.rs@@ -0,0 +1,32 @@+use super::*;+use crate::commands::session::{self, SessionAction};+use crate::refs_test_support::HomeGuard;++#[test]+fn session_and_overlay_responses_show_portable_activation_guidance() {+ let _guard = HomeGuard::new();+ let started = session::execute(SessionAction::Start {+ name: None,+ no_trace: false,+ screenshots: false,+ })+ .expect("session start");+ let id = started["session_id"].as_str().expect("session id");+ let expected = session::activation_export(id);++ assert_eq!(started["next"], expected);+ assert_eq!(+ started["activation"]["environment"],+ "AGENT_DESKTOP_SESSION"+ );+ assert_eq!(started["activation"]["value"], id);++ let enabled = execute(+ id,+ CursorOverlayAction::Enable(CursorOverlayConfig::enabled(None, 6).unwrap()),+ )+ .expect("cursor overlay enable");++ assert_eq!(enabled["next"], expected);+ assert_eq!(enabled["activation"], started["activation"]);+}diff --git a/crates/core/src/commands/session.rs b/crates/core/src/commands/session.rsindex a09b31953..4529157c2 100644--- a/crates/core/src/commands/session.rs+++ b/crates/core/src/commands/session.rs@@ -49,6 +49,8 @@ pub fn execute(action: SessionAction) -> Result<Value, AppError> {"trace": manifest.trace,"artifacts": manifest.artifacts,"created_at": manifest.created_at,+ "next": activation_export(&manifest.id),+ "activation": activation(&manifest.id),}))}SessionAction::End { id } => {@@ -86,3 +88,17 @@ pub fn execute(action: SessionAction) -> Result<Value, AppError> {}}}++pub(super) fn activation_export(session_id: &str) -> String {+ #[cfg(windows)]+ return format!("$env:AGENT_DESKTOP_SESSION = '{session_id}'");+ #[cfg(not(windows))]+ format!("export AGENT_DESKTOP_SESSION={session_id}")+}++pub(super) fn activation(session_id: &str) -> Value {+ json!({+ "environment": "AGENT_DESKTOP_SESSION",+ "value": session_id,+ })+}diff --git a/crates/core/src/cursor_overlay/config.rs b/crates/core/src/cursor_overlay/config.rsindex a212519bb..0866e249b 100644--- a/crates/core/src/cursor_overlay/config.rs+++ b/crates/core/src/cursor_overlay/config.rs@@ -1,3 +1,4 @@+use super::CursorOverlayStyle;use crate::{AdapterError, ErrorCode};use serde::{Deserialize, Serialize};@@ -5,7 +6,7 @@ pub const MAX_CURSOR_LABEL_WORDS: usize = 12;const MAX_CURSOR_LABEL_BYTES: usize = 512;const DEFAULT_CURSOR_LABEL_WORDS: usize = 6;-#[derive(Debug, Clone, Deserialize, Eq, PartialEq, Serialize)]+#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]#[serde(deny_unknown_fields)]pub struct CursorOverlayConfig {#[serde(default)]@@ -14,6 +15,8 @@ pub struct CursorOverlayConfig {label: Option<String>,#[serde(default = "default_word_limit")]max_words: usize,+ #[serde(default)]+ style: CursorOverlayStyle,}impl CursorOverlayConfig {@@ -22,10 +25,20 @@ impl CursorOverlayConfig {enabled: true,label,max_words,+ style: CursorOverlayStyle::default(),}.validated()}+ pub fn with_style(mut self, style: CursorOverlayStyle) -> Result<Self, AdapterError> {+ self.style = style.validated()?;+ Ok(self)+ }++ pub const fn style(&self) -> &CursorOverlayStyle {+ &self.style+ }+pub fn validated(mut self) -> Result<Self, AdapterError> {if !(1..=MAX_CURSOR_LABEL_WORDS).contains(&self.max_words) {return Err(AdapterError::new(@@ -55,6 +68,7 @@ impl CursorOverlayConfig {.label.take().and_then(|label| limit_words(label.trim(), self.max_words));+ self.style = std::mem::take(&mut self.style).validated()?;Ok(self)}@@ -81,6 +95,7 @@ impl Default for CursorOverlayConfig {enabled: false,label: None,max_words: DEFAULT_CURSOR_LABEL_WORDS,+ style: CursorOverlayStyle::default(),}}}diff --git a/crates/core/src/cursor_overlay/control.rs b/crates/core/src/cursor_overlay/control.rsindex 7bdc5c4bd..f0d7fffcb 100644--- a/crates/core/src/cursor_overlay/control.rs+++ b/crates/core/src/cursor_overlay/control.rs@@ -1,4 +1,4 @@-use super::CursorOverlayInstruction;+use super::{CursorOverlayInstruction, CursorOverlayStyle, CursorPhase};use crate::{AdapterError, ErrorCode, context::validate_session_id};use serde::{Deserialize, Serialize};@@ -10,10 +10,14 @@ pub enum CursorOverlayControl {Enable {session_id: String,label: String,+ #[serde(default)]+ style: CursorOverlayStyle,},Present {session_id: String,instruction: CursorOverlayInstruction,+ #[serde(default)]+ style: CursorOverlayStyle,},Hide {session_id: String,@@ -27,17 +31,34 @@ pub enum CursorOverlayControl {}impl CursorOverlayControl {- pub fn enable(session_id: String) -> Self {+ pub fn enable(session_id: String, style: CursorOverlayStyle) -> Self {Self::Enable {session_id,label: CURSOR_OVERLAY_GREETING.into(),+ style,+ }+ }++ pub fn style(&self) -> Option<&CursorOverlayStyle> {+ match self {+ Self::Enable { style, .. } | Self::Present { style, .. } => Some(style),+ _ => None,}}pub fn present(session_id: String, instruction: CursorOverlayInstruction) -> Self {+ Self::present_with_style(session_id, instruction, CursorOverlayStyle::default())+ }++ pub fn present_with_style(+ session_id: String,+ instruction: CursorOverlayInstruction,+ style: CursorOverlayStyle,+ ) -> Self {Self::Present {session_id,instruction,+ style,}}@@ -93,6 +114,14 @@ impl CursorOverlayControl {matches!(self, Self::Hide { .. } | Self::Show { .. })}+ /// A travel control moves the cursor and carries no click effect. Every+ /// platform renderer must acknowledge it once the cursor lands, because the+ /// action waits for that acknowledgement before it dispatches.+ pub fn is_travel(&self) -> bool {+ self.instruction()+ .is_some_and(|instruction| instruction.phase() == CursorPhase::Travel)+ }+pub const fn is_hide(&self) -> bool {matches!(self, Self::Hide { .. })}diff --git a/crates/core/src/cursor_overlay/hand_path.rs b/crates/core/src/cursor_overlay/hand_path.rsnew file mode 100644index 000000000..f5edb81da--- /dev/null+++ b/crates/core/src/cursor_overlay/hand_path.rs@@ -0,0 +1,94 @@+use crate::Point;++const OVERSHOOT: f64 = 1.035;+const PRIMARY_SPAN: f64 = 0.74;+const CORRECTION_START: f64 = 0.62;+const BOW_RATIO: f64 = 0.055;+const MAX_BOW: f64 = 38.0;+const TREMOR_PIXELS: f64 = 1.1;+const TREMOR_CYCLES: f64 = 7.0;++pub(super) struct HandPath {+ start: Point,+ destination: Point,+ bow: f64,+ seed: u64,+}++impl HandPath {+ pub(super) fn new(start: Point, destination: Point) -> Self {+ let distance = distance_between(&start, &destination);+ let seed =+ (start.x.to_bits() ^ destination.y.to_bits()).rotate_left(17) ^ destination.x.to_bits();+ Self {+ bow: (BOW_RATIO * distance).min(MAX_BOW),+ start,+ destination,+ seed,+ }+ }++ pub(super) fn destination(&self) -> Point {+ self.destination.clone()+ }++ pub(super) fn duration_ms(&self) -> u64 {+ let distance = distance_between(&self.start, &self.destination);+ if distance < 1.5 {+ return 0;+ }+ (40.0 + 70.0 * (distance / 40.0 + 1.0).log2()).clamp(90.0, 320.0) as u64+ }++ pub(super) fn at(&self, t: f64) -> Point {+ let dx = self.destination.x - self.start.x;+ let dy = self.destination.y - self.start.y;+ let distance = dx.hypot(dy);+ let travelled = self.submovements(t);+ let (normal_x, normal_y) = if distance > f64::EPSILON {+ (-dy / distance, dx / distance)+ } else {+ (0.0, 0.0)+ };+ let settle = (std::f64::consts::PI * t).sin();+ let sideways = self.bow * (std::f64::consts::PI * t.powf(0.8)).sin()+ + TREMOR_PIXELS * tremor(self.seed, t) * settle;+ Point {+ x: self.start.x + dx * travelled + normal_x * sideways,+ y: self.start.y + dy * travelled + normal_y * sideways,+ }+ }++ fn submovements(&self, t: f64) -> f64 {+ let primary = minimum_jerk((t / PRIMARY_SPAN).clamp(0.0, 1.0));+ let correction =+ minimum_jerk(((t - CORRECTION_START) / (1.0 - CORRECTION_START)).clamp(0.0, 1.0));+ OVERSHOOT * primary + (1.0 - OVERSHOOT) * correction+ }+}++fn distance_between(start: &Point, destination: &Point) -> f64 {+ (destination.x - start.x).hypot(destination.y - start.y)+}++pub(super) fn minimum_jerk(t: f64) -> f64 {+ t * t * t * (10.0 + t * (-15.0 + 6.0 * t))+}++fn tremor(seed: u64, t: f64) -> f64 {+ let x = t * TREMOR_CYCLES;+ let step = x.floor();+ let fraction = x - step;+ let low = unit_hash(seed, step as u64);+ let high = unit_hash(seed, step as u64 + 1);+ let blend = fraction * fraction * (3.0 - 2.0 * fraction);+ (low + (high - low) * blend) * 2.0 - 1.0+}++fn unit_hash(seed: u64, index: u64) -> f64 {+ let mut hash = seed ^ index.wrapping_mul(0x9E37_79B9_7F4A_7C15);+ hash ^= hash >> 33;+ hash = hash.wrapping_mul(0xFF51_AFD7_ED55_8CCD);+ hash ^= hash >> 33;+ (hash >> 11) as f64 / (1u64 << 53) as f64+}diff --git a/crates/core/src/cursor_overlay/instruction.rs b/crates/core/src/cursor_overlay/instruction.rsindex a718803cd..3a0477434 100644--- a/crates/core/src/cursor_overlay/instruction.rs+++ b/crates/core/src/cursor_overlay/instruction.rs@@ -1,5 +1,5 @@-use super::CursorOverlayConfig;-use crate::{AdapterError, ErrorCode, Point};+use super::{CursorOverlayConfig, CursorPhase};+use crate::{AdapterError, ErrorCode, Point, Rect};use serde::{Deserialize, Serialize};#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]@@ -9,6 +9,10 @@ pub struct CursorOverlayInstruction {#[serde(skip_serializing_if = "Option::is_none")]label: Option<String>,click: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ target: Option<Rect>,+ #[serde(default)]+ phase: CursorPhase,}impl CursorOverlayInstruction {@@ -28,9 +32,30 @@ impl CursorOverlayInstruction {destination,label: config.label().map(str::to_owned),click,+ target: None,+ phase: CursorPhase::Travel,})}+ pub const fn with_phase(mut self, phase: CursorPhase) -> Self {+ self.phase = phase;+ self+ }++ pub const fn phase(&self) -> CursorPhase {+ self.phase+ }++ pub fn with_target(mut self, target: Option<Rect>) -> Self {+ self.target =+ target.filter(|rect| rect.validate().is_ok() && rect.width > 0.0 && rect.height > 0.0);+ self+ }++ pub const fn target(&self) -> Option<&Rect> {+ self.target.as_ref()+ }+pub fn validate(&self) -> Result<(), AdapterError> {self.destination.validate()}diff --git a/crates/core/src/cursor_overlay/mod.rs b/crates/core/src/cursor_overlay/mod.rsindex c3db94ad5..9bc33bec7 100644--- a/crates/core/src/cursor_overlay/mod.rs+++ b/crates/core/src/cursor_overlay/mod.rs@@ -1,16 +1,25 @@mod config;mod control;+mod hand_path;mod instruction;mod layout;mod motion;+mod phase;+mod pose;+mod style;mod submit;+mod timing;pub use config::{CursorOverlayConfig, MAX_CURSOR_LABEL_WORDS};pub use control::{CURSOR_OVERLAY_GREETING, CursorOverlayControl};pub use instruction::CursorOverlayInstruction;pub use layout::place_label;pub use motion::CursorMotion;+pub use phase::CursorPhase;+pub use pose::CursorPose;+pub use style::CursorOverlayStyle;pub(crate) use submit::submit;+pub use timing::{CURSOR_ARRIVAL_TIMEOUT_MS, CURSOR_HIGHLIGHT_HOLD_MS, CURSOR_IDLE_REST_MS};#[cfg(test)]mod tests;diff --git a/crates/core/src/cursor_overlay/motion.rs b/crates/core/src/cursor_overlay/motion.rsindex 094706f96..bf9928dc4 100644--- a/crates/core/src/cursor_overlay/motion.rs+++ b/crates/core/src/cursor_overlay/motion.rs@@ -1,56 +1,69 @@+use super::CursorPose;+use super::hand_path::HandPath;use crate::Point;-#[derive(Debug, Clone, PartialEq)]+const RIPPLE_MS: u64 = 300;+pub struct CursorMotion {- start: Point,- destination: Point,+ path: HandPath,duration_ms: u64,- bend: f64,+ click: bool,+ ripple: bool,}impl CursorMotion {pub fn new(start: Point, destination: Point) -> Self {- let dx = destination.x - start.x;- let dy = destination.y - start.y;- let distance = dx.hypot(dy);- let duration_ms = ((0.32 + distance / 2_600.0).clamp(0.42, 0.72) * 1_000.0).round();+ let path = HandPath::new(start, destination);+ let duration_ms = path.duration_ms();Self {- start,- destination,- duration_ms: duration_ms as u64,- bend: (distance * 0.09).min(54.0),+ path,+ duration_ms,+ click: false,+ ripple: true,}}+ pub const fn with_impact(mut self, click: bool) -> Self {+ self.click = click;+ self+ }++ pub const fn with_ripple(mut self, ripple: bool) -> Self {+ self.ripple = ripple;+ self+ }+pub const fn duration_ms(&self) -> u64 {self.duration_ms}- pub fn sample(&self, elapsed_ms: u64) -> Point {- if elapsed_ms == 0 {- return self.start.clone();+ pub const fn total_ms(&self) -> u64 {+ if self.plays_ripple() {+ self.duration_ms + RIPPLE_MS+ } else {+ self.duration_ms}+ }++ pub fn sample(&self, elapsed_ms: u64) -> Point {if elapsed_ms >= self.duration_ms {- return self.destination.clone();+ return self.path.destination();}- let t = elapsed_ms as f64 / self.duration_ms as f64;- let progress = minimum_jerk(t);- let dx = self.destination.x - self.start.x;- let dy = self.destination.y - self.start.y;- let distance = dx.hypot(dy);- let arc = 4.0 * t * (1.0 - t) * self.bend;- let (normal_x, normal_y) = if distance > f64::EPSILON {- (-dy / distance, dx / distance)- } else {- (0.0, 0.0)- };- Point {- x: self.start.x + dx * progress + normal_x * arc,- y: self.start.y + dy * progress + normal_y * arc,+ self.path.at(elapsed_ms as f64 / self.duration_ms as f64)+ }++ pub fn pose(&self, elapsed_ms: u64) -> CursorPose {+ let point = self.sample(elapsed_ms.min(self.duration_ms));+ if !self.plays_ripple() || elapsed_ms <= self.duration_ms {+ return CursorPose::still(point);+ }+ CursorPose {+ point,+ ripple: ((elapsed_ms - self.duration_ms) as f64 / RIPPLE_MS as f64).clamp(0.0, 1.0),}}-}-fn minimum_jerk(t: f64) -> f64 {- t * t * t * (10.0 + t * (-15.0 + 6.0 * t))+ const fn plays_ripple(&self) -> bool {+ self.click && self.ripple+ }}diff --git a/crates/core/src/cursor_overlay/phase.rs b/crates/core/src/cursor_overlay/phase.rsnew file mode 100644index 000000000..1fff06c88--- /dev/null+++ b/crates/core/src/cursor_overlay/phase.rs@@ -0,0 +1,14 @@+use serde::{Deserialize, Serialize};++/// Which half of an action a cursor instruction represents.+///+/// `Travel` is sent before the action dispatches and every platform renderer+/// must acknowledge it once the cursor lands. `Effect` is sent after dispatch+/// confirms and is fire-and-forget.+#[derive(Debug, Clone, Copy, Default, Deserialize, Eq, PartialEq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum CursorPhase {+ #[default]+ Travel,+ Effect,+}diff --git a/crates/core/src/cursor_overlay/pose.rs b/crates/core/src/cursor_overlay/pose.rsnew file mode 100644index 000000000..e755ca1aa--- /dev/null+++ b/crates/core/src/cursor_overlay/pose.rs@@ -0,0 +1,13 @@+use crate::Point;++#[derive(Debug, Clone, PartialEq)]+pub struct CursorPose {+ pub point: Point,+ pub ripple: f64,+}++impl CursorPose {+ pub const fn still(point: Point) -> Self {+ Self { point, ripple: 0.0 }+ }+}diff --git a/crates/core/src/cursor_overlay/style.rs b/crates/core/src/cursor_overlay/style.rsnew file mode 100644index 000000000..429d27b6c--- /dev/null+++ b/crates/core/src/cursor_overlay/style.rs@@ -0,0 +1,142 @@+use crate::{AdapterError, ErrorCode};+use serde::{Deserialize, Serialize};++const DEFAULT_FILL: &str = "#FFFFFF";+const DEFAULT_RIM: &str = "#111318";+const DEFAULT_ACCENT: &str = "#4299FF";+const MIN_SIZE: f64 = 0.5;+const MAX_SIZE: f64 = 4.0;++#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]+#[serde(deny_unknown_fields)]+pub struct CursorOverlayStyle {+ #[serde(default = "default_fill")]+ fill: String,+ #[serde(default = "default_rim")]+ rim: String,+ #[serde(default = "default_accent")]+ accent: String,+ #[serde(default = "default_size")]+ size: f64,+ #[serde(default = "enabled_effect")]+ ripple: bool,+ #[serde(default = "enabled_effect")]+ highlight: bool,+}++impl CursorOverlayStyle {+ pub fn take(&mut self) -> Self {+ std::mem::take(self)+ }++ pub fn validated(self) -> Result<Self, AdapterError> {+ for color in [&self.fill, &self.rim, &self.accent] {+ rgb(color).ok_or_else(|| {+ AdapterError::new(+ ErrorCode::InvalidArgs,+ format!("Cursor overlay color '{color}' must be a hex value like #FFFFFF"),+ )+ })?;+ }+ if !(MIN_SIZE..=MAX_SIZE).contains(&self.size) {+ return Err(AdapterError::new(+ ErrorCode::InvalidArgs,+ format!("Cursor overlay size must be between {MIN_SIZE} and {MAX_SIZE}"),+ ));+ }+ Ok(self)+ }++ pub fn set_fill(&mut self, fill: String) {+ self.fill = fill;+ }++ pub fn set_rim(&mut self, rim: String) {+ self.rim = rim;+ }++ pub fn set_accent(&mut self, accent: String) {+ self.accent = accent;+ }++ pub fn set_size(&mut self, size: f64) {+ self.size = size;+ }++ pub fn set_effects(&mut self, ripple: bool, highlight: bool) {+ self.ripple = ripple;+ self.highlight = highlight;+ }++ pub fn fill_rgb(&self) -> [f64; 3] {+ rgb(&self.fill).unwrap_or([1.0, 1.0, 1.0])+ }++ pub fn rim_rgb(&self) -> [f64; 3] {+ rgb(&self.rim).unwrap_or([0.07, 0.07, 0.09])+ }++ pub fn accent_rgb(&self) -> [f64; 3] {+ rgb(&self.accent).unwrap_or([0.26, 0.60, 1.0])+ }++ pub const fn size(&self) -> f64 {+ self.size+ }++ pub const fn ripple(&self) -> bool {+ self.ripple+ }++ pub const fn highlight(&self) -> bool {+ self.highlight+ }+}++impl Default for CursorOverlayStyle {+ fn default() -> Self {+ Self {+ fill: default_fill(),+ rim: default_rim(),+ accent: default_accent(),+ size: default_size(),+ ripple: true,+ highlight: true,+ }+ }+}++fn default_fill() -> String {+ DEFAULT_FILL.into()+}++fn default_rim() -> String {+ DEFAULT_RIM.into()+}++fn default_accent() -> String {+ DEFAULT_ACCENT.into()+}++const fn default_size() -> f64 {+ 1.0+}++const fn enabled_effect() -> bool {+ true+}++fn rgb(value: &str) -> Option<[f64; 3]> {+ let digits = value.strip_prefix('#').unwrap_or(value);+ let expanded = match digits.len() {+ 3 => digits.chars().flat_map(|c| [c, c]).collect::<String>(),+ 6 => digits.to_owned(),+ _ => return None,+ };+ let channel = |index: usize| {+ u8::from_str_radix(expanded.get(index..index + 2)?, 16)+ .ok()+ .map(|byte| f64::from(byte) / 255.0)+ };+ Some([channel(0)?, channel(2)?, channel(4)?])+}diff --git a/crates/core/src/cursor_overlay/submit.rs b/crates/core/src/cursor_overlay/submit.rsindex 8e8c63005..2a7acf8da 100644--- a/crates/core/src/cursor_overlay/submit.rs+++ b/crates/core/src/cursor_overlay/submit.rs@@ -1,10 +1,13 @@-use crate::{CommandContext, PlatformAdapter, Point};+use super::CursorPhase;+use crate::{CommandContext, PlatformAdapter, Point, Rect};pub(crate) fn submit(adapter: &dyn PlatformAdapter,context: &CommandContext,destination: Point,+ target: Option<Rect>,click: bool,+ phase: CursorPhase,) {if context.is_headed() || !context.cursor_overlay().is_enabled() {return;@@ -14,13 +17,17 @@ pub(crate) fn submit(};let instruction =match super::CursorOverlayInstruction::new(destination, context.cursor_overlay(), click) {- Ok(instruction) => instruction,+ Ok(instruction) => instruction.with_target(target).with_phase(phase),Err(error) => {tracing::warn!(code = %error.code.as_str(), "agent cursor instruction was skipped");return;}};- let control = super::CursorOverlayControl::present(session_id.to_owned(), instruction);+ let control = super::CursorOverlayControl::present_with_style(+ session_id.to_owned(),+ instruction,+ context.cursor_overlay().style().clone(),+ );if let Err(error) = adapter.update_cursor_overlay(&control) {tracing::warn!(code = %error.code.as_str(), "agent cursor presentation was skipped");}diff --git a/crates/core/src/cursor_overlay/tests.rs b/crates/core/src/cursor_overlay/tests.rsindex 0a1902c63..34b413675 100644--- a/crates/core/src/cursor_overlay/tests.rs+++ b/crates/core/src/cursor_overlay/tests.rs@@ -15,20 +15,38 @@ fn motion_reaches_both_endpoints_and_curves_between_them() {}#[test]-fn motion_eases_in_and_out() {+fn motion_is_ballistic_then_corrective_like_a_hand() {let motion = CursorMotion::new(Point { x: 0.0, y: 0.0 }, Point { x: 1_000.0, y: 0.0 });- assert!(motion.sample(motion.duration_ms() / 4).x < 150.0);- assert!(motion.sample(motion.duration_ms() * 3 / 4).x > 850.0);+ let early = motion.sample(motion.duration_ms() / 2).x;+ let overshoot = motion.sample(motion.duration_ms() * 3 / 4).x;++ assert!(+ early > 700.0,+ "the hand covers most of the gap early: {early}"+ );+ assert!(+ overshoot > 1_000.0,+ "the hand overshoots before it corrects: {overshoot}"+ );+ assert_eq!(+ motion.sample(motion.duration_ms()),+ Point { x: 1_000.0, y: 0.0 }+ );}#[test]-fn motion_duration_is_distance_aware_and_bounded() {+fn motion_duration_follows_fitts_law_and_stays_bounded() {let short = CursorMotion::new(Point { x: 0.0, y: 0.0 }, Point { x: 10.0, y: 0.0 });+ let medium = CursorMotion::new(Point { x: 0.0, y: 0.0 }, Point { x: 600.0, y: 0.0 });let long = CursorMotion::new(Point { x: 0.0, y: 0.0 }, Point { x: 4_000.0, y: 0.0 });- assert_eq!(short.duration_ms(), 420);- assert_eq!(long.duration_ms(), 720);+ let still = CursorMotion::new(Point { x: 0.0, y: 0.0 }, Point { x: 0.0, y: 0.0 });++ assert_eq!(still.duration_ms(), 0);+ assert_eq!(short.duration_ms(), 90);+ assert!((200..321).contains(&medium.duration_ms()));+ assert_eq!(long.duration_ms(), 320);}#[test]@@ -85,7 +103,7 @@ fn instruction_rejects_invalid_destination() {#[test]fn control_protocol_carries_the_session_lifecycle() {- let enable = CursorOverlayControl::enable("run-1".into());+ let enable = CursorOverlayControl::enable("run-1".into(), CursorOverlayStyle::default());let disable = CursorOverlayControl::disable("run-1".into());assert_eq!(enable.session_id(), "run-1");@@ -94,3 +112,95 @@ fn control_protocol_carries_the_session_lifecycle() {assert_eq!(disable.session_id(), "run-1");assert!(disable.is_disable());}++#[test]+fn present_control_carries_the_session_style() {+ let mut style = CursorOverlayStyle::default();+ style.set_size(2.0);+ style.set_effects(false, true);+ let config = CursorOverlayConfig::enabled(None, 6)+ .expect("valid config")+ .with_style(style.clone())+ .expect("valid style");+ let instruction = CursorOverlayInstruction::new(Point { x: 20.0, y: 40.0 }, &config, true)+ .expect("valid instruction");++ let control = CursorOverlayControl::present_with_style("run-1".into(), instruction, style);++ assert_eq!(control.style().map(CursorOverlayStyle::size), Some(2.0));+ assert_eq!(control.style().map(CursorOverlayStyle::ripple), Some(false));+}++#[test]+fn travel_never_ripples_before_the_cursor_lands() {+ let motion =+ CursorMotion::new(Point { x: 0.0, y: 0.0 }, Point { x: 600.0, y: 0.0 }).with_impact(true);++ let cruise = motion.pose(motion.duration_ms() / 2);+ let landed = motion.pose(motion.duration_ms());++ assert_eq!(cruise.ripple, 0.0);+ assert_eq!(landed, CursorPose::still(Point { x: 600.0, y: 0.0 }));+}++#[test]+fn the_click_ripples_at_the_destination_without_moving_the_cursor() {+ let motion =+ CursorMotion::new(Point { x: 0.0, y: 0.0 }, Point { x: 600.0, y: 0.0 }).with_impact(true);+ let ripple_ms = motion.total_ms() - motion.duration_ms();++ let early = motion.pose(motion.duration_ms() + ripple_ms / 4);+ let late = motion.pose(motion.total_ms());++ assert!(early.ripple > 0.0 && early.ripple < 1.0);+ assert_eq!(late.ripple, 1.0);+ assert_eq!(early.point, Point { x: 600.0, y: 0.0 });+ assert_eq!(late.point, Point { x: 600.0, y: 0.0 });+}++#[test]+fn a_move_without_a_click_never_ripples() {+ let motion = CursorMotion::new(Point { x: 0.0, y: 0.0 }, Point { x: 600.0, y: 0.0 });++ assert_eq!(motion.total_ms(), motion.duration_ms());+ assert_eq!(+ motion.pose(motion.total_ms()),+ CursorPose::still(Point { x: 600.0, y: 0.0 })+ );+}++#[test]+fn a_disabled_ripple_keeps_the_click_silent() {+ let motion = CursorMotion::new(Point { x: 0.0, y: 0.0 }, Point { x: 600.0, y: 0.0 })+ .with_impact(true)+ .with_ripple(false);++ assert_eq!(motion.total_ms(), motion.duration_ms());+ assert_eq!(motion.pose(motion.total_ms()).ripple, 0.0);+}++#[test]+fn a_clicked_target_rect_reaches_the_renderer() {+ let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");+ let bounds = Rect {+ x: 10.0,+ y: 20.0,+ width: 80.0,+ height: 24.0,+ };+ let point = Point { x: 50.0, y: 32.0 };+ let instruction = CursorOverlayInstruction::new(point.clone(), &config, true)+ .expect("valid instruction")+ .with_target(Some(bounds));+ let degenerate = CursorOverlayInstruction::new(point, &config, true)+ .expect("valid instruction")+ .with_target(Some(Rect {+ x: 0.0,+ y: 0.0,+ width: 0.0,+ height: 5.0,+ }));++ assert_eq!(instruction.target(), Some(&bounds));+ assert_eq!(degenerate.target(), None);+}diff --git a/crates/core/src/cursor_overlay/timing.rs b/crates/core/src/cursor_overlay/timing.rsnew file mode 100644index 000000000..92637f09c--- /dev/null+++ b/crates/core/src/cursor_overlay/timing.rs@@ -0,0 +1,9 @@+/// How long a platform renderer may take to report that the cursor reached its+/// destination before the action dispatches anyway.+pub const CURSOR_ARRIVAL_TIMEOUT_MS: u64 = 900;++/// How long the overlay stays visible with no instruction before it rests.+pub const CURSOR_IDLE_REST_MS: u64 = 6_000;++/// How long the outline around a clicked element stays on screen.+pub const CURSOR_HIGHLIGHT_HOLD_MS: u64 = 900;diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rsindex 67c8b0a73..32b4063e5 100644--- a/crates/core/src/lib.rs+++ b/crates/core/src/lib.rs@@ -171,8 +171,10 @@ pub use clipboard_format::ClipboardFormat;pub use containment_predicate::ContainmentPredicate;pub use context::{CommandContext, WaitSelector};pub use cursor_overlay::{+ CURSOR_ARRIVAL_TIMEOUT_MS, CURSOR_HIGHLIGHT_HOLD_MS, CURSOR_IDLE_REST_MS,CURSOR_OVERLAY_GREETING, CursorMotion, CursorOverlayConfig, CursorOverlayControl,- CursorOverlayInstruction, MAX_CURSOR_LABEL_WORDS, place_label,+ CursorOverlayInstruction, CursorOverlayStyle, CursorPhase, CursorPose, MAX_CURSOR_LABEL_WORDS,+ place_label,};pub use deadline::{DEFAULT_OPERATION_TIMEOUT_MS, Deadline};pub use delivery_disposition::DeliveryDisposition;diff --git a/crates/core/src/ref_action.rs b/crates/core/src/ref_action.rsindex 7e02a2b50..cd855e992 100644--- a/crates/core/src/ref_action.rs+++ b/crates/core/src/ref_action.rs@@ -24,6 +24,7 @@ pub(crate) struct ResolvedRefAction<'a> {pub(crate) struct ActionabilityPreflight {verified_point: Option<crate::Point>,presentation_point: Option<crate::Point>,+ presentation_bounds: Option<crate::Rect>,pointer_delivery: actionability::PointerDelivery,}@@ -101,7 +102,7 @@ pub(crate) fn dispatch_resolved(request.policy = crate::InteractionPolicy::headless();}request = request- .with_verified_point(preflight.verified_point)+ .with_verified_point(preflight.verified_point.clone()).with_expected_process(expected_process.clone());let final_target = ResolvedRefAction::new(target, &handle);final_target.context.trace_lazy(@@ -111,13 +112,14 @@ pub(crate) fn dispatch_resolved(let action_name = request.action.name();let raises_surface = request.action.may_raise_surface();let presentation_action = request.action.clone();+ presentation::before_dispatch(&final_target, &preflight, lease);let dispatch_result = final_target.adapter.execute_action(final_target.handle, request, lease);presentation::after_dispatch(final_target.adapter,final_target.context,- preflight.presentation_point,+ &preflight,&presentation_action,&dispatch_result,);@@ -325,6 +327,7 @@ fn check_actionability_with_trace(Ok(ActionabilityPreflight {verified_point: report.verified_point,presentation_point: report.presentation_point,+ presentation_bounds: report.presentation_bounds,pointer_delivery: report.pointer_delivery,})}diff --git a/crates/core/src/ref_action/presentation.rs b/crates/core/src/ref_action/presentation.rsindex 5b3e8baa8..ce3ab7acf 100644--- a/crates/core/src/ref_action/presentation.rs+++ b/crates/core/src/ref_action/presentation.rs@@ -1,11 +1,36 @@-use crate::{- Action, CommandContext, DeliveryDisposition, DeliverySemantics, PlatformAdapter, Point,-};+use super::{ActionabilityPreflight, ResolvedRefAction};+use crate::cursor_overlay::CursorPhase;+use crate::{Action, CommandContext, DeliveryDisposition, DeliverySemantics, PlatformAdapter};++const DISPATCH_RESERVE_MS: u64 = 100;++pub(super) fn before_dispatch(+ target: &ResolvedRefAction<'_>,+ preflight: &ActionabilityPreflight,+ lease: &crate::InteractionLease,+) {+ if lease.deadline().remaining_ms()+ <= crate::CURSOR_ARRIVAL_TIMEOUT_MS.saturating_add(DISPATCH_RESERVE_MS)+ {+ return;+ }+ let Some(destination) = preflight.presentation_point.clone() else {+ return;+ };+ crate::cursor_overlay::submit(+ target.adapter,+ target.context,+ destination,+ None,+ false,+ CursorPhase::Travel,+ );+}pub(super) fn after_dispatch(adapter: &dyn PlatformAdapter,context: &CommandContext,- destination: Option<Point>,+ preflight: &ActionabilityPreflight,action: &Action,result: &Result<crate::ActionResult, crate::AdapterError>,) {@@ -13,14 +38,20 @@ pub(super) fn after_dispatch(Ok(result) => result.disposition(),Err(error) => error.disposition,};- if result.is_err() && !confirms_dispatch(disposition) {+ if !confirms_dispatch(disposition) {return;}- let Some(destination) = destination else {+ let Some(destination) = preflight.presentation_point.clone() else {return;};- let click = is_click(action) && confirms_dispatch(disposition);- crate::cursor_overlay::submit(adapter, context, destination, click);+ crate::cursor_overlay::submit(+ adapter,+ context,+ destination,+ preflight.presentation_bounds,+ is_click(action),+ CursorPhase::Effect,+ );}fn confirms_dispatch(disposition: DeliverySemantics) -> bool {diff --git a/crates/core/src/ref_action_cursor_overlay_tests.rs b/crates/core/src/ref_action_cursor_overlay_tests.rsindex 8a805a0bf..3a10ba069 100644--- a/crates/core/src/ref_action_cursor_overlay_tests.rs+++ b/crates/core/src/ref_action_cursor_overlay_tests.rs@@ -7,13 +7,22 @@ use std::sync::Mutex;struct CursorAdapter {presented: Mutex<Vec<CursorOverlayControl>>,+ events: Mutex<Vec<CursorEvent>>,fail_presentation: bool,}+#[derive(Debug, PartialEq)]+enum CursorEvent {+ Travel,+ Dispatch,+ Effect,+}+impl CursorAdapter {fn new(fail_presentation: bool) -> Self {Self {presented: Mutex::new(Vec::new()),+ events: Mutex::new(Vec::new()),fail_presentation,}}@@ -28,7 +37,11 @@ impl ObservationOps for CursorAdapter {Ok(NativeHandle::null())}- crate::adapter::complete_live_observation!("button", "Run", [capability::CLICK]);+ crate::adapter::complete_live_observation!(+ "textfield",+ "Run",+ [capability::CLICK, capability::SET_VALUE]+ );}impl ActionOps for CursorAdapter {@@ -38,6 +51,7 @@ impl ActionOps for CursorAdapter {_request: ActionRequest,_lease: &crate::InteractionLease,) -> Result<ActionResult, AdapterError> {+ self.events.lock().unwrap().push(CursorEvent::Dispatch);Ok(ActionResult::delivered_unverified("click"))}}@@ -52,6 +66,11 @@ impl SystemOps for CursorAdapter {if self.fail_presentation {return Err(AdapterError::internal("renderer unavailable"));}+ self.events.lock().unwrap().push(if control.is_travel() {+ CursorEvent::Travel+ } else {+ CursorEvent::Effect+ });self.presented.lock().unwrap().push(control.clone());Ok(())}@@ -70,7 +89,7 @@ fn entry() -> RefEntry {process_instance: Some("test-instance".into()),},identity: crate::RefEntryIdentity {- role: "button".into(),+ role: "textfield".into(),name: Some("Run".into()),value: None,description: None,@@ -82,7 +101,7 @@ fn entry() -> RefEntry {},capabilities: crate::RefCapabilities {states: vec![],- available_actions: vec![capability::CLICK.into()],+ available_actions: vec![capability::CLICK.into(), capability::SET_VALUE.into()],},source: crate::RefSource {source_app: Some("Fixture".into()),@@ -106,7 +125,7 @@ fn enabled_context() -> CommandContext {}#[test]-fn enabled_cursor_presents_verified_center_after_dispatch() {+fn enabled_cursor_moves_before_dispatch_then_clicks_after_it() {let adapter = CursorAdapter::new(false);execute_entry_with_context(@@ -118,13 +137,46 @@ fn enabled_cursor_presents_verified_center_after_dispatch() {.expect("click succeeds");let presented = adapter.presented.lock().unwrap();- assert_eq!(presented.len(), 1);- assert_eq!(- presented[0].instruction().unwrap().destination(),- &crate::Point { x: 11.0, y: 11.0 }+ let center = crate::Point { x: 11.0, y: 11.0 };+ assert_eq!(presented.len(), 2);+ let travel = presented[0].instruction().expect("travel instruction");+ let click = presented[1].instruction().expect("click instruction");++ assert_eq!(travel.destination(), ¢er);+ assert!(+ !travel.is_click(),+ "the cursor sets off before the action runs");- assert!(presented[0].instruction().unwrap().is_click());+ assert!(travel.target().is_none());+ assert_eq!(click.destination(), ¢er);+ assert!(+ click.is_click(),+ "the click effect lands after dispatch confirms"+ );+ assert_eq!(click.target().map(|rect| rect.width), Some(20.0));assert_eq!(presented[0].label(), Some("Opening menu"));+ assert_eq!(+ *adapter.events.lock().unwrap(),+ [+ CursorEvent::Travel,+ CursorEvent::Dispatch,+ CursorEvent::Effect+ ]+ );+}++#[test]+fn short_action_budget_skips_optional_travel_before_dispatch() {+ let adapter = CursorAdapter::new(false);+ let request = ActionRequest::headless(Action::Click).with_timeout_ms(Some(1_000));++ execute_entry_with_context(&adapter, &entry(), request, &enabled_context())+ .expect("click succeeds without optional travel");++ assert_eq!(+ *adapter.events.lock().unwrap(),+ [CursorEvent::Dispatch, CursorEvent::Effect]+ );}#[test]@@ -159,3 +211,24 @@ fn renderer_failure_does_not_change_successful_action() {assert_eq!(result.action, "click");}++#[test]+fn a_value_write_outlines_the_element_without_a_click_ripple() {+ let adapter = CursorAdapter::new(false);++ execute_entry_with_context(+ &adapter,+ &entry(),+ ActionRequest::headless(Action::SetValue("Paris".into())),+ &enabled_context(),+ )+ .expect("set-value succeeds");++ let presented = adapter.presented.lock().unwrap();+ assert_eq!(presented.len(), 2, "travel then effect, same as a click");+ let effect = presented[1].instruction().expect("effect instruction");++ assert!(!effect.is_click(), "a value write must not ripple");+ assert!(effect.target().is_some(), "but it must outline the element");+ assert_eq!(effect.phase(), crate::CursorPhase::Effect);+}diff --git a/crates/core/src/ref_action_poll.rs b/crates/core/src/ref_action_poll.rsindex 00857f336..ce5aca265 100644--- a/crates/core/src/ref_action_poll.rs+++ b/crates/core/src/ref_action_poll.rs@@ -133,6 +133,9 @@ fn is_permanent_actionability_error(code: &ErrorCode) -> bool {}fn timeout(state: &RefActionPollState, deadline: Deadline) -> AdapterError {+ if state.only_live_read_incomplete() {+ return live_read_incomplete(state, deadline);+ }let mut details = json!({"kind": "actionability_timeout","timeout_ms": deadline.timeout_ms(),@@ -153,6 +156,37 @@ fn timeout(state: &RefActionPollState, deadline: Deadline) -> AdapterError {.with_disposition(crate::DeliverySemantics::not_delivered())}+fn live_read_incomplete(state: &RefActionPollState, deadline: Deadline) -> AdapterError {+ let report = state+ .last_report+ .as_ref()+ .and_then(|last| last.get("report"));+ let stats = report.and_then(|report| report.get("query_stats"));+ AdapterError::new(+ ErrorCode::ActionFailed,+ "Live reads were incomplete before actionability could be determined",+ )+ .with_suggestion(+ "Re-snapshot the window and act on a fresh ref, or fall back to --headed coordinate input from the ref bounds.",+ )+ .with_details(json!({+ "kind": "live_read_incomplete",+ "retryable": false,+ "timeout_ms": deadline.timeout_ms(),+ "elapsed_ms": deadline.elapsed().as_millis(),+ "native_read_failures": stats+ .and_then(|stats| stats.pointer("/reads/native_read_failures"))+ .and_then(serde_json::Value::as_u64)+ .unwrap_or(0),+ "nodes_visited": stats+ .and_then(|stats| stats.pointer("/traversal/nodes_visited"))+ .and_then(serde_json::Value::as_u64)+ .unwrap_or(0),+ "last_report": state.last_report,+ }))+ .with_disposition(crate::DeliverySemantics::not_delivered())+}+#[cfg(test)]pub(crate) fn timeout_with_last_report(last_report: serde_json::Value) -> AdapterError {let deadline = Deadline::after(1).expect("test deadline");@@ -191,4 +225,32 @@ mod tests {true);}++ #[test]+ fn incomplete_live_reads_report_the_tool_limitation() {+ let mut state = RefActionPollState::default();+ state.record_preflight_error(+ &AdapterError::new(ErrorCode::AppUnresponsive, "incomplete").with_details(json!({+ "kind": "live_element_evidence",+ "complete": false,+ "query_stats": {+ "reads": { "native_read_failures": 2 },+ "traversal": { "nodes_visited": 1 },+ },+ })),+ );++ let error = timeout(&state, Deadline::after(1).expect("deadline"));+ assert_eq!(error.code, ErrorCode::ActionFailed);+ let details = error.details.expect("structured details");+ assert_eq!(details["kind"], "live_read_incomplete");+ assert_eq!(details["native_read_failures"], 2);+ assert_eq!(details["nodes_visited"], 1);+ assert!(+ !error+ .suggestion+ .expect("recovery suggestion")+ .contains("busy or unresponsive")+ );+ }}diff --git a/crates/core/src/ref_action_poll_state.rs b/crates/core/src/ref_action_poll_state.rsindex cdc8365be..485e96619 100644--- a/crates/core/src/ref_action_poll_state.rs+++ b/crates/core/src/ref_action_poll_state.rs@@ -9,6 +9,7 @@ pub(crate) struct RefActionPollState {pub(crate) expected_bounds_hash: Option<u64>,pub(crate) resolve_attempts: u64,pub(crate) preflight_attempts: u64,+ pub(crate) live_read_incomplete_only: Option<bool>,}impl RefActionPollState {@@ -17,6 +18,8 @@ impl RefActionPollState {}pub(crate) fn record_preflight_error(&mut self, error: &AdapterError) {+ self.live_read_incomplete_only =+ Some(self.live_read_incomplete_only.unwrap_or(true) && is_live_read_incomplete(error));if let Some(observed) = crate::ref_action_wait_evidence::observed_bounds_hash(error) {self.expected_bounds_hash = Some(observed);}@@ -26,6 +29,7 @@ impl RefActionPollState {}pub(crate) fn record_resolve_error(&mut self, error: &AdapterError) {+ self.live_read_incomplete_only = Some(false);self.last_report = Some(json!({"phase": "resolve","code": error.code.as_str(),@@ -34,6 +38,10 @@ impl RefActionPollState {}));}+ pub(crate) fn only_live_read_incomplete(&self) -> bool {+ self.live_read_incomplete_only == Some(true)+ }+pub(crate) fn attach_transient_ambiguity(&self, result: &mut ActionResult) {if !self.saw_ambiguity {return;@@ -92,3 +100,10 @@ impl RefActionPollState {error}}++fn is_live_read_incomplete(error: &AdapterError) -> bool {+ error.details.as_ref().is_some_and(|details| {+ details.get("kind").and_then(Value::as_str) == Some("live_element_evidence")+ && details.get("complete").and_then(Value::as_bool) == Some(false)+ })+}diff --git a/crates/core/src/session/manifest.rs b/crates/core/src/session/manifest.rsindex 4cf26ed1c..eadc7e791 100644--- a/crates/core/src/session/manifest.rs+++ b/crates/core/src/session/manifest.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use crate::CursorOverlayConfig;-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct SessionManifest {pub id: String,#[serde(default, skip_serializing_if = "Option::is_none")]diff --git a/crates/core/src/window_info_tests.rs b/crates/core/src/window_info_tests.rsindex ab10e0089..e87f55c91 100644--- a/crates/core/src/window_info_tests.rs+++ b/crates/core/src/window_info_tests.rs@@ -12,6 +12,7 @@ fn legacy_window_json_defaults_optional_state() {.expect("legacy window");assert!(window.state.is_focused);+ assert!(window.state.accessible);assert_eq!(window.state.minimized, None);assert_eq!(window.state.visible, None);}@@ -27,6 +28,7 @@ fn optional_window_state_serializes_flat() {bounds: None,state: WindowState {is_focused: false,+ accessible: true,minimized: Some(true),visible: Some(false),},@@ -34,6 +36,7 @@ fn optional_window_state_serializes_flat() {let value = serde_json::to_value(window).expect("window json");assert_eq!(value["is_focused"], false);+ assert_eq!(value["accessible"], true);assert_eq!(value["minimized"], true);assert_eq!(value["visible"], false);assert!(value.get("state").is_none());diff --git a/crates/core/src/window_lookup.rs b/crates/core/src/window_lookup.rsindex 9286860c2..7d7fefb0d 100644--- a/crates/core/src/window_lookup.rs+++ b/crates/core/src/window_lookup.rs@@ -82,6 +82,12 @@ pub(crate) fn select_window(if candidates.len() == 1 {return Ok(candidates.swap_remove(0));}+ if candidates.iter().any(|window| window.state.accessible) {+ candidates.retain(|window| window.state.accessible);+ if candidates.len() == 1 {+ return Ok(candidates.swap_remove(0));+ }+ }if candidates.iter().any(|window| window.state.visible == Some(true))diff --git a/crates/core/src/window_lookup_tests.rs b/crates/core/src/window_lookup_tests.rsindex 5c1ee139a..904f95ade 100644--- a/crates/core/src/window_lookup_tests.rs+++ b/crates/core/src/window_lookup_tests.rs@@ -92,3 +92,20 @@ fn shared_window_selector_prefers_the_only_visible_window() {assert_eq!(selected.id, "w-2");}++#[test]+fn shared_window_selector_prefers_an_accessible_window() {+ let accessible = window(Some("generation-a"));+ let mut inaccessible = accessible.clone();+ inaccessible.id = "w-2".into();+ inaccessible.state.accessible = false;++ let selected = select_window(+ vec![inaccessible, accessible],+ crate::AdapterError::new(ErrorCode::WindowNotFound, "none"),+ "multiple",+ )+ .unwrap();++ assert_eq!(selected.id, "w-1");+}diff --git a/crates/core/src/window_state.rs b/crates/core/src/window_state.rsindex 4bd40b8c0..f214f0799 100644--- a/crates/core/src/window_state.rs+++ b/crates/core/src/window_state.rs@@ -1,10 +1,27 @@use serde::{Deserialize, Serialize};-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]pub struct WindowState {pub is_focused: bool,+ #[serde(default = "default_accessible")]+ pub accessible: bool,#[serde(default, skip_serializing_if = "Option::is_none")]pub minimized: Option<bool>,#[serde(default, skip_serializing_if = "Option::is_none")]pub visible: Option<bool>,}++impl Default for WindowState {+ fn default() -> Self {+ Self {+ is_focused: false,+ accessible: true,+ minimized: None,+ visible: None,+ }+ }+}++const fn default_accessible() -> bool {+ true+}diff --git a/crates/ffi/README.md b/crates/ffi/README.mdindex cb8fbca2d..353d9e771 100644--- a/crates/ffi/README.md+++ b/crates/ffi/README.md@@ -42,8 +42,8 @@ Consumers must call `ad_init(AD_ABI_VERSION_MAJOR)` after `dlopen` to verify theloaded dylib matches the header the consumer was built against.Use additive versioned `AdExactRefEntry`, `AdExactWindowInfo`, and-`AdExactSurfaceInfo` APIs when round-tripping observed identities. Legacy ABI-v3-layouts remain binary-compatible but cannot express process generation or a+`AdExactSurfaceInfo` APIs when round-tripping observed identities. Legacy+layouts remain available but cannot express process generation or asurface ID; legacy direct window/ref targeting therefore fails closed.## Command wrappersdiff --git a/crates/ffi/cbindgen.toml b/crates/ffi/cbindgen.tomlindex 9994058ba..99ca4c3ef 100644--- a/crates/ffi/cbindgen.toml+++ b/crates/ffi/cbindgen.toml@@ -106,6 +106,7 @@ _Static_assert(offsetof(AdExactWindowInfo, version) == 0, "AdExactWindowInfo.ver_Static_assert(offsetof(AdExactWindowInfo, size) == 4, "AdExactWindowInfo.size offset changed");_Static_assert(offsetof(AdExactWindowInfo, window) == 8, "AdExactWindowInfo.window offset changed");_Static_assert(offsetof(AdExactWindowInfo, process_instance) == 80, "AdExactWindowInfo.process_instance offset changed");+_Static_assert(offsetof(AdExactWindowInfo, accessible) == 88, "AdExactWindowInfo.accessible offset changed");_Static_assert(sizeof(AdExactSurfaceInfo) == AD_EXACT_SURFACE_INFO_SIZE, "AdExactSurfaceInfo ABI size changed");_Static_assert(_Alignof(AdExactSurfaceInfo) == 8, "AdExactSurfaceInfo ABI alignment changed");_Static_assert(offsetof(AdExactSurfaceInfo, version) == 0, "AdExactSurfaceInfo.version offset changed");diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.hindex 5b3f8e483..68299e1e3 100644--- a/crates/ffi/include/agent_desktop.h+++ b/crates/ffi/include/agent_desktop.h@@ -52,7 +52,7 @@* mismatch means the header and dylib are incompatible and the consumer should* refuse to proceed rather than risk undefined behaviour.*/-#define AD_ABI_VERSION_MAJOR 3+#define AD_ABI_VERSION_MAJOR 4/*** Maximum byte length (excluding the NUL terminator) accepted for any@@ -89,9 +89,9 @@#define AD_EXACT_SURFACE_INFO_SIZE 40-#define AD_EXACT_WINDOW_INFO_VERSION 1+#define AD_EXACT_WINDOW_INFO_VERSION 2-#define AD_EXACT_WINDOW_INFO_SIZE 88+#define AD_EXACT_WINDOW_INFO_SIZE 96#define AD_FIND_CONTROL_SIZE 24@@ -767,6 +767,10 @@ typedef struct AdExactWindowInfo {uint32_t size;struct AdWindowInfo window;const char *process_instance;+ /**+ * False only when observation confirmed no matching accessibility element.+ */+ bool accessible;} AdExactWindowInfo;typedef struct AdAppInfo {@@ -2406,6 +2410,7 @@ _Static_assert(offsetof(AdExactWindowInfo, version) == 0, "AdExactWindowInfo.ver_Static_assert(offsetof(AdExactWindowInfo, size) == 4, "AdExactWindowInfo.size offset changed");_Static_assert(offsetof(AdExactWindowInfo, window) == 8, "AdExactWindowInfo.window offset changed");_Static_assert(offsetof(AdExactWindowInfo, process_instance) == 80, "AdExactWindowInfo.process_instance offset changed");+_Static_assert(offsetof(AdExactWindowInfo, accessible) == 88, "AdExactWindowInfo.accessible offset changed");_Static_assert(sizeof(AdExactSurfaceInfo) == AD_EXACT_SURFACE_INFO_SIZE, "AdExactSurfaceInfo ABI size changed");_Static_assert(_Alignof(AdExactSurfaceInfo) == 8, "AdExactSurfaceInfo ABI alignment changed");_Static_assert(offsetof(AdExactSurfaceInfo, version) == 0, "AdExactSurfaceInfo.version offset changed");diff --git a/crates/ffi/src/abi_version.rs b/crates/ffi/src/abi_version.rsindex fa631b29b..a5df63882 100644--- a/crates/ffi/src/abi_version.rs+++ b/crates/ffi/src/abi_version.rs@@ -12,7 +12,7 @@ use std::ffi::CStr;/// with the major compiled against the header to verify ABI compatibility; a/// mismatch means the header and dylib are incompatible and the consumer should/// refuse to proceed rather than risk undefined behaviour.-pub const AD_ABI_VERSION_MAJOR: u32 = 3;+pub const AD_ABI_VERSION_MAJOR: u32 = 4;static MISMATCH_MESSAGE: &CStr =c"ABI major version mismatch: recompile against the installed header";diff --git a/crates/ffi/src/abi_version_tests.rs b/crates/ffi/src/abi_version_tests.rsindex ddd0ab85c..44b9e832e 100644--- a/crates/ffi/src/abi_version_tests.rs+++ b/crates/ffi/src/abi_version_tests.rs@@ -1,15 +1,8 @@use super::*;-/// ABI 2 shipped the expanded result/ref layouts. Replacing the three-argument-/// `ad_dismiss_notification` with the identity-required five-argument contract-/// breaks callers compiled against ABI 2, so this branch must advertise ABI 3.#[test]-fn abi_major_covers_the_checked_dismiss_signature() {- let major = std::hint::black_box(AD_ABI_VERSION_MAJOR);- assert!(- major >= 3,- "identity-required ad_dismiss_notification is incompatible with ABI 2"- );+fn abi_major_covers_the_exact_window_layout() {+ assert_eq!(AD_ABI_VERSION_MAJOR, 4);}#[test]diff --git a/crates/ffi/src/convert/window.rs b/crates/ffi/src/convert/window.rsindex 7065ecaf4..645d9511f 100644--- a/crates/ffi/src/convert/window.rs+++ b/crates/ffi/src/convert/window.rs@@ -35,6 +35,7 @@ pub(crate) fn exact_window_info_to_c(w: &WindowInfo) -> AdExactWindowInfo {size: crate::types::exact_window_info::AD_EXACT_WINDOW_INFO_SIZE as u32,window: window_info_to_c(w),process_instance: opt_string_to_c(w.process_instance.as_deref()),+ accessible: w.state.accessible,}}@@ -117,6 +118,7 @@ mod tests {}),state: agent_desktop_core::WindowState {is_focused: true,+ accessible: true,minimized: None,visible: None,},@@ -181,6 +183,7 @@ mod tests {unsafe { c_to_string(exact.process_instance) }.as_deref(),Some("9:123"));+ assert!(exact.accessible);unsafe { free_exact_window_info_fields(&mut exact) };assert!(exact.process_instance.is_null());}diff --git a/crates/ffi/src/observation/find_abi_tests.rs b/crates/ffi/src/observation/find_abi_tests.rsindex bc620cf6e..09fe8021c 100644--- a/crates/ffi/src/observation/find_abi_tests.rs+++ b/crates/ffi/src/observation/find_abi_tests.rs@@ -86,6 +86,7 @@ fn ffi_window() -> AdExactWindowInfo {is_focused: false,},process_instance: c"42:100".as_ptr(),+ accessible: true,}}diff --git a/crates/ffi/src/observation/is_abi_tests.rs b/crates/ffi/src/observation/is_abi_tests.rsindex cfe2f9cca..ad195c57e 100644--- a/crates/ffi/src/observation/is_abi_tests.rs+++ b/crates/ffi/src/observation/is_abi_tests.rs@@ -78,6 +78,7 @@ fn window() -> AdExactWindowInfo {is_focused: false,},process_instance: c"42:100".as_ptr(),+ accessible: true,}}diff --git a/crates/ffi/src/types/exact_window_info.rs b/crates/ffi/src/types/exact_window_info.rsindex 274a15a89..cb90a3624 100644--- a/crates/ffi/src/types/exact_window_info.rs+++ b/crates/ffi/src/types/exact_window_info.rs@@ -2,8 +2,8 @@ use std::os::raw::c_char;use crate::types::AdWindowInfo;-pub const AD_EXACT_WINDOW_INFO_VERSION: u32 = 1;-pub const AD_EXACT_WINDOW_INFO_SIZE: usize = 88;+pub const AD_EXACT_WINDOW_INFO_VERSION: u32 = 2;+pub const AD_EXACT_WINDOW_INFO_SIZE: usize = 96;/// Additive generation-pinned window identity for operations that target a/// previously observed live window.@@ -13,6 +13,8 @@ pub struct AdExactWindowInfo {pub size: u32,pub window: AdWindowInfo,pub process_instance: *const c_char,+ /// False only when observation confirmed no matching accessibility element.+ pub accessible: bool,}const _: () = assert!(std::mem::size_of::<AdExactWindowInfo>() == AD_EXACT_WINDOW_INFO_SIZE);diff --git a/crates/ffi/src/windows/to_core.rs b/crates/ffi/src/windows/to_core.rsindex 0b15e8f7a..5abc5eece 100644--- a/crates/ffi/src/windows/to_core.rs+++ b/crates/ffi/src/windows/to_core.rs@@ -36,10 +36,14 @@ pub(crate) fn ad_exact_window_to_core("process_instance is empty",));}- decode_window(&exact.window, process_instance)+ decode_window(&exact.window, process_instance, exact.accessible)}-fn decode_window(w: &AdWindowInfo, process_instance: String) -> Result<WindowInfo, AdapterError> {+fn decode_window(+ w: &AdWindowInfo,+ process_instance: String,+ accessible: bool,+) -> Result<WindowInfo, AdapterError> {if w.pid == 0 {return Err(AdapterError::new(agent_desktop_core::ErrorCode::InvalidArgs,@@ -70,6 +74,7 @@ fn decode_window(w: &AdWindowInfo, process_instance: String) -> Result<WindowInfbounds,state: agent_desktop_core::WindowState {is_focused: w.is_focused,+ accessible,minimized: None,visible: None,},@@ -132,6 +137,18 @@ mod tests {assert!(error.message.contains("version or size"));}+ #[test]+ fn exact_window_preserves_accessibility() {+ let id = CString::new("w-1").unwrap();+ let title = CString::new("Main").unwrap();+ let mut exact = window(id.as_ptr(), title.as_ptr(), std::ptr::null());+ exact.accessible = false;++ let decoded = ad_exact_window_to_core(&exact).unwrap();++ assert!(!decoded.state.accessible);+ }+fn window(id: *const std::os::raw::c_char,title: *const std::os::raw::c_char,@@ -155,6 +172,7 @@ mod tests {is_focused: false,},process_instance: c"7:100".as_ptr(),+ accessible: true,}}}diff --git a/crates/ffi/tests/c_abi_init.rs b/crates/ffi/tests/c_abi_init.rsindex 8e7185f95..ea4580344 100644--- a/crates/ffi/tests/c_abi_init.rs+++ b/crates/ffi/tests/c_abi_init.rs@@ -23,6 +23,13 @@ fn ad_init_succeeds_with_current_major() {}}+#[test]+fn ad_init_rejects_previous_major() {+ unsafe {+ assert_eq!(ad_init(3), AdResult::ErrInvalidArgs);+ }+}+#[test]fn ad_init_rejects_future_major_and_sets_last_error() {unsafe {diff --git a/crates/ffi/tests/c_abi_layout.rs b/crates/ffi/tests/c_abi_layout.rsindex 667443ddd..ee998f0aa 100644--- a/crates/ffi/tests/c_abi_layout.rs+++ b/crates/ffi/tests/c_abi_layout.rs@@ -240,15 +240,16 @@ fn exact_ref_entry_is_additive_versioned_and_layout_pinned() {#[test]fn exact_window_info_is_additive_versioned_and_layout_pinned() {- assert_eq!(agent_desktop_ffi::AD_EXACT_WINDOW_INFO_VERSION, 1);- assert_eq!(agent_desktop_ffi::AD_EXACT_WINDOW_INFO_SIZE, 88);- assert_eq!(unsafe { common::ad_exact_window_info_size() }, 88);- assert_eq!(size_of::<AdExactWindowInfo>(), 88);+ assert_eq!(agent_desktop_ffi::AD_EXACT_WINDOW_INFO_VERSION, 2);+ assert_eq!(agent_desktop_ffi::AD_EXACT_WINDOW_INFO_SIZE, 96);+ assert_eq!(unsafe { common::ad_exact_window_info_size() }, 96);+ assert_eq!(size_of::<AdExactWindowInfo>(), 96);assert_eq!(align_of::<AdExactWindowInfo>(), align_of::<usize>());assert_eq!(offset_of!(AdExactWindowInfo, version), 0);assert_eq!(offset_of!(AdExactWindowInfo, size), 4);assert_eq!(offset_of!(AdExactWindowInfo, window), 8);assert_eq!(offset_of!(AdExactWindowInfo, process_instance), 80);+ assert_eq!(offset_of!(AdExactWindowInfo, accessible), 88);}#[test]diff --git a/crates/macos/build.rs b/crates/macos/build.rsindex 783350f08..f2dde2fa6 100644--- a/crates/macos/build.rs+++ b/crates/macos/build.rs@@ -6,6 +6,8 @@ fn main() {println!("cargo:rerun-if-changed=src/system/appkit_bridge.m");println!("cargo:rerun-if-changed=src/system/screen_bridge.m");println!("cargo:rerun-if-changed=src/system/cursor_overlay_bridge.m");+ println!("cargo:rerun-if-changed=src/system/cursor_overlay_chrome_bridge.m");+ println!("cargo:rerun-if-changed=src/system/cursor_overlay_chrome.h");println!("cargo:rerun-if-changed=src/system/cursor_overlay_display_bridge.m");println!("cargo:rerun-if-env-changed=TARGET");println!("cargo:rerun-if-env-changed=MACOSX_DEPLOYMENT_TARGET");@@ -24,6 +26,7 @@ fn main() {let appkit_object = out_dir.join("appkit_bridge.o");let screen_object = out_dir.join("screen_bridge.o");let cursor_overlay_object = out_dir.join("cursor_overlay_bridge.o");+ let cursor_overlay_chrome_object = out_dir.join("cursor_overlay_chrome_bridge.o");let cursor_overlay_display_object = out_dir.join("cursor_overlay_display_bridge.o");let archive = out_dir.join("libagent_desktop_launch_bridge.a");run(@@ -58,6 +61,22 @@ fn main() {.arg(&cursor_overlay_object),"compile Objective-C cursor overlay bridge",);+ run(+ Command::new("xcrun")+ .args(["--sdk", "macosx", "clang"])+ .args(["-fobjc-arc", "-target", &target])+ .arg(format!("-mmacosx-version-min={deployment}"))+ .args([+ "-Wall",+ "-Wextra",+ "-Werror",+ "-c",+ "src/system/cursor_overlay_chrome_bridge.m",+ "-o",+ ])+ .arg(&cursor_overlay_chrome_object),+ "compile Objective-C cursor overlay chrome bridge",+ );run(Command::new("xcrun").args(["--sdk", "macosx", "clang"])@@ -114,7 +133,8 @@ fn main() {.arg(&appkit_object).arg(&screen_object).arg(&cursor_overlay_object)- .arg(&cursor_overlay_display_object),+ .arg(&cursor_overlay_display_object)+ .arg(&cursor_overlay_chrome_object),"archive Objective-C launch bridge",);println!("cargo:rustc-link-search=native={}", out_dir.display());diff --git a/crates/macos/src/actions/chain_value_write.rs b/crates/macos/src/actions/chain_value_write.rsindex 60a388501..2b7bbe9a3 100644--- a/crates/macos/src/actions/chain_value_write.rs+++ b/crates/macos/src/actions/chain_value_write.rs@@ -12,10 +12,24 @@ mod imp {deadline: Deadline,) -> Result<DeliveryOutcome, AdapterError> {prepare(element, deadline)?;- if attribute == "AXValue" {- ax_helpers::set_ax_value_coerced(element, value, deadline)?;+ let uncertain = if attribute == "AXValue" {+ ax_helpers::set_ax_value_coerced(element, value, deadline).err()} else {- ax_helpers::set_ax_string_or_err(element, attribute, value, deadline)?;+ ax_helpers::set_ax_string_or_err(element, attribute, value, deadline).err()+ };+ if let Some(error) = uncertain {+ if error.disposition != agent_desktop_core::DeliverySemantics::uncertain() {+ return Err(error);+ }+ let recovery = Deadline::detached_after(500)?;+ let observed = crate::tree::copy_value_typed(element, recovery);+ let verified =+ chain_verify::dynamic_write_had_effect(attribute, None, value, observed.as_deref());+ return if verified {+ Ok(DeliveryOutcome::DeliveredVerified)+ } else {+ Err(error)+ };}let mut delivery = crate::actions::DeliveryTracker::default();delivery.mark_delivered();diff --git a/crates/macos/src/system/cg_window.rs b/crates/macos/src/system/cg_window.rsindex ccaa3070e..e28bf5fdb 100644--- a/crates/macos/src/system/cg_window.rs+++ b/crates/macos/src/system/cg_window.rs@@ -24,6 +24,7 @@ impl WindowRecord {self,is_focused: bool,minimized: Option<bool>,+ accessible: bool,) -> Result<WindowInfo, AdapterError> {let title = self.title.unwrap_or_else(|| self.app_name.clone());Ok(WindowInfo {@@ -35,6 +36,7 @@ impl WindowRecord {bounds: Some(self.bounds),state: agent_desktop_core::WindowState {is_focused,+ accessible,minimized,visible: Some(self.visible),},diff --git a/crates/macos/src/system/cursor_overlay/bridge.rs b/crates/macos/src/system/cursor_overlay/bridge.rsindex 472deac92..48cfb4cdc 100644--- a/crates/macos/src/system/cursor_overlay/bridge.rs+++ b/crates/macos/src/system/cursor_overlay/bridge.rs@@ -1,8 +1,26 @@-use agent_desktop_core::{AdapterError, CursorOverlayInstruction, ErrorCode, Point, Rect};+use agent_desktop_core::{+ AdapterError, CURSOR_HIGHLIGHT_HOLD_MS, CursorOverlayInstruction, CursorOverlayStyle,+ CursorPose, ErrorCode, Point, Rect,+};use std::ffi::{CString, c_char};-const CLICK: u8 = 1 << 1;const REDUCE_MOTION: u8 = 1 << 2;+const HIGHLIGHT: u8 = 1 << 3;++#[repr(C)]+struct NativeCursorStyle {+ fill: [f64; 3],+ rim: [f64; 3],+ accent: [f64; 3],+ size: f64,+}++#[repr(C)]+struct NativeCursorFrame {+ x: f64,+ y: f64,+ ripple: f64,+}#[repr(C)]struct NativeRenderConfig {@@ -10,6 +28,8 @@ struct NativeRenderConfig {label: *const c_char,bubble_x: f64,bubble_y: f64,+ target: [f64; 4],+ highlight_seconds: f64,flags: u8,}@@ -17,12 +37,14 @@ unsafe extern "C" {fn agent_desktop_cursor_overlay_initial_point(output: *mut f64) -> bool;fn agent_desktop_cursor_overlay_screen(x: f64, y: f64, output: *mut f64) -> bool;fn agent_desktop_cursor_overlay_run(- points: *const f64,- point_count: usize,+ frames: *const NativeCursorFrame,+ frame_count: usize,config: *const NativeRenderConfig,) -> bool;+ fn agent_desktop_cursor_overlay_style(style: *const NativeCursorStyle);fn agent_desktop_cursor_overlay_idle();fn agent_desktop_cursor_overlay_hide();+ fn agent_desktop_cursor_overlay_rest();fn agent_desktop_cursor_overlay_show();fn agent_desktop_cursor_overlay_stop();}@@ -62,15 +84,19 @@ pub(super) fn screen_at(point: &Point) -> Result<(Rect, u32, bool), AdapterError}pub(super) fn run(- points: &[Point],+ poses: &[CursorPose],fps: u32,instruction: &CursorOverlayInstruction,reduce_motion: bool,bubble: &Rect,) -> Result<(), AdapterError> {- let native_points = points+ let frames = poses.iter()- .flat_map(|point| [point.x, point.y])+ .map(|pose| NativeCursorFrame {+ x: pose.point.x,+ y: pose.point.y,+ ripple: pose.ripple,+ }).collect::<Vec<_>>();let label = instruction.label()@@ -78,12 +104,15 @@ pub(super) fn run(.transpose().map_err(|_| AdapterError::internal("Cursor overlay label encoding failed"))?;let mut flags = 0;- if instruction.is_click() {- flags |= CLICK;- }if reduce_motion {flags |= REDUCE_MOTION;}+ let target = instruction+ .target()+ .map(|rect| [rect.x, rect.y, rect.width, rect.height]);+ if target.is_some() {+ flags |= HIGHLIGHT;+ }let config = NativeRenderConfig {frame_seconds: 1.0 / f64::from(fps),label: label@@ -91,11 +120,11 @@ pub(super) fn run(.map_or(std::ptr::null(), |value| value.as_ptr()),bubble_x: bubble.x,bubble_y: bubble.y,+ target: target.unwrap_or_default(),+ highlight_seconds: CURSOR_HIGHLIGHT_HOLD_MS as f64 / 1_000.0,flags,};- if unsafe {- agent_desktop_cursor_overlay_run(native_points.as_ptr(), native_points.len() / 2, &config)- } {+ if unsafe { agent_desktop_cursor_overlay_run(frames.as_ptr(), frames.len(), &config) } {Ok(())} else {Err(AdapterError::new(@@ -105,6 +134,16 @@ pub(super) fn run(}}+pub(super) fn apply_style(style: &CursorOverlayStyle) {+ let native = NativeCursorStyle {+ fill: style.fill_rgb(),+ rim: style.rim_rgb(),+ accent: style.accent_rgb(),+ size: style.size(),+ };+ unsafe { agent_desktop_cursor_overlay_style(&native) }+}+pub(super) fn idle() {unsafe { agent_desktop_cursor_overlay_idle() }}@@ -113,6 +152,10 @@ pub(super) fn stop() {unsafe { agent_desktop_cursor_overlay_stop() }}+pub(super) fn rest() {+ unsafe { agent_desktop_cursor_overlay_rest() }+}+pub(super) fn hide() {unsafe { agent_desktop_cursor_overlay_hide() }}diff --git a/crates/macos/src/system/cursor_overlay/child.rs b/crates/macos/src/system/cursor_overlay/child.rsindex 80f2a8ed7..1a8612d83 100644--- a/crates/macos/src/system/cursor_overlay/child.rs+++ b/crates/macos/src/system/cursor_overlay/child.rs@@ -1,6 +1,6 @@use agent_desktop_core::{- AdapterError, CursorMotion, CursorOverlayConfig, CursorOverlayControl,- CursorOverlayInstruction, ErrorCode, Point, place_label,+ AdapterError, CURSOR_IDLE_REST_MS, CursorMotion, CursorOverlayConfig, CursorOverlayControl,+ CursorOverlayInstruction, CursorOverlayStyle, CursorPose, ErrorCode, Point, place_label,};use std::io::{Read, Write};use std::os::unix::fs::PermissionsExt;@@ -12,15 +12,21 @@ use std::time::Duration;use super::bridge;pub(super) const MARKER: &str = "AGENT_DESKTOP_CURSOR_OVERLAY_CHILD";-pub(super) const PROTOCOL_VERSION: &str = "v1";pub(super) const SOCKET_ENV: &str = "AGENT_DESKTOP_CURSOR_OVERLAY_SOCKET";const MAX_INSTRUCTION_BYTES: u64 = 4 * 1024;const BUBBLE_SIZE: (f64, f64) = (232.0, 38.0);+#[derive(Default)]+struct OverlayState {+ style: CursorOverlayStyle,+ at: Option<Point>,+ resting: bool,+}+pub(crate) fn entry_from_env() -> Option<Result<(), AdapterError>> {match std::env::var(MARKER) {Err(_) => None,- Ok(value) if value == PROTOCOL_VERSION => Some(run()),+ Ok(value) if value == super::endpoint::PROTOCOL_VERSION => Some(run()),Ok(_) => Some(Err(AdapterError::internal("Invalid cursor overlay child protocol marker",))),@@ -31,6 +37,10 @@ fn run() -> Result<(), AdapterError> {let initial = read_control(std::io::stdin())?;let socket = socket_path(&initial)?;prepare_socket(&socket)?;+ let mut state = OverlayState::default();+ if !handle(&initial, &mut state)? {+ return cleanup(socket);+ }let listener = UnixListener::bind(&socket).map_err(|error| {AdapterError::internal("Could not bind the cursor overlay session socket").with_platform_detail(error.to_string())@@ -43,10 +53,7 @@ fn run() -> Result<(), AdapterError> {AdapterError::internal("Could not configure the cursor overlay session socket").with_platform_detail(error.to_string())})?;- let mut current = None;- if !handle(&initial, &mut current)? {- return cleanup(socket);- }+ let mut quiet_since = std::time::Instant::now();loop {match listener.accept() {Ok((mut stream, _)) => {@@ -62,15 +69,27 @@ fn run() -> Result<(), AdapterError> {let _ = stream.write_all(&[1]);return Ok(());}- if handle(&control, &mut current).is_err() {- continue;+ quiet_since = std::time::Instant::now();+ if state.resting {+ bridge::show();+ state.resting = false;}- if control.is_hide() {+ let outcome = handle(&control, &mut state);+ if outcome.is_ok() && (control.is_hide() || control.is_travel()) {let _ = stream.write_all(&[1]);}+ if outcome.is_err() {+ continue;+ }}Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {bridge::idle();+ if !state.resting+ && quiet_since.elapsed().as_millis() >= u128::from(CURSOR_IDLE_REST_MS)+ {+ bridge::rest();+ state.resting = true;+ }thread::sleep(Duration::from_millis(8));}Err(error) => {@@ -84,14 +103,15 @@ fn run() -> Result<(), AdapterError> {}}-fn handle(- control: &CursorOverlayControl,- current: &mut Option<Point>,-) -> Result<bool, AdapterError> {+fn handle(control: &CursorOverlayControl, state: &mut OverlayState) -> Result<bool, AdapterError> {control.validate()?;if control.is_disable() {return Ok(false);}+ if let Some(style) = control.style() {+ state.style = style.clone();+ bridge::apply_style(&state.style);+ }if control.is_hide() {bridge::hide();return Ok(true);@@ -108,42 +128,60 @@ fn handle(owned = CursorOverlayInstruction::new(bridge::initial_point()?, &config, false)?;&owned};- render(instruction, current)?;- *current = Some(instruction.destination().clone());+ render(instruction, state)?;+ state.at = Some(instruction.destination().clone());Ok(true)}fn render(instruction: &CursorOverlayInstruction,- current: &Option<Point>,+ state: &OverlayState,) -> Result<(), AdapterError> {let (screen, fps, reduce_motion) = bridge::screen_at(instruction.destination())?;let bubble = place_label(instruction.destination(), BUBBLE_SIZE, &screen);- let points = if reduce_motion {- vec![instruction.destination().clone()]+ let shown = if state.style.highlight() {+ instruction.clone()} else {- motion_points(current.as_ref(), instruction.destination(), &screen, fps)+ instruction.clone().with_target(None)};- bridge::run(&points, fps, instruction, reduce_motion, &bubble)+ let frames = if reduce_motion {+ vec![CursorPose::still(instruction.destination().clone())]+ } else {+ motion_frames(state, &shown, &screen, fps)+ };+ bridge::run(&frames, fps, &shown, reduce_motion, &bubble)}-fn motion_points(- current: Option<&Point>,- destination: &Point,+fn motion_frames(+ state: &OverlayState,+ instruction: &CursorOverlayInstruction,screen: &agent_desktop_core::Rect,fps: u32,-) -> Vec<Point> {- let start = current.cloned().unwrap_or_else(|| Point {+) -> Vec<CursorPose> {+ let destination = instruction.destination();+ if instruction.phase() == agent_desktop_core::CursorPhase::Effect {+ let mut frames = vec![CursorPose::still(destination.clone())];+ if instruction.is_click() && state.style.ripple() {+ frames.push(CursorPose {+ point: destination.clone(),+ ripple: 1.0,+ });+ }+ return frames;+ }+ let start = state.at.clone().unwrap_or_else(|| Point {x: (destination.x - 180.0).clamp(screen.x, screen.x + screen.width),y: (destination.y + 108.0).clamp(screen.y, screen.y + screen.height),});- let motion = CursorMotion::new(start, destination.clone());+ let motion = CursorMotion::new(start, destination.clone())+ .with_impact(instruction.is_click())+ .with_ripple(state.style.ripple());let frame_ms = 1_000.0 / f64::from(fps);- let frame_count = (motion.duration_ms() as f64 / frame_ms).ceil() as u64;+ let frame_count = (motion.total_ms() as f64 / frame_ms).ceil() as u64;(0..=frame_count).map(|frame| {- let elapsed = ((frame as f64 * frame_ms).round() as u64).min(motion.duration_ms());- motion.sample(elapsed)+ let elapsed = ((frame as f64 * frame_ms).round() as u64).min(motion.total_ms());+ motion.pose(elapsed)}).collect()}@@ -211,34 +249,98 @@ fn cleanup(path: PathBuf) -> Result<(), AdapterError> {mod tests {use super::*;- #[test]- fn sampled_motion_ends_at_the_requested_destination() {- let screen = agent_desktop_core::Rect {+ fn state(at: Option<Point>) -> OverlayState {+ OverlayState {+ at,+ ..OverlayState::default()+ }+ }++ fn screen() -> agent_desktop_core::Rect {+ agent_desktop_core::Rect {x: 0.0,y: 0.0,width: 1920.0,height: 1080.0,- };+ }+ }++ fn instruction(destination: Point, click: bool) -> CursorOverlayInstruction {+ let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");+ CursorOverlayInstruction::new(destination, &config, click).expect("valid instruction")+ }++ #[test]+ fn sampled_motion_ends_at_the_requested_destination() {let destination = Point { x: 900.0, y: 500.0 };- let points = motion_points(None, &destination, &screen, 120);+ let frames = motion_frames(+ &state(None),+ &instruction(destination.clone(), false),+ &screen(),+ 120,+ );- assert_eq!(points.last(), Some(&destination));- assert!(points.len() >= 51);+ assert_eq!(frames.last().map(|pose| &pose.point), Some(&destination));+ let biggest_step = frames+ .windows(2)+ .map(|pair| {+ (pair[1].point.x - pair[0].point.x).hypot(pair[1].point.y - pair[0].point.y)+ })+ .fold(0.0_f64, f64::max);+ assert!(frames.len() >= 20, "the path is sampled per frame");+ assert!(+ biggest_step < 40.0,+ "no visible jump between frames: {biggest_step}"+ );}#[test]fn subsequent_motion_starts_from_the_previous_destination() {- let screen = agent_desktop_core::Rect {- x: 0.0,- y: 0.0,- width: 1920.0,- height: 1080.0,- };let start = Point { x: 200.0, y: 300.0 };let destination = Point { x: 900.0, y: 500.0 };- let points = motion_points(Some(&start), &destination, &screen, 120);+ let frames = motion_frames(+ &state(Some(start.clone())),+ &instruction(destination.clone(), false),+ &screen(),+ 120,+ );++ assert_eq!(frames.first().map(|pose| &pose.point), Some(&start));+ assert_eq!(frames.last().map(|pose| &pose.point), Some(&destination));+ }++ #[test]+ fn a_click_instruction_adds_ripple_frames_at_the_destination() {+ let destination = Point { x: 900.0, y: 500.0 };+ let moved = motion_frames(+ &state(None),+ &instruction(destination.clone(), false),+ &screen(),+ 120,+ );+ let clicked = motion_frames(+ &state(None),+ &instruction(destination.clone(), true),+ &screen(),+ 120,+ );++ assert!(clicked.len() > moved.len());+ assert!(clicked.iter().any(|pose| pose.ripple > 0.0));+ assert_eq!(clicked.last().map(|pose| &pose.point), Some(&destination));+ }++ #[test]+ fn click_effect_returns_immediately_to_the_control_loop() {+ let destination = Point { x: 900.0, y: 500.0 };+ let effect = instruction(destination.clone(), true)+ .with_phase(agent_desktop_core::CursorPhase::Effect);++ let frames = motion_frames(&state(Some(destination.clone())), &effect, &screen(), 120);- assert_eq!(points.first(), Some(&start));- assert_eq!(points.last(), Some(&destination));+ assert_eq!(frames.len(), 2);+ assert_eq!(frames[0], CursorPose::still(destination.clone()));+ assert_eq!(frames[1].point, destination);+ assert_eq!(frames[1].ripple, 1.0);}}diff --git a/crates/macos/src/system/cursor_overlay/endpoint.rs b/crates/macos/src/system/cursor_overlay/endpoint.rsindex 09766d7e9..3ad4f7c31 100644--- a/crates/macos/src/system/cursor_overlay/endpoint.rs+++ b/crates/macos/src/system/cursor_overlay/endpoint.rs@@ -2,10 +2,18 @@ use agent_desktop_core::{AdapterError, ErrorCode, session};use std::os::unix::ffi::OsStrExt;use std::path::{Path, PathBuf};+pub(super) const PROTOCOL_VERSION: &str = "v2";+pub(super) fn path(session_id: &str) -> Result<PathBuf, AdapterError> {let root = session::agent_desktop_dir().map_err(|error| AdapterError::new(ErrorCode::InvalidArgs, error.to_string()))?;- Ok(path_for_root(&root, session_id))+ Ok(path_for_root(&root, session_id, Some(PROTOCOL_VERSION)))+}++pub(super) fn legacy_path(session_id: &str) -> Result<PathBuf, AdapterError> {+ let root = session::agent_desktop_dir()+ .map_err(|error| AdapterError::new(ErrorCode::InvalidArgs, error.to_string()))?;+ Ok(path_for_root(&root, session_id, None))}pub(super) fn lock_path() -> Result<PathBuf, AdapterError> {@@ -14,10 +22,10 @@ pub(super) fn lock_path() -> Result<PathBuf, AdapterError> {Ok(root.join(".cursor-overlay-start.lock"))}-fn path_for_root(root: &Path, session_id: &str) -> PathBuf {+fn path_for_root(root: &Path, session_id: &str, protocol: Option<&str>) -> PathBuf {let name = format!(".cursor-overlay-{:016x}.sock",- endpoint_hash(root, session_id)+ endpoint_hash(root, session_id, protocol));let path = root.join(&name);if path.as_os_str().as_bytes().len() < 100 {@@ -27,13 +35,14 @@ fn path_for_root(root: &Path, session_id: &str) -> PathBuf {}}-fn endpoint_hash(root: &Path, session_id: &str) -> u64 {+fn endpoint_hash(root: &Path, session_id: &str, protocol: Option<&str>) -> u64 {let mut hash = 0xcbf29ce484222325_u64;for byte in root.as_os_str().as_bytes().iter().chain(session_id.as_bytes())+ .chain(protocol.into_iter().flat_map(str::as_bytes)){hash ^= u64::from(*byte);hash = hash.wrapping_mul(0x100000001b3);@@ -48,11 +57,21 @@ mod tests {#[test]fn long_state_root_uses_a_short_deterministic_socket_path() {let root = Path::new("/private/tmp").join("deep".repeat(40));- let first = path_for_root(&root, "run-1");- let second = path_for_root(&root, "run-1");+ let first = path_for_root(&root, "run-1", Some(PROTOCOL_VERSION));+ let second = path_for_root(&root, "run-1", Some(PROTOCOL_VERSION));assert_eq!(first, second);assert_eq!(first.parent(), Some(Path::new("/tmp")));assert!(first.as_os_str().as_bytes().len() < 100);}++ #[test]+ fn protocol_generation_uses_a_distinct_socket() {+ let root = Path::new("/private/tmp/state");++ assert_ne!(+ path_for_root(root, "run-1", None),+ path_for_root(root, "run-1", Some(PROTOCOL_VERSION))+ );+ }}diff --git a/crates/macos/src/system/cursor_overlay/spawn.rs b/crates/macos/src/system/cursor_overlay/spawn.rsindex ca808f2b3..c19585de6 100644--- a/crates/macos/src/system/cursor_overlay/spawn.rs+++ b/crates/macos/src/system/cursor_overlay/spawn.rs@@ -1,4 +1,6 @@-use agent_desktop_core::{AdapterError, CursorOverlayControl, ErrorCode};+use agent_desktop_core::{+ AdapterError, CURSOR_ARRIVAL_TIMEOUT_MS, CursorOverlayControl, ErrorCode,+};use std::fs::OpenOptions;use std::io::{Read, Write};use std::os::unix::fs::OpenOptionsExt;@@ -9,14 +11,18 @@ use std::process::{Command, Stdio};use std::thread;use std::time::{Duration, Instant};-use super::child::{MARKER, PROTOCOL_VERSION, SOCKET_ENV};+use super::child::{MARKER, SOCKET_ENV};const MAX_INSTRUCTION_BYTES: usize = 4 * 1024;pub(crate) fn update(control: &CursorOverlayControl) -> Result<(), AdapterError> {control.validate()?;let socket = super::endpoint::path(control.session_id())?;- if send(&socket, control).is_ok() || control.is_disable() || control.is_transient() {+ if send(&socket, control).is_ok() {+ return Ok(());+ }+ retire_legacy(control);+ if control.is_disable() || (control.is_transient() && !control.is_travel()) {return Ok(());}let lock_path = super::endpoint::lock_path()?;@@ -60,7 +66,7 @@ fn spawn(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterErr));}let mut child = Command::new(executable)- .env(MARKER, PROTOCOL_VERSION)+ .env(MARKER, super::endpoint::PROTOCOL_VERSION).env(SOCKET_ENV, socket).process_group(0).stdin(Stdio::piped())@@ -79,7 +85,7 @@ fn spawn(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterErr.with_platform_detail(error.to_string())})?;drop(stdin);- let deadline = Instant::now() + Duration::from_millis(500);+ let deadline = Instant::now() + Duration::from_millis(CURSOR_ARRIVAL_TIMEOUT_MS);while Instant::now() < deadline {if UnixStream::connect(socket).is_ok() {return Ok(());@@ -91,6 +97,14 @@ fn spawn(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterErr))}+fn retire_legacy(control: &CursorOverlayControl) {+ let Ok(socket) = super::endpoint::legacy_path(control.session_id()) else {+ return;+ };+ let disable = CursorOverlayControl::disable(control.session_id().to_owned());+ let _ = send(&socket, &disable);+}+fn send(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterError> {let mut stream = UnixStream::connect(socket).map_err(|error| {AdapterError::internal("Could not connect to the macOS cursor overlay")@@ -110,7 +124,8 @@ fn send(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterErroAdapterError::internal("Could not send the cursor overlay control").with_platform_detail(error.to_string())})?;- if !control.is_hide() && !control.is_disable() {+ let travels = control.is_travel();+ if !travels && !control.is_hide() && !control.is_disable() {return Ok(());}stream@@ -119,15 +134,25 @@ fn send(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterErroAdapterError::internal("Could not finish the cursor overlay control").with_platform_detail(error.to_string())})?;- stream- .set_read_timeout(Some(Duration::from_secs(4)))- .map_err(|error| {- AdapterError::internal("Could not bound the cursor overlay acknowledgement")- .with_platform_detail(error.to_string())- })?;- let mut acknowledgement = [0_u8; 1];- stream.read_exact(&mut acknowledgement).map_err(|error| {- AdapterError::internal("macOS cursor overlay did not acknowledge the control")+ let budget = if travels {+ Duration::from_millis(CURSOR_ARRIVAL_TIMEOUT_MS)+ } else {+ Duration::from_secs(4)+ };+ stream.set_read_timeout(Some(budget)).map_err(|error| {+ AdapterError::internal("Could not bound the cursor overlay acknowledgement").with_platform_detail(error.to_string())- })+ })?;+ let mut acknowledgement = [0_u8; 1];+ match stream.read_exact(&mut acknowledgement) {+ Ok(()) => Ok(()),+ Err(error) if travels => {+ tracing::debug!(%error, "cursor overlay arrival was not acknowledged in time");+ Ok(())+ }+ Err(error) => Err(AdapterError::internal(+ "macOS cursor overlay did not acknowledge the control",+ )+ .with_platform_detail(error.to_string())),+ }}diff --git a/crates/macos/src/system/cursor_overlay_bridge.m b/crates/macos/src/system/cursor_overlay_bridge.mindex a6e5f4d5f..d60f5ea44 100644--- a/crates/macos/src/system/cursor_overlay_bridge.m+++ b/crates/macos/src/system/cursor_overlay_bridge.m@@ -1,124 +1,107 @@-#import <AppKit/AppKit.h>-#import <QuartzCore/QuartzCore.h>+#import "cursor_overlay_chrome.h"#import <CoreGraphics/CoreGraphics.h>#import <stdbool.h>#import <stddef.h>#import <stdint.h>-#import <math.h>++typedef struct {+ double x;+ double y;+ double ripple;+} AgentDesktopCursorFrame;typedef struct {double frameSeconds;const char *label;double bubbleX;double bubbleY;+ double target[4];+ double highlightSeconds;uint8_t flags;} AgentDesktopCursorRenderConfig;-static const uint8_t ADClickCue = 1 << 1;static const uint8_t ADReduceMotion = 1 << 2;+static const uint8_t ADHighlightCue = 1 << 3;+static const CGFloat ADStage = 240.0;+static const CGFloat ADBoxWidth = 32.0;+static const CGFloat ADBoxHeight = 40.0;+static const CGFloat ADTipX = 88.0;+static const CGFloat ADTipY = 172.0;+static const CGFloat ADBubbleWidth = 232.0;+static const CGFloat ADBubbleHeight = 38.0;+static const CGFloat ADHighlightPad = 5.0;+static __strong NSWindow *ADCursorWindow = nil;-static __strong CAShapeLayer *ADArrowLayer = nil;-static __strong CAShapeLayer *ADHandPointerLayer = nil;+static __strong CALayer *ADPointer = nil;+static __strong NSWindow *ADRipple = nil;static __strong NSWindow *ADBubbleWindow = nil;static __strong NSTextField *ADBubbleText = nil;-static NSWindow *ADWindow(NSRect frame) {- NSWindow *window = [[NSWindow alloc]- initWithContentRect:frame- styleMask:NSWindowStyleMaskBorderless- backing:NSBackingStoreBuffered- defer:NO];- window.opaque = NO;- window.backgroundColor = NSColor.clearColor;- window.hasShadow = NO;- window.ignoresMouseEvents = YES;- window.releasedWhenClosed = NO;- window.hidesOnDeactivate = NO;- window.level = 25;- window.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |- NSWindowCollectionBehaviorFullScreenAuxiliary;- NSView *view = [[NSView alloc]- initWithFrame:NSMakeRect(0.0, 0.0, frame.size.width, frame.size.height)];- view.wantsLayer = YES;- window.contentView = view;- return window;-}--static CAShapeLayer *ADCursorLayer(void) {+static CAShapeLayer *ADDartLayer(void) {+ static const CGPoint dart[] = {+ {1.0, 35.0}, {29.6, 17.5}, {12.7, 16.3}, {4.2, 1.6},+ };CAShapeLayer *layer = [CAShapeLayer layer];CGMutablePathRef path = CGPathCreateMutable();- CGPathMoveToPoint(path, NULL, 4.0, 35.0);- CGPathAddLineToPoint(path, NULL, 4.0, 7.0);- CGPathAddLineToPoint(path, NULL, 11.0, 14.0);- CGPathAddLineToPoint(path, NULL, 16.0, 3.5);- CGPathAddLineToPoint(path, NULL, 22.0, 6.5);- CGPathAddLineToPoint(path, NULL, 17.0, 16.0);- CGPathAddLineToPoint(path, NULL, 28.0, 16.0);- CGPathCloseSubpath(path);- layer.path = path;- layer.fillColor = [NSColor colorWithSRGBRed:0.98 green:0.99 blue:1.0 alpha:0.98].CGColor;- layer.strokeColor = [NSColor colorWithSRGBRed:0.04 green:0.05 blue:0.07 alpha:0.94].CGColor;- layer.lineWidth = 1.8;- CGPathRelease(path);- return layer;-}--static CAShapeLayer *ADHandLayer(void) {- CAShapeLayer *layer = [CAShapeLayer layer];- CGMutablePathRef path = CGPathCreateMutable();- CGPathMoveToPoint(path, NULL, 8.0, 10.0);- CGPathAddCurveToPoint(path, NULL, 4.0, 14.0, 3.0, 22.0, 7.0, 24.0);- CGPathAddCurveToPoint(path, NULL, 9.0, 25.0, 10.0, 24.0, 11.0, 22.0);- CGPathAddLineToPoint(path, NULL, 11.0, 35.0);- CGPathAddCurveToPoint(path, NULL, 11.0, 39.0, 17.0, 39.0, 17.0, 35.0);- CGPathAddLineToPoint(path, NULL, 17.0, 26.0);- CGPathAddCurveToPoint(path, NULL, 19.0, 30.0, 23.0, 29.0, 23.0, 25.0);- CGPathAddCurveToPoint(path, NULL, 26.0, 28.0, 30.0, 25.0, 29.0, 21.0);- CGPathAddLineToPoint(path, NULL, 28.0, 15.0);- CGPathAddCurveToPoint(path, NULL, 27.0, 10.0, 22.0, 7.0, 16.0, 7.0);+ CGPathMoveToPoint(path, NULL, dart[0].x, dart[0].y);+ for (size_t index = 1; index < sizeof(dart) / sizeof(dart[0]); index += 1) {+ CGPathAddLineToPoint(path, NULL, dart[index].x, dart[index].y);+ }CGPathCloseSubpath(path);layer.path = path;- layer.fillColor = NSColor.whiteColor.CGColor;- layer.strokeColor = [NSColor colorWithWhite:0.05 alpha:0.96].CGColor;- layer.lineWidth = 1.7;- layer.hidden = YES;CGPathRelease(path);+ layer.lineWidth = 3.0;+ layer.lineJoin = kCALineJoinRound;+ layer.shadowColor = NSColor.blackColor.CGColor;+ layer.shadowOpacity = 0.32;+ layer.shadowRadius = 5.0;+ layer.shadowOffset = CGSizeMake(2.5, -3.0);+ ADFreezeLayer(layer);return layer;}-static CAShapeLayer *ADRippleLayer(void) {- CAShapeLayer *layer = [CAShapeLayer layer];- layer.fillColor = NSColor.clearColor.CGColor;- layer.strokeColor = [NSColor colorWithSRGBRed:0.78 green:0.81 blue:0.86 alpha:0.88].CGColor;- layer.lineWidth = 1.4;- layer.hidden = YES;- return layer;-}--static void ADUpdateRipple(CAShapeLayer *layer, double progress) {- if (progress <= 0.0 || progress >= 1.0) {- layer.hidden = YES;- return;- }- double eased = 1.0 - pow(1.0 - progress, 3.0);- double radius = 3.0 + 25.0 * eased;- CGMutablePathRef path = CGPathCreateMutable();- CGPathAddEllipseInRect(path,- NULL,- CGRectMake(36.0 - radius,- 36.0 - radius,- radius * 2.0,- radius * 2.0));- layer.path = path;- layer.opacity = (float)(pow(1.0 - progress, 1.7) * 0.78);- layer.hidden = NO;- CGPathRelease(path);-}--static void ADPump(NSApplication *app) {- [app updateWindows];- [[NSRunLoop currentRunLoop]- runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.0005]];+static void ADTintPointer(void) {+ const AgentDesktopCursorStyle *style = ADStyle();+ CAShapeLayer *rim = (CAShapeLayer *)ADPointer.sublayers.firstObject;+ CAShapeLayer *dart = (CAShapeLayer *)ADPointer.sublayers.lastObject;+ rim.fillColor = ADColor(style->rim, 1.0);+ rim.strokeColor = ADColor(style->rim, 1.0);+ dart.fillColor = ADColor(style->fill, 1.0);+ dart.strokeColor = ADColor(style->fill, 1.0);+ ADPointer.transform = CATransform3DMakeScale(style->size, style->size, 1.0);+}++static CALayer *ADPointerLayer(void) {+ CALayer *pointer = [CALayer layer];+ pointer.bounds = CGRectMake(0.0, 0.0, ADBoxWidth, ADBoxHeight);+ pointer.anchorPoint = CGPointMake(1.0 / ADBoxWidth, 35.0 / ADBoxHeight);+ pointer.position = CGPointMake(ADTipX, ADTipY);+ ADFreezeLayer(pointer);+ CAShapeLayer *rim = ADDartLayer();+ rim.lineWidth = 6.5;+ rim.shadowOpacity = 0.34;+ [pointer addSublayer:rim];+ [pointer addSublayer:ADDartLayer()];+ return pointer;+}++static void ADMoveCursor(const AgentDesktopCursorFrame *frame, double mainHeight) {+ [ADCursorWindow setFrameOrigin:NSMakePoint(frame->x - ADTipX, mainHeight - frame->y - ADTipY)];+}++static NSWindow *ADBubble(void) {+ NSWindow *window = ADWindow(NSMakeRect(0.0, 0.0, ADBubbleWidth, ADBubbleHeight));+ CALayer *surface = window.contentView.layer;+ surface.backgroundColor = NSColor.whiteColor.CGColor;+ surface.cornerRadius = 10.0;+ surface.borderWidth = 1.5;+ surface.borderColor = [NSColor colorWithSRGBRed:0.08 green:0.08 blue:0.09 alpha:1.0].CGColor;+ ADBubbleText = [NSTextField labelWithString:@""];+ ADBubbleText.frame = NSMakeRect(13.0, 7.0, 206.0, 23.0);+ ADBubbleText.textColor = [NSColor colorWithSRGBRed:0.16 green:0.12 blue:0.06 alpha:1.0];+ ADBubbleText.font = [NSFont systemFontOfSize:12.5];+ [window.contentView addSubview:ADBubbleText];+ return window;}void agent_desktop_cursor_overlay_idle(void) {@@ -130,16 +113,36 @@ void agent_desktop_cursor_overlay_idle(void) {void agent_desktop_cursor_overlay_stop(void) {[ADCursorWindow orderOut:nil];[ADBubbleWindow orderOut:nil];+ [ADRipple orderOut:nil];+ ADHighlightStop();ADCursorWindow = nil;- ADArrowLayer = nil;- ADHandPointerLayer = nil;+ ADPointer = nil;+ ADRipple = nil;ADBubbleWindow = nil;ADBubbleText = nil;}+void agent_desktop_cursor_overlay_rest(void) {+ @autoreleasepool {+ NSApplication *app = NSApplication.sharedApplication;+ for (double step = 1.0; step > 0.0; step -= 0.08) {+ ADCursorWindow.alphaValue = step;+ ADBubbleWindow.alphaValue = step;+ ADPump(app);+ [NSThread sleepForTimeInterval:0.012];+ }+ [ADCursorWindow orderOut:nil];+ [ADBubbleWindow orderOut:nil];+ ADCursorWindow.alphaValue = 1.0;+ ADBubbleWindow.alphaValue = 1.0;+ }+}+void agent_desktop_cursor_overlay_hide(void) {[ADCursorWindow orderOut:nil];[ADBubbleWindow orderOut:nil];+ [ADRipple orderOut:nil];+ ADHighlightStop();}void agent_desktop_cursor_overlay_show(void) {@@ -149,128 +152,19 @@ void agent_desktop_cursor_overlay_show(void) {}}-static void ADMoveCursor(NSWindow *window, double x, double y, double mainHeight) {- [window setFrameOrigin:NSMakePoint(x - 4.0, mainHeight - y - 35.0)];-}--static void ADSetBreathing(CALayer *layer, bool enabled) {- if (!enabled) {- [layer removeAnimationForKey:@"agent-breath"];- layer.transform = CATransform3DIdentity;- return;- }- if ([layer animationForKey:@"agent-breath"] != nil) {- return;- }- CABasicAnimation *breath = [CABasicAnimation animationWithKeyPath:@"transform.scale"];- breath.fromValue = @0.99;- breath.toValue = @1.01;- breath.duration = 1.3;- breath.autoreverses = YES;- breath.repeatCount = HUGE_VALF;- breath.timingFunction =- [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];- [layer addAnimation:breath forKey:@"agent-breath"];-}--static void ADPointerTransition(NSApplication *app,- CALayer *arrow,- CALayer *hand,- bool toHand,- double frameSeconds) {- arrow.hidden = NO;- hand.hidden = NO;- double elapsed = 0.0;- while (elapsed < 0.13) {- double t = MIN(1.0, elapsed / 0.13);- double eased = t * t * t * (10.0 + t * (-15.0 + 6.0 * t));- double handOpacity = toHand ? eased : 1.0 - eased;- hand.opacity = (float)handOpacity;- arrow.opacity = (float)(1.0 - handOpacity);- ADPump(app);- [NSThread sleepForTimeInterval:frameSeconds];- elapsed += frameSeconds;- }- hand.hidden = !toHand;- arrow.hidden = toHand;- hand.opacity = toHand ? 1.0 : 0.0;- arrow.opacity = toHand ? 0.0 : 1.0;+static void ADHighlightTarget(const AgentDesktopCursorRenderConfig *config, double mainHeight) {+ const double *target = config->target;+ ADHighlightShow(NSMakeRect(target[0] - ADHighlightPad,+ mainHeight - target[1] - target[3] - ADHighlightPad,+ target[2] + ADHighlightPad * 2.0,+ target[3] + ADHighlightPad * 2.0),+ config->highlightSeconds);}-static void ADRevealBubble(NSApplication *app,- NSWindow *bubble,- NSTextField *text,- NSRect finalFrame,- double frameSeconds) {- CALayer *surface = bubble.contentView.layer;- bubble.alphaValue = 1.0;- text.alphaValue = 0.0;- surface.transform = CATransform3DMakeScale(0.94, 0.94, 1.0);- [bubble orderFrontRegardless];- double elapsed = 0.0;- while (elapsed < 0.28) {- double t = MIN(1.0, elapsed / 0.28);- double eased = t * t * t * (10.0 + t * (-15.0 + 6.0 * t));- NSRect frame = finalFrame;- frame.origin.y -= 7.0 * (1.0 - eased);- [bubble setFrame:frame display:YES];- double scale = 0.94 + 0.06 * eased;- surface.transform = CATransform3DMakeScale(scale, scale, 1.0);- text.alphaValue = eased;- ADPump(app);- [NSThread sleepForTimeInterval:frameSeconds];- elapsed += frameSeconds;- }- [bubble setFrame:finalFrame display:YES];- surface.transform = CATransform3DIdentity;- text.alphaValue = 1.0;-}--static void ADClick(NSApplication *app,- CALayer *cursorLayer,- CALayer *handLayer,- NSWindow *ripple,- CAShapeLayer *first,- CAShapeLayer *second,- double x,- double y,- double mainHeight,- double frameSeconds) {- [ripple setFrameOrigin:NSMakePoint(x - 36.0, mainHeight - y - 36.0)];- [ripple orderFrontRegardless];- ADPointerTransition(app, cursorLayer, handLayer, true, frameSeconds);- double elapsed = 0.0;- while (elapsed < 0.44) {- double t = elapsed / 0.44;- ADUpdateRipple(first, t);- ADUpdateRipple(second, MAX(0.0, (t - 0.2) / 0.8));- ADPump(app);- [NSThread sleepForTimeInterval:frameSeconds];- elapsed += frameSeconds;- }- [ripple orderOut:nil];- ADPointerTransition(app, cursorLayer, handLayer, false, frameSeconds);-}--static void ADFadeBubble(NSApplication *app,- NSWindow *bubble,- double frameSeconds) {- double elapsed = 0.0;- while (elapsed < 0.24) {- double t = MIN(1.0, elapsed / 0.24);- double eased = t * t * (3.0 - 2.0 * t);- bubble.alphaValue = 1.0 - eased;- ADPump(app);- [NSThread sleepForTimeInterval:frameSeconds];- elapsed += frameSeconds;- }- [bubble orderOut:nil];-}--bool agent_desktop_cursor_overlay_run(const double *points,- size_t pointCount,+bool agent_desktop_cursor_overlay_run(const AgentDesktopCursorFrame *frames,+ size_t frameCount,const AgentDesktopCursorRenderConfig *config) {- if (points == NULL || pointCount == 0 || config == NULL || config->frameSeconds <= 0.0) {+ if (frames == NULL || frameCount == 0 || config == NULL || config->frameSeconds <= 0.0) {return false;}@try {@@ -278,110 +172,69 @@ bool agent_desktop_cursor_overlay_run(const double *points,NSApplication *app = NSApplication.sharedApplication;[app setActivationPolicy:NSApplicationActivationPolicyAccessory];[app finishLaunching];- CGRect main = CGDisplayBounds(CGMainDisplayID());- double mainHeight = main.size.height;- bool click = (config->flags & ADClickCue) != 0;+ double mainHeight = CGDisplayBounds(CGMainDisplayID()).size.height;bool reduceMotion = (config->flags & ADReduceMotion) != 0;+ const AgentDesktopCursorFrame *last = &frames[frameCount - 1];if (ADCursorWindow == nil) {- ADCursorWindow = ADWindow(NSMakeRect(0.0, 0.0, 40.0, 42.0));- ADArrowLayer = ADCursorLayer();- [ADCursorWindow.contentView.layer addSublayer:ADArrowLayer];- ADHandPointerLayer = ADHandLayer();- [ADCursorWindow.contentView.layer addSublayer:ADHandPointerLayer];+ ADCursorWindow = ADWindow(NSMakeRect(0.0, 0.0, ADStage, ADStage));+ ADPointer = ADPointerLayer();+ [ADCursorWindow.contentView.layer addSublayer:ADPointer];+ ADBubbleWindow = ADBubble();+ ADRipple = ADRippleWindow();}- NSWindow *cursor = ADCursorWindow;- CAShapeLayer *cursorLayer = ADArrowLayer;- CAShapeLayer *handLayer = ADHandPointerLayer;- ADSetBreathing(cursorLayer, !reduceMotion);- ADSetBreathing(handLayer, !reduceMotion);- [cursor orderFrontRegardless];+ ADTintPointer();+ [ADCursorWindow orderFrontRegardless];- NSRect bubbleFrame = NSZeroRect;bool showsBubble = config->label != NULL && config->label[0] != '\0';- if (ADBubbleWindow == nil) {- ADBubbleWindow = ADWindow(NSMakeRect(0.0, 0.0, 232.0, 38.0));- CALayer *surface = ADBubbleWindow.contentView.layer;- surface.backgroundColor = NSColor.whiteColor.CGColor;- surface.cornerRadius = 10.0;- surface.borderWidth = 1.5;- surface.borderColor =- [NSColor colorWithSRGBRed:0.08 green:0.08 blue:0.09 alpha:1.0].CGColor;- ADBubbleText = [NSTextField labelWithString:@""];- ADBubbleText.frame = NSMakeRect(13.0, 7.0, 206.0, 23.0);- ADBubbleText.textColor =- [NSColor colorWithSRGBRed:0.16 green:0.12 blue:0.06 alpha:1.0];- ADBubbleText.font = [NSFont systemFontOfSize:12.5];- [ADBubbleWindow.contentView addSubview:ADBubbleText];- }- NSString *nextLabel = showsBubble- ? [NSString stringWithUTF8String:config->label]- : @"";+ NSString *nextLabel = showsBubble ? @(config->label) : @"";bool changedLabel = ![ADBubbleText.stringValue isEqualToString:nextLabel];- if (changedLabel && ADBubbleWindow.isVisible) {- if (reduceMotion) {- [ADBubbleWindow orderOut:nil];- } else {- ADFadeBubble(app, ADBubbleWindow, config->frameSeconds);- }- }ADBubbleText.stringValue = nextLabel;- if (showsBubble) {- bubbleFrame = NSMakeRect(config->bubbleX,- mainHeight - config->bubbleY - 38.0,- 232.0,- 38.0);+ NSRect bubbleFrame = NSMakeRect(config->bubbleX,+ mainHeight - config->bubbleY - ADBubbleHeight,+ ADBubbleWidth,+ ADBubbleHeight);+ bool followsBubble = showsBubble && !changedLabel && ADBubbleWindow.isVisible;+ [ADRipple setFrameOrigin:NSMakePoint(last->x - ADRippleSize * 0.5,+ mainHeight - last->y - ADRippleSize * 0.5)];+ size_t movementFrameCount = frameCount;+ bool playsRipple = false;+ for (size_t index = 0; index < frameCount; index += 1) {+ if (frames[index].ripple > 0.0) {+ movementFrameCount = index;+ playsRipple = true;+ break;+ }}-- for (size_t index = 0; index < pointCount; index += 1) {- ADMoveCursor(cursor, points[index * 2], points[index * 2 + 1], mainHeight);- if (showsBubble && !changedLabel && ADBubbleWindow.isVisible) {- NSRect movingFrame = bubbleFrame;- movingFrame.origin.x += points[index * 2] - points[(pointCount - 1) * 2];- movingFrame.origin.y -= points[index * 2 + 1] - points[(pointCount - 1) * 2 + 1];- [ADBubbleWindow setFrame:movingFrame display:YES];+ bool highlighted = (config->flags & ADHighlightCue) == 0 || reduceMotion;++ for (size_t index = 0; index < movementFrameCount; index += 1) {+ ADMoveCursor(&frames[index], mainHeight);+ if (followsBubble) {+ [ADBubbleWindow setFrameOrigin:NSMakePoint(+ bubbleFrame.origin.x + frames[index].x - last->x,+ bubbleFrame.origin.y - frames[index].y + last->y)];}ADPump(app);- if (index + 1 < pointCount) {+ if (index + 1 < movementFrameCount) {[NSThread sleepForTimeInterval:config->frameSeconds];}}-- if (showsBubble && changedLabel && !reduceMotion) {- ADRevealBubble(app,- ADBubbleWindow,- ADBubbleText,- bubbleFrame,- config->frameSeconds);- } else if (showsBubble) {- [ADBubbleWindow setFrame:bubbleFrame display:YES];- ADBubbleWindow.alphaValue = 1.0;- ADBubbleText.alphaValue = 1.0;- [ADBubbleWindow orderFrontRegardless];+ if (playsRipple) {+ ADRipplePlay(ADRipple);+ if (!highlighted) {+ ADHighlightTarget(config, mainHeight);+ highlighted = true;+ }}- if (click && !reduceMotion) {- NSWindow *ripple = ADWindow(NSMakeRect(0.0, 0.0, 72.0, 72.0));- CAShapeLayer *first = ADRippleLayer();- CAShapeLayer *second = ADRippleLayer();- [ripple.contentView.layer addSublayer:first];- [ripple.contentView.layer addSublayer:second];- ADClick(app,- cursorLayer,- handLayer,- ripple,- first,- second,- points[(pointCount - 1) * 2],- points[(pointCount - 1) * 2 + 1],- mainHeight,- config->frameSeconds);- } else if (click) {- cursorLayer.hidden = YES;- handLayer.hidden = NO;- ADPump(app);- [NSThread sleepForTimeInterval:0.12];- handLayer.hidden = YES;- cursorLayer.hidden = NO;+ if (!highlighted) {+ ADHighlightTarget(config, mainHeight);+ }++ if (showsBubble) {+ ADShowBubble(ADBubbleText, bubbleFrame, changedLabel && !reduceMotion);+ } else {+ [ADBubbleWindow orderOut:nil];}return true;}diff --git a/crates/macos/src/system/cursor_overlay_chrome.h b/crates/macos/src/system/cursor_overlay_chrome.hnew file mode 100644index 000000000..27205c9a8--- /dev/null+++ b/crates/macos/src/system/cursor_overlay_chrome.h@@ -0,0 +1,23 @@+#import <AppKit/AppKit.h>+#import <QuartzCore/QuartzCore.h>++extern const CGFloat ADRippleSize;++typedef struct {+ double fill[3];+ double rim[3];+ double accent[3];+ double size;+} AgentDesktopCursorStyle;++CGColorRef ADColor(const double *rgb, CGFloat alpha);+const AgentDesktopCursorStyle *ADStyle(void);++NSWindow *ADWindow(NSRect frame);+void ADPump(NSApplication *app);+void ADFreezeLayer(CALayer *layer);+NSWindow *ADRippleWindow(void);+void ADRipplePlay(NSWindow *window);+void ADHighlightShow(NSRect frame, double seconds);+void ADHighlightStop(void);+void ADShowBubble(NSTextField *text, NSRect frame, bool changed);diff --git a/crates/macos/src/system/cursor_overlay_chrome_bridge.m b/crates/macos/src/system/cursor_overlay_chrome_bridge.mnew file mode 100644index 000000000..7f4d789df--- /dev/null+++ b/crates/macos/src/system/cursor_overlay_chrome_bridge.m@@ -0,0 +1,207 @@+#import "cursor_overlay_chrome.h"++const CGFloat ADRippleSize = 108.0;+static const NSWindowLevel ADEffectLevel = 24;+static const NSUInteger ADRippleRings = 2;++static AgentDesktopCursorStyle ADCurrentStyle = {+ .fill = {1.0, 1.0, 1.0},+ .rim = {0.07, 0.07, 0.09},+ .accent = {0.26, 0.60, 1.0},+ .size = 1.0,+};++static __strong NSWindow *ADHighlightWindow = nil;+static __strong CALayer *ADHighlightBorder = nil;++CGColorRef ADColor(const double *rgb, CGFloat alpha) {+ return [NSColor colorWithSRGBRed:rgb[0] green:rgb[1] blue:rgb[2] alpha:alpha].CGColor;+}++const AgentDesktopCursorStyle *ADStyle(void) {+ return &ADCurrentStyle;+}++void agent_desktop_cursor_overlay_style(const AgentDesktopCursorStyle *style) {+ if (style != NULL) {+ ADCurrentStyle = *style;+ }+}++void ADFreezeLayer(CALayer *layer) {+ layer.actions = @{+ @"transform" : NSNull.null,+ @"opacity" : NSNull.null,+ @"position" : NSNull.null,+ @"bounds" : NSNull.null,+ @"hidden" : NSNull.null,+ };+}++NSWindow *ADWindow(NSRect frame) {+ NSWindow *window = [[NSWindow alloc]+ initWithContentRect:frame+ styleMask:NSWindowStyleMaskBorderless+ backing:NSBackingStoreBuffered+ defer:NO];+ window.opaque = NO;+ window.backgroundColor = NSColor.clearColor;+ window.hasShadow = NO;+ window.ignoresMouseEvents = YES;+ window.releasedWhenClosed = NO;+ window.hidesOnDeactivate = NO;+ window.level = 25;+ window.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |+ NSWindowCollectionBehaviorFullScreenAuxiliary;+ NSView *view = [[NSView alloc]+ initWithFrame:NSMakeRect(0.0, 0.0, frame.size.width, frame.size.height)];+ view.wantsLayer = YES;+ window.contentView = view;+ ADFreezeLayer(view.layer);+ return window;+}++void ADPump(NSApplication *app) {+ [app updateWindows];+ [[NSRunLoop currentRunLoop]+ runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.0005]];+}++static CAShapeLayer *ADRing(CGFloat radius, BOOL filled) {+ CAShapeLayer *layer = [CAShapeLayer layer];+ layer.bounds = CGRectMake(0.0, 0.0, ADRippleSize, ADRippleSize);+ layer.position = CGPointMake(ADRippleSize * 0.5, ADRippleSize * 0.5);+ CGPathRef path = CGPathCreateWithEllipseInRect(+ CGRectMake(ADRippleSize * 0.5 - radius,+ ADRippleSize * 0.5 - radius,+ radius * 2.0,+ radius * 2.0),+ NULL);+ layer.path = path;+ CGPathRelease(path);+ layer.fillColor = NSColor.clearColor.CGColor;+ layer.strokeColor = NSColor.clearColor.CGColor;+ layer.opacity = 0.0;+ layer.shouldRasterize = NO;+ if (filled) {+ layer.shadowOffset = CGSizeZero;+ layer.shadowRadius = 14.0;+ }+ ADFreezeLayer(layer);+ return layer;+}++NSWindow *ADRippleWindow(void) {+ NSWindow *window = ADWindow(NSMakeRect(0.0, 0.0, ADRippleSize, ADRippleSize));+ window.level = ADEffectLevel;+ [window.contentView.layer addSublayer:ADRing(19.0, YES)];+ for (NSUInteger index = 0; index < ADRippleRings; index += 1) {+ [window.contentView.layer addSublayer:ADRing(ADRippleSize * 0.5 - 4.0, NO)];+ }+ return window;+}++void ADRipplePlay(NSWindow *window) {+ NSArray<CALayer *> *layers = window.contentView.layer.sublayers;+ [window orderFrontRegardless];+ for (NSUInteger index = 0; index < layers.count; index += 1) {+ CAShapeLayer *layer = (CAShapeLayer *)layers[index];+ [layer removeAllAnimations];+ layer.fillColor = index == 0 ? ADColor(ADCurrentStyle.accent, 1.0)+ : NSColor.clearColor.CGColor;+ layer.strokeColor = ADColor(ADCurrentStyle.accent, 1.0);+ CAKeyframeAnimation *opacity =+ [CAKeyframeAnimation animationWithKeyPath:@"opacity"];+ opacity.values = index == 0 ? @[ @0.0, @0.42, @0.0 ] : @[ @0.0, @0.9, @0.0 ];+ opacity.keyTimes = @[ @0.0, @0.18, @1.0 ];+ CABasicAnimation *spread =+ [CABasicAnimation animationWithKeyPath:@"transform.scale"];+ spread.fromValue = index == 0 ? @0.22 : @0.04;+ spread.toValue = index == 0 ? @1.12 : @1.0;+ CAAnimationGroup *effect = [CAAnimationGroup animation];+ effect.animations = @[ opacity, spread ];+ effect.duration = 0.3;+ effect.timingFunction =+ [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];+ [layer addAnimation:effect forKey:@"agent-ripple"];+ }+}++static CAKeyframeAnimation *ADHold(NSString *path,+ NSArray *values,+ NSArray *times,+ double seconds) {+ CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:path];+ animation.values = values;+ animation.keyTimes = times;+ animation.duration = seconds;+ animation.removedOnCompletion = NO;+ animation.fillMode = kCAFillModeForwards;+ animation.timingFunction =+ [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];+ return animation;+}++void ADHighlightShow(NSRect frame, double seconds) {+ if (ADHighlightWindow == nil) {+ ADHighlightWindow = ADWindow(frame);+ ADHighlightWindow.level = ADEffectLevel;+ ADHighlightBorder = [CALayer layer];+ ADHighlightBorder.borderWidth = 2.5;+ ADHighlightBorder.cornerRadius = 8.0;+ ADHighlightBorder.opacity = 0.0;+ ADFreezeLayer(ADHighlightBorder);+ [ADHighlightWindow.contentView.layer addSublayer:ADHighlightBorder];+ }+ ADHighlightBorder.borderColor = ADColor(ADCurrentStyle.accent, 1.0);+ ADHighlightBorder.backgroundColor = ADColor(ADCurrentStyle.accent, 0.10);+ ADHighlightBorder.shadowColor = ADColor(ADCurrentStyle.accent, 1.0);+ ADHighlightBorder.shadowOpacity = 0.5;+ ADHighlightBorder.shadowRadius = 10.0;+ ADHighlightBorder.shadowOffset = CGSizeZero;+ [ADHighlightWindow setFrame:frame display:NO];+ ADHighlightBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, frame.size.height);+ [ADHighlightBorder removeAllAnimations];+ [ADHighlightBorder addAnimation:ADHold(@"opacity",+ @[ @0.0, @1.0, @1.0, @0.0 ],+ @[ @0.0, @0.04, @0.55, @1.0 ],+ seconds)+ forKey:@"agent-highlight-fade"];+ [ADHighlightBorder addAnimation:ADHold(@"transform.scale",+ @[ @1.08, @0.99, @1.0, @1.0 ],+ @[ @0.0, @0.12, @0.22, @1.0 ],+ seconds)+ forKey:@"agent-highlight-pop"];+ [ADHighlightWindow orderFrontRegardless];+}++void ADHighlightStop(void) {+ [ADHighlightBorder removeAllAnimations];+ [ADHighlightWindow orderOut:nil];+ ADHighlightWindow = nil;+ ADHighlightBorder = nil;+}++void ADShowBubble(NSTextField *text, NSRect frame, bool changed) {+ NSWindow *bubble = text.window;+ CALayer *surface = bubble.contentView.layer;+ bubble.alphaValue = 1.0;+ text.alphaValue = 1.0;+ [bubble setFrame:frame display:NO];+ if (changed) {+ [surface removeAllAnimations];+ CABasicAnimation *fade = [CABasicAnimation animationWithKeyPath:@"opacity"];+ fade.fromValue = @0.0;+ fade.toValue = @1.0;+ fade.duration = 0.18;+ CABasicAnimation *pop = [CABasicAnimation animationWithKeyPath:@"transform.scale"];+ pop.fromValue = @0.94;+ pop.toValue = @1.0;+ pop.duration = 0.18;+ pop.timingFunction =+ [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];+ [surface addAnimation:fade forKey:@"agent-bubble-fade"];+ [surface addAnimation:pop forKey:@"agent-bubble-pop"];+ }+ [bubble orderFrontRegardless];+}diff --git a/crates/macos/src/system/window_ax_state.rs b/crates/macos/src/system/window_ax_state.rsindex 652b191ac..21902c715 100644--- a/crates/macos/src/system/window_ax_state.rs+++ b/crates/macos/src/system/window_ax_state.rs@@ -1,5 +1,5 @@-use agent_desktop_core::{AdapterError, ErrorCode};-use rustc_hash::FxHashMap;+use agent_desktop_core::{AdapterError, ErrorCode, WindowInfo};+use rustc_hash::{FxHashMap, FxHashSet};use std::time::Instant;type AxWindowIdentity = (Option<String>, Option<i64>);@@ -8,36 +8,27 @@ type AxWindowIdentity = (Option<String>, Option<i64>);pub(crate) struct WindowAxState {pub(crate) focused: Option<AxWindowIdentity>,pub(crate) minimized_by_id: FxHashMap<i64, bool>,+ pub(crate) accessible_window_ids: FxHashSet<i64>,}pub(crate) fn read_until(pid: i32, deadline: Instant) -> Result<WindowAxState, AdapterError> {let app = crate::tree::element_for_pid(pid);let focused = focused_identity(&app, pid, deadline)?;let mut minimized_by_id = FxHashMap::default();- for window in crate::tree::surface_read::elements(&app, "AXWindows", deadline)? {- if crate::tree::surface_read::string(&window, "AXRole", deadline)?.as_deref()- != Some("AXWindow")- {- continue;- }- let window_id =- match crate::system::window_resolve::ax_window_id_with_deadline(&window, deadline) {- Ok(window_id) => window_id,- Err(error) if crate::system::window_bridge::is_unavailable(&error) => break,- Err(error) => return Err(error),- };- let Some(window_id) = window_id else {- continue;- };+ let mut accessible_window_ids = FxHashSet::default();+ for_each_window(pid, deadline, |window, window_id| {+ accessible_window_ids.insert(window_id);if let Some(minimized) =- crate::tree::surface_read::boolean(&window, "AXMinimized", deadline)?+ crate::tree::surface_read::boolean(window, "AXMinimized", deadline)?{minimized_by_id.insert(window_id, minimized);}- }+ Ok(())+ })?;Ok(WindowAxState {focused,minimized_by_id,+ accessible_window_ids,})}@@ -49,9 +40,61 @@ pub(crate) fn read_frontmost_until(Ok(WindowAxState {focused: focused_identity(&app, pid, deadline)?,minimized_by_id: FxHashMap::default(),+ accessible_window_ids: FxHashSet::default(),})}+pub(crate) fn accessible_window_ids_until(+ pid: i32,+ deadline: Instant,+) -> Result<FxHashSet<i64>, AdapterError> {+ let mut ids = FxHashSet::default();+ for_each_window(pid, deadline, |_, id| {+ ids.insert(id);+ Ok(())+ })?;+ Ok(ids)+}++fn for_each_window(+ pid: i32,+ deadline: Instant,+ mut visit: impl FnMut(&crate::tree::AXElement, i64) -> Result<(), AdapterError>,+) -> Result<(), AdapterError> {+ let app = crate::tree::element_for_pid(pid);+ for window in crate::tree::surface_read::elements(&app, "AXWindows", deadline)? {+ match crate::system::window_resolve::ax_window_id_with_deadline(&window, deadline) {+ Ok(Some(id)) => visit(&window, id)?,+ Ok(None) => {}+ Err(error) if crate::system::window_bridge::is_unavailable(&error) => break,+ Err(error) => return Err(error),+ }+ }+ Ok(())+}++pub(crate) fn label_accessibility(+ windows: &mut [WindowInfo],+ mut read: impl FnMut(i32) -> Result<FxHashSet<i64>, AdapterError>,+) {+ let mut pids = windows.iter().map(|window| window.pid).collect::<Vec<_>>();+ pids.sort_unstable();+ pids.dedup();+ for pid in pids {+ let Some(accessible_ids) = crate::system::process_identity::to_pid_t(pid)+ .ok()+ .and_then(|pid| read(pid).ok())+ else {+ continue;+ };+ for window in windows.iter_mut().filter(|window| window.pid == pid) {+ window.state.accessible =+ crate::system::window_resolve::parse_window_number(&window.id)+ .is_some_and(|id| accessible_ids.contains(&id));+ }+ }+}+/// Frontmost-ness only selects whether a focused window is reported, and a busy/// application answering "unknown" is not a reason to fail the command that/// asked. Permission and API failures still propagate, because those describe@@ -113,7 +156,9 @@ fn is_transient_surface_role(role: &str) -> bool {#[cfg(test)]mod tests {- use super::is_transient_surface_role;+ use super::{is_transient_surface_role, label_accessibility};+ use agent_desktop_core::{ProcessId, WindowInfo, WindowState};+ use rustc_hash::FxHashSet;#[test]fn modal_surfaces_can_temporarily_own_focused_window() {@@ -122,4 +167,32 @@ mod tests {}assert!(!is_transient_surface_role("AXButton"));}++ #[test]+ fn failed_pid_probe_keeps_unknown_window_selectable() {+ let mut windows = vec![window(10, "w-1"), window(20, "w-2")];++ label_accessibility(&mut windows, |pid| {+ if pid == 10 {+ Ok(FxHashSet::default())+ } else {+ Err(agent_desktop_core::AdapterError::timeout("busy"))+ }+ });++ assert!(!windows[0].state.accessible);+ assert!(windows[1].state.accessible);+ }++ fn window(pid: u32, id: &str) -> WindowInfo {+ WindowInfo {+ id: id.into(),+ title: "Main".into(),+ app: "Fixture".into(),+ pid: ProcessId::new(pid),+ process_instance: Some(format!("{pid}:100")),+ bounds: None,+ state: WindowState::default(),+ }+ }}diff --git a/crates/macos/src/system/window_inventory.rs b/crates/macos/src/system/window_inventory.rsindex ff595dc23..611f78979 100644--- a/crates/macos/src/system/window_inventory.rs+++ b/crates/macos/src/system/window_inventory.rs@@ -98,6 +98,7 @@ fn focus_state(Ok(crate::system::window_ax_state::WindowAxState {focused: None,minimized_by_id: rustc_hash::FxHashMap::default(),+ accessible_window_ids: rustc_hash::FxHashSet::default(),})}Err(error) => Err(error),@@ -223,7 +224,8 @@ fn windows_from_records_with_focus(}focused_seen |= is_focused;let minimized = state.minimized_by_id.get(&record.window_number).copied();- windows.push(record.into_window_info(is_focused, minimized)?);+ let accessible = state.accessible_window_ids.contains(&record.window_number);+ windows.push(record.into_window_info(is_focused, minimized, accessible)?);}Ok(windows)diff --git a/crates/macos/src/system/window_inventory_global.rs b/crates/macos/src/system/window_inventory_global.rsindex dc0be9cea..642e0c764 100644--- a/crates/macos/src/system/window_inventory_global.rs+++ b/crates/macos/src/system/window_inventory_global.rs@@ -49,7 +49,7 @@ fn capture_global_once(focused_only: bool,deadline: Instant,) -> Result<Vec<WindowInfo>, AdapterError> {- capture_global_with(+ let mut windows = capture_global_with(focused_only,|| crate::system::workspace_apps::window_owner_snapshot_until(deadline),|eligible_pids| {@@ -59,7 +59,14 @@ fn capture_global_once()},|pid| crate::system::window_ax_state::read_frontmost_until(pid, deadline),- )+ )?;+ crate::system::window_ax_state::label_accessibility(&mut windows, |pid| {+ let probe_deadline = Instant::now()+ .checked_add(std::time::Duration::from_millis(50))+ .map_or(deadline, |probe| probe.min(deadline));+ crate::system::window_ax_state::accessible_window_ids_until(pid, probe_deadline)+ });+ Ok(windows)}fn capture_global_with<S: OwnerSnapshotView>(@@ -151,7 +158,7 @@ pub(super) fn assemble_global_windows<S: OwnerSnapshotView>(} else {None};- Some(record.into_window_info(is_focused, minimized))+ Some(record.into_window_info(is_focused, minimized, true))}).collect::<Result<Vec<_>, _>>()}diff --git a/crates/macos/src/system/window_inventory_global_tests.rs b/crates/macos/src/system/window_inventory_global_tests.rsindex 9a8530c18..6706ababe 100644--- a/crates/macos/src/system/window_inventory_global_tests.rs+++ b/crates/macos/src/system/window_inventory_global_tests.rs@@ -391,5 +391,6 @@ fn ax_state(focused: Option<(Option<String>, Option<i64>)>) -> WindowAxState {WindowAxState {focused,minimized_by_id: FxHashMap::default(),+ accessible_window_ids: FxHashSet::default(),}}diff --git a/crates/macos/src/system/window_inventory_tests.rs b/crates/macos/src/system/window_inventory_tests.rsindex b8213b887..56c0b009e 100644--- a/crates/macos/src/system/window_inventory_tests.rs+++ b/crates/macos/src/system/window_inventory_tests.rs@@ -34,6 +34,7 @@ fn ax_state(focused: FocusedWindowIdentity) -> crate::system::window_ax_state::Wcrate::system::window_ax_state::WindowAxState {focused,minimized_by_id: FxHashMap::default(),+ accessible_window_ids: rustc_hash::FxHashSet::default(),}}@@ -126,6 +127,20 @@ fn windows_from_records_preserve_capture_bounds() {assert_eq!(windows[0].bounds, Some(expected));}+#[test]+fn cg_window_without_an_ax_element_is_labelled_inaccessible() {+ let windows = windows_from_records_with_focus(+ vec![record("Clock", 10, "Untitled", 7)],+ false,+ |_| Ok(ax_state(None)),+ |_, _| Ok(true),+ )+ .unwrap();++ let value = serde_json::to_value(&windows[0]).unwrap();+ assert_eq!(value["accessible"], false);+}+#[test]fn visible_windows_survive_ax_inventory_failure() {let visible = record("Preview", 10, "Document", 7);@@ -317,6 +332,7 @@ fn window_with_state(id: &str, visible: Option<bool>, minimized: Option<bool>) -bounds: None,state: agent_desktop_core::WindowState {is_focused: false,+ accessible: true,minimized,visible,},diff --git a/crates/macos/src/system/window_resolve.rs b/crates/macos/src/system/window_resolve.rsindex f2e9e8a98..90c608c96 100644--- a/crates/macos/src/system/window_resolve.rs+++ b/crates/macos/src/system/window_resolve.rs@@ -182,6 +182,7 @@ fn window_info_from_record(bounds: Some(record.bounds),state: agent_desktop_core::WindowState {is_focused: win.state.is_focused,+ accessible: win.state.accessible,minimized: win.state.minimized,visible: Some(record.visible),},diff --git a/crates/macos/src/tree/node_attribute_decode.rs b/crates/macos/src/tree/node_attribute_decode.rsindex fd97768ab..e07d922e2 100644--- a/crates/macos/src/tree/node_attribute_decode.rs+++ b/crates/macos/src/tree/node_attribute_decode.rs@@ -48,9 +48,7 @@ mod imp {}let value = match index {3 => scalar_text(item),- 4..=12 => item- .downcast::<CFBoolean>()- .map(|value| bool::from(value).to_string()),+ 4..=12 => boolean_text(item),_ => None,}?;Some(crate::tree::bounded_string::BoundedString::from_owned(@@ -66,6 +64,15 @@ mod imp {number_text(&number)}+ fn boolean_text(item: &CFType) -> Option<String> {+ if let Some(value) = item.downcast::<CFBoolean>() {+ return Some(bool::from(value).to_string());+ }+ item.downcast::<CFNumber>()?+ .to_i64()+ .map(|value| (value != 0).to_string())+ }+pub(crate) fn number_text(number: &CFNumber) -> Option<String> {let number_ref = number.as_concrete_TypeRef();if unsafe { CFNumberIsFloatType(number_ref) } == 0 {@@ -79,6 +86,10 @@ mod imp {}}+ pub(crate) fn is_number(item: &CFType) -> bool {+ item.downcast::<CFNumber>().is_some()+ }+pub(crate) fn point(item: &CFType) -> Option<CGPoint> {let mut point = CGPoint::new(0.0, 0.0);unsafe {@@ -105,7 +116,7 @@ mod imp {}#[cfg(target_os = "macos")]-pub(crate) use imp::{is_null, number_text, point, size, slot_error, text};+pub(crate) use imp::{is_null, is_number, number_text, point, size, slot_error, text};#[cfg(all(test, target_os = "macos"))]mod tests {@@ -120,12 +131,12 @@ mod tests {unsafe { CFType::wrap_under_get_rule(number.as_CFTypeRef()) }}- fn decode_number(number: &CFNumber) -> String {+ fn decode_number_at(index: usize, number: &CFNumber) -> String {let item = number_item(number);let mut usage = crate::tree::observation_usage::ObservationUsage::new(agent_desktop_core::ObservationBudget::default(),);- text(3, &item, &mut usage)+ text(index, &item, &mut usage).expect("CFNumber must decode").value}@@ -154,8 +165,8 @@ mod tests {#[test]fn fractional_numbers_keep_shortest_round_trip_text() {- let first = decode_number(&CFNumber::from(1.001_f64));- let second = decode_number(&CFNumber::from(1.002_f64));+ let first = decode_number_at(3, &CFNumber::from(1.001_f64));+ let second = decode_number_at(3, &CFNumber::from(1.002_f64));assert_eq!(first, "1.001");assert_eq!(second, "1.002");@@ -165,8 +176,26 @@ mod tests {#[test]fn large_integers_remain_exact() {assert_eq!(- decode_number(&CFNumber::from(i64::MAX)),+ decode_number_at(3, &CFNumber::from(i64::MAX)),i64::MAX.to_string());}++ #[test]+ fn catalyst_numeric_booleans_decode_as_state_values() {+ assert_eq!(decode_number_at(4, &CFNumber::from(0_i32)), "false");+ assert_eq!(decode_number_at(4, &CFNumber::from(1_i32)), "true");+ }++ #[test]+ fn numeric_label_values_are_not_mistaken_for_text() {+ let number = CFNumber::from(0_f32);+ let item = number_item(&number);+ let mut usage = crate::tree::observation_usage::ObservationUsage::new(+ agent_desktop_core::ObservationBudget::default(),+ );++ assert!(is_number(&item));+ assert!(text(15, &item, &mut usage).is_none());+ }}diff --git a/crates/macos/src/tree/node_attribute_fetch.rs b/crates/macos/src/tree/node_attribute_fetch.rsindex ae4053a6a..e4999e93a 100644--- a/crates/macos/src/tree/node_attribute_fetch.rs+++ b/crates/macos/src/tree/node_attribute_fetch.rs@@ -86,6 +86,7 @@ mod imp {0..=16 => match node_attribute_decode::text(index, &item, usage) {Some(value) if value.complete => texts[index] = Some(value.value),Some(_) => status.record_truncated(index),+ None if index == LABEL && node_attribute_decode::is_number(&item) => {}None => status.record_slot_error(index, kAXErrorFailure),},17 => {diff --git a/crates/macos/src/tree/query/child_read.rs b/crates/macos/src/tree/query/child_read.rsindex 37f4757d9..bb6cde235 100644--- a/crates/macos/src/tree/query/child_read.rs+++ b/crates/macos/src/tree/query/child_read.rs@@ -74,8 +74,9 @@ mod imp {max_elements: usize,deadline: std::time::Instant,) -> ChildRead {- super::super::child_source::read_first_nonempty(+ super::super::child_source::read_resilient(crate::tree::element::child_attributes(role),+ deadline,|attribute| read_attribute_children(element, attribute, max_elements, deadline),)}@@ -86,8 +87,9 @@ mod imp {index: usize,deadline: std::time::Instant,) -> ChildRead {- super::super::child_source::read_first_nonempty(+ super::super::child_source::read_resilient(crate::tree::element::child_attributes(role),+ deadline,|attribute| read_attribute_child_at(element, attribute, index, deadline),)}diff --git a/crates/macos/src/tree/query/child_source.rs b/crates/macos/src/tree/query/child_source.rsindex 15819fed2..aea2e6319 100644--- a/crates/macos/src/tree/query/child_source.rs+++ b/crates/macos/src/tree/query/child_source.rs@@ -4,6 +4,35 @@ use super::{};const CANONICAL_CHILDREN: &str = "AXChildren";+const READ_ATTEMPTS: usize = 3;++pub(super) fn read_resilient(+ attributes: &[&str],+ deadline: std::time::Instant,+ mut read_attribute: impl FnMut(&str) -> ChildRead,+) -> ChildRead {+ let mut status = ChildReadStatus::default();+ let mut attempt = 0;+ loop {+ let mut read = read_first_nonempty(attributes, &mut read_attribute);+ attempt += 1;+ let retry = !read.complete+ && !read.status.invalid_element+ && !read.status.api_disabled+ && attempt < READ_ATTEMPTS+ && std::time::Instant::now() < deadline;+ status.merge(std::mem::take(&mut read.status));+ if !retry {+ read.status = status;+ return read;+ }+ std::thread::sleep(+ deadline+ .saturating_duration_since(std::time::Instant::now())+ .min(std::time::Duration::from_millis(1)),+ );+ }+}pub(super) fn read_first_nonempty(attributes: &[&str],@@ -124,4 +153,36 @@ mod tests {assert_eq!(selected.elements.len(), 1);assert!(!selected.complete);}++ #[test]+ fn resilient_read_recovers_after_two_incomplete_attempts() {+ let mut attempts = 0;+ let selected = read_resilient(+ &["AXChildren"],+ std::time::Instant::now() + std::time::Duration::from_secs(1),+ |_| {+ attempts += 1;+ read(1, attempts == 3, ChildSourceAvailability::Available)+ },+ );++ assert_eq!(attempts, 3);+ assert!(selected.complete);+ }++ #[test]+ fn resilient_read_stops_cleanly_after_three_incomplete_attempts() {+ let mut attempts = 0;+ let selected = read_resilient(+ &["AXChildren"],+ std::time::Instant::now() + std::time::Duration::from_secs(1),+ |_| {+ attempts += 1;+ read(0, false, ChildSourceAvailability::Unknown)+ },+ );++ assert_eq!(attempts, 3);+ assert!(!selected.complete);+ }}diff --git a/docs/phases.md b/docs/phases.mdindex edc98fd3d..0f7986ba4 100644--- a/docs/phases.md+++ b/docs/phases.md@@ -641,7 +641,7 @@ crates/ffi/├── build.rs # 5 lines: bakes install_name = @rpath/libagent_desktop_ffi.dylib on macOS only — no codegen step├── codegen_templates/ # empty, untracked — reserved for the P2-O16 build.rs codegen migration, not wired up today├── include/-│ └── agent_desktop.h # committed, drift-checked against the OUT_DIR output; AD_ABI_VERSION_MAJOR = 3+│ └── agent_desktop.h # committed, drift-checked against the OUT_DIR output; AD_ABI_VERSION_MAJOR = 4├── src/ # ad_* extern "C" entrypoints, organized by domain│ ├── types/ # 34 one-type-per-file modules (AdAction, AdRect, AdWindowList, ...)│ ├── convert/ # string / rect / window / app / surface / notification helpers@@ -724,7 +724,7 @@ There is no `ffi-codegen-drift` job. An earlier draft of this document described### Forward Compatibility-- Pre-1.0 the ABI is explicitly unstable; consumers pin the artifact version alongside the cdylib version. `AD_ABI_VERSION_MAJOR` is currently `3` and evolves append-only (Phase 1.6).+- Pre-1.0 the ABI is explicitly unstable; consumers pin the artifact version alongside the cdylib version. `AD_ABI_VERSION_MAJOR` is currently `4` and evolves append-only (Phase 1.6).- Any new `PlatformAdapter` method that lands in Phase 2/3 must add a matching `ad_*` FFI wrapper in the same PR that adds the adapter method.- MCP server mode (Phase 4) is a parallel transport, not an FFI consumer — it calls `PlatformAdapter` directly.@@ -732,7 +732,7 @@ There is no `ffi-codegen-drift` job. An earlier draft of this document described**Resolved:**-- `ad_abi_version()` and `ad_init(expected_major)` ship; consumers call `ad_init` after `dlopen` for a runtime compat check. `AD_ABI_VERSION_MAJOR` is currently `3`.+- `ad_abi_version()` and `ad_init(expected_major)` ship; consumers call `ad_init` after `dlopen` for a runtime compat check. `AD_ABI_VERSION_MAJOR` is currently `4`.- `ad_snapshot`, `ad_execute_by_ref`, `ad_wait`, `ad_version`, and `ad_status` are exported, joined since by `ad_execute_by_ref_timeout`, `ad_trace_export`, and `ad_trace_show`.- `ad_set_log_callback(fn(level, msg))` ships; in-process consumers can install a tracing layer for debug output.@@ -815,7 +815,7 @@ Every sub-phase below follows the same rendering shape: **Goal** (one or two sen2. **Skeleton traversal is platform-agnostic.** The novel progressive skeleton pattern (depth-3 clamp + `children_count` annotation + drill-down via `--root @ref` + scoped invalidation via `RefMap::remove_by_root_ref`) lives entirely in `crates/core/src/snapshot_ref.rs`. Windows adapter contributes ~50 LOC glue: `ControlViewWalker` (NOT `RawViewWalker` or `ContentViewWalker`) + `FindAll(TreeScope_Children, TrueCondition)` for `children_count` + fresh `UICacheRequest` per drill-down.3. **Asymmetric event threading.** The future push-based `watch` command (P2-O11) uses main-thread `AXObserver` on macOS (research-confirmed: Apple DTS says all AX is main-thread-only; AXSwift / Hammerspoon / Phoenix all do this); worker-thread MTA `IUIAutomation` event handler on Windows (Microsoft 2025 threading doc: UIA supports cross-thread event delivery). This is distinct from the already-shipped `wait --event`, which is an in-invocation `SignalBaseline` diff, not a subscription — see the naming note under 2.11 below.4. **No `inventory` / `linkme` command registry.** Research confirmed neither survives link-GC reliably across ld64, ld-prime, GNU ld, lld, MSVC for cdylib consumers. Any future registry uses `build.rs` filesystem enumeration of `crates/core/src/commands/*.rs` — deterministic, cdylib-safe, zero linker magic. The repository's "one command per file" rule becomes the codegen contract when that migration (P2-O16) lands.-5. **FFI compatibility gates: shipped.** The ABI handshake (`ad_abi_version()`, `ad_init(expected_major)`) shipped in Phase 1.6; `AD_ABI_VERSION_MAJOR` is currently `3` and evolves append-only. Any new cross-platform ABI surface Phase 2 adds must preserve that handshake, not re-invent it.+5. **FFI compatibility gates: shipped.** The ABI handshake (`ad_abi_version()`, `ad_init(expected_major)`) shipped in Phase 1.6; `AD_ABI_VERSION_MAJOR` is currently `4` and evolves append-only. Any new cross-platform ABI surface Phase 2 adds must preserve that handshake, not re-invent it.6. **`DeliverFiles` replaces `FileDrop`.** Headless-first forbids `NSDraggingSession` on macOS; the new action uses a 4-tier fallback (URL scheme → `NSWorkspace.open` with `activates: false` → pasteboard + `Cmd-V` → AppleScript). Windows primary delivery is app/shell delivery (`ShellExecuteEx`, app URI handlers, `IFileOperation` for filesystem destinations, and `CF_HDROP` clipboard paste where accepted). `IDataObject + DoDragDrop` is an explicit policy-gated fallback/spike for targets that require drag semantics; it is never the default headless path.### Windows Engineering Invariants (from the Phase 2 plan, Unit 3)@@ -2309,7 +2309,7 @@ Phase 5 spans are OpenTelemetry-compliant so `agent-desktop trace export <uuid>| Compatibility | Tested against target app matrix: Finder, TextEdit, Xcode, VS Code, Chrome, Slack (macOS); Explorer, Notepad, Settings, VS Code, Edge (Windows); Nautilus, Terminal, Firefox, VS Code (Linux). || Distribution | Single binary per platform. No runtime dependencies for the CLI. FFI cdylib tarballs signed via Sigstore (already shipping as of Phase 1.5). Formula / manifest verify Sigstore attestation before installing (P5-O10). || Documentation | README, CLI reference, MCP reference, per-platform setup guides, troubleshooting, audit-log format reference, policy-file reference, OpenTelemetry trace schema. |-| FFI stability | Header drift check green on every PR. ABI version exported via `ad_abi_version()` (major currently 3, append-only since Phase 1.6). Pre-1.0: minor version bump for any public struct field add; major version bump for any removed or changed signature. |+| FFI stability | Header drift check green on every PR. ABI version exported via `ad_abi_version()` (major currently 4, append-only since Phase 1.6). Pre-1.0: minor version bump for any public struct field add; major version bump for any removed or changed signature. |### Performance Optimizationsdiff --git a/skills/agent-desktop-ffi/SKILL.md b/skills/agent-desktop-ffi/SKILL.mdindex 25469e73c..8640d51d3 100644--- a/skills/agent-desktop-ffi/SKILL.md+++ b/skills/agent-desktop-ffi/SKILL.md@@ -129,7 +129,7 @@ plus its explicit `snapshot_id`, to `ad_execute_by_ref` to drive the pipelineactions default to `headless`. Pass `AD_POLICY_KIND_HEADED` (2) to opt in tocursor-based fallbacks.-- **Generation-safe direct APIs.** ABI-v3 legacy `AdRefEntry` and+- **Generation-safe direct APIs.** Legacy `AdRefEntry` and`AdWindowInfo` layouts remain available for binary compatibility, but they donot carry process-generation evidence and direct targeting functions failclosed. Use `AdExactRefEntry`, `AdExactWindowInfo`,diff --git a/skills/agent-desktop-ffi/references/build-and-link.md b/skills/agent-desktop-ffi/references/build-and-link.mdindex ecfa4a18f..88fcef91e 100644--- a/skills/agent-desktop-ffi/references/build-and-link.md+++ b/skills/agent-desktop-ffi/references/build-and-link.md@@ -241,7 +241,7 @@ lib = ctypes.CDLL("./target/release-ffi/libagent_desktop_ffi.dylib")# ABI handshakelib.ad_init.restype = c_int32lib.ad_init.argtypes = [ctypes.c_uint32]-AD_ABI_VERSION_MAJOR = 3 # sync with header macro+AD_ABI_VERSION_MAJOR = 4 # sync with header macrorc = lib.ad_init(AD_ABI_VERSION_MAJOR)assert rc == 0, f"ABI mismatch: rc={rc}"diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.mdindex 91be790fa..291b5759a 100644--- a/skills/agent-desktop/SKILL.md+++ b/skills/agent-desktop/SKILL.md@@ -240,12 +240,13 @@ agent-desktop wait --notification --app "App" # Wait for new notification### System```-agent-desktop session start [--name LABEL] [--screenshots] [--no-trace] # Creates a session; pass the returned ID explicitly+agent-desktop session start [--name LABEL] [--screenshots] [--no-trace] [--cursor] # Creates a session; pass the returned ID explicitlyagent-desktop session end [id] # Seal manifestagent-desktop session list # List session manifestsagent-desktop session gc [--older-than SECS] [--ended] # Reclaim ended/stale sessions-agent-desktop --session <id> cursor-overlay enable [--label TEXT] [--max-words N]-agent-desktop --session <id> cursor-overlay disable # Remove the persistent session overlay+agent-desktop --session <id> cursor-overlay enable [--label TEXT] [--max-words N] [--fill HEX] [--rim HEX] [--accent HEX] [--size N] [--no-ripple] [--no-highlight]+export AGENT_DESKTOP_SESSION=<id>+agent-desktop cursor-overlay disable # Remove the overlay and stop its rendereragent-desktop trace show [--limit N] [--event PREFIX] # Merge trace segments (default tail 500; 0 = all)agent-desktop trace export [--out path.html] [--limit N] # Self-contained HTML viewer (default tail 5000)agent-desktop status # Health, session_id, tracing, artifacts, permissionsdiff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.mdindex 79009698d..39a0aabf5 100644--- a/skills/agent-desktop/references/commands-interaction.md+++ b/skills/agent-desktop/references/commands-interaction.md@@ -87,7 +87,7 @@ When the actionability preflight blocks an action, the error envelope carries th**`receives_events` failures.** When a hit test at the target's center point lands on a different element, `receives_events` fails with `reason: "occluded by <role>"` and a structured `occluder` object on that check: `{ "role", "name", "bounds" }` (the element that actually received the hit, when it can be identified). The target's own bounds have not changed — something else is now on top of them. Recovery is to bring the target's window or element to the front (or dismiss whatever is covering it), then retry; blind-retrying without changing z-order will fail the same way again.-Every ref-resolving action accepts `--timeout-ms` (default `5000`), but it budgets different things. For the dispatch actions (`click`, `double-click`, `triple-click`, `right-click`, `clear`, `focus`, `toggle`, `check`, `uncheck`, `expand`, `collapse`, `scroll-to`, `type`, `set-value`, `select`, `scroll`) it is the actionability-wait budget: they poll roughly every 100ms until the target becomes actionable, then fail with `TIMEOUT` once the budget is exhausted — unless the block is a terminal check (`supported_action`/`policy`/`editable`), which fails fast on the first attempt with `ACTION_NOT_SUPPORTED`/`POLICY_DENIED` rather than waiting out the budget. For `hover` and `drag`, the same budget covers ref resolution, live visibility/bounds, stability, and `receives_events`. Transient misses, app-unresponsive reads, and occlusion are polled until recovery or `TIMEOUT`; terminal errors are returned immediately with their original code.+Every ref-resolving action accepts `--timeout-ms` (default `5000`), but it budgets different things. For the dispatch actions (`click`, `double-click`, `triple-click`, `right-click`, `clear`, `focus`, `toggle`, `check`, `uncheck`, `expand`, `collapse`, `scroll-to`, `type`, `set-value`, `select`, `scroll`) it is the actionability-wait budget: they poll roughly every 100ms until the target becomes actionable, then fail with `TIMEOUT` once the budget is exhausted — unless the block is a terminal check (`supported_action`/`policy`/`editable`), which fails fast on the first attempt with `ACTION_NOT_SUPPORTED`/`POLICY_DENIED` rather than waiting out the budget. For `hover` and `drag`, the same budget covers ref resolution, live visibility/bounds, stability, and `receives_events`. Transient misses, app-unresponsive reads, and occlusion are polled until recovery or `TIMEOUT`; terminal errors are returned immediately with their original code. If every poll completed traversal but one or more required native live reads failed, the command instead returns `ACTION_FAILED` with `details.kind: "live_read_incomplete"` and `retryable: false`; re-snapshot and use a fresh ref rather than treating incomplete evidence as an ordinary timeout.**Implicit scroll-into-view.** Standard ref actions whose `Action` declares a scroll precondition attempt `AXScrollToVisible` before dispatch. The pointer resolver for `hover` and `drag` independently makes one scroll attempt when a ref endpoint is not visibly bounded, then re-resolves and fails closed if it is still not visible. Use the standalone `scroll-to` command when you need an explicit, verifiable scroll result.@@ -319,7 +319,14 @@ Synthesizes a scroll-wheel event at absolute coordinates and requires `--headed`### Agent cursor presentation-When enabled once with `cursor-overlay` for the selected session, the presentation-only cursor remains alive between eligible headless ref actions and moves from its previous destination. Interaction commands do not accept per-command cursor flags. Headed actions temporarily hide the overlay and use the real OS cursor; raw pointer commands keep their existing headed-only behavior.+Enable it once per session with `session start --cursor` or `cursor-overlay enable`. Interaction commands take no cursor flags.++- The cursor stays alive between eligible headless ref actions and travels from its previous destination.+- The action waits for it to land before it dispatches, capped at 900 ms.+- A click plays a ripple and flashes an accent outline around the element.+- Headed actions hide the overlay and use the real OS cursor. Raw pointer commands keep their headed-only behavior.++See `commands-system.md` for the style flags.| Goal | Preferred | Alternative ||------|-----------|-------------|diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.mdindex f65788a69..c2214f92f 100644--- a/skills/agent-desktop/references/commands-system.md+++ b/skills/agent-desktop/references/commands-system.md@@ -145,7 +145,7 @@ Applications with no user interface at all are excluded.agent-desktop list-windowsagent-desktop list-windows --app "Finder"```-Lists all visible windows, optionally filtered by app. Returns array of `{ id, title, app_name, pid, bounds, is_focused }`. Focus is detected through the platform's frontmost/focused-window APIs, not window stacking order.+Lists all visible windows, optionally filtered by app. Returns array of `{ id, title, app_name, pid, bounds, is_focused, accessible }`. Focus is detected through the platform's frontmost/focused-window APIs, not window stacking order. `accessible` is false only when the platform confirmed that semantic accessibility commands cannot reach the window; transient probe failures and omitted legacy values preserve the default true value.The inventory comes from the window server, which knows more windows than theaccessibility layer exposes. Targeting one an application never published@@ -458,19 +458,46 @@ Sessions are on-disk containers under `<state root>/sessions/<id>/` with a `sess### cursor-overlay enable / disable```bash-agent-desktop --session <id> cursor-overlay enable --label "Opening menu" --max-words 6-agent-desktop --session <id> cursor-overlay disable+agent-desktop session start --cursor # session + default cursor in one command+agent-desktop --session <id> cursor-overlay enable --label "Opening menu" --accent "#FF3B7B"+export AGENT_DESKTOP_SESSION=<id>+agent-desktop cursor-overlay disable```-The setting is stored in the selected session manifest and inherited by all eligible headless commands, including batch entries scoped to that session. Enabling immediately presents the persistent cursor with “Hey, let's play with this computer!” The current description remains visible; when its value changes, the old card eases out and the new text eases in. Only `cursor-overlay disable` or session end removes the cursor and card. Action and batch-entry schemas do not accept cursor-enable flags. Headed actions temporarily hide the overlay while the real pointer is used. macOS renders the overlay natively; other platforms use the adapter's presentation no-op.+No flags gives the default look: white body, near-black rim, blue ripple, blue element outline.++Style is stored in the session manifest and inherited by every eligible headless command, batch entries included. Action and batch-entry schemas take no cursor flags. Run `enable` again to restyle; it applies at once.++| Flag | Meaning | Default |+|---|---|---|+| `--label TEXT` | Intent text beside the cursor | none |+| `--max-words N` | Label word limit, 1 to 12 | 6 |+| `--fill HEX` | Cursor body colour | `#FFFFFF` |+| `--rim HEX` | Cursor outline colour | `#111318` |+| `--accent HEX` | Ripple and element outline colour | `#4299FF` |+| `--size N` | Cursor size multiplier, 0.5 to 4.0 | 1.0 |+| `--no-ripple` | No ripple on click | ripple on |+| `--no-highlight` | No element outline on click | outline on |++Behaviour:++- Travel is a human path, 90 to 320 ms. The cursor never rotates or resizes.+- The action waits for the cursor to land, capped at 900 ms. A slow renderer never blocks it.+- A click plays a ripple, then flashes an accent outline around the element for 0.9 s. Both draw below the cursor.+- The card shows the label. With no label there is no card.+- Idle for 6 s it fades out; the next command restores it.+- `disable` removes it and stops the renderer. Ending the session is not needed.+- Headed actions hide it while the real pointer is in use.+- macOS renders it natively; other platforms use the adapter's presentation no-op.### session start```bashagent-desktop session startagent-desktop session start --name "nightly-run"agent-desktop session start --no-trace # Namespace only — no automatic JSONL+agent-desktop session start --cursor # Also show the default cursor overlay```-Creates the session directory, pre-creates `trace/` (when tracing is on), writes `session.json` (`trace: on` unless `--no-trace`), and prints `{ "session_id", "name", "trace", "created_at" }`. Pass that ID through global `--session` or `AGENT_DESKTOP_SESSION` on later commands.+Creates the session directory, pre-creates `trace/` (when tracing is on), writes `session.json` (`trace: on` unless `--no-trace`), and prints `{ "session_id", "name", "trace", "created_at" }`. `--cursor` adds `cursor_overlay` to that response and shows the overlay. Pass that ID through global `--session` or `AGENT_DESKTOP_SESSION` on later commands.### session end```bashdiff --git a/skills/agent-desktop/references/macos.md b/skills/agent-desktop/references/macos.mdindex 1bd04a6f3..3e087f82c 100644--- a/skills/agent-desktop/references/macos.md+++ b/skills/agent-desktop/references/macos.md@@ -245,7 +245,13 @@ After `right-click @ref`, inspect the open menu or the target effect. If macOS r### Agent cursor overlay-macOS keeps one click-through AppKit child and cursor window alive for the enabled session. Enable shows “Hey, let's play with this computer!” and eases away only the card. Later actions start from the cursor's previous destination, use the same minimum-jerk swing, briefly switch the arrow to a hand for click feedback, and ease updated intent text in and out of the solid white, 1.5px near-black card. Only disable or session end removes the cursor; headed actions temporarily hide it while the real cursor is in use. The overlay never activates, moves the OS pointer, or changes command delivery, follows Reduce Motion, and fails soft if its child cannot start.+macOS keeps one click-through AppKit child per enabled session, with separate borderless windows for the cursor, the card, the ripple, and the element outline.++- The cursor is a filled dart with a contrasting rim, drawn from the session style.+- Effect windows sit one level below the cursor window, so the cursor always stays on top.+- The child acknowledges arrival over its session socket; the action dispatches only after that.+- The element outline and the card animate on Core Animation, so neither blocks the render loop.+- Reduce Motion is honoured. The overlay never activates an app, moves the OS pointer, or changes command delivery, and it fails soft if its child cannot start.### App Identificationdiff --git a/src/batch/mod.rs b/src/batch/mod.rsindex 431a685dc..9d216c6ab 100644--- a/src/batch/mod.rs+++ b/src/batch/mod.rs@@ -206,6 +206,8 @@ struct BatchSessionStartArgs {no_trace: bool,#[serde(default)]screenshots: bool,+ #[serde(default)]+ cursor: bool,}#[derive(Deserialize)]@@ -236,6 +238,7 @@ fn parse_session(args: Value) -> Result<SessionArgs, AppError> {name: args.name,no_trace: args.no_trace,screenshots: args.screenshots,+ cursor: args.cursor,})}Some("end") => {diff --git a/src/cli/contract_tests.rs b/src/cli/contract_tests.rsindex f0efc6600..df1ca77b4 100644--- a/src/cli/contract_tests.rs+++ b/src/cli/contract_tests.rs@@ -94,6 +94,9 @@ fn cursor_overlay_enable_is_session_scoped_and_bounded() {"Opening the profile menu for this account now","--max-words","5",+ "--size",+ "2.5",+ "--no-ripple",]).expect("valid cursor overlay command");let Commands::CursorOverlay(args) = cli.command.expect("command") else {@@ -108,6 +111,9 @@ fn cursor_overlay_enable_is_session_scoped_and_bounded() {assert_eq!(cli.session.as_deref(), Some("run-1"));assert!(config.is_enabled());assert_eq!(config.label(), Some("Opening the profile menu for…"));+ assert_eq!(config.style().size(), 2.5);+ assert!(!config.style().ripple());+ assert!(config.style().highlight());}#[test]diff --git a/src/cli/help_after.txt b/src/cli/help_after.txtindex 4cb560998..1305aeb73 100644--- a/src/cli/help_after.txt+++ b/src/cli/help_after.txt@@ -82,10 +82,11 @@ SYSTEMskills Bundled skill docs for AI agents (list, get, path)session start Create a trace-enabled session; pass its returned ID explicitlysession start --screenshots Opt in to screenshot/refmap replay artifacts (requires tracing)+ session start --cursor Create the session and show the default visual cursorsession end Seal a manifest (ID from argument, --session, or environment)session list List session manifestssession gc Remove ended or provably-stale sessions- cursor-overlay enable Enable/configure the visual cursor for the selected session+ cursor-overlay enable Enable/style the visual cursor for the selected session (no flags = defaults)cursor-overlay disable Disable the visual cursor for the selected sessionENVIRONMENT@@ -144,7 +145,7 @@ EXAMPLESagent-desktop snapshot --app Finder -w "button:OK"agent-desktop click @s8f3k2p9:e5 -w ":Saved!"agent-desktop session start --name run-a # note data.session_id- agent-desktop --session <session_id> cursor-overlay enable --label "Opening menu"+ agent-desktop --session <session_id> cursor-overlay enable --label "Opening menu" --accent "#4299FF"agent-desktop --session <session_id> click @s8f3k2p9:e5agent-desktop batch '[{"command":"click","args":{"ref_id":"@e1","snapshot":"<snapshot_id>"}}]'agent-desktop --session run-b batch '[{"command":"status","session":"run-b","args":{}}]'diff --git a/src/cli_args/cursor_overlay_enable.rs b/src/cli_args/cursor_overlay_enable.rsindex fc717b4c1..ce8daa614 100644--- a/src/cli_args/cursor_overlay_enable.rs+++ b/src/cli_args/cursor_overlay_enable.rs@@ -13,16 +13,20 @@ pub(crate) struct CursorOverlayEnableArgs {help = "Limit the cursor overlay label to 1-12 words (default 6)")]pub max_words: Option<usize>,+ #[command(flatten)]+ pub style: super::cursor_overlay_style::CursorOverlayStyleArgs,}impl CursorOverlayEnableArgs {pub(crate) fn to_core(&self,) -> Result<agent_desktop_core::CursorOverlayConfig, agent_desktop_core::AppError> {- use agent_desktop_core::CursorOverlayConfig;-- CursorOverlayConfig::enabled(self.label.clone(), self.max_words.unwrap_or(6))- .map_err(Into::into)+ agent_desktop_core::CursorOverlayConfig::enabled(+ self.label.clone(),+ self.max_words.unwrap_or(6),+ )+ .and_then(|config| config.with_style(self.style.to_core()))+ .map_err(Into::into)}}diff --git a/src/cli_args/cursor_overlay_style.rs b/src/cli_args/cursor_overlay_style.rsnew file mode 100644index 000000000..9234292f5--- /dev/null+++ b/src/cli_args/cursor_overlay_style.rs@@ -0,0 +1,40 @@+use clap::Args;++#[derive(Args, Debug, Default)]+pub(crate) struct CursorOverlayStyleArgs {+ #[arg(long, help = "Cursor body colour as a hex value (default #FFFFFF)")]+ pub fill: Option<String>,+ #[arg(long, help = "Cursor outline colour as a hex value (default #111318)")]+ pub rim: Option<String>,+ #[arg(+ long,+ help = "Ripple and element highlight colour as a hex value (default #4299FF)"+ )]+ pub accent: Option<String>,+ #[arg(long, help = "Cursor size multiplier from 0.5 to 4.0 (default 1.0)")]+ pub size: Option<f64>,+ #[arg(long, help = "Do not play the ripple when the agent clicks")]+ pub no_ripple: bool,+ #[arg(long, help = "Do not outline the element when the agent clicks")]+ pub no_highlight: bool,+}++impl CursorOverlayStyleArgs {+ pub(crate) fn to_core(&self) -> agent_desktop_core::CursorOverlayStyle {+ let mut style = agent_desktop_core::CursorOverlayStyle::default();+ if let Some(fill) = self.fill.clone() {+ style.set_fill(fill);+ }+ if let Some(rim) = self.rim.clone() {+ style.set_rim(rim);+ }+ if let Some(accent) = self.accent.clone() {+ style.set_accent(accent);+ }+ if let Some(size) = self.size {+ style.set_size(size);+ }+ style.set_effects(!self.no_ripple, !self.no_highlight);+ style+ }+}diff --git a/src/cli_args/mod.rs b/src/cli_args/mod.rsindex faba9817a..279ccaf4c 100644--- a/src/cli_args/mod.rs+++ b/src/cli_args/mod.rs@@ -6,6 +6,7 @@ pub(crate) mod batch;pub(crate) mod cursor_overlay;pub(crate) mod cursor_overlay_action;pub(crate) mod cursor_overlay_enable;+pub(crate) mod cursor_overlay_style;pub(crate) mod drag;pub(crate) mod drag_target;pub(crate) mod interaction;diff --git a/src/cli_args/session.rs b/src/cli_args/session.rsindex ae9aeede0..8df005fd0 100644--- a/src/cli_args/session.rs+++ b/src/cli_args/session.rs@@ -29,6 +29,8 @@ pub(crate) struct SessionStartArgs {help = "Capture pre/post-action screenshots and refmap copies (requires tracing; sensitive)")]pub screenshots: bool,+ #[arg(long, help = "Show the visual cursor overlay with its default style")]+ pub cursor: bool,}#[derive(Args, Debug)]diff --git a/src/dispatch/cursor_overlay.rs b/src/dispatch/cursor_overlay.rsindex ce4e037c8..9ed13a882 100644--- a/src/dispatch/cursor_overlay.rs+++ b/src/dispatch/cursor_overlay.rs@@ -20,11 +20,15 @@ pub(crate) fn dispatch()})?;let (action, control) = match args.action {- CursorOverlayAction::Enable(args) => (- cursor_overlay::CursorOverlayAction::Enable(args.to_core()?),- (!context.cursor_overlay().is_enabled())- .then(|| CursorOverlayControl::enable(session_id.to_owned())),- ),+ CursorOverlayAction::Enable(args) => {+ let config = args.to_core()?;+ let control =+ CursorOverlayControl::enable(session_id.to_owned(), config.style().clone());+ (+ cursor_overlay::CursorOverlayAction::Enable(config),+ Some(control),+ )+ }CursorOverlayAction::Disable => (cursor_overlay::CursorOverlayAction::Disable,Some(CursorOverlayControl::disable(session_id.to_owned())),diff --git a/src/dispatch/session.rs b/src/dispatch/session.rsindex 6719e6a1c..49ab89be0 100644--- a/src/dispatch/session.rs+++ b/src/dispatch/session.rs@@ -1,5 +1,7 @@use agent_desktop_core::{- AppError, CursorOverlayControl, PlatformAdapter, commands::session, context::CommandContext,+ AppError, CursorOverlayConfig, CursorOverlayControl, PlatformAdapter,+ commands::{cursor_overlay, session},+ context::CommandContext,};use serde_json::Value;@@ -11,11 +13,18 @@ pub(crate) fn dispatch(context: &CommandContext,) -> Result<Value, AppError> {match args.action {- SessionAction::Start(s) => session::execute(session::SessionAction::Start {- name: s.name,- no_trace: s.no_trace,- screenshots: s.screenshots,- }),+ SessionAction::Start(s) => {+ let show_cursor = s.cursor;+ let mut value = session::execute(session::SessionAction::Start {+ name: s.name,+ no_trace: s.no_trace,+ screenshots: s.screenshots,+ })?;+ if show_cursor {+ show_default_cursor(adapter, &mut value)?;+ }+ Ok(value)+ }SessionAction::End(e) => {let id = resolve_end_session_id(e.id, context.session_id())?;let value = session::execute(session::SessionAction::End { id: id.clone() })?;@@ -30,6 +39,29 @@ pub(crate) fn dispatch(}}+fn show_default_cursor(adapter: &dyn PlatformAdapter, value: &mut Value) -> Result<(), AppError> {+ let Some(id) = value+ .get("session_id")+ .and_then(Value::as_str)+ .map(str::to_owned)+ else {+ return Ok(());+ };+ let config = CursorOverlayConfig::enabled(None, 6)?;+ let control = CursorOverlayControl::enable(id.clone(), config.style().clone());+ let enabled =+ cursor_overlay::execute(&id, cursor_overlay::CursorOverlayAction::Enable(config))?;+ if let Some(overlay) = enabled.get("cursor_overlay").cloned()+ && let Some(map) = value.as_object_mut()+ {+ map.insert("cursor_overlay".into(), overlay);+ }+ if let Err(error) = adapter.update_cursor_overlay(&control) {+ tracing::warn!(code = %error.code.as_str(), "cursor overlay lifecycle update was skipped");+ }+ Ok(())+}+fn resolve_end_session_id(explicit: Option<String>,active: Option<&str>,diff --git a/tests/e2e/safe-semantic.sh b/tests/e2e/safe-semantic.shindex 4ba855716..6b8630704 100755--- a/tests/e2e/safe-semantic.sh+++ b/tests/e2e/safe-semantic.sh@@ -67,16 +67,24 @@ agent_exec() {}capture_frontmost() {- local output+ local output guard_args=(frontmost)+ if [ "$#" -eq 1 ]; then+ guard_args=(non-fixture-frontmost "$1")+ fioutput="$(agent_exec 0 list-windows 2>/dev/null)" || return 1- printf '%s' "$output" | python3 "$safety_guard" frontmost 2>/dev/null+ printf '%s' "$output" | python3 "$safety_guard" "${guard_args[@]}" 2>/dev/null+}++wait_frontmost() {+ for _ in 1 2 3; do+ capture_frontmost "$@" >/dev/null && return 0+ sleep 0.1+ done+ return 1}fixture_is_not_frontmost() {- local output- output="$(agent_exec 0 list-windows 2>/dev/null)" || return 1- printf '%s' "$output" | python3 "$safety_guard" non-fixture-frontmost "$fixture_pid" \- >/dev/null 2>&1+ wait_frontmost "$fixture_pid"}capture_fixture_identity() {@@ -305,7 +313,7 @@ chmod 500 "$fixture_executable" || blocked "fixture executable cannot be frozen"[ -z "$(pgrep -x "$app" 2>/dev/null || true)" ] || \blocked "an unowned fixture process is already running"-capture_frontmost >/dev/null || blocked "frontmost identity is missing or ambiguous"+wait_frontmost || blocked "frontmost identity is missing or ambiguous"AGENT_DESKTOP_FIXTURE_NO_ACTIVATE=1 "$fixture_executable" \>"$suite_root/fixture.stdout" 2>"$suite_root/fixture.stderr" &@@ -381,7 +389,7 @@ pass "check, uncheck, idempotence, and toggle are semantic"safety_checkpoint || fail "final mutation checkpoint failed"close_owned_fixture || fail "could not close the exact spawned fixture PID"-capture_frontmost >/dev/null || fail "final frontmost identity is missing or ambiguous"+wait_frontmost || fail "final frontmost identity is missing or ambiguous"verify_immutable_binary "$bin" "$bin_sha" || fail "immutable binary copy changed"verify_source_binary || fail "reviewed binary changed during the suite"pass "owned fixture never became frontmost while unrelated user focus remained unconstrained"diff --git a/tests/e2e/scenarios/surfaces.sh b/tests/e2e/scenarios/surfaces.shindex ee6abed84..2f568146a 100644--- a/tests/e2e/scenarios/surfaces.sh+++ b/tests/e2e/scenarios/surfaces.sh@@ -1,7 +1,9 @@note "Sheet surface discovery and interaction""$bin" focus-window --app "$app" >/dev/null 2>&1require_value sheet_before sheet-status+require_target open_sheet button open-sheetact_target "$open_sheet" scroll-to >/dev/null 2>&1+require_target open_sheet button open-sheetact_target "$open_sheet" click >/dev/null 2>&1sleep 0.6surface_list="$("$bin" list-surfaces --app "$app" 2>&1)"