agentchrome 1.51.4

A CLI tool for browser automation via the Chrome DevTools Protocol
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
use serde::Serialize;

use agentchrome::connection::ManagedSession;
use agentchrome::error::{AppError, ExitCode};

use crate::cli::{GlobalOpts, PageFindArgs};
use crate::output;

use super::{get_page_info, setup_session};

// =============================================================================
// Output types
// =============================================================================

/// A single element match from `page find`.
#[derive(Debug, Clone, Serialize)]
struct FindMatch {
    #[serde(skip_serializing_if = "Option::is_none")]
    uid: Option<String>,
    role: String,
    name: String,
    #[serde(rename = "boundingBox", skip_serializing_if = "Option::is_none")]
    bounding_box: Option<BoundingBox>,
}

/// Pixel-based bounding box of an element.
#[derive(Debug, Clone, Serialize)]
struct BoundingBox {
    x: f64,
    y: f64,
    width: f64,
    height: f64,
}

// =============================================================================
// Summary builder
// =============================================================================

/// Build a domain-specific summary for the `page find` large-response gate.
///
/// Fields:
/// - `match_count`: total number of matches returned
/// - `roles_seen`: distinct role values across all matches
fn summary_of_find(matches: &[FindMatch]) -> serde_json::Value {
    #[allow(clippy::cast_possible_truncation)]
    let match_count = matches.len() as u64;
    let mut roles: Vec<String> = matches
        .iter()
        .map(|m| m.role.clone())
        .collect::<std::collections::HashSet<_>>()
        .into_iter()
        .collect();
    roles.sort_unstable();

    serde_json::json!({
        "match_count": match_count,
        "roles_seen": roles,
    })
}

// =============================================================================
// Bounding box resolution
// =============================================================================

/// Resolve bounding box for a DOM node by its `backendDOMNodeId`.
///
/// Returns `None` if the element is invisible or has been removed from the DOM.
async fn resolve_bounding_box(
    managed: &ManagedSession,
    backend_dom_node_id: i64,
) -> Option<BoundingBox> {
    // Resolve backendNodeId → nodeId via DOM.describeNode
    let describe = managed
        .send_command(
            "DOM.describeNode",
            Some(serde_json::json!({ "backendNodeId": backend_dom_node_id })),
        )
        .await
        .ok()?;

    let node_id = describe["node"]["nodeId"].as_i64()?;

    // Get box model for the resolved nodeId
    let box_result = managed
        .send_command(
            "DOM.getBoxModel",
            Some(serde_json::json!({ "nodeId": node_id })),
        )
        .await
        .ok()?;

    let content = box_result["model"]["content"].as_array()?;
    if content.len() < 8 {
        return None;
    }

    // Content quad: [x1,y1, x2,y2, x3,y3, x4,y4] — top-left and bottom-right
    let x1 = content[0].as_f64()?;
    let y1 = content[1].as_f64()?;
    let x3 = content[4].as_f64()?;
    let y3 = content[5].as_f64()?;

    Some(BoundingBox {
        x: x1,
        y: y1,
        width: x3 - x1,
        height: y3 - y1,
    })
}

// =============================================================================
// CSS selector search
// =============================================================================

