Skip to content

Computer use CLI for AI agents

fix: keep the overlay caret on the insertion point after key presses (#353)

Chris Tate2ef0d3bef387
diff --git a/apps/docs/content/docs/commands/system.mdx b/apps/docs/content/docs/commands/system.mdx
index 560baa8d2..9d2aa2da0 100644
--- a/apps/docs/content/docs/commands/system.mdx
+++ b/apps/docs/content/docs/commands/system.mdx
@@ -115,7 +115,7 @@ agent-desktop session gc [--older-than SECONDS] [--ended]
## cursor-overlay
-Configures the presentation-only cursor overlay for a session. The overlay draws an agent cursor, a click ripple, and an element highlight, and never changes what an action does. On macOS and Windows, after `type` or `set-value` lands, it also draws a caret at the field's insertion point. It needs an active session, and it cannot run inside a [batch](/desktop/commands/batch).
+Configures the presentation-only cursor overlay for a session. The overlay draws an agent cursor, a click ripple, and an element highlight, and never changes what an action does. On macOS and Windows, after `type` or `set-value` lands, it also draws a caret at the field's insertion point, and moves it after a `press` that moves the insertion point. It needs an active session, and it cannot run inside a [batch](/desktop/commands/batch).
```bash
agent-desktop --session "$AGENT_DESKTOP_SESSION" cursor-overlay enable [STYLE FLAGS]
diff --git a/crates/core/src/adapter/observation.rs b/crates/core/src/adapter/observation.rs
index 819854a9c..876fb0373 100644
--- a/crates/core/src/adapter/observation.rs
+++ b/crates/core/src/adapter/observation.rs
@@ -226,6 +226,18 @@ pub trait ObservationOps: Send + Sync {
Err(AdapterError::not_supported("get_insertion_caret"))
}
+ /// The insertion point of the text element that has keyboard focus, in
+ /// `process` when given and system-wide otherwise, as
+ /// [`get_insertion_caret`](Self::get_insertion_caret) reports it. `None`
+ /// when the focused element is not a text element or has no insertion point.
+ fn get_focused_insertion_caret(
+ &self,
+ _process: Option<crate::ProcessId>,
+ _deadline: Deadline,
+ ) -> Result<Option<Rect>, AdapterError> {
+ Err(AdapterError::not_supported("get_focused_insertion_caret"))
+ }
+
/// Fresh pointer geometry and visibility from one observation when supported.
/// The default preserves bounds-first reads and optional state evidence.
fn observe_pointer(
diff --git a/crates/core/src/commands/press.rs b/crates/core/src/commands/press.rs
index 5c32fc49a..81a6c8010 100644
--- a/crates/core/src/commands/press.rs
+++ b/crates/core/src/commands/press.rs
@@ -24,6 +24,7 @@ pub fn execute(
ensure_combo_allowed(&combo, &args.combo, args.force, adapter)?;
let deadline = crate::Deadline::standard()?;
+ let mut pressed_process = None;
let result = if let Some((expected, window)) = target_app(&args, adapter, deadline)? {
let lease = adapter.acquire_interaction_lease(deadline)?;
let live = crate::commands::helpers::revalidate_app_for_mutation(
@@ -32,6 +33,7 @@ pub fn execute(
lease.deadline(),
)?;
let process = crate::commands::helpers::process_identity(&live)?;
+ pressed_process = Some(process.pid);
if context.physical_input_policy().is_headed() {
match &window {
Some(window) => crate::actions::headed_focus::focus_exact_window(
@@ -61,6 +63,7 @@ pub fn execute(
&lease,
)?
};
+ crate::cursor_overlay::follow_caret_after_key(adapter, context, pressed_process);
super::helpers::apply_scoped_post_action_wait(
serde_json::to_value(result)?,
args.app,
diff --git a/crates/core/src/cursor_overlay/caret_follow.rs b/crates/core/src/cursor_overlay/caret_follow.rs
new file mode 100644
index 000000000..644c28c26
--- /dev/null
+++ b/crates/core/src/cursor_overlay/caret_follow.rs
@@ -0,0 +1,69 @@
+//! Keeps the agent's caret on the insertion point after a key press.
+//!
+//! A key such as an arrow or a formatting shortcut can move the insertion
+//! point without any text being typed, which would leave a caret drawn by an
+//! earlier `type` behind. The app handles the key after it is posted, so the
+//! insertion point is read until two reads agree after a short settle, inside
+//! a small budget.
+
+use std::time::{Duration, Instant};
+
+use crate::{AdapterError, CommandContext, Deadline, ErrorCode, PlatformAdapter, ProcessId, Rect};
+
+const SETTLE: Duration = Duration::from_millis(60);
+const SETTLE_LIMIT: Duration = Duration::from_millis(240);
+const POLL: Duration = Duration::from_millis(20);
+const READ_BUDGET_MS: u64 = 150;
+
+/// After a key press reaches `process` (or the focused app, when `None`),
+/// moves a caret the overlay is showing to the focused text element's
+/// insertion point, or hides it when there is none. Nothing is sent when the
+/// overlay is off or the adapter cannot read the focused insertion point.
+pub(crate) fn follow_caret_after_key(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ process: Option<ProcessId>,
+) {
+ if !context.cursor_overlay().is_enabled() {
+ return;
+ }
+ let read = |deadline| adapter.get_focused_insertion_caret(process, deadline);
+ if let Some(caret) = settled_caret(read, POLL) {
+ super::submit_caret_follow(adapter, context, caret);
+ }
+}
+
+/// The insertion point once it has settled: the first read that matches the
+/// one before it after [`SETTLE`], or the last read at [`SETTLE_LIMIT`].
+/// `None` when the adapter does not support the read or the first read fails.
+fn settled_caret(
+ read: impl Fn(Deadline) -> Result<Option<Rect>, AdapterError>,
+ poll: Duration,
+) -> Option<Option<Rect>> {
+ let started = Instant::now();
+ let mut previous: Option<Option<Rect>> = None;
+ loop {
+ let current = match Deadline::after(READ_BUDGET_MS).map(&read) {
+ Ok(Ok(current)) => current,
+ Ok(Err(error))
+ if matches!(
+ error.code,
+ ErrorCode::PlatformNotSupported | ErrorCode::ActionNotSupported
+ ) =>
+ {
+ return None;
+ }
+ Ok(Err(_)) | Err(_) => return previous,
+ };
+ let elapsed = started.elapsed();
+ if elapsed >= SETTLE_LIMIT || (elapsed >= SETTLE && previous == Some(current)) {
+ return Some(current);
+ }
+ previous = Some(current);
+ std::thread::sleep(poll);
+ }
+}
+
+#[cfg(test)]
+#[path = "caret_follow_tests.rs"]
+mod tests;
diff --git a/crates/core/src/cursor_overlay/caret_follow_tests.rs b/crates/core/src/cursor_overlay/caret_follow_tests.rs
new file mode 100644
index 000000000..50cbd621d
--- /dev/null
+++ b/crates/core/src/cursor_overlay/caret_follow_tests.rs
@@ -0,0 +1,130 @@
+use super::settled_caret;
+use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps};
+use crate::{AdapterError, CommandContext, CursorOverlayControl, CursorPhase, Rect};
+use std::cell::Cell;
+use std::sync::Mutex;
+use std::time::Duration;
+
+fn caret_at(x: f64) -> Rect {
+ Rect {
+ x,
+ y: 10.0,
+ width: 2.0,
+ height: 16.0,
+ }
+}
+
+#[test]
+fn the_caret_is_read_until_the_app_has_moved_the_insertion_point() {
+ let reads = [
+ caret_at(40.0),
+ caret_at(64.0),
+ caret_at(64.0),
+ caret_at(64.0),
+ ];
+ let index = Cell::new(0);
+
+ let settled = settled_caret(
+ |_| {
+ let read = reads[index.get().min(reads.len() - 1)];
+ index.set(index.get() + 1);
+ Ok(Some(read))
+ },
+ Duration::from_millis(25),
+ );
+
+ assert_eq!(settled, Some(Some(caret_at(64.0))));
+}
+
+#[test]
+fn a_focused_element_without_an_insertion_point_settles_on_none() {
+ assert_eq!(
+ settled_caret(|_| Ok(None), Duration::from_millis(25)),
+ Some(None)
+ );
+}
+
+#[test]
+fn an_adapter_that_cannot_read_the_focused_caret_leaves_the_caret_alone() {
+ assert_eq!(
+ settled_caret(
+ |_| Err(AdapterError::not_supported("get_focused_insertion_caret")),
+ Duration::from_millis(25),
+ ),
+ None
+ );
+}
+
+struct FocusedCaretAdapter {
+ caret: Result<Option<Rect>, ()>,
+ presented: Mutex<Vec<CursorOverlayControl>>,
+}
+
+impl ObservationOps for FocusedCaretAdapter {
+ fn get_focused_insertion_caret(
+ &self,
+ _process: Option<crate::ProcessId>,
+ _deadline: crate::Deadline,
+ ) -> Result<Option<Rect>, AdapterError> {
+ self.caret
+ .map_err(|()| AdapterError::not_supported("get_focused_insertion_caret"))
+ }
+}
+impl ActionOps for FocusedCaretAdapter {}
+impl InputOps for FocusedCaretAdapter {}
+impl SystemOps for FocusedCaretAdapter {
+ fn update_cursor_overlay(&self, control: &CursorOverlayControl) -> Result<(), AdapterError> {
+ self.presented.lock().unwrap().push(control.clone());
+ Ok(())
+ }
+}
+
+fn presented_after_key(caret: Result<Option<Rect>, ()>) -> Vec<CursorOverlayControl> {
+ let adapter = FocusedCaretAdapter {
+ caret,
+ presented: Mutex::new(Vec::new()),
+ };
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ let context = CommandContext::default().with_cursor_overlay_session("test-session", config);
+ super::follow_caret_after_key(&adapter, &context, Some(crate::ProcessId::new(42)));
+ adapter.presented.into_inner().unwrap()
+}
+
+#[test]
+fn a_key_press_moves_a_showing_caret_to_the_new_insertion_point() {
+ let presented = presented_after_key(Ok(Some(caret_at(64.0))));
+
+ assert_eq!(presented.len(), 1);
+ let instruction = presented[0].instruction().expect("a caret instruction");
+ assert_eq!(instruction.phase(), CursorPhase::CaretFollow);
+ assert_eq!(instruction.target(), Some(&caret_at(64.0)));
+ assert!(presented[0].expects_acknowledgement());
+}
+
+#[test]
+fn a_key_press_that_leaves_no_insertion_point_hides_the_caret() {
+ let presented = presented_after_key(Ok(None));
+
+ let instruction = presented[0].instruction().expect("a caret instruction");
+ assert_eq!(instruction.phase(), CursorPhase::CaretFollow);
+ assert!(instruction.target().is_none());
+}
+
+#[test]
+fn a_key_press_sends_nothing_when_the_adapter_cannot_read_the_caret() {
+ assert!(presented_after_key(Err(())).is_empty());
+}
+
+/// A renderer that has rested has already cleared its caret, so it must be
+/// able to tell a caret-follow from a control that should wake it.
+#[test]
+fn a_caret_follow_is_told_apart_from_controls_that_wake_the_overlay() {
+ let presented = presented_after_key(Ok(Some(caret_at(64.0))));
+ assert!(presented[0].is_caret_follow());
+
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ let travel =
+ crate::CursorOverlayInstruction::new(crate::Point { x: 1.0, y: 1.0 }, &config, false)
+ .expect("valid instruction");
+ assert!(!CursorOverlayControl::present("test-session".into(), travel).is_caret_follow());
+}
diff --git a/crates/core/src/cursor_overlay/control.rs b/crates/core/src/cursor_overlay/control.rs
index c604ddc4f..ee8f42f5e 100644
--- a/crates/core/src/cursor_overlay/control.rs
+++ b/crates/core/src/cursor_overlay/control.rs
@@ -195,6 +195,13 @@ impl CursorOverlayControl {
})
}
+ /// A caret-follow after a key press. A renderer that has rested has
+ /// already cleared its caret, so it acknowledges this without waking.
+ pub fn is_caret_follow(&self) -> bool {
+ self.instruction()
+ .is_some_and(|instruction| instruction.phase() == CursorPhase::CaretFollow)
+ }
+
pub fn expects_acknowledgement(&self) -> bool {
self.is_hide()
|| self.is_show()
@@ -203,7 +210,7 @@ impl CursorOverlayControl {
|| self.instruction().is_some_and(|instruction| {
matches!(
instruction.phase(),
- CursorPhase::Effect | CursorPhase::Caret
+ CursorPhase::Effect | CursorPhase::Caret | CursorPhase::CaretFollow
)
})
}
diff --git a/crates/core/src/cursor_overlay/mod.rs b/crates/core/src/cursor_overlay/mod.rs
index 40a7b7b6b..3838af04b 100644
--- a/crates/core/src/cursor_overlay/mod.rs
+++ b/crates/core/src/cursor_overlay/mod.rs
@@ -1,3 +1,4 @@
+mod caret_follow;
mod config;
mod control;
mod cursor_hold;
@@ -15,6 +16,7 @@ mod style;
mod submit;
mod timing;
+pub(crate) use caret_follow::follow_caret_after_key;
pub use config::{CursorOverlayConfig, MAX_CURSOR_LABEL_BYTES, MAX_CURSOR_LABEL_WORDS};
pub use control::{CURSOR_OVERLAY_GREETING, CursorOverlayControl};
pub(crate) use cursor_hold::hold_cursor;
@@ -31,7 +33,8 @@ pub use pose::CursorPose;
pub use style::CursorOverlayStyle;
pub(crate) use submit::{
cancel_drag, confirms_delivery, dispatch_mouse_event_with_cursor, input_was_delivered, submit,
- submit_caret, submit_drag, submit_drag_effect, submit_travel, submit_travel_before_lease,
+ submit_caret, submit_caret_follow, submit_drag, submit_drag_effect, submit_travel,
+ submit_travel_before_lease,
};
pub use timing::{
CURSOR_ARRIVAL_TIMEOUT_MS, CURSOR_HIGHLIGHT_HOLD_MS, CURSOR_IDLE_REST_MS,
diff --git a/crates/core/src/cursor_overlay/phase.rs b/crates/core/src/cursor_overlay/phase.rs
index 3843fd231..8027d8a0a 100644
--- a/crates/core/src/cursor_overlay/phase.rs
+++ b/crates/core/src/cursor_overlay/phase.rs
@@ -10,6 +10,10 @@ use serde::{Deserialize, Serialize};
/// the app is inserting text; the cursor stays where it is. It is
/// acknowledged like `Effect`, so the renderer reads it before the sender
/// closes the connection.
+/// `CaretFollow` moves a caret that is already showing to the instruction's
+/// target, or hides it when the instruction has none, after a key press may
+/// have moved the insertion point. It never shows a caret that is not showing,
+/// and it is acknowledged like `Caret`.
#[derive(Debug, Clone, Copy, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CursorPhase {
@@ -18,4 +22,5 @@ pub enum CursorPhase {
Drag,
Effect,
Caret,
+ CaretFollow,
}
diff --git a/crates/core/src/cursor_overlay/submit.rs b/crates/core/src/cursor_overlay/submit.rs
index b04b3376e..1def54436 100644
--- a/crates/core/src/cursor_overlay/submit.rs
+++ b/crates/core/src/cursor_overlay/submit.rs
@@ -91,6 +91,28 @@ pub(crate) fn submit_caret(adapter: &dyn PlatformAdapter, context: &CommandConte
let _ = send(adapter, context, instruction);
}
+/// Moves a caret the overlay is already showing to `caret`, or hides it when
+/// `caret` is `None`.
+pub(crate) fn submit_caret_follow(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ caret: Option<Rect>,
+) {
+ let destination = caret.map_or(Point { x: 0.0, y: 0.0 }, |caret| Point {
+ x: caret.x,
+ y: caret.y + caret.height / 2.0,
+ });
+ let instruction =
+ super::CursorOverlayInstruction::new(destination, context.cursor_overlay(), false).map(
+ |instruction| {
+ instruction
+ .with_target(caret)
+ .with_phase(CursorPhase::CaretFollow)
+ },
+ );
+ let _ = send(adapter, context, instruction);
+}
+
pub(crate) fn input_was_delivered(result: &Result<OperationReport, AdapterError>) -> bool {
result.as_ref().map_or_else(
|error| confirms_delivery(error.disposition),
diff --git a/crates/core/src/ref_action/mod.rs b/crates/core/src/ref_action/mod.rs
index 405a83831..84705d1a6 100644
--- a/crates/core/src/ref_action/mod.rs
+++ b/crates/core/src/ref_action/mod.rs
@@ -137,6 +137,7 @@ 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 ripples = presentation::effect_ripples(&final_target, &presentation_action);
presentation::before_dispatch(&final_target, &preflight, &presentation_action, lease);
let dispatch_result =
crate::execute_verified_action(final_target.adapter, final_target.handle, request, lease);
@@ -148,7 +149,7 @@ pub(crate) fn dispatch_resolved(
final_target.adapter,
final_target.context,
&preflight,
- &presentation_action,
+ ripples,
&dispatch_result,
);
let mut result = dispatch_result?;
diff --git a/crates/core/src/ref_action/presentation.rs b/crates/core/src/ref_action/presentation.rs
index f3cd77b73..561d85b76 100644
--- a/crates/core/src/ref_action/presentation.rs
+++ b/crates/core/src/ref_action/presentation.rs
@@ -5,6 +5,7 @@ use crate::cursor_overlay::CursorPhase;
use crate::{Action, CommandContext, PlatformAdapter};
const SAME_POINT: f64 = 1.5;
+const FOCUS_READ_MS: u64 = 150;
thread_local! {
static TRAVELLED_BEFORE_LEASE: Cell<Option<(f64, f64)>> = const { Cell::new(None) };
@@ -97,9 +98,30 @@ pub(crate) fn enters_text(action: &Action) -> bool {
matches!(action, Action::TypeText(_) | Action::SetValue(_))
}
-/// Typing clicks into its field first, so its effect plays the click ripple.
-fn clicks_in_to_type(action: &Action) -> bool {
- matches!(action, Action::TypeText(_))
+/// Whether the effect after dispatch plays the click ripple. Typing plays it
+/// only when it has to click into its field: a field that already has
+/// keyboard focus is typed into where it is. That costs one live-state read,
+/// made only for typing with the overlay on; an element whose state cannot be
+/// read is treated as unfocused, so typing into it ripples.
+pub(super) fn effect_ripples(target: &ResolvedRefAction<'_>, action: &Action) -> bool {
+ if is_click(action) {
+ return true;
+ }
+ if !matches!(action, Action::TypeText(_)) || !target.context.cursor_overlay().is_enabled() {
+ return false;
+ }
+ let deadline = target
+ .deadline
+ .capped(std::time::Duration::from_millis(FOCUS_READ_MS));
+ let focused = target
+ .adapter
+ .get_live_state(target.handle, deadline)
+ .ok()
+ .flatten()
+ .is_some_and(|state| {
+ crate::tree::state::has_state(&state.states, crate::tree::state::FOCUSED)
+ });
+ !focused
}
fn center_of(bounds: &crate::Rect) -> Option<crate::Point> {
@@ -121,7 +143,7 @@ pub(super) fn after_dispatch(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
preflight: &ActionabilityPreflight,
- action: &Action,
+ ripples: bool,
result: &Result<crate::ActionResult, crate::AdapterError>,
) {
let disposition = match result {
@@ -143,7 +165,7 @@ pub(super) fn after_dispatch(
context,
destination,
preflight.presentation_bounds,
- is_click(action) || clicks_in_to_type(action),
+ ripples,
CursorPhase::Effect,
);
}
diff --git a/crates/core/src/ref_action/presentation_caret_tests.rs b/crates/core/src/ref_action/presentation_caret_tests.rs
index b6a786134..1fed5a5fb 100644
--- a/crates/core/src/ref_action/presentation_caret_tests.rs
+++ b/crates/core/src/ref_action/presentation_caret_tests.rs
@@ -15,6 +15,7 @@ const CARET: Rect = Rect {
struct CaretAdapter {
caret: Option<Rect>,
+ focused: bool,
value: Mutex<Option<String>>,
presented: Mutex<Vec<CursorOverlayControl>>,
}
@@ -23,6 +24,7 @@ impl CaretAdapter {
fn new(caret: Option<Rect>) -> Self {
Self {
caret,
+ focused: false,
value: Mutex::new(None),
presented: Mutex::new(Vec::new()),
}
@@ -52,7 +54,11 @@ impl ObservationOps for CaretAdapter {
[capability::CLICK, capability::TYPE_TEXT, capability::SET_VALUE],
adapter => crate::ElementState {
role: "textfield".into(),
- states: Vec::new(),
+ states: if adapter.focused {
+ vec![crate::tree::state::FOCUSED.into()]
+ } else {
+ Vec::new()
+ },
value: adapter.value.lock().unwrap().clone(),
enabled: Some(true),
hidden: Some(false),
@@ -166,3 +172,23 @@ fn a_field_without_an_insertion_point_keeps_its_outline_and_draws_no_caret() {
assert_eq!(effect.phase(), CursorPhase::Effect);
assert!(effect.target().is_some());
}
+
+#[test]
+fn typing_into_a_field_that_already_has_focus_plays_no_click_ripple() {
+ let adapter = CaretAdapter {
+ focused: true,
+ ..CaretAdapter::new(Some(CARET))
+ };
+ type_into(&adapter);
+
+ let presented = adapter.presented.lock().unwrap();
+ let effect = presented
+ .iter()
+ .filter_map(CursorOverlayControl::instruction)
+ .find(|instruction| instruction.phase() == CursorPhase::Effect)
+ .expect("an effect instruction");
+ assert!(
+ !effect.is_click(),
+ "the field is typed into where it is, so nothing clicks into it"
+ );
+}
diff --git a/crates/core/src/ref_action/ref_action_cursor_overlay_tests.rs b/crates/core/src/ref_action/ref_action_cursor_overlay_tests.rs
index 633d297a3..24495b45a 100644
--- a/crates/core/src/ref_action/ref_action_cursor_overlay_tests.rs
+++ b/crates/core/src/ref_action/ref_action_cursor_overlay_tests.rs
@@ -255,7 +255,7 @@ fn physical_effect_uses_verified_input_point_and_requires_delivery() {
&adapter,
&context,
&preflight,
- &Action::Click,
+ true,
&Err(AdapterError::stale_ref("blocked")
.with_disposition(crate::DeliverySemantics::NotDelivered)),
);
@@ -264,7 +264,7 @@ fn physical_effect_uses_verified_input_point_and_requires_delivery() {
&adapter,
&context,
&preflight,
- &Action::Click,
+ true,
&Ok(ActionResult::delivered_unverified("click")),
);
let presented = adapter.presented.lock().unwrap();
diff --git a/crates/macos/src/system/cursor_overlay/bridge.rs b/crates/macos/src/system/cursor_overlay/bridge.rs
index 80c4bdbc1..0a2f05cdb 100644
--- a/crates/macos/src/system/cursor_overlay/bridge.rs
+++ b/crates/macos/src/system/cursor_overlay/bridge.rs
@@ -59,24 +59,54 @@ unsafe extern "C" {
fn agent_desktop_cursor_overlay_idle();
fn agent_desktop_cursor_overlay_caret(x: f64, y: f64, width: f64, height: f64);
fn agent_desktop_cursor_overlay_caret_clear();
+ fn agent_desktop_cursor_overlay_caret_follow(
+ present: bool,
+ x: f64,
+ y: f64,
+ width: f64,
+ height: f64,
+ );
fn agent_desktop_cursor_overlay_hide();
fn agent_desktop_cursor_overlay_rest();
fn agent_desktop_cursor_overlay_show();
fn agent_desktop_cursor_overlay_stop();
}
-pub(super) fn caret(at: Option<&Rect>) {
- if let Some(at) = at {
- unsafe { agent_desktop_cursor_overlay_caret(at.x, at.y, at.width, at.height) }
+pub(super) fn is_caret(instruction: &CursorOverlayInstruction) -> bool {
+ matches!(
+ instruction.phase(),
+ CursorPhase::Caret | CursorPhase::CaretFollow
+ )
+}
+
+/// Draws the caret at the instruction's target. `CaretFollow` only moves a
+/// caret already showing, and hides it when there is no target.
+pub(super) fn caret(instruction: &CursorOverlayInstruction) {
+ let follow = instruction.phase() == CursorPhase::CaretFollow;
+ match instruction.target() {
+ Some(at) if follow => unsafe {
+ agent_desktop_cursor_overlay_caret_follow(true, at.x, at.y, at.width, at.height)
+ },
+ Some(at) => unsafe { agent_desktop_cursor_overlay_caret(at.x, at.y, at.width, at.height) },
+ None if follow => unsafe {
+ agent_desktop_cursor_overlay_caret_follow(false, 0.0, 0.0, 0.0, 0.0)
+ },
+ None => {}
}
}
-/// Clears the caret when the cursor sets off from `at` for somewhere else;
-/// see `CursorOverlayInstruction::departs_from`.
-pub(super) fn clear_caret_on_departure(instruction: &CursorOverlayInstruction, at: Option<&Point>) {
+/// Draws a caret instruction and reports that it was one. Any other
+/// instruction clears the caret when it sets the cursor off from `at` for
+/// somewhere else; see `CursorOverlayInstruction::departs_from`.
+pub(super) fn apply_caret(instruction: &CursorOverlayInstruction, at: Option<&Point>) -> bool {
+ if is_caret(instruction) {
+ caret(instruction);
+ return true;
+ }
if instruction.departs_from(at) {
unsafe { agent_desktop_cursor_overlay_caret_clear() }
}
+ false
}
pub(super) fn begin_drag(from: &Point, trail: bool) {
@@ -194,7 +224,7 @@ pub(super) fn apply_style(style: &CursorOverlayStyle, image_changed: bool) {
fn pointer_flags(instruction: &CursorOverlayInstruction) -> u8 {
match instruction.phase() {
CursorPhase::Effect => ARROW_AFTER_EFFECT,
- CursorPhase::Caret => 0,
+ CursorPhase::Caret | CursorPhase::CaretFollow => 0,
CursorPhase::Drag => ARROW_ON_DEPARTURE,
CursorPhase::Travel if instruction.is_pointer() => ARROW_ON_DEPARTURE | POINT_ON_ARRIVAL,
CursorPhase::Travel => ARROW_ON_DEPARTURE,
diff --git a/crates/macos/src/system/cursor_overlay/bridge_tests.rs b/crates/macos/src/system/cursor_overlay/bridge_tests.rs
index 857a09ce1..5bac8b517 100644
--- a/crates/macos/src/system/cursor_overlay/bridge_tests.rs
+++ b/crates/macos/src/system/cursor_overlay/bridge_tests.rs
@@ -52,3 +52,14 @@ fn pointer_flags_do_not_collide_with_render_flags() {
}
}
}
+
+#[test]
+fn both_caret_phases_draw_only_the_caret_and_leave_the_pointer_alone() {
+ for phase in [CursorPhase::Caret, CursorPhase::CaretFollow] {
+ assert!(is_caret(&instruction(phase, true)), "{phase:?}");
+ assert_eq!(pointer_flags(&instruction(phase, true)), 0, "{phase:?}");
+ }
+ for phase in [CursorPhase::Travel, CursorPhase::Drag, CursorPhase::Effect] {
+ assert!(!is_caret(&instruction(phase, false)), "{phase:?}");
+ }
+}
diff --git a/crates/macos/src/system/cursor_overlay/child.rs b/crates/macos/src/system/cursor_overlay/child.rs
index adf90bc92..c8d315a06 100644
--- a/crates/macos/src/system/cursor_overlay/child.rs
+++ b/crates/macos/src/system/cursor_overlay/child.rs
@@ -88,10 +88,13 @@ fn run() -> Result<(), AdapterError> {
let _ = stream.write_all(&[1]);
return Ok(());
}
+ if state.resting && control.is_caret_follow() {
+ let _ = stream.write_all(&[1]);
+ continue;
+ }
quiet_since = std::time::Instant::now();
- if state.resting {
+ if std::mem::take(&mut state.resting) {
bridge::show();
- state.resting = false;
}
let outcome = handle(&control, &mut state);
if outcome.is_ok() && control.expects_acknowledgement() {
@@ -127,9 +130,8 @@ fn run() -> Result<(), AdapterError> {
/// connects, so a control is drawn within the frame it was sent in rather
/// than after a fixed sleep.
fn wait_for_connection(listener: &std::os::unix::net::UnixListener, timeout: Duration) {
- use std::os::fd::AsRawFd;
let mut ready = libc::pollfd {
- fd: listener.as_raw_fd(),
+ fd: std::os::fd::AsRawFd::as_raw_fd(listener),
events: libc::POLLIN,
revents: 0,
};
@@ -218,7 +220,7 @@ fn apply_landing_memory(
let Some(instruction) = instruction else {
return;
};
- if instruction.phase() == CursorPhase::Caret {
+ if bridge::is_caret(instruction) {
return;
}
state.at = Some(if instruction.phase() == CursorPhase::Drag {
@@ -235,11 +237,9 @@ fn render(
instruction: &CursorOverlayInstruction,
state: &OverlayState,
) -> Result<(), AdapterError> {
- if instruction.phase() == CursorPhase::Caret {
- bridge::caret(instruction.target());
+ if bridge::apply_caret(instruction, state.at.as_ref()) {
return Ok(());
}
- bridge::clear_caret_on_departure(instruction, state.at.as_ref());
if instruction.phase() == CursorPhase::Drag {
let from = instruction.drag_from().unwrap_or(instruction.destination());
let (screen, fps, reduce_motion) = bridge::screen_at(from)?;
diff --git a/crates/macos/src/system/cursor_overlay/cursor_overlay_bridge.m b/crates/macos/src/system/cursor_overlay/cursor_overlay_bridge.m
index fa269583a..ed8ccc19b 100644
--- a/crates/macos/src/system/cursor_overlay/cursor_overlay_bridge.m
+++ b/crates/macos/src/system/cursor_overlay/cursor_overlay_bridge.m
@@ -209,6 +209,21 @@ void agent_desktop_cursor_overlay_caret_clear(void) {
ADCaretStop();
}
+void agent_desktop_cursor_overlay_caret_follow(bool present, double x, double y, double width,
+ double height) {
+ if (!ADCaretShowing()) {
+ return;
+ }
+ if (present) {
+ agent_desktop_cursor_overlay_caret(x, y, width, height);
+ return;
+ }
+ @autoreleasepool {
+ ADCaretStop();
+ ADPump(NSApplication.sharedApplication);
+ }
+}
+
void agent_desktop_cursor_overlay_rest(void) {
@autoreleasepool {
NSApplication *app = NSApplication.sharedApplication;
diff --git a/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome.h b/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome.h
index 46e9df225..2e25af198 100644
--- a/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome.h
+++ b/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome.h
@@ -24,6 +24,7 @@ void ADHighlightShow(NSRect frame, double seconds);
void ADHighlightStop(void);
void ADCaretShow(NSRect frame);
void ADCaretStop(void);
+bool ADCaretShowing(void);
void ADTrailBegin(NSPoint point);
void ADTrailAppend(NSPoint point);
void ADTrailFinish(double seconds);
diff --git a/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome_bridge.m b/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome_bridge.m
index b9e9026c6..4290f6a59 100644
--- a/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome_bridge.m
+++ b/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome_bridge.m
@@ -238,6 +238,10 @@ void ADCaretShow(NSRect frame) {
[CATransaction flush];
}
+bool ADCaretShowing(void) {
+ return ADCaretWindow != nil && ADCaretWindow.isVisible;
+}
+
void ADCaretStop(void) {
[ADCaretWindow orderOut:nil];
ADCaretWindow = nil;
diff --git a/crates/macos/src/tree/adapter.rs b/crates/macos/src/tree/adapter.rs
index 9fb1d6dad..7dee59cdd 100644
--- a/crates/macos/src/tree/adapter.rs
+++ b/crates/macos/src/tree/adapter.rs
@@ -180,6 +180,23 @@ impl ObservationOps for MacOSAdapter {
))
}
+ fn get_focused_insertion_caret(
+ &self,
+ process: Option<agent_desktop_core::ProcessId>,
+ deadline: Deadline,
+ ) -> Result<Option<agent_desktop_core::Rect>, AdapterError> {
+ let pid = process
+ .map(|process| i32::try_from(process.get()))
+ .transpose()
+ .map_err(|_| {
+ AdapterError::new(
+ agent_desktop_core::ErrorCode::InvalidArgs,
+ "Process id is out of range",
+ )
+ })?;
+ crate::tree::properties::text_insertion::focused_insertion_caret(pid, deadline)
+ }
+
fn get_live_element(
&self,
handle: &NativeHandle,
diff --git a/crates/macos/src/tree/properties/text_insertion.rs b/crates/macos/src/tree/properties/text_insertion.rs
index 8d6ed889a..edb929a91 100644
--- a/crates/macos/src/tree/properties/text_insertion.rs
+++ b/crates/macos/src/tree/properties/text_insertion.rs
@@ -6,11 +6,36 @@
#[cfg(target_os = "macos")]
mod imp {
use crate::tree::AXElement;
- use agent_desktop_core::{Deadline, Rect};
+ use agent_desktop_core::{AdapterError, Deadline, ErrorCode, Rect};
const CARET_WIDTH: f64 = 2.0;
const MIN_CARET_HEIGHT: f64 = 10.0;
+ /// The insertion caret of the element with keyboard focus in `pid`, or in
+ /// the focused app when `pid` is `None`.
+ pub(crate) fn focused_insertion_caret(
+ pid: Option<i32>,
+ deadline: Deadline,
+ ) -> Result<Option<Rect>, AdapterError> {
+ let owner = match pid {
+ Some(pid) => crate::tree::element_for_pid(pid),
+ None => AXElement(unsafe { accessibility_sys::AXUIElementCreateSystemWide() }),
+ };
+ let focused = super::super::attributes::copy_element_attr_result(
+ &owner,
+ "AXFocusedUIElement",
+ deadline,
+ )
+ .map_err(|error| {
+ AdapterError::new(
+ ErrorCode::ActionFailed,
+ "Could not read the focused element",
+ )
+ .with_details(serde_json::json!({ "ax_error": error }))
+ })?;
+ Ok(focused.and_then(|focused| insertion_caret(&focused, deadline)))
+ }
+
pub(crate) fn insertion_caret(element: &AXElement, deadline: Deadline) -> Option<Rect> {
let selection = super::super::attributes::selected_text_range(element, deadline)?;
let at = selection.end;
@@ -123,11 +148,18 @@ mod imp {
#[cfg(not(target_os = "macos"))]
mod imp {
use crate::tree::AXElement;
- use agent_desktop_core::{Deadline, Rect};
+ use agent_desktop_core::{AdapterError, Deadline, Rect};
pub(crate) fn insertion_caret(_element: &AXElement, _deadline: Deadline) -> Option<Rect> {
None
}
+
+ pub(crate) fn focused_insertion_caret(
+ _pid: Option<i32>,
+ _deadline: Deadline,
+ ) -> Result<Option<Rect>, AdapterError> {
+ Err(AdapterError::not_supported("get_focused_insertion_caret"))
+ }
}
-pub(crate) use imp::insertion_caret;
+pub(crate) use imp::{focused_insertion_caret, insertion_caret};
diff --git a/crates/windows/src/adapter.rs b/crates/windows/src/adapter.rs
index 8af580f8c..418d1c5aa 100644
--- a/crates/windows/src/adapter.rs
+++ b/crates/windows/src/adapter.rs
@@ -132,6 +132,14 @@ impl ObservationOps for WindowsAdapter {
crate::tree::text_insertion::get_insertion_caret(handle, deadline)
}
+ fn get_focused_insertion_caret(
+ &self,
+ process: Option<agent_desktop_core::ProcessId>,
+ deadline: Deadline,
+ ) -> Result<Option<agent_desktop_core::Rect>, AdapterError> {
+ crate::tree::text_insertion::get_focused_insertion_caret(process, deadline)
+ }
+
fn get_live_state(
&self,
handle: &NativeHandle,
diff --git a/crates/windows/src/system/cursor_overlay/caret_mark.rs b/crates/windows/src/system/cursor_overlay/caret_mark.rs
index 3b6fb4f43..51f37fa07 100644
--- a/crates/windows/src/system/cursor_overlay/caret_mark.rs
+++ b/crates/windows/src/system/cursor_overlay/caret_mark.rs
@@ -26,18 +26,33 @@ mod imp {
pub(crate) struct CaretMark {
window: OverlayWindow,
+ shown: std::cell::Cell<bool>,
}
impl CaretMark {
pub(crate) fn create() -> Result<Self, AdapterError> {
Ok(Self {
window: OverlayWindow::create()?,
+ shown: std::cell::Cell::new(false),
})
}
+ /// Draws the caret over `at`. With `follow`, only a caret already
+ /// showing moves, and no `at` hides it.
+ pub(crate) fn place(&self, at: Option<&Rect>, accent: [f64; 3], follow: bool) {
+ if follow && !self.shown.get() {
+ return;
+ }
+ match at {
+ Some(at) => self.show(at, accent),
+ None if follow => self.hide(),
+ None => {}
+ }
+ }
+
/// Draws the caret over `at`. The CLI and the renderer are both
/// per-monitor DPI aware, so `at` is already in physical pixels.
- pub(crate) fn show(&self, at: &Rect, accent: [f64; 3]) {
+ fn show(&self, at: &Rect, accent: [f64; 3]) {
let width = at.width.round().max(1.0) as i32;
let height = at.height.round().max(1.0) as i32;
let channel = |value: f64| (value.clamp(0.0, 1.0) * 255.0).round() as u32;
@@ -55,11 +70,13 @@ mod imp {
&pixels,
);
self.window.pump();
+ self.shown.set(true);
}
pub(crate) fn hide(&self) {
let _ = self.window.present(0, 0, 0, 0, &[]);
self.window.pump();
+ self.shown.set(false);
}
/// Hides the caret when the cursor sets off from `from` for `to`
diff --git a/crates/windows/src/system/cursor_overlay/surface_host.rs b/crates/windows/src/system/cursor_overlay/surface_host.rs
index f20afcf6c..dc21024b5 100644
--- a/crates/windows/src/system/cursor_overlay/surface_host.rs
+++ b/crates/windows/src/system/cursor_overlay/surface_host.rs
@@ -72,6 +72,9 @@ impl SurfaceHost {
/// dispatches the moment its acknowledgement arrives, so the cursor
/// has to already be where the click will land.
pub(crate) fn apply(&mut self, control: &CursorOverlayControl) {
+ if self.rest.resting && control.is_caret_follow() {
+ return;
+ }
self.rest.resting = false;
self.rest.quiet_since = Instant::now();
if let Some(style) = control.style() {
@@ -101,11 +104,10 @@ impl SurfaceHost {
.clone(),
instruction.target().cloned(),
),
- CursorPhase::Caret => {
- if let Some(at) = instruction.target() {
- let accent = self.presentation.style.accent_rgb();
- self.caret.show(at, accent);
- }
+ phase @ (CursorPhase::Caret | CursorPhase::CaretFollow) => {
+ let accent = self.presentation.style.accent_rgb();
+ let follow = phase == CursorPhase::CaretFollow;
+ self.caret.place(instruction.target(), accent, follow);
}
CursorPhase::Effect => {}
},
@@ -136,7 +138,7 @@ impl SurfaceHost {
instruction.is_click(),
interrupt,
),
- CursorPhase::Caret => {}
+ CursorPhase::Caret | CursorPhase::CaretFollow => {}
}
}
CursorOverlayControl::Hide { .. } | CursorOverlayControl::Disable { .. } => {}
diff --git a/crates/windows/src/tree/text_insertion.rs b/crates/windows/src/tree/text_insertion.rs
index f7ca01a3c..0cd7b9b1a 100644
--- a/crates/windows/src/tree/text_insertion.rs
+++ b/crates/windows/src/tree/text_insertion.rs
@@ -39,7 +39,7 @@ fn count_line_breaks(text: &str) -> u32 {
mod imp {
use super::{caret_at, count_line_breaks, is_line_break};
use crate::tree::element::uia_element;
- use agent_desktop_core::{AdapterError, Deadline, NativeHandle, Rect};
+ use agent_desktop_core::{AdapterError, Deadline, NativeHandle, ProcessId, Rect};
use uiautomation::patterns::{UITextPattern, UITextRange};
use uiautomation::types::{TextPatternRangeEndpoint, TextUnit};
use uiautomation::variants::SafeArray;
@@ -57,6 +57,28 @@ mod imp {
Ok(caret(&pattern))
}
+ /// The insertion caret of the element with keyboard focus, when it belongs
+ /// to `process` (or to any process, when `process` is `None`).
+ pub(crate) fn get_focused_insertion_caret(
+ process: Option<ProcessId>,
+ deadline: Deadline,
+ ) -> Result<Option<Rect>, AdapterError> {
+ deadline.ensure_remaining()?;
+ let client = crate::tree::automation::automation_client()?;
+ let Ok(focused) = client.get_focused_element() else {
+ return Ok(None);
+ };
+ if process.is_some_and(|process| {
+ focused.get_process_id().ok().map(ProcessId::new) != Some(process)
+ }) {
+ return Ok(None);
+ }
+ let Ok(pattern) = focused.get_pattern::<UITextPattern>() else {
+ return Ok(None);
+ };
+ Ok(caret(&pattern))
+ }
+
fn caret(pattern: &UITextPattern) -> Option<Rect> {
let selection = pattern.get_selection().ok()?.into_iter().next()?;
let previous = collapsed_at_end(pattern, &selection)?;
@@ -167,9 +189,16 @@ mod imp {
) -> Result<Option<Rect>, AdapterError> {
Ok(None)
}
+
+ pub(crate) fn get_focused_insertion_caret(
+ _process: Option<agent_desktop_core::ProcessId>,
+ _deadline: Deadline,
+ ) -> Result<Option<Rect>, AdapterError> {
+ Err(AdapterError::not_supported("get_focused_insertion_caret"))
+ }
}
-pub(crate) use imp::get_insertion_caret;
+pub(crate) use imp::{get_focused_insertion_caret, get_insertion_caret};
#[cfg(test)]
#[path = "text_insertion_tests.rs"]
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index b5f3e8b4a..c86ad54f2 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -198,7 +198,7 @@ On macOS and Windows:
Windows accepts the motion settings but keeps its built-in motion.
-On macOS and Windows, after `type` or `set-value` lands, the overlay draws the agent's caret, a thin bar in the accent color, at the field's insertion point and leaves the element outline off. `type --interval-ms` moves the caret with each keystroke while the cursor stays put. A field that reports no insertion point keeps the outline and gets no caret. The caret goes away when the cursor sets off for somewhere else, and stays for another `type` into the same field.
+On macOS and Windows, after `type` or `set-value` lands, the overlay draws the agent's caret, a thin bar in the accent color, at the field's insertion point and leaves the element outline off. `type --interval-ms` moves the caret with each keystroke while the cursor stays put. A field that reports no insertion point keeps the outline and gets no caret. The caret goes away when the cursor sets off for somewhere else, and stays for another `type` into the same field. After `press` delivers, a caret that is showing moves to the focused field's new insertion point, or disappears when the focused element has none. `type` plays the click ripple only when its field does not already have keyboard focus.
Multi-agent cursors (macOS and Windows): start with `session start --cursor --multi-agent`, then pass the returned session id to every subagent.