rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! The tools that act on a page: the clicks, `hover`, `type`, `key` and
//! `form_input`, and when config turns them on, `javascript_exec` and
//! `file_upload`.
//!
//! Each sends its input, then waits for the page to act on it: two drawn
//! frames, or, when the input starts a navigation of the tab, until the
//! page it leads to is ready (see [`Watch::settle`]).

use super::keys::{self, Chord, Typed};
use super::opt_in::{self, Uploads};
use super::schema::{FIND_LIMIT, NAVIGATION_LIMIT};
use super::tabs::{execution, Node, OpenTab};
use super::text;
use crate::browser::view::Placed;
use crate::browser::VIEWPORT;
use rho_browser::cdp::dom::GetContentQuads;
use rho_browser::cdp::input::{
    DispatchMouseEvent, InsertText, Modifiers, MouseButton, MouseEventKind,
};
use rho_browser::tab::{Effect, LoadError, Viewport, Watch};
use rho_protocol::{BrowserRect, BrowserViewport};
use rho_sdk::tool::ToolError;
use serde::Deserialize;
use serde_json::{json, Value};

/// An action on a page.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Act {
    /// A click or hover over `target`, holding `modifiers`.
    Point {
        pointer: Pointer,
        target: Target,
        modifiers: Modifiers,
    },
    /// Typing text at the page's focus.
    Type(String),
    /// Pressing `chords` in turn, `repeat` times over. `text` is the keys
    /// as the model wrote them, for the reply.
    Key {
        text: String,
        chords: Vec<Chord>,
        repeat: u8,
    },
    /// Setting the form field a ref names to a string, number or boolean.
    FormInput { element: String, value: Value },
    /// Running the model's JavaScript in the page (`javascript_exec`).
    Script(String),
    /// Setting the files of the file input a ref names (`file_upload`).
    Upload { element: String, files: Uploads },
}

/// Where a pointer action lands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Target {
    /// The element a ref such as `ref_3` names, at the center of its box.
    Ref(String),
    /// A point in the viewport, in CSS pixels.
    Point { x: u32, y: u32 },
}

/// What a pointer action does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Pointer {
    Left,
    Right,
    Middle,
    Double,
    Triple,
    Hover,
}

impl Pointer {
    /// The button it clicks and how many times, or `None` for a hover.
    fn clicks(self) -> Option<(MouseButton, u32)> {
        match self {
            Self::Left => Some((MouseButton::Left, 1)),
            Self::Right => Some((MouseButton::Right, 1)),
            Self::Middle => Some((MouseButton::Middle, 1)),
            Self::Double => Some((MouseButton::Left, 2)),
            Self::Triple => Some((MouseButton::Left, 3)),
            Self::Hover => None,
        }
    }

    /// What it did to `what`, for the reply.
    fn done(self, what: &str) -> String {
        match self {
            Self::Left => format!("Clicked {what}."),
            Self::Right => format!("Right-clicked {what}."),
            Self::Middle => format!("Middle-clicked {what}."),
            Self::Double => format!("Double-clicked {what}."),
            Self::Triple => format!("Triple-clicked {what}."),
            Self::Hover => format!("Hovered over {what}."),
        }
    }
}

/// What an action did, for the reply, and where the element it acted on
/// by ref was just before it acted, for a client to outline.
#[derive(Debug)]
pub(super) struct Done {
    pub(super) text: String,
    pub(super) placed: Option<Placed>,
}

impl From<String> for Done {
    fn from(text: String) -> Self {
        Self { text, placed: None }
    }
}

/// Does `act` on `open`'s page and says what it did.
pub(super) async fn run(open: &mut OpenTab, act: &Act) -> Result<Done, ToolError> {
    match act {
        Act::Point {
            pointer,
            target,
            modifiers,
        } => point(open, *pointer, target, *modifiers).await,
        Act::Type(text) => type_text(open, text).await.map(Done::from),
        Act::Key {
            text,
            chords,
            repeat,
        } => press_keys(open, text, chords, *repeat)
            .await
            .map(Done::from),
        Act::FormInput { element, value } => form_input(open, element, value).await.map(Done::from),
        Act::Script(script) => {
            let watch = open.watch();
            let value = opt_in::run_script(open, script).await?;
            settle(open, watch, value).await.map(Done::from)
        }
        Act::Upload { element, files } => {
            let node = open.node(element).await?;
            let watch = open.watch();
            let done = opt_in::upload(open, &node, files).await?;
            settle(open, watch, done).await.map(Done::from)
        }
    }
}