/// Find elements by CSS selector using CDP DOM methods.
///
/// Returns up to `limit` matches with role, name, and bounding box.
async fn find_by_selector(
    managed: &ManagedSession,
    selector: &str,
    limit: usize,
) -> Result<Vec<FindMatch>, AppError> {
    // Get the document root
    let doc = managed
        .send_command("DOM.getDocument", None)
        .await
        .map_err(|e| AppError::snapshot_failed(&e.to_string()))?;
    let root_node_id = doc["root"]["nodeId"]
        .as_i64()
        .ok_or_else(|| AppError::snapshot_failed("DOM.getDocument missing root nodeId"))?;

    // Query all matching nodes
    let query_result = managed
        .send_command(
            "DOM.querySelectorAll",
            Some(serde_json::json!({
                "nodeId": root_node_id,
                "selector": selector,
            })),
        )
        .await
        .map_err(|e| AppError {
            message: format!("CSS selector query failed: {e}"),
            code: ExitCode::ProtocolError,
            custom_json: None,
        })?;

    let node_ids = query_result["nodeIds"]
        .as_array()
        .ok_or_else(|| AppError::snapshot_failed("DOM.querySelectorAll missing nodeIds"))?;

    let mut matches = Vec::with_capacity(limit.min(node_ids.len()));
    for node_id_val in node_ids.iter().take(limit) {
        let Some(node_id) = node_id_val.as_i64() else {
            continue;
        };

        // Get backendDOMNodeId via DOM.describeNode
        let describe = managed
            .send_command(
                "DOM.describeNode",
                Some(serde_json::json!({ "nodeId": node_id })),
            )
            .await;

        let backend_dom_node_id = describe
            .as_ref()
            .ok()
            .and_then(|d| d["node"]["backendNodeId"].as_i64());

        // Get accessibility info for this node
        let (role, name) = if let Some(backend_id) = backend_dom_node_id {
            let ax_result = managed
                .send_command(
                    "Accessibility.getPartialAXTree",
                    Some(serde_json::json!({
                        "backendNodeId": backend_id,
                        "fetchRelatives": false,
                    })),
                )
                .await;

            if let Ok(ax) = ax_result {
                let nodes = ax["nodes"].as_array();
                let first = nodes.and_then(|arr| arr.first());
                let role = first
                    .and_then(|n| n["role"]["value"].as_str())
                    .unwrap_or("none")
                    .to_string();
                let name = first
                    .and_then(|n| n["name"]["value"].as_str())
                    .unwrap_or("")
                    .to_string();
                (role, name)
            } else {
                ("none".to_string(), String::new())
            }
        } else {
            ("none".to_string(), String::new())
        };

        // Get bounding box
        let bounding_box = if let Some(backend_id) = backend_dom_node_id {
            resolve_bounding_box(managed, backend_id).await
        } else {
            None
        };

        matches.push(FindMatch {
            uid: None, // UIDs assigned after full snapshot
            role,
            name,
            bounding_box,
        });
    }

    Ok(matches)
}

// =============================================================================
// Snapshot capture helper
// =============================================================================

/// Capture the accessibility tree, build it, and persist snapshot state.
async fn capture_snapshot(
    managed: &ManagedSession,
) -> Result<crate::snapshot::BuildResult, AppError> {
    let ax_result = managed
        .send_command("Accessibility.getFullAXTree", None)
        .await
        .map_err(|e| AppError::snapshot_failed(&e.to_string()))?;
    let nodes = ax_result["nodes"]
        .as_array()
        .ok_or_else(|| AppError::snapshot_failed("response missing 'nodes' array"))?;
    let build = crate::snapshot::build_tree(nodes, false);

    let (url, _title) = get_page_info(managed).await?;
    let state = crate::snapshot::SnapshotState {
        url,
        timestamp: agentchrome::session::now_iso8601(),
        uid_map: build.uid_map.clone(),
        frame_index: None,
        frame_id: None,
        aggregate: false,
        frame_uid_ranges: Vec::new(),
        frame_ids: Vec::new(),
    };
    if let Err(e) = crate::snapshot::write_snapshot_state(&state) {
        eprintln!("warning: could not save snapshot state: {e}");
    }

    Ok(build)
}

// =============================================================================
// UID assignment from snapshot tree
// =============================================================================

/// Try to assign a UID from the snapshot tree to a CSS-matched element.
fn assign_uid_from_snapshot(node: &crate::snapshot::SnapshotNode, m: &mut FindMatch) {
    if node.role == m.role
        && node.name == m.name
        && let Some(ref uid) = node.uid
    {
        m.uid = Some(uid.clone());
        return;
    }
    for child in &node.children {
        if m.uid.is_some() {
            return;
        }
        assign_uid_from_snapshot(child, m);
    }
}

