chrome-agent 0.11.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
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
use std::collections::HashMap;

use serde_json::json;

use crate::cdp::client::CdpClient;
use crate::commands;
use crate::element_ref::ElementRef;
use crate::session::{self, BrowserSession, SessionStore};

/// Connect to a page-level CDP endpoint with retry. Sets up Page domain,
/// console interceptor, and optionally Runtime domain + stealth patches.
pub async fn connect_page(
    http_endpoint: &str,
    target_id: &str,
    stealth: bool,
) -> Result<CdpClient, crate::BoxError> {
    let mut last_err = String::new();
    for attempt in 0..8u32 {
        match crate::browser::get_page_ws_url(http_endpoint, target_id).await {
            Ok(page_ws) => match CdpClient::connect(&page_ws).await {
                Ok(client) => {
                    // Verify connection is alive with a lightweight call
                    if let Err(e) = client.call::<_, serde_json::Value>(
                        "Runtime.evaluate",
                        json!({"expression": "1", "returnByValue": true}),
                    ).await {
                        last_err = format!("Connection verify failed: {e}");
                        drop(client);
                        if attempt < 7 {
                            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                        }
                        continue;
                    }
                    // Setup: enable Page domain
                    if let Err(e) = client.enable("Page").await {
                        last_err = format!("Page.enable failed: {e}");
                        drop(client);
                        if attempt < 7 {
                            tokio::time::sleep(std::time::Duration::from_millis(300)).await;
                        }
                        continue;
                    }
                    // Console interceptor
                    commands::console::inject(&client).await;
                    if stealth {
                        crate::setup::apply_stealth(&client).await;
                    } else {
                        let _ = client.enable("Runtime").await;
                    }
                    return Ok(client);
                }
                Err(e) => last_err = e.to_string(),
            },
            Err(e) => last_err = e.to_string(),
        }
        if attempt < 7 {
            tokio::time::sleep(std::time::Duration::from_millis(300)).await;
        }
    }
    Err(format!("Failed to connect to page after 8 attempts: {last_err}").into())
}


/// What an action reports about the page once it has run.
pub struct ActionReport {
    /// `--inspect`: the whole tree.
    pub inspect: bool,
    /// `--verdict auto`: what changed since the last snapshot of this page.
    pub changes: bool,
    /// Character cap on the change report. 0 removes it.
    pub budget: usize,
    pub max_depth: Option<usize>,
}

/// Reporting policy taken from the global flags, before `cli.command` is consumed.
#[derive(Clone, Copy)]
pub struct ReportPolicy {
    pub changes: bool,
    pub budget: usize,
}

impl ReportPolicy {
    /// Build the per-action report from the policy plus that command's own flags.
    pub const fn for_action(self, inspect: bool, max_depth: Option<usize>) -> ActionReport {
        ActionReport { inspect, changes: self.changes, budget: self.budget, max_depth }
    }
}

/// What a fill put in, and what the page kept. Emitted on every fill so a value that was
/// reformatted, truncated or rejected is visible rather than hidden behind "Filled".
pub fn fill_value_report(outcome: &crate::element::FillOutcome) -> serde_json::Value {
    let mut v = if outcome.sensitive {
        json!({
            "redacted": true,
            "requested_length": outcome.requested.chars().count(),
            "actual_length": outcome.actual.as_ref().map(|a| a.chars().count()),
            "verbatim": outcome.verbatim(),
        })
    } else {
        json!({
            "requested": outcome.requested,
            "actual": outcome.actual,
            "verbatim": outcome.verbatim(),
        })
    };
    // "The field holds X" is only true as of a moment. Saying which moment is the only
    // honest form of the claim: a page can revert at any time, and one did at 400ms.
    v["observed_after_ms"] = json!(outcome.observed_after_ms);
    if let Some(caveat) = &outcome.caveat {
        v["caveat"] = json!(caveat);
    }
    v
}

