rho-coding-agent 3.10.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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! A page's accessibility tree as text for the model: one element per line,
//! `role "name" [ref_N]`, indented by depth.
//!
//! Only what renders is read. Chrome's accessibility tree leaves out text
//! hidden with `display: none`, `visibility: hidden` or `aria-hidden`, and
//! text it marks ignored is skipped here too, so such text does not reach
//! the model. Text hidden other ways, such as with `opacity: 0`, still does;
//! the default read keeps to the viewport, which leaves out text moved off
//! screen.
//! Wrapper elements with no role or name of their own are left out and
//! their children take their place, which keeps a typical page in the
//! hundreds of lines.

use super::refs::Refs;
use rho_browser::cdp::accessibility::AxNode;
use rho_browser::cdp::dom_snapshot::DocumentSnapshot;
use rho_browser::cdp::{AxNodeId, BackendNodeId};
use std::collections::HashMap;
use std::fmt::Write as _;

/// Which elements `read_page` shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Filter {
    /// Every element in the viewport.
    Visible,
    /// Only the controls in the viewport, one per line without nesting.
    Interactive,
    /// Every element, in the viewport or not.
    All,
}

/// What a `read_page` call asked for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Read {
    pub(super) filter: Filter,
    /// How many levels of elements to show below the start.
    pub(super) depth: usize,
    /// The element whose subtree to show, by its ref; the whole page when
    /// `None`.
    pub(super) start: Option<BackendNodeId>,
}

/// What the viewport shows: each rendered node's box, and the scrolled
/// viewport, in document pixels.
#[derive(Debug, Clone, PartialEq)]
pub(super) struct View {
    boxes: HashMap<BackendNodeId, Rect>,
    viewport: Rect,
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct Rect {
    x: f64,
    y: f64,
    width: f64,
    height: f64,
}

impl Rect {
    fn overlaps(&self, other: &Rect) -> bool {
        self.width > 0.0
            && self.height > 0.0
            && self.x < other.x + other.width
            && other.x < self.x + self.width
            && self.y < other.y + other.height
            && other.y < self.y + self.height
    }
}

impl View {
    /// The view of `document`, the main frame's, in a viewport of `width`
    /// by `height` CSS pixels.
    pub(super) fn of(document: &DocumentSnapshot, width: u32, height: u32) -> Self {
        let nodes = &document.nodes.backend_node_id;
        let boxes = document
            .layout
            .node_index
            .iter()
            .zip(&document.layout.bounds)
            .filter_map(|(&index, &[x, y, width, height])| {
                Some((
                    *nodes.get(index)?,
                    Rect {
                        x,
                        y,
                        width,
                        height,
                    },
                ))
            })
            .collect();
        Self {
            boxes,
            viewport: Rect {
                x: document.scroll_offset_x,
                y: document.scroll_offset_y,
                width: f64::from(width),
                height: f64::from(height),
            },
        }
    }
}

/// A rendered read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Rendered {
    pub(super) text: String,
    /// Elements below the depth limit were left out.
    pub(super) cut_at_depth: bool,
}