// =============================================================================
// Command executor
// =============================================================================

/// Validate that at least one of `--query`, `--selector`, or `--role` is provided.
fn validate_find_args(args: &PageFindArgs) -> Result<(), AppError> {
    if args.query.is_none() && args.selector.is_none() && args.role.is_none() {
        return Err(AppError {
            message: "a text query, --selector, or --role is required".to_string(),
            code: ExitCode::GeneralError,
            custom_json: None,
        });
    }
    Ok(())
}

/// Run the find pipeline against a prepared session: enable required domains,
/// capture a snapshot, then execute either the CSS-selector or accessibility
/// text search path.
async fn gather_find_matches(
    session: &mut ManagedSession,
    args: &PageFindArgs,
) -> Result<Vec<FindMatch>, AppError> {
    session.ensure_domain("Accessibility").await?;
    session.ensure_domain("DOM").await?;
    session.ensure_domain("Runtime").await?;

    let build = capture_snapshot(session).await?;

    if let Some(ref selector) = args.selector {
        let mut css_matches = find_by_selector(session, selector, args.limit).await?;
        for m in &mut css_matches {
            assign_uid_from_snapshot(&build.root, m);
        }
        Ok(css_matches)
    } else {
        let query = args.query.as_deref().unwrap_or("");
        let hits = crate::snapshot::search_tree(
            &build.root,
            query,
            args.role.as_deref(),
            args.exact,
            args.limit,
        );
        let mut matches = Vec::with_capacity(hits.len());
        for hit in hits {
            let bounding_box = if let Some(backend_id) = hit.backend_dom_node_id {
                resolve_bounding_box(session, backend_id).await
            } else {
                None
            };
            matches.push(FindMatch {
                uid: hit.uid,
                role: hit.role,
                name: hit.name,
                bounding_box,
            });
        }
        Ok(matches)
    }
}

pub async fn execute_find(
    global: &GlobalOpts,
    args: &PageFindArgs,
    frame: Option<&str>,
) -> Result<(), AppError> {
    validate_find_args(args)?;

    let (client, mut managed) = setup_session(global).await?;
    if global.auto_dismiss_dialogs {
        let _dismiss = managed.spawn_auto_dismiss().await?;
    }

    let matches = if let Some(frame_str) = frame {
        let arg = agentchrome::frame::parse_frame_arg(frame_str)?;
        let mut frame_ctx = agentchrome::frame::resolve_frame(&client, &mut managed, &arg).await?;
        let frame_session = agentchrome::frame::frame_session_mut(&mut frame_ctx, &mut managed);
        gather_find_matches(frame_session, args).await?
    } else {
        gather_find_matches(&mut managed, args).await?
    };

    // Output
    if global.output.plain {
        for m in &matches {
            let uid_str = m.uid.as_ref().map_or(String::new(), |u| format!("[{u}] "));
            let bb_str = m.bounding_box.as_ref().map_or(String::new(), |bb| {
                format!(" ({},{} {}x{})", bb.x, bb.y, bb.width, bb.height)
            });
            println!("{uid_str}{} \"{}\"{bb_str}", m.role, m.name);
        }
        return Ok(());
    }

    output::emit(
        &matches,
        &global.output,
        "page find",
        |v: &Vec<FindMatch>| summary_of_find(v.as_slice()),
    )
}

// =============================================================================
// Script runner compute function
// =============================================================================