/// The uid of the node an action is about to touch, whichever way it was named.
///
/// Resolved before the action runs: afterwards the element may be detached, and the answer
/// would describe a different page. Returns the fields to merge into the response, so a
/// caller that has none of its own can pass this straight through.
pub async fn target_details(
    client: &CdpClient,
    selector: Option<&str>,
    uid: Option<&str>,
) -> Option<serde_json::Value> {
    let resolved = match (selector, uid) {
        (Some(sel), _) => crate::element::selector_uid(client, sel).await,
        // A uid-targeted action already names its node; echoing it keeps the field's
        // meaning the same whichever way the caller aimed.
        (None, Some(uid)) => Some(uid.to_string()),
        (None, None) => None,
    };
    resolved.map(|uid| json!({"uid": uid}))
}

/// Merge two optional field sets into one response object.
#[must_use]
pub fn merge_details(
    first: Option<serde_json::Value>,
    second: Option<serde_json::Value>,
) -> Option<serde_json::Value> {
    match (first, second) {
        (Some(mut a), Some(b)) => {
            if let (Some(target), Some(extra)) = (a.as_object_mut(), b.as_object()) {
                for (key, value) in extra {
                    target.insert(key.clone(), value.clone());
                }
            }
            Some(a)
        }
        (Some(only), None) | (None, Some(only)) => Some(only),
        (None, None) => None,
    }
}

/// Per-field report for a bulk fill: what each target was, and what it kept.
///
/// `key` is "uid" or "selector" depending on how the caller named the field. Secrets go
/// through the same redaction as a single fill — a bulk path that printed them would be a
/// way around it.
#[must_use]
pub fn bulk_fill_report(
    key: &str,
    outcomes: &[(String, crate::element::FillOutcome)],
) -> serde_json::Value {
    serde_json::Value::Array(
        outcomes
            .iter()
            .map(|(target, outcome)| json!({key: target, "value": fill_value_report(outcome)}))
            .collect(),
    )
}

/// Split a check/uncheck outcome into the message and the fields that go with it.
///
/// `observed_after_ms` is absent when the element already held the desired state: nothing
/// was dispatched, so claiming an observation window afterwards would invent one.
#[must_use]
pub fn check_report(outcome: crate::element::CheckOutcome) -> (String, Option<serde_json::Value>) {
    let details = outcome.observed_after_ms.map(|ms| json!({"observed_after_ms": ms}));
    (outcome.message, details)
}

/// Execute a command, report what it did to the page, and persist the new baseline.
///
/// By default an action now answers "what changed", not just "what I was asked to do".
/// Without it the agent has to spend a second call to find out whether the click landed,
/// and that extra turn is the cost this is meant to remove. `--verdict off` restores the
/// older behaviour for callers that would rather have the latency back.
pub async fn output_action(
    client: &CdpClient,
    store: &mut SessionStore,
    browser_name: &str,
    page_name: &str,
    target_id: &str,
    msg: String,
    report: &ActionReport,
    json_mode: bool,
) -> Result<(), crate::BoxError> {
    output_action_with(client, store, browser_name, page_name, target_id, msg, report, json_mode, None).await
}

