agentchrome 1.17.0

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
use std::time::{Duration, Instant};

use serde::Serialize;

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

use crate::cli::{
    GlobalOpts, NavigateArgs, NavigateCommand, NavigateReloadArgs, NavigateUrlArgs, WaitUntil,
};
use crate::output::{print_output, setup_session_with_interceptors as setup_session};
use crate::page::wait::check_selector_condition;

/// Default navigation wait timeout in milliseconds.
pub const DEFAULT_NAVIGATE_TIMEOUT_MS: u64 = 30_000;

/// Network idle threshold in milliseconds.
pub const NETWORK_IDLE_MS: u64 = 500;

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

#[derive(Serialize)]
struct NavigateResult {
    url: String,
    title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    status: Option<u16>,
}

#[derive(Serialize)]
struct HistoryResult {
    url: String,
    title: String,
}

// =============================================================================
// Dispatcher
// =============================================================================

/// Execute the `navigate` subcommand group.
///
/// # Errors
///
/// Returns `AppError` if the subcommand fails.
pub async fn execute_navigate(global: &GlobalOpts, args: &NavigateArgs) -> Result<(), AppError> {
    match &args.command {
        Some(NavigateCommand::Back) => execute_back(global).await,
        Some(NavigateCommand::Forward) => execute_forward(global).await,
        Some(NavigateCommand::Reload(reload_args)) => execute_reload(global, reload_args).await,
        None => execute_url(global, &args.url_args).await,
    }
}

// =============================================================================
// URL navigation
// =============================================================================

async fn execute_url(global: &GlobalOpts, args: &NavigateUrlArgs) -> Result<(), AppError> {
    let url = args.url.as_deref().ok_or_else(|| AppError {
        message: "URL is required. Usage: agentchrome navigate <URL>".into(),
        code: ExitCode::GeneralError,
        custom_json: None,
    })?;

    let timeout_ms = args.timeout.unwrap_or(DEFAULT_NAVIGATE_TIMEOUT_MS);
    let start = Instant::now();
    let (_client, mut managed) = setup_session(global).await?;
    if global.auto_dismiss_dialogs {
        let _dismiss = managed.spawn_auto_dismiss().await?;
    }

    // Enable required domains
    managed.ensure_domain("Page").await?;
    managed.ensure_domain("Network").await?;

    // Subscribe to events BEFORE navigating
    let response_rx = managed.subscribe("Network.responseReceived").await?;

    // Subscribe for wait strategy
    let wait_rx = match args.wait_until {
        WaitUntil::Load => Some(managed.subscribe("Page.loadEventFired").await?),
        WaitUntil::Domcontentloaded => Some(managed.subscribe("Page.domContentEventFired").await?),
        WaitUntil::Networkidle | WaitUntil::None => None,
    };

    // For network idle, we need request tracking subscriptions
    let network_subs = if args.wait_until == WaitUntil::Networkidle {
        let req_rx = managed.subscribe("Network.requestWillBeSent").await?;
        let fin_rx = managed.subscribe("Network.loadingFinished").await?;
        let fail_rx = managed.subscribe("Network.loadingFailed").await?;
        Some((req_rx, fin_rx, fail_rx))
    } else {
        None
    };

    // Build navigate params
    let params = serde_json::json!({ "url": url });
    if args.ignore_cache {
        // Page.navigate doesn't have ignoreCache; we use Network.setCacheDisabled instead
        managed
            .send_command(
                "Network.setCacheDisabled",
                Some(serde_json::json!({ "cacheDisabled": true })),
            )
            .await?;
    }

    // Navigate
    let result = managed.send_command("Page.navigate", Some(params)).await?;

    // Check for navigation errors (e.g., DNS failure)
    if let Some(error_text) = result["errorText"].as_str() {
        if !error_text.is_empty() {
            return Err(AppError::navigation_failed(error_text));
        }
    }

    let frame_id = result["frameId"].as_str().unwrap_or_default().to_string();

    // Wait according to strategy
    match args.wait_until {
        WaitUntil::Load | WaitUntil::Domcontentloaded => {
            if let Some(rx) = wait_rx {
                wait_for_event(rx, timeout_ms, &format!("{:?}", args.wait_until)).await?;
            }
        }
        WaitUntil::Networkidle => {
            if let Some((req_rx, fin_rx, fail_rx)) = network_subs {
                wait_for_network_idle(req_rx, fin_rx, fail_rx, timeout_ms).await?;
            }
        }
        WaitUntil::None => {}
    }

    // Optional: wait for a CSS selector to appear after the primary wait strategy
    if let Some(ref selector) = args.wait_for_selector {
        managed.ensure_domain("Runtime").await?;

        #[allow(clippy::cast_possible_truncation)]
        let elapsed_ms = start.elapsed().as_millis() as u64;
        if elapsed_ms >= timeout_ms {
            return Err(AppError::navigation_timeout(
                timeout_ms,
                &format!("selector \"{selector}\" (no time remaining after page load)"),
            ));
        }
        let remaining_ms = timeout_ms - elapsed_ms;
        let deadline = Instant::now() + Duration::from_millis(remaining_ms);
        let interval = Duration::from_millis(100);

        // Immediate pre-check
        if !check_selector_condition(&managed, selector).await {
            loop {
                tokio::time::sleep(interval).await;
                if Instant::now() > deadline {
                    return Err(AppError::navigation_timeout(
                        timeout_ms,
                        &format!("selector \"{selector}\" not found"),
                    ));
                }
                if check_selector_condition(&managed, selector).await {
                    break;
                }
            }
        }
    }

    // Extract HTTP status from responseReceived events
    let status = extract_http_status(response_rx, &frame_id);

    // Get final page info
    let (page_url, page_title) = get_page_info(&managed).await?;

    let output = NavigateResult {
        url: page_url,
        title: page_title,
        status,
    };

    print_output(&output, &global.output)
}