/// What is under `(x, y)`: `null` when it is `this` or inside it, or else
/// the element there, if any. A text node stands for its element, and a
/// label for the control it clicks.
const UNCOVERED: &str = r##"function (x, y) {
  const self = this.nodeType === Node.ELEMENT_NODE ? this : this.parentElement;
  const root = this.getRootNode();
  const hit = (typeof root.elementFromPoint === "function" ? root : document).elementFromPoint(x, y);
  if (hit === null) return { tag: null, id: "", classes: "" };
  if (self === null || self === hit || self.contains(hit)) return null;
  if (hit.closest("label")?.control === self) return null;
  const classes = typeof hit.className === "string" ? hit.className.trim() : "";
  return { tag: hit.localName, id: hit.id, classes };
}"##;

/// What covers the point an element would be clicked at.
#[derive(Deserialize)]
struct Cover {
    /// The covering element's tag, or none when no element is there.
    tag: Option<String>,
    id: String,
    classes: String,
}

impl Cover {
    /// A short description, such as `<div id="banner">`.
    fn describe(&self) -> String {
        let Some(tag) = &self.tag else {
            return "no element".to_owned();
        };
        let mut text = format!("<{tag}");
        for (name, value) in [("id", &self.id), ("class", &self.classes)] {
            if !value.is_empty() {
                text.push_str(&format!(" {name}={}", text::quoted(value)));
            }
        }
        text.push('>');
        text
    }
}

/// Sets a form field to `value`, firing the events typing would, and
/// returns `{set}` with what it shows now, or `{refused}` with why not,
/// leaving the field as it was. A select's options are listed up to
/// `limit`; one that takes several adds the option to those selected.
const SET_VALUE: &str = r##"function (value, limit) {
  const el = this;
  if (el.nodeType !== Node.ELEMENT_NODE) return { refused: "not_field", tag: "#text" };
  const tag = el.localName;
  const fire = () => {
    el.dispatchEvent(new Event("input", { bubbles: true }));
    el.dispatchEvent(new Event("change", { bubbles: true }));
  };
  if (el.matches(":disabled")) return { refused: "disabled" };
  if (tag === "select") {
    const wanted = String(value);
    const options = [...el.options];
    const option = options.find(o => o.value === wanted)
      ?? options.find(o => o.textContent.trim() === wanted.trim());
    if (option === undefined) {
      return { refused: "no_option", options: options.slice(0, limit).map(o => o.textContent.trim()) };
    }
    if (option.disabled) return { refused: "option_disabled" };
    if (el.multiple) option.selected = true;
    else for (const other of options) other.selected = other === option;
    fire();
    return { set: option.textContent.trim() };
  }
  if (tag === "input" && (el.type === "checkbox" || el.type === "radio")) {
    if (typeof value !== "boolean") return { refused: "needs_boolean", type: el.type };
    if (el.type === "radio" && el.checked && !value) return { refused: "radio_off" };
    if (el.checked !== value) el.click();
    if (el.checked !== value) return { refused: "unchanged" };
    return { set: value };
  }
  if (tag === "input" && ["file", "button", "submit", "reset", "image"].includes(el.type)) {
    return { refused: "not_field", tag: "input type=" + el.type };
  }
  if (tag === "input" || tag === "textarea") {
    if (el.readOnly) return { refused: "readonly" };
    const text = String(value);
    const before = el.value;
    el.focus();
    el.value = text;
    if (el.value !== text) {
      const shows = el.value;
      el.value = before;
      return { refused: "rejected", type: el.type, shows };
    }
    fire();
    return { set: el.value };
  }
  return { refused: el.isContentEditable ? "editable" : "not_field", tag };
}"##;

/// What [`SET_VALUE`] returns.
#[derive(Deserialize)]
#[serde(untagged)]
enum SetValue {
    Set { set: Value },
    Refused(Refusal),
}

/// Why [`SET_VALUE`] did not set a field.
#[derive(Deserialize)]
#[serde(tag = "refused", rename_all = "snake_case")]
enum Refusal {
    Disabled,
    Readonly,
    /// A radio button asked to turn off.
    RadioOff,
    /// A checkbox or radio button the page kept as it was.
    Unchanged,
    /// A select with no such option, and its first options.
    NoOption {
        options: Vec<String>,
    },
    OptionDisabled,
    /// A checkbox or radio button given a value that is not a boolean.
    NeedsBoolean {
        #[serde(rename = "type")]
        kind: String,
    },
    /// A field that did not take the value, and what it showed with it.
    Rejected {
        #[serde(rename = "type")]
        kind: String,
        shows: String,
    },
    /// An editable element that is not a form field.
    Editable {
        tag: String,
    },
    NotField {
        tag: String,
    },
}