/// `output_action` plus whatever the command itself observed — the value a fill left
/// behind, the window a check looked through. Merged at the top level of the response so
/// the CLI and the pipe dispatchers, which build their JSON separately, agree on shape.
#[allow(clippy::too_many_arguments)]
pub async fn output_action_with(
    client: &CdpClient,
    store: &mut SessionStore,
    browser_name: &str,
    page_name: &str,
    target_id: &str,
    msg: String,
    report: &ActionReport,
    json_mode: bool,
    details: Option<serde_json::Value>,
) -> Result<(), crate::BoxError> {
    let mut obj = json!({"ok": true, "message": msg});
    if let Some(fields) = details.as_ref().and_then(serde_json::Value::as_object) {
        for (key, value) in fields {
            obj[key.as_str()] = value.clone();
        }
    }
    let mut trailer = String::new();
    // Silence used to mean four different things here. Whatever happens below, the response
    // carries the one that applies.
    let mut observation = if report.changes {
        crate::verdict::Observation::NoBaseline
    } else {
        crate::verdict::Observation::ReportingDisabled
    };

    if report.inspect || report.changes {
        // Wait for the page to stop reacting rather than for a fixed guess: a page that
        // does nothing costs a quiet window, one that renders late is still caught.
        crate::snapshot::settle(client, 100, 1000).await;
        // The baseline is always full depth. Storing a `--max-depth` view would make the
        // next comparison read every node the limit cut off as newly added: verified, an
        // action with `--max-depth 1` then a plain `diff` invented additions.
        //
        // A read that fails is not an action that failed. This used to propagate with `?`,
        // so a click that had already been delivered came back as `ok:false` — and the
        // natural response to that is to click again, which is real. `pipe_dispatch` stated
        // the opposite policy in a comment and followed it; this is the CLI adopting it.
        let Ok(snapshot) = commands::inspect::run(client, false, None, None, None).await else {
            let assessment = crate::verdict::classify(crate::verdict::Observation::ReadFailed);
            attach_verdict(&mut obj, assessment);
            if json_mode {
                json_output(&obj);
            } else {
                println!("{msg}");
                println!("verdict: {} ({})", assessment.verdict, assessment.reason);
            }
            return Ok(());
        };

        if report.changes {
            let previous = store
                .browsers
                .get(browser_name)
                .and_then(|b| b.pages.get(page_name))
                .map(|p| {
                    (
                        p.last_snapshot.clone(),
                        p.last_snapshot_frame.clone().zip(p.last_snapshot_loader.clone()),
                    )
                });
            if let Some((Some(old_text), stored)) = previous {
                let identity = commands::diff::Identity::from_loader(
                    stored.as_ref().map(|(f, l)| (f.as_str(), l.as_str())),
                    snapshot.identity.as_ref().map(|(f, l)| (f.as_str(), l.as_str())),
                );
                let cmp = commands::diff::compare(identity, &old_text, &snapshot.text);
                let body = if report.budget == 0 {
                    cmp.text.clone()
                } else {
                    crate::truncate::truncate_str(
                        cmp.text.trim_end(),
                        report.budget,
                        "\n… truncated, run `inspect` for the rest",
                    )
                    .into_owned()
                };
                obj["changed"] = json!({
                    "added": cmp.added,
                    "removed": cmp.removed,
                    "changed": cmp.changed,
                    "unchanged": cmp.unchanged,
                    "moved": cmp.moved,
                    "anonymous": cmp.anonymous,
                    "document_changed": cmp.document_changed,
                    "identity_known": cmp.identity_known,
                });
                obj["delta"] = json!(body);
                observation = crate::verdict::Observation::Compared {
                    document_changed: cmp.document_changed,
                    identity_known: cmp.identity_known,
                    edits: cmp.added + cmp.removed + cmp.changed,
                    moved: cmp.moved,
                    focus_moved: cmp.focus_from.is_some() || cmp.focus_to.is_some(),
                };
                if cmp.focus_from.is_some() || cmp.focus_to.is_some() {
                    obj["focus"] = json!({"from": cmp.focus_from, "to": cmp.focus_to});
                }
                if let Some(hint) = cmp.hint {
                    obj["hint"] = json!(hint);
                }
                trailer = body;
            }
        }

        if report.inspect {
            // The caller asked to see the tree at their depth; the baseline above stays
            // full so the two never get confused.
            let shown = if report.max_depth.is_some() {
                commands::inspect::run(client, false, report.max_depth, None, None)
                    .await
                    .map_or_else(|_| snapshot.text.clone(), |s| s.text)
            } else {
                snapshot.text.clone()
            };
            obj["snapshot"] = json!(shown);
            trailer.clone_from(&shown);
        }

        if let Some(browser_s) = store.browsers.get_mut(browser_name) {
            let page = session::ensure_page(browser_s, page_name, target_id);
            page.last_snapshot = Some(snapshot.text);
            let (f, l) = snapshot.identity.map_or((None, None), |(f, l)| (Some(f), Some(l)));
            page.last_snapshot_frame = f;
            page.last_snapshot_loader = l;
            page.uid_map = snapshot.uid_map;
        }
    }

    let assessment = crate::verdict::classify(observation);
    attach_verdict(&mut obj, assessment);

    if json_mode {
        json_output(&obj);
    } else {
        println!("{msg}");
        if !trailer.is_empty() {
            println!("{}", trailer.trim_end());
        }
        println!("verdict: {} ({})", assessment.verdict, assessment.reason);
    }
    Ok(())
}