/// Run `page find` against an existing session and return the matches as JSON.
///
/// Used by the script runner to invoke `page find` without printing to stdout.
///
/// # Errors
///
/// Returns `AppError` on argument validation, snapshot capture, or search failure.
pub async fn compute_find(
    managed: &mut ManagedSession,
    args: &PageFindArgs,
) -> Result<serde_json::Value, AppError> {
    validate_find_args(args)?;
    let matches = gather_find_matches(managed, args).await?;
    serde_json::to_value(&matches).map_err(|e| AppError {
        message: format!("serialization error: {e}"),
        code: ExitCode::GeneralError,
        custom_json: None,
    })
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // =========================================================================
    // FindMatch / BoundingBox serialization tests
    // =========================================================================

    #[test]
    fn find_match_serialization_with_all_fields() {
        let m = FindMatch {
            uid: Some("s3".to_string()),
            role: "button".to_string(),
            name: "Submit".to_string(),
            bounding_box: Some(BoundingBox {
                x: 120.0,
                y: 340.0,
                width: 80.0,
                height: 36.0,
            }),
        };
        let json: serde_json::Value = serde_json::to_value(&m).unwrap();
        assert_eq!(json["uid"], "s3");
        assert_eq!(json["role"], "button");
        assert_eq!(json["name"], "Submit");
        assert_eq!(json["boundingBox"]["x"], 120.0);
        assert_eq!(json["boundingBox"]["y"], 340.0);
        assert_eq!(json["boundingBox"]["width"], 80.0);
        assert_eq!(json["boundingBox"]["height"], 36.0);
    }

    #[test]
    fn find_match_serialization_without_uid() {
        let m = FindMatch {
            uid: None,
            role: "heading".to_string(),
            name: "Title".to_string(),
            bounding_box: Some(BoundingBox {
                x: 50.0,
                y: 10.0,
                width: 300.0,
                height: 32.0,
            }),
        };
        let json: serde_json::Value = serde_json::to_value(&m).unwrap();
        assert!(json.get("uid").is_none());
        assert_eq!(json["role"], "heading");
        assert!(json.get("boundingBox").is_some());
    }

    #[test]
    fn find_match_serialization_without_bounding_box() {
        let m = FindMatch {
            uid: Some("s1".to_string()),
            role: "button".to_string(),
            name: "Hidden".to_string(),
            bounding_box: None,
        };
        let json: serde_json::Value = serde_json::to_value(&m).unwrap();
        assert_eq!(json["uid"], "s1");
        assert!(json.get("boundingBox").is_none());
    }

    #[test]
    fn find_match_serialization_minimal() {
        let m = FindMatch {
            uid: None,
            role: "text".to_string(),
            name: "Hello".to_string(),
            bounding_box: None,
        };
        let json: serde_json::Value = serde_json::to_value(&m).unwrap();
        assert!(json.get("uid").is_none());
        assert!(json.get("boundingBox").is_none());
        assert_eq!(json["role"], "text");
        assert_eq!(json["name"], "Hello");
    }

    #[test]
    fn find_match_array_serialization() {
        let matches = vec![
            FindMatch {
                uid: Some("s1".to_string()),
                role: "button".to_string(),
                name: "OK".to_string(),
                bounding_box: Some(BoundingBox {
                    x: 10.0,
                    y: 20.0,
                    width: 50.0,
                    height: 30.0,
                }),
            },
            FindMatch {
                uid: None,
                role: "heading".to_string(),
                name: "Title".to_string(),
                bounding_box: None,
            },
        ];
        let json: serde_json::Value = serde_json::to_value(&matches).unwrap();
        let arr = json.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        assert_eq!(arr[0]["uid"], "s1");
        assert!(arr[1].get("uid").is_none());
    }

    #[test]
    fn find_match_empty_array_serialization() {
        let matches: Vec<FindMatch> = vec![];
        let json = serde_json::to_string(&matches).unwrap();
        assert_eq!(json, "[]");
    }

    #[test]
    fn bounding_box_camel_case_key() {
        let m = FindMatch {
            uid: None,
            role: "button".to_string(),
            name: "Test".to_string(),
            bounding_box: Some(BoundingBox {
                x: 0.0,
                y: 0.0,
                width: 100.0,
                height: 50.0,
            }),
        };
        let json_str = serde_json::to_string(&m).unwrap();
        assert!(json_str.contains("\"boundingBox\""));
        assert!(!json_str.contains("\"bounding_box\""));
    }

    // =========================================================================
    // assign_uid_from_snapshot tests
    // =========================================================================

    fn make_snapshot_node(
        role: &str,
        name: &str,
        uid: Option<&str>,
        children: Vec<crate::snapshot::SnapshotNode>,
    ) -> crate::snapshot::SnapshotNode {
        crate::snapshot::SnapshotNode {
            role: role.to_string(),
            name: name.to_string(),
            uid: uid.map(String::from),
            properties: None,
            backend_dom_node_id: None,
            frame: None,
            children,
        }
    }

    #[test]
    fn assign_uid_matches_role_and_name() {
        let tree = make_snapshot_node(
            "document",
            "Page",
            None,
            vec![make_snapshot_node("button", "Submit", Some("s1"), vec![])],
        );
        let mut m = FindMatch {
            uid: None,
            role: "button".to_string(),
            name: "Submit".to_string(),
            bounding_box: None,
        };
        assign_uid_from_snapshot(&tree, &mut m);
        assert_eq!(m.uid.as_deref(), Some("s1"));
    }

    #[test]
    fn assign_uid_no_match_leaves_none() {
        let tree = make_snapshot_node(
            "document",
            "Page",
            None,
            vec![make_snapshot_node("button", "Submit", Some("s1"), vec![])],
        );
        let mut m = FindMatch {
            uid: None,
            role: "link".to_string(),
            name: "Other".to_string(),
            bounding_box: None,
        };
        assign_uid_from_snapshot(&tree, &mut m);
        assert!(m.uid.is_none());
    }

    #[test]
    fn assign_uid_first_match_wins() {
        let tree = make_snapshot_node(
            "document",
            "Page",
            None,
            vec![
                make_snapshot_node("button", "OK", Some("s1"), vec![]),
                make_snapshot_node("button", "OK", Some("s2"), vec![]),
            ],
        );
        let mut m = FindMatch {
            uid: None,
            role: "button".to_string(),
            name: "OK".to_string(),
            bounding_box: None,
        };
        assign_uid_from_snapshot(&tree, &mut m);
        assert_eq!(m.uid.as_deref(), Some("s1"));
    }

    // =========================================================================
    // summary_of_find
    // =========================================================================

    fn make_find_match(role: &str, name: &str) -> FindMatch {
        FindMatch {
            uid: None,
            role: role.to_string(),
            name: name.to_string(),
            bounding_box: None,
        }
    }

    #[test]
    fn summary_of_find_empty_matches() {
        let matches: Vec<FindMatch> = vec![];
        let summary = summary_of_find(&matches);
        assert_eq!(summary["match_count"], 0);
        let roles = summary["roles_seen"].as_array().unwrap();
        assert!(roles.is_empty());
    }

    #[test]
    fn summary_of_find_counts_matches() {
        let matches = vec![
            make_find_match("button", "OK"),
            make_find_match("button", "Cancel"),
            make_find_match("link", "Home"),
        ];
        let summary = summary_of_find(&matches);
        assert_eq!(summary["match_count"], 3);
    }

    #[test]
    fn summary_of_find_deduplicates_roles() {
        let matches = vec![
            make_find_match("button", "OK"),
            make_find_match("button", "Cancel"),
            make_find_match("link", "Home"),
        ];
        let summary = summary_of_find(&matches);
        let roles: Vec<&str> = summary["roles_seen"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert_eq!(roles.len(), 2);
        assert!(roles.contains(&"button"));
        assert!(roles.contains(&"link"));
    }

    #[test]
    fn summary_of_find_roles_sorted() {
        let matches = vec![
            make_find_match("link", "Home"),
            make_find_match("button", "OK"),
            make_find_match("heading", "Title"),
        ];
        let summary = summary_of_find(&matches);
        let roles: Vec<&str> = summary["roles_seen"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        // Must be sorted
        let mut sorted = roles.clone();
        sorted.sort_unstable();
        assert_eq!(roles, sorted);
    }
}