Skip to content

Computer use CLI for AI agents

feat(windows): show the insertion caret after text entry (#350)

Chris Tate6a0d6120e17c
diff --git a/apps/docs/content/docs/commands/system.mdx b/apps/docs/content/docs/commands/system.mdx
index cf0f6744e..560baa8d2 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, 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. 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/windows/src/adapter.rs b/crates/windows/src/adapter.rs
index 0424b6910..8af580f8c 100644
--- a/crates/windows/src/adapter.rs
+++ b/crates/windows/src/adapter.rs
@@ -124,6 +124,14 @@ impl ObservationOps for WindowsAdapter {
crate::tree::text_selection::get_text_selection(handle, deadline)
}
+ fn get_insertion_caret(
+ &self,
+ handle: &NativeHandle,
+ deadline: Deadline,
+ ) -> Result<Option<agent_desktop_core::Rect>, AdapterError> {
+ crate::tree::text_insertion::get_insertion_caret(handle, 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
new file mode 100644
index 000000000..3b6fb4f43
--- /dev/null
+++ b/crates/windows/src/system/cursor_overlay/caret_mark.rs
@@ -0,0 +1,77 @@
+//! The agent's text caret: a thin bar in the accent colour where the app is
+//! inserting text, in a layered window of its own so it can sit in a text
+//! field far from wherever the cursor rests. It marks the field the cursor
+//! was typing in, so it goes when the cursor sets off for somewhere else.
+
+#[cfg(target_os = "windows")]
+pub(crate) use imp::CaretMark;
+
+use agent_desktop_core::{CURSOR_SAME_POINT, Point};
+
+/// Whether moving the cursor from `from` to `to` leaves the place it was:
+/// [`CURSOR_SAME_POINT`] or more away, the way the macOS renderer decides.
+pub(crate) fn leaves(from: &Point, to: &Point) -> bool {
+ (to.x - from.x).hypot(to.y - from.y) >= CURSOR_SAME_POINT
+}
+
+#[cfg(test)]
+#[path = "caret_mark_tests.rs"]
+mod tests;
+
+#[cfg(target_os = "windows")]
+mod imp {
+ use agent_desktop_core::{AdapterError, Rect};
+
+ use crate::system::cursor_overlay::window::OverlayWindow;
+
+ pub(crate) struct CaretMark {
+ window: OverlayWindow,
+ }
+
+ impl CaretMark {
+ pub(crate) fn create() -> Result<Self, AdapterError> {
+ Ok(Self {
+ window: OverlayWindow::create()?,
+ })
+ }
+
+ /// 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]) {
+ 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;
+ let pixel = (0xFF << 24)
+ | (channel(accent[0]) << 16)
+ | (channel(accent[1]) << 8)
+ | channel(accent[2]);
+ let pixels = vec![pixel; (width as usize) * (height as usize)];
+ self.window.raise();
+ let _ = self.window.present(
+ at.x.round() as i32,
+ at.y.round() as i32,
+ width,
+ height,
+ &pixels,
+ );
+ self.window.pump();
+ }
+
+ pub(crate) fn hide(&self) {
+ let _ = self.window.present(0, 0, 0, 0, &[]);
+ self.window.pump();
+ }
+
+ /// Hides the caret when the cursor sets off from `from` for `to`
+ /// somewhere else; a travel that stays put keeps it.
+ pub(crate) fn hide_when_leaving(
+ &self,
+ from: &agent_desktop_core::Point,
+ to: &agent_desktop_core::Point,
+ ) {
+ if super::leaves(from, to) {
+ self.hide();
+ }
+ }
+ }
+}
diff --git a/crates/windows/src/system/cursor_overlay/caret_mark_tests.rs b/crates/windows/src/system/cursor_overlay/caret_mark_tests.rs
new file mode 100644
index 000000000..ddd7a03b6
--- /dev/null
+++ b/crates/windows/src/system/cursor_overlay/caret_mark_tests.rs
@@ -0,0 +1,10 @@
+use super::leaves;
+use agent_desktop_core::Point;
+
+#[test]
+fn a_move_somewhere_else_leaves_and_one_that_stays_put_does_not() {
+ let at = Point { x: 100.0, y: 50.0 };
+
+ assert!(leaves(&at, &Point { x: 140.0, y: 50.0 }));
+ assert!(!leaves(&at, &Point { x: 101.0, y: 50.5 }));
+}
diff --git a/crates/windows/src/system/cursor_overlay/mod.rs b/crates/windows/src/system/cursor_overlay/mod.rs
index cb2bdd25a..4d252ec84 100644
--- a/crates/windows/src/system/cursor_overlay/mod.rs
+++ b/crates/windows/src/system/cursor_overlay/mod.rs
@@ -12,6 +12,8 @@
//! a test.
pub(crate) mod animation;
+#[cfg(target_os = "windows")]
+pub(crate) mod caret_mark;
pub(crate) mod child;
pub(crate) mod cursor_image;
#[cfg(target_os = "windows")]
diff --git a/crates/windows/src/system/cursor_overlay/surface_host.rs b/crates/windows/src/system/cursor_overlay/surface_host.rs
index e61a5a69b..f20afcf6c 100644
--- a/crates/windows/src/system/cursor_overlay/surface_host.rs
+++ b/crates/windows/src/system/cursor_overlay/surface_host.rs
@@ -17,8 +17,8 @@
use super::presentation::{Presentation, RestState};
#[cfg(target_os = "windows")]
use crate::system::cursor_overlay::{
- animation, fade, geometry, label, monitors, render, reveal::Reveal, schedule, session_state,
- text, topology::DisplayTopology, window::OverlayWindow,
+ animation, caret_mark::CaretMark, fade, geometry, label, monitors, render, reveal::Reveal,
+ schedule, session_state, text, topology::DisplayTopology, window::OverlayWindow,
};
#[cfg(target_os = "windows")]
use agent_desktop_core::{
@@ -36,6 +36,7 @@ const REST_FADE_STEPS: u32 = 13;
#[cfg(target_os = "windows")]
pub(crate) struct SurfaceHost {
window: OverlayWindow,
+ caret: CaretMark,
session_id: String,
presentation: Presentation,
rest: RestState,
@@ -50,6 +51,7 @@ impl SurfaceHost {
let pose = monitors::resting_point(topology.monitors()).unwrap_or(Point { x: 0.0, y: 0.0 });
Ok(Self {
window: OverlayWindow::create()?,
+ caret: CaretMark::create()?,
session_id,
presentation: Presentation::resting_at(pose),
rest: RestState {
@@ -99,7 +101,12 @@ impl SurfaceHost {
.clone(),
instruction.target().cloned(),
),
- CursorPhase::Caret => {}
+ CursorPhase::Caret => {
+ if let Some(at) = instruction.target() {
+ let accent = self.presentation.style.accent_rgb();
+ self.caret.show(at, accent);
+ }
+ }
CursorPhase::Effect => {}
},
}
@@ -157,6 +164,8 @@ impl SurfaceHost {
/// action is blocked on, so giving it up for a newer control would
/// dispatch a click at wherever the cursor had got to.
fn travel(&mut self, destination: Point, target: Option<Rect>) {
+ self.caret
+ .hide_when_leaving(&self.presentation.pose, &destination);
let motion = CursorMotion::new(self.presentation.pose.clone(), destination.clone())
.with_impact(false)
.with_ripple(false);
@@ -283,6 +292,7 @@ impl SurfaceHost {
fn clear(&self) {
let _ = self.window.present(0, 0, 1, 1, &[0u32]);
self.window.pump();
+ self.caret.hide();
}
/// One quiet tick: pump the window, re-read the display topology, and
diff --git a/crates/windows/src/tree/mod.rs b/crates/windows/src/tree/mod.rs
index 9d9dd1322..e91a867a9 100644
--- a/crates/windows/src/tree/mod.rs
+++ b/crates/windows/src/tree/mod.rs
@@ -12,6 +12,7 @@ pub mod roles;
pub mod states;
pub(crate) mod surface_inventory;
pub mod surfaces;
+pub(crate) mod text_insertion;
pub(crate) mod text_selection;
pub mod walk;
diff --git a/crates/windows/src/tree/text_insertion.rs b/crates/windows/src/tree/text_insertion.rs
new file mode 100644
index 000000000..f7ca01a3c
--- /dev/null
+++ b/crates/windows/src/tree/text_insertion.rs
@@ -0,0 +1,176 @@
+//! Where a text element's insertion point sits on screen, read from its Text
+//! pattern: 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.
+//! A degenerate range has no bounds of its own, so the caret is placed from
+//! its neighbour.
+
+/// The caret for a line box `line`, `x` along it.
+fn caret_at(x: f64, line: &agent_desktop_core::Rect) -> agent_desktop_core::Rect {
+ agent_desktop_core::Rect {
+ x,
+ y: line.y,
+ width: 2.0,
+ height: line.height.max(10.0),
+ }
+}
+
+fn is_line_break(text: &str) -> bool {
+ matches!(text, "\r" | "\n" | "\r\n" | "\u{2028}" | "\u{2029}")
+}
+
+/// How many lines `text` ends, so a caret on an empty line, whose break a
+/// provider reports no bounds for, can be placed that many lines below the
+/// first: CR LF is one break, and so is a lone CR, LF or Unicode separator.
+fn count_line_breaks(text: &str) -> u32 {
+ let mut count = 0;
+ let mut after_cr = false;
+ for character in text.chars() {
+ if !(character == '\n' && after_cr)
+ && matches!(character, '\r' | '\n' | '\u{2028}' | '\u{2029}')
+ {
+ count += 1;
+ }
+ after_cr = character == '\r';
+ }
+ count
+}
+
+#[cfg(target_os = "windows")]
+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 uiautomation::patterns::{UITextPattern, UITextRange};
+ use uiautomation::types::{TextPatternRangeEndpoint, TextUnit};
+ use uiautomation::variants::SafeArray;
+ use windows::Win32::System::Variant::VT_R8;
+
+ pub(crate) fn get_insertion_caret(
+ handle: &NativeHandle,
+ deadline: Deadline,
+ ) -> Result<Option<Rect>, AdapterError> {
+ deadline.ensure_remaining()?;
+ let element = uia_element(handle)?;
+ let Ok(pattern) = element.0.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)?;
+ let moved = previous
+ .move_endpoint_by_unit(TextPatternRangeEndpoint::Start, TextUnit::Character, -1)
+ .ok()?;
+ if moved == 0 {
+ let first = first_character(pattern)?;
+ return Some(caret_at(first.x, &first));
+ }
+ let text = previous.get_text(-1).ok()?;
+ let line = bounds(&previous);
+ if !is_line_break(&text) {
+ let line = line?;
+ return Some(caret_at(line.x + line.width, &line));
+ }
+ let first = first_character(pattern);
+ if let Some(line) = line {
+ return Some(Rect {
+ x: first.map_or(line.x, |first| first.x),
+ y: line.y + line.height,
+ width: 2.0,
+ height: line.height.max(10.0),
+ });
+ }
+ let first = first?;
+ let breaks = count_line_breaks(&text_before(pattern, &selection)?);
+ Some(Rect {
+ x: first.x,
+ y: first.y + f64::from(breaks) * first.height,
+ width: 2.0,
+ height: first.height.max(10.0),
+ })
+ }
+
+ /// The document's text up to the insertion point.
+ fn text_before(pattern: &UITextPattern, selection: &UITextRange) -> Option<String> {
+ let range = pattern.get_document_range().ok()?;
+ range
+ .move_endpoint_by_range(
+ TextPatternRangeEndpoint::End,
+ selection,
+ TextPatternRangeEndpoint::End,
+ )
+ .ok()?;
+ range.get_text(-1).ok()
+ }
+
+ fn collapsed_at_end(pattern: &UITextPattern, selection: &UITextRange) -> Option<UITextRange> {
+ let range = pattern.get_document_range().ok()?;
+ range
+ .move_endpoint_by_range(
+ TextPatternRangeEndpoint::Start,
+ selection,
+ TextPatternRangeEndpoint::End,
+ )
+ .ok()?;
+ range
+ .move_endpoint_by_range(
+ TextPatternRangeEndpoint::End,
+ selection,
+ TextPatternRangeEndpoint::End,
+ )
+ .ok()?;
+ Some(range)
+ }
+
+ fn first_character(pattern: &UITextPattern) -> Option<Rect> {
+ let range = pattern.get_document_range().ok()?;
+ let document_start = pattern.get_document_range().ok()?;
+ range
+ .move_endpoint_by_range(
+ TextPatternRangeEndpoint::End,
+ &document_start,
+ TextPatternRangeEndpoint::Start,
+ )
+ .ok()?;
+ range
+ .move_endpoint_by_unit(TextPatternRangeEndpoint::End, TextUnit::Character, 1)
+ .ok()?;
+ bounds(&range)
+ }
+
+ /// The first line box of a range, from its bounding rectangles: x, y,
+ /// width and height quadruples in screen pixels.
+ fn bounds(range: &UITextRange) -> Option<Rect> {
+ let raw = unsafe { range.as_ref().GetBoundingRectangles() }.ok()?;
+ let values: Vec<f64> = SafeArray::from(raw).into_vector(VT_R8).ok()?;
+ let [x, y, width, height] = values.get(..4)? else {
+ return None;
+ };
+ (*height > 0.0).then_some(Rect {
+ x: *x,
+ y: *y,
+ width: *width,
+ height: *height,
+ })
+ }
+}
+
+#[cfg(not(target_os = "windows"))]
+mod imp {
+ use agent_desktop_core::{AdapterError, Deadline, NativeHandle, Rect};
+
+ pub(crate) fn get_insertion_caret(
+ _handle: &NativeHandle,
+ _deadline: Deadline,
+ ) -> Result<Option<Rect>, AdapterError> {
+ Ok(None)
+ }
+}
+
+pub(crate) use imp::get_insertion_caret;
+
+#[cfg(test)]
+#[path = "text_insertion_tests.rs"]
+mod tests;
diff --git a/crates/windows/src/tree/text_insertion_tests.rs b/crates/windows/src/tree/text_insertion_tests.rs
new file mode 100644
index 000000000..c6ec281ee
--- /dev/null
+++ b/crates/windows/src/tree/text_insertion_tests.rs
@@ -0,0 +1,31 @@
+use super::{caret_at, count_line_breaks, is_line_break};
+
+#[test]
+fn the_caret_takes_the_line_box_height_at_the_given_x() {
+ let line = agent_desktop_core::Rect {
+ x: 10.0,
+ y: 40.0,
+ width: 8.0,
+ height: 18.0,
+ };
+ let caret = caret_at(18.0, &line);
+ assert_eq!(
+ (caret.x, caret.y, caret.width, caret.height),
+ (18.0, 40.0, 2.0, 18.0)
+ );
+}
+
+#[test]
+fn line_breaks_of_every_kind_are_recognised() {
+ for text in ["\r", "\n", "\r\n", "\u{2028}", "\u{2029}"] {
+ assert!(is_line_break(text), "{text:?}");
+ }
+ assert!(!is_line_break("a"));
+}
+
+#[test]
+fn crlf_counts_as_one_line_break() {
+ assert_eq!(count_line_breaks("first\r\n\r\nthird\r\n"), 3);
+ assert_eq!(count_line_breaks("a\rb\nc\u{2028}"), 3);
+ assert_eq!(count_line_breaks("no breaks"), 0);
+}
diff --git a/skills/agent-desktop-windows/references/shell-and-overlay.md b/skills/agent-desktop-windows/references/shell-and-overlay.md
index 9e2f64856..c937dae39 100644
--- a/skills/agent-desktop-windows/references/shell-and-overlay.md
+++ b/skills/agent-desktop-windows/references/shell-and-overlay.md
@@ -119,6 +119,10 @@ agent-desktop cursor-overlay disable
each action replaces the card text.
- **It fades out after 6 s with no instruction** and comes straight back on the
next command.
+- **The caret comes from the Text pattern.** After text entry, the agent's caret
+ sits where the field's Text pattern places the insertion point, in a window
+ of its own, and goes when the cursor sets off for somewhere else. A field
+ without the Text pattern keeps the element outline.
- **It draws in physical pixels**, the space element bounds are reported in,
so it is not scaled again for the monitor's DPI. Multi-monitor placement is
unit-tested only and not verified on a live multi-monitor desktop.
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index cddad8be2..b5f3e8b4a 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, 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.
Multi-agent cursors (macOS and Windows): start with `session start --cursor --multi-agent`, then pass the returned session id to every subagent.