/// Write the verdict, its reason, and — when the verdict is an admission of ignorance —
/// what to do about it.
///
/// `hint` may already hold the diff's own advice (a navigation tells the caller its uids
/// are dead). The verdict's hint goes in its own field rather than overwriting it: two
/// different pieces of advice, one slot, and the more specific one loses.
pub fn attach_verdict(obj: &mut serde_json::Value, assessment: crate::verdict::Assessment) {
    obj["verdict"] = json!(assessment.verdict.as_str());
    obj["verdict_reason"] = json!(assessment.reason);
    if let Some(hint) = crate::verdict::hint_for(assessment) {
        obj["verdict_hint"] = json!(hint);
    }
}

/// Output goto result with optional post-inspect.
pub async fn output_goto(
    client: &CdpClient,
    store: &mut SessionStore,
    browser_name: &str,
    page_name: &str,
    target_id: &str,
    url: &str,
    title: &str,
    inspect: bool,
    max_depth: Option<usize>,
    json_mode: bool,
) -> Result<(), crate::BoxError> {
    let browser_session = store.browsers.get_mut(browser_name)
        .ok_or_else(|| format!("Browser session '{browser_name}' not found in session store"))?;
    let page = session::ensure_page(
        browser_session,
        page_name,
        target_id,
    );
    // The old document is gone, so every uid in the stored map now points at a node that
    // no longer exists — and `backendNodeId` counters overlap between documents, so a
    // stale uid can silently resolve to an unrelated element on the new page. Drop the
    // map here; the `if inspect` branches below refill it when the caller asked to see
    // the page. Without a fresh inspect the agent gets "uid not found" and a hint, which
    // is the correct answer.
    page.uid_map.clear();
    if json_mode {
        let mut obj = json!({"ok": true, "url": url, "title": title});
        if inspect {
            let snapshot = commands::inspect::run(client, false, max_depth, None, None).await?;
            obj["snapshot"] = json!(snapshot.text);
            page.last_snapshot = Some(snapshot.text);
            let (f, l) = snapshot.identity.map_or((None, None), |(f, l)| (Some(f), Some(l)));
            page.last_snapshot_frame = f;
            page.last_snapshot_loader = l;
            page.uid_map = snapshot.uid_map;
        }
        json_output(&obj);
    } else {
        if title.is_empty() {
            println!("{url}");
        } else {
            println!("{url}{title}");
        }
        if inspect {
            let snapshot = commands::inspect::run(client, false, max_depth, None, None).await?;
            println!("{}", snapshot.text);
            page.last_snapshot = Some(snapshot.text);
            let (f, l) = snapshot.identity.map_or((None, None), |(f, l)| (Some(f), Some(l)));
            page.last_snapshot_frame = f;
            page.last_snapshot_loader = l;
            page.uid_map = snapshot.uid_map;
        }
    }
    Ok(())
}

/// Print a `serde_json::Value` as a single compact JSON line to stdout.
pub fn json_output(value: &serde_json::Value) {
    println!("{}", serde_json::to_string(value).unwrap_or_default());
}