// =============================================================================
// History: Back
// =============================================================================

async fn execute_back(global: &GlobalOpts) -> Result<(), AppError> {
    let (_client, mut managed) = setup_session(global).await?;
    if global.auto_dismiss_dialogs {
        let _dismiss = managed.spawn_auto_dismiss().await?;
    }

    managed.ensure_domain("Page").await?;

    // Get navigation history
    let history = managed
        .send_command("Page.getNavigationHistory", None)
        .await?;

    #[allow(clippy::cast_possible_truncation)]
    let current_index = history["currentIndex"].as_u64().unwrap_or(0) as usize;

    if current_index == 0 {
        return Err(AppError {
            message: "Cannot go back: already at the beginning of history.".into(),
            code: ExitCode::GeneralError,
            custom_json: None,
        });
    }

    let entries = history["entries"].as_array().ok_or_else(|| AppError {
        message: "Invalid navigation history response".into(),
        code: ExitCode::GeneralError,
        custom_json: None,
    })?;

    let target_entry = &entries[current_index - 1];
    let entry_id = target_entry["id"].as_i64().unwrap_or(0);

    // Subscribe to both frameNavigated (cross-document) and navigatedWithinDocument
    // (same-document / SPA pushState) before navigating — whichever fires first wins.
    let nav_rx = managed.subscribe("Page.frameNavigated").await?;
    let within_doc_rx = managed.subscribe("Page.navigatedWithinDocument").await?;

    // Navigate to history entry
    managed
        .send_command(
            "Page.navigateToHistoryEntry",
            Some(serde_json::json!({ "entryId": entry_id })),
        )
        .await?;

    // Wait for navigation (cross-document or same-document)
    wait_for_history_navigation(
        nav_rx,
        within_doc_rx,
        global.timeout.unwrap_or(DEFAULT_NAVIGATE_TIMEOUT_MS),
    )
    .await?;

    let (page_url, page_title) = get_page_info(&managed).await?;

    let output = HistoryResult {
        url: page_url,
        title: page_title,
    };

    print_output(&output, &global.output)
}

