agentchrome 1.51.5

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
use std::path::Path;
use std::process::Command;

use serde::Serialize;
use serde_json::{Map, Value};

use agentchrome::connection::{resolve_connection, resolve_target};
use agentchrome::error::{AppError, ExitCode};

use crate::cli::{AuditArgs, AuditCommand, AuditLighthouseArgs, GlobalOpts};
use crate::output;

/// Valid Lighthouse category names.
const VALID_CATEGORIES: &[&str] = &[
    "performance",
    "accessibility",
    "best-practices",
    "seo",
    "pwa",
];

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

/// Build the `{categories, total_issues, failing_audit_ids}` summary for
/// `audit lighthouse` large-response objects.
///
/// `total_issues` and `failing_audit_ids` are serialized as `null` because the
/// scores-only object carries only per-category scores — the failing-audit list
/// lives in the full Lighthouse report, not in the summary input.
fn summary_of_audit(value: &Value) -> Value {
    let Some(obj) = value.as_object() else {
        return serde_json::json!({
            "categories": Value::Null,
            "total_issues": Value::Null,
            "failing_audit_ids": Value::Null,
        });
    };

    let mut categories = Vec::new();
    for (key, score) in obj {
        if key == "url" {
            continue;
        }
        categories.push(serde_json::json!({
            "id": key,
            "score": score,
        }));
    }

    serde_json::json!({
        "categories": categories,
        "total_issues": Value::Null,
        "failing_audit_ids": Value::Null,
    })
}

pub async fn execute_audit(global: &GlobalOpts, args: &AuditArgs) -> Result<(), AppError> {
    match &args.command {
        AuditCommand::Lighthouse(lh_args) => execute_lighthouse(global, lh_args).await,
    }
}

async fn execute_lighthouse(
    global: &GlobalOpts,
    args: &AuditLighthouseArgs,
) -> Result<(), AppError> {
    // --install-prereqs runs before resolve_connection: the install path does not
    // need an active Chrome session.
    if args.install_prereqs {
        return install_lighthouse_prereqs();
    }

    // 1. Resolve the Chrome connection to get the port.
    let conn = resolve_connection(&global.host, global.port, global.ws_url.as_deref()).await?;

    // 2. Determine the URL to audit.
    let url = if let Some(u) = &args.url {
        u.clone()
    } else {
        // No explicit URL — use the current page's URL.
        let target = resolve_target(
            &conn.host,
            conn.port,
            global.tab.as_deref(),
            global.page_id.as_deref(),
        )
        .await?;
        target.url
    };

    // 3. Find the lighthouse binary.
    find_lighthouse_binary()?;

    // 4. Validate --only categories.
    let categories = validate_categories(args.only.as_deref())?;

    // 5. Build and execute the lighthouse command.
    let mut cmd = std::process::Command::new("lighthouse");
    cmd.arg(&url)
        .arg("--port")
        .arg(conn.port.to_string())
        .arg("--output")
        .arg("json")
        .arg("--chrome-flags=--headless");

    if let Some(ref cats) = categories {
        let joined = cats.join(",");
        cmd.arg(format!("--only-categories={joined}"));
    }

    let output = cmd.output().map_err(|e| AppError {
        message: format!("failed to execute lighthouse: {e}"),
        code: ExitCode::GeneralError,
        custom_json: None,
    })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(AppError {
            message: format!("lighthouse exited with error: {}", stderr.trim()),
            code: ExitCode::GeneralError,
            custom_json: None,
        });
    }

    // 6. Parse stdout JSON and extract scores.
    let raw_json: Value = serde_json::from_slice(&output.stdout).map_err(|e| AppError {
        message: format!("failed to parse lighthouse JSON output: {e}"),
        code: ExitCode::GeneralError,
        custom_json: None,
    })?;

    let scores = extract_scores(&raw_json, categories.as_deref(), &url);

    // 7. Optionally write full report to file.
    if let Some(ref path) = args.output_file {
        write_report(path, &output.stdout)?;
    }

    // 8. Print scores JSON to stdout via the large-response gate.
    output::emit(
        &scores,
        &global.output,
        "audit lighthouse",
        summary_of_audit,
    )?;

    Ok(())
}

