Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat(windows): draw image cursors in the overlay (#345)
Chris Tate7e5943e98851
diff --git a/Cargo.lock b/Cargo.lockindex 890ee0711..3135275a4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -107,6 +107,7 @@ name = "agent-desktop-windows"version = "1.0.2"dependencies = ["agent-desktop-core",+ "png","serde_json","thiserror","tracing",diff --git a/crates/windows/Cargo.toml b/crates/windows/Cargo.tomlindex e91e43124..82d6d6196 100644--- a/crates/windows/Cargo.toml+++ b/crates/windows/Cargo.toml@@ -7,6 +7,7 @@ publish = false[dependencies]agent-desktop-core.workspace = true+png = { version = "=0.18.1", default-features = false }serde_json.workspace = truethiserror.workspace = truetracing.workspace = truediff --git a/crates/windows/src/system/cursor_overlay/cursor_image.rs b/crates/windows/src/system/cursor_overlay/cursor_image.rsnew file mode 100644index 000000000..df33c9f52--- /dev/null+++ b/crates/windows/src/system/cursor_overlay/cursor_image.rs@@ -0,0 +1,169 @@+//! A caller's cursor image, drawn in place of the built-in dart.+//!+//! The PNG is decoded once per version of its file and kept premultiplied,+//! in the surface's own BGRA layout, so a frame only composites it. Each draw+//! checks the file's size and modification time, the way the macOS renderer+//! re-checks its image, so a replaced PNG is decoded again and one that failed+//! to decode is retried once it changes. It is drawn at the style's size, with+//! its hotspot on the pose point, the way the macOS renderer draws it.++use std::cell::RefCell;+use std::collections::HashMap;+use std::rc::Rc;+use std::time::SystemTime;++use agent_desktop_core::{CursorImage, Point, Rect};++use super::raster::{Surface, SurfaceMapping};++pub(crate) struct DecodedImage {+ width: u32,+ height: u32,+ pixels: Vec<u32>,+}++/// A file's version as the cache sees it: its length and modification time.+type FileStamp = (u64, Option<SystemTime>);++/// A decode and the file version it was made from; `None` when it failed.+type CachedDecode = (FileStamp, Option<Rc<DecodedImage>>);++thread_local! {+ static DECODED: RefCell<HashMap<String, CachedDecode>> = RefCell::new(HashMap::new());+}++/// The decoded image for `image`, or `None` when its file is missing or not a+/// readable PNG; the dart is drawn instead. A result is reused only while the+/// file keeps the size and modification time it was decoded at.+pub(crate) fn decoded(image: &CursorImage) -> Option<Rc<DecodedImage>> {+ let path = image.path();+ let stamp = file_stamp(path)?;+ DECODED.with(|cache| {+ let mut cache = cache.borrow_mut();+ if let Some((cached, decoded)) = cache.get(path)+ && *cached == stamp+ {+ return decoded.clone();+ }+ let decoded = decode(path).map(Rc::new);+ cache.insert(path.to_owned(), (stamp, decoded.clone()));+ decoded+ })+}++fn file_stamp(path: &str) -> Option<FileStamp> {+ let metadata = std::fs::metadata(path).ok()?;+ Some((metadata.len(), metadata.modified().ok()))+}++/// Where the image lands for a pose: its hotspot on the tip, scaled.+pub(crate) fn image_rect(+ tip: &Point,+ image: &CursorImage,+ decoded: &DecodedImage,+ scale: f64,+) -> Rect {+ let hotspot = image.hotspot();+ Rect {+ x: tip.x - hotspot.x * scale,+ y: tip.y - hotspot.y * scale,+ width: f64::from(decoded.width) * scale,+ height: f64::from(decoded.height) * scale,+ }+}++/// Composites the image over the surface, sampling the nearest source pixel+/// for each destination pixel so a 1:1 draw is exact.+pub(crate) fn draw_image(+ surface: &mut Surface,+ mapping: &SurfaceMapping,+ at: &Rect,+ decoded: &DecodedImage,+) {+ let local = mapping.to_local(at);+ if local.width <= 0.0 || local.height <= 0.0 {+ return;+ }+ let left = local.x.floor() as i32;+ let top = local.y.floor() as i32;+ let right = (local.x + local.width).ceil() as i32;+ let bottom = (local.y + local.height).ceil() as i32;+ for y in top.max(0)..bottom.min(surface.height) {+ let v = ((f64::from(y) + 0.5 - local.y) / local.height * f64::from(decoded.height)).floor();+ if v < 0.0 || v >= f64::from(decoded.height) {+ continue;+ }+ for x in left.max(0)..right.min(surface.width) {+ let u =+ ((f64::from(x) + 0.5 - local.x) / local.width * f64::from(decoded.width)).floor();+ if u < 0.0 || u >= f64::from(decoded.width) {+ continue;+ }+ let source = decoded.pixels[(v as usize) * (decoded.width as usize) + (u as usize)];+ composite(surface, x, y, source);+ }+ }+}++/// Source-over for one premultiplied pixel onto the premultiplied surface.+fn composite(surface: &mut Surface, x: i32, y: i32, source: u32) {+ let source_alpha = source >> 24;+ if source_alpha == 0 {+ return;+ }+ let index = (y as usize) * (surface.width as usize) + (x as usize);+ let Some(under) = surface.pixels.get(index).copied() else {+ return;+ };+ let keep = 255 - source_alpha;+ let channel = |shift: u32| {+ let over = (source >> shift) & 0xFF;+ let below = (under >> shift) & 0xFF;+ (over + (below * keep + 127) / 255).min(255)+ };+ surface.pixels[index] =+ (channel(24) << 24) | (channel(16) << 16) | (channel(8) << 8) | channel(0);+}++fn decode(path: &str) -> Option<DecodedImage> {+ use png::{ColorType, Decoder, Transformations};++ let file = std::fs::File::open(path).ok()?;+ let mut decoder = Decoder::new(std::io::BufReader::new(file));+ decoder.set_transformations(Transformations::EXPAND | Transformations::STRIP_16);+ let mut reader = decoder.read_info().ok()?;+ let mut frame = vec![0; reader.output_buffer_size()?];+ let info = reader.next_frame(&mut frame).ok()?;+ let channels = match info.color_type {+ ColorType::Rgba => 4,+ ColorType::Rgb => 3,+ ColorType::GrayscaleAlpha => 2,+ ColorType::Grayscale => 1,+ ColorType::Indexed => return None,+ };+ let count = (info.width as usize).checked_mul(info.height as usize)?;+ let pixels = (0..count)+ .map(|index| premultiplied(&frame[index * channels..index * channels + channels]))+ .collect();+ Some(DecodedImage {+ width: info.width,+ height: info.height,+ pixels,+ })+}++fn premultiplied(sample: &[u8]) -> u32 {+ let (red, green, blue, alpha) = match *sample {+ [r, g, b, a] => (r, g, b, a),+ [r, g, b] => (r, g, b, 255),+ [l, a] => (l, l, l, a),+ [l] => (l, l, l, 255),+ _ => (0, 0, 0, 0),+ };+ let scale = |channel: u8| (u32::from(channel) * u32::from(alpha) + 127) / 255;+ (u32::from(alpha) << 24) | (scale(red) << 16) | (scale(green) << 8) | scale(blue)+}++#[cfg(test)]+#[path = "cursor_image_tests.rs"]+mod tests;diff --git a/crates/windows/src/system/cursor_overlay/cursor_image_tests.rs b/crates/windows/src/system/cursor_overlay/cursor_image_tests.rsnew file mode 100644index 000000000..0f20d1c50--- /dev/null+++ b/crates/windows/src/system/cursor_overlay/cursor_image_tests.rs@@ -0,0 +1,104 @@+use super::*;++#[test]+fn an_opaque_sample_keeps_its_colour_and_a_clear_one_vanishes() {+ assert_eq!(premultiplied(&[255, 174, 0, 255]), 0xFF_FF_AE_00);+ assert_eq!(premultiplied(&[255, 255, 255, 0]), 0);+}++#[test]+fn a_half_transparent_sample_is_premultiplied() {+ assert_eq!(premultiplied(&[255, 0, 0, 128]), 0x80_80_00_00);+}++#[test]+fn the_image_hangs_from_its_hotspot_at_the_style_size() {+ let image = CursorImage::new(+ if cfg!(windows) {+ "C:\\cursor.png"+ } else {+ "/cursor.png"+ }+ .into(),+ Point { x: 18.0, y: 16.0 },+ )+ .expect("valid image");+ let decoded = DecodedImage {+ width: 200,+ height: 100,+ pixels: vec![0; 20_000],+ };+ let rect = image_rect(&Point { x: 100.0, y: 50.0 }, &image, &decoded, 0.5);+ assert_eq!(+ (rect.x, rect.y, rect.width, rect.height),+ (91.0, 42.0, 100.0, 50.0)+ );+}++#[test]+fn compositing_over_a_transparent_surface_copies_the_source() {+ let mut surface = Surface::try_transparent(2, 1).expect("surface");+ composite(&mut surface, 1, 0, 0x80_40_20_10);+ assert_eq!(surface.pixels, vec![0, 0x80_40_20_10]);+}++fn write_png(path: &std::path::Path, width: u32, height: u32) {+ let file = std::fs::File::create(path).expect("png file");+ let mut encoder = png::Encoder::new(std::io::BufWriter::new(file), width, height);+ encoder.set_color(png::ColorType::Rgba);+ encoder.set_depth(png::BitDepth::Eight);+ let pixels = vec![255u8; (width * height * 4) as usize];+ encoder+ .write_header()+ .expect("png header")+ .write_image_data(&pixels)+ .expect("png pixels");+}++fn scratch_png(name: &str) -> std::path::PathBuf {+ let directory = std::env::temp_dir().join(format!(+ "agent-desktop-cursor-image-{}-{name}",+ std::process::id()+ ));+ std::fs::create_dir_all(&directory).expect("scratch directory");+ directory.join("cursor.png")+}++fn image_at(path: &std::path::Path) -> CursorImage {+ CursorImage::new(+ path.to_str().expect("utf-8 path").into(),+ Point { x: 0.0, y: 0.0 },+ )+ .expect("valid image")+}++/// Replacing the PNG at the same path, then enabling again with it, has to+/// draw the new art rather than the decode cached for the old file.+#[test]+fn a_replaced_png_is_decoded_again() {+ let path = scratch_png("replaced");+ write_png(&path, 4, 4);+ let image = image_at(&path);+ assert_eq!(decoded(&image).expect("decodes").width, 4);++ write_png(&path, 8, 6);++ let refreshed = decoded(&image).expect("decodes the new file");+ assert_eq!((refreshed.width, refreshed.height), (8, 6));+ let _ = std::fs::remove_file(&path);+}++/// A file that failed to decode is not written off for good: once it is+/// fixed it is drawn.+#[test]+fn a_png_that_failed_to_decode_is_retried_once_it_changes() {+ let path = scratch_png("retried");+ std::fs::write(&path, b"not a png").expect("broken file");+ let image = image_at(&path);+ assert!(decoded(&image).is_none());++ write_png(&path, 5, 5);++ assert_eq!(decoded(&image).expect("decodes once fixed").width, 5);+ let _ = std::fs::remove_file(&path);+}diff --git a/crates/windows/src/system/cursor_overlay/geometry.rs b/crates/windows/src/system/cursor_overlay/geometry.rsindex 0f8784a28..3284ad7e1 100644--- a/crates/windows/src/system/cursor_overlay/geometry.rs+++ b/crates/windows/src/system/cursor_overlay/geometry.rs@@ -104,7 +104,7 @@ pub(crate) fn follower_rect(union}-fn union_of(left: &Rect, right: &Rect) -> Rect {+pub(crate) fn union_of(left: &Rect, right: &Rect) -> Rect {let x = left.x.min(right.x);let y = left.y.min(right.y);let right_edge = (left.x + left.width).max(right.x + right.width);diff --git a/crates/windows/src/system/cursor_overlay/mod.rs b/crates/windows/src/system/cursor_overlay/mod.rsindex 977b3dc49..cb2bdd25a 100644--- a/crates/windows/src/system/cursor_overlay/mod.rs+++ b/crates/windows/src/system/cursor_overlay/mod.rs@@ -13,6 +13,7 @@pub(crate) mod animation;pub(crate) mod child;+pub(crate) mod cursor_image;#[cfg(target_os = "windows")]pub(crate) mod dib;#[cfg(target_os = "windows")]diff --git a/crates/windows/src/system/cursor_overlay/presentation.rs b/crates/windows/src/system/cursor_overlay/presentation.rsindex dfb829327..f68d545f5 100644--- a/crates/windows/src/system/cursor_overlay/presentation.rs+++ b/crates/windows/src/system/cursor_overlay/presentation.rs@@ -10,11 +10,11 @@ pub(crate) use imp::{Presentation, RestState};#[cfg(target_os = "windows")]mod imp {use crate::system::cursor_overlay::reveal::Reveal;- use agent_desktop_core::{CursorOverlayStyle, Point};+ use agent_desktop_core::{CursorOverlayControl, CursorOverlayStyle, Point};use std::time::Instant;/// The three things a frame is composed from, plus when the card began- /// appearing.+ /// appearing, and whether the cursor shows its pointer image.////// The reveal instant belongs here rather than beside the rest state/// because it is a property of the label: it is set when the label@@ -24,6 +24,52 @@ mod imp {pub(crate) pose: Point,pub(crate) label: Option<String>,pub(crate) reveal: Reveal,+ pointing: bool,+ arrives_pointing: bool,+ }++ impl Presentation {+ pub(crate) fn resting_at(pose: Point) -> Self {+ Self {+ style: CursorOverlayStyle::default(),+ pose,+ label: None,+ reveal: Reveal::Settled,+ pointing: false,+ arrives_pointing: false,+ }+ }++ /// The label a control asks the card to show. The greeting `Enable`+ /// sends is left off while the cursor is drawn from a custom image.+ pub(crate) fn label_from<'a>(&self, control: &'a CursorOverlayControl) -> Option<&'a str> {+ let greeting_over_image = control.is_enable() && self.style.image().is_some();+ control.label().filter(|_| !greeting_over_image)+ }++ /// A travel sets off showing the arrow, and arrives showing the+ /// pointer image when it lands on a pressable control.+ pub(crate) fn depart(&mut self, arrives_pointing: bool) {+ self.pointing = false;+ self.arrives_pointing = arrives_pointing;+ }++ pub(crate) fn arrive(&mut self) {+ self.pointing = std::mem::take(&mut self.arrives_pointing);+ }++ /// The style a frame is drawn with: the session's own, with the+ /// pointer image standing in for the arrow while the cursor rests on+ /// a pressable control.+ pub(crate) fn shown_style(&self) -> CursorOverlayStyle {+ let mut shown = self.style.clone();+ if self.pointing+ && let Some(pointer) = self.style.pointer_image()+ {+ shown.set_image(Some(pointer.clone()));+ }+ shown+ }}/// Whether the overlay has faded out, and how long it has been quiet.diff --git a/crates/windows/src/system/cursor_overlay/render.rs b/crates/windows/src/system/cursor_overlay/render.rsindex 4dc87d6d5..156414c17 100644--- a/crates/windows/src/system/cursor_overlay/render.rs+++ b/crates/windows/src/system/cursor_overlay/render.rs@@ -7,7 +7,7 @@use agent_desktop_core::{CursorOverlayStyle, Point, Rect, place_label};use super::raster::{self, Surface, SurfaceMapping};-use super::{geometry, rounded};+use super::{cursor_image, geometry, rounded};/// Everything a frame needs, resolved from the control and the clock before/// any pixel is touched.@@ -37,6 +37,11 @@ pub(crate) struct Composed {pub(crate) fn compose(frame: &Frame<'_>) -> Composed {let scale = frame.style.size();+ let image = frame.style.image().and_then(|image| {+ let decoded = cursor_image::decoded(image)?;+ let rect = cursor_image::image_rect(&frame.tip, image, &decoded, scale);+ Some((decoded, rect))+ });let label_rect = frame.label.map(|_| place_label(&frame.tip, geometry::bubble_size(scale), &frame.screen));@@ -46,12 +51,15 @@ pub(crate) fn compose(frame: &Frame<'_>) -> Composed {.filter(|_| frame.style.highlight() && frame.highlight_opacity > 0.0);let highlight_rect = highlighted.map(|target| geometry::highlight_rect(target, scale));- let bounds = geometry::follower_rect(+ let mut bounds = geometry::follower_rect(&frame.tip,scale,label_rect.as_ref(),highlight_rect.as_ref(),);+ if let Some((_, rect)) = &image {+ bounds = geometry::union_of(&bounds, rect);+ }let mapping = SurfaceMapping {origin: Point {x: bounds.x.floor(),@@ -108,13 +116,16 @@ pub(crate) fn compose(frame: &Frame<'_>) -> Composed {}});- raster::draw_glyph(- &mut surface,- &mapping,- &frame.tip,- frame.style.fill_rgb(),- frame.style.rim_rgb(),- );+ match &image {+ Some((decoded, rect)) => cursor_image::draw_image(&mut surface, &mapping, rect, decoded),+ None => raster::draw_glyph(+ &mut surface,+ &mapping,+ &frame.tip,+ frame.style.fill_rgb(),+ frame.style.rim_rgb(),+ ),+ }Composed {origin: mapping.origin,diff --git a/crates/windows/src/system/cursor_overlay/surface_host.rs b/crates/windows/src/system/cursor_overlay/surface_host.rsindex e4d2147cc..95851906b 100644--- a/crates/windows/src/system/cursor_overlay/surface_host.rs+++ b/crates/windows/src/system/cursor_overlay/surface_host.rs@@ -23,7 +23,7 @@ use crate::system::cursor_overlay::{#[cfg(target_os = "windows")]use agent_desktop_core::{CURSOR_HIGHLIGHT_HOLD_MS, CURSOR_IDLE_REST_MS, CURSOR_REST_FADE_MS, CursorMotion,- CursorOverlayControl, CursorOverlayStyle, CursorPhase, Point, Rect,+ CursorOverlayControl, CursorPhase, Point, Rect,};#[cfg(target_os = "windows")]use std::time::{Duration, Instant};@@ -51,12 +51,7 @@ impl SurfaceHost {Ok(Self {window: OverlayWindow::create()?,session_id,- presentation: Presentation {- style: CursorOverlayStyle::default(),- pose,- label: None,- reveal: Reveal::Settled,- },+ presentation: Presentation::resting_at(pose),rest: RestState {resting: false,quiet_since: Instant::now(),@@ -90,10 +85,13 @@ impl SurfaceHost {self.clear();}CursorOverlayControl::Present { instruction, .. } => match instruction.phase() {- CursorPhase::Travel => self.travel(- instruction.destination().clone(),- instruction.target().cloned(),- ),+ CursorPhase::Travel => {+ self.presentation.depart(instruction.is_pointer());+ self.travel(+ instruction.destination().clone(),+ instruction.target().cloned(),+ );+ }CursorPhase::Drag => self.take_drag_origin(instruction.drag_from()@@ -148,6 +146,7 @@ impl SurfaceHost {/// shown before the acknowledgement because a drag is a pre-dispatch/// control that its caller blocks on.fn take_drag_origin(&mut self, origin: Point, target: Option<Rect>) {+ self.presentation.depart(false);self.travel(origin, target);}@@ -170,6 +169,7 @@ impl SurfaceHost {frames.wait();}self.presentation.pose = destination;+ self.presentation.arrive();self.draw(0.0, target.as_ref(), 0.0);self.begin_reveal();}@@ -241,9 +241,10 @@ impl SurfaceHost {width: 1920.0,height: 1080.0,});+ let shown = self.presentation.shown_style();let frame = render::Frame {tip: self.presentation.pose.clone(),- style: &self.presentation.style,+ style: &shown,ripple_phase,target: target.cloned(),highlight_opacity,@@ -343,7 +344,7 @@ impl SurfaceHost {) {return;}- let next = control.label().and_then(label::clamp);+ let next = self.presentation.label_from(control).and_then(label::clamp);if next != self.presentation.label {self.presentation.reveal = Reveal::for_label(next.as_deref());}diff --git a/skills/agent-desktop-windows/references/shell-and-overlay.md b/skills/agent-desktop-windows/references/shell-and-overlay.mdindex d84e00af1..9e2f64856 100644--- a/skills/agent-desktop-windows/references/shell-and-overlay.md+++ b/skills/agent-desktop-windows/references/shell-and-overlay.md@@ -114,8 +114,9 @@ agent-desktop cursor-overlay disable- **`--fill` and `--rim` also colour the label card** (its body and its text).A fill that matches the window behind it leaves the card nearly invisible.- **The card shows only when there is something to say.** `enable` without- `--label` greets once. After that, only an action that carries a description- draws the card. Each `enable` and each action replaces the card text.+ `--label` greets once, and with `--image` it does not greet. After that,+ only an action that carries a description draws the card. Each `enable` and+ each action replaces the card text.- **It fades out after 6 s with no instruction** and comes straight back on thenext command.- **It draws in physical pixels**, the space element bounds are reported in,diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.mdindex 327027351..50434d15c 100644--- a/skills/agent-desktop/references/commands-system.md+++ b/skills/agent-desktop/references/commands-system.md@@ -190,10 +190,13 @@ On macOS:- `--travel-ms MIN,MAX` needs `30 ≤ MIN ≤ MAX`. Travel max plus `--dwell-ms` must be at most 700 ms, or the command returns `INVALID_ARGS`.- Reduce Motion skips travel and dwell. Physical headed drags keep their own motion.-- `--image` and `--pointer-image` take a PNG of at most 2 MiB and 1024 pixels per side. Relative paths resolve at `enable`. `--fill` and `--rim` conflict with `--image`. A missing or invalid image falls back to the arrow.++On macOS and Windows:++- `--image` and `--pointer-image` take a PNG of at most 2 MiB and 1024 pixels per side, drawn at `--size` with the hotspot on the point the cursor targets. Relative paths resolve at `enable`. `--fill` and `--rim` conflict with `--image`. A missing or invalid image falls back to the arrow.- The pointer image shows on arrival at a pressable control. Text fields keep the arrow.-Windows accepts the motion and image settings but keeps its built-in motion and arrow.+Windows accepts the motion settings but keeps its built-in motion.Multi-agent cursors (macOS and Windows): start with `session start --cursor --multi-agent`, then pass the returned session id to every subagent.