// =============================================================================
// History: Forward
// =============================================================================

async fn execute_forward(global: &GlobalOpts) -> Result<(), AppError> {
    let (_client, mut managed) = setup_session(global).await?;
    if global.auto_dismiss_dialogs {
        let _dismiss = managed.spawn_auto_dismiss().await?;
    }

    managed.ensure_domain("Page").await?;

    let history = managed
        .send_command("Page.getNavigationHistory", None)
        .await?;

    #[allow(clippy::cast_possible_truncation)]
    let current_index = history["currentIndex"].as_u64().unwrap_or(0) as usize;

    let entries = history["entries"].as_array().ok_or_else(|| AppError {
        message: "Invalid navigation history response".into(),
        code: ExitCode::GeneralError,
        custom_json: None,
    })?;

    let next_index = current_index + 1;
    if next_index >= entries.len() {
        return Err(AppError {
            message: "Cannot go forward: already at the end of history.".into(),
            code: ExitCode::GeneralError,
            custom_json: None,
        });
    }

    let target_entry = &entries[next_index];
    let entry_id = target_entry["id"].as_i64().unwrap_or(0);

    // Subscribe to both frameNavigated (cross-document) and navigatedWithinDocument
    // (same-document / SPA pushState) before navigating — whichever fires first wins.
    let nav_rx = managed.subscribe("Page.frameNavigated").await?;
    let within_doc_rx = managed.subscribe("Page.navigatedWithinDocument").await?;

    managed
        .send_command(
            "Page.navigateToHistoryEntry",
            Some(serde_json::json!({ "entryId": entry_id })),
        )
        .await?;

    // Wait for navigation (cross-document or same-document)
    wait_for_history_navigation(
        nav_rx,
        within_doc_rx,
        global.timeout.unwrap_or(DEFAULT_NAVIGATE_TIMEOUT_MS),
    )
    .await?;

    let (page_url, page_title) = get_page_info(&managed).await?;

    let output = HistoryResult {
        url: page_url,
        title: page_title,
    };

    print_output(&output, &global.output)
}

// =============================================================================
// Reload
// =============================================================================

async fn execute_reload(global: &GlobalOpts, args: &NavigateReloadArgs) -> Result<(), AppError> {
    let (_client, mut managed) = setup_session(global).await?;
    if global.auto_dismiss_dialogs {
        let _dismiss = managed.spawn_auto_dismiss().await?;
    }

    managed.ensure_domain("Page").await?;

    let load_rx = managed.subscribe("Page.loadEventFired").await?;

    let params = serde_json::json!({ "ignoreCache": args.ignore_cache });
    managed.send_command("Page.reload", Some(params)).await?;

    wait_for_event(
        load_rx,
        global.timeout.unwrap_or(DEFAULT_NAVIGATE_TIMEOUT_MS),
        "load",
    )
    .await?;

    let (page_url, page_title) = get_page_info(&managed).await?;

    let output = HistoryResult {
        url: page_url,
        title: page_title,
    };

    print_output(&output, &global.output)
}

// =============================================================================
// Wait strategies
// =============================================================================

pub async fn wait_for_event(
    mut rx: tokio::sync::mpsc::Receiver<CdpEvent>,
    timeout_ms: u64,
    strategy: &str,
) -> Result<(), AppError> {
    let timeout = Duration::from_millis(timeout_ms);
    tokio::select! {
        event = rx.recv() => {
            match event {
                Some(_) => Ok(()),
                None => Err(AppError {
                    message: format!("Event channel closed while waiting for {strategy}"),
                    code: ExitCode::GeneralError,
                    custom_json: None,
                }),
            }
        }
        () = tokio::time::sleep(timeout) => {
            Err(AppError::navigation_timeout(timeout_ms, strategy))
        }
    }
}