/// Surfaces both the direct `npm install` hint and the `--install-prereqs`
/// self-service path in a single error so one invocation emits exactly one
/// JSON error object on stderr.
const LIGHTHOUSE_NOT_FOUND_MESSAGE: &str = "lighthouse binary not found. Install it with: npm install -g lighthouse\nOr run: agentchrome audit lighthouse --install-prereqs";

fn general_error(message: impl Into<String>) -> AppError {
    AppError {
        message: message.into(),
        code: ExitCode::GeneralError,
        custom_json: None,
    }
}

/// Check that the `lighthouse` binary is available on PATH.
fn find_lighthouse_binary() -> Result<(), AppError> {
    if probe_version("lighthouse").is_some() {
        return Ok(());
    }
    Err(general_error(LIGHTHOUSE_NOT_FOUND_MESSAGE))
}

fn probe_version(bin: &str) -> Option<String> {
    probe_version_with(&|| Command::new(bin))
}

fn probe_version_with(factory: &dyn Fn() -> Command) -> Option<String> {
    let mut cmd = factory();
    cmd.arg("--version");
    let output = cmd.output().ok()?;
    if !output.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

#[derive(Serialize)]
struct InstallPrereqsResult {
    installed: &'static str,
    version: String,
}

fn install_lighthouse_prereqs() -> Result<(), AppError> {
    install_lighthouse_prereqs_with(&npm_factory)
}

/// On Windows, `npm` ships as `npm.cmd` and `CreateProcess` does not honor
/// `PATHEXT`, so we probe the bare name and fall back to `npm.cmd`.
fn npm_factory() -> Command {
    if cfg!(windows) && Command::new("npm").arg("--version").output().is_err() {
        return Command::new("npm.cmd");
    }
    Command::new("npm")
}

fn install_lighthouse_prereqs_with(npm_factory: &dyn Fn() -> Command) -> Result<(), AppError> {
    if probe_version_with(npm_factory).is_none() {
        return Err(general_error(
            "npm not found on PATH — install Node.js first",
        ));
    }

    let output = npm_factory()
        .args(["install", "-g", "lighthouse"])
        .output()
        .map_err(|e| general_error(format!("Failed to invoke npm: {e}")))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        let detail = if stderr.is_empty() {
            format!("npm exited with status {}", output.status)
        } else {
            stderr
        };
        return Err(general_error(format!(
            "Failed to install lighthouse: {detail}"
        )));
    }

    let version = probe_version("lighthouse").ok_or_else(|| {
        general_error("lighthouse installed but not on PATH — open a new shell and retry")
    })?;

    let payload = InstallPrereqsResult {
        installed: "lighthouse",
        version,
    };
    let json = serde_json::to_string(&payload)
        .map_err(|e| general_error(format!("serialization error: {e}")))?;
    println!("{json}");

    Ok(())
}

/// Validate the `--only` category filter.
///
/// Returns `None` if no filter was specified (all categories).
/// Returns `Some(vec)` with validated category names.
fn validate_categories(only: Option<&str>) -> Result<Option<Vec<String>>, AppError> {
    let Some(only) = only else {
        return Ok(None);
    };

    let cats: Vec<String> = only.split(',').map(|s| s.trim().to_string()).collect();

    for cat in &cats {
        if !VALID_CATEGORIES.contains(&cat.as_str()) {
            return Err(AppError {
                message: format!(
                    "invalid category '{cat}'. Valid categories: {}",
                    VALID_CATEGORIES.join(", ")
                ),
                code: ExitCode::GeneralError,
                custom_json: None,
            });
        }
    }

    Ok(Some(cats))
}