/// Provide a contextual hint for common errors.
pub fn error_hint(msg: &str) -> Option<&'static str> {
    // Chrome 136+ refuses CDP on the *default* user profile. chrome-agent launches
    // its own dedicated profile so this only bites when --connect points at a Chrome
    // started on the normal profile. Matched before the generic "Connection refused"
    // branch so the actionable hint wins.
    if msg.contains("Failed to connect to page") || msg.contains("DevToolsActivePort") {
        Some("Could not attach over CDP. Chrome 136+ disables remote debugging on the default profile: drop --connect to let chrome-agent launch its own dedicated profile, or relaunch your Chrome with a separate --user-data-dir.")
    } else if msg.contains("Connection refused") || msg.contains("No such file") {
        Some("Is Chrome running? Try: chrome-agent goto <url>")
    } else if msg.contains("uid=") && msg.contains("not found") {
        Some("Run `chrome-agent inspect` to refresh element uids")
    } else if msg.contains("Navigation failed") {
        Some("Check the URL is valid and the page is reachable")
    } else if msg.contains("No snapshot") || msg.contains("No inspect") || msg.contains("uid_map is empty") {
        Some("Run 'chrome-agent inspect' first")
    } else if msg.contains("Timeout") || msg.contains("timeout") {
        Some("Use --timeout N for slow pages")
    } else if msg.contains("not interactable") || msg.contains("no visible box model") {
        Some("Element may be hidden. Try: chrome-agent scroll <uid>")
    } else if msg.contains("No element matches selector") {
        Some("CSS selector didn't match. Check with: chrome-agent eval \"document.querySelector('...')\"")
    } else if msg.contains("backendDomNodeId") || msg.contains("response parse") {
        Some("Page structure issue. Try: chrome-agent click --selector or chrome-agent eval")
    } else if msg.contains("may not have an article") || msg.contains("Readability") {
        Some("Page has no article structure. Try: chrome-agent text or chrome-agent text --selector \"main\"")
    } else if msg.contains("Provide a uid") || msg.contains("Provide --uid") {
        Some("Specify what to target: uid (e.g. n47), --selector \"css\", or --xy x,y")
    } else if msg.contains("Evaluation error") || msg.contains("TypeError") || msg.contains("ReferenceError") || msg.contains("SyntaxError") {
        Some("JS error in page context. Check expression syntax. Use --selector to scope to an element.")
    } else if msg.contains("dispatcher task exited") || msg.contains("transport closed") {
        Some("Browser connection lost. Try running the command again.")
    } else if msg.contains("not an <iframe>") || msg.contains("not an <IFRAME>") {
        Some("Only <iframe> is supported. For <frame>/<frameset>, use eval to access frame content.")
    } else if msg.contains("No child frame found") {
        Some("Iframe not found. Check the selector matches an <iframe> element.")
    } else if msg.contains("not a <select>") {
        Some("Element is not a <select>. For custom dropdowns, click to open then click the option.")
    } else if msg.contains("No option matching") {
        Some("No dropdown option matched. Use inspect --uid to check available options, or try the visible text.")
    } else if msg.contains("File not found") {
        Some("Check the file path exists on disk.")
    } else if msg.contains("expected a JSON array") {
        Some("Batch expects a JSON array of commands on stdin: [{\"cmd\":\"inspect\"}, ...]")
    } else {
        None
    }
}

/// Get the `uid_map` from the current session, or empty if none.
pub fn get_uid_map(store: &SessionStore, browser_name: &str, page_name: &str) -> HashMap<String, ElementRef> {
    store
        .browsers
        .get(browser_name)
        .and_then(|b| b.pages.get(page_name))
        .map(|p| p.uid_map.clone())
        .unwrap_or_default()
}

/// Resolve the page target id: use existing from session, or pick first page, or create one.
pub async fn resolve_page_target(
    client: &CdpClient,
    browser_session: &mut BrowserSession,
    page_name: &str,
) -> Result<String, crate::BoxError> {
    if let Some(page) = browser_session.pages.get(page_name) {
        return Ok(page.target_id.clone());
    }

    if page_name == "default" {
        let result: crate::cdp::types::GetTargetsResult = client
            .call("Target.getTargets", serde_json::json!({}))
            .await?;

        let claimed_targets: std::collections::HashSet<&str> = browser_session
            .pages
            .values()
            .map(|p| p.target_id.as_str())
            .collect();

        let available = result
            .target_infos
            .iter()
            .find(|t| t.target_type == "page" && !claimed_targets.contains(t.target_id.as_str()));

        if let Some(target) = available {
            let target_id = target.target_id.clone();
            session::ensure_page(browser_session, page_name, &target_id);
            return Ok(target_id);
        }
    }

    let create_result: crate::cdp::types::CreateTargetResult = client
        .call(
            "Target.createTarget",
            crate::cdp::types::CreateTargetParams {
                url: "about:blank".into(),
                width: None,
                height: None,
                new_window: None,
                background: None,
            },
        )
        .await?;

    let target_id = create_result.target_id;
    session::ensure_page(browser_session, page_name, &target_id);
    Ok(target_id)
}