/// Wait for either `Page.frameNavigated` (cross-document) or
/// `Page.navigatedWithinDocument` (same-document / SPA pushState) — whichever
/// fires first. This prevents timeouts on SPA history navigations where Chrome
/// only emits the within-document event.
async fn wait_for_history_navigation(
    mut frame_rx: tokio::sync::mpsc::Receiver<CdpEvent>,
    mut within_doc_rx: tokio::sync::mpsc::Receiver<CdpEvent>,
    timeout_ms: u64,
) -> Result<(), AppError> {
    let timeout = Duration::from_millis(timeout_ms);
    tokio::select! {
        event = frame_rx.recv() => {
            match event {
                Some(_) => Ok(()),
                None => Err(AppError {
                    message: "Event channel closed while waiting for navigation".into(),
                    code: ExitCode::GeneralError,
                    custom_json: None,
                }),
            }
        }
        event = within_doc_rx.recv() => {
            match event {
                Some(_) => Ok(()),
                None => Err(AppError {
                    message: "Event channel closed while waiting for navigation".into(),
                    code: ExitCode::GeneralError,
                    custom_json: None,
                }),
            }
        }
        () = tokio::time::sleep(timeout) => {
            Err(AppError::navigation_timeout(timeout_ms, "navigation"))
        }
    }
}

pub async fn wait_for_network_idle(
    mut req_rx: tokio::sync::mpsc::Receiver<CdpEvent>,
    mut fin_rx: tokio::sync::mpsc::Receiver<CdpEvent>,
    mut fail_rx: tokio::sync::mpsc::Receiver<CdpEvent>,
    timeout_ms: u64,
) -> Result<(), AppError> {
    let timeout = Duration::from_millis(timeout_ms);
    let idle_duration = Duration::from_millis(NETWORK_IDLE_MS);
    let deadline = tokio::time::Instant::now() + timeout;

    let mut in_flight: i64 = 0;
    let idle_timer = tokio::time::sleep(idle_duration);
    tokio::pin!(idle_timer);

    loop {
        tokio::select! {
            event = req_rx.recv() => {
                if event.is_some() {
                    in_flight += 1;
                    // Reset idle timer
                    idle_timer.as_mut().reset(tokio::time::Instant::now() + idle_duration);
                }
            }
            event = fin_rx.recv() => {
                if event.is_some() {
                    in_flight = (in_flight - 1).max(0);
                    if in_flight == 0 {
                        idle_timer.as_mut().reset(tokio::time::Instant::now() + idle_duration);
                    }
                }
            }
            event = fail_rx.recv() => {
                if event.is_some() {
                    in_flight = (in_flight - 1).max(0);
                    if in_flight == 0 {
                        idle_timer.as_mut().reset(tokio::time::Instant::now() + idle_duration);
                    }
                }
            }
            () = &mut idle_timer => {
                if in_flight == 0 {
                    return Ok(());
                }
                // Reset timer if still in-flight
                idle_timer.as_mut().reset(tokio::time::Instant::now() + idle_duration);
            }
            () = tokio::time::sleep_until(deadline) => {
                return Err(AppError::navigation_timeout(timeout_ms, "networkidle"));
            }
        }
    }
}

// =============================================================================
// Helpers
// =============================================================================

/// Get the current page URL and title via `Runtime.evaluate`.
async fn get_page_info(managed: &ManagedSession) -> Result<(String, String), AppError> {
    let url_result = managed
        .send_command(
            "Runtime.evaluate",
            Some(serde_json::json!({ "expression": "location.href" })),
        )
        .await?;

    let title_result = managed
        .send_command(
            "Runtime.evaluate",
            Some(serde_json::json!({ "expression": "document.title" })),
        )
        .await?;

    let url = url_result["result"]["value"]
        .as_str()
        .unwrap_or_default()
        .to_string();
    let title = title_result["result"]["value"]
        .as_str()
        .unwrap_or_default()
        .to_string();

    Ok((url, title))
}

