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
use std::time::Instant;

use globset::GlobBuilder;
use serde::Serialize;
use tokio::time::Duration;

use agentchrome::error::AppError;

use crate::cli::{GlobalOpts, PageWaitArgs};
use crate::navigate::{DEFAULT_NAVIGATE_TIMEOUT_MS, wait_for_network_idle};

use super::{get_page_info, print_output, setup_session};

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

#[derive(Serialize)]
struct WaitResult {
    condition: String,
    matched: bool,
    url: String,
    title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pattern: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    selector: Option<String>,
}

// =============================================================================
// Plain text output
// =============================================================================

fn print_wait_plain(result: &WaitResult) {
    println!("Condition: {}", result.condition);
    println!("Matched:   {}", result.matched);
    println!("URL:       {}", result.url);
    println!("Title:     {}", result.title);
    if let Some(ref p) = result.pattern {
        println!("Pattern:   {p}");
    }
    if let Some(ref t) = result.text {
        println!("Text:      {t}");
    }
    if let Some(ref s) = result.selector {
        println!("Selector:  {s}");
    }
}

// =============================================================================
// Condition checking helpers
// =============================================================================

/// Evaluate a JS expression via Runtime.evaluate, returning the result value.
/// Returns `None` if the evaluation fails (e.g. page is navigating).
pub(crate) async fn eval_js(
    managed: &agentchrome::connection::ManagedSession,
    expression: &str,
) -> Option<serde_json::Value> {
    let result = managed
        .send_command(
            "Runtime.evaluate",
            Some(serde_json::json!({ "expression": expression })),
        )
        .await
        .ok()?;
    Some(result["result"]["value"].clone())
}

/// Check the URL condition: fetch location.href and match against a glob.
async fn check_url_condition(
    managed: &agentchrome::connection::ManagedSession,
    matcher: &globset::GlobMatcher,
) -> bool {
    let Some(val) = eval_js(managed, "location.href").await else {
        return false;
    };
    let Some(href) = val.as_str() else {
        return false;
    };
    matcher.is_match(href)
}

/// Check the text condition: evaluate document.body.innerText.includes(text).
async fn check_text_condition(
    managed: &agentchrome::connection::ManagedSession,
    text: &str,
) -> bool {
    let encoded = serde_json::to_string(text).unwrap_or_default();
    let expr = format!("document.body.innerText.includes({encoded})");
    let Some(val) = eval_js(managed, &expr).await else {
        return false;
    };
    val.as_bool().unwrap_or(false)
}

/// Check the selector condition: evaluate document.querySelector(sel) !== null.
pub(crate) async fn check_selector_condition(
    managed: &agentchrome::connection::ManagedSession,
    selector: &str,
) -> bool {
    let encoded = serde_json::to_string(selector).unwrap_or_default();
    let expr = format!("document.querySelector({encoded}) !== null");
    let Some(val) = eval_js(managed, &expr).await else {
        return false;
    };
    val.as_bool().unwrap_or(false)
}

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

pub async fn execute_wait(
    global: &GlobalOpts,
    args: &PageWaitArgs,
    frame: Option<&str>,
) -> Result<(), AppError> {
    let timeout_ms = global.timeout.unwrap_or(DEFAULT_NAVIGATE_TIMEOUT_MS);

    // Network idle path (event-driven, not polled)
    if args.network_idle {
        return execute_network_idle_wait(global, timeout_ms).await;
    }

    // Poll-based conditions: --url, --text, --selector
    let (client, mut managed) = setup_session(global).await?;

    // Resolve optional frame context
    let mut frame_ctx = if let Some(frame_str) = frame {
        let arg = agentchrome::frame::parse_frame_arg(frame_str)?;
        Some(agentchrome::frame::resolve_frame(&client, &mut managed, &arg).await?)
    } else {
        None
    };

    // Enable Runtime domain (needs &mut)
    {
        let eff_mut = if let Some(ref mut ctx) = frame_ctx {
            agentchrome::frame::frame_session_mut(ctx, &mut managed)
        } else {
            &mut managed
        };
        eff_mut.ensure_domain("Runtime").await?;
    }

    let effective = if let Some(ref ctx) = frame_ctx {
        agentchrome::frame::frame_session(ctx, &managed)
    } else {
        &managed
    };

    if let Some(ref pattern) = args.url {
        poll_url(global, effective, pattern, timeout_ms, args.interval).await
    } else if let Some(ref text) = args.text {
        poll_text(global, effective, text, timeout_ms, args.interval).await
    } else if let Some(ref selector) = args.selector {
        poll_selector(global, effective, selector, timeout_ms, args.interval).await
    } else {
        unreachable!("No condition specified — clap should have caught this");
    }
}

