Skip to main content

adk_vision/screen/
fit.rs

1//! Screenshots resized to a model's image limits before they are sent, with the scale kept.
2//!
3//! Claude's computer use toolset takes no display size and the API does not downscale a
4//! screenshot for it: an oversized image is refused. Claude then answers in pixels of the
5//! image it received, so the caller resizes first and maps every coordinate back through
6//! the scale it used.
7
8use std::sync::{Arc, Mutex};
9
10use adk_core::{
11    ActuationOutput, ComputerAction, ComputerActionKind, ComputerActuator, ScreenPoint, Screenshot,
12};
13use async_trait::async_trait;
14use serde::{Deserialize, Serialize};
15
16use crate::edit::ops;
17use crate::error::{Result, VisionError};
18use crate::geometry::{BBox, Transform, TransformChain};
19use crate::media::{DecodeLimits, SourceImage};
20
21/// Claude counts one visual token per 28 × 28 patch and pads each side to a multiple of 28.
22const PATCH: u32 = 28;
23
24/// The image limits of a model that reads screenshots: the longest side and the visual
25/// tokens of `⌈w/28⌉ × ⌈h/28⌉`, each side padded up to a multiple of 28.
26///
27/// # Example
28///
29/// ```
30/// use adk_vision::screen::ScreenshotLimits;
31///
32/// let limits = ScreenshotLimits::for_claude_model("claude-sonnet-5-5");
33/// assert_eq!(limits, ScreenshotLimits::CLAUDE_HIGH);
34/// // A 3024×1964 screenshot of a DPR-2 display is resized to 2380×1546.
35/// assert_eq!(limits.fitted_size((3024, 1964)), (2380, 1546));
36/// // The documented standard-tier examples.
37/// assert_eq!(ScreenshotLimits::CLAUDE_STANDARD.fitted_size((1920, 1080)), (1456, 819));
38/// assert_eq!(ScreenshotLimits::CLAUDE_STANDARD.fitted_size((1075, 1520)), (924, 1307));
39/// ```
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase")]
42pub struct ScreenshotLimits {
43    /// The longest side, after padding to a multiple of 28.
44    pub max_edge: u32,
45    /// The visual tokens.
46    pub max_tokens: u32,
47}
48
49impl ScreenshotLimits {
50    /// Claude Opus 4.7 and later, Sonnet 5 and later, Haiku 5.5, Fable and Mythos — every
51    /// model that takes `computer_toolset_20260801`: 2,576 px and 4,784 visual tokens.
52    pub const CLAUDE_HIGH: Self = Self { max_edge: 2576, max_tokens: 4784 };
53    /// Earlier Claude models: 1,568 px and 1,568 visual tokens.
54    pub const CLAUDE_STANDARD: Self = Self { max_edge: 1568, max_tokens: 1568 };
55
56    /// The limits of a Claude model ID, first-party, Bedrock or Vertex.
57    pub fn for_claude_model(model: &str) -> Self {
58        if claude_high_tier(model) { Self::CLAUDE_HIGH } else { Self::CLAUDE_STANDARD }
59    }
60
61    /// The visual tokens an image of `size` costs.
62    pub fn tokens(size: (u32, u32)) -> u64 {
63        u64::from(size.0.div_ceil(PATCH)) * u64::from(size.1.div_ceil(PATCH))
64    }
65
66    /// Whether an image of `size` is taken as it is.
67    pub fn fits(&self, size: (u32, u32)) -> bool {
68        let padded = |side: u32| u64::from(side.div_ceil(PATCH)) * u64::from(PATCH);
69        padded(size.0) <= u64::from(self.max_edge)
70            && padded(size.1) <= u64::from(self.max_edge)
71            && Self::tokens(size) <= u64::from(self.max_tokens)
72    }
73
74    /// The largest aspect-preserving size within the limits, as the provider computes it:
75    /// a binary search along the long edge. An image that fits is returned unchanged.
76    pub fn fitted_size(&self, size: (u32, u32)) -> (u32, u32) {
77        let (width, height) = (size.0.max(1), size.1.max(1));
78        if self.fits((width, height)) {
79            return (width, height);
80        }
81        if height > width {
82            let (h, w) = self.fitted_size((height, width));
83            return (w, h);
84        }
85        let aspect = f64::from(width) / f64::from(height);
86        let short = |long: u32| ((f64::from(long) / aspect).round_ties_even() as u32).max(1);
87        // `lo` always fits and `hi` never does.
88        let (mut lo, mut hi) = (1u32, width);
89        while lo + 1 < hi {
90            let mid = lo + (hi - lo) / 2;
91            if self.fits((mid, short(mid))) {
92                lo = mid;
93            } else {
94                hi = mid;
95            }
96        }
97        (lo, short(lo))
98    }
99}
100
101/// Whether a Claude model ID is on the high-resolution image tier.
102pub(crate) fn claude_high_tier(model: &str) -> bool {
103    let id = model.to_ascii_lowercase();
104    let Some(start) = id.find("claude-") else {
105        return false;
106    };
107    let rest = &id[start + "claude-".len()..];
108    let mut parts = rest.split(['-', '@', '.', ':']);
109    let family = parts.next().unwrap_or_default();
110    let major: u32 = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
111    let minor: u32 = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
112    match family {
113        "fable" | "mythos" => true,
114        "opus" => major > 4 || (major == 4 && minor >= 7),
115        "sonnet" => major >= 5,
116        "haiku" => major > 5 || (major == 5 && minor >= 5),
117        _ => false,
118    }
119}
120
121/// The scale between a screenshot and the copy a model saw: coordinates the model gives
122/// are in `sent` pixels and map back to `source` pixels through it.
123///
124/// # Example
125///
126/// ```
127/// use adk_vision::BBox;
128/// use adk_vision::screen::ScreenshotScale;
129///
130/// let scale = ScreenshotScale::new((3024, 1964), (2380, 1546));
131/// let save = scale.bbox_to_source(&BBox::new(1511.1, 928.9, 1652.8, 991.8));
132/// assert!((save.x0 - 1920.0).abs() < 0.5 && (save.y1 - 1260.0).abs() < 0.5);
133/// // Claude's zoom region, in the sent screenshot's pixels, in source pixels.
134/// assert_eq!(scale.region_to_source([0, 0, 2380, 1546]), [0, 0, 3024, 1964]);
135/// ```
136#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase")]
138pub struct ScreenshotScale {
139    /// The screenshot as captured, `[width, height]`.
140    pub source: [u32; 2],
141    /// The image the model received, `[width, height]`.
142    pub sent: [u32; 2],
143}
144
145impl ScreenshotScale {
146    /// The scale from a `source` screenshot to the `sent` copy.
147    pub fn new(source: (u32, u32), sent: (u32, u32)) -> Self {
148        Self { source: [source.0.max(1), source.1.max(1)], sent: [sent.0.max(1), sent.1.max(1)] }
149    }
150
151    /// No resize.
152    pub fn identity(size: (u32, u32)) -> Self {
153        Self::new(size, size)
154    }
155
156    /// The scale a screenshot of `size` gets under `limits`.
157    pub fn fitted(size: (u32, u32), limits: &ScreenshotLimits) -> Self {
158        Self::new(size, limits.fitted_size(size))
159    }
160
161    /// Whether the model saw the screenshot unresized.
162    pub fn is_identity(&self) -> bool {
163        self.source == self.sent
164    }
165
166    fn factors(&self) -> (f64, f64) {
167        (
168            f64::from(self.source[0]) / f64::from(self.sent[0]),
169            f64::from(self.source[1]) / f64::from(self.sent[1]),
170        )
171    }
172
173    /// Maps a point in sent pixels to source pixels.
174    pub fn to_source(&self, point: [f32; 2]) -> [f32; 2] {
175        let (fx, fy) = self.factors();
176        [(f64::from(point[0]) * fx) as f32, (f64::from(point[1]) * fy) as f32]
177    }
178
179    /// Maps a point in source pixels to sent pixels.
180    pub fn to_sent(&self, point: [f32; 2]) -> [f32; 2] {
181        let (fx, fy) = self.factors();
182        [(f64::from(point[0]) / fx) as f32, (f64::from(point[1]) / fy) as f32]
183    }
184
185    /// Maps a box in sent pixels to source pixels.
186    pub fn bbox_to_source(&self, bbox: &BBox) -> BBox {
187        let a = self.to_source([bbox.x0, bbox.y0]);
188        let b = self.to_source([bbox.x1, bbox.y1]);
189        BBox::new(a[0], a[1], b[0], b[1])
190    }
191
192    /// Maps a whole-pixel point the model gave to the source pixel under its centre,
193    /// clamped to the screenshot.
194    pub fn point_to_source(&self, point: ScreenPoint) -> ScreenPoint {
195        let (fx, fy) = self.factors();
196        let map = |v: i64, f: f64, max: u32| {
197            (((v as f64 + 0.5) * f).floor() as i64).clamp(0, i64::from(max) - 1)
198        };
199        ScreenPoint::new(map(point.x, fx, self.source[0]), map(point.y, fy, self.source[1]))
200    }
201
202    /// Maps a source pixel to the whole sent pixel that covers its centre.
203    pub fn point_to_sent(&self, point: ScreenPoint) -> ScreenPoint {
204        let (fx, fy) = self.factors();
205        let map = |v: i64, f: f64, max: u32| {
206            (((v as f64 + 0.5) / f).floor() as i64).clamp(0, i64::from(max) - 1)
207        };
208        ScreenPoint::new(map(point.x, fx, self.sent[0]), map(point.y, fy, self.sent[1]))
209    }
210
211    /// Maps a `zoom` region `[x0, y0, x1, y1]` in sent pixels to source pixels, rounded
212    /// outwards so the whole region is captured.
213    pub fn region_to_source(&self, region: [i64; 4]) -> [i64; 4] {
214        let (fx, fy) = self.factors();
215        let [x0, y0, x1, y1] = region;
216        let w = i64::from(self.source[0]);
217        let h = i64::from(self.source[1]);
218        [
219            ((x0 as f64 * fx).floor() as i64).clamp(0, w),
220            ((y0 as f64 * fy).floor() as i64).clamp(0, h),
221            ((x1 as f64 * fx).ceil() as i64).clamp(0, w),
222            ((y1 as f64 * fy).ceil() as i64).clamp(0, h),
223        ]
224    }
225
226    /// The transform chain from the source screenshot to the sent copy, for a
227    /// [`RegionNormalizer`](crate::RegionNormalizer) or a region's origin.
228    ///
229    /// # Errors
230    ///
231    /// Never for a scale built by this type's constructors.
232    pub fn chain(&self) -> Result<TransformChain> {
233        let chain = TransformChain::new(self.source[0], self.source[1]);
234        if self.is_identity() {
235            return Ok(chain);
236        }
237        chain.then(Transform::Resize { width: self.sent[0], height: self.sent[1] })
238    }
239}
240
241/// Resizes a screenshot to `limits` when it is larger, returning the PNG to send and the
242/// scale to map the model's coordinates back with.
243///
244/// # Errors
245///
246/// Returns [`VisionError::InvalidInput`] when the bytes are not a PNG, JPEG or WebP image
247/// within the decode limits.
248///
249/// # Example
250///
251/// ```
252/// use adk_vision::DecodedImage;
253/// use adk_vision::screen::{ScreenshotLimits, fit_screenshot};
254///
255/// let shot = DecodedImage::filled(3024, 1964, [236, 236, 236, 255]).encode_png().unwrap();
256/// let (sent, scale) = fit_screenshot(&shot, &ScreenshotLimits::CLAUDE_HIGH).unwrap();
257/// assert_eq!(scale.sent, [2380, 1546]);
258/// assert!(sent.len() < shot.len() * 2);
259/// ```
260pub fn fit_screenshot(
261    bytes: &[u8],
262    limits: &ScreenshotLimits,
263) -> Result<(Vec<u8>, ScreenshotScale)> {
264    let image = SourceImage::decode(bytes, &DecodeLimits::default())?;
265    let size = image.size();
266    let scale = ScreenshotScale::fitted(size, limits);
267    if scale.is_identity() {
268        return Ok((bytes.to_vec(), scale));
269    }
270    let resized = ops::resize(image.pixels(), scale.sent[0], scale.sent[1]);
271    Ok((resized.encode_png()?, scale))
272}
273
274fn image_output(png: Vec<u8>) -> Result<ActuationOutput> {
275    let shot = Screenshot::png(png)
276        .ok_or_else(|| VisionError::InvalidInput("the resized screenshot is not a PNG".into()))?;
277    Ok(ActuationOutput::Image(shot))
278}
279
280/// A [`ComputerActuator`] whose screenshots fit a model's image limits: each screenshot is
281/// resized before it is returned, the scale is recorded, and every coordinate the model
282/// gives — clicks, drags, scrolls, moves and `zoom` regions — is mapped back to the inner
283/// actuator's pixels through it.
284///
285/// `zoom` is always offered: when the inner actuator has no zoom, the region is cropped
286/// from a fresh full-resolution screenshot. A zoom image is downscaled to fit within the
287/// sent screenshot's size when it is larger, keeping its aspect ratio.
288///
289/// # Example
290///
291/// ```
292/// use std::sync::Arc;
293/// use adk_core::{ActuationOutput, ComputerAction, ComputerActuator, Result, Screenshot};
294/// use adk_vision::DecodedImage;
295/// use adk_vision::screen::FittedActuator;
296///
297/// struct Retina;
298///
299/// #[async_trait::async_trait]
300/// impl ComputerActuator for Retina {
301///     fn display_size(&self) -> Option<(u32, u32)> {
302///         Some((3024, 1964))
303///     }
304///     async fn perform(&self, _action: ComputerAction) -> Result<ActuationOutput> {
305///         let png = DecodedImage::filled(3024, 1964, [0, 0, 0, 255]).encode_png().unwrap();
306///         Ok(ActuationOutput::Image(Screenshot::png(png).unwrap()))
307///     }
308/// }
309///
310/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
311/// let fitted = FittedActuator::for_claude_model(Arc::new(Retina), "claude-sonnet-5-5");
312/// let ActuationOutput::Image(shot) = fitted.perform(ComputerAction::Screenshot).await.unwrap()
313/// else { unreachable!() };
314/// assert_eq!((shot.width, shot.height), (2380, 1546));
315/// assert_eq!(fitted.scale().unwrap().source, [3024, 1964]);
316/// # });
317/// ```
318pub struct FittedActuator {
319    inner: Arc<dyn ComputerActuator>,
320    limits: ScreenshotLimits,
321    last: Mutex<Option<ScreenshotScale>>,
322}
323
324impl FittedActuator {
325    /// Fits `inner`'s screenshots to `limits`.
326    pub fn new(inner: Arc<dyn ComputerActuator>, limits: ScreenshotLimits) -> Self {
327        Self { inner, limits, last: Mutex::new(None) }
328    }
329
330    /// Fits `inner`'s screenshots to a Claude model's limits.
331    pub fn for_claude_model(inner: Arc<dyn ComputerActuator>, model: &str) -> Self {
332        Self::new(inner, ScreenshotLimits::for_claude_model(model))
333    }
334
335    /// The scale of the last screenshot returned, or of the inner display before any.
336    pub fn scale(&self) -> Option<ScreenshotScale> {
337        let last = *self.last.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
338        last.or_else(|| {
339            self.inner.display_size().map(|size| ScreenshotScale::fitted(size, &self.limits))
340        })
341    }
342
343    fn record(&self, scale: ScreenshotScale) {
344        *self.last.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(scale);
345    }
346
347    fn up(&self, point: ScreenPoint) -> ScreenPoint {
348        self.scale().map_or(point, |scale| scale.point_to_source(point))
349    }
350
351    async fn inner_image(&self, action: ComputerAction) -> Result<Vec<u8>> {
352        match self.inner.perform(action).await? {
353            ActuationOutput::Image(shot) => Ok(shot.data),
354            other => Err(VisionError::Backend {
355                backend: "screen".into(),
356                message: format!("the actuator answered an image request with {other:?}"),
357            }),
358        }
359    }
360
361    async fn screenshot(&self) -> Result<ActuationOutput> {
362        let png = self.inner_image(ComputerAction::Screenshot).await?;
363        let (sent, scale) = fit_screenshot(&png, &self.limits)?;
364        self.record(scale);
365        image_output(sent)
366    }
367
368    async fn zoom(&self, region: [i64; 4]) -> Result<ActuationOutput> {
369        let scale = self.scale().ok_or_else(|| {
370            VisionError::InvalidInput("zoom needs a screenshot first, to know its scale".into())
371        })?;
372        let [x0, y0, x1, y1] = scale.region_to_source(region);
373        if x1 <= x0 || y1 <= y0 {
374            return Err(VisionError::InvalidInput(format!(
375                "zoom region {region:?} has no pixels on the {}x{} screenshot",
376                scale.sent[0], scale.sent[1]
377            )));
378        }
379        let crop = if self.inner.supports(ComputerActionKind::Zoom) {
380            let png = self.inner_image(ComputerAction::Zoom { region: [x0, y0, x1, y1] }).await?;
381            SourceImage::decode(&png, &DecodeLimits::default())?.pixels().clone()
382        } else {
383            let png = self.inner_image(ComputerAction::Screenshot).await?;
384            let full = SourceImage::decode(&png, &DecodeLimits::default())?;
385            let (w, h) = full.size();
386            let to_u32 = |v: i64, max: u32| u32::try_from(v.max(0)).unwrap_or(max).min(max);
387            let (cx0, cy0) = (to_u32(x0, w), to_u32(y0, h));
388            let (cx1, cy1) = (to_u32(x1, w), to_u32(y1, h));
389            if cx1 <= cx0 || cy1 <= cy0 {
390                return Err(VisionError::InvalidInput(format!(
391                    "zoom region {region:?} lies outside the {w}x{h} screen"
392                )));
393            }
394            ops::crop(full.pixels(), cx0, cy0, cx1 - cx0, cy1 - cy0)
395        };
396        let (cw, ch) = crop.size();
397        let fit = f64::from(scale.sent[0]) / f64::from(cw);
398        let fit = fit.min(f64::from(scale.sent[1]) / f64::from(ch)).min(1.0);
399        let mut size = (
400            ((f64::from(cw) * fit).round() as u32).max(1),
401            ((f64::from(ch) * fit).round() as u32).max(1),
402        );
403        size = self.limits.fitted_size(size);
404        let out = if size == (cw, ch) { crop } else { ops::resize(&crop, size.0, size.1) };
405        image_output(out.encode_png()?)
406    }
407}
408
409#[async_trait]
410impl ComputerActuator for FittedActuator {
411    fn display_size(&self) -> Option<(u32, u32)> {
412        self.inner.display_size().map(|size| self.limits.fitted_size(size))
413    }
414
415    fn supports(&self, kind: ComputerActionKind) -> bool {
416        kind == ComputerActionKind::Zoom
417            || (kind == ComputerActionKind::Screenshot)
418            || self.inner.supports(kind)
419    }
420
421    async fn perform(&self, action: ComputerAction) -> adk_core::Result<ActuationOutput> {
422        let mapped = match action {
423            ComputerAction::Screenshot => return Ok(self.screenshot().await?),
424            ComputerAction::Zoom { region } => return Ok(self.zoom(region).await?),
425            ComputerAction::Click { button, count, at, modifiers } => {
426                ComputerAction::Click { button, count, at: at.map(|p| self.up(p)), modifiers }
427            }
428            ComputerAction::Drag { from, to, modifiers } => {
429                ComputerAction::Drag { from: self.up(from), to: self.up(to), modifiers }
430            }
431            ComputerAction::MoveTo { at } => ComputerAction::MoveTo { at: self.up(at) },
432            ComputerAction::Scroll { at, direction, amount, modifiers } => {
433                ComputerAction::Scroll { at: at.map(|p| self.up(p)), direction, amount, modifiers }
434            }
435            other => other,
436        };
437        let output = self.inner.perform(mapped).await?;
438        Ok(match output {
439            ActuationOutput::Cursor(point) => ActuationOutput::Cursor(
440                self.scale().map_or(point, |scale| scale.point_to_sent(point)),
441            ),
442            other => other,
443        })
444    }
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    #[test]
452    fn documented_sizes_match_the_reference() {
453        let standard = ScreenshotLimits::CLAUDE_STANDARD;
454        assert_eq!(standard.fitted_size((1920, 1080)), (1456, 819));
455        assert_eq!(standard.fitted_size((1075, 1520)), (924, 1307));
456        assert_eq!(standard.fitted_size((3024, 1964)), (1372, 891));
457        // High tier: the same scan is taken unresized.
458        assert_eq!(ScreenshotLimits::CLAUDE_HIGH.fitted_size((1075, 1520)), (1075, 1520));
459    }
460
461    #[test]
462    fn fitted_sizes_stay_within_both_limits() {
463        for limits in [ScreenshotLimits::CLAUDE_HIGH, ScreenshotLimits::CLAUDE_STANDARD] {
464            for size in [(3024, 1964), (5120, 2880), (8000, 1000), (1000, 8000), (2576, 2576)] {
465                let fitted = limits.fitted_size(size);
466                assert!(limits.fits(fitted), "{size:?} -> {fitted:?}");
467                // One more pixel on the long edge no longer fits.
468                if fitted != size {
469                    let grown = (fitted.0 + 28, fitted.1 + 28);
470                    assert!(!limits.fits(grown), "{size:?}: {grown:?} also fits");
471                }
472            }
473        }
474    }
475
476    #[test]
477    fn tiers_follow_the_model() {
478        for high in ["claude-sonnet-5-5", "claude-opus-5-5", "claude-fable-5-2", "claude-haiku-5-5"]
479        {
480            assert!(claude_high_tier(high), "{high}");
481        }
482        for standard in ["claude-sonnet-4-6", "claude-haiku-4-5", "gpt-5"] {
483            assert!(!claude_high_tier(standard), "{standard}");
484        }
485    }
486
487    #[test]
488    fn points_round_trip_within_a_pixel() {
489        let scale = ScreenshotScale::new((3024, 1964), (2380, 1546));
490        for (x, y) in [(0, 0), (1, 1), (1189, 772), (2379, 1545)] {
491            let source = scale.point_to_source(ScreenPoint::new(x, y));
492            let back = scale.point_to_sent(source);
493            assert_eq!((back.x, back.y), (x, y));
494        }
495    }
496}