/// Extract category scores from the Lighthouse JSON output.
fn extract_scores(raw: &Value, categories: Option<&[String]>, url: &str) -> Value {
    let mut result = Map::new();
    result.insert("url".to_string(), Value::String(url.to_string()));

    let cats_to_check: Vec<&str> = match categories {
        Some(cats) => cats.iter().map(String::as_str).collect(),
        None => VALID_CATEGORIES.to_vec(),
    };

    let lh_categories = &raw["categories"];

    for cat in cats_to_check {
        let score = &lh_categories[cat]["score"];
        if let Some(n) = score.as_f64() {
            result.insert(
                cat.to_string(),
                Value::Number(serde_json::Number::from_f64(n).unwrap_or_else(|| {
                    // NaN/Inf can't be represented — fall back to 0
                    serde_json::Number::from(0)
                })),
            );
        } else {
            result.insert(cat.to_string(), Value::Null);
        }
    }

    Value::Object(result)
}

/// Write the raw Lighthouse JSON report to a file.
fn write_report(path: &Path, data: &[u8]) -> Result<(), AppError> {
    std::fs::write(path, data).map_err(|e| AppError {
        message: format!("failed to write report to {}: {e}", path.display()),
        code: ExitCode::GeneralError,
        custom_json: None,
    })
}

// =============================================================================
// Script runner adapter
// =============================================================================