/// Poll for URL matching a glob pattern.
async fn poll_url(
    global: &GlobalOpts,
    managed: &agentchrome::connection::ManagedSession,
    pattern: &str,
    timeout_ms: u64,
    interval_ms: u64,
) -> Result<(), AppError> {
    let glob = GlobBuilder::new(pattern)
        .literal_separator(false)
        .build()
        .map_err(|e| AppError {
            message: format!("Invalid glob pattern: {e}"),
            code: agentchrome::error::ExitCode::GeneralError,
            custom_json: None,
        })?;
    let matcher = glob.compile_matcher();
    let deadline = Instant::now() + Duration::from_millis(timeout_ms);
    let interval = Duration::from_millis(interval_ms);

    // Immediate pre-check
    if check_url_condition(managed, &matcher).await {
        return finish_poll_wait(
            global,
            managed,
            "url",
            Some(pattern.to_string()),
            None,
            None,
        )
        .await;
    }

    loop {
        tokio::time::sleep(interval).await;
        if Instant::now() > deadline {
            return Err(AppError::wait_timeout(
                timeout_ms,
                &format!("url \"{pattern}\" not matched"),
            ));
        }
        if check_url_condition(managed, &matcher).await {
            return finish_poll_wait(
                global,
                managed,
                "url",
                Some(pattern.to_string()),
                None,
                None,
            )
            .await;
        }
    }
}

/// Poll for text appearing in page content.
async fn poll_text(
    global: &GlobalOpts,
    managed: &agentchrome::connection::ManagedSession,
    text: &str,
    timeout_ms: u64,
    interval_ms: u64,
) -> Result<(), AppError> {
    let deadline = Instant::now() + Duration::from_millis(timeout_ms);
    let interval = Duration::from_millis(interval_ms);

    if check_text_condition(managed, text).await {
        return finish_poll_wait(global, managed, "text", None, Some(text.to_string()), None).await;
    }

    loop {
        tokio::time::sleep(interval).await;
        if Instant::now() > deadline {
            return Err(AppError::wait_timeout(
                timeout_ms,
                &format!("text \"{text}\" not found"),
            ));
        }
        if check_text_condition(managed, text).await {
            return finish_poll_wait(global, managed, "text", None, Some(text.to_string()), None)
                .await;
        }
    }
}

/// Poll for a CSS selector matching an element.
async fn poll_selector(
    global: &GlobalOpts,
    managed: &agentchrome::connection::ManagedSession,
    selector: &str,
    timeout_ms: u64,
    interval_ms: u64,
) -> Result<(), AppError> {
    let deadline = Instant::now() + Duration::from_millis(timeout_ms);
    let interval = Duration::from_millis(interval_ms);

    if check_selector_condition(managed, selector).await {
        return finish_poll_wait(
            global,
            managed,
            "selector",
            None,
            None,
            Some(selector.to_string()),
        )
        .await;
    }

    loop {
        tokio::time::sleep(interval).await;
        if Instant::now() > deadline {
            return Err(AppError::wait_timeout(
                timeout_ms,
                &format!("selector \"{selector}\" not found"),
            ));
        }
        if check_selector_condition(managed, selector).await {
            return finish_poll_wait(
                global,
                managed,
                "selector",
                None,
                None,
                Some(selector.to_string()),
            )
            .await;
        }
    }
}

/// Build and output the `WaitResult` after a poll-based condition is met.
async fn finish_poll_wait(
    global: &GlobalOpts,
    managed: &agentchrome::connection::ManagedSession,
    condition: &str,
    pattern: Option<String>,
    text: Option<String>,
    selector: Option<String>,
) -> Result<(), AppError> {
    let (url, title) = get_page_info(managed).await?;
    let result = WaitResult {
        condition: condition.to_string(),
        matched: true,
        url,
        title,
        pattern,
        text,
        selector,
    };

    if global.output.plain {
        print_wait_plain(&result);
    } else {
        print_output(&result, &global.output)?;
    }

    Ok(())
}