impl Refusal {
    fn message(&self, element: &str) -> String {
        match self {
            Self::Disabled => format!("{element} is disabled, so it cannot be set."),
            Self::Readonly => format!("{element} is read-only, so it cannot be set."),
            Self::NoOption { options } => format!(
                "{element} has no option with that value or text. Its options: {}.",
                options
                    .iter()
                    .map(|option| text::quoted(option))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Self::OptionDisabled => {
                format!("{element}'s option with that value or text is disabled.")
            }
            Self::NeedsBoolean { kind } => {
                format!("{element} is a {kind}; set it with true or false.")
            }
            Self::RadioOff => format!(
                "{element} is a radio button, which is turned off by setting another in its group."
            ),
            Self::Unchanged => format!("{element} did not change: the page kept it as it was."),
            Self::Rejected { kind, shows } => format!(
                "{element} is a {kind} field and did not take that value: it showed {} with it, so it was left as it was.",
                text::quoted(shows)
            ),
            Self::Editable { tag } => format!(
                "{element} is an editable <{tag}>, not a form field: click it and type instead."
            ),
            Self::NotField { tag } => format!(
                "{element} is a <{tag}>, not a form field form_input can set: use a text field, text area, checkbox, radio button or select."
            ),
        }
    }
}

/// Clicks or hovers over `target`, holding `modifiers`.
async fn point(
    open: &mut OpenTab,
    pointer: Pointer,
    target: &Target,
    modifiers: Modifiers,
) -> Result<Done, ToolError> {
    let ((x, y), placed) = match target {
        Target::Point { x, y } => ((f64::from(*x), f64::from(*y)), None),
        Target::Ref(element) => {
            let drawn = element_box(open, element).await?;
            let placed = Placed {
                element: element.clone(),
                rect: drawn.rect(),
                viewport: BrowserViewport::new(VIEWPORT.width, VIEWPORT.height),
            };
            (drawn.center(), Some(placed))
        }
    };
    let watch = open.watch();
    let mouse = |kind, button, click_count| DispatchMouseEvent {
        kind,
        x,
        y,
        button,
        click_count,
        modifiers,
        delta_x: None,
        delta_y: None,
    };
    open.call(&mouse(
        MouseEventKind::Moved,
        /*button*/ None,
        /*click_count*/ None,
    ))
    .await?;
    if let Some((button, count)) = pointer.clicks() {
        for click in 1..=count {
            for kind in [MouseEventKind::Pressed, MouseEventKind::Released] {
                open.call(&mouse(kind, Some(button), Some(click))).await?;
            }
        }
    }
    let what = match target {
        Target::Ref(element) => format!("element {element}"),
        Target::Point { x, y } => format!("({x}, {y})"),
    };
    let text = settle(open, watch, pointer.done(&what)).await?;
    Ok(Done { text, placed })
}

/// Types `text` at the page's focus.
async fn type_text(open: &mut OpenTab, text: &str) -> Result<String, ToolError> {
    let watch = open.watch();
    for step in keys::typing(text) {
        match step {
            Typed::Key(key) => {
                let chord = Chord {
                    modifiers: Modifiers::NONE,
                    key,
                };
                press(open, &chord).await?;
            }
            Typed::Text(text) => {
                open.call(&InsertText { text }).await?;
            }
        }
    }
    let count = text.chars().count();
    settle(open, watch, format!("Typed {count} characters.")).await
}

/// Presses `chords` in turn, `repeat` times over.
async fn press_keys(
    open: &mut OpenTab,
    text: &str,
    chords: &[Chord],
    repeat: u8,
) -> Result<String, ToolError> {
    let watch = open.watch();
    for _ in 0..repeat {
        for chord in chords {
            press(open, chord).await?;
        }
    }
    let times = match repeat {
        1 => String::new(),
        repeat => format!(" {repeat} times"),
    };
    settle(open, watch, format!("Pressed {text}{times}.")).await
}

/// Sets the form field `element` names to `value`.
async fn form_input(open: &mut OpenTab, element: &str, value: &Value) -> Result<String, ToolError> {
    let node = open.node(element).await?;
    let watch = open.watch();
    let answer = open
        .call_on(&node, SET_VALUE, vec![value.clone(), json!(FIND_LIMIT)])
        .await?;
    let answer: SetValue = serde_json::from_value(answer)
        .map_err(|error| execution(format!("the browser answered oddly: {error}")))?;
    let shown = match answer {
        SetValue::Set { set } => set,
        SetValue::Refused(refusal) => return Err(execution(refusal.message(element))),
    };
    let shown = match shown {
        Value::String(shown) => text::quoted(&shown),
        other => other.to_string(),
    };
    settle(open, watch, format!("Set {element} to {shown}.")).await
}

/// The part of `element`'s box in the viewport, once scrolled into view,
/// whose center a click lands on, if nothing covers it there.
async fn element_box(open: &mut OpenTab, element: &str) -> Result<Visible, ToolError> {
    let node = open.node(element).await?;
    open.scroll_into_view(&node).await?;
    let drawn = drawn_box(open, &node).await?;
    let (x, y) = drawn.center();
    let cover = open
        .call_on(&node, UNCOVERED, vec![json!(x), json!(y)])
        .await?;
    let cover: Option<Cover> = serde_json::from_value(cover)
        .map_err(|error| execution(format!("the browser answered oddly: {error}")))?;
    match cover {
        None => Ok(drawn),
        Some(cover) => Err(execution(format!(
            "{element} is covered by {} at ({x:.0}, {y:.0}), which would get the click instead. Close or move what covers it, or click by coordinate.",
            cover.describe()
        ))),
    }
}

/// The part of `node`'s box in the viewport.
async fn drawn_box(open: &OpenTab, node: &Node<'_>) -> Result<Visible, ToolError> {
    let quads = open
        .on_node(&GetContentQuads {
            backend_node_id: node.id,
        })
        .await?
        // A node the page does not draw has no box.
        .map(|quads| quads.quads)
        .unwrap_or_default();
    visible_box(&quads, VIEWPORT).ok_or_else(|| {
        execution(format!(
            "{} is not visible in the viewport, so it cannot be clicked: it may be hidden or have no size. Use read_page or screenshot to find what to click.",
            node.name
        ))
    })
}

/// The part within the viewport of an element's box, in CSS pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Visible {
    left: f64,
    top: f64,
    right: f64,
    bottom: f64,
}

