1use 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
38#[serde(rename_all = "camelCase")]
39pub struct PreviewedTarget {
40 pub screenshot: Digest,
42 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub window: Option<String>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub label: Option<String>,
48 pub points: BBox,
50 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#[non_exhaustive]
68#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
69#[serde(rename_all = "camelCase", tag = "kind")]
70pub enum Deviation {
71 Window {
73 expected: Option<String>,
75 found: Option<String>,
77 },
78 Missing {
80 label: Option<String>,
82 },
83 WrongTarget {
85 expected: BBox,
87 found: BBox,
89 label: Option<String>,
91 },
92 ArgumentsChanged {
94 call_id: String,
96 },
97 NotInPlan {
99 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 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 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#[non_exhaustive]
207#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase", tag = "kind")]
209pub enum PlanRefusal {
210 TooManyActions {
212 max: usize,
214 },
215 OtherWindow {
217 plan: Option<String>,
219 step: Option<String>,
221 },
222 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
253#[serde(rename_all = "camelCase")]
254pub struct PlanStep {
255 pub call_id: String,
257 pub action: String,
259 pub args: Value,
261 #[serde(default, skip_serializing_if = "Option::is_none")]
263 pub target: Option<PreviewedTarget>,
264}
265
266#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
293#[serde(rename_all = "camelCase")]
294pub struct ScreenPlan {
295 pub screenshot: Digest,
297 #[serde(default, skip_serializing_if = "Option::is_none")]
299 pub window: Option<String>,
300 pub max_actions: usize,
302 pub steps: Vec<PlanStep>,
304}
305
306impl ScreenPlan {
307 pub const DEFAULT_MAX_ACTIONS: usize = 10;
309
310 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 #[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 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 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 pub fn digest(&self) -> Digest {
400 Digest::of_json(self)
401 }
402
403 pub fn step(&self, call_id: &str) -> Option<&PlanStep> {
405 self.steps.iter().find(|step| step.call_id == call_id)
406 }
407
408 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 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 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}