adk_vision/screen/marks.rs
1//! Set-of-marks grounding: numbered candidates on one screenshot, and the target a chosen
2//! number resolves to (spec 3.7 ยง7.14).
3
4use serde::{Deserialize, Serialize};
5use serde_json::{Value, json};
6
7use super::fit::ScreenshotScale;
8use crate::digest::Digest;
9use crate::edit::{EditOp, Overlay, Rgba, apply_edit};
10use crate::error::{Result, VisionError};
11use crate::geometry::{BBox, ScreenSpace, Shape, TransformChain};
12use crate::media::DecodedImage;
13use crate::traits::Word;
14
15/// Where a candidate came from, and so how an action reaches it.
16#[non_exhaustive]
17#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
18#[serde(rename_all = "camelCase", tag = "kind")]
19pub enum CandidateSource {
20 /// An interactive element from `browser_elements`; a click on it is a `browser_click`
21 /// by its selector, with no coordinates.
22 BrowserElement {
23 /// The element's stable CSS selector.
24 selector: String,
25 /// Its ARIA role or tag.
26 #[serde(default, skip_serializing_if = "Option::is_none")]
27 role: Option<String>,
28 },
29 /// A word local OCR recognised on the screenshot.
30 OcrWord {
31 /// The reader's confidence.
32 #[serde(default, skip_serializing_if = "Option::is_none")]
33 confidence: Option<f32>,
34 },
35 /// A point a model gave, such as a coordinate from Claude's computer use toolset.
36 ModelPoint {
37 /// The backend that gave it.
38 backend: String,
39 },
40}
41
42/// One numbered candidate, its region in the screenshot's pixels.
43#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase")]
45pub struct Candidate {
46 /// The number drawn on it, from 1.
47 pub mark: u32,
48 /// Where it is, in screenshot pixels.
49 pub region: BBox,
50 /// Its text or accessible name.
51 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub label: Option<String>,
53 /// Where it came from.
54 pub source: CandidateSource,
55}
56
57/// One interactive element as `browser_elements` returns it: a rectangle in CSS pixels of
58/// the viewport and a selector that matches only it.
59#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
60#[serde(rename_all = "camelCase")]
61pub struct BrowserElement {
62 /// A CSS selector matching exactly this element.
63 pub selector: String,
64 /// Its ARIA role or tag.
65 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub role: Option<String>,
67 /// Its accessible name or text.
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub name: Option<String>,
70 /// Its rectangle in CSS pixels of the viewport.
71 pub rect: CssRect,
72}
73
74/// A rectangle in CSS pixels.
75#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
76pub struct CssRect {
77 /// Left edge.
78 pub x: f32,
79 /// Top edge.
80 pub y: f32,
81 /// Width.
82 pub width: f32,
83 /// Height.
84 pub height: f32,
85}
86
87/// The answer of `browser_elements`: the page's device pixel ratio and its elements.
88///
89/// # Example
90///
91/// ```
92/// use adk_vision::screen::BrowserElements;
93///
94/// let page: BrowserElements = serde_json::from_value(serde_json::json!({
95/// "devicePixelRatio": 2,
96/// "elements": [{ "selector": "#save", "role": "button", "name": "Save",
97/// "rect": { "x": 960, "y": 590, "width": 90, "height": 40 } }]
98/// })).unwrap();
99/// assert_eq!(page.elements[0].selector, "#save");
100/// ```
101#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase")]
103pub struct BrowserElements {
104 /// Screenshot pixels per CSS pixel.
105 pub device_pixel_ratio: f32,
106 /// The elements, in document order.
107 pub elements: Vec<BrowserElement>,
108}
109
110/// Numbered candidates on one screenshot: what `vision_annotate` draws and what a model
111/// names by number.
112///
113/// Every region is in the screenshot's pixels; [`ScreenSpace`] maps them to the logical
114/// points an action uses, so a target's click point is derived from a region of the
115/// screenshot whose digest the target records (V-I14).
116///
117/// # Example
118///
119/// ```
120/// use adk_vision::{BBox, Digest, ScreenSpace};
121/// use adk_vision::screen::{CandidateSource, MarkSet};
122///
123/// let mut marks = MarkSet::new(Digest::of(b"shot"), (3024, 1964), ScreenSpace::new("built-in", [0.0, 0.0], 2.0));
124/// let save = marks.push(
125/// BBox::new(1920.0, 1180.0, 2100.0, 1260.0),
126/// Some("Save".into()),
127/// CandidateSource::OcrWord { confidence: Some(0.98) },
128/// )
129/// .unwrap();
130/// let target = marks.ground(save).unwrap();
131/// assert_eq!(target.click, [1005.0, 610.0]);
132/// assert!(target.points.contains(target.click));
133/// ```
134#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
135#[serde(rename_all = "camelCase")]
136pub struct MarkSet {
137 /// The screenshot the candidates are on.
138 pub screenshot: Digest,
139 /// Its `[width, height]` in pixels.
140 pub size: [u32; 2],
141 /// Its display: origin in the global point space and device pixel ratio.
142 pub screen: ScreenSpace,
143 /// The window the screenshot shows, when known.
144 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub window: Option<String>,
146 /// The candidates, numbered from 1.
147 pub candidates: Vec<Candidate>,
148}
149
150/// Labels compare without case or surrounding whitespace.
151pub(crate) fn same_label(a: Option<&str>, b: Option<&str>) -> bool {
152 match (a, b) {
153 (Some(a), Some(b)) => a.trim().eq_ignore_ascii_case(b.trim()),
154 (None, None) => true,
155 _ => false,
156 }
157}
158
159impl MarkSet {
160 /// An empty set on the screenshot with `digest` and `size`, shown on `screen`.
161 pub fn new(screenshot: Digest, size: (u32, u32), screen: ScreenSpace) -> Self {
162 Self { screenshot, size: [size.0, size.1], screen, window: None, candidates: Vec::new() }
163 }
164
165 /// Names the window the screenshot shows.
166 #[must_use]
167 pub fn with_window(mut self, window: impl Into<String>) -> Self {
168 self.window = Some(window.into());
169 self
170 }
171
172 /// Adds a candidate, clamped to the screenshot, and returns its mark; an empty region
173 /// is skipped and returns `None`.
174 pub fn push(
175 &mut self,
176 region: BBox,
177 label: Option<String>,
178 source: CandidateSource,
179 ) -> Option<u32> {
180 let region = region.clamped(self.size[0], self.size[1]);
181 if region.is_empty() {
182 return None;
183 }
184 let mark = u32::try_from(self.candidates.len() + 1).unwrap_or(u32::MAX);
185 self.candidates.push(Candidate { mark, region, label, source });
186 Some(mark)
187 }
188
189 /// Adds the elements `browser_elements` returned, their CSS rectangles scaled by the
190 /// page's device pixel ratio into the screenshot's pixels; returns their marks.
191 pub fn add_browser_elements(&mut self, page: &BrowserElements) -> Vec<u32> {
192 let ratio = if page.device_pixel_ratio > 0.0 { page.device_pixel_ratio } else { 1.0 };
193 page.elements
194 .iter()
195 .filter_map(|element| {
196 let r = element.rect;
197 let region =
198 BBox::from_xywh(r.x * ratio, r.y * ratio, r.width * ratio, r.height * ratio);
199 self.push(
200 region,
201 element.name.clone(),
202 CandidateSource::BrowserElement {
203 selector: element.selector.clone(),
204 role: element.role.clone(),
205 },
206 )
207 })
208 .collect()
209 }
210
211 /// Adds the words a local reader recognised on this screenshot; words of another image
212 /// are skipped. Returns their marks.
213 pub fn add_words(&mut self, words: &[Word]) -> Vec<u32> {
214 let screenshot = self.screenshot;
215 words
216 .iter()
217 .filter(|word| word.region.image == screenshot)
218 .filter_map(|word| {
219 let region = word.region.shape.bbox()?;
220 self.push(
221 region,
222 Some(word.text.clone()),
223 CandidateSource::OcrWord { confidence: word.confidence },
224 )
225 })
226 .collect()
227 }
228
229 /// Adds a point a model gave in the pixels of the copy it received, mapped through
230 /// `scale` to this screenshot. The candidate is the smallest existing candidate that
231 /// contains the point, taking its label, or a box of eight points around the point.
232 /// Returns its mark.
233 pub fn add_model_point(
234 &mut self,
235 point: [f32; 2],
236 scale: &ScreenshotScale,
237 backend: &str,
238 ) -> Option<u32> {
239 let at = scale.to_source(point);
240 let containing = self
241 .candidates
242 .iter()
243 .filter(|c| c.region.contains(at))
244 .min_by(|a, b| a.region.area().total_cmp(&b.region.area()))
245 .map(|c| (c.region, c.label.clone()));
246 let (region, label) = containing.unwrap_or_else(|| {
247 let half = 4.0 * self.ratio();
248 (BBox::new(at[0] - half, at[1] - half, at[0] + half, at[1] + half), None)
249 });
250 self.push(region, label, CandidateSource::ModelPoint { backend: backend.to_string() })
251 }
252
253 fn ratio(&self) -> f32 {
254 if self.screen.device_pixel_ratio > 0.0 { self.screen.device_pixel_ratio } else { 1.0 }
255 }
256
257 /// The candidate with `mark`.
258 pub fn candidate(&self, mark: u32) -> Option<&Candidate> {
259 self.candidates.iter().find(|c| c.mark == mark)
260 }
261
262 /// The candidates whose label is `label`, ignoring case and surrounding whitespace.
263 pub fn by_label(&self, label: &str) -> Vec<&Candidate> {
264 self.candidates.iter().filter(|c| same_label(c.label.as_deref(), Some(label))).collect()
265 }
266
267 /// What `vision_annotate` draws: each candidate's outline and its numbered badge at its
268 /// top-left corner, sized by the device pixel ratio so they read the same in points.
269 pub fn overlays(&self) -> Vec<Overlay> {
270 let ratio = self.ratio();
271 let thickness = (2.0 * ratio).round().max(1.0) as u32;
272 self.candidates
273 .iter()
274 .flat_map(|c| {
275 [
276 Overlay::Box { bbox: c.region, color: Rgba::RED, thickness },
277 Overlay::Mark {
278 at: [c.region.x0, c.region.y0],
279 number: c.mark,
280 color: Rgba::RED,
281 scale: ratio,
282 },
283 ]
284 })
285 .collect()
286 }
287
288 /// The `vision_annotate` arguments that draw these marks: boxes in screenshot pixels,
289 /// each with its mark, at the screenshot's device pixel ratio.
290 pub fn annotate_args(&self) -> Value {
291 let boxes: Vec<Value> = self
292 .candidates
293 .iter()
294 .map(|c| {
295 json!({
296 "box": [c.region.x0, c.region.y0, c.region.x1, c.region.y1],
297 "label": c.label,
298 "mark": c.mark,
299 })
300 })
301 .collect();
302 json!({ "image": self.screenshot, "boxes": boxes, "devicePixelRatio": self.ratio() })
303 }
304
305 /// Draws the marks on the screenshot's pixels.
306 ///
307 /// # Errors
308 ///
309 /// [`VisionError::InvalidInput`] when `pixels` is not the screenshot's size.
310 pub fn annotate(&self, pixels: &DecodedImage) -> Result<DecodedImage> {
311 if pixels.size() != (self.size[0], self.size[1]) {
312 return Err(VisionError::InvalidInput(format!(
313 "the marks are for a {}x{} screenshot, not {}x{}",
314 self.size[0],
315 self.size[1],
316 pixels.width(),
317 pixels.height()
318 )));
319 }
320 let chain = TransformChain::new(self.size[0], self.size[1]);
321 apply_edit(pixels, &chain, &EditOp::Annotate { overlays: self.overlays() })
322 }
323
324 /// The target `mark` names: its region in pixels and points and its click point.
325 ///
326 /// # Errors
327 ///
328 /// [`VisionError::InvalidInput`] naming the marks there are when `mark` is not one.
329 pub fn ground(&self, mark: u32) -> Result<GroundedTarget> {
330 let candidate = self.candidate(mark).ok_or_else(|| {
331 VisionError::InvalidInput(format!(
332 "mark {mark} is not on this screenshot; its marks are 1 to {}",
333 self.candidates.len()
334 ))
335 })?;
336 Ok(self.target_of(candidate))
337 }
338
339 pub(crate) fn target_of(&self, candidate: &Candidate) -> GroundedTarget {
340 let points = self.screen.bbox_to_points(&candidate.region);
341 GroundedTarget {
342 mark: candidate.mark,
343 screenshot: self.screenshot,
344 screenshot_size: self.size,
345 screen: self.screen.clone(),
346 window: self.window.clone(),
347 pixels: candidate.region,
348 points,
349 click: self.screen.to_points(candidate.region.center()),
350 label: candidate.label.clone(),
351 source: candidate.source.clone(),
352 }
353 }
354}
355
356/// A chosen mark resolved for an action: the region in screenshot pixels and logical
357/// points, the click point in points, and the screenshot it came from.
358#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
359#[serde(rename_all = "camelCase")]
360pub struct GroundedTarget {
361 /// The mark chosen.
362 pub mark: u32,
363 /// The screenshot's digest, which the action records (V-I14).
364 pub screenshot: Digest,
365 /// The screenshot's `[width, height]` in pixels.
366 pub screenshot_size: [u32; 2],
367 /// The display the screenshot shows.
368 pub screen: ScreenSpace,
369 /// The window, when known.
370 #[serde(default, skip_serializing_if = "Option::is_none")]
371 pub window: Option<String>,
372 /// The region in screenshot pixels.
373 pub pixels: BBox,
374 /// The region in logical points.
375 pub points: BBox,
376 /// The click point, the region's centre, in logical points.
377 pub click: [f32; 2],
378 /// The candidate's label.
379 #[serde(default, skip_serializing_if = "Option::is_none")]
380 pub label: Option<String>,
381 /// Where the candidate came from.
382 pub source: CandidateSource,
383}
384
385impl GroundedTarget {
386 /// The click point in screenshot pixels.
387 pub fn click_pixel(&self) -> [f32; 2] {
388 self.screen.to_pixels(self.click)
389 }
390
391 /// `browser_click` arguments for a browser element: its selector, no coordinates.
392 /// `None` for a desktop candidate.
393 ///
394 /// # Example
395 ///
396 /// ```
397 /// use adk_vision::{Digest, ScreenSpace};
398 /// use adk_vision::screen::{BrowserElements, MarkSet};
399 ///
400 /// let page: BrowserElements = serde_json::from_value(serde_json::json!({
401 /// "devicePixelRatio": 2,
402 /// "elements": [{ "selector": "#save", "name": "Save",
403 /// "rect": { "x": 960, "y": 590, "width": 90, "height": 40 } }]
404 /// })).unwrap();
405 /// let mut marks = MarkSet::new(Digest::of(b"page"), (3024, 1964), ScreenSpace::new("viewport", [0.0, 0.0], 2.0));
406 /// let mark = marks.add_browser_elements(&page)[0];
407 /// let target = marks.ground(mark).unwrap();
408 /// assert_eq!(target.browser_click_args().unwrap(), serde_json::json!({ "selector": "#save" }));
409 /// ```
410 pub fn browser_click_args(&self) -> Option<Value> {
411 match &self.source {
412 CandidateSource::BrowserElement { selector, .. } => {
413 Some(json!({ "selector": selector }))
414 }
415 CandidateSource::OcrWord { .. } | CandidateSource::ModelPoint { .. } => None,
416 }
417 }
418
419 /// The click point as a whole pixel of the copy a model received under `scale`, for a
420 /// `computer.left_click` on a fitted screenshot.
421 pub fn toolset_coordinate(&self, scale: &ScreenshotScale) -> [i64; 2] {
422 let sent = scale.to_sent(self.click_pixel());
423 let clamp = |v: f32, max: u32| (v.floor() as i64).clamp(0, i64::from(max) - 1);
424 [clamp(sent[0], scale.sent[0]), clamp(sent[1], scale.sent[1])]
425 }
426
427 /// The target as a region of its screenshot, for evidence and the annotated viewer.
428 pub fn shape(&self) -> Shape {
429 Shape::Box(self.pixels)
430 }
431
432 /// `adk-computer-use` target evidence for this target: bounds in logical points at the
433 /// screenshot's device pixel ratio and the screenshot's digest (spec 3.7 V-I14).
434 ///
435 /// # Example
436 ///
437 /// ```
438 /// use adk_vision::{BBox, Digest, ScreenSpace};
439 /// use adk_vision::screen::{CandidateSource, MarkSet};
440 ///
441 /// let mut marks = MarkSet::new(Digest::of(b"shot"), (3024, 1964), ScreenSpace::new("built-in", [0.0, 0.0], 2.0));
442 /// let mark = marks
443 /// .push(BBox::new(1920.0, 1180.0, 2100.0, 1260.0), Some("Save".into()), CandidateSource::OcrWord { confidence: None })
444 /// .unwrap();
445 /// let evidence = marks.ground(mark).unwrap().target_evidence(
446 /// "darwin", "com.example.form", "observation-1", "2026-11-22T10:00:00Z",
447 /// );
448 /// let bounds = evidence.bounds.as_ref().unwrap();
449 /// assert_eq!((bounds.x, bounds.y, bounds.width, bounds.height), (960.0, 590.0, 90.0, 40.0));
450 /// assert!(evidence.check_screen_binding().is_ok());
451 /// ```
452 #[cfg(feature = "computer-use")]
453 pub fn target_evidence(
454 &self,
455 platform: &str,
456 app_id: &str,
457 observation_id: &str,
458 captured_at: &str,
459 ) -> adk_computer_use::TargetEvidence {
460 let ratio = f64::from(self.screen.device_pixel_ratio);
461 let p = &self.points;
462 adk_computer_use::TargetEvidence {
463 platform: platform.to_string(),
464 app_id: app_id.to_string(),
465 pid: None,
466 window_id: self.window.clone().map(Value::String),
467 window_title_digest: None,
468 display_id: Some(self.screen.display.clone()),
469 role: match &self.source {
470 CandidateSource::BrowserElement { role, .. } => role.clone(),
471 CandidateSource::OcrWord { .. } | CandidateSource::ModelPoint { .. } => None,
472 },
473 label_digest: self
474 .label
475 .as_deref()
476 .map(|label| Digest::of(label.as_bytes()).to_string()),
477 bounds: Some(adk_computer_use::Bounds::points(
478 f64::from(p.x0),
479 f64::from(p.y0),
480 f64::from(p.width()),
481 f64::from(p.height()),
482 ratio,
483 )),
484 observation_id: observation_id.to_string(),
485 screenshot_hash: Some(self.screenshot.to_string()),
486 device_pixel_ratio: Some(ratio),
487 ui_tree_revision: None,
488 confidence: match &self.source {
489 CandidateSource::OcrWord { confidence: Some(c) } => f64::from(*c),
490 CandidateSource::BrowserElement { .. }
491 | CandidateSource::OcrWord { confidence: None }
492 | CandidateSource::ModelPoint { .. } => 1.0,
493 },
494 captured_at: captured_at.to_string(),
495 }
496 }
497}