impl Visible {
    /// Its center, where a click lands.
    fn center(self) -> (f64, f64) {
        (
            (self.left + self.right) / 2.0,
            (self.top + self.bottom) / 2.0,
        )
    }

    /// It rounded out to whole pixels. It lies within the viewport, so
    /// each edge fits a `u32`.
    fn rect(self) -> BrowserRect {
        let (left, top) = (self.left.floor(), self.top.floor());
        BrowserRect::new(
            left as u32,
            top as u32,
            (self.right.ceil() - left) as u32,
            (self.bottom.ceil() - top) as u32,
        )
    }
}

/// The part within `viewport` of the first of `quads`, each four corners
/// as `x, y` pairs, that is at least a pixel each way, so its center is on
/// the element.
fn visible_box(quads: &[[f64; 8]], viewport: Viewport) -> Option<Visible> {
    let (width, height) = (f64::from(viewport.width), f64::from(viewport.height));
    quads.iter().find_map(|quad| {
        let xs = [quad[0], quad[2], quad[4], quad[6]];
        let ys = [quad[1], quad[3], quad[5], quad[7]];
        let left = xs.iter().copied().fold(f64::INFINITY, f64::min).max(0.0);
        let right = xs
            .iter()
            .copied()
            .fold(f64::NEG_INFINITY, f64::max)
            .min(width);
        let top = ys.iter().copied().fold(f64::INFINITY, f64::min).max(0.0);
        let bottom = ys
            .iter()
            .copied()
            .fold(f64::NEG_INFINITY, f64::max)
            .min(height);
        (right - left >= 1.0 && bottom - top >= 1.0).then_some(Visible {
            left,
            top,
            right,
            bottom,
        })
    })
}

/// Presses `chord`: its modifiers down in order, the key, then the
/// modifiers up in reverse.
async fn press(open: &OpenTab, chord: &Chord) -> Result<(), ToolError> {
    let held: Vec<_> = keys::held(chord.modifiers).collect();
    let mut modifiers = Modifiers::NONE;
    for (modifier, key) in &held {
        modifiers = modifiers.with(*modifier);
        open.call(&key.down(modifiers)).await?;
    }
    open.call(&chord.key.down(modifiers)).await?;
    open.call(&chord.key.up(modifiers)).await?;
    for (modifier, key) in held.iter().rev() {
        modifiers = modifiers.without(*modifier);
        open.call(&key.up(modifiers)).await?;
    }
    Ok(())
}

/// Waits for the input sent since `watch` began to take effect, then
/// returns `done`, with a note when the page it led to did not load.
async fn settle(open: &mut OpenTab, watch: Watch, done: String) -> Result<String, ToolError> {
    let drawn = async {
        // A page that cannot run the script has acted all the same.
        let _ = open.drawn().await;
    };
    match watch.settle(drawn, NAVIGATION_LIMIT).await {
        Ok(Effect::Stayed | Effect::Navigated) => Ok(done),
        Err(LoadError::TimedOut(limit)) => Ok(format!(
            "{done} The page it led to was still loading after {} s, so its loading was stopped. Use screenshot or read_page to see what loaded.",
            limit.as_secs()
        )),
        Err(LoadError::Closed) => Err(execution(format!(
            "{done} Then the tab closed, or the browser exited."
        ))),
        Err(error @ (LoadError::Cdp(_) | LoadError::Failed(_) | LoadError::NoHistory(_))) => Err(
            execution(format!("{done} Then the browser could not tell what it did: {error}")),
        ),
    }
}

#[cfg(test)]
#[path = "actions_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "actions_live_tests.rs"]
mod live_tests;