chrome-agent 0.7.0

Browser automation for AI agents. Single binary, zero deps, CDP direct to Chrome.
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
use std::path::PathBuf;
use std::process::Command;

fn binary() -> String {
    let mut path = std::env::current_exe()
        .unwrap()
        .parent()
        .unwrap()
        .parent()
        .unwrap()
        .to_path_buf();
    path.push("chrome-agent");
    path.to_string_lossy().into_owned()
}

fn fixture_url(name: &str) -> String {
    let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    path.push("tests/fixtures");
    path.push(name);
    format!("file://{}", path.display())
}

fn run_cli(args: &[&str]) -> (String, String, i32) {
    let output = Command::new(binary())
        .args(args)
        .output()
        .expect("Failed to run chrome-agent");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let code = output.status.code().unwrap_or(-1);
    (stdout, stderr, code)
}

fn chrome_available() -> bool {
    let candidates = if cfg!(target_os = "macos") {
        vec!["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"]
    } else {
        vec!["google-chrome", "chromium"]
    };
    for candidate in candidates {
        if std::path::Path::new(candidate).exists() {
            return true;
        }
        if Command::new("which")
            .arg(candidate)
            .output()
            .is_ok_and(|o| o.status.success())
        {
            return true;
        }
    }
    false
}

fn goto_fixture(browser: &str, fixture: &str) -> bool {
    let url = fixture_url(fixture);
    let (_, stderr, code) = run_cli(&["--browser", browser, "goto", &url]);
    if code != 0 {
        eprintln!("SKIP: goto failed for {fixture}: {stderr}");
        return false;
    }
    true
}

fn extract_json(browser: &str) -> Option<serde_json::Value> {
    let (stdout, stderr, code) = run_cli(&["--json", "--browser", browser, "extract"]);
    if code != 0 {
        eprintln!("extract failed: {stderr} {stdout}");
        return None;
    }
    for line in stdout.lines() {
        if line.starts_with('{')
            && let Ok(v) = serde_json::from_str::<serde_json::Value>(line) {
                return Some(v);
            }
    }
    None
}

fn extract_json_with_args(browser: &str, args: &[&str]) -> Option<serde_json::Value> {
    let mut full_args = vec!["--json", "--browser", browser, "extract"];
    full_args.extend_from_slice(args);
    let (stdout, stderr, code) = run_cli(&full_args);
    if code != 0 {
        eprintln!("extract failed: {stderr} {stdout}");
        return None;
    }
    for line in stdout.lines() {
        if line.starts_with('{')
            && let Ok(v) = serde_json::from_str::<serde_json::Value>(line) {
                return Some(v);
            }
    }
    None
}

fn cleanup(browser: &str) {
    let _ = run_cli(&["--browser", browser, "close", "--purge"]);
}