/// Renders `read` of `tree`, the root first as `getFullAXTree` returns it,
/// naming each element shown with its ref in `refs`. `view` decides what is
/// in the viewport; [`Filter::All`] needs none. `None` when the element
/// `read` starts at is not in the tree.
pub(super) fn render(
    tree: &[AxNode],
    view: Option<&View>,
    read: &Read,
    refs: &mut Refs,
) -> Option<Rendered> {
    let page = Page::new(tree);
    let start = match read.start {
        Some(node) => *page.by_dom.get(&node)?,
        None => 0,
    };
    let in_view = match (read.filter, view) {
        (Filter::All, _) | (_, None) => None,
        (Filter::Visible | Filter::Interactive, Some(view)) => Some(page.in_view(view)),
    };
    let mut out = Out::default();
    let mut stack = vec![Visit {
        index: start,
        depth: 0,
        element_above: None,
    }];
    while let Some(visit) = stack.pop() {
        let Visit {
            index,
            depth,
            element_above,
        } = visit;
        if in_view.as_ref().is_some_and(|in_view| !in_view[index]) {
            continue;
        }
        let node = &tree[index];
        let mut below = Visit {
            index,
            depth,
            element_above,
        };
        match Kind::of(node, /*start*/ index == start && read.start.is_some()) {
            Kind::Skipped => continue,
            Kind::Transparent => {}
            Kind::Text(_) if depth >= read.depth => {
                out.cut_at_depth = true;
                continue;
            }
            Kind::Text(run) => {
                // A link's or heading's text is its name, and a text
                // box's its value, already shown.
                let repeated = element_above.is_some_and(|above| {
                    let above = &tree[above];
                    VALUED.contains(&role(above)) || name(above).contains(run.trim())
                });
                if read.filter != Filter::Interactive && !repeated {
                    out.text(depth, node.parent_id.as_ref(), &run);
                }
                continue;
            }
            Kind::Element if depth >= read.depth => {
                out.cut_at_depth = true;
                continue;
            }
            Kind::Element => {
                match read.filter {
                    Filter::Interactive if !is_interactive(node) => {}
                    Filter::Interactive => {
                        out.element(node, 0, refs);
                        below.depth += 1;
                    }
                    Filter::Visible | Filter::All => {
                        out.element(node, depth, refs);
                        below.depth += 1;
                    }
                }
                below.element_above = Some(index);
            }
        }
        for &child in page.children[index].iter().rev() {
            stack.push(Visit {
                index: child,
                ..below
            });
        }
    }
    Some(out.finish())
}

/// A node to visit, and what it shows under.
#[derive(Clone, Copy)]
struct Visit {
    index: usize,
    /// Its depth among the elements shown.
    depth: usize,
    /// The nearest element above it.
    element_above: Option<usize>,
}

/// The text so far, with a run of page text that has not ended yet.
#[derive(Default)]
struct Out {
    text: String,
    run: Option<Run>,
    cut_at_depth: bool,
}

/// Page text that shows as one line.
struct Run {
    depth: usize,
    /// The parent of the text node that ended it.
    parent: Option<AxNodeId>,
    text: String,
}

impl Out {
    /// Adds `run`, a text node under `parent`, to the text line at `depth`,
    /// starting one if an element came between. Runs under one parent
    /// join as they are, so `<b>Hel</b>lo` stays a word; runs under
    /// different ones get a space between, so `<div>One</div><div>Two</div>`
    /// does not become one.
    fn text(&mut self, depth: usize, parent: Option<&AxNodeId>, run: &str) {
        match &mut self.run {
            Some(line) if line.depth == depth => {
                if line.parent.as_ref() != parent
                    && !line.text.ends_with(' ')
                    && !run.starts_with(' ')
                {
                    line.text.push(' ');
                }
                line.text.push_str(run);
                line.parent = parent.cloned();
            }
            _ => {
                self.end_run();
                self.run = Some(Run {
                    depth,
                    parent: parent.cloned(),
                    text: run.to_owned(),
                });
            }
        }
    }

    fn element(&mut self, node: &AxNode, indent: usize, refs: &mut Refs) {
        self.end_run();
        write_element(&mut self.text, node, indent, refs);
    }

    fn end_run(&mut self) {
        if let Some(Run { depth, text, .. }) = self.run.take() {
            let run = text.trim();
            if !run.is_empty() {
                let _ = writeln!(
                    self.text,
                    "{:indent$}text {}",
                    "",
                    quoted(run),
                    indent = depth * 2
                );
            }
        }
    }

    fn finish(mut self) -> Rendered {
        self.end_run();
        Rendered {
            text: self.text,
            cut_at_depth: self.cut_at_depth,
        }
    }
}

