Skip to main content

adk_vision/screen/
plan.rs

1//! Previewed screen plans: up to N actions in one window, approved once, each action
2//! grounded again and checked against its previewed target before it runs (spec 3.7 Q8,
3//! S14).
4
5use std::fmt;
6
7use serde::{Deserialize, Serialize};
8use serde_json::{Value, json};
9
10use super::fit::ScreenshotScale;
11use super::marks::{GroundedTarget, MarkSet, same_label};
12use crate::digest::Digest;
13use crate::geometry::BBox;
14
15/// What an approved action expects to hit: the previewed target's label, region and click
16/// point in logical points, its window and the screenshot it was grounded on.
17///
18/// # Example
19///
20/// ```
21/// use adk_vision::{BBox, Digest, ScreenSpace};
22/// use adk_vision::screen::{CandidateSource, MarkSet, PreviewedTarget};
23///
24/// let screen = ScreenSpace::new("built-in", [0.0, 0.0], 2.0);
25/// let ocr = CandidateSource::OcrWord { confidence: None };
26/// let mut before = MarkSet::new(Digest::of(b"before"), (3024, 1964), screen.clone());
27/// let save = before.push(BBox::new(1920.0, 1180.0, 2100.0, 1260.0), Some("Save".into()), ocr.clone()).unwrap();
28/// let preview = PreviewedTarget::from(&before.ground(save).unwrap());
29///
30/// // A fresh screenshot with two "Save" buttons: the one under the previewed point is chosen.
31/// let mut after = MarkSet::new(Digest::of(b"after"), (3024, 1964), screen);
32/// after.push(BBox::new(40.0, 120.0, 220.0, 200.0), Some("Save".into()), ocr.clone());
33/// after.push(BBox::new(1920.0, 1180.0, 2100.0, 1260.0), Some("Save".into()), ocr);
34/// assert_eq!(preview.reground(&after).unwrap().mark, 2);
35/// assert!(preview.check(&after, 1).is_err());
36/// ```
37#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
38#[serde(rename_all = "camelCase")]
39pub struct PreviewedTarget {
40    /// The screenshot the preview was grounded on.
41    pub screenshot: Digest,
42    /// The window, when known.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub window: Option<String>,
45    /// The target's label.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub label: Option<String>,
48    /// Its region in logical points.
49    pub points: BBox,
50    /// The click point in logical points.
51    pub click: [f32; 2],
52}
53
54impl From<&GroundedTarget> for PreviewedTarget {
55    fn from(target: &GroundedTarget) -> Self {
56        Self {
57            screenshot: target.screenshot,
58            window: target.window.clone(),
59            label: target.label.clone(),
60            points: target.points,
61            click: target.click,
62        }
63    }
64}
65
66/// Why an action no longer matches its preview; the action is held again.
67#[non_exhaustive]
68#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
69#[serde(rename_all = "camelCase", tag = "kind")]
70pub enum Deviation {
71    /// The fresh screenshot shows another window than the plan's.
72    Window {
73        /// The plan's window.
74        expected: Option<String>,
75        /// The window now.
76        found: Option<String>,
77    },
78    /// No candidate with the previewed label covers the previewed click point.
79    Missing {
80        /// The previewed label.
81        label: Option<String>,
82    },
83    /// The candidate about to be acted on is not the previewed target.
84    WrongTarget {
85        /// The previewed region, in points.
86        expected: BBox,
87        /// The candidate's region, in points.
88        found: BBox,
89        /// The candidate's label.
90        label: Option<String>,
91    },
92    /// The call's arguments differ from the previewed ones.
93    ArgumentsChanged {
94        /// The call's ID.
95        call_id: String,
96    },
97    /// The call is not a step of the approved plan.
98    NotInPlan {
99        /// The call's ID.
100        call_id: String,
101    },
102}
103
104impl fmt::Display for Deviation {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        match self {
107            Self::Window { expected, found } => write!(
108                f,
109                "the screen shows window {} but the plan was approved for {}; the action is held again",
110                found.as_deref().unwrap_or("(unknown)"),
111                expected.as_deref().unwrap_or("(unknown)")
112            ),
113            Self::Missing { label } => write!(
114                f,
115                "no {} is at the previewed point any more; the action is held again",
116                label.as_deref().map_or("target".to_string(), |l| format!("\"{l}\""))
117            ),
118            Self::WrongTarget { expected, found, label } => write!(
119                f,
120                "the action would hit {} at ({:.0}, {:.0})-({:.0}, {:.0}) pt, not the previewed \
121                 target at ({:.0}, {:.0})-({:.0}, {:.0}) pt; ground it again",
122                label.as_deref().map_or("a target".to_string(), |l| format!("\"{l}\"")),
123                found.x0,
124                found.y0,
125                found.x1,
126                found.y1,
127                expected.x0,
128                expected.y0,
129                expected.x1,
130                expected.y1
131            ),
132            Self::ArgumentsChanged { call_id } => write!(
133                f,
134                "call {call_id} changed its arguments after the plan was approved; it is held again"
135            ),
136            Self::NotInPlan { call_id } => {
137                write!(f, "call {call_id} is not in the approved plan; it is held on its own")
138            }
139        }
140    }
141}
142
143impl std::error::Error for Deviation {}
144
145impl PreviewedTarget {
146    fn window_matches(&self, fresh: &MarkSet) -> Result<(), Deviation> {
147        match (&self.window, &fresh.window) {
148            (Some(expected), Some(found)) if expected != found => Err(Deviation::Window {
149                expected: Some(expected.clone()),
150                found: Some(found.clone()),
151            }),
152            _ => Ok(()),
153        }
154    }
155
156    /// Checks the candidate an executor is about to act on, on a fresh screenshot, against
157    /// the preview: same window, same label, and the candidate's region covers the
158    /// previewed click point while the previewed region covers the candidate's.
159    ///
160    /// # Errors
161    ///
162    /// The [`Deviation`] found; a mark that is not on `fresh` is [`Deviation::Missing`].
163    pub fn check(&self, fresh: &MarkSet, mark: u32) -> Result<GroundedTarget, Deviation> {
164        self.window_matches(fresh)?;
165        let candidate =
166            fresh.candidate(mark).ok_or(Deviation::Missing { label: self.label.clone() })?;
167        let target = fresh.target_of(candidate);
168        if same_label(target.label.as_deref(), self.label.as_deref())
169            && target.points.contains(self.click)
170            && self.points.contains(target.click)
171        {
172            Ok(target)
173        } else {
174            Err(Deviation::WrongTarget {
175                expected: self.points,
176                found: target.points,
177                label: target.label,
178            })
179        }
180    }
181
182    /// Grounds the preview again on a fresh screenshot: the candidate with the previewed
183    /// label whose region covers the previewed click point, the smallest when several do.
184    /// A preview without a label is checked by window only and keeps its click point.
185    ///
186    /// # Errors
187    ///
188    /// [`Deviation::Window`] for another window, [`Deviation::Missing`] when no candidate
189    /// with the label covers the point.
190    pub fn reground(&self, fresh: &MarkSet) -> Result<GroundedTarget, Deviation> {
191        self.window_matches(fresh)?;
192        fresh
193            .candidates
194            .iter()
195            .filter(|c| {
196                self.label.is_none() || same_label(c.label.as_deref(), self.label.as_deref())
197            })
198            .filter(|c| fresh.screen.bbox_to_points(&c.region).contains(self.click))
199            .min_by(|a, b| a.region.area().total_cmp(&b.region.area()))
200            .map(|c| fresh.target_of(c))
201            .ok_or(Deviation::Missing { label: self.label.clone() })
202    }
203}
204
205/// Why a step cannot join a plan.
206#[non_exhaustive]
207#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase", tag = "kind")]
209pub enum PlanRefusal {
210    /// The plan already holds its maximum number of actions.
211    TooManyActions {
212        /// The maximum.
213        max: usize,
214    },
215    /// The step's target is in another window than the plan's.
216    OtherWindow {
217        /// The plan's window.
218        plan: Option<String>,
219        /// The step's window.
220        step: Option<String>,
221    },
222    /// The step's target was grounded on another screenshot than the plan's.
223    OtherScreenshot,
224}
225
226impl fmt::Display for PlanRefusal {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        match self {
229            Self::TooManyActions { max } => {
230                write!(
231                    f,
232                    "a screen plan holds at most {max} actions; preview the rest as a new plan"
233                )
234            }
235            Self::OtherWindow { plan, step } => write!(
236                f,
237                "a screen plan stays in one window: this step is in {}, the plan in {}",
238                step.as_deref().unwrap_or("(unknown)"),
239                plan.as_deref().unwrap_or("(unknown)")
240            ),
241            Self::OtherScreenshot => {
242                write!(f, "every step of a screen plan is grounded on the plan's screenshot")
243            }
244        }
245    }
246}
247
248impl std::error::Error for PlanRefusal {}
249
250/// One step of a [`ScreenPlan`]: a call, its arguments and the target it was previewed
251/// against.
252#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
253#[serde(rename_all = "camelCase")]
254pub struct PlanStep {
255    /// The call's ID.
256    pub call_id: String,
257    /// The tool or toolset member, such as `computer.left_click`.
258    pub action: String,
259    /// The call's arguments as previewed.
260    pub args: Value,
261    /// The previewed target, for an action that points at something.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub target: Option<PreviewedTarget>,
264}
265
266/// Up to N actions in one window, previewed on one screenshot and approved once (spec 3.7
267/// Q8). The approval binds the plan's digest; each step is grounded again on a fresh
268/// screenshot and checked against its previewed target before it runs, and any deviation
269/// holds it again. A plan is never a standing rule.
270///
271/// # Example
272///
273/// ```
274/// use adk_vision::{BBox, Digest, ScreenSpace};
275/// use adk_vision::screen::{CandidateSource, MarkSet, ScreenPlan};
276/// use serde_json::json;
277///
278/// let ocr = CandidateSource::OcrWord { confidence: None };
279/// let mut marks = MarkSet::new(Digest::of(b"form"), (3024, 1964), ScreenSpace::new("built-in", [0.0, 0.0], 2.0))
280///     .with_window("Customer form");
281/// let name = marks.push(BBox::new(400.0, 300.0, 1300.0, 380.0), Some("Name".into()), ocr.clone()).unwrap();
282/// let save = marks.push(BBox::new(1920.0, 1180.0, 2100.0, 1260.0), Some("Save".into()), ocr).unwrap();
283///
284/// let mut plan = ScreenPlan::new(&marks);
285/// plan.push("c1", "computer.left_click", json!({ "mark": name }), Some(&marks.ground(name).unwrap())).unwrap();
286/// plan.push("c2", "computer.type", json!({ "text": "Ada Lovelace" }), None).unwrap();
287/// plan.push("c3", "computer.left_click", json!({ "mark": save }), Some(&marks.ground(save).unwrap())).unwrap();
288/// assert_eq!(plan.steps.len(), 3);
289/// // The same steps always give the same digest, which the one approval binds.
290/// assert_eq!(plan.digest(), plan.clone().digest());
291/// ```
292#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
293#[serde(rename_all = "camelCase")]
294pub struct ScreenPlan {
295    /// The screenshot every step was grounded on.
296    pub screenshot: Digest,
297    /// The one window the plan acts in.
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    pub window: Option<String>,
300    /// The most actions the plan holds.
301    pub max_actions: usize,
302    /// The steps, in call order.
303    pub steps: Vec<PlanStep>,
304}
305
306impl ScreenPlan {
307    /// Actions one plan holds unless set otherwise.
308    pub const DEFAULT_MAX_ACTIONS: usize = 10;
309
310    /// An empty plan on the screenshot and window of `marks`.
311    pub fn new(marks: &MarkSet) -> Self {
312        Self {
313            screenshot: marks.screenshot,
314            window: marks.window.clone(),
315            max_actions: Self::DEFAULT_MAX_ACTIONS,
316            steps: Vec::new(),
317        }
318    }
319
320    /// Sets the most actions the plan holds.
321    #[must_use]
322    pub fn with_max_actions(mut self, max: usize) -> Self {
323        self.max_actions = max.max(1);
324        self
325    }
326
327    /// Appends a step.
328    ///
329    /// # Errors
330    ///
331    /// The [`PlanRefusal`] when the plan is full or the target is in another window or on
332    /// another screenshot.
333    pub fn push(
334        &mut self,
335        call_id: impl Into<String>,
336        action: impl Into<String>,
337        args: Value,
338        target: Option<&GroundedTarget>,
339    ) -> Result<(), PlanRefusal> {
340        if self.steps.len() >= self.max_actions {
341            return Err(PlanRefusal::TooManyActions { max: self.max_actions });
342        }
343        if let Some(target) = target {
344            if target.window != self.window {
345                return Err(PlanRefusal::OtherWindow {
346                    plan: self.window.clone(),
347                    step: target.window.clone(),
348                });
349            }
350            if target.screenshot != self.screenshot {
351                return Err(PlanRefusal::OtherScreenshot);
352            }
353        }
354        self.steps.push(PlanStep {
355            call_id: call_id.into(),
356            action: action.into(),
357            args,
358            target: target.map(PreviewedTarget::from),
359        });
360        Ok(())
361    }
362
363    /// Previews Claude computer use toolset calls on `marks`: each `coordinate` (in the
364    /// pixels of the copy Claude received under `scale`) is grounded to the smallest
365    /// candidate that covers it.
366    ///
367    /// # Errors
368    ///
369    /// The [`PlanRefusal`] of the first step that cannot join.
370    pub fn from_toolset_calls(
371        marks: &MarkSet,
372        scale: &ScreenshotScale,
373        calls: &[(String, String, Value)],
374    ) -> Result<Self, PlanRefusal> {
375        let mut plan = Self::new(marks);
376        for (call_id, member, args) in calls {
377            let target = args
378                .get("coordinate")
379                .and_then(Value::as_array)
380                .and_then(|pair| {
381                    Some([pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32])
382                })
383                .and_then(|point| {
384                    let at = scale.to_source([point[0] + 0.5, point[1] + 0.5]);
385                    marks
386                        .candidates
387                        .iter()
388                        .filter(|c| c.region.contains(at))
389                        .min_by(|a, b| a.region.area().total_cmp(&b.region.area()))
390                        .map(|c| marks.target_of(c))
391                });
392            plan.push(call_id.clone(), member.clone(), args.clone(), target.as_ref())?;
393        }
394        Ok(plan)
395    }
396
397    /// The plan's identity, which the one approval binds: the digest of its canonical JSON,
398    /// keys sorted.
399    pub fn digest(&self) -> Digest {
400        Digest::of_json(self)
401    }
402
403    /// The step for `call_id`.
404    pub fn step(&self, call_id: &str) -> Option<&PlanStep> {
405        self.steps.iter().find(|step| step.call_id == call_id)
406    }
407
408    /// The arguments a step is approved with: its own, with `expect_target` naming the plan
409    /// digest and the previewed target, so the call's fingerprint binds what was shown.
410    pub fn approved_args(&self, call_id: &str) -> Option<Value> {
411        let step = self.step(call_id)?;
412        let mut args = step.args.clone();
413        if let Value::Object(map) = &mut args {
414            map.insert(
415                "expect_target".into(),
416                json!({ "plan": self.digest(), "target": step.target }),
417            );
418        }
419        Some(args)
420    }
421
422    /// Checks a call before it runs: it is a step of the plan with the previewed
423    /// arguments, and — for a step with a target — the target grounded again on `fresh`
424    /// is the previewed one.
425    ///
426    /// # Errors
427    ///
428    /// The [`Deviation`] found; the call is held again.
429    pub fn check_call(
430        &self,
431        call_id: &str,
432        args: &Value,
433        fresh: &MarkSet,
434    ) -> Result<Option<GroundedTarget>, Deviation> {
435        let step = self.step(call_id).ok_or(Deviation::NotInPlan { call_id: call_id.into() })?;
436        let mut bare = args.clone();
437        if let Value::Object(map) = &mut bare {
438            map.remove("expect_target");
439        }
440        if bare != step.args {
441            return Err(Deviation::ArgumentsChanged { call_id: call_id.into() });
442        }
443        if let (Some(expected), Some(found)) = (&self.window, &fresh.window)
444            && expected != found
445        {
446            return Err(Deviation::Window {
447                expected: Some(expected.clone()),
448                found: Some(found.clone()),
449            });
450        }
451        step.target.as_ref().map(|target| target.reground(fresh)).transpose()
452    }
453
454    /// The plan as the lines of an approval card.
455    pub fn render(&self) -> String {
456        let mut out = format!(
457            "{} action(s) in {} on screenshot {}:",
458            self.steps.len(),
459            self.window.as_deref().unwrap_or("the current window"),
460            self.screenshot
461        );
462        for (i, step) in self.steps.iter().enumerate() {
463            out.push_str(&format!("\n{}. {}", i + 1, step.action));
464            if let Some(target) = &step.target {
465                out.push_str(&format!(
466                    " on {} at ({:.0}, {:.0}) pt",
467                    target.label.as_deref().map_or("a point".to_string(), |l| format!("\"{l}\"")),
468                    target.click[0],
469                    target.click[1]
470                ));
471            } else if let Some(text) = step.args.get("text").and_then(Value::as_str) {
472                out.push_str(&format!(" \"{text}\""));
473            }
474        }
475        out
476    }
477}