pub fn cmd_status(json_mode: bool) -> Result<(), crate::BoxError> {
    let store = session::load_session()?;
    let daemon_alive = session::daemon_socket_exists();

    if json_mode {
        let browsers: Vec<serde_json::Value> = store
            .browsers
            .iter()
            .map(|(name, b)| {
                json!({
                    "name": name,
                    "pid": b.pid,
                    "headless": b.headless,
                    "pages": b.pages.len(),
                    "ws": b.ws_endpoint,
                })
            })
            .collect();
        json_output(&json!({
            "ok": true,
            "browsers": browsers,
            "daemon": if daemon_alive { "running" } else { "stopped" },
        }));
    } else {
        if store.browsers.is_empty() {
            println!("No active browser sessions.");
        } else {
            for (name, browser) in &store.browsers {
                let status = if let Some(pid) = browser.pid {
                    format!("pid={pid}")
                } else {
                    "external".into()
                };
                let mode = if browser.headless { "headless" } else { "headed" };
                println!(
                    "browser={name}  {status}  {mode}  pages={}  ws={}",
                    browser.pages.len(),
                    browser.ws_endpoint
                );
            }
        }

        println!(
            "daemon: {}",
            if daemon_alive { "running" } else { "stopped" }
        );
    }

    Ok(())
}

/// Message for `cmd_stop`, given whether we actually reached a live daemon.
/// Pure so the stop decision can be unit-tested without a socket.
#[cfg(any(unix, test))]
const fn stop_message(reached_daemon: bool) -> &'static str {
    if reached_daemon {
        "Daemon stopped."
    } else {
        "Daemon is not running."
    }
}

pub async fn cmd_stop(json_mode: bool) -> Result<(), crate::BoxError> {
    #[cfg(not(unix))]
    {
        let msg = "Daemon is not supported on this platform.";
        if json_mode { json_output(&json!({"ok": true, "message": msg})); }
        else { println!("{msg}"); }
        return Ok(());
    }

    #[cfg(unix)]
    {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::UnixStream;

    let socket_path = session::daemon_socket_path()?;

    // Try to reach the daemon. A missing socket — or a stale one left by a
    // crashed daemon (connect yields ECONNREFUSED) — both mean "not running".
    // Don't let the raw connect error escape via `?`; clean the stale socket
    // and report the friendly path instead.
    let stream = if socket_path.exists() {
        match UnixStream::connect(&socket_path).await {
            Ok(stream) => Some(stream),
            Err(_) => {
                let _ = std::fs::remove_file(&socket_path);
                None
            }
        }
    } else {
        None
    };

    let Some(mut stream) = stream else {
        let msg = stop_message(false);
        if json_mode { json_output(&json!({"ok": true, "message": msg})); }
        else { println!("{msg}"); }
        return Ok(());
    };

    stream
        .write_all(b"{\"command\":\"stop\"}\n")
        .await?;
    stream.shutdown().await?;

    let mut buf = Vec::new();
    let _ = stream.read_to_end(&mut buf).await;

    let msg = stop_message(true);
    if json_mode { json_output(&json!({"ok": true, "message": msg})); }
    else { println!("{msg}"); }
    Ok(())
    } // #[cfg(unix)]
}

/// Whether this command can own the browser named by `--browser`, and may therefore
/// take it down when interrupted.
///
/// `--browser` is a global flag, so every invocation carries a name — defaulted to
/// `"default"`, the one most single-agent users get — including the commands that never
/// open a browser at all. `run::run` returns before the connection block for each of
/// these; arming the handler for them meant Ctrl+C during a read-only `status` killed
/// whichever agent happened to hold that name. `close` is excluded for the opposite
/// reason: it kills its own pid deliberately, and does not need a second, racier path.
#[must_use]
pub const fn interrupt_owns_browser(command: &crate::cli::Command) -> bool {
    use crate::cli::Command as C;
    !matches!(
        command,
        C::Daemon { .. } | C::Status | C::Stop | C::Close { .. } | C::History { .. }
    )
}

/// The pid this invocation may kill on interrupt: its own browser's, and no other.
///
/// The Ctrl+C handler used to walk every entry in `sessions.json` — a file shared by
/// every agent on the machine — so interrupting one agent killed the Chrome of every
/// other agent running under a different `--browser` name, which is exactly the
/// isolation the flag exists to provide.
#[must_use]
pub fn interrupt_kill_target(store: &SessionStore, browser_name: &str) -> Option<u32> {
    store.browsers.get(browser_name).and_then(|b| b.pid)
}