/// RAII guard: closes browser on drop (even on panic).
struct TestBrowser(&'static str);

impl TestBrowser {
    const fn new(name: &'static str) -> Self {
        Self(name)
    }
    const fn name(&self) -> &str {
        self.0
    }
}

impl Drop for TestBrowser {
    fn drop(&mut self) {
        cleanup(self.0);
    }
}

// ─── Product table: should extract TR rows with links and prices ───

#[test]
fn extract_table_finds_product_rows() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-table");
    if !goto_fixture(b.name(), "extract_table.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 5, "Should find 5 product rows, got {count}");
    assert!(items.len() >= 5, "Should return 5 items");

    let first = &items[0];
    assert!(first.get("title").and_then(|v| v.as_str()).is_some(), "First item should have title: {first}");
    assert!(first.get("url").and_then(|v| v.as_str()).is_some(), "First item should have URL: {first}");

    let pattern = json["pattern"].as_str().unwrap_or("");
    assert!(pattern.contains("TR") || pattern.contains("tr"), "Pattern should be TR-based, got: {pattern}");
}

// ─── Blog cards: should extract article elements ───

#[test]
fn extract_cards_finds_articles() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-cards");
    if !goto_fixture(b.name(), "extract_cards.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 4, "Should find 4 blog cards, got {count}");

    let pattern = json["pattern"].as_str().unwrap_or("");
    assert!(
        pattern.contains("ARTICLE") || pattern.contains("article") || pattern.contains("post"),
        "Pattern should be ARTICLE-based, got: {pattern}"
    );

    let first = &items[0];
    let title = first.get("title").and_then(|v| v.as_str()).unwrap_or("");
    assert!(title.contains("Rust Async"), "First title should mention Rust Async, got: {title}");

    assert!(items.iter().any(|item| item.get("date").is_some()), "Should have date fields");
    assert!(items.iter().any(|item| item.get("image").is_some()), "Should have image fields");
}

// ─── HN-like: should pick item-rows, not vote links or spacers ───

#[test]
fn extract_hn_like_finds_stories_not_vote_links() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-hn");
    if !goto_fixture(b.name(), "extract_hn_like.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 4, "Should find 4 news items, got {count}");

    for item in items {
        let title = item.get("title").and_then(|v| v.as_str()).unwrap_or("");
        assert!(!title.contains("") && title.len() > 5, "Title should be article, not vote: '{title}'");
    }

    for item in items {
        let url = item.get("url").and_then(|v| v.as_str()).unwrap_or("");
        assert!(!url.contains("/vote/"), "URL should be article URL, not vote: {url}");
    }
}

// ─── E-commerce: should prefer product cards over nav/footer links ───

#[test]
fn extract_ecommerce_finds_products_not_nav() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-ecom");
    if !goto_fixture(b.name(), "extract_ecommerce.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 4, "Should find 4 product cards, got {count}");

    let pattern = json["pattern"].as_str().unwrap_or("");
    assert!(!pattern.to_uppercase().contains("NAV"), "Should not extract nav pattern: {pattern}");

    let first = &items[0];
    let title = first.get("title").and_then(|v| v.as_str()).unwrap_or("");
    assert!(title.len() > 5, "Product should have meaningful title, got: '{title}'");

    assert!(items.iter().any(|item| item.get("price").is_some()), "Should have price fields");
    assert!(items.iter().any(|item| item.get("image").is_some()), "Should have image fields");
}

// ─── Search results list ───

#[test]
fn extract_list_finds_search_results() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-list");
    if !goto_fixture(b.name(), "extract_list.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 4, "Should find >=4 search results, got {count}");

    let pattern = json["pattern"].as_str().unwrap_or("");
    assert!(pattern.contains("LI") || pattern.contains("li"), "Pattern should be LI-based, got: {pattern}");

    for (i, item) in items.iter().enumerate() {
        let title = item.get("title").and_then(|v| v.as_str()).unwrap_or("");
        let url = item.get("url").and_then(|v| v.as_str()).unwrap_or("");
        assert!(title.len() > 5, "Item {i} should have title, got: '{title}'");
        assert!(!url.is_empty(), "Item {i} should have URL");
    }
}

// ─── Nav-heavy page: should extract feature cards, not nav links ───

#[test]
fn extract_nested_nav_prefers_content_over_navigation() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-nav");
    if !goto_fixture(b.name(), "extract_nested_nav.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 4, "Should find 4 feature cards, got {count}");

    let titles: Vec<&str> = items.iter().filter_map(|item| item.get("title").and_then(|v| v.as_str())).collect();
    let nav_titles = ["Home", "Features", "Pricing", "Docs", "Blog", "Login"];
    for title in &titles {
        assert!(!nav_titles.contains(title), "Should not extract nav link '{title}'");
    }
}

// ─── No pattern page: should return error ───

#[test]
fn extract_no_pattern_returns_error() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-nopattern");
    if !goto_fixture(b.name(), "extract_no_pattern.html") { return; }

    let (stdout, _, code) = run_cli(&["--json", "--browser", b.name(), "extract"]);

    if code == 0 {
        for line in stdout.lines() {
            if line.starts_with('{')
                && let Ok(json) = serde_json::from_str::<serde_json::Value>(line) {
                    let items = json["items"].as_array().map_or(0, std::vec::Vec::len);
                    assert!(items <= 1, "No-pattern page should have <=1 items, got {items}");
                    break;
                }
        }
    }
}

// ─── Mixed page (dashboard): should extract activity feed ───

#[test]
fn extract_mixed_finds_activity_feed() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-mixed");
    if !goto_fixture(b.name(), "extract_mixed.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 4, "Should find 4 activity items, got {count}");
    assert!(items.iter().any(|item| item.get("date").is_some()), "Should have dates");
    assert!(items.iter().any(|item| item.get("image").is_some()), "Should have images");
}

// ─── Extract with --selector scoping ───

