1use 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
21const PATCH: u32 = 28;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase")]
42pub struct ScreenshotLimits {
43 pub max_edge: u32,
45 pub max_tokens: u32,
47}
48
49impl ScreenshotLimits {
50 pub const CLAUDE_HIGH: Self = Self { max_edge: 2576, max_tokens: 4784 };
53 pub const CLAUDE_STANDARD: Self = Self { max_edge: 1568, max_tokens: 1568 };
55
56 pub fn for_claude_model(model: &str) -> Self {
58 if claude_high_tier(model) { Self::CLAUDE_HIGH } else { Self::CLAUDE_STANDARD }
59 }
60
61 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 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 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 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
101pub(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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase")]
138pub struct ScreenshotScale {
139 pub source: [u32; 2],
141 pub sent: [u32; 2],
143}
144
145impl ScreenshotScale {
146 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 pub fn identity(size: (u32, u32)) -> Self {
153 Self::new(size, size)
154 }
155
156 pub fn fitted(size: (u32, u32), limits: &ScreenshotLimits) -> Self {
158 Self::new(size, limits.fitted_size(size))
159 }
160
161 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 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 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 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 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 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 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 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
241pub 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
280pub struct FittedActuator {
319 inner: Arc<dyn ComputerActuator>,
320 limits: ScreenshotLimits,
321 last: Mutex<Option<ScreenshotScale>>,
322}
323
324impl FittedActuator {
325 pub fn new(inner: Arc<dyn ComputerActuator>, limits: ScreenshotLimits) -> Self {
327 Self { inner, limits, last: Mutex::new(None) }
328 }
329
330 pub fn for_claude_model(inner: Arc<dyn ComputerActuator>, model: &str) -> Self {
332 Self::new(inner, ScreenshotLimits::for_claude_model(model))
333 }
334
335 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 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 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}