/// Whether `comm` (the executable per `ps -o comm=`) is a browser this tool could have
/// launched. The kill below is gated on it — see `kill_pid`.
///
/// A plain substring match on "chrome" is not enough: this tool's own binary is named
/// `chrome-agent`, and `chromedriver` exists too. Under the exact PID-reuse race the
/// guard is for, a reused pid landing on a sibling chrome-agent process would have been
/// classified as a browser and killed — the scenario the guard claims to prevent.
#[cfg(any(unix, test))]
fn is_browser_process(comm: &str) -> bool {
    let base = comm.rsplit('/').next().unwrap_or(comm).to_ascii_lowercase();
    if base.contains("chrome-agent") || base.contains("chromedriver") {
        return false;
    }
    base.contains("chrome") || base.contains("chromium") || base.contains("headless_shell")
}

/// Kill a managed-browser process (best-effort, unix only). Killing the
/// main Chrome process is enough — its helper processes exit with it.
///
/// Guarded against PID reuse: a stored pid may have died and been reassigned by the
/// OS to an unrelated process, and signalling whatever holds the number now is data
/// loss, not cleanup. The executable is checked first; a pid that is gone, or that
/// no longer names a browser, is left alone. The check-then-kill window is
/// milliseconds — not zero, but no longer unbounded.
pub fn kill_pid(pid: u32) {
    #[cfg(unix)]
    {
        let comm = std::process::Command::new("ps")
            .args(["-p", &pid.to_string(), "-o", "comm="])
            .output()
            .ok()
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());
        if comm.as_deref().is_some_and(|c| !c.is_empty() && is_browser_process(c)) {
            let _ = std::process::Command::new("kill")
                .arg(pid.to_string())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status();
        }
    }
    #[cfg(not(unix))]
    {
        let _ = pid;
    }
}