#[test]
fn extract_with_selector_scopes_correctly() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-selector");
    if !goto_fixture(b.name(), "extract_ecommerce.html") { return; }

    let json = extract_json_with_args(b.name(), &["--selector", ".product-grid"]);

    if let Some(json) = json {
        let count = json["count"].as_u64().unwrap_or(0);
        assert!(count >= 4, "Scoped extract should find 4 products, got {count}");
    }
}

// ─── Extract with --limit ───

#[test]
fn extract_limit_caps_results() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-limit");
    if !goto_fixture(b.name(), "extract_list.html") { return; }

    let json = extract_json_with_args(b.name(), &["--limit", "2"]);

    if let Some(json) = json {
        let items_len = json["items"].as_array().map_or(0, std::vec::Vec::len);
        assert_eq!(items_len, 2, "Limit should cap to 2 items, got {items_len}");
        let count = json["count"].as_u64().unwrap_or(0);
        assert!(count >= 4, "Total count should be >=4, got {count}");
    }
}

// ─── Link-heavy nav: should prefer job listings over nav links ───
// MDR heuristic: text-to-link ratio filters navigation regions

#[test]
fn extract_link_heavy_nav_prefers_content() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-linknav");
    if !goto_fixture(b.name(), "extract_link_heavy_nav.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 4, "Should find 4 job listings, got {count}");

    for item in items {
        let title = item.get("title").and_then(|v| v.as_str()).unwrap_or("");
        assert!(!title.starts_with("Page "), "Should not extract nav link '{title}'");
    }

    assert!(items.iter().any(|item| item.get("date").is_some()), "Job listings should have dates");
}

// ─── FAQ definition list ───

#[test]
fn extract_faq_items() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-faq");
    if !goto_fixture(b.name(), "extract_definition_list.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 5, "Should find 5 FAQ items, got {count}");

    for (i, item) in items.iter().enumerate() {
        let title = item.get("title").and_then(|v| v.as_str()).unwrap_or("");
        assert!(title.len() > 5, "FAQ item {i} should have question, got: '{title}'");
    }
}

// ─── Semantic classes: classes matching /card|item|repo/ boost detection ───

#[test]
fn extract_semantic_classes_boost() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-semclass");
    if !goto_fixture(b.name(), "extract_semantic_classes.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 4, "Should find 4 repo cards, got {count}");

    let first_title = items[0].get("title").and_then(|v| v.as_str()).unwrap_or("");
    assert!(
        first_title.contains("chrome-agent") || first_title.contains("dev-browser"),
        "First item should be repo, got: '{first_title}'"
    );

    assert!(items.iter().any(|item| item.get("date").is_some()), "Should have dates");
}

// ─── Ads interleaved: should extract articles, not ads ───

#[test]
fn extract_ads_interleaved_finds_articles() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-ads");
    if !goto_fixture(b.name(), "extract_ads_interleaved.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 4, "Should find 4 articles, got {count}");

    let pattern = json["pattern"].as_str().unwrap_or("");
    assert!(
        pattern.contains("ARTICLE") || pattern.contains("story"),
        "Pattern should be article-based, got: {pattern}"
    );

    for item in items {
        let title = item.get("title").and_then(|v| v.as_str()).unwrap_or("");
        assert!(!title.contains("Sponsored"), "Should not extract ads: '{title}'");
    }

    assert!(items.iter().any(|item| item.get("date").is_some()), "Should have dates");
}

// ─── Flat table (leaderboard) ───

#[test]
fn extract_flat_table_rows() {
    if !chrome_available() { eprintln!("SKIP: Chrome not found"); return; }
    let b = TestBrowser::new("ext-ftable");
    if !goto_fixture(b.name(), "extract_flat_table.html") { return; }

    let json = extract_json(b.name());

    let json = json.expect("extract should return JSON");
    let items = json["items"].as_array().expect("items array");
    let count = json["count"].as_u64().unwrap_or(0);

    assert!(count >= 7, "Should find 7 leaderboard rows, got {count}");

    let first = &items[0];
    let title = first.get("title").and_then(|v| v.as_str()).unwrap_or("");
    assert!(title.contains("alice") || title.contains("dev"), "First should be username, got: '{title}'");

    let first_url = first.get("url").and_then(|v| v.as_str()).unwrap_or("");
    assert!(first_url.contains("/u/"), "Should link to user profile, got: {first_url}");
}