/// Up to `limit` elements of `tree` that match `query`, best first, each
/// with its ref in `refs`. Every word of the query counts: one found in an
/// element's role, name or value scores a point, and a role also answers to
/// its plain names, so "search field" finds a `searchbox`.
pub(super) fn find(tree: &[AxNode], query: &str, limit: usize, refs: &mut Refs) -> Vec<String> {
    let words: Vec<String> = query
        .split(|c: char| !c.is_alphanumeric())
        .filter(|word| !word.is_empty() && !STOP_WORDS.contains(word))
        .map(str::to_lowercase)
        .collect();
    if words.is_empty() {
        return Vec::new();
    }
    let page = Page::new(tree);
    let mut matches: Vec<(usize, bool, usize, &AxNode)> = page
        .document_order()
        .into_iter()
        .enumerate()
        .filter_map(|(order, index)| {
            let node = &tree[index];
            if !matches!(Kind::of(node, false), Kind::Element) {
                return None;
            }
            let haystack = haystack(node);
            let score = words
                .iter()
                .filter(|word| haystack.contains(word.as_str()))
                .count();
            (score > 0).then_some((score, is_interactive(node), order, node))
        })
        .collect();
    matches.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));
    matches
        .into_iter()
        .take(limit)
        .map(|(_, _, _, node)| {
            let mut line = String::new();
            write_element(&mut line, node, 0, refs);
            line.pop();
            line
        })
        .collect()
}

const STOP_WORDS: [&str; 11] = [
    "a", "an", "the", "to", "for", "of", "on", "in", "with", "and", "or",
];

fn haystack(node: &AxNode) -> String {
    let role = role(node);
    let mut haystack = format!("{role} {} ", role_aliases(role));
    for value in [&node.name, &node.value, &node.description]
        .into_iter()
        .flatten()
    {
        if let Some(text) = value.as_str() {
            haystack.push_str(text);
            haystack.push(' ');
        }
    }
    haystack.to_lowercase()
}

/// Plain names a request may use for a role.
fn role_aliases(role: &str) -> &'static str {
    match role {
        "textbox" | "searchbox" | "combobox" => "field input box text search",
        "checkbox" | "switch" => "check box toggle",
        "radio" => "option choice",
        "img" | "image" => "image picture",
        "heading" => "title header",
        "navigation" => "nav menu",
        "listbox" => "list select dropdown",
        _ => "",
    }
}

/// The tree's nodes by position, with each one's children.
struct Page<'a> {
    tree: &'a [AxNode],
    children: Vec<Vec<usize>>,
    by_dom: HashMap<BackendNodeId, usize>,
}

impl<'a> Page<'a> {
    fn new(tree: &'a [AxNode]) -> Self {
        let by_id: HashMap<&AxNodeId, usize> = tree
            .iter()
            .enumerate()
            .map(|(index, node)| (&node.node_id, index))
            .collect();
        let children = tree
            .iter()
            .map(|node| {
                node.child_ids
                    .iter()
                    .filter_map(|child| by_id.get(child).copied())
                    .collect()
            })
            .collect();
        let by_dom = tree
            .iter()
            .enumerate()
            .filter_map(|(index, node)| Some((node.backend_dom_node_id?, index)))
            .collect();
        Self {
            tree,
            children,
            by_dom,
        }
    }

    /// Every node reachable from the root, parents before children and
    /// siblings in page order.
    fn document_order(&self) -> Vec<usize> {
        let mut order = Vec::with_capacity(self.tree.len());
        let mut seen = vec![false; self.tree.len()];
        let mut stack = if self.tree.is_empty() {
            Vec::new()
        } else {
            vec![0]
        };
        while let Some(index) = stack.pop() {
            if std::mem::replace(&mut seen[index], true) {
                continue;
            }
            order.push(index);
            stack.extend(self.children[index].iter().rev());
        }
        order
    }

    /// Whether each node, or any node below it, has a box in the viewport.
    fn in_view(&self, view: &View) -> Vec<bool> {
        let mut in_view: Vec<bool> = self
            .tree
            .iter()
            .map(|node| {
                node.backend_dom_node_id
                    .and_then(|dom| view.boxes.get(&dom))
                    .is_some_and(|rect| rect.overlaps(&view.viewport))
            })
            .collect();
        for &index in self.document_order().iter().rev() {
            if self.children[index].iter().any(|&child| in_view[child]) {
                in_view[index] = true;
            }
        }
        in_view
    }
}

/// How a node shows.
enum Kind {
    /// Not at all, nor anything below it.
    Skipped,
    /// Not itself; its children show in its place.
    Transparent,
    /// As text joined into its line.
    Text(String),
    /// As an element line.
    Element,
}