/// Run an `audit` command against an existing session and return a JSON value.
///
/// # Errors
///
/// Propagates `AppError` from the underlying audit logic.
#[allow(dead_code)]
pub async fn run_from_session(
    _managed: &mut agentchrome::connection::ManagedSession,
    global: &GlobalOpts,
    args: &AuditArgs,
) -> Result<serde_json::Value, AppError> {
    execute_audit(global, args).await?;
    Ok(serde_json::json!({"executed": true}))
}

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

    #[test]
    fn validate_categories_valid() {
        let result = validate_categories(Some("performance,accessibility")).unwrap();
        assert_eq!(
            result,
            Some(vec!["performance".to_string(), "accessibility".to_string()])
        );
    }

    #[test]
    fn validate_categories_invalid() {
        let result = validate_categories(Some("performance,bogus"));
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("bogus"));
    }

    #[test]
    fn validate_categories_none() {
        let result = validate_categories(None).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn validate_categories_all_valid() {
        let result =
            validate_categories(Some("performance,accessibility,best-practices,seo,pwa")).unwrap();
        assert_eq!(result.as_ref().unwrap().len(), 5);
    }

    #[test]
    fn validate_categories_trimmed() {
        let result = validate_categories(Some(" performance , seo ")).unwrap();
        assert_eq!(
            result,
            Some(vec!["performance".to_string(), "seo".to_string()])
        );
    }

    #[test]
    fn extract_scores_all_categories() {
        let raw = json!({
            "categories": {
                "performance": {"score": 0.95},
                "accessibility": {"score": 0.88},
                "best-practices": {"score": 1.0},
                "seo": {"score": 0.92},
                "pwa": {"score": 0.5}
            }
        });

        let scores = extract_scores(&raw, None, "https://example.com");
        let obj = scores.as_object().unwrap();

        assert_eq!(obj["url"], "https://example.com");
        assert_eq!(obj["performance"], 0.95);
        assert_eq!(obj["accessibility"], 0.88);
        assert_eq!(obj["best-practices"], 1.0);
        assert_eq!(obj["seo"], 0.92);
        assert_eq!(obj["pwa"], 0.5);
    }

    #[test]
    fn extract_scores_filtered() {
        let raw = json!({
            "categories": {
                "performance": {"score": 0.95},
                "accessibility": {"score": 0.88},
                "best-practices": {"score": 1.0},
                "seo": {"score": 0.92},
                "pwa": {"score": 0.5}
            }
        });

        let filter = vec!["performance".to_string(), "seo".to_string()];
        let scores = extract_scores(&raw, Some(&filter), "https://example.com");
        let obj = scores.as_object().unwrap();

        assert_eq!(obj.len(), 3); // url + 2 categories
        assert_eq!(obj["performance"], 0.95);
        assert_eq!(obj["seo"], 0.92);
        assert!(!obj.contains_key("accessibility"));
        assert!(!obj.contains_key("best-practices"));
        assert!(!obj.contains_key("pwa"));
    }

    #[test]
    fn extract_scores_null_score() {
        let raw = json!({
            "categories": {
                "performance": {"score": null},
                "accessibility": {"score": 0.88}
            }
        });

        let filter = vec!["performance".to_string(), "accessibility".to_string()];
        let scores = extract_scores(&raw, Some(&filter), "https://example.com");
        let obj = scores.as_object().unwrap();

        assert!(obj["performance"].is_null());
        assert_eq!(obj["accessibility"], 0.88);
    }

    #[test]
    fn lighthouse_not_found_message_mentions_both_paths() {
        assert!(LIGHTHOUSE_NOT_FOUND_MESSAGE.contains("npm install -g lighthouse"));
        assert!(LIGHTHOUSE_NOT_FOUND_MESSAGE.contains("--install-prereqs"));
    }

    #[test]
    fn install_prereqs_errors_when_npm_missing() {
        let npm = || Command::new("/nonexistent/definitely-not-npm-binary-xyz");
        let err = install_lighthouse_prereqs_with(&npm).unwrap_err();
        assert!(
            err.message.contains("npm not found on PATH"),
            "expected npm-missing error, got: {}",
            err.message
        );
        assert!(err.message.contains("Node.js"));
    }

    #[test]
    #[cfg(unix)]
    fn install_prereqs_errors_when_npm_install_fails() {
        // `sh -c SCRIPT $0 $1 $2...` — the factory builds `sh -c SCRIPT sh` so that
        // $0=sh and $1 is whatever probe/install appends. --version succeeds, install fails.
        let npm = || {
            let mut c = Command::new("sh");
            c.arg("-c")
                .arg(r#"case "$1" in --version) echo 10.0.0; exit 0;; install) echo "npm err" >&2; exit 1;; esac"#)
                .arg("sh");
            c
        };
        let err = install_lighthouse_prereqs_with(&npm).unwrap_err();
        assert!(
            err.message.contains("Failed to install lighthouse"),
            "got: {}",
            err.message
        );
        assert!(
            err.message.contains("npm err"),
            "expected stderr capture, got: {}",
            err.message
        );
    }

    #[test]
    fn extract_scores_missing_categories_key() {
        let raw = json!({});

        let scores = extract_scores(&raw, None, "https://example.com");
        let obj = scores.as_object().unwrap();

        assert_eq!(obj["url"], "https://example.com");
        // All categories should be null when the categories key is missing
        for cat in VALID_CATEGORIES {
            assert!(obj[*cat].is_null(), "expected null for {cat}");
        }
    }

    // -------------------------------------------------------------------------
    // summary_of_audit tests
    // -------------------------------------------------------------------------

    #[test]
    fn summary_of_audit_happy_path_shape() {
        let scores = json!({
            "url": "https://example.com",
            "performance": 0.95,
            "accessibility": 0.88,
        });
        let summary = summary_of_audit(&scores);
        let obj = summary.as_object().unwrap();
        assert!(obj.contains_key("categories"), "must have categories key");
        assert!(
            obj.contains_key("total_issues"),
            "must have total_issues key"
        );
        assert!(
            obj.contains_key("failing_audit_ids"),
            "must have failing_audit_ids key"
        );
        // total_issues and failing_audit_ids are null (not measurable from scores object)
        assert!(obj["total_issues"].is_null());
        assert!(obj["failing_audit_ids"].is_null());
        let cats = obj["categories"].as_array().unwrap();
        // Should have 2 category entries (url key is excluded)
        assert_eq!(cats.len(), 2);
        for cat in cats {
            assert!(cat["id"].is_string());
            // score can be a number (measurable) or null
        }
    }

    #[test]
    fn summary_of_audit_null_score_is_preserved() {
        let scores = json!({
            "url": "https://example.com",
            "pwa": null,
        });
        let summary = summary_of_audit(&scores);
        let cats = summary["categories"].as_array().unwrap();
        assert_eq!(cats.len(), 1);
        assert_eq!(cats[0]["id"], "pwa");
        assert!(cats[0]["score"].is_null());
    }

    #[test]
    fn summary_of_audit_non_object_returns_null_fields() {
        let summary = summary_of_audit(&json!([1, 2, 3]));
        assert!(summary["categories"].is_null());
        assert!(summary["total_issues"].is_null());
        assert!(summary["failing_audit_ids"].is_null());
    }
}