Skip to content

Computer use CLI for AI agents

feat: harden native automation and add cursor overlay (#137)

Lahfir25a00877726d
diff --git a/CONCEPTS.md b/CONCEPTS.md
index 9a2976474..ab0841ead 100644
--- a/CONCEPTS.md
+++ b/CONCEPTS.md
@@ -108,6 +108,10 @@ The side-effect contract attached to an action request, controlling whether the
Core owns those preconditions through `HeadedRequirement`: `FocusedWindow` for keyboard or focus-sensitive work, and `FocusedWindowAndCursor` for pointer delivery. For ref actions, core focuses the exact source window before dispatch and resolves a verified target point for pointer work; the platform adapter owns the OS-specific focus primitive and delivery mechanism. Raw coordinate input has no ref identity, so it never infers or focuses a window. On macOS, headed `click`, `right-click`, `type`, `clear`, and `scroll` are physical-first; double/triple-click, hover, and drag are physical-only; expand/collapse and the remaining semantic actions stay semantic after the core focus precondition.
+### 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.
+
### Headless Ref Action
A 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.md
index 33a49652b..ffaa191b8 100644
--- a/README.md
+++ b/README.md
@@ -118,7 +118,7 @@ For dense apps (Slack, VS Code, Notion), use **progressive skeleton traversal**
agent-desktop snapshot --skeleton --app Slack -i --compact
# Keep snapshot_id, for example s8f3k2p9
-# 2. Drill into a region of interest (named containers get refs as drill targets)
+# 2. Drill into a region of interest (each truncated branch exposes a safe drill ref)
agent-desktop snapshot --root @e3 --snapshot s8f3k2p9 -i --compact
# 3. Act on an element found in the drill-down
@@ -174,6 +174,19 @@ agent-desktop session end "$AGENT_DESKTOP_SESSION"
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.
+
+```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
+```
+
+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.
+
## Driving Chromium apps (CDP)
For a Chromium-based app (Slack, VS Code, Discord, Obsidian, Notion), `launch --cdp` opens a verified Chrome DevTools Protocol endpoint on the web contents. Any framework that speaks CDP can connect — Playwright, Puppeteer, `chrome-remote-interface`, agent-browser — with agent-browser preferred for its ref-based agent workflow and bundled `electron` skill. Native surfaces (menus, dialogs, windows, screenshots) stay on the accessibility path either way.
@@ -338,6 +351,8 @@ agent-desktop session start [--name LABEL] [--no-trace] # create session; pass
agent-desktop session end [id]
agent-desktop session list
agent-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 status # platform, permissions, session_id, tracing, latest snapshot
agent-desktop permissions # check accessibility/screen-recording/automation
agent-desktop permissions --request # request in the bounded isolated helper
diff --git a/crates/core/src/actionability/evaluate.rs b/crates/core/src/actionability/evaluate.rs
index c19752359..1b289998f 100644
--- a/crates/core/src/actionability/evaluate.rs
+++ b/crates/core/src/actionability/evaluate.rs
@@ -85,6 +85,7 @@ pub(super) fn check_with_stability(
requirements.pointer_delivery(&request.action, &evidence.available_actions, request.policy);
let mut checks = Vec::new();
let mut verified_point = None;
+ let presentation_point = evidence.bounds.and_then(center_point);
if requirements.visible {
checks.push(gates::visibility(evidence));
}
@@ -105,7 +106,12 @@ pub(super) fn check_with_stability(
{
return finish(
evidence,
- ActionabilityReport::from_checks(checks, verified_point, pointer_delivery),
+ ActionabilityReport::from_checks(
+ checks,
+ verified_point,
+ presentation_point,
+ pointer_delivery,
+ ),
);
}
if matches!(pointer_delivery, super::PointerDelivery::Physical) {
@@ -124,10 +130,24 @@ pub(super) fn check_with_stability(
}
finish(
evidence,
- ActionabilityReport::from_checks(checks, verified_point, pointer_delivery),
+ ActionabilityReport::from_checks(
+ checks,
+ verified_point,
+ presentation_point,
+ pointer_delivery,
+ ),
)
}
+fn center_point(bounds: crate::Rect) -> Option<crate::Point> {
+ bounds.validate().ok().and_then(|bounds| {
+ (bounds.width > 0.0 && bounds.height > 0.0).then_some(crate::Point {
+ x: bounds.x + bounds.width / 2.0,
+ y: bounds.y + bounds.height / 2.0,
+ })
+ })
+}
+
fn finish(
evidence: &ActionabilityEvidence,
report: ActionabilityReport,
diff --git a/crates/core/src/actionability/receives_events.rs b/crates/core/src/actionability/receives_events.rs
index f31f6bd1e..4b62176ca 100644
--- a/crates/core/src/actionability/receives_events.rs
+++ b/crates/core/src/actionability/receives_events.rs
@@ -101,7 +101,8 @@ pub(crate) fn require_receives_events(
Err(error) => return Err(error),
Ok(HitTestResult::InterceptedBy { role, name, bounds }) => occluded(role, name, bounds),
};
- let report = ActionabilityReport::from_checks(vec![check], None, PointerDelivery::Physical);
+ let report =
+ ActionabilityReport::from_checks(vec![check], 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.rs
index 2f3a5951a..9a237775b 100644
--- a/crates/core/src/actionability/report.rs
+++ b/crates/core/src/actionability/report.rs
@@ -9,6 +9,8 @@ pub(crate) struct ActionabilityReport {
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) verified_point: Option<Point>,
#[serde(skip)]
+ pub(crate) presentation_point: Option<Point>,
+ #[serde(skip)]
pub(crate) pointer_delivery: PointerDelivery,
}
@@ -16,6 +18,7 @@ impl ActionabilityReport {
pub(crate) fn from_checks(
checks: Vec<ActionabilityCheck>,
verified_point: Option<Point>,
+ presentation_point: Option<Point>,
pointer_delivery: PointerDelivery,
) -> Self {
let actionable = checks.iter().all(|check| !is_blocking(check));
@@ -23,6 +26,7 @@ impl ActionabilityReport {
actionable,
checks,
verified_point,
+ presentation_point,
pointer_delivery,
}
}
@@ -81,6 +85,7 @@ mod tests {
failed("supported_action", Some(ErrorCode::PolicyDenied)),
],
None,
+ None,
PointerDelivery::NotApplicable,
);
diff --git a/crates/core/src/adapter/observation.rs b/crates/core/src/adapter/observation.rs
index f75589f56..1ea1783ac 100644
--- a/crates/core/src/adapter/observation.rs
+++ b/crates/core/src/adapter/observation.rs
@@ -57,7 +57,7 @@ pub trait ObservationOps: Send + Sync {
.list_apps(deadline)?
.into_iter()
.filter(|app| {
- app.name.eq_ignore_ascii_case(name)
+ app.matches_identifier(name)
&& bundle_id.is_none_or(|expected| {
app.bundle_id
.as_deref()
diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rs
index c415dad4c..8552ddad6 100644
--- a/crates/core/src/adapter/system.rs
+++ b/crates/core/src/adapter/system.rs
@@ -1,13 +1,21 @@
use crate::{
- AdapterError, AdapterSession, AppInfo, Deadline, DismissAllNotificationsRequest,
- DismissNotificationRequest, ImageBuffer, InteractionLease, InteractionPolicy, KeyCombo,
- NotificationActionRequest, NotificationFilter, NotificationInfo, PermissionReport,
- PermissionState, ProcessIdentity, SessionAffinity, SignalBaseline, SignalFilter, WindowInfo,
- WindowOp, action_result::ActionResult, display_info::DisplayInfo,
+ AdapterError, AdapterSession, AppInfo, CursorOverlayControl, Deadline,
+ DismissAllNotificationsRequest, DismissNotificationRequest, ImageBuffer, InteractionLease,
+ InteractionPolicy, KeyCombo, NotificationActionRequest, NotificationFilter, NotificationInfo,
+ PermissionReport, PermissionState, ProcessIdentity, SessionAffinity, SignalBaseline,
+ SignalFilter, WindowInfo, WindowOp, action_result::ActionResult, display_info::DisplayInfo,
screenshot_target::ScreenshotTarget,
};
pub trait SystemOps: Send + Sync {
+ fn update_cursor_overlay(&self, _control: &CursorOverlayControl) -> Result<(), AdapterError> {
+ Ok(())
+ }
+
+ fn run_cursor_overlay_child(&self) -> Option<Result<(), AdapterError>> {
+ None
+ }
+
fn acquire_interaction_lease(
&self,
_deadline: Deadline,
diff --git a/crates/core/src/adapter/system_tests.rs b/crates/core/src/adapter/system_tests.rs
index f2840b115..8f95b1978 100644
--- a/crates/core/src/adapter/system_tests.rs
+++ b/crates/core/src/adapter/system_tests.rs
@@ -18,6 +18,20 @@ fn default_surfaces_fail_closed() {
assert!(DefaultOnly.supported_surfaces().is_empty());
}
+#[test]
+fn default_cursor_overlay_is_a_successful_no_op() {
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ let instruction =
+ crate::CursorOverlayInstruction::new(crate::Point { x: 20.0, y: 40.0 }, &config, true)
+ .expect("valid instruction");
+ let control = crate::CursorOverlayControl::present("test-session".into(), instruction);
+
+ DefaultOnly
+ .update_cursor_overlay(&control)
+ .expect("default presentation is fail-soft");
+ assert!(DefaultOnly.run_cursor_overlay_child().is_none());
+}
+
#[test]
fn default_permission_report_is_unknown_not_denied() {
let report = DefaultOnly
diff --git a/crates/core/src/app_info.rs b/crates/core/src/app_info.rs
index c87aa8501..0cfbe7c54 100644
--- a/crates/core/src/app_info.rs
+++ b/crates/core/src/app_info.rs
@@ -32,7 +32,7 @@ impl AppInfo {
/// name or bundle identifier. The one predicate every launch-target
/// match uses, so a name match and a bundle match never drift apart.
pub fn matches_identifier(&self, id: &str) -> bool {
- self.name.eq_ignore_ascii_case(id)
+ app_name_matches(&self.name, id)
|| self
.bundle_id
.as_deref()
@@ -40,6 +40,22 @@ impl AppInfo {
}
}
+pub fn app_name_matches(actual: &str, expected: &str) -> bool {
+ let mut actual = actual
+ .chars()
+ .filter(|character| !crate::search_text::is_bidirectional_control(*character));
+ let mut expected = expected
+ .chars()
+ .filter(|character| !crate::search_text::is_bidirectional_control(*character));
+ loop {
+ match (actual.next(), expected.next()) {
+ (Some(actual), Some(expected)) if actual.eq_ignore_ascii_case(&expected) => {}
+ (None, None) => return true,
+ _ => return false,
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -74,6 +90,19 @@ mod tests {
);
}
+ #[test]
+ fn matches_name_with_bidirectional_formatting_controls() {
+ assert!(app("\u{200e}WhatsApp", None).matches_identifier("WhatsApp"));
+ assert!(app("WhatsApp", None).matches_identifier("\u{2067}WhatsApp\u{2069}"));
+ }
+
+ #[test]
+ fn name_identity_remains_exact_after_bidi_controls_are_removed() {
+ assert!(!app("Foo Bar", None).matches_identifier("Foo Bar"));
+ assert!(!app("WhatsApp Beta", None).matches_identifier("WhatsApp"));
+ assert!(!app("WhatsApp!", None).matches_identifier("WhatsApp"));
+ }
+
#[test]
fn does_not_match_an_unrelated_identifier() {
assert!(!app("Fixture", Some("com.example.fixture")).matches_identifier("Other"));
diff --git a/crates/core/src/app_lookup.rs b/crates/core/src/app_lookup.rs
index a4d88a30f..cd73288a4 100644
--- a/crates/core/src/app_lookup.rs
+++ b/crates/core/src/app_lookup.rs
@@ -149,7 +149,7 @@ pub(crate) fn revalidate_app_for_mutation(
.into_iter()
.filter(|candidate| {
candidate.process_instance.as_deref() == Some(expected_identity.instance.as_str())
- && candidate.name.eq_ignore_ascii_case(&expected.name)
+ && crate::app_name_matches(&candidate.name, &expected.name)
&& expected.bundle_id.as_deref().is_none_or(|expected_bundle| {
candidate
.bundle_id
diff --git a/crates/core/src/cdp_endpoint_tests.rs b/crates/core/src/cdp_endpoint_tests.rs
index 48d9da22e..01ffdadaa 100644
--- a/crates/core/src/cdp_endpoint_tests.rs
+++ b/crates/core/src/cdp_endpoint_tests.rs
@@ -94,8 +94,9 @@ fn probe_completes_against_a_server_that_never_closes_the_connection() {
}
#[test]
-fn probe_returns_the_unavailable_error_quickly_when_nothing_is_listening() {
- let port = pick_free_port().unwrap();
+fn probe_leaves_responder_flag_unset_when_no_bytes_arrive() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
let started = std::time::Instant::now();
let error = probe(port, Deadline::after(300).unwrap()).unwrap_err();
diff --git a/crates/core/src/commands/batch.rs b/crates/core/src/commands/batch.rs
index e3fad2877..eefadc3a5 100644
--- a/crates/core/src/commands/batch.rs
+++ b/crates/core/src/commands/batch.rs
@@ -3,6 +3,7 @@ use serde::Deserialize;
use serde_json::Value;
#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
pub struct BatchCommand {
pub command: String,
pub session: Option<String>,
diff --git a/crates/core/src/commands/cursor_overlay.rs b/crates/core/src/commands/cursor_overlay.rs
new file mode 100644
index 000000000..d09b10fc4
--- /dev/null
+++ b/crates/core/src/commands/cursor_overlay.rs
@@ -0,0 +1,20 @@
+use crate::{AppError, CursorOverlayConfig, session::set_cursor_overlay};
+use serde_json::{Value, json};
+
+#[derive(Debug, Clone)]
+pub enum CursorOverlayAction {
+ Enable(CursorOverlayConfig),
+ Disable,
+}
+
+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 manifest = set_cursor_overlay(session_id, cursor_overlay)?;
+ Ok(json!({
+ "session_id": manifest.id,
+ "cursor_overlay": manifest.cursor_overlay,
+ }))
+}
diff --git a/crates/core/src/commands/focus_window.rs b/crates/core/src/commands/focus_window.rs
index 471a0d567..b29610446 100644
--- a/crates/core/src/commands/focus_window.rs
+++ b/crates/core/src/commands/focus_window.rs
@@ -17,28 +17,29 @@ pub fn execute(args: FocusWindowArgs, adapter: &dyn PlatformAdapter) -> Result<V
};
let windows = adapter.list_windows(&filter, deadline)?;
- let window = if let Some(id) = &args.window_id {
- windows.into_iter().find(|w| &w.id == id)
- } else if let Some(title) = &args.title {
+ let candidates = if let Some(id) = &args.window_id {
windows
.into_iter()
- .find(|w| w.title.contains(title.as_str()))
- } else if let Some(app) = &args.app {
+ .filter(|window| &window.id == id)
+ .collect()
+ } else if let Some(title) = &args.title {
windows
.into_iter()
- .find(|w| w.app.eq_ignore_ascii_case(app))
+ .filter(|window| window.title.contains(title.as_str()))
+ .collect()
+ } else if args.app.is_some() {
+ windows
} else {
return Err(AppError::invalid_input(
"Provide --window-id, --app, or --title to identify the window",
));
};
-
- let window = window.ok_or_else(|| {
- AppError::Adapter(
- crate::AdapterError::new(crate::ErrorCode::WindowNotFound, "No matching window found")
- .with_suggestion("Run 'list-windows' to see available windows and their IDs."),
- )
- })?;
+ let window = crate::window_lookup::select_window(
+ candidates,
+ crate::AdapterError::new(crate::ErrorCode::WindowNotFound, "No matching window found")
+ .with_suggestion("Run 'list-windows' to see available windows and their IDs."),
+ "More than one window matches the focus target",
+ )?;
let window_id = window.id.clone();
let lease = adapter.acquire_interaction_lease(deadline)?;
diff --git a/crates/core/src/commands/focus_window_tests.rs b/crates/core/src/commands/focus_window_tests.rs
index 1118c7a1e..a226981b7 100644
--- a/crates/core/src/commands/focus_window_tests.rs
+++ b/crates/core/src/commands/focus_window_tests.rs
@@ -171,3 +171,29 @@ fn focus_confirmation_resets_after_transient_wrong_window() {
assert_eq!(value.id, "w1");
assert_eq!(*adapter.focused_window_calls.lock().unwrap(), 4);
}
+
+#[test]
+fn app_filter_results_are_not_discarded_by_display_name() {
+ let mut target = window("w1", false);
+ target.app = "WhatsApp".into();
+ let mut focused = target.clone();
+ focused.state.is_focused = true;
+ let adapter = FocusAdapter {
+ windows: vec![target],
+ focused_windows: Mutex::new(vec![focused]),
+ focused_window_calls: Mutex::new(0),
+ focused_window_supported: true,
+ };
+
+ let value = execute(
+ FocusWindowArgs {
+ window_id: None,
+ app: Some("net.whatsapp.WhatsApp".into()),
+ title: None,
+ },
+ &adapter,
+ )
+ .unwrap();
+
+ assert_eq!(value["focused"]["id"], "w1");
+}
diff --git a/crates/core/src/commands/is_check.rs b/crates/core/src/commands/is_check.rs
index 914d5d896..edf2705a6 100644
--- a/crates/core/src/commands/is_check.rs
+++ b/crates/core/src/commands/is_check.rs
@@ -5,7 +5,7 @@ use crate::{
context::CommandContext,
element_state::ElementState,
refs::RefEntry,
- state::{self, CHECKED, DISABLED, EXPANDED, FOCUSED, VisibilityEvidence},
+ state::{self, CHECKED, DISABLED, EXPANDED, FOCUSED, SELECTED, VisibilityEvidence},
};
use serde_json::{Value, json};
@@ -21,6 +21,7 @@ pub enum IsProperty {
Checked,
Focused,
Expanded,
+ Selected,
}
pub fn execute(
@@ -37,6 +38,7 @@ pub fn execute(
IsProperty::Checked => "checked",
IsProperty::Focused => "focused",
IsProperty::Expanded => "expanded",
+ IsProperty::Selected => "selected",
};
let deadline = crate::Deadline::standard()?;
@@ -77,6 +79,7 @@ pub fn execute(
),
state::has_state(&state.states, EXPANDED),
),
+ IsProperty::Selected => (true, state::has_state(&state.states, SELECTED)),
};
Ok(
diff --git a/crates/core/src/commands/is_check_tests.rs b/crates/core/src/commands/is_check_tests.rs
index c63df5794..4a56854f8 100644
--- a/crates/core/src/commands/is_check_tests.rs
+++ b/crates/core/src/commands/is_check_tests.rs
@@ -331,13 +331,16 @@ fn checked_falls_back_to_snapshot_state_when_live_state_is_missing() {
fn basic_state_properties_use_live_state() {
let _guard = HomeGuard::new();
let snapshot_id = save_entry(entry(vec![], None, vec![]));
- let adapter =
- LiveStateAdapter::with_live(visible_bounds(), vec!["focused".into(), "expanded".into()]);
+ let adapter = LiveStateAdapter::with_live(
+ visible_bounds(),
+ vec!["focused".into(), "expanded".into(), "selected".into()],
+ );
for (property, expected) in [
(IsProperty::Enabled, true),
(IsProperty::Focused, true),
(IsProperty::Expanded, true),
+ (IsProperty::Selected, true),
] {
let result = execute(
IsArgs {
diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs
index 5f2a42592..27c816955 100644
--- a/crates/core/src/commands/mod.rs
+++ b/crates/core/src/commands/mod.rs
@@ -8,6 +8,7 @@ pub mod clipboard_set;
pub mod close_app;
pub mod collapse;
pub(crate) mod combo;
+pub mod cursor_overlay;
pub mod dismiss_all_notifications;
pub mod dismiss_notification;
pub mod double_click;
diff --git a/crates/core/src/commands/mouse_click_tests.rs b/crates/core/src/commands/mouse_click_tests.rs
index 693fb15db..125cd1cb2 100644
--- a/crates/core/src/commands/mouse_click_tests.rs
+++ b/crates/core/src/commands/mouse_click_tests.rs
@@ -5,12 +5,14 @@ use std::sync::Mutex;
struct ModifierCaptureAdapter {
captured: Mutex<Option<MouseEvent>>,
+ presented: Mutex<Option<crate::CursorOverlayControl>>,
}
impl ModifierCaptureAdapter {
fn new() -> Self {
Self {
captured: Mutex::new(None),
+ presented: Mutex::new(None),
}
}
}
@@ -19,6 +21,14 @@ impl ObservationOps for ModifierCaptureAdapter {}
impl ActionOps for ModifierCaptureAdapter {}
impl SystemOps for ModifierCaptureAdapter {
crate::adapter::guarded_interaction_lease!();
+
+ fn update_cursor_overlay(
+ &self,
+ control: &crate::CursorOverlayControl,
+ ) -> Result<(), AdapterError> {
+ *self.presented.lock().unwrap() = Some(control.clone());
+ Ok(())
+ }
}
impl InputOps for ModifierCaptureAdapter {
@@ -81,6 +91,29 @@ fn no_modifiers_requested_dispatches_empty_modifiers() {
assert!(captured.as_ref().unwrap().modifiers.is_empty());
}
+#[test]
+fn headed_mouse_click_suppresses_cursor_overlay() {
+ let adapter = ModifierCaptureAdapter::new();
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+
+ execute(
+ MouseClickArgs {
+ x: 10.0,
+ y: 20.0,
+ button: MouseButton::Left,
+ count: 1,
+ modifiers: Vec::new(),
+ },
+ &adapter,
+ &CommandContext::default()
+ .with_headed(true)
+ .with_cursor_overlay(config),
+ )
+ .expect("mouse click succeeds");
+
+ assert!(adapter.presented.lock().unwrap().is_none());
+}
+
#[test]
fn zero_clicks_fail_before_dispatch() {
let adapter = ModifierCaptureAdapter::new();
diff --git a/crates/core/src/commands/skills.rs b/crates/core/src/commands/skills.rs
index 49d85cff2..f8e629e11 100644
--- a/crates/core/src/commands/skills.rs
+++ b/crates/core/src/commands/skills.rs
@@ -93,7 +93,7 @@ const SKILLS: &[Skill] = &[
Skill {
canonical: "agent-desktop",
aliases: &["desktop", "agent-desktop"],
- summary: "Primary guide. Snapshot/ref loop, JSON envelope, 58 commands including session lifecycle, observation, interaction, keyboard/mouse, app lifecycle, notifications, clipboard, wait.",
+ summary: "Primary guide. Snapshot/ref loop, JSON envelope, 59 commands including session lifecycle, cursor overlay, observation, interaction, keyboard/mouse, app lifecycle, notifications, clipboard, wait.",
main: SKILL_DESKTOP_MAIN,
refs: skill_desktop_refs,
},
diff --git a/crates/core/src/commands/wait.rs b/crates/core/src/commands/wait.rs
index 0cbd45b0f..6f0571013 100644
--- a/crates/core/src/commands/wait.rs
+++ b/crates/core/src/commands/wait.rs
@@ -199,9 +199,6 @@ fn wait_for_text(
let mut last_error = None;
loop {
- if deadline.is_expired() {
- return wait_timeout::text(&text, timeout_ms, expected_count, last_error);
- }
match snapshot::build(adapter, &opts, app.as_deref(), None, deadline) {
Ok(mut result) => {
let matches = wait_text_match::find(&result.tree, &normalized_text, expected_count);
@@ -246,12 +243,11 @@ fn wait_for_text(
Err(err) => return Err(err),
}
- let remaining = deadline.remaining();
- if remaining.is_zero() {
+ if deadline.is_expired() {
return wait_timeout::text(&text, timeout_ms, expected_count, last_error);
}
- std::thread::sleep(remaining.min(interval));
+ std::thread::sleep(deadline.remaining().min(interval));
interval = (interval * 2).min(Duration::from_millis(1000));
}
}
diff --git a/crates/core/src/commands/wait_event.rs b/crates/core/src/commands/wait_event.rs
index 159c77252..f7da3af6d 100644
--- a/crates/core/src/commands/wait_event.rs
+++ b/crates/core/src/commands/wait_event.rs
@@ -142,7 +142,7 @@ fn process_from_baseline(
let mut matches = baseline
.apps
.iter()
- .filter(|candidate| candidate.name.eq_ignore_ascii_case(app));
+ .filter(|candidate| candidate.matches_identifier(app));
let Some(first) = matches.next() else {
return Ok(None);
};
diff --git a/crates/core/src/commands/wait_event_tests.rs b/crates/core/src/commands/wait_event_tests.rs
index 0c34d3124..d47e947ce 100644
--- a/crates/core/src/commands/wait_event_tests.rs
+++ b/crates/core/src/commands/wait_event_tests.rs
@@ -344,6 +344,18 @@ fn failed_inventory_poll_never_reports_app_termination() {
assert_eq!(details["baseline_counts"]["apps"], 1);
}
+#[test]
+fn seeded_process_resolves_bundle_identifier() {
+ let baseline = baseline_with_apps(vec![app("TextEdit", "test-instance")]);
+
+ let process = process_from_baseline(&baseline, "com.example.editor")
+ .unwrap()
+ .unwrap();
+
+ assert_eq!(process.pid, crate::ProcessId::new(42));
+ assert_eq!(process.instance, "test-instance");
+}
+
#[path = "wait_event_deadline_tests.rs"]
mod deadline_tests;
diff --git a/crates/core/src/commands/window_target.rs b/crates/core/src/commands/window_target.rs
index 1318fd094..90ccbbe71 100644
--- a/crates/core/src/commands/window_target.rs
+++ b/crates/core/src/commands/window_target.rs
@@ -54,7 +54,6 @@ fn resolve_window(
)?
.into_iter()
.filter(|window| window.id == window_id)
- .filter(|window| app.is_none_or(|app| window.app.eq_ignore_ascii_case(app)))
.collect();
return window_lookup::select_window(
candidates,
diff --git a/crates/core/src/context.rs b/crates/core/src/context.rs
index 01f045660..5080a46db 100644
--- a/crates/core/src/context.rs
+++ b/crates/core/src/context.rs
@@ -1,15 +1,20 @@
use crate::{
- AdapterError, AppError, SignalBaseline, action::Action, action_request::ActionRequest,
- interaction_policy::InteractionPolicy, session, trace::TraceConfig,
+ AdapterError, AppError, CursorOverlayConfig, SignalBaseline, action::Action,
+ action_request::ActionRequest, interaction_policy::InteractionPolicy, session,
+ trace::TraceConfig,
};
use serde_json::{Value, json};
use std::cell::Cell;
use std::path::PathBuf;
use std::time::Instant;
+mod options;
mod session_scope;
+mod wait_selector;
+use options::CommandOptions;
use session_scope::SessionScope;
+pub use wait_selector::WaitSelector;
#[derive(Debug, Clone, Default)]
pub struct CommandContext {
@@ -17,16 +22,7 @@ pub struct CommandContext {
inherited_deadline: Option<crate::Deadline>,
trace: TraceConfig,
artifacts_full: bool,
- interaction_policy: InteractionPolicy,
- wait_selector: Option<WaitSelector>,
- event_baseline: Option<Result<SignalBaseline, AdapterError>>,
-}
-
-#[derive(Debug, Clone)]
-pub struct WaitSelector {
- pub query_raw: String,
- pub gone: bool,
- pub timeout_ms: u64,
+ options: CommandOptions,
}
/// Emits `command.start` on construction and `command.end` on `complete`.
@@ -95,19 +91,22 @@ impl CommandContext {
let (segment_dir, artifacts_full) =
session_trace_state(session_id.as_deref(), trace_path.is_some())?;
let session = acquire_session_scope(session_id, None)?;
+ let cursor_overlay =
+ session::cursor_overlay_for_session(session.as_ref().map(|scope| scope.id.as_str()))?;
Ok(Self {
session,
inherited_deadline: None,
trace: TraceConfig::build(trace_path, segment_dir, trace_strict)?,
artifacts_full,
- interaction_policy: InteractionPolicy::headless(),
- wait_selector: None,
- event_baseline: None,
+ options: CommandOptions {
+ cursor_overlay,
+ ..CommandOptions::default()
+ },
})
}
pub fn with_headed(mut self, headed: bool) -> Self {
- self.interaction_policy = if headed {
+ self.options.interaction_policy = if headed {
InteractionPolicy::headed()
} else {
InteractionPolicy::headless()
@@ -116,34 +115,62 @@ impl CommandContext {
}
pub fn with_interaction_policy(mut self, policy: InteractionPolicy) -> Self {
- self.interaction_policy = policy;
+ self.options.interaction_policy = policy;
self
}
pub fn with_wait_selector(mut self, wait_selector: Option<WaitSelector>) -> Self {
- self.wait_selector = wait_selector;
+ self.options.wait_selector = wait_selector;
self
}
pub fn wait_selector(&self) -> Option<&WaitSelector> {
- self.wait_selector.as_ref()
+ self.options.wait_selector.as_ref()
}
pub fn with_event_baseline(
mut self,
baseline: Option<Result<SignalBaseline, AdapterError>>,
) -> Self {
- self.event_baseline = baseline;
+ self.options.event_baseline = baseline;
self
}
+ pub fn cursor_overlay(&self) -> &CursorOverlayConfig {
+ &self.options.cursor_overlay
+ }
+
+ #[cfg(test)]
+ pub(crate) fn with_cursor_overlay(mut self, cursor_overlay: CursorOverlayConfig) -> Self {
+ self.options.cursor_overlay = cursor_overlay;
+ self
+ }
+
+ #[cfg(test)]
+ pub(crate) fn with_cursor_overlay_session(
+ mut self,
+ session_id: &str,
+ cursor_overlay: CursorOverlayConfig,
+ ) -> Self {
+ self.session = Some(SessionScope {
+ id: session_id.into(),
+ lease: None,
+ });
+ self.options.cursor_overlay = cursor_overlay;
+ self
+ }
+
+ pub fn is_headed(&self) -> bool {
+ self.options.interaction_policy.is_headed()
+ }
+
pub fn with_inherited_deadline(mut self, deadline: crate::Deadline) -> Self {
self.inherited_deadline = Some(deadline);
self
}
pub fn event_baseline(&self) -> Option<&Result<SignalBaseline, AdapterError>> {
- self.event_baseline.as_ref()
+ self.options.event_baseline.as_ref()
}
pub fn command_scope(&self, command: &'static str) -> Result<CommandScope<'_>, AppError> {
@@ -200,7 +227,7 @@ impl CommandContext {
}
fn policy_with_base(&self, base: InteractionPolicy) -> InteractionPolicy {
- base.join(self.interaction_policy)
+ base.join(self.options.interaction_policy)
}
pub fn for_batch_item(&self, session_id: Option<String>) -> Result<Self, AppError> {
@@ -225,14 +252,17 @@ impl CommandContext {
} else {
acquire_session_scope(session_id, self.inherited_deadline)?
};
+ let cursor_overlay = if reuses_parent_session {
+ self.options.cursor_overlay.clone()
+ } else {
+ session::cursor_overlay_for_session(session.as_ref().map(|scope| scope.id.as_str()))?
+ };
Ok(Self {
session,
inherited_deadline: self.inherited_deadline,
trace,
artifacts_full,
- interaction_policy: self.interaction_policy,
- wait_selector: None,
- event_baseline: None,
+ options: self.options.for_batch(cursor_overlay),
})
}
diff --git a/crates/core/src/context/options.rs b/crates/core/src/context/options.rs
new file mode 100644
index 000000000..21b5f5052
--- /dev/null
+++ b/crates/core/src/context/options.rs
@@ -0,0 +1,22 @@
+use crate::{AdapterError, CursorOverlayConfig, InteractionPolicy, SignalBaseline};
+
+use super::WaitSelector;
+
+#[derive(Debug, Clone, Default)]
+pub(super) struct CommandOptions {
+ pub interaction_policy: InteractionPolicy,
+ pub wait_selector: Option<WaitSelector>,
+ pub event_baseline: Option<Result<SignalBaseline, AdapterError>>,
+ pub cursor_overlay: CursorOverlayConfig,
+}
+
+impl CommandOptions {
+ pub fn for_batch(&self, cursor_overlay: CursorOverlayConfig) -> Self {
+ Self {
+ interaction_policy: self.interaction_policy,
+ wait_selector: None,
+ event_baseline: None,
+ cursor_overlay,
+ }
+ }
+}
diff --git a/crates/core/src/context/wait_selector.rs b/crates/core/src/context/wait_selector.rs
new file mode 100644
index 000000000..afb7843be
--- /dev/null
+++ b/crates/core/src/context/wait_selector.rs
@@ -0,0 +1,6 @@
+#[derive(Debug, Clone)]
+pub struct WaitSelector {
+ pub query_raw: String,
+ pub gone: bool,
+ pub timeout_ms: u64,
+}
diff --git a/crates/core/src/context_tests.rs b/crates/core/src/context_tests.rs
index e9d46a3fd..9b3218d2a 100644
--- a/crates/core/src/context_tests.rs
+++ b/crates/core/src/context_tests.rs
@@ -9,6 +9,25 @@ fn accepts_filesystem_safe_session_ids() {
assert!(validate_session_id("agent-1_A").is_ok());
}
+#[test]
+fn session_cursor_config_is_loaded_by_commands_and_batch_entries() {
+ let _guard = crate::refs_test_support::HomeGuard::new();
+ let manifest = start_session(StartSessionOptions::default()).expect("session starts");
+ let enabled =
+ crate::CursorOverlayConfig::enabled(Some("Opening menu".into()), 6).expect("valid config");
+ crate::session::set_cursor_overlay(&manifest.id, enabled).expect("setting persists");
+
+ let context =
+ CommandContext::new(Some(manifest.id.clone()), None, false).expect("context loads session");
+ let batch_context = context
+ .for_batch_item(None)
+ .expect("batch inherits session");
+
+ assert!(context.cursor_overlay().is_enabled());
+ assert_eq!(context.cursor_overlay().label(), Some("Opening menu"));
+ assert_eq!(batch_context.cursor_overlay(), context.cursor_overlay());
+}
+
#[test]
fn rejects_path_like_session_ids() {
assert!(validate_session_id("../agent").is_err());
diff --git a/crates/core/src/cursor_overlay/config.rs b/crates/core/src/cursor_overlay/config.rs
new file mode 100644
index 000000000..a212519bb
--- /dev/null
+++ b/crates/core/src/cursor_overlay/config.rs
@@ -0,0 +1,103 @@
+use crate::{AdapterError, ErrorCode};
+use serde::{Deserialize, Serialize};
+
+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)]
+#[serde(deny_unknown_fields)]
+pub struct CursorOverlayConfig {
+ #[serde(default)]
+ enabled: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ label: Option<String>,
+ #[serde(default = "default_word_limit")]
+ max_words: usize,
+}
+
+impl CursorOverlayConfig {
+ pub fn enabled(label: Option<String>, max_words: usize) -> Result<Self, AdapterError> {
+ Self {
+ enabled: true,
+ label,
+ max_words,
+ }
+ .validated()
+ }
+
+ pub fn validated(mut self) -> Result<Self, AdapterError> {
+ if !(1..=MAX_CURSOR_LABEL_WORDS).contains(&self.max_words) {
+ return Err(AdapterError::new(
+ ErrorCode::InvalidArgs,
+ format!(
+ "Agent cursor label word limit must be between 1 and {MAX_CURSOR_LABEL_WORDS}"
+ ),
+ ));
+ }
+ if !self.enabled && self.label.is_some() {
+ return Err(AdapterError::new(
+ ErrorCode::InvalidArgs,
+ "Agent cursor label requires agent cursor mode 'on'",
+ ));
+ }
+ if self
+ .label
+ .as_deref()
+ .is_some_and(|label| label.trim().len() > MAX_CURSOR_LABEL_BYTES)
+ {
+ return Err(AdapterError::new(
+ ErrorCode::InvalidArgs,
+ format!("Agent cursor label must be at most {MAX_CURSOR_LABEL_BYTES} bytes"),
+ ));
+ }
+ self.label = self
+ .label
+ .take()
+ .and_then(|label| limit_words(label.trim(), self.max_words));
+ Ok(self)
+ }
+
+ pub const fn is_enabled(&self) -> bool {
+ self.enabled
+ }
+
+ pub const fn is_disabled(&self) -> bool {
+ !self.enabled
+ }
+
+ pub fn label(&self) -> Option<&str> {
+ self.label.as_deref()
+ }
+
+ pub const fn max_words(&self) -> usize {
+ self.max_words
+ }
+}
+
+impl Default for CursorOverlayConfig {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ label: None,
+ max_words: DEFAULT_CURSOR_LABEL_WORDS,
+ }
+ }
+}
+
+fn default_word_limit() -> usize {
+ DEFAULT_CURSOR_LABEL_WORDS
+}
+
+fn limit_words(value: &str, max_words: usize) -> Option<String> {
+ let words = value.split_whitespace().collect::<Vec<_>>();
+ if words.is_empty() {
+ return None;
+ }
+ if words.len() <= max_words {
+ return Some(words.join(" "));
+ }
+ let mut limited = words[..max_words].join(" ");
+ limited.push('…');
+ Some(limited)
+}
diff --git a/crates/core/src/cursor_overlay/control.rs b/crates/core/src/cursor_overlay/control.rs
new file mode 100644
index 000000000..7bdc5c4bd
--- /dev/null
+++ b/crates/core/src/cursor_overlay/control.rs
@@ -0,0 +1,110 @@
+use super::CursorOverlayInstruction;
+use crate::{AdapterError, ErrorCode, context::validate_session_id};
+use serde::{Deserialize, Serialize};
+
+pub const CURSOR_OVERLAY_GREETING: &str = "Hey, let's play with this computer!";
+
+#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
+#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
+pub enum CursorOverlayControl {
+ Enable {
+ session_id: String,
+ label: String,
+ },
+ Present {
+ session_id: String,
+ instruction: CursorOverlayInstruction,
+ },
+ Hide {
+ session_id: String,
+ },
+ Show {
+ session_id: String,
+ },
+ Disable {
+ session_id: String,
+ },
+}
+
+impl CursorOverlayControl {
+ pub fn enable(session_id: String) -> Self {
+ Self::Enable {
+ session_id,
+ label: CURSOR_OVERLAY_GREETING.into(),
+ }
+ }
+
+ pub fn present(session_id: String, instruction: CursorOverlayInstruction) -> Self {
+ Self::Present {
+ session_id,
+ instruction,
+ }
+ }
+
+ pub fn disable(session_id: String) -> Self {
+ Self::Disable { session_id }
+ }
+
+ pub fn hide(session_id: String) -> Self {
+ Self::Hide { session_id }
+ }
+
+ pub fn show(session_id: String) -> Self {
+ Self::Show { session_id }
+ }
+
+ pub fn validate(&self) -> Result<(), AdapterError> {
+ validate_session_id(self.session_id()).map_err(|_| {
+ AdapterError::new(ErrorCode::InvalidArgs, "Invalid cursor overlay session id")
+ })?;
+ if let Self::Present { instruction, .. } = self {
+ instruction.validate()?;
+ }
+ Ok(())
+ }
+
+ pub fn session_id(&self) -> &str {
+ match self {
+ Self::Enable { session_id, .. }
+ | Self::Present { session_id, .. }
+ | Self::Hide { session_id }
+ | Self::Show { session_id }
+ | Self::Disable { session_id } => session_id,
+ }
+ }
+
+ pub fn label(&self) -> Option<&str> {
+ match self {
+ Self::Enable { label, .. } => Some(label),
+ Self::Present { instruction, .. } => instruction.label(),
+ Self::Hide { .. } | Self::Show { .. } | Self::Disable { .. } => None,
+ }
+ }
+
+ pub const fn is_enable(&self) -> bool {
+ matches!(self, Self::Enable { .. })
+ }
+
+ pub const fn is_disable(&self) -> bool {
+ matches!(self, Self::Disable { .. })
+ }
+
+ pub const fn is_transient(&self) -> bool {
+ matches!(self, Self::Hide { .. } | Self::Show { .. })
+ }
+
+ pub const fn is_hide(&self) -> bool {
+ matches!(self, Self::Hide { .. })
+ }
+
+ pub const fn is_show(&self) -> bool {
+ matches!(self, Self::Show { .. })
+ }
+
+ pub fn instruction(&self) -> Option<&CursorOverlayInstruction> {
+ match self {
+ Self::Present { instruction, .. } => Some(instruction),
+ _ => None,
+ }
+ }
+}
diff --git a/crates/core/src/cursor_overlay/instruction.rs b/crates/core/src/cursor_overlay/instruction.rs
new file mode 100644
index 000000000..a718803cd
--- /dev/null
+++ b/crates/core/src/cursor_overlay/instruction.rs
@@ -0,0 +1,49 @@
+use super::CursorOverlayConfig;
+use crate::{AdapterError, ErrorCode, Point};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct CursorOverlayInstruction {
+ destination: Point,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ label: Option<String>,
+ click: bool,
+}
+
+impl CursorOverlayInstruction {
+ pub fn new(
+ destination: Point,
+ config: &CursorOverlayConfig,
+ click: bool,
+ ) -> Result<Self, AdapterError> {
+ destination.validate()?;
+ if !config.is_enabled() {
+ return Err(AdapterError::new(
+ ErrorCode::InvalidArgs,
+ "Agent cursor instruction requires enabled presentation",
+ ));
+ }
+ Ok(Self {
+ destination,
+ label: config.label().map(str::to_owned),
+ click,
+ })
+ }
+
+ pub fn validate(&self) -> Result<(), AdapterError> {
+ self.destination.validate()
+ }
+
+ pub fn destination(&self) -> &Point {
+ &self.destination
+ }
+
+ pub fn label(&self) -> Option<&str> {
+ self.label.as_deref()
+ }
+
+ pub const fn is_click(&self) -> bool {
+ self.click
+ }
+}
diff --git a/crates/core/src/cursor_overlay/layout.rs b/crates/core/src/cursor_overlay/layout.rs
new file mode 100644
index 000000000..743226574
--- /dev/null
+++ b/crates/core/src/cursor_overlay/layout.rs
@@ -0,0 +1,27 @@
+use crate::{Point, Rect};
+
+const DESTINATION_GAP: f64 = 18.0;
+
+pub fn place_label(destination: &Point, size: (f64, f64), screen: &Rect) -> Rect {
+ let (width, height) = size;
+ let right = screen.x + screen.width;
+ let bottom = screen.y + screen.height;
+ let preferred_x = destination.x + DESTINATION_GAP;
+ let preferred_y = destination.y + DESTINATION_GAP;
+ let x = if preferred_x + width <= right {
+ preferred_x
+ } else {
+ destination.x - width - DESTINATION_GAP
+ };
+ let y = if preferred_y + height <= bottom {
+ preferred_y
+ } else {
+ destination.y - height - DESTINATION_GAP
+ };
+ Rect {
+ x: x.clamp(screen.x, (right - width).max(screen.x)),
+ y: y.clamp(screen.y, (bottom - height).max(screen.y)),
+ width: width.min(screen.width.max(0.0)),
+ height: height.min(screen.height.max(0.0)),
+ }
+}
diff --git a/crates/core/src/cursor_overlay/mod.rs b/crates/core/src/cursor_overlay/mod.rs
new file mode 100644
index 000000000..c3db94ad5
--- /dev/null
+++ b/crates/core/src/cursor_overlay/mod.rs
@@ -0,0 +1,16 @@
+mod config;
+mod control;
+mod instruction;
+mod layout;
+mod motion;
+mod submit;
+
+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(crate) use submit::submit;
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/core/src/cursor_overlay/motion.rs b/crates/core/src/cursor_overlay/motion.rs
new file mode 100644
index 000000000..094706f96
--- /dev/null
+++ b/crates/core/src/cursor_overlay/motion.rs
@@ -0,0 +1,56 @@
+use crate::Point;
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct CursorMotion {
+ start: Point,
+ destination: Point,
+ duration_ms: u64,
+ bend: f64,
+}
+
+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();
+ Self {
+ start,
+ destination,
+ duration_ms: duration_ms as u64,
+ bend: (distance * 0.09).min(54.0),
+ }
+ }
+
+ 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();
+ }
+ if elapsed_ms >= self.duration_ms {
+ return self.destination.clone();
+ }
+ 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,
+ }
+ }
+}
+
+fn minimum_jerk(t: f64) -> f64 {
+ t * t * t * (10.0 + t * (-15.0 + 6.0 * t))
+}
diff --git a/crates/core/src/cursor_overlay/submit.rs b/crates/core/src/cursor_overlay/submit.rs
new file mode 100644
index 000000000..8e8c63005
--- /dev/null
+++ b/crates/core/src/cursor_overlay/submit.rs
@@ -0,0 +1,27 @@
+use crate::{CommandContext, PlatformAdapter, Point};
+
+pub(crate) fn submit(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ destination: Point,
+ click: bool,
+) {
+ if context.is_headed() || !context.cursor_overlay().is_enabled() {
+ return;
+ }
+ let Some(session_id) = context.session_id() else {
+ return;
+ };
+ let instruction =
+ match super::CursorOverlayInstruction::new(destination, context.cursor_overlay(), click) {
+ Ok(instruction) => instruction,
+ 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);
+ 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.rs
new file mode 100644
index 000000000..0a1902c63
--- /dev/null
+++ b/crates/core/src/cursor_overlay/tests.rs
@@ -0,0 +1,96 @@
+use super::*;
+use crate::{Point, Rect};
+
+#[test]
+fn motion_reaches_both_endpoints_and_curves_between_them() {
+ let motion = CursorMotion::new(Point { x: 20.0, y: 40.0 }, Point { x: 420.0, y: 240.0 });
+
+ assert_eq!(motion.sample(0), Point { x: 20.0, y: 40.0 });
+ assert_eq!(
+ motion.sample(motion.duration_ms()),
+ Point { x: 420.0, y: 240.0 }
+ );
+ let midpoint = motion.sample(motion.duration_ms() / 2);
+ assert!((midpoint.x - 220.0).hypot(midpoint.y - 140.0) > 30.0);
+}
+
+#[test]
+fn motion_eases_in_and_out() {
+ 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);
+}
+
+#[test]
+fn motion_duration_is_distance_aware_and_bounded() {
+ let short = CursorMotion::new(Point { x: 0.0, y: 0.0 }, Point { x: 10.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);
+}
+
+#[test]
+fn label_limit_handles_unicode_words_and_ellipsis() {
+ let config = CursorOverlayConfig::enabled(
+ Some("Opening the profile menu for this account now".into()),
+ 5,
+ )
+ .expect("valid config");
+
+ assert_eq!(config.label(), Some("Opening the profile menu for…"));
+}
+
+#[test]
+fn label_has_a_bounded_transport_size() {
+ let error = CursorOverlayConfig::enabled(Some("x".repeat(513)), MAX_CURSOR_LABEL_WORDS)
+ .expect_err("oversized labels must be rejected when configured");
+
+ assert_eq!(error.code, crate::ErrorCode::InvalidArgs);
+}
+
+#[test]
+fn label_placement_stays_on_screen_and_clear_of_destination() {
+ let screen = Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 800.0,
+ height: 600.0,
+ };
+ let bubble = place_label(&Point { x: 790.0, y: 590.0 }, (232.0, 38.0), &screen);
+
+ assert!(bubble.x >= screen.x);
+ assert!(bubble.y >= screen.y);
+ assert!(bubble.x + bubble.width <= screen.x + screen.width);
+ assert!(bubble.y + bubble.height <= screen.y + screen.height);
+ assert!(bubble.x + bubble.width <= 782.0 || bubble.y + bubble.height <= 582.0);
+}
+
+#[test]
+fn instruction_rejects_invalid_destination() {
+ let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ let error = CursorOverlayInstruction::new(
+ Point {
+ x: f64::NAN,
+ y: 10.0,
+ },
+ &config,
+ true,
+ )
+ .expect_err("invalid point");
+
+ assert_eq!(error.code, crate::ErrorCode::InvalidArgs);
+}
+
+#[test]
+fn control_protocol_carries_the_session_lifecycle() {
+ let enable = CursorOverlayControl::enable("run-1".into());
+ let disable = CursorOverlayControl::disable("run-1".into());
+
+ assert_eq!(enable.session_id(), "run-1");
+ assert_eq!(enable.label(), Some("Hey, let's play with this computer!"));
+ assert!(enable.is_enable());
+ assert_eq!(disable.session_id(), "run-1");
+ assert!(disable.is_disable());
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index ea03c110a..67c8b0a73 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -20,6 +20,7 @@ mod clipboard_format;
pub mod commands;
mod containment_predicate;
pub mod context;
+pub mod cursor_overlay;
mod deadline;
mod delivery_disposition;
mod delivery_semantics;
@@ -164,11 +165,15 @@ pub use adapter::system::SystemOps;
pub use adapter_error::AdapterError;
pub use adapter_session::AdapterSession;
pub use app_error::AppError;
-pub use app_info::{AppInfo, AppPresentation};
+pub use app_info::{AppInfo, AppPresentation, app_name_matches};
pub use clipboard_content::ClipboardContent;
pub use clipboard_format::ClipboardFormat;
pub use containment_predicate::ContainmentPredicate;
pub use context::{CommandContext, WaitSelector};
+pub use cursor_overlay::{
+ CURSOR_OVERLAY_GREETING, CursorMotion, CursorOverlayConfig, CursorOverlayControl,
+ CursorOverlayInstruction, MAX_CURSOR_LABEL_WORDS, place_label,
+};
pub use deadline::{DEFAULT_OPERATION_TIMEOUT_MS, Deadline};
pub use delivery_disposition::DeliveryDisposition;
pub use delivery_semantics::DeliverySemantics;
diff --git a/crates/core/src/ref_action.rs b/crates/core/src/ref_action.rs
index 8be9afbbe..7e02a2b50 100644
--- a/crates/core/src/ref_action.rs
+++ b/crates/core/src/ref_action.rs
@@ -10,6 +10,8 @@ use crate::{
};
use serde_json::json;
+mod presentation;
+
const TRACE_CAPTURE_BUDGET_MS: u64 = 1_000;
const PRE_CAPTURE_DISPATCH_RESERVE_MS: u64 = 100;
@@ -21,6 +23,7 @@ pub(crate) struct ResolvedRefAction<'a> {
pub(crate) struct ActionabilityPreflight {
verified_point: Option<crate::Point>,
+ presentation_point: Option<crate::Point>,
pointer_delivery: actionability::PointerDelivery,
}
@@ -107,9 +110,17 @@ 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();
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,
+ &presentation_action,
+ &dispatch_result,
+ );
let mut result = dispatch_result?;
if raises_surface {
result.surfaces = settled_surfaces(&final_target, expected_process);
@@ -313,6 +324,7 @@ fn check_actionability_with_trace(
})?;
Ok(ActionabilityPreflight {
verified_point: report.verified_point,
+ presentation_point: report.presentation_point,
pointer_delivery: report.pointer_delivery,
})
}
@@ -378,3 +390,7 @@ pub(crate) fn into_adapter_error(err: AppError) -> AdapterError {
#[cfg(test)]
#[path = "ref_action_tests.rs"]
mod tests;
+
+#[cfg(test)]
+#[path = "ref_action_cursor_overlay_tests.rs"]
+mod cursor_overlay_tests;
diff --git a/crates/core/src/ref_action/presentation.rs b/crates/core/src/ref_action/presentation.rs
new file mode 100644
index 000000000..5b3e8baa8
--- /dev/null
+++ b/crates/core/src/ref_action/presentation.rs
@@ -0,0 +1,40 @@
+use crate::{
+ Action, CommandContext, DeliveryDisposition, DeliverySemantics, PlatformAdapter, Point,
+};
+
+pub(super) fn after_dispatch(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ destination: Option<Point>,
+ action: &Action,
+ result: &Result<crate::ActionResult, crate::AdapterError>,
+) {
+ let disposition = match result {
+ Ok(result) => result.disposition(),
+ Err(error) => error.disposition,
+ };
+ if result.is_err() && !confirms_dispatch(disposition) {
+ return;
+ }
+ let Some(destination) = destination else {
+ return;
+ };
+ let click = is_click(action) && confirms_dispatch(disposition);
+ crate::cursor_overlay::submit(adapter, context, destination, click);
+}
+
+fn confirms_dispatch(disposition: DeliverySemantics) -> bool {
+ matches!(
+ disposition.delivery(),
+ DeliveryDisposition::DeliveryUncertain
+ | DeliveryDisposition::DeliveredUnverified
+ | DeliveryDisposition::DeliveredVerified
+ )
+}
+
+fn is_click(action: &Action) -> bool {
+ matches!(
+ action,
+ Action::Click | Action::DoubleClick | Action::RightClick | Action::TripleClick
+ )
+}
diff --git a/crates/core/src/ref_action_cursor_overlay_tests.rs b/crates/core/src/ref_action_cursor_overlay_tests.rs
new file mode 100644
index 000000000..8a805a0bf
--- /dev/null
+++ b/crates/core/src/ref_action_cursor_overlay_tests.rs
@@ -0,0 +1,161 @@
+use super::*;
+use crate::adapter::{
+ ActionOps, InputOps, NativeHandle, ObservationOps, SnapshotSurface, SystemOps,
+};
+use crate::{Action, ActionResult, AdapterError, CursorOverlayControl, capability};
+use std::sync::Mutex;
+
+struct CursorAdapter {
+ presented: Mutex<Vec<CursorOverlayControl>>,
+ fail_presentation: bool,
+}
+
+impl CursorAdapter {
+ fn new(fail_presentation: bool) -> Self {
+ Self {
+ presented: Mutex::new(Vec::new()),
+ fail_presentation,
+ }
+ }
+}
+
+impl ObservationOps for CursorAdapter {
+ fn resolve_element_strict(
+ &self,
+ _entry: &RefEntry,
+ _deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+
+ crate::adapter::complete_live_observation!("button", "Run", [capability::CLICK]);
+}
+
+impl ActionOps for CursorAdapter {
+ fn execute_action(
+ &self,
+ _handle: &NativeHandle,
+ _request: ActionRequest,
+ _lease: &crate::InteractionLease,
+ ) -> Result<ActionResult, AdapterError> {
+ Ok(ActionResult::delivered_unverified("click"))
+ }
+}
+
+impl InputOps for CursorAdapter {}
+
+impl SystemOps for CursorAdapter {
+ crate::adapter::guarded_interaction_lease!();
+ crate::adapter::exact_window_focus!();
+
+ fn update_cursor_overlay(&self, control: &CursorOverlayControl) -> Result<(), AdapterError> {
+ if self.fail_presentation {
+ return Err(AdapterError::internal("renderer unavailable"));
+ }
+ self.presented.lock().unwrap().push(control.clone());
+ Ok(())
+ }
+}
+
+fn entry() -> RefEntry {
+ let bounds = crate::Rect {
+ x: 1.0,
+ y: 1.0,
+ width: 20.0,
+ height: 20.0,
+ };
+ RefEntry {
+ process: crate::RefProcess {
+ pid: crate::ProcessId::new(1),
+ process_instance: Some("test-instance".into()),
+ },
+ identity: crate::RefEntryIdentity {
+ role: "button".into(),
+ name: Some("Run".into()),
+ value: None,
+ description: None,
+ native_id: None,
+ },
+ geometry: crate::RefGeometry {
+ bounds: Some(bounds),
+ bounds_hash: bounds.bounds_hash(),
+ },
+ capabilities: crate::RefCapabilities {
+ states: vec![],
+ available_actions: vec![capability::CLICK.into()],
+ },
+ source: crate::RefSource {
+ source_app: Some("Fixture".into()),
+ source_window_id: Some("w-42".into()),
+ source_window_title: Some("Fixture".into()),
+ source_window_bounds_hash: None,
+ source_surface: SnapshotSurface::Window,
+ },
+ scope: crate::RefScope {
+ root_ref: None,
+ path_is_absolute: false,
+ path: smallvec::SmallVec::new(),
+ },
+ }
+}
+
+fn enabled_context() -> CommandContext {
+ let config =
+ crate::CursorOverlayConfig::enabled(Some("Opening menu".into()), 6).expect("valid config");
+ CommandContext::default().with_cursor_overlay_session("test-session", config)
+}
+
+#[test]
+fn enabled_cursor_presents_verified_center_after_dispatch() {
+ let adapter = CursorAdapter::new(false);
+
+ execute_entry_with_context(
+ &adapter,
+ &entry(),
+ ActionRequest::headless(Action::Click),
+ &enabled_context(),
+ )
+ .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 }
+ );
+ assert!(presented[0].instruction().unwrap().is_click());
+ assert_eq!(presented[0].label(), Some("Opening menu"));
+}
+
+#[test]
+fn disabled_and_headed_contexts_do_not_present() {
+ let adapter = CursorAdapter::new(false);
+
+ execute_entry(&adapter, &entry(), ActionRequest::headless(Action::Click))
+ .expect("click succeeds");
+ let headed = enabled_context().with_headed(true);
+ execute_entry_with_context(
+ &adapter,
+ &entry(),
+ ActionRequest::headed(Action::Click),
+ &headed,
+ )
+ .expect("click succeeds");
+
+ assert!(adapter.presented.lock().unwrap().is_empty());
+}
+
+#[test]
+fn renderer_failure_does_not_change_successful_action() {
+ let adapter = CursorAdapter::new(true);
+
+ let result = execute_entry_with_context(
+ &adapter,
+ &entry(),
+ ActionRequest::headless(Action::Click),
+ &enabled_context(),
+ )
+ .expect("presentation failure stays fail-soft");
+
+ assert_eq!(result.action, "click");
+}
diff --git a/crates/core/src/ref_alloc.rs b/crates/core/src/ref_alloc.rs
index e978a1b16..eaa1c4d0d 100644
--- a/crates/core/src/ref_alloc.rs
+++ b/crates/core/src/ref_alloc.rs
@@ -1,5 +1,6 @@
use crate::AccessibilityNode;
use crate::refs::{RefEntry, RefMap};
+use std::collections::HashSet;
pub(crate) use crate::ref_alloc_config::RefAllocConfig;
@@ -159,7 +160,64 @@ pub(crate) fn allocate_refs(
refmap: &mut RefMap,
config: &RefAllocConfig,
) -> Result<AccessibilityNode, crate::AppError> {
- allocate_refs_at_path(node, refmap, config, &mut config.scope.path_prefix.to_vec())
+ let mut skeleton_anchors = HashSet::new();
+ if config.scope.root_ref_id.is_none() {
+ plan_skeleton_anchors(&node, &mut Vec::new(), &mut skeleton_anchors);
+ }
+ allocate_refs_at_path(
+ node,
+ refmap,
+ config,
+ &mut config.scope.path_prefix.to_vec(),
+ &skeleton_anchors,
+ )
+}
+
+fn plan_skeleton_anchors(
+ node: &AccessibilityNode,
+ path: &mut Vec<usize>,
+ anchors: &mut HashSet<Vec<usize>>,
+) -> bool {
+ let mut uncovered_boundary = node.children_count.is_some();
+ for (index, child) in node.children.iter().enumerate() {
+ path.push(index);
+ uncovered_boundary |= plan_skeleton_anchors(child, path, anchors);
+ path.pop();
+ }
+ if !uncovered_boundary {
+ return false;
+ }
+ if can_receive_observed_ref(node) && is_ref_able(node) {
+ return false;
+ }
+ if !path.is_empty() && is_resolvable_skeleton_anchor(node) {
+ anchors.insert(path.clone());
+ return false;
+ }
+ true
+}
+
+fn is_resolvable_skeleton_anchor(node: &AccessibilityNode) -> bool {
+ can_receive_observed_ref(node)
+ && (has_meaningful_text(node.identity.name.as_deref())
+ || has_meaningful_text(node.identity.description.as_deref())
+ || node.identity.native_id.as_ref().is_some_and(|identifier| {
+ identifier.kind != crate::IdentifierKind::Unknown
+ && !identifier.value.trim().is_empty()
+ })
+ || node
+ .presentation
+ .bounds
+ .and_then(|bounds| bounds.bounds_hash())
+ .is_some())
+}
+
+fn can_receive_observed_ref(node: &AccessibilityNode) -> bool {
+ crate::Role::is_canonical(&node.role) && node.role != "unknown"
+}
+
+fn has_meaningful_text(value: Option<&str>) -> bool {
+ value.is_some_and(|text| !text.trim().is_empty())
}
fn allocate_refs_at_path(
@@ -167,6 +225,7 @@ fn allocate_refs_at_path(
refmap: &mut RefMap,
config: &RefAllocConfig,
path: &mut Vec<usize>,
+ skeleton_anchors: &HashSet<Vec<usize>>,
) -> Result<AccessibilityNode, crate::AppError> {
let node_is_ref_able = is_ref_able(&node);
@@ -184,20 +243,7 @@ fn allocate_refs_at_path(
node.ref_id = allocate_observed_ref(refmap, entry)?;
}
- let has_label = node
- .identity
- .name
- .as_deref()
- .is_some_and(|name| !name.is_empty())
- || node
- .identity
- .description
- .as_deref()
- .is_some_and(|description| !description.is_empty());
- let is_skeleton_anchor = !node_is_ref_able
- && node.children_count.is_some()
- && has_label
- && config.scope.root_ref_id.is_none();
+ let is_skeleton_anchor = !node_is_ref_able && skeleton_anchors.contains(path.as_slice());
if is_skeleton_anchor {
let mut entry = ref_entry_from_node(&node, &config.source, None, path);
@@ -216,7 +262,7 @@ fn allocate_refs_at_path(
for (idx, child) in node.children.into_iter().enumerate() {
let collapsible = config.options.compact && is_collapsible(&child);
path.push(idx);
- let child = allocate_refs_at_path(child, refmap, config, path)?;
+ let child = allocate_refs_at_path(child, refmap, config, path, skeleton_anchors)?;
path.pop();
if collapsible {
if let Some(child) = child.children.into_iter().next() {
diff --git a/crates/core/src/refs_store_tests.rs b/crates/core/src/refs_store_tests.rs
index 1ad04353b..53a72c772 100644
--- a/crates/core/src/refs_store_tests.rs
+++ b/crates/core/src/refs_store_tests.rs
@@ -1,5 +1,6 @@
use super::*;
use crate::{
+ ErrorCode,
adapter::SnapshotSurface,
refs::{RefEntry, RefMap},
refs_test_support::HomeGuard,
@@ -74,6 +75,28 @@ fn snapshot_roundtrip_updates_latest_pointer() {
assert_eq!(store.load(None).unwrap().len(), 1);
}
+fn save_snapshot_after_contention(store: &RefStore, name: &str) -> String {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
+ loop {
+ match store.save_new_snapshot(&map_with(name)) {
+ Ok(id) => return id,
+ Err(AppError::Adapter(inner))
+ if inner.code == ErrorCode::Timeout
+ && inner
+ .details
+ .as_ref()
+ .and_then(|details| details.get("kind"))
+ .and_then(serde_json::Value::as_str)
+ == Some("lock_timeout")
+ && std::time::Instant::now() < deadline =>
+ {
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ Err(error) => panic!("contended snapshot save failed: {error:?}"),
+ }
+ }
+}
+
#[test]
fn concurrent_writers_preserve_all_snapshots() {
let _guard = HomeGuard::new();
@@ -83,9 +106,7 @@ fn concurrent_writers_preserve_all_snapshots() {
for i in 0..8 {
let store = store.clone();
handles.push(std::thread::spawn(move || {
- store
- .save_new_snapshot(&map_with(&format!("Snapshot {i}")))
- .unwrap()
+ save_snapshot_after_contention(&store, &format!("Snapshot {i}"))
}));
}
diff --git a/crates/core/src/search_text.rs b/crates/core/src/search_text.rs
index ba676a664..48d74f0c7 100644
--- a/crates/core/src/search_text.rs
+++ b/crates/core/src/search_text.rs
@@ -2,6 +2,9 @@ pub(crate) fn normalize(value: &str) -> String {
let mut normalized = String::with_capacity(value.len());
let mut pending_space = false;
for character in value.chars() {
+ if is_bidirectional_control(character) {
+ continue;
+ }
if character.is_whitespace() {
pending_space = !normalized.is_empty();
continue;
@@ -15,6 +18,13 @@ pub(crate) fn normalize(value: &str) -> String {
normalized
}
+pub(crate) fn is_bidirectional_control(character: char) -> bool {
+ matches!(
+ character,
+ '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
+ )
+}
+
pub(crate) fn contains(haystack: &str, normalized_needle: &str) -> bool {
if normalized_needle.is_empty() {
return true;
diff --git a/crates/core/src/search_text_tests.rs b/crates/core/src/search_text_tests.rs
index af07ea8eb..05186aed9 100644
--- a/crates/core/src/search_text_tests.rs
+++ b/crates/core/src/search_text_tests.rs
@@ -30,6 +30,12 @@ fn contains_handles_non_ascii_text() {
assert!(contains("Résumé", &normalize("rés")));
}
+#[test]
+fn matching_ignores_bidirectional_formatting_controls() {
+ assert_eq!(normalize("\u{200e}WhatsApp"), normalize("WhatsApp"));
+ assert_eq!(normalize("\u{2067}Search\u{2069}"), normalize("Search"));
+}
+
#[test]
fn contains_empty_needle_is_true_not_panic() {
assert!(contains("anything", ""));
diff --git a/crates/core/src/session/manifest.rs b/crates/core/src/session/manifest.rs
index d3d0c943d..4cf26ed1c 100644
--- a/crates/core/src/session/manifest.rs
+++ b/crates/core/src/session/manifest.rs
@@ -1,5 +1,7 @@
use serde::{Deserialize, Serialize};
+use crate::CursorOverlayConfig;
+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionManifest {
pub id: String,
@@ -12,6 +14,8 @@ pub struct SessionManifest {
pub trace: SessionTraceMode,
#[serde(default)]
pub artifacts: ArtifactsMode,
+ #[serde(default, skip_serializing_if = "CursorOverlayConfig::is_disabled")]
+ pub cursor_overlay: CursorOverlayConfig,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
diff --git a/crates/core/src/session/mod.rs b/crates/core/src/session/mod.rs
index 03c3480f9..60b24acaf 100644
--- a/crates/core/src/session/mod.rs
+++ b/crates/core/src/session/mod.rs
@@ -7,7 +7,8 @@ pub use liveness::SessionLivenessLease;
pub use manifest::{ArtifactsMode, SessionManifest, SessionTraceMode};
use crate::{
- AppError, context::validate_session_id, refs::write_private_file, refs_store::RefStore,
+ AppError, CursorOverlayConfig, context::validate_session_id, refs::write_private_file,
+ refs_store::RefStore,
};
use serde_json;
use std::io::ErrorKind;
@@ -100,6 +101,46 @@ pub fn write_manifest(manifest: &SessionManifest) -> Result<(), AppError> {
write_private_file(&manifest_path(&manifest.id)?, json.as_bytes())
}
+pub fn set_cursor_overlay(
+ session_id: &str,
+ cursor_overlay: CursorOverlayConfig,
+) -> Result<SessionManifest, AppError> {
+ let mut manifest = read_manifest(session_id)?.ok_or_else(|| {
+ AppError::invalid_input_with_suggestion(
+ format!("Session '{session_id}' has no manifest"),
+ "Run `session start`, then pass its id with --session.",
+ )
+ })?;
+ if manifest.ended_at.is_some() {
+ return Err(AppError::invalid_input_with_suggestion(
+ format!("Session '{session_id}' has ended"),
+ "Start a new session before changing cursor overlay settings.",
+ ));
+ }
+ manifest.cursor_overlay = cursor_overlay.validated()?;
+ write_manifest(&manifest)?;
+ Ok(manifest)
+}
+
+pub fn cursor_overlay_for_session(
+ session_id: Option<&str>,
+) -> Result<CursorOverlayConfig, AppError> {
+ let Some(session_id) = session_id else {
+ return Ok(CursorOverlayConfig::default());
+ };
+ let config = read_manifest(session_id)?
+ .filter(|manifest| manifest.ended_at.is_none())
+ .map(|manifest| manifest.cursor_overlay)
+ .unwrap_or_default();
+ match config.validated() {
+ Ok(config) => Ok(config),
+ Err(error) => {
+ tracing::warn!(code = %error.code.as_str(), "ignoring invalid session cursor overlay configuration");
+ Ok(CursorOverlayConfig::default())
+ }
+ }
+}
+
pub fn trace_enabled_for_session(session_id: &str) -> Result<bool, AppError> {
Ok(read_manifest(session_id)?.is_some_and(|manifest| manifest.trace_enabled()))
}
@@ -183,6 +224,7 @@ pub fn start_session(options: StartSessionOptions) -> Result<SessionManifest, Ap
ended_at: None,
trace: options.trace,
artifacts: options.artifacts,
+ cursor_overlay: CursorOverlayConfig::default(),
};
write_manifest(&manifest)?;
Ok(manifest)
diff --git a/crates/core/src/session/session_tests.rs b/crates/core/src/session/session_tests.rs
index 6b7772666..a6a5558a2 100644
--- a/crates/core/src/session/session_tests.rs
+++ b/crates/core/src/session/session_tests.rs
@@ -45,6 +45,7 @@ fn manifest_round_trips_with_optional_fields() {
ended_at: None,
trace: SessionTraceMode::On,
artifacts: ArtifactsMode::Events,
+ cursor_overlay: crate::CursorOverlayConfig::default(),
};
write_manifest(&manifest).unwrap();
let loaded = read_manifest("run-1").unwrap().expect("manifest");
diff --git a/crates/core/src/skeleton_anchor_tests.rs b/crates/core/src/skeleton_anchor_tests.rs
new file mode 100644
index 000000000..f9af29394
--- /dev/null
+++ b/crates/core/src/skeleton_anchor_tests.rs
@@ -0,0 +1,91 @@
+use super::*;
+
+#[test]
+fn native_id_ancestor_covers_unnamed_boundaries() {
+ let mut split_view = node("group");
+ split_view.identity.native_id = Some(crate::ElementIdentifier {
+ kind: crate::IdentifierKind::AxIdentifier,
+ value: "main, SidebarNavigationSplitView".into(),
+ });
+ split_view.children = (0..3)
+ .map(|_| {
+ let mut boundary = node("group");
+ boundary.children_count = Some(1);
+ boundary
+ })
+ .collect();
+ let mut root = node("window");
+ root.children = vec![split_view];
+
+ let mut refmap = RefMap::new();
+ let result = ref_alloc::allocate_refs(root, &mut refmap, &run_config(false, false)).unwrap();
+
+ let split_view = &result.children[0];
+ assert!(split_view.ref_id.is_some());
+ assert!(
+ split_view
+ .children
+ .iter()
+ .all(|boundary| boundary.ref_id.is_none())
+ );
+ let entry = refmap.get(split_view.ref_id.as_deref().unwrap()).unwrap();
+ assert_eq!(
+ entry
+ .identity
+ .native_id
+ .as_ref()
+ .map(|identifier| identifier.value.as_str()),
+ Some("main, SidebarNavigationSplitView")
+ );
+}
+
+#[test]
+fn unlabeled_bounded_boundary_gets_drill_ref() {
+ let mut boundary = node("group");
+ boundary.children_count = Some(5);
+ boundary.presentation.bounds = Some(crate::Rect {
+ x: 10.0,
+ y: 20.0,
+ width: 300.0,
+ height: 400.0,
+ });
+ let mut root = node("window");
+ root.children = vec![boundary];
+
+ let mut refmap = RefMap::new();
+ let result = ref_alloc::allocate_refs(root, &mut refmap, &run_config(false, false)).unwrap();
+
+ let boundary = &result.children[0];
+ assert!(boundary.ref_id.is_some());
+ assert!(boundary.presentation.bounds.is_none());
+ let entry = refmap.get(boundary.ref_id.as_deref().unwrap()).unwrap();
+ assert!(entry.geometry.bounds.is_none());
+ assert!(entry.geometry.bounds_hash.is_some());
+}
+
+#[test]
+fn deepest_resolvable_anchor_wins() {
+ let mut boundary = node("group");
+ boundary.children_count = Some(5);
+ boundary.presentation.bounds = Some(crate::Rect {
+ x: 10.0,
+ y: 20.0,
+ width: 300.0,
+ height: 400.0,
+ });
+ let mut split_view = node("group");
+ split_view.identity.native_id = Some(crate::ElementIdentifier {
+ kind: crate::IdentifierKind::AxIdentifier,
+ value: "split-view".into(),
+ });
+ split_view.children = vec![boundary];
+ let mut root = node("window");
+ root.children = vec![split_view];
+
+ let mut refmap = RefMap::new();
+ let result = ref_alloc::allocate_refs(root, &mut refmap, &run_config(false, false)).unwrap();
+
+ assert!(result.children[0].ref_id.is_none());
+ assert!(result.children[0].children[0].ref_id.is_some());
+ assert_eq!(refmap.len(), 1);
+}
diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rs
index b1b6e8cfa..1627d8135 100644
--- a/crates/core/src/snapshot.rs
+++ b/crates/core/src/snapshot.rs
@@ -97,7 +97,7 @@ pub(crate) fn resolve_window_for_surface(
crate::window_lookup::select_surface_owner(
windows_for_app(adapter, app_name, deadline)?,
crate::AdapterError::new(
- crate::ErrorCode::AppNotFound,
+ crate::ErrorCode::WindowNotFound,
format!(
"No window found to identify the application owning surface '{}'",
surface.as_str()
@@ -115,21 +115,7 @@ fn windows_for_app(
focused_only: app_name.is_none(),
app: app_name.map(str::to_string),
};
- Ok(windows_matching_app(
- adapter.list_windows(&filter, deadline)?,
- app_name,
- ))
-}
-
-/// The adapter filter is advisory, so the app name is applied again here.
-fn windows_matching_app(windows: Vec<WindowInfo>, app_name: Option<&str>) -> Vec<WindowInfo> {
- match app_name {
- Some(app) => windows
- .into_iter()
- .filter(|window| window.app.eq_ignore_ascii_case(app))
- .collect(),
- None => windows,
- }
+ Ok(adapter.list_windows(&filter, deadline)?)
}
pub(crate) fn resolve_window(
@@ -157,11 +143,12 @@ pub(crate) fn resolve_window(
})
} else if let Some(app) = app_name {
crate::window_lookup::select_window(
- windows_matching_app(windows, app_name),
+ windows,
crate::AdapterError::new(
- crate::ErrorCode::AppNotFound,
- format!("No window found for app '{app}'"),
- ),
+ crate::ErrorCode::WindowNotFound,
+ format!("Application '{app}' is running but has no matching window"),
+ )
+ .with_suggestion("Wait for the app to present a window, or run 'list-windows --app'."),
"More than one window matches the target",
)
} else {
@@ -230,3 +217,7 @@ pub(crate) fn emit_snapshot_saved(
#[cfg(test)]
#[path = "snapshot_tests.rs"]
mod tests;
+
+#[cfg(test)]
+#[path = "snapshot_window_tests.rs"]
+mod window_tests;
diff --git a/crates/core/src/snapshot_ref.rs b/crates/core/src/snapshot_ref.rs
index ad764b619..11bfed6f5 100644
--- a/crates/core/src/snapshot_ref.rs
+++ b/crates/core/src/snapshot_ref.rs
@@ -1,6 +1,6 @@
use crate::{
AppError,
- adapter::{PlatformAdapter, TreeOptions},
+ adapter::{PlatformAdapter, TreeOptions, WindowFilter},
context::CommandContext,
live_locator::{ObservationRequest, ObservationRoot},
ref_alloc::{self, RefAllocConfig},
@@ -45,6 +45,7 @@ pub fn run_from_ref_with_context(
.clone();
let deadline = crate::Deadline::after(3_000)?;
+ let window = resolve_result_window(&entry, adapter, deadline)?;
let handle = adapter.resolve_element_strict(&entry, deadline)?;
let observation_options = opts.with_ref_identity_bounds();
@@ -106,17 +107,6 @@ pub fn run_from_ref_with_context(
})
})?;
- let instance = entry.process.process_instance.as_deref().ok_or_else(|| {
- AppError::Adapter(crate::AdapterError::stale_ref(
- "root ref has no process-instance identity",
- ))
- })?;
- let window = crate::window_lookup::find_window_for_process(
- crate::ProcessIdentity::new(entry.process.pid, instance),
- adapter,
- deadline,
- )?;
-
Ok(SnapshotResult {
tree,
refmap,
@@ -127,6 +117,48 @@ pub fn run_from_ref_with_context(
})
}
+/// The drill result reports the window the ref was captured from, so it must
+/// resolve that exact window — not any window of the process. Resolving before
+/// observation keeps a failed drill from persisting refs it never returns.
+fn resolve_result_window(
+ entry: &crate::refs::RefEntry,
+ adapter: &dyn PlatformAdapter,
+ deadline: crate::Deadline,
+) -> Result<crate::WindowInfo, AppError> {
+ let Some(window_id) = entry.source.source_window_id.as_deref() else {
+ let instance = entry.process.process_instance.as_deref().ok_or_else(|| {
+ AppError::Adapter(crate::AdapterError::stale_ref(
+ "root ref has no process-instance identity",
+ ))
+ })?;
+ return crate::window_lookup::find_window_for_process(
+ crate::ProcessIdentity::new(entry.process.pid, instance),
+ adapter,
+ deadline,
+ );
+ };
+ let candidates = adapter
+ .list_windows(
+ &WindowFilter {
+ focused_only: false,
+ app: None,
+ },
+ deadline,
+ )?
+ .into_iter()
+ .filter(|window| window.id == window_id && window.pid == entry.process.pid)
+ .collect();
+ crate::window_lookup::select_window(
+ candidates,
+ crate::AdapterError::new(
+ crate::ErrorCode::WindowNotFound,
+ format!("Source window '{window_id}' was not found"),
+ )
+ .with_suggestion("Run 'snapshot' to refresh, then retry with an updated ref"),
+ "Multiple windows matched the source window ID",
+ )
+}
+
/// A drill-down replaces refs inside an existing snapshot, so it must observe
/// its whole subtree or leave the stored map untouched. Partial projection is
/// only safe for a full snapshot, which writes a fresh map and destroys nothing.
diff --git a/crates/core/src/snapshot_ref_tests.rs b/crates/core/src/snapshot_ref_tests.rs
index 9d1e8501e..9e9a95a69 100644
--- a/crates/core/src/snapshot_ref_tests.rs
+++ b/crates/core/src/snapshot_ref_tests.rs
@@ -54,6 +54,7 @@ struct StubAdapter {
subtree_error: Option<AdapterError>,
resolve_calls: AtomicU32,
drops: Arc<AtomicU32>,
+ windows: Vec<crate::WindowInfo>,
}
impl StubAdapter {
@@ -63,6 +64,17 @@ impl StubAdapter {
subtree_error: None,
resolve_calls: AtomicU32::new(0),
drops: Arc::new(AtomicU32::new(0)),
+ windows: vec![window_info("w-42", true)],
+ }
+ }
+
+ fn with_windows(subtree: AccessibilityNode, windows: Vec<crate::WindowInfo>) -> Self {
+ Self {
+ subtree,
+ subtree_error: None,
+ resolve_calls: AtomicU32::new(0),
+ drops: Arc::new(AtomicU32::new(0)),
+ windows,
}
}
@@ -72,10 +84,26 @@ impl StubAdapter {
subtree_error: Some(error),
resolve_calls: AtomicU32::new(0),
drops: Arc::new(AtomicU32::new(0)),
+ windows: vec![window_info("w-42", true)],
}
}
}
+fn window_info(id: &str, focused: bool) -> crate::WindowInfo {
+ crate::WindowInfo {
+ id: id.into(),
+ title: "Test".into(),
+ app: "TestApp".into(),
+ pid: crate::ProcessId::new(42),
+ process_instance: Some("test-instance".into()),
+ bounds: None,
+ state: crate::WindowState {
+ is_focused: focused,
+ ..Default::default()
+ },
+ }
+}
+
impl ObservationOps for StubAdapter {
fn observe_tree(
&self,
@@ -93,18 +121,7 @@ impl ObservationOps for StubAdapter {
_filter: &crate::adapter::WindowFilter,
_deadline: crate::Deadline,
) -> Result<Vec<crate::WindowInfo>, AdapterError> {
- Ok(vec![crate::WindowInfo {
- id: "w-42".into(),
- title: "Test".into(),
- app: "TestApp".into(),
- pid: crate::ProcessId::new(42),
- process_instance: Some("test-instance".into()),
- bounds: None,
- state: crate::WindowState {
- is_focused: true,
- ..Default::default()
- },
- }])
+ Ok(self.windows.clone())
}
fn resolve_element_strict(
@@ -335,5 +352,8 @@ fn test_run_from_ref_re_drill_replaces_drill_refs_only() {
);
}
+#[path = "snapshot_ref_window_tests.rs"]
+mod window_tests;
+
#[path = "snapshot_ref_merge_tests.rs"]
mod merge_tests;
diff --git a/crates/core/src/snapshot_ref_window_tests.rs b/crates/core/src/snapshot_ref_window_tests.rs
new file mode 100644
index 000000000..7f2480f9a
--- /dev/null
+++ b/crates/core/src/snapshot_ref_window_tests.rs
@@ -0,0 +1,57 @@
+use super::*;
+
+fn seed_skeleton_refmap_on_window(window_id: Option<&'static str>) -> RefMap {
+ let src = crate::ref_alloc_source::RefAllocSource {
+ window_id,
+ ..source("TestApp")
+ };
+ let mut map = RefMap::new();
+ let anchor = ref_entry_from_node(&named("group", "Sidebar"), &src, None, &[0]);
+ let _ = map.allocate(anchor);
+ let other = ref_entry_from_node(&named("button", "Toolbar"), &src, None, &[1]);
+ let _ = map.allocate(other);
+ map
+}
+
+#[test]
+fn test_run_from_ref_resolves_source_window_among_same_process_windows() {
+ let _guard = HomeGuard::new();
+ let snapshot_id = save_latest(seed_skeleton_refmap_on_window(Some("w-467")));
+
+ let subtree = named("button", "Save");
+ let adapter = StubAdapter::with_windows(
+ subtree,
+ vec![window_info("w-467", false), window_info("w-475", false)],
+ );
+
+ let result = run_from_ref(&adapter, &drill_opts(), "@e1", Some(&snapshot_id))
+ .expect("drill must resolve its own source window, not the process");
+ assert_eq!(result.window.id, "w-467");
+}
+
+#[test]
+fn test_run_from_ref_does_not_persist_refs_when_source_window_is_gone() {
+ let _guard = HomeGuard::new();
+ let snapshot_id = save_latest(seed_skeleton_refmap_on_window(Some("w-gone")));
+
+ let subtree = named("button", "Save");
+ let adapter = StubAdapter::with_windows(subtree, vec![window_info("w-475", true)]);
+
+ let result = run_from_ref(&adapter, &drill_opts(), "@e1", Some(&snapshot_id));
+ let err = match result {
+ Ok(_) => panic!("drill must fail when its source window is gone"),
+ Err(e) => e,
+ };
+ match err {
+ AppError::Adapter(adapter_err) => {
+ assert_eq!(adapter_err.code, crate::ErrorCode::WindowNotFound);
+ }
+ other => panic!("expected Adapter(WindowNotFound), got {other:?}"),
+ }
+ let on_disk = load_latest();
+ assert_eq!(
+ on_disk.len(),
+ 2,
+ "seed refs only; a failed drill must not persist refs"
+ );
+}
diff --git a/crates/core/src/snapshot_tests.rs b/crates/core/src/snapshot_tests.rs
index 299550222..65cbc92b1 100644
--- a/crates/core/src/snapshot_tests.rs
+++ b/crates/core/src/snapshot_tests.rs
@@ -346,3 +346,6 @@ fn test_skeleton_fixture_matches_golden() {
"interactive textfield should be @e4"
);
}
+
+#[path = "skeleton_anchor_tests.rs"]
+mod skeleton_anchor_tests;
diff --git a/crates/core/src/snapshot_window_tests.rs b/crates/core/src/snapshot_window_tests.rs
new file mode 100644
index 000000000..4f7c843ab
--- /dev/null
+++ b/crates/core/src/snapshot_window_tests.rs
@@ -0,0 +1,64 @@
+use super::*;
+use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps};
+
+struct WindowAdapter {
+ windows: Vec<WindowInfo>,
+}
+
+impl ObservationOps for WindowAdapter {
+ fn list_windows(
+ &self,
+ _filter: &WindowFilter,
+ _deadline: crate::Deadline,
+ ) -> Result<Vec<WindowInfo>, crate::AdapterError> {
+ Ok(self.windows.clone())
+ }
+}
+
+impl ActionOps for WindowAdapter {}
+impl InputOps for WindowAdapter {}
+impl SystemOps for WindowAdapter {}
+
+fn window(app: &str) -> WindowInfo {
+ WindowInfo {
+ id: "w-1".into(),
+ title: "WhatsApp".into(),
+ app: app.into(),
+ pid: crate::ProcessId::new(10),
+ process_instance: Some("instance-10".into()),
+ bounds: None,
+ state: Default::default(),
+ }
+}
+
+#[test]
+fn adapter_owned_app_resolution_preserves_bundle_identifier_matches() {
+ let adapter = WindowAdapter {
+ windows: vec![window("WhatsApp")],
+ };
+
+ let resolved = resolve_window(
+ &adapter,
+ Some("net.whatsapp.WhatsApp"),
+ None,
+ crate::Deadline::after(100).unwrap(),
+ )
+ .unwrap();
+
+ assert_eq!(resolved.id, "w-1");
+}
+
+#[test]
+fn running_application_without_a_window_is_not_reported_as_absent() {
+ let adapter = WindowAdapter { windows: vec![] };
+
+ let error = resolve_window(
+ &adapter,
+ Some("WhatsApp"),
+ None,
+ crate::Deadline::after(100).unwrap(),
+ )
+ .unwrap_err();
+
+ assert_eq!(error.code(), "WINDOW_NOT_FOUND");
+}
diff --git a/crates/core/src/window_filter.rs b/crates/core/src/window_filter.rs
index 75a6b6da4..6c4a11d62 100644
--- a/crates/core/src/window_filter.rs
+++ b/crates/core/src/window_filter.rs
@@ -1,5 +1,7 @@
#[derive(Debug, Clone, Default)]
pub struct WindowFilter {
pub focused_only: bool,
+ /// Exact application identity enforced by the platform adapter. Adapters
+ /// may resolve this against display names, bundle identifiers, or PIDs.
pub app: Option<String>,
}
diff --git a/crates/ffi/src/observation/is.rs b/crates/ffi/src/observation/is.rs
index f4e78c28b..57f2c4e7c 100644
--- a/crates/ffi/src/observation/is.rs
+++ b/crates/ffi/src/observation/is.rs
@@ -10,6 +10,7 @@ enum SupportedProperty {
Focused,
Disabled,
Enabled,
+ Selected,
}
impl SupportedProperty {
@@ -18,6 +19,7 @@ impl SupportedProperty {
"focused" => Some(Self::Focused),
"disabled" => Some(Self::Disabled),
"enabled" => Some(Self::Enabled),
+ "selected" => Some(Self::Selected),
_ => None,
}
}
@@ -32,6 +34,7 @@ impl SupportedProperty {
Self::Focused => contains("focused"),
Self::Disabled => contains("disabled"),
Self::Enabled => !contains("disabled"),
+ Self::Selected => contains("selected"),
}
}
}
@@ -123,7 +126,7 @@ unsafe fn is_in_window(
None => {
let error = agent_desktop_core::AdapterError::new(
agent_desktop_core::ErrorCode::InvalidArgs,
- "unknown property — expected one of: focused, disabled, enabled",
+ "unknown property — expected one of: focused, disabled, enabled, selected",
);
set_last_error(&error);
return AdResult::ErrInvalidArgs;
@@ -189,7 +192,9 @@ mod tests {
}
#[test]
- fn rejects_unknown_properties() {
- assert!(SupportedProperty::parse("selected").is_none());
+ fn selected_property_evaluates_normalized_state() {
+ let property = SupportedProperty::parse("selected").expect("selected must be supported");
+ assert!(property.evaluate(&[String::from("SeLeCtEd")]));
+ assert!(!property.evaluate(&[]));
}
}
diff --git a/crates/ffi/src/observation/is_abi_tests.rs b/crates/ffi/src/observation/is_abi_tests.rs
index 8e33f294d..cfe2f9cca 100644
--- a/crates/ffi/src/observation/is_abi_tests.rs
+++ b/crates/ffi/src/observation/is_abi_tests.rs
@@ -25,7 +25,10 @@ impl ObservationOps for DuplicateAdapter {
));
};
ObservedTree::from_roots(
- vec![button(Vec::new()), button(vec!["disabled".into()])],
+ vec![
+ button(vec!["selected".into()]),
+ button(vec!["disabled".into()]),
+ ],
ObservationSource::Window {
window: window.clone(),
surface: agent_desktop_core::SnapshotSurface::Window,
@@ -130,3 +133,22 @@ fn last_and_nth_selection_are_applied_at_the_c_boundary() {
}
unsafe { crate::adapter::ad_adapter_destroy(adapter) };
}
+
+#[test]
+fn first_selection_reports_selected_at_the_c_boundary() {
+ let adapter = crate::adapter::register_adapter(AdAdapter {
+ inner: Box::new(DuplicateAdapter),
+ session_id: None,
+ _session_lease: None,
+ })
+ .unwrap();
+ let mut query = query();
+ query.control.selection.kind = AdFindSelectionKind::First as i32;
+ let mut out = false;
+
+ let result = unsafe { ad_is_exact(adapter, &window(), &query, c"selected".as_ptr(), &mut out) };
+
+ unsafe { crate::adapter::ad_adapter_destroy(adapter) };
+ assert_eq!(result, AdResult::Ok);
+ assert!(out);
+}
diff --git a/crates/macos/build.rs b/crates/macos/build.rs
index 10196c417..783350f08 100644
--- a/crates/macos/build.rs
+++ b/crates/macos/build.rs
@@ -5,6 +5,8 @@ fn main() {
println!("cargo:rerun-if-changed=src/system/launch_bridge.m");
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_display_bridge.m");
println!("cargo:rerun-if-env-changed=TARGET");
println!("cargo:rerun-if-env-changed=MACOSX_DEPLOYMENT_TARGET");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("macos") {
@@ -21,7 +23,41 @@ fn main() {
let object = out_dir.join("launch_bridge.o");
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_display_object = out_dir.join("cursor_overlay_display_bridge.o");
let archive = out_dir.join("libagent_desktop_launch_bridge.a");
+ 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_display_bridge.m",
+ "-o",
+ ])
+ .arg(&cursor_overlay_display_object),
+ "compile Objective-C cursor overlay display 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_bridge.m",
+ "-o",
+ ])
+ .arg(&cursor_overlay_object),
+ "compile Objective-C cursor overlay bridge",
+ );
run(
Command::new("xcrun")
.args(["--sdk", "macosx", "clang"])
@@ -76,12 +112,15 @@ fn main() {
.arg(&archive)
.arg(&object)
.arg(&appkit_object)
- .arg(&screen_object),
+ .arg(&screen_object)
+ .arg(&cursor_overlay_object)
+ .arg(&cursor_overlay_display_object),
"archive Objective-C launch bridge",
);
println!("cargo:rustc-link-search=native={}", out_dir.display());
println!("cargo:rustc-link-lib=static=agent_desktop_launch_bridge");
println!("cargo:rustc-link-lib=framework=AppKit");
+ println!("cargo:rustc-link-lib=framework=QuartzCore");
}
fn required_target() -> String {
diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rs
index 3388791c4..37ca9eaf3 100644
--- a/crates/macos/src/system/adapter.rs
+++ b/crates/macos/src/system/adapter.rs
@@ -9,6 +9,17 @@ use agent_desktop_core::{
use crate::adapter::MacOSAdapter;
impl SystemOps for MacOSAdapter {
+ fn update_cursor_overlay(
+ &self,
+ control: &agent_desktop_core::CursorOverlayControl,
+ ) -> Result<(), AdapterError> {
+ crate::system::cursor_overlay::update(control)
+ }
+
+ fn run_cursor_overlay_child(&self) -> Option<Result<(), AdapterError>> {
+ crate::system::cursor_overlay::entry_from_env()
+ }
+
fn acquire_interaction_lease(
&self,
deadline: Deadline,
diff --git a/crates/macos/src/system/app_inventory.rs b/crates/macos/src/system/app_inventory.rs
index b7e7512f2..ef8c13fa7 100644
--- a/crates/macos/src/system/app_inventory.rs
+++ b/crates/macos/src/system/app_inventory.rs
@@ -251,7 +251,7 @@ fn sort_apps(apps: &mut [AppInfo]) {
fn matching_pids(apps: &[AppInfo], app_name: &str) -> Vec<ProcessId> {
let mut pids = apps
.iter()
- .filter(|app| app.name.eq_ignore_ascii_case(app_name))
+ .filter(|app| agent_desktop_core::app_name_matches(&app.name, app_name))
.map(|app| app.pid)
.collect::<Vec<_>>();
pids.sort_unstable();
diff --git a/crates/macos/src/system/cg_window.rs b/crates/macos/src/system/cg_window.rs
index fbf2dbb06..ccaa3070e 100644
--- a/crates/macos/src/system/cg_window.rs
+++ b/crates/macos/src/system/cg_window.rs
@@ -44,16 +44,14 @@ impl WindowRecord {
#[derive(Clone, Copy)]
pub(crate) enum WindowRecordScope<'a> {
- App(&'a str),
Pid(i32),
Pids(&'a rustc_hash::FxHashSet<i32>),
Window(i64),
}
impl WindowRecordScope<'_> {
- fn matches(self, app_name: &str, pid: i32, window_number: i64) -> bool {
+ fn matches(self, pid: i32, window_number: i64) -> bool {
match self {
- Self::App(expected) => app_name.eq_ignore_ascii_case(expected),
Self::Pid(expected) => pid == expected,
Self::Pids(expected) => expected.contains(&pid),
Self::Window(expected) => window_number == expected,
@@ -141,7 +139,7 @@ pub(super) fn records_from_dictionaries(
continue;
}
let window_number = required_int_field(&dictionary, "kCGWindowNumber")?;
- if !scope.matches(&app_name, pid, window_number) {
+ if !scope.matches(pid, window_number) {
continue;
}
let bounds = rect_field(&dictionary, "kCGWindowBounds")
diff --git a/crates/macos/src/system/cg_window_tests.rs b/crates/macos/src/system/cg_window_tests.rs
index 1a305c67e..63caab766 100644
--- a/crates/macos/src/system/cg_window_tests.rs
+++ b/crates/macos/src/system/cg_window_tests.rs
@@ -72,8 +72,9 @@ fn persistent_window_churn_times_out_with_exact_attempt_metrics() {
#[test]
fn scoped_capture_never_probes_an_unrelated_inaccessible_owner() {
+ let eligible = rustc_hash::FxHashSet::from_iter([10]);
let mut records = vec![record("Target", 10, 7, true), record("Other", 418, 8, true)];
- retain_scope(&mut records, WindowRecordScope::App("Target"));
+ retain_scope(&mut records, WindowRecordScope::Pids(&eligible));
let mut probed = Vec::new();
capture_process_instances_with(
@@ -108,11 +109,12 @@ fn scoped_capture_propagates_the_selected_owners_denial() {
}
#[test]
-fn app_scope_keeps_all_matching_processes_and_ignores_unrelated_churn() {
+fn pid_set_scope_keeps_all_matching_processes_and_ignores_unrelated_churn() {
+ let eligible = rustc_hash::FxHashSet::from_iter([10, 11]);
let mut first = vec![record("Target", 10, 7, true), record("Other", 20, 8, false)];
let mut second = vec![record("Target", 10, 7, true), record("Other", 20, 8, true)];
- retain_scope(&mut first, WindowRecordScope::App("Target"));
- retain_scope(&mut second, WindowRecordScope::App("Target"));
+ retain_scope(&mut first, WindowRecordScope::Pids(&eligible));
+ retain_scope(&mut second, WindowRecordScope::Pids(&eligible));
first.push(record("Target", 11, 9, true));
second.push(record("Target", 11, 9, true));
@@ -171,10 +173,11 @@ fn pid_set_scope_excludes_ineligible_owners_before_identity_reads() {
#[test]
fn target_churn_remains_visible_after_scoping() {
+ let eligible = rustc_hash::FxHashSet::from_iter([10]);
let mut first = vec![record("Target", 10, 7, false)];
let mut second = vec![record("Target", 10, 7, true)];
- retain_scope(&mut first, WindowRecordScope::App("Target"));
- retain_scope(&mut second, WindowRecordScope::App("Target"));
+ retain_scope(&mut first, WindowRecordScope::Pids(&eligible));
+ retain_scope(&mut second, WindowRecordScope::Pids(&eligible));
assert_ne!(inventory_signature(&first), inventory_signature(&second));
}
@@ -203,7 +206,7 @@ fn records_fixture(visible: bool) -> Vec<WindowRecord> {
}
fn retain_scope(records: &mut Vec<WindowRecord>, scope: WindowRecordScope<'_>) {
- records.retain(|record| scope.matches(&record.app_name, record.pid, record.window_number));
+ records.retain(|record| scope.matches(record.pid, record.window_number));
}
fn record(app_name: &str, pid: i32, window_number: i64, visible: bool) -> WindowRecord {
diff --git a/crates/macos/src/system/cursor_overlay/bridge.rs b/crates/macos/src/system/cursor_overlay/bridge.rs
new file mode 100644
index 000000000..472deac92
--- /dev/null
+++ b/crates/macos/src/system/cursor_overlay/bridge.rs
@@ -0,0 +1,122 @@
+use agent_desktop_core::{AdapterError, CursorOverlayInstruction, ErrorCode, Point, Rect};
+use std::ffi::{CString, c_char};
+
+const CLICK: u8 = 1 << 1;
+const REDUCE_MOTION: u8 = 1 << 2;
+
+#[repr(C)]
+struct NativeRenderConfig {
+ frame_seconds: f64,
+ label: *const c_char,
+ bubble_x: f64,
+ bubble_y: f64,
+ flags: u8,
+}
+
+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,
+ config: *const NativeRenderConfig,
+ ) -> bool;
+ fn agent_desktop_cursor_overlay_idle();
+ fn agent_desktop_cursor_overlay_hide();
+ fn agent_desktop_cursor_overlay_show();
+ fn agent_desktop_cursor_overlay_stop();
+}
+
+pub(super) fn initial_point() -> Result<Point, AdapterError> {
+ let mut output = [0.0; 2];
+ if !unsafe { agent_desktop_cursor_overlay_initial_point(output.as_mut_ptr()) } {
+ return Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ "macOS cursor overlay could not select an initial position",
+ ));
+ }
+ Ok(Point {
+ x: output[0],
+ y: output[1],
+ })
+}
+
+pub(super) fn screen_at(point: &Point) -> Result<(Rect, u32, bool), AdapterError> {
+ let mut output = [0.0; 6];
+ if !unsafe { agent_desktop_cursor_overlay_screen(point.x, point.y, output.as_mut_ptr()) } {
+ return Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ "No macOS display contains the cursor overlay destination",
+ ));
+ }
+ Ok((
+ Rect {
+ x: output[0],
+ y: output[1],
+ width: output[2],
+ height: output[3],
+ },
+ (output[4] as u32).clamp(60, 120),
+ output[5] != 0.0,
+ ))
+}
+
+pub(super) fn run(
+ points: &[Point],
+ fps: u32,
+ instruction: &CursorOverlayInstruction,
+ reduce_motion: bool,
+ bubble: &Rect,
+) -> Result<(), AdapterError> {
+ let native_points = points
+ .iter()
+ .flat_map(|point| [point.x, point.y])
+ .collect::<Vec<_>>();
+ let label = instruction
+ .label()
+ .map(|value| CString::new(value.replace('\0', " ")))
+ .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 config = NativeRenderConfig {
+ frame_seconds: 1.0 / f64::from(fps),
+ label: label
+ .as_ref()
+ .map_or(std::ptr::null(), |value| value.as_ptr()),
+ bubble_x: bubble.x,
+ bubble_y: bubble.y,
+ flags,
+ };
+ if unsafe {
+ agent_desktop_cursor_overlay_run(native_points.as_ptr(), native_points.len() / 2, &config)
+ } {
+ Ok(())
+ } else {
+ Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ "macOS cursor overlay renderer failed",
+ ))
+ }
+}
+
+pub(super) fn idle() {
+ unsafe { agent_desktop_cursor_overlay_idle() }
+}
+
+pub(super) fn stop() {
+ unsafe { agent_desktop_cursor_overlay_stop() }
+}
+
+pub(super) fn hide() {
+ unsafe { agent_desktop_cursor_overlay_hide() }
+}
+
+pub(super) fn show() {
+ unsafe { agent_desktop_cursor_overlay_show() }
+}
diff --git a/crates/macos/src/system/cursor_overlay/child.rs b/crates/macos/src/system/cursor_overlay/child.rs
new file mode 100644
index 000000000..80f2a8ed7
--- /dev/null
+++ b/crates/macos/src/system/cursor_overlay/child.rs
@@ -0,0 +1,244 @@
+use agent_desktop_core::{
+ AdapterError, CursorMotion, CursorOverlayConfig, CursorOverlayControl,
+ CursorOverlayInstruction, ErrorCode, Point, place_label,
+};
+use std::io::{Read, Write};
+use std::os::unix::fs::PermissionsExt;
+use std::os::unix::net::UnixListener;
+use std::path::{Path, PathBuf};
+use std::thread;
+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);
+
+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(_) => Some(Err(AdapterError::internal(
+ "Invalid cursor overlay child protocol marker",
+ ))),
+ }
+}
+
+fn run() -> Result<(), AdapterError> {
+ let initial = read_control(std::io::stdin())?;
+ let socket = socket_path(&initial)?;
+ prepare_socket(&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())
+ })?;
+ std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600)).map_err(|error| {
+ AdapterError::internal("Could not protect the cursor overlay session socket")
+ .with_platform_detail(error.to_string())
+ })?;
+ listener.set_nonblocking(true).map_err(|error| {
+ 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);
+ }
+ loop {
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ let Ok(control) = read_control(&mut stream) else {
+ continue;
+ };
+ if control.session_id() != initial.session_id() {
+ continue;
+ }
+ if control.is_disable() {
+ drop(listener);
+ cleanup(socket)?;
+ let _ = stream.write_all(&[1]);
+ return Ok(());
+ }
+ if handle(&control, &mut current).is_err() {
+ continue;
+ }
+ if control.is_hide() {
+ let _ = stream.write_all(&[1]);
+ }
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ bridge::idle();
+ thread::sleep(Duration::from_millis(8));
+ }
+ Err(error) => {
+ let _ = cleanup(socket);
+ return Err(
+ AdapterError::internal("Cursor overlay session socket failed")
+ .with_platform_detail(error.to_string()),
+ );
+ }
+ }
+ }
+}
+
+fn handle(
+ control: &CursorOverlayControl,
+ current: &mut Option<Point>,
+) -> Result<bool, AdapterError> {
+ control.validate()?;
+ if control.is_disable() {
+ return Ok(false);
+ }
+ if control.is_hide() {
+ bridge::hide();
+ return Ok(true);
+ }
+ if control.is_show() {
+ bridge::show();
+ return Ok(true);
+ }
+ let owned;
+ let instruction = if let Some(instruction) = control.instruction() {
+ instruction
+ } else {
+ let config = CursorOverlayConfig::enabled(control.label().map(str::to_owned), 12)?;
+ owned = CursorOverlayInstruction::new(bridge::initial_point()?, &config, false)?;
+ &owned
+ };
+ render(instruction, current)?;
+ *current = Some(instruction.destination().clone());
+ Ok(true)
+}
+
+fn render(
+ instruction: &CursorOverlayInstruction,
+ current: &Option<Point>,
+) -> 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()]
+ } else {
+ motion_points(current.as_ref(), instruction.destination(), &screen, fps)
+ };
+ bridge::run(&points, fps, instruction, reduce_motion, &bubble)
+}
+
+fn motion_points(
+ current: Option<&Point>,
+ destination: &Point,
+ screen: &agent_desktop_core::Rect,
+ fps: u32,
+) -> Vec<Point> {
+ let start = current.cloned().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 frame_ms = 1_000.0 / f64::from(fps);
+ let frame_count = (motion.duration_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)
+ })
+ .collect()
+}
+
+fn read_control(reader: impl Read) -> Result<CursorOverlayControl, AdapterError> {
+ let mut payload = Vec::new();
+ reader
+ .take(MAX_INSTRUCTION_BYTES + 1)
+ .read_to_end(&mut payload)
+ .map_err(|error| {
+ AdapterError::internal("Could not read cursor overlay control")
+ .with_platform_detail(error.to_string())
+ })?;
+ if payload.len() as u64 > MAX_INSTRUCTION_BYTES {
+ return Err(AdapterError::internal(
+ "Cursor overlay instruction exceeds the transport limit",
+ ));
+ }
+ let control: CursorOverlayControl = serde_json::from_slice(&payload).map_err(|error| {
+ AdapterError::internal("Could not decode cursor overlay control")
+ .with_platform_detail(error.to_string())
+ })?;
+ control.validate()?;
+ Ok(control)
+}
+
+fn socket_path(control: &CursorOverlayControl) -> Result<PathBuf, AdapterError> {
+ let expected = super::endpoint::path(control.session_id())?;
+ let supplied = std::env::var_os(SOCKET_ENV)
+ .map(PathBuf::from)
+ .ok_or_else(|| AdapterError::internal("Cursor overlay child socket is missing"))?;
+ if supplied != expected {
+ return Err(AdapterError::new(
+ ErrorCode::InvalidArgs,
+ "Cursor overlay child socket does not match its session",
+ ));
+ }
+ Ok(expected)
+}
+
+fn prepare_socket(path: &Path) -> Result<(), AdapterError> {
+ match std::fs::remove_file(path) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(
+ AdapterError::internal("Could not replace stale cursor overlay socket")
+ .with_platform_detail(error.to_string()),
+ ),
+ }
+}
+
+fn cleanup(path: PathBuf) -> Result<(), AdapterError> {
+ bridge::stop();
+ match std::fs::remove_file(path) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(
+ AdapterError::internal("Could not remove cursor overlay socket")
+ .with_platform_detail(error.to_string()),
+ ),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sampled_motion_ends_at_the_requested_destination() {
+ let screen = agent_desktop_core::Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 1920.0,
+ height: 1080.0,
+ };
+ let destination = Point { x: 900.0, y: 500.0 };
+ let points = motion_points(None, &destination, &screen, 120);
+
+ assert_eq!(points.last(), Some(&destination));
+ assert!(points.len() >= 51);
+ }
+
+ #[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);
+
+ assert_eq!(points.first(), Some(&start));
+ assert_eq!(points.last(), Some(&destination));
+ }
+}
diff --git a/crates/macos/src/system/cursor_overlay/endpoint.rs b/crates/macos/src/system/cursor_overlay/endpoint.rs
new file mode 100644
index 000000000..09766d7e9
--- /dev/null
+++ b/crates/macos/src/system/cursor_overlay/endpoint.rs
@@ -0,0 +1,58 @@
+use agent_desktop_core::{AdapterError, ErrorCode, session};
+use std::os::unix::ffi::OsStrExt;
+use std::path::{Path, PathBuf};
+
+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))
+}
+
+pub(super) fn lock_path() -> Result<PathBuf, AdapterError> {
+ let root = session::agent_desktop_dir()
+ .map_err(|error| AdapterError::new(ErrorCode::InvalidArgs, error.to_string()))?;
+ Ok(root.join(".cursor-overlay-start.lock"))
+}
+
+fn path_for_root(root: &Path, session_id: &str) -> PathBuf {
+ let name = format!(
+ ".cursor-overlay-{:016x}.sock",
+ endpoint_hash(root, session_id)
+ );
+ let path = root.join(&name);
+ if path.as_os_str().as_bytes().len() < 100 {
+ path
+ } else {
+ PathBuf::from("/tmp").join(name)
+ }
+}
+
+fn endpoint_hash(root: &Path, session_id: &str) -> u64 {
+ let mut hash = 0xcbf29ce484222325_u64;
+ for byte in root
+ .as_os_str()
+ .as_bytes()
+ .iter()
+ .chain(session_id.as_bytes())
+ {
+ hash ^= u64::from(*byte);
+ hash = hash.wrapping_mul(0x100000001b3);
+ }
+ hash
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[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");
+
+ assert_eq!(first, second);
+ assert_eq!(first.parent(), Some(Path::new("/tmp")));
+ assert!(first.as_os_str().as_bytes().len() < 100);
+ }
+}
diff --git a/crates/macos/src/system/cursor_overlay/mod.rs b/crates/macos/src/system/cursor_overlay/mod.rs
new file mode 100644
index 000000000..245fab335
--- /dev/null
+++ b/crates/macos/src/system/cursor_overlay/mod.rs
@@ -0,0 +1,7 @@
+mod bridge;
+mod child;
+mod endpoint;
+mod spawn;
+
+pub(crate) use child::entry_from_env;
+pub(crate) use spawn::update;
diff --git a/crates/macos/src/system/cursor_overlay/spawn.rs b/crates/macos/src/system/cursor_overlay/spawn.rs
new file mode 100644
index 000000000..ca808f2b3
--- /dev/null
+++ b/crates/macos/src/system/cursor_overlay/spawn.rs
@@ -0,0 +1,133 @@
+use agent_desktop_core::{AdapterError, CursorOverlayControl, ErrorCode};
+use std::fs::OpenOptions;
+use std::io::{Read, Write};
+use std::os::unix::fs::OpenOptionsExt;
+use std::os::unix::net::UnixStream;
+use std::os::unix::process::CommandExt;
+use std::path::Path;
+use std::process::{Command, Stdio};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use super::child::{MARKER, PROTOCOL_VERSION, 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() {
+ return Ok(());
+ }
+ let lock_path = super::endpoint::lock_path()?;
+ let lock = OpenOptions::new()
+ .create(true)
+ .read(true)
+ .truncate(false)
+ .write(true)
+ .mode(0o600)
+ .open(lock_path)
+ .map_err(|error| {
+ AdapterError::internal("Could not open the cursor overlay startup lock")
+ .with_platform_detail(error.to_string())
+ })?;
+ lock.lock().map_err(|error| {
+ AdapterError::internal("Could not acquire the cursor overlay startup lock")
+ .with_platform_detail(error.to_string())
+ })?;
+ if send(&socket, control).is_ok() {
+ return Ok(());
+ }
+ spawn(&socket, control)
+}
+
+fn spawn(socket: &Path, control: &CursorOverlayControl) -> Result<(), AdapterError> {
+ let executable = std::env::current_exe().map_err(|error| {
+ AdapterError::internal("Could not locate the cursor overlay executable")
+ .with_platform_detail(error.to_string())
+ })?;
+ if executable.file_stem().and_then(|name| name.to_str()) != Some("agent-desktop") {
+ return Ok(());
+ }
+ let payload = serde_json::to_vec(control).map_err(|error| {
+ AdapterError::internal("Could not encode macOS cursor overlay control")
+ .with_platform_detail(error.to_string())
+ })?;
+ if payload.len() > MAX_INSTRUCTION_BYTES {
+ return Err(AdapterError::new(
+ ErrorCode::InvalidArgs,
+ "Cursor overlay instruction exceeds the transport limit",
+ ));
+ }
+ let mut child = Command::new(executable)
+ .env(MARKER, PROTOCOL_VERSION)
+ .env(SOCKET_ENV, socket)
+ .process_group(0)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .map_err(|error| {
+ AdapterError::internal("Could not start the macOS cursor overlay")
+ .with_platform_detail(error.to_string())
+ })?;
+ let mut stdin = child.stdin.take().ok_or_else(|| {
+ AdapterError::internal("Cursor overlay child did not expose its input pipe")
+ })?;
+ stdin.write_all(&payload).map_err(|error| {
+ AdapterError::internal("Could not send the cursor overlay control")
+ .with_platform_detail(error.to_string())
+ })?;
+ drop(stdin);
+ let deadline = Instant::now() + Duration::from_millis(500);
+ while Instant::now() < deadline {
+ if UnixStream::connect(socket).is_ok() {
+ return Ok(());
+ }
+ thread::sleep(Duration::from_millis(10));
+ }
+ Err(AdapterError::internal(
+ "macOS cursor overlay did not become ready",
+ ))
+}
+
+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")
+ .with_platform_detail(error.to_string())
+ })?;
+ let payload = serde_json::to_vec(control).map_err(|error| {
+ AdapterError::internal("Could not encode macOS cursor overlay control")
+ .with_platform_detail(error.to_string())
+ })?;
+ if payload.len() > MAX_INSTRUCTION_BYTES {
+ return Err(AdapterError::new(
+ ErrorCode::InvalidArgs,
+ "Cursor overlay instruction exceeds the transport limit",
+ ));
+ }
+ stream.write_all(&payload).map_err(|error| {
+ AdapterError::internal("Could not send the cursor overlay control")
+ .with_platform_detail(error.to_string())
+ })?;
+ if !control.is_hide() && !control.is_disable() {
+ return Ok(());
+ }
+ stream
+ .shutdown(std::net::Shutdown::Write)
+ .map_err(|error| {
+ AdapterError::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")
+ .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.m
new file mode 100644
index 000000000..a6e5f4d5f
--- /dev/null
+++ b/crates/macos/src/system/cursor_overlay_bridge.m
@@ -0,0 +1,392 @@
+#import <AppKit/AppKit.h>
+#import <QuartzCore/QuartzCore.h>
+#import <CoreGraphics/CoreGraphics.h>
+#import <stdbool.h>
+#import <stddef.h>
+#import <stdint.h>
+#import <math.h>
+
+typedef struct {
+ double frameSeconds;
+ const char *label;
+ double bubbleX;
+ double bubbleY;
+ uint8_t flags;
+} AgentDesktopCursorRenderConfig;
+
+static const uint8_t ADClickCue = 1 << 1;
+static const uint8_t ADReduceMotion = 1 << 2;
+static __strong NSWindow *ADCursorWindow = nil;
+static __strong CAShapeLayer *ADArrowLayer = nil;
+static __strong CAShapeLayer *ADHandPointerLayer = 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) {
+ 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);
+ 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);
+ 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]];
+}
+
+void agent_desktop_cursor_overlay_idle(void) {
+ @autoreleasepool {
+ ADPump(NSApplication.sharedApplication);
+ }
+}
+
+void agent_desktop_cursor_overlay_stop(void) {
+ [ADCursorWindow orderOut:nil];
+ [ADBubbleWindow orderOut:nil];
+ ADCursorWindow = nil;
+ ADArrowLayer = nil;
+ ADHandPointerLayer = nil;
+ ADBubbleWindow = nil;
+ ADBubbleText = nil;
+}
+
+void agent_desktop_cursor_overlay_hide(void) {
+ [ADCursorWindow orderOut:nil];
+ [ADBubbleWindow orderOut:nil];
+}
+
+void agent_desktop_cursor_overlay_show(void) {
+ [ADCursorWindow orderFrontRegardless];
+ if (ADBubbleText.stringValue.length > 0) {
+ [ADBubbleWindow orderFrontRegardless];
+ }
+}
+
+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 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,
+ const AgentDesktopCursorRenderConfig *config) {
+ if (points == NULL || pointCount == 0 || config == NULL || config->frameSeconds <= 0.0) {
+ return false;
+ }
+ @try {
+ @autoreleasepool {
+ NSApplication *app = NSApplication.sharedApplication;
+ [app setActivationPolicy:NSApplicationActivationPolicyAccessory];
+ [app finishLaunching];
+ CGRect main = CGDisplayBounds(CGMainDisplayID());
+ double mainHeight = main.size.height;
+ bool click = (config->flags & ADClickCue) != 0;
+ bool reduceMotion = (config->flags & ADReduceMotion) != 0;
+
+ 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];
+ }
+ NSWindow *cursor = ADCursorWindow;
+ CAShapeLayer *cursorLayer = ADArrowLayer;
+ CAShapeLayer *handLayer = ADHandPointerLayer;
+ ADSetBreathing(cursorLayer, !reduceMotion);
+ ADSetBreathing(handLayer, !reduceMotion);
+ [cursor 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]
+ : @"";
+ 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);
+ }
+
+ 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];
+ }
+ ADPump(app);
+ if (index + 1 < pointCount) {
+ [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 (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;
+ }
+ return true;
+ }
+ } @catch (NSException *exception) {
+ (void)exception;
+ return false;
+ }
+}
diff --git a/crates/macos/src/system/cursor_overlay_display_bridge.m b/crates/macos/src/system/cursor_overlay_display_bridge.m
new file mode 100644
index 000000000..664bc2b3d
--- /dev/null
+++ b/crates/macos/src/system/cursor_overlay_display_bridge.m
@@ -0,0 +1,76 @@
+#import <AppKit/AppKit.h>
+#import <CoreGraphics/CoreGraphics.h>
+#import <stdbool.h>
+
+static NSRect ADTopLeftRect(NSRect frame) {
+ CGRect main = CGDisplayBounds(CGMainDisplayID());
+ return NSMakeRect(frame.origin.x,
+ main.size.height - NSMaxY(frame),
+ frame.size.width,
+ frame.size.height);
+}
+
+static NSScreen *ADScreenAt(double x, double y) {
+ NSPoint point = NSMakePoint(x, y);
+ for (NSScreen *screen in NSScreen.screens) {
+ if (NSPointInRect(point, ADTopLeftRect(screen.frame))) {
+ return screen;
+ }
+ }
+ return nil;
+}
+
+bool agent_desktop_cursor_overlay_initial_point(double *output) {
+ if (output == NULL) {
+ return false;
+ }
+ @autoreleasepool {
+ NSScreen *screen = NSScreen.mainScreen;
+ if (screen == nil) {
+ return false;
+ }
+ NSRect frame = ADTopLeftRect(screen.visibleFrame);
+ output[0] = NSMidX(frame);
+ output[1] = NSMidY(frame);
+ return true;
+ }
+}
+
+bool agent_desktop_cursor_overlay_screen(double x,
+ double y,
+ double *output) {
+ if (output == NULL) {
+ return false;
+ }
+ @try {
+ @autoreleasepool {
+ NSScreen *screen = ADScreenAt(x, y);
+ if (screen == nil) {
+ return false;
+ }
+ NSRect frame = ADTopLeftRect(screen.visibleFrame);
+ output[0] = frame.origin.x;
+ output[1] = frame.origin.y;
+ output[2] = frame.size.width;
+ output[3] = frame.size.height;
+ double refreshRate = 60.0;
+ NSNumber *screenNumber = screen.deviceDescription[@"NSScreenNumber"];
+ if (screenNumber != nil) {
+ CGDisplayModeRef mode = CGDisplayCopyDisplayMode(screenNumber.unsignedIntValue);
+ if (mode != NULL) {
+ double reportedRate = CGDisplayModeGetRefreshRate(mode);
+ if (reportedRate > 0.0) {
+ refreshRate = reportedRate;
+ }
+ CGDisplayModeRelease(mode);
+ }
+ }
+ output[4] = MAX(60.0, MIN(120.0, refreshRate));
+ output[5] = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion ? 1.0 : 0.0;
+ return true;
+ }
+ } @catch (NSException *exception) {
+ (void)exception;
+ return false;
+ }
+}
diff --git a/crates/macos/src/system/mod.rs b/crates/macos/src/system/mod.rs
index 1359a85d3..3cc2011df 100644
--- a/crates/macos/src/system/mod.rs
+++ b/crates/macos/src/system/mod.rs
@@ -5,6 +5,7 @@ pub(crate) mod appkit_bridge;
pub(crate) mod cg_window;
pub(crate) mod cg_window_exact;
pub(crate) mod cocoa_runtime;
+pub(crate) mod cursor_overlay;
pub(crate) mod display;
pub(crate) mod display_work_area;
pub(crate) mod focus;
diff --git a/crates/macos/src/system/process_apps.rs b/crates/macos/src/system/process_apps.rs
index 8b46e6467..0a37fb70d 100644
--- a/crates/macos/src/system/process_apps.rs
+++ b/crates/macos/src/system/process_apps.rs
@@ -23,7 +23,9 @@ fn list_apps_with_filter(
command.args(["-axo", "pid=,comm="]);
let output = crate::system::process::run_with_deadline(&mut command, "ps", deadline)?;
let mut apps = apps_from_output(output)?;
- apps.retain(|app| name.is_none_or(|name| app.name.eq_ignore_ascii_case(name)));
+ apps.retain(|app| {
+ name.is_none_or(|name| agent_desktop_core::app_name_matches(&app.name, name))
+ });
enrich_process_instances(apps, crate::system::process_identity::token_for_pid)
}
diff --git a/crates/macos/src/system/signals.rs b/crates/macos/src/system/signals.rs
index 7a37c89a5..b55ad1302 100644
--- a/crates/macos/src/system/signals.rs
+++ b/crates/macos/src/system/signals.rs
@@ -72,7 +72,7 @@ fn filter_apps(filter: &SignalFilter, all: Vec<AppInfo>) -> Vec<AppInfo> {
if let Some(name) = &filter.app {
return all
.into_iter()
- .filter(|app| app.name.eq_ignore_ascii_case(name))
+ .filter(|app| app.matches_identifier(name))
.collect();
}
if let Some(process) = &filter.process {
diff --git a/crates/macos/src/system/signals_tests.rs b/crates/macos/src/system/signals_tests.rs
index f6c4785fe..53bf5af21 100644
--- a/crates/macos/src/system/signals_tests.rs
+++ b/crates/macos/src/system/signals_tests.rs
@@ -59,6 +59,27 @@ fn matching_apps_filters_by_name_case_insensitively() {
assert_eq!(apps[0].pid, 42);
}
+#[test]
+fn matching_apps_accepts_bundle_identifier() {
+ let filter = SignalFilter {
+ app: Some("com.example.editor".into()),
+ process: None,
+ };
+ let apps = filter_apps(
+ &filter,
+ vec![AppInfo {
+ name: "TextEdit".into(),
+ pid: agent_desktop_core::ProcessId::new(42),
+ bundle_id: Some("com.example.editor".into()),
+ process_instance: None,
+ presentation: None,
+ }],
+ );
+
+ assert_eq!(apps.len(), 1);
+ assert_eq!(apps[0].pid, 42);
+}
+
#[test]
fn app_filter_with_no_constraints_preserves_the_complete_inventory() {
let filter = SignalFilter::default();
diff --git a/crates/macos/src/system/window_inventory.rs b/crates/macos/src/system/window_inventory.rs
index 3fdb294e7..ff595dc23 100644
--- a/crates/macos/src/system/window_inventory.rs
+++ b/crates/macos/src/system/window_inventory.rs
@@ -31,30 +31,58 @@ pub(crate) fn list_windows_until(
filter: &WindowFilter,
deadline: Instant,
) -> Result<Vec<WindowInfo>, AdapterError> {
- let app_filter = filter.app.as_deref().unwrap_or("").to_ascii_lowercase();
- if app_filter.is_empty() {
+ let Some(app_filter) = filter.app.as_deref().filter(|name| !name.is_empty()) else {
return crate::system::window_inventory_global::list_windows_until(
filter.focused_only,
deadline,
);
+ };
+ crate::system::window_inventory_global::stabilize_global_with(deadline, || {
+ crate::system::window_inventory_global::capture_validated_with(
+ || crate::system::workspace_apps::window_owner_snapshot_until(deadline),
+ |owners| owners.matching_pids(app_filter),
+ |pids| {
+ require_running_app(pids, app_filter)?;
+ cg_window::window_records_until(deadline, cg_window::WindowRecordScope::Pids(pids))
+ },
+ |records, _| {
+ let mut windows = windows_from_records_with_focus(
+ records,
+ filter.focused_only,
+ |pid| crate::system::window_ax_state::read_until(pid, deadline),
+ crate::system::process_identity::matches_instance,
+ )?;
+ narrow_to_real_windows(&mut windows);
+ Ok(windows)
+ },
+ |before, after, before_pids, records| {
+ let after_pids = after.matching_pids(app_filter);
+ crate::system::window_inventory_global::validate_scoped_snapshot_pair(
+ before,
+ after,
+ before_pids,
+ &after_pids,
+ records,
+ )
+ },
+ )
+ })
+}
+
+fn require_running_app(
+ pids: &rustc_hash::FxHashSet<i32>,
+ app_filter: &str,
+) -> Result<(), AdapterError> {
+ if !pids.is_empty() {
+ return Ok(());
}
- let scope = cg_window::WindowRecordScope::App(&app_filter);
- let records = cg_window::window_records_until(deadline, scope)?;
- let candidates = records;
- windows_from_records_with_focus(
- candidates,
- filter.focused_only,
- |pid| crate::system::window_ax_state::read_until(pid, deadline),
- crate::system::process_identity::matches_instance,
+ Err(AdapterError::new(
+ agent_desktop_core::ErrorCode::AppNotFound,
+ format!("No running application matches '{app_filter}'"),
)
+ .with_suggestion("Run 'list-apps' to see running applications, or launch the app first."))
}
-/// The window server already knows which windows exist; accessibility is only
-/// asked which one holds focus and which are minimized. An application too busy
-/// to answer that — a freshly launched one, or one sitting in a modal panel —
-/// must not hide its windows from the inventory, or a caller waits out its whole
-/// deadline for windows the window server listed immediately. Selecting *the
-/// focused* window is the one case that genuinely needs the answer.
fn focus_state(
ax_state: &mut impl FnMut(
i32,
@@ -62,31 +90,30 @@ fn focus_state(
-> Result<crate::system::window_ax_state::WindowAxState, AdapterError>,
pid: i32,
focused_only: bool,
+ has_visible_window: bool,
) -> Result<crate::system::window_ax_state::WindowAxState, AdapterError> {
match ax_state(pid) {
Ok(state) => Ok(state),
- Err(error) if focused_only => Err(error),
- Err(_) => Ok(crate::system::window_ax_state::WindowAxState {
- focused: None,
- minimized_by_id: rustc_hash::FxHashMap::default(),
- }),
+ Err(_) if !focused_only && has_visible_window => {
+ Ok(crate::system::window_ax_state::WindowAxState {
+ focused: None,
+ minimized_by_id: rustc_hash::FxHashMap::default(),
+ })
+ }
+ Err(error) => Err(error),
}
}
-/// An application carries offscreen bookkeeping windows alongside the one the
-/// user sees — TextEdit answers with four menu-bar-sized panels plus a save
-/// accessory view before its first document appears. Counting those makes the
-/// only real window look ambiguous, and reports an application that has not
-/// drawn anything yet as having several windows to choose between.
-///
-/// A minimized window is the user's window and is kept: it is offscreen for a
-/// reason the caller cares about, unlike a panel that was never meant to be
-/// seen. Dropping it would report an application as having no window while its
-/// window sits in the Dock.
+fn visible_window_pids(records: &[cg_window::WindowRecord]) -> rustc_hash::FxHashSet<i32> {
+ records
+ .iter()
+ .filter(|record| record.visible)
+ .map(|record| record.pid)
+ .collect()
+}
+
fn narrow_to_real_windows(windows: &mut Vec<WindowInfo>) {
- windows.retain(|window| {
- window.state.visible == Some(true) || window.state.minimized == Some(true)
- });
+ windows.retain(|window| window.state.visible == Some(true) || window.state.minimized.is_some());
}
pub(crate) fn exact_window_for_pid_until(
@@ -140,6 +167,7 @@ fn windows_from_records_with_focus(
.into_iter()
.filter(|record| record.window_number > 0)
.collect::<Vec<_>>();
+ let visible_pids = visible_window_pids(&candidates);
let mut title_counts = std::collections::HashMap::new();
for record in &candidates {
*title_counts
@@ -170,9 +198,12 @@ fn windows_from_records_with_focus(
.unwrap_or(0);
let state = match state_cache.entry(record.pid) {
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
- std::collections::hash_map::Entry::Vacant(entry) => {
- entry.insert(focus_state(&mut ax_state, record.pid, focused_only)?)
- }
+ std::collections::hash_map::Entry::Vacant(entry) => entry.insert(focus_state(
+ &mut ax_state,
+ record.pid,
+ focused_only,
+ visible_pids.contains(&record.pid),
+ )?),
};
if !verify_instance(record.pid, process_instance)? {
return Err(identity_race_error(
@@ -200,7 +231,7 @@ fn windows_from_records_with_focus(
#[cfg(test)]
fn matches_app_filter(app_name: &str, app_filter: &str) -> bool {
- app_filter.is_empty() || app_name.eq_ignore_ascii_case(app_filter)
+ app_filter.is_empty() || agent_desktop_core::app_name_matches(app_name, app_filter)
}
fn identity_race_error(pid: i32, phase: &str) -> AdapterError {
diff --git a/crates/macos/src/system/window_inventory_global.rs b/crates/macos/src/system/window_inventory_global.rs
index fe3f20098..dc0be9cea 100644
--- a/crates/macos/src/system/window_inventory_global.rs
+++ b/crates/macos/src/system/window_inventory_global.rs
@@ -32,7 +32,7 @@ pub(super) trait OwnerSnapshotView {
fn same_generation(&self, other: &Self) -> bool;
}
-#[derive(Clone, Copy)]
+#[derive(Clone, Copy, PartialEq)]
pub(super) enum OwnerGeneration {
LaunchTime(f64),
LiveProcess,
@@ -64,17 +64,48 @@ fn capture_global_once(
fn capture_global_with<S: OwnerSnapshotView>(
focused_only: bool,
+ capture_owners: impl FnMut() -> Result<S, AdapterError>,
+ capture_records: impl FnMut(&FxHashSet<i32>) -> Result<Vec<WindowRecord>, AdapterError>,
+ mut read_frontmost: impl FnMut(i32) -> Result<WindowAxState, AdapterError>,
+) -> Result<Vec<WindowInfo>, AdapterError> {
+ capture_stable_with(
+ capture_owners,
+ OwnerSnapshotView::eligible_pids,
+ capture_records,
+ |records, owners| {
+ assemble_global_windows(records, owners, focused_only, &mut read_frontmost)
+ },
+ )
+}
+
+pub(super) fn capture_stable_with<S: OwnerSnapshotView>(
+ capture_owners: impl FnMut() -> Result<S, AdapterError>,
+ select_pids: impl FnMut(&S) -> FxHashSet<i32>,
+ capture_records: impl FnMut(&FxHashSet<i32>) -> Result<Vec<WindowRecord>, AdapterError>,
+ assemble: impl FnMut(Vec<WindowRecord>, &S) -> Result<Vec<WindowInfo>, AdapterError>,
+) -> Result<Vec<WindowInfo>, AdapterError> {
+ capture_validated_with(
+ capture_owners,
+ select_pids,
+ capture_records,
+ assemble,
+ |before, after, _, records| validate_snapshot_pair(before, after, records),
+ )
+}
+
+pub(super) fn capture_validated_with<S: OwnerSnapshotView>(
mut capture_owners: impl FnMut() -> Result<S, AdapterError>,
+ mut select_pids: impl FnMut(&S) -> FxHashSet<i32>,
mut capture_records: impl FnMut(&FxHashSet<i32>) -> Result<Vec<WindowRecord>, AdapterError>,
- mut read_frontmost: impl FnMut(i32) -> Result<WindowAxState, AdapterError>,
+ mut assemble: impl FnMut(Vec<WindowRecord>, &S) -> Result<Vec<WindowInfo>, AdapterError>,
+ mut validate: impl FnMut(&S, &S, &FxHashSet<i32>, &[WindowRecord]) -> Result<(), AdapterError>,
) -> Result<Vec<WindowInfo>, AdapterError> {
let before = capture_owners()?;
- let eligible_pids = OwnerSnapshotView::eligible_pids(&before);
+ let eligible_pids = select_pids(&before);
let records = capture_records(&eligible_pids)?;
- let assembled =
- assemble_global_windows(records.clone(), &before, focused_only, &mut read_frontmost);
+ let assembled = assemble(records.clone(), &before);
let after = capture_owners()?;
- validate_snapshot_pair(&before, &after, &records)?;
+ validate(&before, &after, &eligible_pids, &records)?;
assembled
}
@@ -136,6 +167,23 @@ pub(super) fn validate_snapshot_pair<S: OwnerSnapshotView>(
validate_record_generations(records, after)
}
+pub(super) fn validate_scoped_snapshot_pair<S: OwnerSnapshotView>(
+ before: &S,
+ after: &S,
+ before_pids: &FxHashSet<i32>,
+ after_pids: &FxHashSet<i32>,
+ records: &[WindowRecord],
+) -> Result<(), AdapterError> {
+ if before_pids != after_pids
+ || before_pids
+ .iter()
+ .any(|pid| before.generation(*pid) != after.generation(*pid))
+ {
+ return Err(owner_churn_error(None, "selected_appkit_snapshot_changed"));
+ }
+ validate_record_generations(records, after)
+}
+
pub(super) fn stabilize_global_with(
deadline: Instant,
mut capture: impl FnMut() -> Result<Vec<WindowInfo>, AdapterError>,
diff --git a/crates/macos/src/system/window_inventory_global_tests.rs b/crates/macos/src/system/window_inventory_global_tests.rs
index cd6674a42..9a8530c18 100644
--- a/crates/macos/src/system/window_inventory_global_tests.rs
+++ b/crates/macos/src/system/window_inventory_global_tests.rs
@@ -338,6 +338,27 @@ fn post_ax_snapshot_is_captured_and_churn_wins_over_stale_ax_failure() {
assert_eq!(error.details.unwrap()["phase"], "appkit_snapshot_changed");
}
+#[test]
+fn scoped_pid_selection_is_still_bound_to_the_owner_generation() {
+ let snapshots = std::cell::RefCell::new(std::collections::VecDeque::from([
+ owners(&[(10, 100.0), (20, 200.0)], Some(10)),
+ owners(&[(10, 106.0), (20, 200.0)], Some(10)),
+ ]));
+
+ let error = capture_stable_with(
+ || Ok(snapshots.borrow_mut().pop_front().unwrap()),
+ |_| FxHashSet::from_iter([10]),
+ |selected| {
+ assert_eq!(selected, &FxHashSet::from_iter([10]));
+ Ok(vec![record(10, 1, "Target")])
+ },
+ |_, _| Ok(Vec::new()),
+ )
+ .unwrap_err();
+
+ assert_eq!(error.details.unwrap()["phase"], "appkit_snapshot_changed");
+}
+
fn owners(entries: &[(i32, f64)], frontmost: Option<i32>) -> Owners {
Owners {
launches: entries
diff --git a/crates/macos/src/system/window_inventory_tests.rs b/crates/macos/src/system/window_inventory_tests.rs
index 448309282..b8213b887 100644
--- a/crates/macos/src/system/window_inventory_tests.rs
+++ b/crates/macos/src/system/window_inventory_tests.rs
@@ -3,6 +3,33 @@ use crate::system::cg_window::WindowRecord;
use agent_desktop_core::Rect;
use rustc_hash::FxHashMap;
+#[derive(Clone)]
+struct ScopedOwners(FxHashMap<i32, f64>);
+
+impl crate::system::window_inventory_global::OwnerSnapshotView for ScopedOwners {
+ fn eligible_pids(&self) -> rustc_hash::FxHashSet<i32> {
+ self.0.keys().copied().collect()
+ }
+
+ fn generation(
+ &self,
+ pid: i32,
+ ) -> Option<crate::system::window_inventory_global::OwnerGeneration> {
+ self.0
+ .get(&pid)
+ .copied()
+ .map(crate::system::window_inventory_global::OwnerGeneration::LaunchTime)
+ }
+
+ fn frontmost_pid(&self) -> Option<i32> {
+ None
+ }
+
+ fn same_generation(&self, other: &Self) -> bool {
+ self.0 == other.0
+ }
+}
+
fn ax_state(focused: FocusedWindowIdentity) -> crate::system::window_ax_state::WindowAxState {
crate::system::window_ax_state::WindowAxState {
focused,
@@ -34,6 +61,7 @@ fn apps_from_window_records_keeps_same_name_with_distinct_pids() {
#[test]
fn matches_app_filter_accepts_exact_case_insensitive_name() {
assert!(matches_app_filter("Docker Desktop", "docker desktop"));
+ assert!(matches_app_filter("\u{200e}WhatsApp", "WhatsApp"));
assert!(!matches_app_filter("Finder", "docker"));
}
@@ -98,6 +126,41 @@ fn windows_from_records_preserve_capture_bounds() {
assert_eq!(windows[0].bounds, Some(expected));
}
+#[test]
+fn visible_windows_survive_ax_inventory_failure() {
+ let visible = record("Preview", 10, "Document", 7);
+ let mut panel = record("Preview", 10, "Panel", 8);
+ panel.visible = false;
+
+ let mut windows = windows_from_records_with_focus(
+ vec![visible, panel],
+ false,
+ |_| Err(AdapterError::timeout("AX unavailable")),
+ |_, _| Ok(true),
+ )
+ .unwrap();
+ narrow_to_real_windows(&mut windows);
+
+ assert_eq!(windows.len(), 1);
+ assert_eq!(windows[0].id, "w-7");
+}
+
+#[test]
+fn offscreen_only_inventory_requires_ax_classification() {
+ let mut offscreen = record("Preview", 10, "Document", 7);
+ offscreen.visible = false;
+
+ let error = windows_from_records_with_focus(
+ vec![offscreen],
+ false,
+ |_| Err(AdapterError::timeout("AX unavailable")),
+ |_, _| Ok(true),
+ )
+ .unwrap_err();
+
+ assert_eq!(error.code, agent_desktop_core::ErrorCode::Timeout);
+}
+
#[test]
fn windows_from_records_never_publish_zero_window_ids() {
let windows = windows_from_records_with_focus(
@@ -158,6 +221,75 @@ fn deadline_window_inventory_rejects_expiry_before_native_reads() {
assert_eq!(error.code.as_str(), "TIMEOUT");
}
+#[test]
+fn explicit_app_filter_distinguishes_not_running_from_no_windows() {
+ let empty = rustc_hash::FxHashSet::default();
+ let error = require_running_app(&empty, "WhatsApp").unwrap_err();
+ assert_eq!(error.code, agent_desktop_core::ErrorCode::AppNotFound);
+
+ let running = rustc_hash::FxHashSet::from_iter([42]);
+ assert!(require_running_app(&running, "WhatsApp").is_ok());
+}
+
+#[test]
+fn scoped_validation_ignores_unrelated_owner_churn() {
+ let before = ScopedOwners(FxHashMap::from_iter([(10, 100.0), (20, 200.0)]));
+ let after = ScopedOwners(FxHashMap::from_iter([(10, 100.0), (30, 300.0)]));
+ let selected = rustc_hash::FxHashSet::from_iter([10]);
+
+ crate::system::window_inventory_global::validate_scoped_snapshot_pair(
+ &before,
+ &after,
+ &selected,
+ &selected,
+ &[],
+ )
+ .unwrap();
+}
+
+#[test]
+fn scoped_validation_rejects_selected_owner_replacement() {
+ let before = ScopedOwners(FxHashMap::from_iter([(10, 100.0)]));
+ let after = ScopedOwners(FxHashMap::from_iter([(10, 101.0)]));
+ let selected = rustc_hash::FxHashSet::from_iter([10]);
+
+ let error = crate::system::window_inventory_global::validate_scoped_snapshot_pair(
+ &before,
+ &after,
+ &selected,
+ &selected,
+ &[],
+ )
+ .unwrap_err();
+
+ assert_eq!(
+ error.details.unwrap()["phase"],
+ "selected_appkit_snapshot_changed"
+ );
+}
+
+#[test]
+fn scoped_validation_rejects_selected_pid_membership_change() {
+ let before = ScopedOwners(FxHashMap::from_iter([(10, 100.0)]));
+ let after = ScopedOwners(FxHashMap::from_iter([(11, 101.0)]));
+ let before_pids = rustc_hash::FxHashSet::from_iter([10]);
+ let after_pids = rustc_hash::FxHashSet::from_iter([11]);
+
+ let error = crate::system::window_inventory_global::validate_scoped_snapshot_pair(
+ &before,
+ &after,
+ &before_pids,
+ &after_pids,
+ &[],
+ )
+ .unwrap_err();
+
+ assert_eq!(
+ error.details.unwrap()["phase"],
+ "selected_appkit_snapshot_changed"
+ );
+}
+
fn record(app_name: &str, pid: i32, title: &str, window_number: i64) -> WindowRecord {
WindowRecord {
app_name: app_name.to_string(),
@@ -192,10 +324,10 @@ fn window_with_state(id: &str, visible: Option<bool>, minimized: Option<bool>) -
}
#[test]
-fn narrowing_drops_bookkeeping_panels_but_keeps_a_minimized_window() {
+fn narrowing_drops_unconfirmed_panels_but_keeps_ax_windows() {
let mut windows = vec![
- window_with_state("panel", Some(false), Some(false)),
- window_with_state("never-drawn", Some(false), None),
+ window_with_state("ax-offscreen", Some(false), Some(false)),
+ window_with_state("cg-only-panel", Some(false), None),
window_with_state("minimized", Some(false), Some(true)),
window_with_state("onscreen", Some(true), Some(false)),
];
@@ -203,12 +335,12 @@ fn narrowing_drops_bookkeeping_panels_but_keeps_a_minimized_window() {
narrow_to_real_windows(&mut windows);
let kept = windows.iter().map(|w| w.id.as_str()).collect::<Vec<_>>();
- assert_eq!(kept, vec!["minimized", "onscreen"]);
+ assert_eq!(kept, vec!["ax-offscreen", "minimized", "onscreen"]);
}
#[test]
fn narrowing_leaves_nothing_when_an_application_has_only_panels() {
- let mut windows = vec![window_with_state("panel", Some(false), Some(false))];
+ let mut windows = vec![window_with_state("panel", Some(false), None)];
narrow_to_real_windows(&mut windows);
diff --git a/crates/macos/src/system/workspace_apps.rs b/crates/macos/src/system/workspace_apps.rs
index e49dc3148..cc2d982b1 100644
--- a/crates/macos/src/system/workspace_apps.rs
+++ b/crates/macos/src/system/workspace_apps.rs
@@ -64,6 +64,20 @@ impl WindowOwnerSnapshot {
self.owners.iter().map(|owner| owner.pid).collect()
}
+ pub(crate) fn matching_pids(&self, identifier: &str) -> rustc_hash::FxHashSet<i32> {
+ self.owners
+ .iter()
+ .filter(|owner| {
+ agent_desktop_core::app_name_matches(&owner.name, identifier)
+ || owner
+ .bundle_id
+ .as_deref()
+ .is_some_and(|bundle_id| bundle_id.eq_ignore_ascii_case(identifier))
+ })
+ .map(|owner| owner.pid)
+ .collect()
+ }
+
pub(crate) fn owner(&self, pid: i32) -> Option<&WindowOwner> {
self.owners.iter().find(|owner| owner.pid == pid)
}
@@ -87,7 +101,12 @@ pub(crate) fn list_apps_scoped_until(
deadline: Instant,
) -> Result<Vec<AppInfo>, AdapterError> {
list_apps_with(deadline, |app| {
- app.name.eq_ignore_ascii_case(name)
+ (agent_desktop_core::app_name_matches(&app.name, name)
+ || (bundle_id.is_none()
+ && app
+ .bundle_id
+ .as_deref()
+ .is_some_and(|candidate| candidate.eq_ignore_ascii_case(name))))
&& bundle_id.is_none_or(|bundle| {
app.bundle_id
.as_deref()
diff --git a/crates/macos/src/system/workspace_apps_tests.rs b/crates/macos/src/system/workspace_apps_tests.rs
index 3ef6d5829..984685a97 100644
--- a/crates/macos/src/system/workspace_apps_tests.rs
+++ b/crates/macos/src/system/workspace_apps_tests.rs
@@ -46,6 +46,33 @@ fn owner_snapshot_includes_regular_and_accessory_but_excludes_prohibited() {
assert_eq!(snapshot.frontmost().unwrap().launch_time, Some(101.5));
}
+#[test]
+fn owner_snapshot_matches_visible_app_name_and_bundle_id() {
+ let bytes = br#"{
+ "applications":[
+ {"name":"\u200eWhatsApp","pid":10,"bundle_id":"net.whatsapp.WhatsApp","launch_time":100.25,"activation_policy":"regular"}
+ ],
+ "frontmost_pid":10,
+ "frontmost_launch_time":100.25
+ }"#;
+ let snapshot = window_owner_snapshot_from_json(bytes, deadline()).unwrap();
+
+ assert_eq!(
+ snapshot
+ .matching_pids("WhatsApp")
+ .into_iter()
+ .collect::<Vec<_>>(),
+ [10]
+ );
+ assert_eq!(
+ snapshot
+ .matching_pids("net.whatsapp.WhatsApp")
+ .into_iter()
+ .collect::<Vec<_>>(),
+ [10]
+ );
+}
+
#[test]
fn non_launchservices_accessory_keeps_optional_launch_identity() {
let bytes = br#"{
diff --git a/crates/macos/src/tree/node_attribute_fetch.rs b/crates/macos/src/tree/node_attribute_fetch.rs
index 7e2b6f9a5..ae4053a6a 100644
--- a/crates/macos/src/tree/node_attribute_fetch.rs
+++ b/crates/macos/src/tree/node_attribute_fetch.rs
@@ -12,7 +12,7 @@ mod imp {
node_attribute_names::copy_node_attribute_values,
node_attribute_read::NodeAttributeRead,
node_attribute_status::{
- AX_DOM_IDENTIFIER, AX_IDENTIFIER, NodeAttributeStatus, ROLE, SUBROLE, VALUE,
+ AX_DOM_IDENTIFIER, AX_IDENTIFIER, LABEL, NodeAttributeStatus, ROLE, SUBROLE, VALUE,
},
node_attrs::{parse_bool_attr, parse_enabled},
node_control_states::NodeControlStates,
@@ -217,7 +217,10 @@ mod imp {
NodeAttributeRead {
attrs: NodeAttrs {
name_evidence: agent_desktop_core::NameEvidence {
- explicit_label: None,
+ explicit_label: get(LABEL).or_else(|| {
+ crate::tree::roles::accessible_name_from_subrole(subrole.as_deref())
+ .map(str::to_owned)
+ }),
labelled_by_text,
native_title: get(1),
static_value: (role.as_deref() == Some("AXStaticText"))
diff --git a/crates/macos/src/tree/node_attribute_names.rs b/crates/macos/src/tree/node_attribute_names.rs
index ae19ff546..b66108326 100644
--- a/crates/macos/src/tree/node_attribute_names.rs
+++ b/crates/macos/src/tree/node_attribute_names.rs
@@ -97,13 +97,13 @@ mod imp {
pub(crate) fn attribute_mask(requirements: EvidenceRequirements) -> u32 {
use crate::tree::node_attribute_status::{
AX_DOM_IDENTIFIER, AX_IDENTIFIER, BUSY, DESCRIPTION, DISCLOSING, ENABLED, EXPANDED,
- FOCUSED, HIDDEN, HORIZONTAL_SCROLLBAR, MODAL, PLACEHOLDER, POSITION, REQUIRED, ROLE,
- SELECTED, SIZE, SUBROLE, TITLE, TITLE_ELEMENT, VALUE, VERTICAL_SCROLLBAR,
+ FOCUSED, HIDDEN, HORIZONTAL_SCROLLBAR, LABEL, MODAL, PLACEHOLDER, POSITION, REQUIRED,
+ ROLE, SELECTED, SIZE, SUBROLE, TITLE, TITLE_ELEMENT, VALUE, VERTICAL_SCROLLBAR,
attribute_bit,
};
let mut mask = attribute_bit(ROLE) | attribute_bit(SUBROLE);
if requirements.name || requirements.description {
- for index in [TITLE, DESCRIPTION, VALUE, PLACEHOLDER, TITLE_ELEMENT] {
+ for index in [TITLE, DESCRIPTION, VALUE, LABEL, PLACEHOLDER, TITLE_ELEMENT] {
mask |= attribute_bit(index);
}
}
@@ -191,7 +191,7 @@ mod tests {
assert_eq!(attribute_mask(requirements).count_ones(), 2);
assert_eq!(
attribute_mask(EvidenceRequirements::snapshot()).count_ones(),
- NODE_ATTRIBUTE_COUNT as u32 - 1
+ NODE_ATTRIBUTE_COUNT as u32
);
}
@@ -204,7 +204,7 @@ mod tests {
};
let requested = requested_indices(attribute_mask(requirements)).collect::<Vec<_>>();
- assert_eq!(requested, [0, 1, 2, 3, 16, 17, 22]);
+ assert_eq!(requested, [0, 1, 2, 3, 15, 16, 17, 22]);
}
#[test]
diff --git a/crates/macos/src/tree/query/child_read_plan.rs b/crates/macos/src/tree/query/child_read_plan.rs
index 261be378b..080712d7e 100644
--- a/crates/macos/src/tree/query/child_read_plan.rs
+++ b/crates/macos/src/tree/query/child_read_plan.rs
@@ -60,4 +60,22 @@ mod tests {
assert_eq!(plan.max_elements(false), 5);
}
+
+ #[test]
+ fn actionable_group_cannot_load_past_the_boundary() {
+ let plan = ChildReadPlan::boundary_aware(4_096, 0, 3, 3);
+ let transparent = super::super::node_evidence::is_transparent_wrapper(
+ Some("AXGroup"),
+ None,
+ &agent_desktop_core::NameEvidence::default(),
+ None,
+ &agent_desktop_core::IdentifierEvidence::absent(),
+ &agent_desktop_core::LocatorField::Known(vec![
+ agent_desktop_core::capability::CLICK.into(),
+ ]),
+ );
+
+ assert!(!transparent);
+ assert_eq!(plan.max_elements(transparent), 0);
+ }
}
diff --git a/crates/macos/src/tree/query/node_evidence.rs b/crates/macos/src/tree/query/node_evidence.rs
index af7274334..fdeae169f 100644
--- a/crates/macos/src/tree/query/node_evidence.rs
+++ b/crates/macos/src/tree/query/node_evidence.rs
@@ -3,11 +3,16 @@ use agent_desktop_core::{
LocatorStats,
};
-pub(crate) fn is_wrapper_candidate(role: Option<&str>, subrole: Option<&str>) -> bool {
- role == Some("AXGenericElement")
- && role.is_some_and(|role| {
- crate::tree::roles::ax_role_and_subrole_to_str(role, subrole) == "group"
- })
+fn is_wrapper_candidate(
+ role: Option<&str>,
+ subrole: Option<&str>,
+ name: &agent_desktop_core::NameEvidence,
+ value: Option<&str>,
+ identifiers: &IdentifierEvidence,
+) -> bool {
+ role.is_some_and(|role| {
+ crate::tree::roles::ax_role_and_subrole_to_str(role, subrole) == "group"
+ }) && direct_wrapper_identity_is_empty(name, value, identifiers)
}
pub(crate) fn is_transparent_wrapper(
@@ -18,7 +23,18 @@ pub(crate) fn is_transparent_wrapper(
identifiers: &IdentifierEvidence,
actions: &LocatorField<Vec<String>>,
) -> bool {
- let strings = [
+ is_wrapper_candidate(role, subrole, name, value, identifiers)
+ && actions
+ .known()
+ .is_some_and(|actions| actions.iter().all(|action| is_structural_action(action)))
+}
+
+fn direct_wrapper_identity_is_empty(
+ name: &agent_desktop_core::NameEvidence,
+ value: Option<&str>,
+ identifiers: &IdentifierEvidence,
+) -> bool {
+ [
name.explicit_label.as_deref(),
name.labelled_by_text.as_deref(),
name.native_title.as_deref(),
@@ -27,14 +43,20 @@ pub(crate) fn is_transparent_wrapper(
name.placeholder.as_deref(),
name.description.as_deref(),
value,
- ];
- is_wrapper_candidate(role, subrole)
- && strings
- .into_iter()
- .all(|text| text.is_none_or(|text| text.trim().is_empty()))
+ ]
+ .into_iter()
+ .all(|text| text.is_none_or(|text| text.trim().is_empty()))
&& identifiers.is_complete()
&& identifiers.identifiers().is_empty()
- && actions.known().is_some_and(Vec::is_empty)
+}
+
+fn is_structural_action(action: &str) -> bool {
+ matches!(
+ action,
+ agent_desktop_core::capability::RIGHT_CLICK
+ | agent_desktop_core::capability::SCROLL_TO
+ | agent_desktop_core::capability::SET_FOCUS
+ )
}
pub(crate) fn option_field<T>(value: Option<T>, uncertain: bool) -> LocatorField<T> {
@@ -161,25 +183,19 @@ mod tests {
}
#[test]
- fn only_semantically_inert_generic_elements_are_transparent() {
+ fn inert_native_groups_are_transparent() {
let (name, identifiers, actions) = inert_generic_wrapper();
- assert!(is_transparent_wrapper(
- Some("AXGenericElement"),
- None,
- &name,
- None,
- &identifiers,
- &actions,
- ));
- assert!(!is_transparent_wrapper(
- Some("AXGroup"),
- None,
- &name,
- None,
- &identifiers,
- &actions,
- ));
+ for role in ["AXGenericElement", "AXGroup"] {
+ assert!(is_transparent_wrapper(
+ Some(role),
+ None,
+ &name,
+ None,
+ &identifiers,
+ &actions,
+ ));
+ }
}
#[test]
@@ -196,7 +212,7 @@ mod tests {
));
name.native_title = None;
- let actions = LocatorField::Known(vec!["AXPress".into()]);
+ let actions = LocatorField::Known(vec![agent_desktop_core::capability::CLICK.into()]);
assert!(!is_transparent_wrapper(
Some("AXGenericElement"),
None,
@@ -206,4 +222,23 @@ mod tests {
&actions,
));
}
+
+ #[test]
+ fn structural_actions_do_not_make_anonymous_groups_consume_depth() {
+ let (name, identifiers, _) = inert_generic_wrapper();
+ let actions = LocatorField::Known(vec![
+ agent_desktop_core::capability::RIGHT_CLICK.into(),
+ agent_desktop_core::capability::SCROLL_TO.into(),
+ agent_desktop_core::capability::SET_FOCUS.into(),
+ ]);
+
+ assert!(is_transparent_wrapper(
+ Some("AXGroup"),
+ None,
+ &name,
+ None,
+ &identifiers,
+ &actions,
+ ));
+ }
}
diff --git a/crates/macos/src/tree/query/node_read.rs b/crates/macos/src/tree/query/node_read.rs
index 4999dcc36..98f058b64 100644
--- a/crates/macos/src/tree/query/node_read.rs
+++ b/crates/macos/src/tree/query/node_read.rs
@@ -5,8 +5,8 @@ use serde_json::json;
use crate::tree::query::evidence_fields::{description_field, name_field};
use crate::tree::query::node_evidence::{
- identifiers as identifier_evidence, is_transparent_wrapper, is_wrapper_candidate, option_field,
- required_complete, unknown as unknown_evidence, update_identifier_stats,
+ identifiers as identifier_evidence, is_transparent_wrapper, option_field, required_complete,
+ unknown as unknown_evidence, update_identifier_stats,
};
use crate::tree::query::node_read_context::NodeReadContext;
use crate::tree::{AXElement, query::child_read::ChildRead};
@@ -59,7 +59,58 @@ pub(crate) fn read_node(
});
}
let attrs = read.attrs;
- let wrapper_candidate = is_wrapper_candidate(attrs.role.as_deref(), attrs.subrole.as_deref());
+ let role = attrs
+ .role
+ .as_deref()
+ .map(|role| crate::tree::roles::ax_role_and_subrole_to_str(role, attrs.subrole.as_deref()))
+ .unwrap_or("unknown")
+ .to_string();
+ let secure = attrs.role.as_deref() == Some("AXSecureTextField")
+ || attrs.subrole.as_deref() == Some("AXSecureTextField");
+ let value = (!secure).then(|| attrs.value.clone()).flatten();
+ let actions = if let Some(actions) =
+ read_native_actions_if(requirements.ref_evidence.actions, || {
+ crate::tree::action_list::read_platform_available_actions(
+ element,
+ &role,
+ attrs.has_scrollbars,
+ deadline,
+ usage,
+ )
+ }) {
+ stats.reads.counts.action_reads += 1;
+ stats.reads.health.cannot_complete += u64::from(actions.cannot_complete);
+ stats.reads.health.deadline_exhausted += u64::from(actions.deadline_exhausted);
+ stats.semantic_reads.settable_reads += actions.settable_reads;
+ if actions.api_disabled {
+ return Err(permission_error("actions"));
+ }
+ if actions.invalid_element {
+ return Ok(NodeRead {
+ attrs: crate::tree::NodeAttrs::default(),
+ evidence: unknown_evidence(),
+ web_wrapper: false,
+ invalid_element: true,
+ child_read: ChildRead::empty(false),
+ evidence_complete: false,
+ });
+ }
+ if actions.complete && !actions.deadline_exhausted && !read.status.scrollbars_unknown() {
+ LocatorField::Known(actions.actions)
+ } else {
+ LocatorField::Unknown
+ }
+ } else {
+ LocatorField::Unknown
+ };
+ let wrapper_candidate = is_transparent_wrapper(
+ attrs.role.as_deref(),
+ attrs.subrole.as_deref(),
+ &attrs.name_evidence,
+ value.as_deref(),
+ &identifiers,
+ &actions,
+ );
let child_read = crate::tree::query::child_read::read_children(
element,
attrs.role.as_deref(),
@@ -85,16 +136,6 @@ pub(crate) fn read_node(
evidence_complete: false,
});
}
-
- let role = attrs
- .role
- .as_deref()
- .map(|role| crate::tree::roles::ax_role_and_subrole_to_str(role, attrs.subrole.as_deref()))
- .unwrap_or("unknown")
- .to_string();
- let secure = attrs.role.as_deref() == Some("AXSecureTextField")
- || attrs.subrole.as_deref() == Some("AXSecureTextField");
- let value = (!secure).then(|| attrs.value.clone()).flatten();
let (name_evidence, child_label_complete) = if requirements.name || requirements.description {
crate::tree::child_labels::complete_name_evidence_with_deadline(
&attrs,
@@ -138,41 +179,6 @@ pub(crate) fn read_node(
let states = requirements.states.then(|| {
crate::tree::state_reader::states_from_element(element, &attrs, &role, &state_context)
});
- let actions = if let Some(actions) =
- read_native_actions_if(requirements.ref_evidence.actions, || {
- crate::tree::action_list::read_platform_available_actions(
- element,
- &role,
- attrs.has_scrollbars,
- deadline,
- usage,
- )
- }) {
- stats.reads.counts.action_reads += 1;
- stats.reads.health.cannot_complete += u64::from(actions.cannot_complete);
- stats.reads.health.deadline_exhausted += u64::from(actions.deadline_exhausted);
- stats.semantic_reads.settable_reads += actions.settable_reads;
- if actions.api_disabled {
- return Err(permission_error("actions"));
- }
- if actions.invalid_element {
- return Ok(NodeRead {
- attrs: crate::tree::NodeAttrs::default(),
- evidence: unknown_evidence(),
- web_wrapper: false,
- invalid_element: true,
- child_read: ChildRead::empty(false),
- evidence_complete: false,
- });
- }
- if actions.complete && !actions.deadline_exhausted && !read.status.scrollbars_unknown() {
- LocatorField::Known(actions.actions)
- } else {
- LocatorField::Unknown
- }
- } else {
- LocatorField::Unknown
- };
let web_wrapper = is_transparent_wrapper(
attrs.role.as_deref(),
attrs.subrole.as_deref(),
diff --git a/crates/macos/src/tree/resolve_roots.rs b/crates/macos/src/tree/resolve_roots.rs
index 6d5fe5fe6..c6dcf83bc 100644
--- a/crates/macos/src/tree/resolve_roots.rs
+++ b/crates/macos/src/tree/resolve_roots.rs
@@ -286,7 +286,7 @@ fn verify_source_application(
)?;
if actual
.as_deref()
- .is_some_and(|actual| actual.eq_ignore_ascii_case(expected))
+ .is_some_and(|actual| agent_desktop_core::app_name_matches(actual, expected))
{
return Ok(());
}
diff --git a/crates/macos/src/tree/roles.rs b/crates/macos/src/tree/roles.rs
index 0223904f1..764325bcb 100644
--- a/crates/macos/src/tree/roles.rs
+++ b/crates/macos/src/tree/roles.rs
@@ -108,9 +108,19 @@ pub(crate) fn ax_role_and_subrole_to_str(ax_role: &str, ax_subrole: Option<&str>
pub(crate) use agent_desktop_core::roles::is_toggleable_role;
+pub(crate) fn accessible_name_from_subrole(subrole: Option<&str>) -> Option<&'static str> {
+ match subrole {
+ Some("AXCloseButton") => Some("Close"),
+ Some("AXMinimizeButton") => Some("Minimize"),
+ Some("AXZoomButton") => Some("Zoom"),
+ Some("AXFullScreenButton") => Some("Full Screen"),
+ _ => None,
+ }
+}
+
#[cfg(test)]
mod tests {
- use super::{ax_role_and_subrole_to_str, ax_role_to_str};
+ use super::{accessible_name_from_subrole, ax_role_and_subrole_to_str, ax_role_to_str};
#[test]
fn interactive_ax_roles_map_to_exact_normalized_roles() {
@@ -126,6 +136,23 @@ mod tests {
assert_eq!(ax_role_to_str("AXDockItem"), "dockitem");
}
+ #[test]
+ fn native_window_control_subroles_have_accessible_names() {
+ assert_eq!(
+ accessible_name_from_subrole(Some("AXCloseButton")),
+ Some("Close")
+ );
+ assert_eq!(
+ accessible_name_from_subrole(Some("AXMinimizeButton")),
+ Some("Minimize")
+ );
+ assert_eq!(
+ accessible_name_from_subrole(Some("AXZoomButton")),
+ Some("Zoom")
+ );
+ assert_eq!(accessible_name_from_subrole(Some("AXButton")), None);
+ }
+
#[test]
fn aliased_ax_roles_collapse_to_one_normalized_role() {
assert_eq!(ax_role_to_str("AXTextField"), "textfield");
diff --git a/docs/phases.md b/docs/phases.md
index d655b3cac..edc98fd3d 100644
--- a/docs/phases.md
+++ b/docs/phases.md
@@ -397,7 +397,7 @@ Snapshot refs persist through `RefStore`. The default namespace stores snapshots
**Progressive Skeleton Traversal:**
- `--skeleton` flag clamps depth to `min(max_depth, 3)`, annotates truncated containers with `children_count` for agent discovery
- `--root <REF>` flag starts traversal from a previously-discovered ref instead of window root; `--snapshot <snapshot_id>` selects the ref namespace
-- Named or described containers at skeleton boundary receive refs as drill-down targets (with empty `available_actions`)
+- Each truncated skeleton branch exposes its deepest safely resolvable drill target using stable text, native ID, or bounds evidence; anonymous boundaries fall back to their nearest resolvable ancestor
- Scoped invalidation: re-drilling a ref replaces only that ref's subtree refs, preserving all others
- Core modules: `ref_alloc.rs` (canonical `allocate_refs` + `RefAllocConfig`), `snapshot_ref.rs` (drill-down flow that delegates allocation to `ref_alloc`)
- macOS: `count_children()` uses raw `CFArrayGetCount` without materializing `AXElement` wrappers for performance
diff --git a/docs/plans/2026-08-21-0003-feat-agent-cursor-overlay-plan-addendum.md b/docs/plans/2026-08-21-0003-feat-agent-cursor-overlay-plan-addendum.md
new file mode 100644
index 000000000..5d9c34689
--- /dev/null
+++ b/docs/plans/2026-08-21-0003-feat-agent-cursor-overlay-plan-addendum.md
@@ -0,0 +1,39 @@
+---
+title: Native Agent Cursor Overlay - Persistent Presence Addendum
+type: feat
+date: 2026-08-21
+topic: agent-cursor-overlay
+supersedes: 2026-08-21-0003-feat-agent-cursor-overlay-plan.md
+---
+
+# Persistent Presence Addendum
+
+This addendum records the user-directed lifecycle changes accepted during live macOS dogfood. It supersedes KTD3, AE10, the process-lifecycle and privacy paragraphs, and any short-lived-child assumption in the original plan. The remaining product and planning contract stays unchanged.
+
+## Lifecycle Contract
+
+- `cursor-overlay enable` stores one session-wide setting and starts one macOS renderer for that session. It shows `Hey, let's play with this computer!` beside the persistent cursor.
+- The cursor window remains visible and alive between commands. An action updates its position, description, pointer state, and click cue; completing an action never removes it.
+- Only `cursor-overlay disable` or ending the owning session stops the renderer and removes the cursor.
+- Action commands and batch entries inherit the session setting. They never accept a cursor-enabled argument.
+- A headed command synchronously hides an existing custom cursor before using the real pointer and restores the persistent custom cursor afterward. It does not start a missing renderer.
+
+## macOS Transport
+
+- The shipped executable hosts one detached renderer child per enabled session.
+- The initial bounded control arrives through inherited stdin. Later bounded controls use a session-derived, owner-only Unix-domain socket; labels never enter process arguments.
+- A process-scoped startup lock prevents parallel commands from spawning duplicate renderer children.
+- Hide and disable are acknowledged after the renderer applies them. Presentation remains fail-soft and never changes action delivery, JSON, exit status, or retry guidance.
+- Malformed or failed later presentation messages do not terminate the persistent renderer.
+
+## Platform Boundary
+
+Core owns only portable configuration, motion, placement, control messages, and the default no-op adapter method. The binary remains the target-selection wiring point. The macOS crate alone owns process hosting, AppKit windows, drawing, display cadence, and transport. Windows and Linux need only implement that adapter method with their native renderer; no command, batch, core, or response-contract changes are required.
+
+## Updated Acceptance Examples
+
+- After enable, the greeting card and cursor remain visible for the entire session.
+- After any eligible click, the hand transition and ripple finish and the arrow remains at the destination.
+- When the description changes, the old card eases out and the new text eases in without restarting the renderer. The current card remains until that change.
+- A headed action shows only the real cursor during the action, then restores the custom cursor.
+- Disable returns only after the renderer has removed its socket and visual surface, so an immediate enable starts a fresh renderer reliably.
diff --git a/docs/plans/2026-08-21-0003-feat-agent-cursor-overlay-plan.md b/docs/plans/2026-08-21-0003-feat-agent-cursor-overlay-plan.md
new file mode 100644
index 000000000..8568c6c6e
--- /dev/null
+++ b/docs/plans/2026-08-21-0003-feat-agent-cursor-overlay-plan.md
@@ -0,0 +1,326 @@
+---
+title: Native Agent Cursor Overlay - Plan
+type: feat
+date: 2026-08-21
+topic: agent-cursor-overlay
+artifact_contract: ce-unified-plan/v1
+artifact_readiness: implementation-ready
+product_contract_source: ce-brainstorm
+execution: code
+---
+
+# Native Agent Cursor Overlay
+
+> Persistent renderer lifecycle changes from live dogfood are authoritative in [the persistent presence addendum](2026-08-21-0003-feat-agent-cursor-overlay-plan-addendum.md).
+
+## Goal Capsule
+
+- **Objective:** Let an agent optionally show a smooth, expressive cursor and short intent label at action destinations without moving, replacing, or intercepting the user's OS pointer.
+- **Means:** A deterministic shared presentation engine drives a short-lived native overlay host through a fail-soft event channel (KTD2, KTD3, KTD4).
+- **Product authority:** The user's accepted cursor prototype direction, this Product Contract, and the existing Interaction Policy contract in `CONCEPTS.md`.
+- **Execution profile:** Deep macOS delivery with a platform-neutral seam. Implement U1-U4 and U7 in dependency order; Windows and Linux retain a compiling no-op path until they add only their native renderer.
+- **Stop conditions:** Stop if presentation changes action delivery, policy, response data, or native-pointer ownership; stop if macOS lacks executable behavior evidence or another target needs core, CLI, or dispatch changes to remain compatible.
+- **Tail ownership:** LFG owns the open-PR and CI tail. It must not merge.
+
+---
+
+## Product Contract
+
+### Summary
+
+Agent Desktop gains an optional custom agent cursor that animates to verified action destinations while the real OS pointer remains untouched. The cursor uses subtle natural motion, compact click feedback, and an optional word-limited description that reveals and breathes without becoming visual noise.
+
+**Product Contract preservation:** R15 and platform scope changed by the user's final direction: macOS ships now, while the shared contract must let Windows and Linux add only their native rendering part later.
+
+### Problem Frame
+
+Headless desktop actions are effective but visually opaque: a person watching the desktop cannot see what target the agent is acting on or what it intends to do next. Reusing the real pointer would make that feedback disruptive and would violate Agent Desktop's headless interaction contract.
+
+The overlay must therefore communicate intent as presentation only. It cannot become a new input mechanism, a shortcut around strict ref resolution, or a reason to weaken delivery and retry semantics.
+
+### Actors
+
+- A1. **Agent caller:** Enables the overlay and may provide a short description for an action.
+- A2. **Desktop user:** Sees the agent's visual intent while retaining full ownership of the real pointer and desktop focus.
+- A3. **Platform renderer:** Presents the visual cursor without participating in action authority or delivery.
+
+### Key Decisions
+
+- KD1. **Use a separate visual cursor, never the OS pointer** (session-settled: user-directed — chosen over moving or commandeering the native cursor: the user must keep uninterrupted control). Governs R1, R2, R3.
+- KD2. **Ship only the macOS renderer behind a platform-neutral seam** (session-settled: user-directed — chosen over implementing three native renderers now: shared motion, configuration, and dispatch stay portable, while Windows and Linux compile through a no-op and later supply only native presentation). Governs R4, R5, R15.
+- KD3. **Use an eased minimum-jerk glide with a visible human swing, not spring motion** (session-settled: user-directed — the cursor must accelerate and settle naturally without a conspicuous spring-follow treatment). Governs R6, R7.
+- KD4. **Use a compact recognizable pointer with no blue agent dot** (session-settled: user-directed — chosen over the rejected blue circular marker: the visual should read as a cursor without dominating the screen). Governs R8.
+- KD5. **Represent clicks with a small neutral water ripple and a distinct pressed state** (session-settled: user-directed — chosen over a large blue click puck: click feedback should feel alive without becoming a spotlight). Governs R9, R10.
+- KD6. **Make the nearby description optional, customizable, and word-limited** (session-settled: user-directed — chosen over a static or unbounded label: changing intent should reveal cleanly without producing a large text bubble). Governs R11, R12, R13.
+- KD7. **Ship the overlay disabled by default and configure it once per session.** Existing commands keep their current visual behavior until the caller enables the session overlay. Governs R14, R16.
+- KD8. **Preserve the current source-window resolution behavior.** The branch's fixed exact-window targeting is the base for overlay destinations, not work to redesign. Governs R5.
+
+### Requirements
+
+**Safety and action integrity**
+
+- R1. The agent cursor is a click-through visual overlay that never moves, clicks, reads, replaces, hides, or intercepts the user's OS pointer.
+- R2. Showing the overlay never focuses an application, raises an interaction permission, or changes the selected `InteractionPolicy`.
+- R3. Overlay creation, animation, or teardown failure never changes action delivery, JSON output, exit code, retry disposition, or recovery guidance.
+- R4. Portable configuration, motion rules, action-to-visual mapping, text bounds, and deterministic behavior belong to shared core code; native surface creation, coordinate conversion, frame scheduling, and drawing belong behind default no-op `PlatformAdapter` presentation methods.
+- R5. A ref-targeted visual destination comes only from the live verified point produced by the existing resolve and preflight path, including the exact source-window behavior already fixed on this branch.
+
+**Motion and presence**
+
+- R6. Every overlay-enabled action with a verified screen destination that reaches dispatch animates the custom cursor to that point with a distance-aware minimum-jerk trajectory, clear ease-in/ease-out, and a restrained but visible swing curve.
+- R7. Motion follows the display's available frame cadence up to 120 Hz, remains smooth at 60 Hz, and completes quickly enough to feel like action feedback rather than a blocking tutorial.
+- R8. The cursor is compact, subtly tilted, immediately recognizable as a pointer, neutral in color, and free of a persistent agent dot or halo.
+- R9. Click-family actions switch the arrow briefly into a distinct hand pointer and emit a small neutral ripple centered on the destination only after dispatch has begun.
+- R10. The ripple uses short, fading concentric waves and never implies that the application verified the requested outcome.
+
+**Description container**
+
+- R11. The caller may omit the description entirely or provide explicit display text; Agent Desktop never derives display text from typed values, clipboard contents, element values, or other action payloads.
+- R12. Description text is capped by a caller-selected maximum word count, defaults to six words, has a bounded hard maximum, and truncates overflow with an ellipsis.
+- R13. The container prefers the cursor's bottom-right and uses a solid bright white surface with a 1.5px near-black border. Screen-edge placement may flip it to remain visible, and changed text reveals and breathes subtly.
+
+**Control and coverage**
+
+- R14. A dedicated CLI command enables, configures, or disables the overlay in the selected session manifest; action commands never accept or require a cursor-enable flag.
+- R15. macOS ships the native behavior now. Windows and Linux compile against the same target-selected presentation contract through a default no-op, so adding either native renderer requires no core, CLI, batch, action-dispatch, or response-contract redesign.
+- R16. Once enabled, every eligible command in the selected session, including batch entries scoped to that session, inherits the stored configuration until it is changed or disabled.
+- R17. Existing physical `hover`, `drag`, and mouse commands retain their current headed policy and action meaning; the visual overlay mirrors eligible destinations but never turns a physical hover into a headless application interaction.
+- R18. On macOS, the renderer follows the system Reduce Motion preference by replacing travel and breathing motion with a brief non-traveling appearance while preserving destination and click meaning.
+- R19. Headed mode never shows the visual overlay because the real OS cursor already represents the action.
+
+### Key Flows
+
+- F1. **Overlay-enabled headless click**
+ - **Trigger:** A1 runs a semantic click with the overlay enabled.
+ - **Steps:** Agent Desktop strictly resolves the ref, verifies the live destination, dispatches using the existing policy, and then submits one delivery-aware custom-cursor playback without touching the native pointer.
+ - **Outcome:** A2 sees where the agent acted while the command's delivery contract remains unchanged.
+ - **Covered by:** R1, R2, R3, R5, R6, R9.
+- F2. **Description appearance or change**
+ - **Trigger:** An eligible action supplies a new explicit description.
+ - **Steps:** The description is word-limited, positioned safely near the destination, and revealed with a fresh transition before settling into a subtle breath.
+ - **Outcome:** A2 can read the agent's immediate intent without a persistent or oversized panel.
+ - **Covered by:** R11, R12, R13.
+- F3. **Overlay unavailable**
+ - **Trigger:** The compositor, display, or native overlay surface is unavailable.
+ - **Steps:** The renderer skips presentation and tears down any partial visual state without modifying the action response.
+ - **Outcome:** Automation remains truthful and usable even when presentation is unavailable.
+ - **Covered by:** R3, R15.
+- F4. **Overlay disabled**
+ - **Trigger:** The caller leaves the feature off or explicitly disables it.
+ - **Steps:** Agent Desktop executes the existing command path with no renderer invocation.
+ - **Outcome:** Behavior, latency, and output match the pre-overlay CLI.
+ - **Covered by:** R14.
+
+### Acceptance Examples
+
+- AE1. **Covers R1, R2, R5, R6, R9.** **Given** an overlay-enabled strict headless click on a live ref, **When** dispatch has begun, **Then** the custom cursor glides to the verified point and emits its compact pressed ripple while the OS pointer position and application focus remain unchanged by the overlay.
+- AE2. **Covers R3, R5, R9.** **Given** a stale, ambiguous, occluded, or otherwise preflight-rejected target, **When** the command fails before dispatch, **Then** no click ripple is shown and the original structured error is returned unchanged.
+- AE3. **Covers R10.** **Given** dispatch begins but application-state verification later fails, **When** the ripple is shown, **Then** the command still reports the real unverified or failed outcome; the ripple is never treated as proof of success.
+- AE4. **Covers R11, R12, R13.** **Given** the description `Opening the profile menu for this account now` with a five-word limit, **When** it appears, **Then** the visible text is `Opening the profile menu for…`, the container reveals again, and it remains clear of the destination and screen edges.
+- AE5. **Covers R13.** **Given** one eligible action changes the visible description from the previous action, **When** the new text arrives, **Then** the container performs a fresh reveal instead of swapping text abruptly.
+- AE6. **Covers R3, R15.** **Given** the macOS overlay cannot start, or the selected target has no native renderer, **When** an otherwise valid action runs, **Then** the command keeps its original JSON body, exit code, delivery semantics, and retry guidance.
+- AE7. **Covers R14.** **Given** the overlay is disabled, **When** the same command runs, **Then** no visual surface is created and the command path is behaviorally identical to the current branch.
+- AE8. **Covers R17.** **Given** a headless invocation of the existing physical `hover` command, **When** the overlay feature is enabled, **Then** the command still returns its existing policy denial rather than pretending the application was hovered.
+- AE9. **Covers R18.** **Given** macOS Reduce Motion is enabled, **When** an eligible action presents the cursor, **Then** the cursor appears at the verified destination without traveling or breathing and any eligible click cue remains compact.
+- AE10. **Covers R19.** **Given** a session with the overlay enabled, **When** an eligible command runs with `--headed`, **Then** only the real OS cursor is used and no overlay child starts.
+
+### Success Criteria
+
+- On a 60 Hz macOS display, the native renderer shows no visible frame skipping during a normal glide; on a 120 Hz display it can use the higher cadence without changing the motion shape.
+- Enabling the overlay cannot be detected through OS pointer position, focus, interaction policy, action mechanism, or delivery semantics.
+- Description changes and click feedback remain readable at normal desktop scale without obscuring the action target.
+- macOS Reduce Motion produces no cursor travel or breathing animation.
+- macOS has behavior-level evidence for click-through input handling, coordinate mapping, teardown, and native-pointer non-displacement. Shared tests prove the portable contract, and Windows/Linux builds prove the default no-op requires no integration changes.
+
+### Scope Boundaries
+
+**In scope**
+
+- CLI and batch presentation for eligible verified action destinations.
+- Shared motion, labeling, configuration, and fail-soft behavior.
+- A platform-neutral presentation seam plus the macOS native transparent overlay surface.
+
+**Deferred to follow-up work**
+
+- FFI, language-binding, MCP, or plugin configuration parity.
+- Native Windows and Linux renderer modules; their future scope is limited to target-specific surface, coordinate, frame, and drawing code behind the existing seam.
+- Additional cursor or description-card themes beyond the fixed neutral treatment.
+- Long-lived visualization history, recordings, trails, or multi-agent cursor identities.
+
+**Outside this product's identity**
+
+- Moving or synthesizing input through the custom cursor.
+- Replacing the system cursor or hiding it from the user.
+- Browser DOM injection or a browser-only cursor implementation.
+- Treating visual feedback as verification that an application changed state.
+- Reopening the branch's source-window resolution fix.
+
+### Assumptions Deferred to Planning
+
+- Planning may choose a bounded helper, short-lived native host, or self-contained playback lifecycle. The chosen approach must preserve smooth motion between actions where practical, avoid holding the interaction lease, and satisfy R3 and R7.
+- Planning may finalize the dedicated command spelling and bounded maximum label size while preserving session-scoped opt-in, the disable path, and the six-word default required above.
+
+### Sources / Research
+
+- `docs/prototypes/2026-08-20-native-cursor-motion/decisions.md` — local-only accepted motion, cursor, click-ripple, description, and core/platform separation decisions; intentionally ignored by Git.
+- `docs/prototypes/2026-08-20-native-cursor-motion/01-motion-comparison/` — local-only standalone Rust/AppKit prototype and reproduction instructions; intentionally ignored by Git.
+- `CONCEPTS.md` — canonical Interaction Policy, Headless Ref Action, Coordinate Fallback, and exact source-window behavior.
+- `docs/solutions/best-practices/macos-gesture-headless-capability-2026-06-10.md` — portable policy belongs in core while native capability belongs in platform adapters.
+- `docs/solutions/best-practices/preserve-command-policy-semantics-during-refactor-2026-05-12.md` — shared mechanics must not flatten action-specific policy or verification.
+- `docs/solutions/best-practices/playwright-grade-desktop-reliability-2026-06-02.md` — live resolution and preflight remain authoritative before dispatch.
+- `docs/solutions/documentation-gaps/hover-drag-skip-the-actionability-battery.md` — physical pointer commands retain their dedicated headed reliability pipeline.
+- `docs/solutions/best-practices/never-ship-platform-code-that-ci-cannot-execute.md` — every platform branch requires executable behavior evidence.
+
+---
+
+## Planning Contract
+
+### Key Technical Decisions
+
+- KTD1. **Persist presentation configuration in the existing session manifest.** A dedicated command updates it once; each selected session loads it into `CommandContext`, and batch entries inherit the configuration of their selected session. Action commands, FFI, and MCP remain unchanged. Governs R3, R11, R14, R16.
+- KTD2. **Submit one fail-soft presentation instruction after action dispatch returns.** Strict resolution, actionability, and policy gates run first. Success or a delivery-aware result that confirms dispatch began may request playback; preflight and not-delivered failures request nothing. Submission errors are warning-only and never alter the action result. Governs R3, R5, R9, R10.
+- KTD3. **Run one bounded overlay child through a hidden mode of the shipped executable.** The parent writes one bounded instruction to the child's inherited stdin, closes the pipe, and never waits on animation. This keeps rendering outside the Interaction Lease without a daemon, endpoint, token, second binary, or persistent state. Governs R2, R3, R7, R16.
+- KTD4. **Extend the existing `PlatformAdapter` with default no-op presentation methods.** Core owns minimum-jerk travel, the restrained arc, reveal/breathe/ripple timing, bounds placement, action-to-cue mapping, and delivery-aware invocation. A platform override owns child startup, frame clocks, coordinate conversion, native surfaces, and drawing. Windows and Linux inherit the default without source changes. Governs R4, R6-R10, R13, R15.
+- KTD5. **Implement only the macOS native surface now.** Extract the accepted AppKit/Core Animation prototype into the macOS adapter. Other adapters inherit the default no-op and gain no placeholder native code or dependencies. Governs R1-R3, R7, R13, R15.
+- KTD6. **Expose dedicated session-scoped enable and disable commands.** `cursor-overlay enable` accepts an optional caller-authored label with a six-word default capped at twelve; `cursor-overlay disable` clears the session setting. No action or batch entry accepts a cursor flag. Governs R11-R14, R16, R19.
+
+### Assumptions
+
+- The overlay child exits after the final short playback; no cross-process cursor continuity is promised in this shipment.
+- A single command's click cue stays attached to its verified destination. A later command owns a separate bounded playback.
+
+### High-Level Technical Design
+
+```mermaid
+flowchart TB
+ CLI[cursor-overlay enable or disable] --> MANIFEST[Session manifest]
+ MANIFEST --> CTX[CommandContext]
+ CTX --> PREFLIGHT[Strict resolve and actionability]
+ PREFLIGHT --> ACTION[Existing action dispatch]
+ ACTION --> EVENTS[Delivery-aware presentation instruction]
+ EVENTS --> ADAPTER[PlatformAdapter presentation method]
+ ADAPTER --> HOST[macOS bounded child stdin]
+ ADAPTER --> NOOP[Default no-op]
+ HOST --> ENGINE[Core motion state machine]
+ ENGINE --> MAC[AppKit backend]
+```
+
+```mermaid
+sequenceDiagram
+ participant C as Core command
+ participant H as Overlay host
+ participant A as Platform action
+ C->>C: strict resolve and preflight
+ C->>A: dispatch under existing lease
+ A-->>C: result or delivery-aware error
+ C-->>H: one playback when delivery began
+ C->>C: return unchanged response semantics
+```
+
+```mermaid
+stateDiagram-v2
+ [*] --> Hidden
+ Hidden --> Traveling: playback instruction
+ Traveling --> Settled: destination reached
+ Settled --> Ripple: delivered click cue
+ Ripple --> Settled: ripple complete
+ Settled --> Hidden: display timeout
+ Hidden --> [*]: playback complete
+```
+
+### System-Wide Impact
+
+- **Command contracts:** The CLI gains one session-scoped cursor-overlay command. Action and batch-entry schemas, JSON success/error envelopes, Interaction Policy, action mechanisms, post-action waits, and FFI stay unchanged.
+- **Process lifecycle:** An enabled macOS command may start one bounded child of the current executable and write one instruction through inherited stdin. Spawn, pipe, renderer, or teardown failure only skips presentation.
+- **Privacy and security:** Labels never derive from action payloads, never enter child-process arguments, and are bounded before transport. The child accepts inherited stdin only; there is no listening endpoint or persistent credential.
+- **Performance:** Disabled mode does not connect, spawn, allocate frames, or add adapter reads. Enabled submission is bounded and occurs outside animation work; the required performance baseline detects command-latency regression.
+
+### Risks and Mitigations
+
+- **A visual cue could overstate delivery.** Submit playback only after the result proves dispatch began and key the click cue to delivery semantics, never verification.
+- **Future platform work could leak into shared layers.** Contract tests pin the adapter methods and default no-op; Windows/Linux renderer work is rejected if it changes core, CLI, batch, action dispatch, or response schemas.
+- **Multiple rapid CLI processes can briefly overlap visuals.** Accept that bounded ceiling for the first macOS shipment; add cross-process coordination only if dogfood shows visible overlap.
+
+---
+
+## Implementation Units
+
+### U1. Shared cursor contract and motion engine
+
+- **Goal:** Add bounded configuration, event, frame, protocol, and deterministic motion types without platform dependencies.
+- **Requirements:** R3, R4, R6-R13, R15, R18.
+- **Dependencies:** None.
+- **Files:** `crates/core/src/cursor_overlay/`, `crates/core/src/adapter/{actions,system}.rs`, `crates/core/src/lib.rs`, `crates/core/src/rect.rs`, `crates/core/src/cursor_overlay/tests.rs`.
+- **Approach:** Implement the accepted minimum-jerk curve, 9% bounded swing arc, distance-aware duration, reveal/breathe/ripple state, word limiting, edge placement, and bounded stdin protocol. Keep each domain type in its own file.
+- **Patterns to follow:** `crates/core/src/trace.rs` for bounded sanitized data and existing serde request types for strict protocol decoding.
+- **Test scenarios:** Covers AE4/AE5: Unicode word limits and changed labels reveal again. At 60/120 Hz the same timestamps produce the same path and terminal point. Ripple begins only for a delivered-click event, and invalid/beyond-limit protocol input is rejected.
+- **Verification:** Pure core tests prove deterministic positions, timing bounds, state transitions, label limits, the default no-op adapter contract, and no platform-crate dependency.
+
+### U2. Session-scoped CLI and context configuration
+
+- **Goal:** Add one persistent session-scoped enable/disable command and load that configuration for every selected-session command.
+- **Requirements:** R11-R14, R16, R19.
+- **Dependencies:** U1.
+- **Files:** `src/cli_args/cursor_overlay.rs`, `src/cli_args/cursor_overlay_enable.rs`, `src/cli/mod.rs`, `src/dispatch/cursor_overlay.rs`, `crates/core/src/commands/cursor_overlay.rs`, `crates/core/src/session/manifest.rs`, `crates/core/src/session/mod.rs`, `crates/core/src/context.rs`, `src/cli/contract_tests.rs`, `src/batch/tests.rs`.
+- **Approach:** Persist validated configuration in the selected session manifest through `cursor-overlay enable|disable`, then load it once into each `CommandContext`. Batch entries inherit the manifest of their selected session. Keep action schemas unchanged and suppress presentation whenever the context is headed.
+- **Test scenarios:** Covers AE7/AE10: absent or disabled session settings create no presentation request, and headed mode suppresses an enabled session overlay. Enable accepts 1-12 words; zero or overflow fails as invalid input. Single commands and batch entries scoped to the same session load identical configuration.
+- **Verification:** CLI help, clap parsing, serde denial of unknown fields, and batch context tests pin the public input contract.
+
+### U3. Delivery-aware action integration
+
+- **Goal:** Emit presentation events from verified ref-action destinations without changing action behavior.
+- **Requirements:** R1-R3, R5, R9, R10, R16, R17; F1-F4.
+- **Dependencies:** U1, U2.
+- **Files:** `crates/core/src/ref_action.rs`, `crates/core/src/ref_action/presentation.rs`, `crates/core/src/actionability/report.rs`, and related tests.
+- **Approach:** Carry a presentation point separately from physical-delivery hit-test evidence. Keep the near-limit ref-action file focused by placing event selection in its presentation submodule. Dispatch through the unchanged action path, then submit one move/label/click instruction only for success or a delivery-aware failure that confirms dispatch began. Ignore presentation errors after tracing a sanitized warning.
+- **Test scenarios:** Covers AE1-AE3/AE8: stale, ambiguous, occluded, policy-denied, or not-delivered paths emit nothing; successful click emits one playback instruction without modifying policy; post-dispatch verification failure may emit a ripple when delivery began but keeps its original response. Headed and raw pointer commands use the real cursor and do not enter the overlay path.
+- **Verification:** Mock backends assert exact event ordering and byte-equivalent command results with presentation enabled, disabled, and failing.
+
+### U4. macOS native overlay child
+
+- **Goal:** Productionize the accepted AppKit/Core Animation prototype as a click-through, no-focus renderer.
+- **Requirements:** R1-R3, R6-R10, R13, R15, R18; AE1, AE4-AE7, AE9.
+- **Dependencies:** U1-U3.
+- **Files:** `crates/macos/src/system/cursor_overlay/`, `crates/macos/src/system/mod.rs`, `crates/macos/src/adapter.rs`, `src/cursor_overlay.rs`, `src/main.rs`, `crates/macos/src/system/cursor_overlay/tests.rs`, `tests/e2e/scenarios/interaction.sh`.
+- **Approach:** Reuse the prototype's corrected pointer, neutral waves, AppKit window flags, screen clamping, display cadence, and native Reduce Motion preference. Override the existing adapter presentation methods. Route child mode before clap/tracing through the already target-selected adapter, read one instruction from inherited stdin, silence child stdout/stderr, and pump only the child's native event loop.
+- **Test scenarios:** The fixture test records OS pointer and focus before/during/after playback, confirms both remain unchanged, verifies click-through against the underlying harmless target, and captures normal, reduced-motion, and edge-position screenshots. Renderer creation or child startup failure leaves the command response unchanged and cannot contaminate stdout JSON.
+- **Verification:** macOS unit tests plus a permissioned release-binary fixture run provide behavior evidence; no user-data application is mutated.
+
+### U7. Distribution, documentation, and release proof
+
+- **Goal:** Make the hidden host and public flags shippable without regressing size, latency, or existing contracts.
+- **Requirements:** R3, R7, R14-R18 and all Success Criteria.
+- **Dependencies:** U1-U4.
+- **Files:** `README.md`, `docs/json-output.md`, relevant release/package smoke tests; `.github/workflows/ci.yml` only if existing gates do not already execute the added tests.
+- **Approach:** Keep the child mode inside the existing executable so archive layouts stay unchanged. Document the macOS capability and platform implementation seam, pin default no-op target wiring, and preserve size/performance gates; do not add overlay fields to JSON responses.
+- **Test scenarios:** Release archives still contain the same required executables; default-off invocations have equivalent output and latency; enabled macOS playback meets 60/120 Hz frame-shape expectations; Windows/Linux compile without native cursor dependencies; every executable stays under 15 MB.
+- **Verification:** CI, package smoke tests, macOS renderer evidence, cross-target no-op checks, and the repository performance baseline all pass on the final diff.
+
+---
+
+## Verification Contract
+
+| Gate | Command or evidence | Proves |
+|---|---|---|
+| Format and lint | `cargo fmt --all -- --check`; `cargo clippy --all-targets -- -D warnings` | Repository style and zero warnings |
+| Workspace tests | `cargo test --lib --workspace` | Shared, CLI, batch, and platform unit contracts |
+| Dependency inversion | `cargo tree -p agent-desktop-core` | Core imports no platform crate |
+| Native behavior | macOS fixture release run with normal and Reduce Motion settings | Click-through, no focus/pointer displacement, coordinates, teardown, accessibility, fail-soft behavior |
+| Platform seam | Core mock/no-op tests plus existing Windows/Linux target checks | Future native modules need only implement target-specific presentation |
+| Output compatibility | Golden CLI/batch success and error comparisons with cursor off/on/backend failure | R3 and default-off compatibility |
+| Performance | `bash scripts/perf-baseline-compare.sh` against the merge-base | Disabled-path latency stays flat and enabled overhead is intentional |
+| Distribution | Release/package smoke checks and 15 MB executable-size gates | Hidden child mode ships on macOS without archive drift; other targets remain unchanged |
+
+---
+
+## Definition of Done
+
+- U1-U4 and U7 verification outcomes pass, and every Product Requirement has unit or gate coverage.
+- Default-off commands perform no overlay connection, spawn, frame, or display work and keep existing JSON plus exit semantics.
+- Enabled presentation never changes the native pointer, focus, Interaction Policy, delivery disposition, retry guidance, post-action wait, or trace sanitization.
+- macOS has executable native evidence for click-through input handling, coordinate mapping, teardown, and pointer non-displacement; Windows/Linux retain compiling default no-op wiring without native implementation changes.
+- Description text is caller-authored, bounded before transport, absent from child-process argv and unsanitized trace fields, and never derived from typed or clipboard values.
+- macOS honors the system Reduce Motion preference without adding a second product setting.
+- The final release binary remains under 15 MB, the performance comparison is reviewed, and abandoned prototype-only or dead-end production code is absent from the diff.
+- A future Windows or Linux renderer can be added by overriding the target adapter's presentation methods without changing shared core behavior, CLI/batch parsing, action dispatch, binary routing, or response schemas.
+- The source-window resolution behavior on this branch remains intact and covered; the implementation does not reopen it.
diff --git a/scripts/perf-baseline-compare.sh b/scripts/perf-baseline-compare.sh
index 04139f5a5..8e5c1d9b7 100755
--- a/scripts/perf-baseline-compare.sh
+++ b/scripts/perf-baseline-compare.sh
@@ -11,8 +11,7 @@
# scripts/perf-baseline-compare.sh [--base <ref>] [--apps "Slack,Google Chrome"]
# [--rounds N] [--out <dir>] [--skip-fixture]
#
-# Real-app probes never dispatch actions. Apps this script launches itself are
-# closed again afterwards; apps that were already running are left untouched.
+# Real-app probes never dispatch actions or alter application lifecycle.
set -euo pipefail
base_ref=""
@@ -47,19 +46,41 @@ head_bin="$repo/target/release/agent-desktop"
echo "== building base release binary (${base_sha}) in a temporary worktree"
wt="$out/base-worktree"
git worktree add --detach "$wt" "$base_ref" >/dev/null
-trap 'git worktree remove --force "$wt" >/dev/null 2>&1 || true; git worktree prune >/dev/null 2>&1 || true' EXIT
+fixture_pid=""
+cleanup_fixture() {
+ [ -n "$fixture_pid" ] || return 0
+ kill "$fixture_pid" >/dev/null 2>&1 || true
+ for _ in {1..20}; do
+ if ! kill -0 "$fixture_pid" >/dev/null 2>&1; then
+ wait "$fixture_pid" 2>/dev/null || true
+ fixture_pid=""
+ return
+ fi
+ sleep 0.1
+ done
+ kill -KILL "$fixture_pid" >/dev/null 2>&1 || true
+ wait "$fixture_pid" 2>/dev/null || true
+ fixture_pid=""
+}
+cleanup() {
+ cleanup_fixture
+ git worktree remove --force "$wt" >/dev/null 2>&1 || true
+ git worktree prune >/dev/null 2>&1 || true
+}
+trap cleanup EXIT
(cd "$wt" && cargo build --release -p agent-desktop >/dev/null)
base_bin="$wt/target/release/agent-desktop"
if [ "$skip_fixture" -ne 1 ]; then
echo "== fixture A/B (${rounds} rounds; actions run against the fixture only)"
bash tests/fixture-app/build.sh "$out/fixture" >/dev/null
- open "$out/fixture/AgentDeskFixture.app"
+ "$out/fixture/AgentDeskFixture.app/Contents/MacOS/AgentDeskFixture" >/dev/null 2>&1 &
+ fixture_pid=$!
sleep 3
python3 scripts/perf_ab_probe.py --mode fixture --app AgentDeskFixture \
--head-bin "$head_bin" --base-bin "$base_bin" --rounds "$rounds" \
--json-out "$out/fixture-ab.json" >/dev/null
- pkill -f AgentDeskFixture.app || true
+ cleanup_fixture
fi
echo "== synthetic locator benchmark (HEAD)"
@@ -71,20 +92,14 @@ if [ -n "$apps" ]; then
for app in "${app_list[@]}"; do
app="$(echo "$app" | sed 's/^ *//;s/ *$//')"
slug="$(echo "$app" | tr ' ' '-' | tr '[:upper:]' '[:lower:]')"
- was_running=1
- pgrep -f "/${app}.app/" >/dev/null 2>&1 || was_running=0
- if [ "$was_running" -eq 0 ]; then
- echo "== launching ${app} for read-only observation"
- open -a "$app" || { echo " skip: cannot open ${app}"; continue; }
- sleep 12
+ if ! inventory=$("$head_bin" list-windows --app "$app" 2>&1); then
+ echo " skip: cannot verify running app ${app}: ${inventory}"
+ continue
fi
echo "== read-only probe: ${app} (${rounds} rounds, snapshots + find only)"
python3 scripts/perf_ab_probe.py --mode app --app "$app" \
--head-bin "$head_bin" --base-bin "$base_bin" --rounds "$rounds" \
--json-out "$out/app-${slug}.json" >/dev/null || echo " probe failed for ${app}"
- if [ "$was_running" -eq 0 ]; then
- "$head_bin" close-app --app "$app" >/dev/null 2>&1 || true
- fi
done
fi
diff --git a/scripts/perf_ab_probe.py b/scripts/perf_ab_probe.py
index 5ab312b5d..c0e04dbd5 100755
--- a/scripts/perf_ab_probe.py
+++ b/scripts/perf_ab_probe.py
@@ -92,6 +92,7 @@ def fixture_cases(binary, app):
button, textfield = fixture_refs(binary, app)
return [
("snapshot -i", ["snapshot", "--app", app, "-i"]),
+ ("snapshot skeleton", ["snapshot", "--app", app, "--skeleton"]),
("snapshot d30", ["snapshot", "--app", app, "--max-depth", "30"]),
("get", ["get", button]),
("is visible", ["is", button, "--property", "visible"]),
@@ -104,6 +105,7 @@ def fixture_cases(binary, app):
def app_cases(app):
return [
("snapshot -i", ["snapshot", "--app", app, "-i"]),
+ ("snapshot skeleton", ["snapshot", "--app", app, "--skeleton"]),
("snapshot d30", ["snapshot", "--app", app, "--max-depth", "30"]),
]
@@ -128,10 +130,10 @@ def summarize(results, shapes):
report = {}
for label, cases in results.items():
for name, samples in cases.items():
- times = sorted(t for t, _ in samples)
+ times = sorted(t for t, ok in samples if ok)
report.setdefault(name, {})[label] = {
- "p50_ms": round(statistics.median(times), 1),
- "p95_ms": round(times[max(0, int(len(times) * 0.95) - 1)], 1),
+ "p50_ms": round(statistics.median(times), 1) if times else None,
+ "p95_ms": round(times[max(0, int(len(times) * 0.95) - 1)], 1) if times else None,
"ok_rate": sum(1 for _, ok in samples if ok) / len(samples),
"shape": shapes[label].get(name),
}
@@ -183,6 +185,8 @@ def main():
json.dump(payload, handle, indent=1)
json.dump(payload, sys.stdout, indent=1)
print()
+ if any(side["ok_rate"] < 1.0 for case in report.values() for side in case.values()):
+ raise SystemExit(1)
if __name__ == "__main__":
diff --git a/scripts/perf_report_html.py b/scripts/perf_report_html.py
index 513bcb0a2..89a1c6fda 100644
--- a/scripts/perf_report_html.py
+++ b/scripts/perf_report_html.py
@@ -132,8 +132,7 @@ def load(path):
def fmt_ms(value):
- return f"{value:.1f} ms"
-
+ return f"{value:.1f} ms" if value is not None else "-"
def ok_pct(value):
return f"{value * 100:.0f}%"
@@ -148,7 +147,7 @@ def build_ab_rows(payload):
rows = []
for name, sides in payload.get("cases", {}).items():
head, base = sides.get("HEAD"), sides.get("BASE")
- if not head or not base:
+ if not head or not base or min(head.get("ok_rate", 1.0), base.get("ok_rate", 1.0)) < 1.0:
continue
delta_text, delta_cls = chart.fmt_delta(head["p50_ms"], base["p50_ms"])
rows.append({
@@ -225,11 +224,11 @@ def build_tiles(fixture, synthetic):
tiles = []
if fixture:
click = fixture.get("cases", {}).get("click", {})
- if click.get("HEAD") and click.get("BASE"):
+ if click.get("HEAD", {}).get("ok_rate") == click.get("BASE", {}).get("ok_rate") == 1.0:
h, b = click["HEAD"]["p50_ms"], click["BASE"]["p50_ms"]
tiles.append(tile("Click p50 (fixture)", fmt_ms(h), h, b))
d30 = fixture.get("cases", {}).get("snapshot d30", {})
- if d30.get("HEAD") and d30.get("BASE"):
+ if d30.get("HEAD", {}).get("ok_rate") == d30.get("BASE", {}).get("ok_rate") == 1.0:
h, b = d30["HEAD"]["p50_ms"], d30["BASE"]["p50_ms"]
tiles.append(tile("Snapshot d30 p50 (fixture)", fmt_ms(h), h, b))
scenarios = (synthetic or {}).get("scenarios") or []
@@ -272,11 +271,12 @@ def case_rows(payload, require_base):
head, base = sides.get("HEAD"), sides.get("BASE")
if not head or (require_base and not base):
continue
- delta_text = chart.fmt_delta(head["p50_ms"], base["p50_ms"])[0] if base else None
+ comparable = base and min(head.get("ok_rate", 1.0), base.get("ok_rate", 1.0)) == 1.0
+ delta_text = chart.fmt_delta(head["p50_ms"], base["p50_ms"])[0] if comparable else None
ok = (f'{ok_pct(base.get("ok_rate", 1.0))}/{ok_pct(head.get("ok_rate", 1.0))}' if base
else f'-/{ok_pct(head.get("ok_rate", 1.0))}')
rows.append([name, fmt_ms(base["p50_ms"]) if base else "-", fmt_ms(base["p95_ms"]) if base else "-",
- fmt_ms(head["p50_ms"]), fmt_ms(head["p95_ms"]), delta_text or "n/a", ok])
+ fmt_ms(head["p50_ms"]), fmt_ms(head["p95_ms"]), delta_text or "not comparable", ok])
return rows
diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md
index 1b0322a21..91be790fa 100644
--- a/skills/agent-desktop/SKILL.md
+++ b/skills/agent-desktop/SKILL.md
@@ -9,7 +9,7 @@ description: >
Use when an AI agent needs to observe, interact with, or automate desktop applications
(click buttons, fill forms, navigate menus, read UI state, toggle checkboxes, scroll,
drag, type text, take screenshots, manage windows, use clipboard, manage notifications).
- Covers 58 command names (54 operational; four held-input names fail closed until
+ Covers 59 command names (55 operational; four held-input names fail closed until
daemon ownership exists) across observation, interaction, keyboard/mouse, app
lifecycle, notifications (macOS), clipboard, wait, session lifecycle, and a
`skills` command that bundles docs straight from the binary.
@@ -50,13 +50,13 @@ Detailed documentation is split into focused reference files. Read them as neede
## The Observe-Act Loop (Progressive Skeleton Traversal)
-Use **progressive skeleton traversal** as the default approach. It reduces token consumption 78-96% for dense apps by exploring the UI in two phases: a shallow skeleton overview, then targeted drill-downs into regions of interest.
+When you know the target's role or exact name, use `find --role ... --name ... --exact` directly. Otherwise, use **progressive skeleton traversal** for dense or unfamiliar apps: a shallow overview followed by targeted drill-downs.
```
1. SKELETON → agent-desktop snapshot --skeleton --app "App" -i --compact
Parse the overview. Identify the region containing your target.
Regions show children_count (e.g., "Sidebar" with children_count: 42).
- Named containers at truncation boundary have refs for drill-down.
+ The nearest safely resolvable container has a ref for drill-down.
Keep the returned snapshot_id.
2. DRILL → agent-desktop snapshot --root @e3 --snapshot <snapshot_id> -i --compact
@@ -86,7 +86,7 @@ Use **progressive skeleton traversal** as the default approach. It reduces token
- Refs are assigned depth-first and emitted with their snapshot, for example `@s8f3k2p9:e1`, `@s8f3k2p9:e2`, `@s8f3k2p9:e3`. Legacy bare refs require an explicit `--snapshot`.
- An element gets a ref when it is addressable for an action: an interactive role (button, textfield, checkbox, link, menuitem, tab, slider, combobox, treeitem, cell, radiobutton, switch, ...) **or** any element advertising an action — so `scrollarea` (Scroll) and `disclosure` (Expand/Collapse) are ref-able and `scroll`/`expand`/`collapse` can target them
- A `SetFocus`-only affordance does not earn a ref on its own
-- In skeleton mode, named/described containers at truncation boundary also get refs (drill-down targets with empty `available_actions`)
+- In skeleton mode, each truncated branch exposes the deepest safely resolvable drill target using stable text, native ID, or bounds evidence; the nearest resolvable ancestor is used when the boundary itself is anonymous
- Static text and non-actionable groups/containers remain in tree for context but have no ref
- Refs are deterministic within a snapshot but NOT stable across snapshots if UI changed
- Snapshot output uses qualified refs that embed `snapshot_id` and need no separate `--snapshot`; a session-owned ref still requires the same `--session` or `AGENT_DESKTOP_SESSION` scope because lookup never crosses namespaces
@@ -134,7 +134,7 @@ Exit codes: `0` success, `1` structured error, `2` argument error.
`TIMEOUT` errors carry a `details` object whose `kind` field selects the schema. `kind: "wait_timeout"` includes `predicate`, `timeout_ms`, and `last_observed` or `last_error`, plus `ref`/`title`/`text_chars` depending on the wait mode. `kind: "chain_deadline"` includes `value_before`, `value_at_timeout`, `target`, and `mutated` (increment waits) or `wanted_expanded`/`observed_expanded` (disclosure waits). `mutated: true` — or an unknown `observed_expanded` state — means re-read the element before retrying; `mutated: false` means the state did not change and retrying directly is safe.
-## Command Quick Reference (58 names, 54 operational)
+## Command Quick Reference (59 names, 55 operational)
### Observation
```
@@ -244,6 +244,8 @@ agent-desktop session start [--name LABEL] [--screenshots] [--no-trace] # Creat
agent-desktop session end [id] # Seal manifest
agent-desktop session list # List session manifests
agent-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 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, permissions
@@ -257,14 +259,14 @@ agent-desktop skills get desktop --full # Load this skill + all referenc
## Key Principles for Agents
-1. **Skeleton first, drill second.** Start with `--skeleton -i --compact` for dense apps. Drill into regions with `--root @ref`. Full snapshot only for simple apps. For a Chromium app you are launching fresh, prefer `launch --cdp` + a CDP client for the web contents instead (principle 15).
+1. **Find known targets; skeleton unknown structure.** If role or exact name is known, use targeted `find` first. Use `--skeleton -i --compact` when the region is unknown, then drill with `--root @ref`. For fresh Chromium launches, prefer `launch --cdp` plus a CDP client.
2. **Use `-i --compact` flags.** Filters to interactive elements and collapses empty wrappers, minimizing tokens.
3. **Refs are snapshot-scoped.** Keep `snapshot_id` for deterministic multi-step use; re-drill the affected region after any UI-changing action. Scoped invalidation keeps other refs intact.
4. **Prefer refs over coordinates.** `click @s8f3k2p9:e5` > `agent-desktop --headed mouse-click --xy 500,300`.
5. **Use `wait` for async UI.** After launch/dialog triggers, wait for expected state.
6. **Check permissions first.** Run `permissions` on first use; screenshots also need Screen Recording.
7. **Handle errors.** Branch on `error.code` only — `error.message` and `error.suggestion` text is informational and may change between versions.
-8. **Use `find` for targeted searches, and scope it.** Faster than any snapshot when you know role/name. Narrow it with `--root @ref` for one region or `--surface menubar` for a menu — an unscoped find on a dense tree returns hundreds of refs and can exhaust its budget.
+8. **Scope targeted searches.** Pair known names with role and `--exact`; use `--limit 2` before a mutation when uniqueness is not guaranteed. Narrow with `--root @ref` for one region or `--surface menubar` for a menu.
9. **Use surfaces for overlays.** `snapshot --surface menu` for menus, `--surface sheet` for dialogs. Never `--skeleton` for surfaces — they're already focused. Reach one item inside an overlay with `find --surface`, not a full surface snapshot.
10. **Read `data.surfaces` after acting.** An action that opens a sheet, menu, or alert reports it there. Target that overlay next instead of searching windows for what changed.
11. **Batch for performance.** Multiple commands in one invocation.
diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.md
index c5e180848..79009698d 100644
--- a/skills/agent-desktop/references/commands-interaction.md
+++ b/skills/agent-desktop/references/commands-interaction.md
@@ -317,6 +317,10 @@ Synthesizes a scroll-wheel event at absolute coordinates and requires `--headed`
## Choosing the Right Command
+### 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.
+
| Goal | Preferred | Alternative |
|------|-----------|-------------|
| Click a button | `click @ref` | `agent-desktop --headed mouse-click --xy X,Y` if physical interaction is intended |
diff --git a/skills/agent-desktop/references/commands-observation.md b/skills/agent-desktop/references/commands-observation.md
index 2ebdfecfe..2a6ed3d85 100644
--- a/skills/agent-desktop/references/commands-observation.md
+++ b/skills/agent-desktop/references/commands-observation.md
@@ -77,7 +77,7 @@ agent-desktop snapshot --root @e12 --snapshot <snapshot_id> -i
**Skeleton mode (`--skeleton`):**
- Produces a shallow overview by clamping depth to `min(max_depth, 3)`
- Truncated containers include a `children_count` field showing how many children were omitted
-- Named or described containers at the truncation boundary receive refs with empty `available_actions`, serving as drill-down targets for `--root`
+- Each truncated branch exposes its deepest safely resolvable drill target using stable text, native ID, or bounds evidence; an anonymous boundary falls back to its nearest resolvable ancestor
**Root mode (`--root <REF>`):**
- Starts tree traversal from the given ref instead of the window root
@@ -103,7 +103,7 @@ agent-desktop snapshot --root @e3 --snapshot <snapshot_id> -i
- Use `--surface sheet` for modal dialogs
- Use `--compact` with `-i` for maximum token efficiency
- Combine `--max-depth 5` to limit deep trees (e.g., Xcode)
-- Use `--skeleton` first to get a high-level map, then `--root` to drill into specific regions
+- Use exact `find` first when you know the target role or name; otherwise use `--skeleton` for a high-level map, then `--root` to drill into specific regions
- Combine `--skeleton` with `-i` and `--compact` for the most token-efficient initial overview
- For a Chromium-based app's web contents (Slack, VS Code, Discord, and similar), `launch --cdp` plus a CDP client is a faster alternative to skeleton traversal on a fresh launch — see `references/commands-system.md`
- Keep `snapshot_id` when commands must resolve against a specific snapshot instead of the latest snapshot pointer
@@ -210,6 +210,7 @@ agent-desktop is @s8f3k2p9:e2 --property enabled
agent-desktop is @s8f3k2p9:e3 --property checked
agent-desktop is @s8f3k2p9:e4 --property focused
agent-desktop is @s8f3k2p9:e5 --property expanded
+agent-desktop is @s8f3k2p9:e6 --property selected
```
| Property | Checks |
@@ -219,6 +220,7 @@ agent-desktop is @s8f3k2p9:e5 --property expanded
| `checked` | Checkbox/switch is checked |
| `focused` | Element has keyboard focus |
| `expanded` | Disclosure/tree item is expanded |
+| `selected` | Selectable element is selected |
**Output:**
```json
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index 29829455d..f65788a69 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -455,6 +455,15 @@ Each entry may include `"session": "id"` beside `command` and `args`. If omitted
Sessions are on-disk containers under `<state root>/sessions/<id>/` with a `session.json` manifest, snapshot refmaps, and (when tracing is on) a `trace/` directory. The state root defaults to `~/.agent-desktop`; setting `AGENT_DESKTOP_HOME` relocates it — the env value is the root itself, applied to every subcommand. A relative or empty value fails with `INVALID_ARGS` before dispatch, and `status` reports the resolved root as `state_root`. Session selection is explicit; `session start` returns an ID but does not activate it for later processes.
+### 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
+```
+
+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.
+
### session start
```bash
agent-desktop session start
diff --git a/skills/agent-desktop/references/macos.md b/skills/agent-desktop/references/macos.md
index 78cef0f54..1bd04a6f3 100644
--- a/skills/agent-desktop/references/macos.md
+++ b/skills/agent-desktop/references/macos.md
@@ -243,6 +243,10 @@ After `right-click @ref`, inspect the open menu or the target effect. If macOS r
## macOS-Specific Behavior
+### 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.
+
### App Identification
Apps can be referenced by:
diff --git a/src/batch/mod.rs b/src/batch/mod.rs
index 1629f86c2..431a685dc 100644
--- a/src/batch/mod.rs
+++ b/src/batch/mod.rs
@@ -95,6 +95,10 @@ pub(crate) fn parse_command(item: BatchCommand) -> Result<Commands, AppError> {
"version" => no_args(command, item.args).map(|()| Commands::Version),
"skills" => parse_skills(item.args).map(Commands::Skills),
"session" => parse_session(item.args).map(Commands::Session),
+ "cursor-overlay" => Err(AppError::invalid_input_with_suggestion(
+ "Cursor overlay configuration cannot run inside a batch",
+ "Enable or disable it once for the selected session before running the batch.",
+ )),
"trace" => parse_trace(item.args).map(Commands::Trace),
"batch" => Err(AppError::invalid_input_with_suggestion(
"Batch commands cannot be nested",
diff --git a/src/batch/tests.rs b/src/batch/tests.rs
index 146a96824..28c603611 100644
--- a/src/batch/tests.rs
+++ b/src/batch/tests.rs
@@ -22,6 +22,16 @@ fn parses_optional_batch_session_scope() {
assert_eq!(commands[0].session.as_deref(), Some("agent-a"));
}
+#[test]
+fn rejects_per_item_cursor_configuration() {
+ let error = agent_desktop_core::commands::batch::parse_commands(
+ r#"[{"command":"status","agent_cursor":{"enabled":true},"args":{}}]"#,
+ )
+ .expect_err("cursor configuration belongs to the session command");
+
+ assert!(error.to_string().contains("agent_cursor"));
+}
+
#[test]
fn session_batch_rejects_unknown_field() {
assert!(
diff --git a/src/cli/contract_tests.rs b/src/cli/contract_tests.rs
index 82b99c03c..f0efc6600 100644
--- a/src/cli/contract_tests.rs
+++ b/src/cli/contract_tests.rs
@@ -1,4 +1,4 @@
-use crate::cli::Cli;
+use crate::cli::{Cli, Commands};
use clap::{CommandFactory, Parser, error::ErrorKind};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
@@ -35,6 +35,7 @@ const NON_COMMAND_MODULES: &[&str] = &[
];
const COMMAND_SPECIFIC_TESTS: &[&str] = &[
+ "cursor-overlay",
"find",
"focus-window",
"is",
@@ -81,6 +82,62 @@ fn standard_version_flag_reports_the_package_version() {
);
}
+#[test]
+fn cursor_overlay_enable_is_session_scoped_and_bounded() {
+ let cli = Cli::try_parse_from([
+ "agent-desktop",
+ "--session",
+ "run-1",
+ "cursor-overlay",
+ "enable",
+ "--label",
+ "Opening the profile menu for this account now",
+ "--max-words",
+ "5",
+ ])
+ .expect("valid cursor overlay command");
+ let Commands::CursorOverlay(args) = cli.command.expect("command") else {
+ panic!("expected cursor overlay command");
+ };
+ let crate::cli_args::cursor_overlay_action::CursorOverlayAction::Enable(args) = args.action
+ else {
+ panic!("expected enable action");
+ };
+ let config = args.to_core().expect("valid cursor config");
+
+ assert_eq!(cli.session.as_deref(), Some("run-1"));
+ assert!(config.is_enabled());
+ assert_eq!(config.label(), Some("Opening the profile menu for…"));
+}
+
+#[test]
+fn cursor_overlay_disable_is_a_dedicated_command() {
+ let cli = Cli::try_parse_from([
+ "agent-desktop",
+ "--session",
+ "run-1",
+ "cursor-overlay",
+ "disable",
+ ])
+ .expect("valid disable command");
+
+ let Commands::CursorOverlay(args) = cli.command.expect("command") else {
+ panic!("expected cursor overlay command");
+ };
+ assert!(matches!(
+ args.action,
+ crate::cli_args::cursor_overlay_action::CursorOverlayAction::Disable
+ ));
+}
+
+#[test]
+fn action_commands_reject_the_removed_cursor_flag() {
+ let error = Cli::try_parse_from(["agent-desktop", "--agent-cursor", "on", "click", "@e1"])
+ .expect_err("cursor configuration is not an action flag");
+
+ assert_eq!(error.kind(), ErrorKind::UnknownArgument);
+}
+
#[test]
fn ci_compares_the_release_binary_to_the_workspace_version() {
let workflow = include_str!("../../.github/workflows/ci.yml");
@@ -170,12 +227,12 @@ fn macos_capability_count_includes_restored_notifications() {
let commands = cli_command_names();
assert_eq!(
commands.len(),
- 58,
+ 59,
"the published CLI command count changed"
);
assert_eq!(
commands.len(),
- 58,
+ 59,
"macOS operational command count changed; update capability documentation"
);
}
diff --git a/src/cli/help_after.txt b/src/cli/help_after.txt
index 97c33c131..4cb560998 100644
--- a/src/cli/help_after.txt
+++ b/src/cli/help_after.txt
@@ -3,7 +3,7 @@ OBSERVATION
screenshot PNG screenshot of an application window
find Search elements by role, name, value, or text (--limit defaults to 50)
get <ref> --property <p> Read element property: text, value, title, bounds, role, states
- is <ref> --property <p> Check state: visible, enabled, checked, focused, expanded
+ is <ref> --property <p> Check state: visible, enabled, checked, focused, expanded, selected
list-surfaces Available surfaces for an app
INTERACTION
@@ -85,6 +85,8 @@ SYSTEM
session end Seal a manifest (ID from argument, --session, or environment)
session list List session manifests
session gc Remove ended or provably-stale sessions
+ cursor-overlay enable Enable/configure the visual cursor for the selected session
+ cursor-overlay disable Disable the visual cursor for the selected session
ENVIRONMENT
AGENT_DESKTOP_SESSION Session ID fallback when --session is not passed
@@ -142,6 +144,7 @@ EXAMPLES
agent-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> click @s8f3k2p9:e5
agent-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/mod.rs b/src/cli/mod.rs
index 9ad095853..d46721690 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -12,6 +12,7 @@ use crate::cli_args::{
ScrollArgs, SelectArgs, SetValueArgs, TypeArgs,
},
batch::BatchArgs,
+ cursor_overlay::CursorOverlayArgs,
drag::DragCliArgs,
mouse_wheel::MouseWheelArgs,
notifications::{
@@ -38,7 +39,9 @@ pub(crate) enum Commands {
Screenshot(ScreenshotArgs),
#[command(about = "Read an element property (text, value, title, bounds, role, states)")]
Get(GetArgs),
- #[command(about = "Check element state (visible, enabled, checked, focused, expanded)")]
+ #[command(
+ about = "Check element state (visible, enabled, checked, focused, expanded, selected)"
+ )]
Is(IsArgs),
#[command(about = "Click element via accessibility press action")]
Click(RefArgs),
@@ -150,6 +153,8 @@ pub(crate) enum Commands {
Skills(SkillsArgs),
#[command(about = "Manage trace-enabled agent sessions (start, end, list, gc)")]
Session(SessionArgs),
+ #[command(about = "Configure the presentation-only cursor overlay for a session")]
+ CursorOverlay(CursorOverlayArgs),
#[command(about = "Read merged session trace timelines")]
Trace(TraceArgs),
}
@@ -231,6 +236,7 @@ impl Commands {
Self::Batch(_) => CommandMetadata::new("batch", false),
Self::Skills(_) => CommandMetadata::new("skills", false),
Self::Session(_) => CommandMetadata::new("session", false),
+ Self::CursorOverlay(_) => CommandMetadata::new("cursor-overlay", false),
Self::Trace(_) => CommandMetadata::new("trace", false),
}
}
@@ -291,6 +297,7 @@ impl Commands {
Self::Session(args) => {
!matches!(&args.action, crate::cli_args::session::SessionAction::List)
}
+ Self::CursorOverlay(_) => true,
Self::Trace(args) => {
matches!(&args.action, crate::cli_args::trace::TraceAction::Export(_))
}
diff --git a/src/cli/root.rs b/src/cli/root.rs
index 5dc6c9aca..d044f7492 100644
--- a/src/cli/root.rs
+++ b/src/cli/root.rs
@@ -3,6 +3,7 @@ use std::path::PathBuf;
use clap::Parser;
use super::{Commands, post_action_wait::PostActionWaitArgs};
+use crate::cli_args::interaction::InteractionArgs;
const BEFORE_HELP: &str = include_str!("help_before.txt");
const AFTER_HELP: &str = include_str!("help_after.txt");
@@ -42,12 +43,8 @@ pub(crate) struct Cli {
help = "Fail on trace setup/pre-action write errors"
)]
pub trace_strict: bool,
- #[arg(
- long,
- global = true,
- help = "Prefer physical delivery for natural input commands and permit focus/cursor side effects. Default is strict headless semantic delivery."
- )]
- pub headed: bool,
+ #[command(flatten)]
+ pub interaction: InteractionArgs,
#[command(flatten)]
pub post_action_wait: PostActionWaitArgs,
#[command(subcommand)]
diff --git a/src/cli_args/cursor_overlay.rs b/src/cli_args/cursor_overlay.rs
new file mode 100644
index 000000000..3bdb74602
--- /dev/null
+++ b/src/cli_args/cursor_overlay.rs
@@ -0,0 +1,9 @@
+use clap::Args;
+
+use super::cursor_overlay_action::CursorOverlayAction;
+
+#[derive(Args, Debug)]
+pub(crate) struct CursorOverlayArgs {
+ #[command(subcommand)]
+ pub action: CursorOverlayAction,
+}
diff --git a/src/cli_args/cursor_overlay_action.rs b/src/cli_args/cursor_overlay_action.rs
new file mode 100644
index 000000000..fa37b4f9a
--- /dev/null
+++ b/src/cli_args/cursor_overlay_action.rs
@@ -0,0 +1,11 @@
+use clap::Subcommand;
+
+use super::cursor_overlay_enable::CursorOverlayEnableArgs;
+
+#[derive(Subcommand, Debug)]
+pub(crate) enum CursorOverlayAction {
+ #[command(about = "Enable and configure the cursor overlay for the selected session")]
+ Enable(CursorOverlayEnableArgs),
+ #[command(about = "Disable the cursor overlay for the selected session")]
+ Disable,
+}
diff --git a/src/cli_args/cursor_overlay_enable.rs b/src/cli_args/cursor_overlay_enable.rs
new file mode 100644
index 000000000..fc717b4c1
--- /dev/null
+++ b/src/cli_args/cursor_overlay_enable.rs
@@ -0,0 +1,38 @@
+use clap::Args;
+
+#[derive(Args, Debug)]
+pub(crate) struct CursorOverlayEnableArgs {
+ #[arg(
+ long,
+ help = "Show caller-authored intent text beside the cursor overlay"
+ )]
+ pub label: Option<String>,
+ #[arg(
+ long,
+ value_parser = parse_word_limit,
+ help = "Limit the cursor overlay label to 1-12 words (default 6)"
+ )]
+ pub max_words: Option<usize>,
+}
+
+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)
+ }
+}
+
+fn parse_word_limit(value: &str) -> Result<usize, String> {
+ let parsed = value
+ .parse::<usize>()
+ .map_err(|_| "word limit must be an integer from 1 to 12".to_string())?;
+ if (1..=12).contains(&parsed) {
+ Ok(parsed)
+ } else {
+ Err("word limit must be from 1 to 12".to_string())
+ }
+}
diff --git a/src/cli_args/interaction.rs b/src/cli_args/interaction.rs
new file mode 100644
index 000000000..7d28765ce
--- /dev/null
+++ b/src/cli_args/interaction.rs
@@ -0,0 +1,11 @@
+use clap::Args;
+
+#[derive(Args, Debug, Default)]
+pub(crate) struct InteractionArgs {
+ #[arg(
+ long,
+ global = true,
+ help = "Prefer physical delivery for natural input commands and permit focus/cursor side effects. Default is strict headless semantic delivery."
+ )]
+ pub headed: bool,
+}
diff --git a/src/cli_args/mod.rs b/src/cli_args/mod.rs
index 16ce6a3e6..faba9817a 100644
--- a/src/cli_args/mod.rs
+++ b/src/cli_args/mod.rs
@@ -3,8 +3,12 @@ use serde::Deserialize;
pub(crate) mod actions;
pub(crate) mod batch;
+pub(crate) mod cursor_overlay;
+pub(crate) mod cursor_overlay_action;
+pub(crate) mod cursor_overlay_enable;
pub(crate) mod drag;
pub(crate) mod drag_target;
+pub(crate) mod interaction;
pub(crate) mod mouse_wheel;
pub(crate) mod notifications;
pub(crate) mod session;
@@ -261,7 +265,7 @@ pub(crate) struct IsArgs {
#[arg(
long,
default_value = "visible",
- help = "State: visible, enabled, checked, focused, expanded"
+ help = "State: visible, enabled, checked, focused, expanded, selected"
)]
#[serde(default = "default_is_property")]
pub property: String,
diff --git a/src/command_policy/mod.rs b/src/command_policy/mod.rs
index 0aa22c2e8..66479810b 100644
--- a/src/command_policy/mod.rs
+++ b/src/command_policy/mod.rs
@@ -15,7 +15,11 @@ pub(crate) enum PermissionNeed {
pub(crate) fn policy_for(cmd: &Commands) -> PermissionNeed {
use PermissionNeed::{Accessibility, AccessibilityAndScreenRecording, None, ScreenRecording};
match cmd {
- Commands::Version | Commands::Skills(_) | Commands::Session(_) | Commands::Trace(_) => None,
+ Commands::Version
+ | Commands::Skills(_)
+ | Commands::Session(_)
+ | Commands::CursorOverlay(_)
+ | Commands::Trace(_) => None,
Commands::Status | Commands::Permissions(_) => None,
Commands::ListWindows(_) | Commands::ListDisplays | Commands::ListApps(_) => None,
Commands::ClipboardGet(_) | Commands::ClipboardSet(_) | Commands::ClipboardClear => None,
@@ -221,6 +225,7 @@ fn validate_args(cmd: &Commands) -> Result<(), AppError> {
| Commands::Batch(_)
| Commands::Skills(_)
| Commands::Session(_)
+ | Commands::CursorOverlay(_)
| Commands::Trace(_) => {}
}
Ok(())
diff --git a/src/dispatch/cursor_overlay.rs b/src/dispatch/cursor_overlay.rs
new file mode 100644
index 000000000..ce4e037c8
--- /dev/null
+++ b/src/dispatch/cursor_overlay.rs
@@ -0,0 +1,40 @@
+use agent_desktop_core::{
+ AppError, CursorOverlayControl, PlatformAdapter, commands::cursor_overlay,
+ context::CommandContext,
+};
+use serde_json::Value;
+
+use crate::cli_args::{
+ cursor_overlay::CursorOverlayArgs, cursor_overlay_action::CursorOverlayAction,
+};
+
+pub(crate) fn dispatch(
+ args: CursorOverlayArgs,
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+) -> Result<Value, AppError> {
+ let session_id = context.session_id().ok_or_else(|| {
+ AppError::invalid_input_with_suggestion(
+ "Cursor overlay settings require an active session",
+ "Run `session start`, then pass its id with --session or AGENT_DESKTOP_SESSION.",
+ )
+ })?;
+ 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::Disable => (
+ cursor_overlay::CursorOverlayAction::Disable,
+ Some(CursorOverlayControl::disable(session_id.to_owned())),
+ ),
+ };
+ let value = cursor_overlay::execute(session_id, action)?;
+ if let Some(control) = control
+ && let Err(error) = adapter.update_cursor_overlay(&control)
+ {
+ tracing::warn!(code = %error.code.as_str(), "cursor overlay lifecycle update was skipped");
+ }
+ Ok(value)
+}
diff --git a/src/dispatch/mod.rs b/src/dispatch/mod.rs
index 935df32c0..991d65df3 100644
--- a/src/dispatch/mod.rs
+++ b/src/dispatch/mod.rs
@@ -1,5 +1,6 @@
mod app_window;
mod clipboard;
+mod cursor_overlay;
mod interaction;
mod keyboard_mouse;
mod notifications;
@@ -9,7 +10,9 @@ mod session;
mod system;
mod trace;
-use agent_desktop_core::{AppError, PermissionReport, PlatformAdapter, context::CommandContext};
+use agent_desktop_core::{
+ AppError, CursorOverlayControl, PermissionReport, PlatformAdapter, context::CommandContext,
+};
use serde_json::Value;
use crate::cli::Commands;
@@ -21,11 +24,20 @@ pub(crate) fn dispatch(
context: &CommandContext,
) -> Result<Value, AppError> {
tracing::debug!("dispatch: {}", cmd.name());
+ let overlay_session =
+ if cmd.is_mutating() && context.is_headed() && context.cursor_overlay().is_enabled() {
+ context.session_id().map(str::to_owned)
+ } else {
+ None
+ };
let scope = if cmd.is_mutating() {
context.mutating_command_scope(cmd.name())?
} else {
context.command_scope(cmd.name())?
};
+ if let Some(session_id) = overlay_session.as_ref() {
+ let _ = adapter.update_cursor_overlay(&CursorOverlayControl::hide(session_id.clone()));
+ }
let result = match cmd {
Commands::Snapshot(args) => observation::snapshot(args, adapter, context),
Commands::Find(args) => observation::find(args, adapter, context),
@@ -85,9 +97,13 @@ pub(crate) fn dispatch(
Commands::Version => system::version(),
Commands::Batch(args) => system::batch(args, adapter, permission_report, context),
Commands::Skills(args) => system::skills(args),
- Commands::Session(args) => system::session(args, context),
+ Commands::Session(args) => system::session(args, adapter, context),
+ Commands::CursorOverlay(args) => cursor_overlay::dispatch(args, adapter, context),
Commands::Trace(args) => system::trace(args, context),
};
+ if let Some(session_id) = overlay_session {
+ let _ = adapter.update_cursor_overlay(&CursorOverlayControl::show(session_id));
+ }
scope.complete(&result)?;
result
}
diff --git a/src/dispatch/parse.rs b/src/dispatch/parse.rs
index 3b4cfc796..7aa7d19e4 100644
--- a/src/dispatch/parse.rs
+++ b/src/dispatch/parse.rs
@@ -26,8 +26,9 @@ pub(crate) fn parse_is_property(s: &str) -> Result<is_check::IsProperty, AppErro
"checked" => Ok(is_check::IsProperty::Checked),
"focused" => Ok(is_check::IsProperty::Focused),
"expanded" => Ok(is_check::IsProperty::Expanded),
+ "selected" => Ok(is_check::IsProperty::Selected),
_ => Err(AppError::invalid_input(
- "Unknown property. Valid: visible, enabled, checked, focused, expanded",
+ "Unknown property. Valid: visible, enabled, checked, focused, expanded, selected",
)),
}
}
diff --git a/src/dispatch/parse_tests.rs b/src/dispatch/parse_tests.rs
index 8cf354f61..0d241ca1c 100644
--- a/src/dispatch/parse_tests.rs
+++ b/src/dispatch/parse_tests.rs
@@ -43,12 +43,17 @@ fn rejects_unknown_get_property() {
#[test]
fn rejects_unknown_is_property() {
- match parse_is_property("selected") {
+ match parse_is_property("placeholder") {
Ok(_) => panic!("expected invalid is property"),
Err(err) => assert_eq!(err.code(), "INVALID_ARGS"),
}
}
+#[test]
+fn parses_selected_is_property() {
+ assert!(parse_is_property("selected").is_ok());
+}
+
#[test]
fn rejects_unknown_mouse_button() {
assert_eq!(
diff --git a/src/dispatch/session.rs b/src/dispatch/session.rs
index d053ee0f5..6719e6a1c 100644
--- a/src/dispatch/session.rs
+++ b/src/dispatch/session.rs
@@ -1,9 +1,15 @@
-use agent_desktop_core::{AppError, commands::session, context::CommandContext};
+use agent_desktop_core::{
+ AppError, CursorOverlayControl, PlatformAdapter, commands::session, context::CommandContext,
+};
use serde_json::Value;
use crate::cli_args::session::{SessionAction, SessionArgs};
-pub(crate) fn dispatch(args: SessionArgs, context: &CommandContext) -> Result<Value, AppError> {
+pub(crate) fn dispatch(
+ args: SessionArgs,
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+) -> Result<Value, AppError> {
match args.action {
SessionAction::Start(s) => session::execute(session::SessionAction::Start {
name: s.name,
@@ -12,7 +18,9 @@ pub(crate) fn dispatch(args: SessionArgs, context: &CommandContext) -> Result<Va
}),
SessionAction::End(e) => {
let id = resolve_end_session_id(e.id, context.session_id())?;
- session::execute(session::SessionAction::End { id })
+ let value = session::execute(session::SessionAction::End { id: id.clone() })?;
+ let _ = adapter.update_cursor_overlay(&CursorOverlayControl::disable(id));
+ Ok(value)
}
SessionAction::List => session::execute(session::SessionAction::List),
SessionAction::Gc(g) => session::execute(session::SessionAction::Gc {
diff --git a/src/dispatch/system.rs b/src/dispatch/system.rs
index d3d187d10..49972553a 100644
--- a/src/dispatch/system.rs
+++ b/src/dispatch/system.rs
@@ -90,8 +90,12 @@ pub(super) fn skills(args: SkillsArgs) -> Result<Value, AppError> {
}
}
-pub(super) fn session(args: SessionArgs, context: &CommandContext) -> Result<Value, AppError> {
- session_dispatch::dispatch(args, context)
+pub(super) fn session(
+ args: SessionArgs,
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+) -> Result<Value, AppError> {
+ session_dispatch::dispatch(args, adapter, context)
}
pub(super) fn trace(args: TraceArgs, context: &CommandContext) -> Result<Value, AppError> {
diff --git a/src/main.rs b/src/main.rs
index c541dd850..299cc14ae 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -16,7 +16,7 @@ mod dispatch;
mod test_noop_ops;
use agent_desktop_core::{
- AdapterError, AppError, DeliverySemantics, ErrorCode,
+ AdapterError, AppError, DeliverySemantics, ErrorCode, SystemOps,
context::{CommandContext, WaitSelector},
output::{ErrorPayload, Response},
session::resolve_active_session,
@@ -30,6 +30,13 @@ use std::process::ExitCode;
const EXIT_INVALID_ARGS: u8 = 2;
fn main() -> ExitCode {
+ if let Some(result) = build_adapter().run_cursor_overlay_child() {
+ return if result.is_ok() {
+ ExitCode::SUCCESS
+ } else {
+ ExitCode::FAILURE
+ };
+ }
#[cfg(target_os = "macos")]
if let Some(exit_code) = run_permission_prompt_helper() {
return exit_code;
@@ -132,7 +139,7 @@ fn run() -> ExitCode {
};
let context = match CommandContext::new(session_id, cli.trace, cli.trace_strict) {
Ok(context) => context
- .with_headed(cli.headed)
+ .with_headed(cli.interaction.headed)
.with_wait_selector(wait_selector.clone()),
Err(err) => {
return finish(cmd_name, Err(pre_dispatch_error(err)));