impl Kind {
    fn of(node: &AxNode, start: bool) -> Self {
        let role = role(node);
        match role {
            // Line boxes of a text run, which repeat its text.
            "InlineTextBox" => Self::Skipped,
            "StaticText" if node.ignored => Self::Skipped,
            "StaticText" => Self::Text(clean(
                node.name
                    .as_ref()
                    .and_then(|name| name.as_str())
                    .unwrap_or(""),
            )),
            _ if start => Self::Element,
            _ if node.ignored => Self::Transparent,
            "RootWebArea" | "WebArea" => Self::Transparent,
            "generic" | "none" | "" if !has_name(node) => Self::Transparent,
            _ => Self::Element,
        }
    }
}

fn role(node: &AxNode) -> &str {
    node.role
        .as_ref()
        .and_then(|role| role.as_str())
        .unwrap_or("")
}

fn name(node: &AxNode) -> String {
    clean(
        node.name
            .as_ref()
            .and_then(|name| name.as_str())
            .unwrap_or(""),
    )
}

fn has_name(node: &AxNode) -> bool {
    !name(node).trim().is_empty()
}

/// The roles a person acts on.
const INTERACTIVE: [&str; 17] = [
    "button",
    "checkbox",
    "combobox",
    "link",
    "listbox",
    "menuitem",
    "menuitemcheckbox",
    "menuitemradio",
    "option",
    "radio",
    "searchbox",
    "slider",
    "spinbutton",
    "switch",
    "tab",
    "textbox",
    "treeitem",
];

fn is_interactive(node: &AxNode) -> bool {
    INTERACTIVE.contains(&role(node))
        || (has_name(node) && property(node, "focusable") == Some(&serde_json::Value::Bool(true)))
}

fn property<'a>(node: &'a AxNode, name: &str) -> Option<&'a serde_json::Value> {
    node.properties
        .iter()
        .find(|property| property.name == name)
        .and_then(|property| property.value.value.as_ref())
}

/// The roles whose value is what a person typed or picked.
const VALUED: [&str; 5] = ["textbox", "searchbox", "combobox", "spinbutton", "slider"];

fn write_element(text: &mut String, node: &AxNode, indent: usize, refs: &mut Refs) {
    use serde_json::Value;

    let role = role(node);
    let _ = write!(text, "{:indent$}{role}", "", indent = indent * 2);
    let name = name(node);
    if !name.trim().is_empty() {
        let _ = write!(text, " {}", quoted(name.trim()));
    }
    if VALUED.contains(&role) {
        if let Some(value) = node.value.as_ref().and_then(|value| value.value.as_ref()) {
            let value = match value {
                Value::String(value) => clean(value),
                other => other.to_string(),
            };
            let _ = write!(text, " value={}", quoted(&value));
        }
    }
    if let Some(Value::Number(level)) = property(node, "level") {
        let _ = write!(text, " level={level}");
    }
    match property(node, "checked") {
        Some(Value::String(checked)) if checked == "true" => text.push_str(" checked"),
        Some(Value::String(checked)) if checked == "mixed" => text.push_str(" mixed"),
        Some(Value::Bool(true)) => text.push_str(" checked"),
        _ => {}
    }
    match property(node, "expanded") {
        Some(Value::Bool(true)) => text.push_str(" expanded"),
        Some(Value::Bool(false)) => text.push_str(" collapsed"),
        _ => {}
    }
    for state in ["selected", "disabled"] {
        if property(node, state) == Some(&Value::Bool(true)) {
            let _ = write!(text, " {state}");
        }
    }
    if let Some(dom) = node.backend_dom_node_id {
        let _ = write!(text, " [{}]", refs.name(dom));
    }
    text.push('\n');
}

/// `text` with each run of whitespace one space, kept at the ends so runs
/// still join with their spaces, and control characters gone, so page
/// text cannot break a line or fake one.
fn clean(text: &str) -> String {
    let mut cleaned = String::with_capacity(text.len());
    let mut space = false;
    for c in text.chars() {
        if c.is_whitespace() {
            space = true;
        } else if !c.is_control() {
            if std::mem::take(&mut space) {
                cleaned.push(' ');
            }
            cleaned.push(c);
        }
    }
    if space {
        cleaned.push(' ');
    }
    cleaned
}

fn quoted(text: &str) -> String {
    format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
}

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