/// Event-driven network idle wait path.
async fn execute_network_idle_wait(global: &GlobalOpts, timeout_ms: u64) -> Result<(), AppError> {
    let (_client, mut managed) = setup_session(global).await?;
    managed.ensure_domain("Runtime").await?;
    managed.ensure_domain("Network").await?;

    let req_rx = managed.subscribe("Network.requestWillBeSent").await?;
    let fin_rx = managed.subscribe("Network.loadingFinished").await?;
    let fail_rx = managed.subscribe("Network.loadingFailed").await?;

    wait_for_network_idle(req_rx, fin_rx, fail_rx, timeout_ms).await?;

    let (url, title) = get_page_info(&managed).await?;
    let result = WaitResult {
        condition: "network-idle".to_string(),
        matched: true,
        url,
        title,
        pattern: None,
        text: None,
        selector: None,
    };

    if global.output.plain {
        print_wait_plain(&result);
    } else {
        print_output(&result, &global.output)?;
    }

    Ok(())
}

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

#[cfg(test)]
mod tests {
    use globset::GlobBuilder;

    fn build_matcher(pattern: &str) -> globset::GlobMatcher {
        GlobBuilder::new(pattern)
            .literal_separator(false)
            .build()
            .unwrap()
            .compile_matcher()
    }

    #[test]
    fn glob_wildcard_matches_across_slashes() {
        let m = build_matcher("*/dashboard*");
        assert!(m.is_match("https://example.com/dashboard"));
        assert!(m.is_match("https://example.com/dashboard/settings"));
        assert!(m.is_match("http://localhost:3000/dashboard"));
    }

    #[test]
    fn glob_exact_url_match() {
        let m = build_matcher("https://example.com");
        assert!(m.is_match("https://example.com"));
        assert!(!m.is_match("https://example.com/path"));
    }

    #[test]
    fn glob_no_match() {
        let m = build_matcher("*/login*");
        assert!(!m.is_match("https://example.com/dashboard"));
        assert!(!m.is_match("https://example.com/"));
    }

    #[test]
    fn glob_star_matches_everything() {
        let m = build_matcher("*");
        assert!(m.is_match("https://example.com/anything/at/all"));
        assert!(m.is_match(""));
    }

    #[test]
    fn glob_complex_pattern() {
        let m = build_matcher("https://*.example.com/*");
        assert!(m.is_match("https://app.example.com/page"));
        assert!(m.is_match("https://sub.example.com/"));
    }

    #[test]
    fn wait_result_serialization_url_condition() {
        let result = super::WaitResult {
            condition: "url".to_string(),
            matched: true,
            url: "https://example.com/dashboard".to_string(),
            title: "Dashboard".to_string(),
            pattern: Some("*/dashboard*".to_string()),
            text: None,
            selector: None,
        };
        let json: serde_json::Value = serde_json::to_value(&result).unwrap();
        assert_eq!(json["condition"], "url");
        assert_eq!(json["matched"], true);
        assert_eq!(json["url"], "https://example.com/dashboard");
        assert_eq!(json["pattern"], "*/dashboard*");
        assert!(json.get("text").is_none());
        assert!(json.get("selector").is_none());
    }

    #[test]
    fn wait_result_serialization_text_condition() {
        let result = super::WaitResult {
            condition: "text".to_string(),
            matched: true,
            url: "https://example.com".to_string(),
            title: "Example".to_string(),
            pattern: None,
            text: Some("Products".to_string()),
            selector: None,
        };
        let json: serde_json::Value = serde_json::to_value(&result).unwrap();
        assert_eq!(json["condition"], "text");
        assert_eq!(json["text"], "Products");
        assert!(json.get("pattern").is_none());
        assert!(json.get("selector").is_none());
    }

    #[test]
    fn wait_result_serialization_selector_condition() {
        let result = super::WaitResult {
            condition: "selector".to_string(),
            matched: true,
            url: "https://example.com".to_string(),
            title: "Example".to_string(),
            pattern: None,
            text: None,
            selector: Some("#results-table".to_string()),
        };
        let json: serde_json::Value = serde_json::to_value(&result).unwrap();
        assert_eq!(json["condition"], "selector");
        assert_eq!(json["selector"], "#results-table");
        assert!(json.get("pattern").is_none());
        assert!(json.get("text").is_none());
    }

    #[test]
    fn wait_result_serialization_network_idle() {
        let result = super::WaitResult {
            condition: "network-idle".to_string(),
            matched: true,
            url: "https://example.com".to_string(),
            title: "Example".to_string(),
            pattern: None,
            text: None,
            selector: None,
        };
        let json: serde_json::Value = serde_json::to_value(&result).unwrap();
        assert_eq!(json["condition"], "network-idle");
        assert_eq!(json["matched"], true);
        assert!(json.get("pattern").is_none());
        assert!(json.get("text").is_none());
        assert!(json.get("selector").is_none());
    }
}