/// Extract the HTTP status code from buffered `Network.responseReceived` events,
/// matching the main frame.
fn extract_http_status(
    mut rx: tokio::sync::mpsc::Receiver<CdpEvent>,
    frame_id: &str,
) -> Option<u16> {
    // Drain all buffered events
    let mut status = None;
    while let Ok(event) = rx.try_recv() {
        // Match the response for the main frame document
        let event_frame = event.params["frameId"].as_str().unwrap_or_default();
        let resource_type = event.params["type"].as_str().unwrap_or_default();
        if event_frame == frame_id && resource_type == "Document" {
            if let Some(s) = event.params["response"]["status"].as_u64() {
                #[allow(clippy::cast_possible_truncation)]
                {
                    status = Some(s as u16);
                }
            }
        }
    }
    status
}

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

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

    #[test]
    fn navigate_result_serialization() {
        let result = NavigateResult {
            url: "https://example.com".to_string(),
            title: "Example".to_string(),
            status: Some(200),
        };
        let json: serde_json::Value = serde_json::to_value(&result).unwrap();
        assert_eq!(json["url"], "https://example.com");
        assert_eq!(json["title"], "Example");
        assert_eq!(json["status"], 200);
    }

    #[test]
    fn navigate_result_without_status() {
        let result = NavigateResult {
            url: "https://example.com".to_string(),
            title: "Example".to_string(),
            status: None,
        };
        let json: serde_json::Value = serde_json::to_value(&result).unwrap();
        assert_eq!(json["url"], "https://example.com");
        assert!(json.get("status").is_none());
    }

    #[test]
    fn history_result_serialization() {
        let result = HistoryResult {
            url: "https://example.com".to_string(),
            title: "Example".to_string(),
        };
        let json: serde_json::Value = serde_json::to_value(&result).unwrap();
        assert_eq!(json["url"], "https://example.com");
        assert_eq!(json["title"], "Example");
    }

    #[test]
    fn wait_until_default_is_load() {
        let default = WaitUntil::default();
        assert_eq!(default, WaitUntil::Load);
    }

    fn mock_cdp_event(method: &str) -> CdpEvent {
        CdpEvent {
            method: method.to_string(),
            params: serde_json::Value::Null,
            session_id: None,
        }
    }

    #[tokio::test]
    async fn history_navigation_resolves_on_frame_navigated() {
        let (frame_tx, frame_rx) = tokio::sync::mpsc::channel(1);
        let (_within_tx, within_rx) = tokio::sync::mpsc::channel(1);

        frame_tx
            .send(mock_cdp_event("Page.frameNavigated"))
            .await
            .unwrap();

        let result = wait_for_history_navigation(frame_rx, within_rx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn history_navigation_resolves_on_within_document() {
        let (_frame_tx, frame_rx) = tokio::sync::mpsc::channel(1);
        let (within_tx, within_rx) = tokio::sync::mpsc::channel(1);

        within_tx
            .send(mock_cdp_event("Page.navigatedWithinDocument"))
            .await
            .unwrap();

        let result = wait_for_history_navigation(frame_rx, within_rx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn history_navigation_times_out_when_no_event() {
        let (_frame_tx, frame_rx) = tokio::sync::mpsc::channel(1);
        let (_within_tx, within_rx) = tokio::sync::mpsc::channel(1);

        let result = wait_for_history_navigation(frame_rx, within_rx, 50).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains("timed out"));
    }

    #[tokio::test]
    async fn history_navigation_errors_on_closed_frame_channel() {
        let (frame_tx, frame_rx) = tokio::sync::mpsc::channel(1);
        let (_within_tx, within_rx) = tokio::sync::mpsc::channel(1);

        drop(frame_tx);

        let result = wait_for_history_navigation(frame_rx, within_rx, 1000).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains("channel closed"));
    }

    #[tokio::test]
    async fn history_navigation_errors_on_closed_within_doc_channel() {
        let (_frame_tx, frame_rx) = tokio::sync::mpsc::channel(1);
        let (within_tx, within_rx) = tokio::sync::mpsc::channel(1);

        drop(within_tx);

        let result = wait_for_history_navigation(frame_rx, within_rx, 1000).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains("channel closed"));
    }
}