Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat(core, macos): show the insertion caret after text entry (#349)
Chris Tate6b62bda615c8
diff --git a/apps/docs/content/docs/commands/system.mdx b/apps/docs/content/docs/commands/system.mdxindex 0cc67982b..cf0f6744e 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. 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, 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).```bashagent-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.rsindex c4bb462a1..819854a9c 100644--- a/crates/core/src/adapter/observation.rs+++ b/crates/core/src/adapter/observation.rs@@ -215,6 +215,17 @@ pub trait ObservationOps: Send + Sync {Err(AdapterError::not_supported("get_element_bounds"))}+ /// Screen bounds of a text element's insertion point: a caret-wide rect as+ /// tall as the line it sits on. `None` when the element reports no+ /// insertion point.+ fn get_insertion_caret(+ &self,+ _handle: &NativeHandle,+ _deadline: Deadline,+ ) -> Result<Option<Rect>, AdapterError> {+ Err(AdapterError::not_supported("get_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/type_text_interval.rs b/crates/core/src/commands/type_text_interval.rsindex bdfd000da..4e94e26eb 100644--- a/crates/core/src/commands/type_text_interval.rs+++ b/crates/core/src/commands/type_text_interval.rs@@ -48,7 +48,9 @@ pub(crate) fn execute(let slot = clock.wait();let request = context.request_base(Action::TypeText(unit.clone()));let delivered = match &burst {- Some(burst) => deliver(adapter, burst, request, budget(unit)).map(|_| ()),+ Some(burst) => deliver(adapter, burst, request, budget(unit)).map(|_| {+ crate::ref_action::presentation::move_caret(adapter, context, &burst.handle);+ }),None => execute_ref_action_with_context(RefArgs {ref_id: args.ref_id.clone(),diff --git a/crates/core/src/commands/type_text_interval_caret_tests.rs b/crates/core/src/commands/type_text_interval_caret_tests.rsnew file mode 100644index 000000000..f07f5e159--- /dev/null+++ b/crates/core/src/commands/type_text_interval_caret_tests.rs@@ -0,0 +1,141 @@+use crate::adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps};+use crate::commands::type_text::{TypeArgs, execute};+use crate::refs::refs_test_support::HomeGuard;+use crate::{+ ActionRequest, ActionResult, AdapterError, CommandContext, CursorOverlayControl, CursorPhase,+ Rect, RefEntry, actions::capability,+};+use std::sync::Mutex;++/// A text field that reports an insertion point and records what the+/// overlay was asked to draw.+#[derive(Default)]+struct CaretField {+ typed: Mutex<String>,+ presented: Mutex<Vec<CursorOverlayControl>>,+}++impl ObservationOps for CaretField {+ fn resolve_element_strict(+ &self,+ _entry: &RefEntry,+ _deadline: crate::Deadline,+ ) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn get_insertion_caret(+ &self,+ _handle: &NativeHandle,+ _deadline: crate::Deadline,+ ) -> Result<Option<Rect>, AdapterError> {+ let typed = self.typed.lock().unwrap().chars().count() as f64;+ Ok(Some(Rect {+ x: 10.0 + typed * 7.0,+ y: 4.0,+ width: 2.0,+ height: 14.0,+ }))+ }++ crate::adapter::complete_live_observation!(+ "textfield",+ "Name",+ [capability::CLICK, capability::TYPE_TEXT],+ adapter => crate::ElementState {+ role: "textfield".into(),+ states: Vec::new(),+ value: Some(adapter.typed.lock().unwrap().clone()),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ }+ );+}++impl ActionOps for CaretField {+ fn execute_action(+ &self,+ _handle: &NativeHandle,+ request: ActionRequest,+ _lease: &crate::InteractionLease,+ ) -> Result<ActionResult, AdapterError> {+ if let crate::Action::TypeText(text) = request.action {+ self.typed.lock().unwrap().push_str(&text);+ }+ Ok(ActionResult::delivered_unverified("type_text"))+ }+}++impl InputOps for CaretField {}++impl SystemOps for CaretField {+ crate::adapter::guarded_interaction_lease!();+ crate::adapter::exact_window_focus!();++ fn update_cursor_overlay(&self, control: &CursorOverlayControl) -> Result<(), AdapterError> {+ self.presented.lock().unwrap().push(control.clone());+ Ok(())+ }+}++fn field_in_session(session: &str) -> String {+ let bounds = Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ };+ let mut entry = crate::adapter::minimal_ref_entry("textfield", Some("Name"));+ entry.geometry.bounds = Some(bounds);+ entry.geometry.bounds_hash = bounds.bounds_hash();+ entry.capabilities.available_actions =+ vec![capability::CLICK.into(), capability::TYPE_TEXT.into()];+ entry.source.source_app = Some("Fixture".into());+ entry.source.source_window_id = Some("w-42".into());+ entry.source.source_window_title = Some("Fixture".into());+ let mut refmap = crate::refs::RefMap::new();+ refmap.allocate(entry);+ crate::refs::refs_store::RefStore::for_session(Some(session))+ .expect("the session store")+ .save_new_snapshot(&refmap)+ .expect("the snapshot")+}++/// `type --interval-ms` keeps the caret on the insertion point as it types:+/// the first keystroke places it, and every keystroke after it moves it.+#[test]+fn an_interval_burst_moves_the_caret_with_every_keystroke() {+ let _home = HomeGuard::new();+ let snapshot_id = field_in_session("test-session");+ let adapter = CaretField::default();+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");+ let context = CommandContext::default().with_cursor_overlay_session("test-session", config);++ execute(+ TypeArgs {+ ref_id: format!("@{snapshot_id}:e1"),+ text: "hello".into(),+ timeout_ms: None,+ interval_ms: Some(5),+ },+ &adapter,+ &context,+ )+ .expect("typing succeeds");++ let carets: Vec<f64> = adapter+ .presented+ .lock()+ .unwrap()+ .iter()+ .filter_map(CursorOverlayControl::instruction)+ .filter(|instruction| instruction.phase() == CursorPhase::Caret)+ .filter_map(|instruction| instruction.target().map(|caret| caret.x))+ .collect();+ assert_eq!(+ carets,+ [17.0, 24.0, 31.0, 38.0, 45.0],+ "one caret per keystroke, each at the insertion point it left"+ );+}diff --git a/crates/core/src/commands/type_text_interval_tests.rs b/crates/core/src/commands/type_text_interval_tests.rsindex 4cbc5e902..321858eb0 100644--- a/crates/core/src/commands/type_text_interval_tests.rs+++ b/crates/core/src/commands/type_text_interval_tests.rs@@ -50,3 +50,6 @@ fn the_next_keystroke_is_due_an_interval_after_its_slot_or_half_one_after_a_late#[path = "type_text_interval_clock_tests.rs"]mod clock;++#[path = "type_text_interval_caret_tests.rs"]+mod caret;diff --git a/crates/core/src/cursor_overlay/control.rs b/crates/core/src/cursor_overlay/control.rsindex 514c0a010..c604ddc4f 100644--- a/crates/core/src/cursor_overlay/control.rs+++ b/crates/core/src/cursor_overlay/control.rs@@ -200,9 +200,12 @@ impl CursorOverlayControl {|| self.is_show()|| self.is_disable()|| self.is_travel()- || self- .instruction()- .is_some_and(|instruction| instruction.phase() == CursorPhase::Effect)+ || self.instruction().is_some_and(|instruction| {+ matches!(+ instruction.phase(),+ CursorPhase::Effect | CursorPhase::Caret+ )+ })}pub const fn is_hide(&self) -> bool {diff --git a/crates/core/src/cursor_overlay/instruction.rs b/crates/core/src/cursor_overlay/instruction.rsindex 95772bfdf..8f2650292 100644--- a/crates/core/src/cursor_overlay/instruction.rs+++ b/crates/core/src/cursor_overlay/instruction.rs@@ -100,4 +100,23 @@ impl CursorOverlayInstruction {pub const fn is_click(&self) -> bool {self.click}++ /// Whether this instruction sets the cursor off from `at` for somewhere+ /// else: a travel, or a drag from its origin, to a point+ /// [`CURSOR_SAME_POINT`](super::CURSOR_SAME_POINT) or more away. The agent's+ /// caret marks the field the cursor was typing in, so renderers clear it+ /// then and keep it for a travel that stays put, such as typing again into+ /// the same field.+ pub fn departs_from(&self, at: Option<&Point>) -> bool {+ let to = match self.phase {+ CursorPhase::Travel => &self.destination,+ CursorPhase::Drag => self.drag_from.as_ref().unwrap_or(&self.destination),+ _ => return false,+ };+ at.is_none_or(|at| (to.x - at.x).hypot(to.y - at.y) >= super::CURSOR_SAME_POINT)+ }}++#[cfg(test)]+#[path = "instruction_tests.rs"]+mod instruction_tests;diff --git a/crates/core/src/cursor_overlay/instruction_tests.rs b/crates/core/src/cursor_overlay/instruction_tests.rsnew file mode 100644index 000000000..9b6f5fdef--- /dev/null+++ b/crates/core/src/cursor_overlay/instruction_tests.rs@@ -0,0 +1,34 @@+use super::{CursorOverlayConfig, CursorOverlayInstruction, CursorPhase};+use crate::Point;++fn instruction(x: f64, phase: CursorPhase) -> CursorOverlayInstruction {+ let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");+ CursorOverlayInstruction::new(Point { x, y: 50.0 }, &config, false)+ .expect("valid instruction")+ .with_phase(phase)+}++#[test]+fn a_travel_somewhere_else_departs_and_one_that_stays_put_does_not() {+ let at = Point { x: 100.0, y: 50.0 };++ assert!(instruction(140.0, CursorPhase::Travel).departs_from(Some(&at)));+ assert!(!instruction(101.0, CursorPhase::Travel).departs_from(Some(&at)));+ assert!(instruction(101.0, CursorPhase::Travel).departs_from(None));+}++#[test]+fn only_travels_and_drags_depart() {+ let at = Point { x: 100.0, y: 50.0 };+ for phase in [CursorPhase::Effect, CursorPhase::Caret] {+ assert!(+ !instruction(400.0, phase).departs_from(Some(&at)),+ "{phase:?}"+ );+ }+ let drag = instruction(400.0, CursorPhase::Drag).with_drag_from(Some(at.clone()));+ assert!(+ !drag.departs_from(Some(&at)),+ "a drag sets off from its origin, where the cursor already is"+ );+}diff --git a/crates/core/src/cursor_overlay/layout.rs b/crates/core/src/cursor_overlay/layout.rsindex 743226574..93f29d670 100644--- a/crates/core/src/cursor_overlay/layout.rs+++ b/crates/core/src/cursor_overlay/layout.rs@@ -1,5 +1,8 @@use crate::{Point, Rect};+/// How close, in points, two cursor positions are to count as the same place.+pub const CURSOR_SAME_POINT: f64 = 1.5;+const DESTINATION_GAP: f64 = 18.0;pub fn place_label(destination: &Point, size: (f64, f64), screen: &Rect) -> Rect {diff --git a/crates/core/src/cursor_overlay/mod.rs b/crates/core/src/cursor_overlay/mod.rsindex b0fc65810..40a7b7b6b 100644--- a/crates/core/src/cursor_overlay/mod.rs+++ b/crates/core/src/cursor_overlay/mod.rs@@ -23,7 +23,7 @@ pub use image::{};pub use images::CursorImages;pub use instruction::CursorOverlayInstruction;-pub use layout::place_label;+pub use layout::{CURSOR_SAME_POINT, place_label};pub use motion::CursorMotion;pub use motion_profile::CursorMotionProfile;pub use phase::CursorPhase;@@ -31,7 +31,7 @@ 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_drag, submit_drag_effect, submit_travel, submit_travel_before_lease,+ submit_caret, 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.rsindex e7903be79..3843fd231 100644--- a/crates/core/src/cursor_overlay/phase.rs+++ b/crates/core/src/cursor_overlay/phase.rs@@ -6,6 +6,10 @@ use serde::{Deserialize, Serialize};/// `Drag` arms pointer tracking and is acknowledged once the renderer is ready./// `Effect` is sent after dispatch; the renderer acknowledges it, and the/// action result does not depend on that acknowledgement.+/// `Caret` places the agent's text caret at the instruction's target, where+/// 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.#[derive(Debug, Clone, Copy, Default, Deserialize, Eq, PartialEq, Serialize)]#[serde(rename_all = "snake_case")]pub enum CursorPhase {@@ -13,4 +17,5 @@ pub enum CursorPhase {Travel,Drag,Effect,+ Caret,}diff --git a/crates/core/src/cursor_overlay/submit.rs b/crates/core/src/cursor_overlay/submit.rsindex 2cf7735f5..b04b3376e 100644--- a/crates/core/src/cursor_overlay/submit.rs+++ b/crates/core/src/cursor_overlay/submit.rs@@ -73,6 +73,24 @@ fn travel_within(send(adapter, context, instruction)}+/// Places the agent's text caret at `caret`, where the app is inserting text,+/// without moving the cursor.+pub(crate) fn submit_caret(adapter: &dyn PlatformAdapter, context: &CommandContext, caret: Rect) {+ let destination = 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(Some(caret))+ .with_phase(CursorPhase::Caret)+ },+ );+ 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),@@ -226,3 +244,7 @@ pub(crate) fn dispatch_mouse_event_with_cursor(}result}++#[cfg(test)]+#[path = "submit_tests.rs"]+mod tests;diff --git a/crates/core/src/cursor_overlay/submit_tests.rs b/crates/core/src/cursor_overlay/submit_tests.rsnew file mode 100644index 000000000..6a3ece44b--- /dev/null+++ b/crates/core/src/cursor_overlay/submit_tests.rs@@ -0,0 +1,28 @@+use super::super::{+ CursorOverlayConfig, CursorOverlayControl, CursorOverlayInstruction, CursorPhase,+};++#[test]+fn a_caret_instruction_round_trips_through_the_overlay_transport() {+ let config = CursorOverlayConfig::enabled(None, 6).expect("valid config");+ let caret = crate::Rect {+ x: 50.0,+ y: 78.0,+ width: 2.0,+ height: 25.0,+ };+ let instruction =+ CursorOverlayInstruction::new(crate::Point { x: 50.0, y: 90.5 }, &config, false)+ .expect("valid instruction")+ .with_target(Some(caret))+ .with_phase(CursorPhase::Caret);+ let control = CursorOverlayControl::present_with_style(+ "run-1".into(),+ instruction,+ config.style().clone(),+ );+ let wire = serde_json::to_vec(&control).expect("encodes");+ let decoded: CursorOverlayControl = serde_json::from_slice(&wire).expect("decodes");+ assert_eq!(decoded, control);+ assert!(decoded.expects_acknowledgement());+}diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rsindex bc0422f98..ae07d6714 100644--- a/crates/core/src/lib.rs+++ b/crates/core/src/lib.rs@@ -44,10 +44,10 @@ pub use context::{CommandContext, WaitSelector};pub use cursor_overlay::{CURSOR_ARRIVAL_TIMEOUT_MS, CURSOR_HIGHLIGHT_HOLD_MS, CURSOR_IDLE_REST_MS,CURSOR_LABEL_REVEAL_MS, CURSOR_MOTION_BUDGET_MS, CURSOR_OVERLAY_GREETING, CURSOR_REST_FADE_MS,- CursorImage, CursorImages, CursorMotion, CursorMotionProfile, CursorOverlayConfig,- CursorOverlayControl, CursorOverlayInstruction, CursorOverlayStyle, CursorPhase, CursorPose,- MAX_CURSOR_IMAGE_BYTES, MAX_CURSOR_IMAGE_PATH_BYTES, MAX_CURSOR_IMAGE_PIXELS,- MAX_CURSOR_LABEL_BYTES, MAX_CURSOR_LABEL_WORDS, place_label,+ CURSOR_SAME_POINT, CursorImage, CursorImages, CursorMotion, CursorMotionProfile,+ CursorOverlayConfig, CursorOverlayControl, CursorOverlayInstruction, CursorOverlayStyle,+ CursorPhase, CursorPose, MAX_CURSOR_IMAGE_BYTES, MAX_CURSOR_IMAGE_PATH_BYTES,+ MAX_CURSOR_IMAGE_PIXELS, MAX_CURSOR_LABEL_BYTES, MAX_CURSOR_LABEL_WORDS, place_label,};pub use input::clipboard_content::ClipboardContent;pub use input::clipboard_format::ClipboardFormat;diff --git a/crates/core/src/ref_action/mod.rs b/crates/core/src/ref_action/mod.rsindex 7e62dbe64..405a83831 100644--- a/crates/core/src/ref_action/mod.rs+++ b/crates/core/src/ref_action/mod.rs@@ -8,7 +8,7 @@ use crate::refs::RefEntry;use crate::{AdapterError, AppError, actionability};use serde_json::json;-mod presentation;+pub(crate) mod presentation;pub(crate) mod ref_action_actionability;pub(crate) mod ref_action_context;pub(crate) mod ref_action_poll;@@ -140,6 +140,10 @@ pub(crate) fn dispatch_resolved(presentation::before_dispatch(&final_target, &preflight, &presentation_action, lease);let dispatch_result =crate::execute_verified_action(final_target.adapter, final_target.handle, request, lease);+ let mut preflight = preflight;+ if presentation::after_text_entry(&final_target, &presentation_action, &dispatch_result) {+ preflight.presentation_bounds = None;+ }presentation::after_dispatch(final_target.adapter,final_target.context,diff --git a/crates/core/src/ref_action/presentation.rs b/crates/core/src/ref_action/presentation.rsindex 0936060a0..f3cd77b73 100644--- a/crates/core/src/ref_action/presentation.rs+++ b/crates/core/src/ref_action/presentation.rs@@ -93,6 +93,15 @@ fn target_center(})}+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(_))+}+fn center_of(bounds: &crate::Rect) -> Option<crate::Point> {bounds.validate().ok()?;(bounds.width > 0.0 && bounds.height > 0.0).then(|| crate::Point {@@ -134,11 +143,56 @@ pub(super) fn after_dispatch(context,destination,preflight.presentation_bounds,- is_click(action),+ is_click(action) || clicks_in_to_type(action),CursorPhase::Effect,);}+/// After text entry lands, draws the agent's caret where the element is now+/// inserting text, when the element reports an insertion point. Returns+/// whether it did: the caret then marks the field, so the element outline is+/// left off rather than flashing on every keystroke.+pub(super) fn after_text_entry(+ target: &ResolvedRefAction<'_>,+ action: &Action,+ result: &Result<crate::ActionResult, crate::AdapterError>,+) -> bool {+ let delivered = match result {+ Ok(result) => crate::cursor_overlay::confirms_delivery(result.disposition()),+ Err(error) => crate::cursor_overlay::confirms_delivery(error.disposition),+ };+ delivered && enters_text(action) && place_caret(target.adapter, target.context, target.handle)+}++fn place_caret(+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+ handle: &crate::NativeHandle,+) -> bool {+ if !context.cursor_overlay().is_enabled() {+ return false;+ }+ let Ok(deadline) = crate::Deadline::after(crate::CURSOR_ARRIVAL_TIMEOUT_MS) else {+ return false;+ };+ let Ok(Some(caret)) = adapter.get_insertion_caret(handle, deadline) else {+ return false;+ };+ crate::cursor_overlay::submit_caret(adapter, context, caret);+ true+}++/// Moves the agent's caret to the element's insertion point during a typing+/// burst. The cursor stays where it clicked into the field, the way a person's+/// pointer stays put while they type.+pub(crate) fn move_caret(+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+ handle: &crate::NativeHandle,+) {+ place_caret(adapter, context, handle);+}+fn destination(preflight: &ActionabilityPreflight) -> Option<crate::Point> {match preflight.pointer_delivery {crate::actionability::PointerDelivery::Physical => preflightdiff --git a/crates/core/src/ref_action/presentation_caret_tests.rs b/crates/core/src/ref_action/presentation_caret_tests.rsnew file mode 100644index 000000000..b6a786134--- /dev/null+++ b/crates/core/src/ref_action/presentation_caret_tests.rs@@ -0,0 +1,168 @@+use crate::adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps};+use crate::ref_action::execute_entry_with_context;+use crate::{+ Action, ActionRequest, ActionResult, AdapterError, CommandContext, CursorOverlayControl,+ CursorPhase, Rect, RefEntry, actions::capability,+};+use std::sync::Mutex;++const CARET: Rect = Rect {+ x: 40.0,+ y: 4.0,+ width: 2.0,+ height: 14.0,+};++struct CaretAdapter {+ caret: Option<Rect>,+ value: Mutex<Option<String>>,+ presented: Mutex<Vec<CursorOverlayControl>>,+}++impl CaretAdapter {+ fn new(caret: Option<Rect>) -> Self {+ Self {+ caret,+ value: Mutex::new(None),+ presented: Mutex::new(Vec::new()),+ }+ }+}++impl ObservationOps for CaretAdapter {+ fn resolve_element_strict(+ &self,+ _entry: &RefEntry,+ _deadline: crate::Deadline,+ ) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ fn get_insertion_caret(+ &self,+ _handle: &NativeHandle,+ _deadline: crate::Deadline,+ ) -> Result<Option<Rect>, AdapterError> {+ Ok(self.caret)+ }++ crate::adapter::complete_live_observation!(+ "textfield",+ "Name",+ [capability::CLICK, capability::TYPE_TEXT, capability::SET_VALUE],+ adapter => crate::ElementState {+ role: "textfield".into(),+ states: Vec::new(),+ value: adapter.value.lock().unwrap().clone(),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ }+ );+}++impl ActionOps for CaretAdapter {+ fn execute_action(+ &self,+ _handle: &NativeHandle,+ request: ActionRequest,+ _lease: &crate::InteractionLease,+ ) -> Result<ActionResult, AdapterError> {+ if let Action::TypeText(text) | Action::SetValue(text) = &request.action {+ *self.value.lock().unwrap() = Some(text.clone());+ }+ Ok(ActionResult::delivered_unverified("type"))+ }+}++impl InputOps for CaretAdapter {}++impl SystemOps for CaretAdapter {+ crate::adapter::guarded_interaction_lease!();+ crate::adapter::exact_window_focus!();++ fn update_cursor_overlay(&self, control: &CursorOverlayControl) -> Result<(), AdapterError> {+ self.presented.lock().unwrap().push(control.clone());+ Ok(())+ }+}++fn field() -> RefEntry {+ let bounds = Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ };+ let mut entry = crate::adapter::minimal_ref_entry("textfield", Some("Name"));+ entry.geometry.bounds = Some(bounds);+ entry.geometry.bounds_hash = bounds.bounds_hash();+ entry.capabilities.available_actions = vec![+ capability::CLICK.into(),+ capability::TYPE_TEXT.into(),+ capability::SET_VALUE.into(),+ ];+ entry.source.source_app = Some("Fixture".into());+ entry.source.source_window_id = Some("w-42".into());+ entry.source.source_window_title = Some("Fixture".into());+ entry+}++fn overlay_context() -> CommandContext {+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");+ CommandContext::default().with_cursor_overlay_session("test-session", config)+}++fn type_into(adapter: &CaretAdapter) {+ execute_entry_with_context(+ adapter,+ &field(),+ ActionRequest::headless(Action::TypeText("hello".into())),+ &overlay_context(),+ )+ .expect("type succeeds");+}++#[test]+fn typing_draws_the_caret_at_the_insertion_point_and_drops_the_outline() {+ let adapter = CaretAdapter::new(Some(CARET));+ type_into(&adapter);++ let presented = adapter.presented.lock().unwrap();+ let caret = presented+ .iter()+ .filter_map(CursorOverlayControl::instruction)+ .find(|instruction| instruction.phase() == CursorPhase::Caret)+ .expect("a caret instruction");+ assert_eq!(caret.target(), Some(&CARET));+ let effect = presented+ .iter()+ .filter_map(CursorOverlayControl::instruction)+ .find(|instruction| instruction.phase() == CursorPhase::Effect)+ .expect("an effect instruction");+ assert!(effect.is_click(), "typing clicks into its field first");+ assert!(+ effect.target().is_none(),+ "the caret marks the field, so the element outline is left off"+ );+}++#[test]+fn a_field_without_an_insertion_point_keeps_its_outline_and_draws_no_caret() {+ let adapter = CaretAdapter::new(None);+ type_into(&adapter);++ let presented = adapter.presented.lock().unwrap();+ assert!(+ presented+ .iter()+ .filter_map(CursorOverlayControl::instruction)+ .all(|instruction| instruction.phase() != CursorPhase::Caret)+ );+ let effect = presented+ .last()+ .and_then(CursorOverlayControl::instruction)+ .expect("an effect instruction");+ assert_eq!(effect.phase(), CursorPhase::Effect);+ assert!(effect.target().is_some());+}diff --git a/crates/core/src/ref_action/presentation_tests.rs b/crates/core/src/ref_action/presentation_tests.rsindex 45634a823..c1ce5305e 100644--- a/crates/core/src/ref_action/presentation_tests.rs+++ b/crates/core/src/ref_action/presentation_tests.rs@@ -50,3 +50,6 @@ mod lease;#[path = "presentation_shared_cursor_tests.rs"]mod shared_cursor;++#[path = "presentation_caret_tests.rs"]+mod caret;diff --git a/crates/macos/src/system/cursor_overlay/bridge.rs b/crates/macos/src/system/cursor_overlay/bridge.rsindex 2e95895e0..80c4bdbc1 100644--- a/crates/macos/src/system/cursor_overlay/bridge.rs+++ b/crates/macos/src/system/cursor_overlay/bridge.rs@@ -57,12 +57,28 @@ unsafe extern "C" {hotspot_y: f64,) -> bool;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_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) }+ }+}++/// 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>) {+ if instruction.departs_from(at) {+ unsafe { agent_desktop_cursor_overlay_caret_clear() }+ }+}+pub(super) fn begin_drag(from: &Point, trail: bool) {unsafe { agent_desktop_cursor_overlay_drag_begin(from.x, from.y, trail) }}@@ -178,6 +194,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::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/child.rs b/crates/macos/src/system/cursor_overlay/child.rsindex 52d86f03c..adf90bc92 100644--- a/crates/macos/src/system/cursor_overlay/child.rs+++ b/crates/macos/src/system/cursor_overlay/child.rs@@ -218,6 +218,9 @@ fn apply_landing_memory(let Some(instruction) = instruction else {return;};+ if instruction.phase() == CursorPhase::Caret {+ return;+ }state.at = Some(if instruction.phase() == CursorPhase::Drag {instruction.drag_from()@@ -232,6 +235,11 @@ fn render(instruction: &CursorOverlayInstruction,state: &OverlayState,) -> Result<(), AdapterError> {+ if instruction.phase() == CursorPhase::Caret {+ bridge::caret(instruction.target());+ 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.mindex 24480c2d9..fa269583a 100644--- a/crates/macos/src/system/cursor_overlay/cursor_overlay_bridge.m+++ b/crates/macos/src/system/cursor_overlay/cursor_overlay_bridge.m@@ -185,6 +185,7 @@ void agent_desktop_cursor_overlay_stop(void) {[ADBubbleWindow orderOut:nil];[ADRipple orderOut:nil];ADHighlightStop();+ ADCaretStop();ADTrailStop();ADCursorWindow = nil;ADPointer = nil;@@ -193,6 +194,21 @@ void agent_desktop_cursor_overlay_stop(void) {ADBubbleText = nil;}+void agent_desktop_cursor_overlay_caret(double x, double y, double width, double height) {+ if (ADCursorWindow == nil) {+ return;+ }+ @autoreleasepool {+ double mainHeight = CGDisplayBounds(CGMainDisplayID()).size.height;+ ADCaretShow(NSMakeRect(x, mainHeight - y - height, width, height));+ ADPump(NSApplication.sharedApplication);+ }+}++void agent_desktop_cursor_overlay_caret_clear(void) {+ ADCaretStop();+}+void agent_desktop_cursor_overlay_rest(void) {@autoreleasepool {NSApplication *app = NSApplication.sharedApplication;@@ -204,6 +220,7 @@ void agent_desktop_cursor_overlay_rest(void) {}[ADCursorWindow orderOut:nil];[ADBubbleWindow orderOut:nil];+ ADCaretStop();ADCursorWindow.alphaValue = 1.0;ADBubbleWindow.alphaValue = 1.0;ADTrailStop();@@ -212,6 +229,7 @@ void agent_desktop_cursor_overlay_rest(void) {void agent_desktop_cursor_overlay_hide(void) {ADDragCancel();+ ADCaretStop();[ADCursorWindow orderOut:nil];[ADBubbleWindow orderOut:nil];[ADRipple orderOut:nil];diff --git a/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome.h b/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome.hindex 997f08cdd..46e9df225 100644--- a/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome.h+++ b/crates/macos/src/system/cursor_overlay/cursor_overlay_chrome.h@@ -22,6 +22,8 @@ NSWindow *ADRippleWindow(void);void ADRipplePlay(NSWindow *window);void ADHighlightShow(NSRect frame, double seconds);void ADHighlightStop(void);+void ADCaretShow(NSRect frame);+void ADCaretStop(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.mindex 130bae7e2..d8244567b 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@@ -214,6 +214,31 @@ void ADHighlightShow(NSRect frame, double seconds) {[ADHighlightWindow orderFrontRegardless];}+static __strong NSWindow *ADCaretWindow = nil;+static __strong CALayer *ADCaretBar = nil;++void ADCaretShow(NSRect frame) {+ if (ADCaretWindow == nil) {+ ADCaretWindow = ADWindow(frame);+ ADCaretWindow.level = ADEffectLevel;+ ADCaretBar = [CALayer layer];+ ADCaretBar.cornerRadius = 1.0;+ ADFreezeLayer(ADCaretBar);+ [ADCaretWindow.contentView.layer addSublayer:ADCaretBar];+ }+ ADCaretBar.backgroundColor = ADColor(ADCurrentStyle.accent, 1.0);+ [ADCaretWindow setFrame:frame display:NO];+ ADCaretBar.frame = CGRectMake(0.0, 0.0, frame.size.width, frame.size.height);+ [ADCaretWindow orderFrontRegardless];+ [CATransaction flush];+}++void ADCaretStop(void) {+ [ADCaretWindow orderOut:nil];+ ADCaretWindow = nil;+ ADCaretBar = nil;+}+void ADHighlightStop(void) {[ADHighlightBorder removeAllAnimations];[ADHighlightWindow orderOut:nil];diff --git a/crates/macos/src/tree/adapter.rs b/crates/macos/src/tree/adapter.rsindex bce5626dc..9fb1d6dad 100644--- a/crates/macos/src/tree/adapter.rs+++ b/crates/macos/src/tree/adapter.rs@@ -169,6 +169,17 @@ impl ObservationOps for MacOSAdapter {Err(AdapterError::not_supported("get_live_actions"))}+ fn get_insertion_caret(+ &self,+ handle: &NativeHandle,+ deadline: Deadline,+ ) -> Result<Option<agent_desktop_core::Rect>, AdapterError> {+ Ok(crate::tree::properties::text_insertion::insertion_caret(+ ax_element(handle)?,+ deadline,+ ))+ }+fn get_live_element(&self,handle: &NativeHandle,diff --git a/crates/macos/src/tree/properties/ax_ipc.rs b/crates/macos/src/tree/properties/ax_ipc.rsindex 7cf132c8f..951b697d5 100644--- a/crates/macos/src/tree/properties/ax_ipc.rs+++ b/crates/macos/src/tree/properties/ax_ipc.rs@@ -5,10 +5,10 @@ use std::time::{Duration, Instant};use accessibility_sys::{AXUIElementCopyActionNames, AXUIElementCopyAttributeValue, AXUIElementCopyAttributeValues,AXUIElementCopyElementAtPosition, AXUIElementCopyMultipleAttributeValues,- AXUIElementGetAttributeValueCount, AXUIElementGetPid, AXUIElementIsAttributeSettable,- AXUIElementPerformAction, AXUIElementSetAttributeValue, AXUIElementSetMessagingTimeout,- kAXErrorAPIDisabled, kAXErrorCannotComplete, kAXErrorFailure, kAXErrorInvalidUIElement,- kAXErrorSuccess,+ AXUIElementCopyParameterizedAttributeValue, AXUIElementGetAttributeValueCount,+ AXUIElementGetPid, AXUIElementIsAttributeSettable, AXUIElementPerformAction,+ AXUIElementSetAttributeValue, AXUIElementSetMessagingTimeout, kAXErrorAPIDisabled,+ kAXErrorCannotComplete, kAXErrorFailure, kAXErrorInvalidUIElement, kAXErrorSuccess,};#[cfg(target_os = "macos")]use core_foundation_sys::{@@ -116,6 +116,23 @@ pub(crate) fn copy_attribute_value((error, value)}+#[cfg(target_os = "macos")]+pub(crate) fn copy_parameterized_attribute_value(+ element: &crate::tree::AXElement,+ attribute: CFStringRef,+ parameter: CFTypeRef,+ deadline: impl AxDeadline,+) -> (i32, CFTypeRef) {+ let mut value: CFTypeRef = std::ptr::null();+ let error = match prepare(element, deadline) {+ Ok(_) => unsafe {+ AXUIElementCopyParameterizedAttributeValue(element.0, attribute, parameter, &mut value)+ },+ Err(error) => adapter_error_to_ax(&error),+ };+ (error, value)+}+#[cfg(target_os = "macos")]pub(crate) fn copy_attribute_values(element: &crate::tree::AXElement,diff --git a/crates/macos/src/tree/properties/mod.rs b/crates/macos/src/tree/properties/mod.rsindex 428296f50..5ef22c871 100644--- a/crates/macos/src/tree/properties/mod.rs+++ b/crates/macos/src/tree/properties/mod.rs@@ -22,3 +22,4 @@ pub(crate) mod node_identifiers;pub(crate) mod node_semantic_states;pub(crate) mod readonly;pub(crate) mod text_attributes;+pub(crate) mod text_insertion;diff --git a/crates/macos/src/tree/properties/text_insertion.rs b/crates/macos/src/tree/properties/text_insertion.rsnew file mode 100644index 000000000..8d6ed889a--- /dev/null+++ b/crates/macos/src/tree/properties/text_insertion.rs@@ -0,0 +1,133 @@+//! Where a text element's insertion point sits on screen, read from the text+//! system rather than inferred from the element's bounds: the bounds of the+//! character before the insertion point, or, after a line break or in an+//! empty field, the start of the line it opens.++#[cfg(target_os = "macos")]+mod imp {+ use crate::tree::AXElement;+ use agent_desktop_core::{Deadline, Rect};++ const CARET_WIDTH: f64 = 2.0;+ const MIN_CARET_HEIGHT: f64 = 10.0;++ 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;+ if at == 0 {+ return bounds_for_range(element, 0, 1, deadline)+ .or_else(|| bounds_for_range(element, 0, 0, deadline))+ .map(|first| caret(first.x, &first));+ }+ let previous = bounds_for_range(element, at - 1, 1, deadline)?;+ if string_for_range(element, at - 1, 1, deadline).as_deref() != Some("\n") {+ return Some(caret(previous.x + previous.width, &previous));+ }+ let left = bounds_for_range(element, 0, 1, deadline).map_or(previous.x, |first| first.x);+ Some(Rect {+ x: left,+ y: previous.y + previous.height,+ width: CARET_WIDTH,+ height: previous.height.max(MIN_CARET_HEIGHT),+ })+ }++ fn caret(x: f64, line: &Rect) -> Rect {+ Rect {+ x,+ y: line.y,+ width: CARET_WIDTH,+ height: line.height.max(MIN_CARET_HEIGHT),+ }+ }++ fn bounds_for_range(+ element: &AXElement,+ location: usize,+ length: usize,+ deadline: Deadline,+ ) -> Option<Rect> {+ use accessibility_sys::{AXValueGetValue, kAXValueTypeCGRect};+ use core_graphics::geometry::CGRect;++ let raw = copy_for_range(element, "AXBoundsForRange", location, length, deadline)?;+ let mut rect = CGRect::new(+ &core_graphics::geometry::CGPoint::new(0.0, 0.0),+ &core_graphics::geometry::CGSize::new(0.0, 0.0),+ );+ let decoded = unsafe {+ AXValueGetValue(+ raw.as_CFTypeRef() as _,+ kAXValueTypeCGRect,+ (&mut rect as *mut CGRect).cast(),+ )+ };+ (decoded && rect.size.height > 0.0).then_some(Rect {+ x: rect.origin.x,+ y: rect.origin.y,+ width: rect.size.width,+ height: rect.size.height,+ })+ }++ fn string_for_range(+ element: &AXElement,+ location: usize,+ length: usize,+ deadline: Deadline,+ ) -> Option<String> {+ use core_foundation::string::CFString;++ let raw = copy_for_range(element, "AXStringForRange", location, length, deadline)?;+ raw.downcast::<CFString>().map(|text| text.to_string())+ }++ use core_foundation::base::TCFType;++ fn copy_for_range(+ element: &AXElement,+ attribute: &str,+ location: usize,+ length: usize,+ deadline: Deadline,+ ) -> Option<core_foundation::base::CFType> {+ use accessibility_sys::{AXValueCreate, kAXErrorSuccess, kAXValueTypeCFRange};+ use core_foundation::{base::CFType, string::CFString};+ use core_foundation_sys::base::CFRange;++ let range = CFRange {+ location: isize::try_from(location).ok()?,+ length: isize::try_from(length).ok()?,+ };+ let parameter =+ unsafe { AXValueCreate(kAXValueTypeCFRange, (&range as *const CFRange).cast()) };+ if parameter.is_null() {+ return None;+ }+ let parameter = unsafe { CFType::wrap_under_create_rule(parameter as _) };+ let attribute = CFString::new(attribute);+ let (error, raw) = super::super::ax_ipc::copy_parameterized_attribute_value(+ element,+ attribute.as_concrete_TypeRef(),+ parameter.as_CFTypeRef(),+ deadline,+ );+ if raw.is_null() {+ return None;+ }+ let value = unsafe { CFType::wrap_under_create_rule(raw) };+ (error == kAXErrorSuccess).then_some(value)+ }+}++#[cfg(not(target_os = "macos"))]+mod imp {+ use crate::tree::AXElement;+ use agent_desktop_core::{Deadline, Rect};++ pub(crate) fn insertion_caret(_element: &AXElement, _deadline: Deadline) -> Option<Rect> {+ None+ }+}++pub(crate) use imp::insertion_caret;diff --git a/crates/windows/src/system/cursor_overlay/surface_host.rs b/crates/windows/src/system/cursor_overlay/surface_host.rsindex 95851906b..e61a5a69b 100644--- a/crates/windows/src/system/cursor_overlay/surface_host.rs+++ b/crates/windows/src/system/cursor_overlay/surface_host.rs@@ -99,6 +99,7 @@ impl SurfaceHost {.clone(),instruction.target().cloned(),),+ CursorPhase::Caret => {}CursorPhase::Effect => {}},}@@ -128,6 +129,7 @@ impl SurfaceHost {instruction.is_click(),interrupt,),+ CursorPhase::Caret => {}}}CursorOverlayControl::Hide { .. } | CursorOverlayControl::Disable { .. } => {}diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.mdindex bd0bde384..cddad8be2 100644--- a/skills/agent-desktop/references/commands-system.md+++ b/skills/agent-desktop/references/commands-system.md@@ -198,6 +198,8 @@ On macOS and Windows:Windows accepts the motion settings but keeps its built-in motion.+On macOS, 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.+Multi-agent cursors (macOS and Windows): start with `session start --cursor --multi-agent`, then pass the returned session id to every subagent.- Desktop UI actions then require an agent id: global `--agent-id <id>` or `AGENT_DESKTOP_AGENT_ID`. The flag wins. Observations, clipboard commands and session administration do not need one.