pub fn cmd_close(browser_name: &str, purge: bool, json_mode: bool) -> Result<(), crate::BoxError> {
    let mut store = session::load_session()?;

    let browser = store.browsers.remove(browser_name);

    let message = match browser {
        Some(b) => {
            if let Some(pid) = b.pid {
                kill_pid(pid);
                format!("Closed browser={browser_name} (pid={pid})")
            } else {
                format!("Removed external browser session: {browser_name}")
            }
        }
        None => {
            format!("No browser session named '{browser_name}'.")
        }
    };

    // Purge browser profile if requested
    if purge
        && let Some(home) = dirs::home_dir() {
            let profile_dir = home.join(".chrome-agent").join("browsers").join(browser_name);
            if profile_dir.exists() {
                // Wait briefly for Chrome to exit after kill, then retry purge
                for _ in 0..5 {
                    if std::fs::remove_dir_all(&profile_dir).is_ok() {
                        break;
                    }
                    std::thread::sleep(std::time::Duration::from_millis(500));
                }
            }
        }

    let message = if purge {
        format!("{message} (profile purged)")
    } else {
        message
    };

    if json_mode {
        json_output(&json!({"ok": true, "message": message}));
    } else {
        println!("{message}");
    }

    session::save_session(&mut store)?;
    Ok(())
}

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

    #[test]
    fn kill_pid_refuses_a_pid_that_no_longer_belongs_to_a_browser() {
        // A stored pid can be reaped and reassigned by the OS to an unrelated
        // process. Killing whatever holds the number now is data loss, not cleanup.
        let mut child = std::process::Command::new("sleep")
            .arg("30")
            .spawn()
            .expect("spawn a stand-in for the reused pid");
        kill_pid(child.id());
        std::thread::sleep(std::time::Duration::from_millis(300));
        let status = child.try_wait().expect("poll the stand-in");
        let survived = status.is_none();
        let _ = child.kill();
        let _ = child.wait();
        assert!(survived, "kill_pid killed an unrelated process holding a reused pid");
    }

    #[test]
    fn a_command_that_never_opens_a_browser_has_none_to_interrupt() {
        // `--browser` is global, so these carry the default name and would otherwise
        // kill whichever agent happens to be using it — while never having touched it.
        // Each of these returns from `run::run` before the connection block.
        use crate::cli::Command as C;
        for command in [
            C::Daemon { action: crate::cli::DaemonAction::Start },
            C::Status,
            C::Stop,
            C::Close { purge: false },
            C::History { filter: None, limit: 20 },
        ] {
            assert!(
                !interrupt_owns_browser(&command),
                "this command never opens a browser, so it has none to kill"
            );
        }
        // Anything that does connect keeps the cleanup.
        assert!(interrupt_owns_browser(&C::Tabs));
        assert!(interrupt_owns_browser(&C::Pipe));
    }

    #[test]
    fn an_interrupt_only_targets_this_invocation_s_browser() {
        let mut store = SessionStore::default();
        session::ensure_browser(&mut store, "agent-1", "ws://a", Some(111), true, None);
        session::ensure_browser(&mut store, "agent-2", "ws://b", Some(222), true, None);

        assert_eq!(interrupt_kill_target(&store, "agent-1"), Some(111));
        assert_eq!(
            interrupt_kill_target(&store, "agent-2"),
            Some(222),
            "a sibling agent's browser is never this invocation's to kill"
        );
        assert_eq!(interrupt_kill_target(&store, "never-launched"), None);
    }

    #[test]
    fn browser_executables_are_recognised_and_bystanders_are_not() {
        for browser in [
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            "chrome",
            "chromium",
            "chromium-browser",
            "headless_shell",
            "Google Chrome for Testing",
        ] {
            assert!(is_browser_process(browser), "should recognise {browser}");
        }
        for bystander in [
            "sleep",
            "postgres",
            "/usr/bin/python3",
            "node",
            // The guard's own binary contains "chrome": under the PID-reuse race it
            // protects against, a sibling chrome-agent must not be classified as prey.
            "chrome-agent",
            "/tmp/chrome-agent",
            "chromedriver",
        ] {
            assert!(!is_browser_process(bystander), "must not kill {bystander}");
        }
    }

    #[test]
    fn bug_error_hint_covers_all_cases() {
        // Verify all error patterns have hints
        assert!(error_hint("Connection refused").is_some());
        assert!(error_hint("uid=n5 not found").is_some());
        assert!(error_hint("Navigation failed").is_some());
        assert!(error_hint("No snapshot").is_some());
        assert!(error_hint("Timeout waiting").is_some());
        assert!(error_hint("not interactable").is_some());
        assert!(error_hint("No element matches selector").is_some());
        assert!(error_hint("response parse error").is_some());
        assert!(error_hint("Readability failed").is_some());
        assert!(error_hint("Provide a uid").is_some());
        assert!(error_hint("Evaluation error: TypeError: foo").is_some());
        assert!(error_hint("dispatcher task exited").is_some());
        // v0.4.0 new command hints
        assert!(error_hint("Element is not an <iframe>").is_some());
        assert!(error_hint("No child frame found for selector").is_some());
        assert!(error_hint("Element is not a <select>").is_some());
        assert!(error_hint("No option matching: foo").is_some());
        assert!(error_hint("File not found: /tmp/nope").is_some());
        assert!(error_hint("batch: expected a JSON array").is_some());
        // Unknown errors should return None
        assert!(error_hint("something random").is_none());
    }

    #[test]
    fn connect_failure_hints_at_chrome_136() {
        // The page-attach failure and the missing-port marker both point the user
        // at the Chrome 136+ default-profile restriction and the --connect workaround.
        for msg in [
            "Failed to connect to page after 8 attempts: Connection refused",
            "DevToolsActivePort file doesn't exist",
        ] {
            let hint = error_hint(msg).expect("connect failure should have a hint");
            assert!(hint.contains("136"), "hint should mention Chrome 136: {hint}");
            assert!(hint.contains("--connect"), "hint should mention --connect: {hint}");
        }
    }

    #[test]
    fn plain_connection_refused_keeps_generic_hint() {
        // A bare "Connection refused" (no page-attach context) must NOT be hijacked
        // by the 136 branch — it keeps the generic "is Chrome running?" hint.
        let hint = error_hint("Connection refused").unwrap();
        assert!(hint.contains("Chrome running"));
        assert!(!hint.contains("136"));
    }

    #[test]
    fn stop_message_reflects_daemon_reachability() {
        // Regression for A3c: a stale socket (connect refused) must map to the
        // friendly "not running" path, not a raw propagated error. The reached=false
        // branch is exactly what cmd_stop selects when connect fails.
        assert_eq!(stop_message(true), "Daemon stopped.");
        assert_eq!(stop_message(false), "Daemon is not running.");
    }
}