opencrabs 0.3.43

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
//! Browser Manager
//!
//! Smart browser detection: finds the user's default/preferred Chromium-based
//! browser, connects to a running instance when possible, or launches a new one.
//! Manages named page sessions (tabs) for concurrent browsing.

use base64::Engine;
use chromiumoxide::browser::BrowserConfig;
use chromiumoxide::{Browser, Page};
use futures::StreamExt;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;

use crate::config::BrowserConfig as ConfigBrowserConfig;

/// Shared browser manager. Clone-safe via inner `Arc`.
#[derive(Clone)]
pub struct BrowserManager {
    inner: Arc<Mutex<ManagerInner>>,
    config: Arc<ConfigBrowserConfig>,
}

struct ManagerInner {
    browser: Option<Browser>,
    pages: HashMap<String, Page>,
    handler_handle: Option<tokio::task::JoinHandle<()>>,
    headless: bool,
    /// Per-session hash of the most recent screenshot bytes. Lets
    /// `browser_screenshot` reject a no-op repeat without sending another
    /// identical 25KB image into the LLM context. Updated on every
    /// successful screenshot; never explicitly invalidated — when the
    /// page genuinely changes the new bytes will hash differently.
    last_screenshot_hash: HashMap<uuid::Uuid, u64>,
}

/// Best-effort cleanup when the last `BrowserManager` clone (and
/// therefore the inner Arc) is dropped — typically app exit.
///
/// Previously, opencrabs shutdown left the CDP handler task running
/// as a tokio zombie and the headed Chrome process alive (visible
/// window, orphaned Arc<Browser>), since no signal handler or Drop
/// impl closed either. Subsequent opencrabs restarts would then hit
/// the SingletonLock path (fixed in P0) or fight over the user's
/// profile.
///
/// Drop can't be async, so we do the synchronous subset: abort the
/// handler task (JoinHandle::abort is sync and cancels the future at
/// the next await point), and drop the Browser option — Browser's own
/// Drop closes the CDP connection, which causes headless Chrome to
/// exit. Headed Chrome typically remains running visually until the
/// user closes it, which matches user expectations.
impl Drop for ManagerInner {
    fn drop(&mut self) {
        if self.browser.is_none() && self.handler_handle.is_none() {
            return; // never launched
        }
        self.pages.clear();
        self.browser.take();
        if let Some(h) = self.handler_handle.take() {
            h.abort();
        }
        tracing::debug!("browser: ManagerInner dropped — handler aborted, CDP closed");
    }
}

/// Normalize a user-configured CDP endpoint for `Browser::connect`.
///
/// chromey resolves the real `/devtools/browser/<id>` websocket URL via the
/// `/json/version` endpoint ONLY when the URL scheme is `http`/`https`. A bare
/// `ws://host:port` (no devtools path) is handed straight to the websocket
/// client, and Chromium rejects the upgrade on the root path — so the
/// documented `ws://localhost:9222` form would silently fail to connect.
///
/// This rewrites a path-less `ws://`/`wss://` endpoint to `http://`/`https://`
/// so resolution kicks in. A full devtools websocket URL (one that already has
/// a `/devtools/...` path) is left untouched, as is any `http(s)` endpoint.
pub(crate) fn normalize_cdp_endpoint(endpoint: &str) -> String {
    let trimmed = endpoint.trim().trim_end_matches('/');
    for (ws_scheme, http_scheme) in [("ws://", "http://"), ("wss://", "https://")] {
        if let Some(rest) = trimmed.strip_prefix(ws_scheme) {
            // Path-less host:port → rewrite scheme so /json/version resolution runs.
            // A real devtools URL contains a path and is left as-is.
            if !rest.contains('/') {
                return format!("{http_scheme}{rest}");
            }
            return endpoint.to_string();
        }
    }
    endpoint.to_string()
}

impl Default for BrowserManager {
    fn default() -> Self {
        Self::new(ConfigBrowserConfig::default())
    }
}

impl BrowserManager {
    pub fn new(config: ConfigBrowserConfig) -> Self {
        // Auto-detect: use headed mode only if a display is available
        let headless = !Self::has_display();
        if headless {
            tracing::info!("No display detected — browser will run headless");
        }
        Self::with_headless(headless, config)
    }

    /// Create a browser manager with explicit headless/headed mode.
    pub fn with_headless(headless: bool, config: ConfigBrowserConfig) -> Self {
        Self {
            inner: Arc::new(Mutex::new(ManagerInner {
                browser: None,
                pages: HashMap::new(),
                handler_handle: None,
                headless,
                last_screenshot_hash: HashMap::new(),
            })),
            config: Arc::new(config),
        }
    }

    /// Detect whether a display server is available (X11, Wayland, or macOS/Windows).
    pub(crate) fn has_display() -> bool {
        if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
            // macOS and Windows always have a display (unless headless server, rare)
            true
        } else {
            // Linux/Unix: check for DISPLAY (X11) or WAYLAND_DISPLAY
            std::env::var("DISPLAY").is_ok() || std::env::var("WAYLAND_DISPLAY").is_ok()
        }
    }

    /// Switch between headless and headed mode. Shuts down the current browser
    /// if the mode changes — the next page request will relaunch in the new mode.
    pub async fn set_headless(&self, headless: bool) -> bool {
        let mut inner = self.inner.lock().await;
        if inner.headless == headless {
            return false; // no change
        }
        // Prevent headed mode on headless environments (VPS without display)
        if !headless && !Self::has_display() {
            tracing::warn!("Cannot switch to headed mode — no display detected. Staying headless.");
            return false;
        }
        inner.headless = headless;
        // Tear down existing browser so it relaunches in the new mode
        inner.pages.clear();
        inner.browser.take();
        if let Some(handle) = inner.handler_handle.take() {
            handle.abort();
        }
        tracing::info!(
            "Browser mode switched to {}",
            if headless { "headless" } else { "headed" }
        );
        true
    }

    /// Returns the current headless mode.
    pub async fn is_headless(&self) -> bool {
        self.inner.lock().await.headless
    }

    /// Ensure the browser is launched. No-op if already running and the
    /// handler task is still alive.
    ///
    /// When the underlying Chrome process dies (OS kill, CDP socket
    /// break, OOM, user closed the window) the handler task completes
    /// and `handler_handle.is_finished()` becomes true. The Browser
    /// object is still in the map but its CDP channel is dead — the
    /// next `page.goto()` returns `Navigation failed: channel closed`
    /// (2026-04-19 09:49 log). We detect that here and relaunch.
    async fn ensure_browser(&self) -> anyhow::Result<()> {
        let mut inner = self.inner.lock().await;
        if inner.browser.is_some() && !handler_is_dead(inner.handler_handle.as_ref()) {
            return Ok(());
        }
        if inner.browser.is_some() {
            tracing::warn!(
                "browser: CDP handler task is dead — tearing down stale Browser handle and relaunching"
            );
            inner.pages.clear();
            inner.browser.take();
            if let Some(h) = inner.handler_handle.take() {
                h.abort();
            }
        }

        // If a CDP endpoint is configured, connect to it instead of launching
        // a new browser. This allows multiple profiles to share a single
        // Chromium instance, saving significant memory.
        if let Some(ref endpoint) = self.config.cdp_endpoint {
            // chromey's Browser::connect only auto-resolves the real
            // /devtools/browser/<id> websocket URL when the endpoint is an
            // http(s) URL (it queries /json/version). A bare `ws://host:port`
            // would be handed straight to the websocket client and Chromium
            // rejects the upgrade on the root path. Normalize a path-less
            // ws/wss endpoint to http/https so resolution kicks in — so both
            // `ws://localhost:9222` and `http://localhost:9222` work.
            let resolved = normalize_cdp_endpoint(endpoint);
            tracing::info!(
                "Connecting to existing Chromium instance at {endpoint} (resolved: {resolved})"
            );
            let (browser, mut handler) = Browser::connect(&resolved).await.map_err(|e| {
                anyhow::anyhow!(
                    "Failed to connect to CDP endpoint {endpoint} (resolved {resolved}): {e}"
                )
            })?;

            let handle = tokio::spawn(async move {
                while let Some(event) = handler.next().await {
                    if event.is_err() {
                        tracing::warn!("CDP handler error, browser connection may be lost");
                        break;
                    }
                }
            });

            inner.browser = Some(browser);
            inner.handler_handle = Some(handle);
            tracing::info!("Connected to external Chromium via CDP at {endpoint}");
            return Ok(());
        }

        let mode = if inner.headless { "headless" } else { "headed" };

        // Smart browser detection: default browser first, then any Chromium-based browser
        let detected = detect_browser();
        let browser_name = detected
            .as_ref()
            .map(|b| b.name.as_str())
            .unwrap_or("Chrome");
        let browser_path_for_log = detected
            .as_ref()
            .map(|b| b.path.display().to_string())
            .unwrap_or_else(|| "<chromey default>".to_string());
        tracing::info!("Launching {mode} {browser_name} via CDP (binary: {browser_path_for_log})");

        let mut builder = BrowserConfig::builder();
        builder = builder.no_sandbox().window_size(1280, 720);
        if !inner.headless {
            builder = builder.with_head();
        }
        // Bump launch_timeout from chromey's default 20s to 60s. The
        // 2026-04-22 13:54 failure showed Brave on macOS occasionally
        // taking longer than 20s to print its `DevTools listening on
        // ws://...` line — 30s gap between two retries followed by a
        // BrowserStderr("") timeout. macOS app-bundle binaries can be
        // slow to print stderr when LaunchServices is in the loop, and
        // chromey's only wedge-recovery is the timeout. 60s gives slow
        // launches room without making real failures take noticeably
        // longer to surface.
        builder = builder.launch_timeout(std::time::Duration::from_secs(60));
        if let Some(ref info) = detected {
            builder = builder.chrome_executable(&info.path);
        }

        // Use the browser's own profile so the user's logins/cookies are available.
        // Falls back to our own profile dir if we can't find the browser's profile
        // or if it's locked by a running instance.
        //
        // Retry the lock check with exponential backoff before falling
        // through to the fallback. When the user's main browser is
        // *starting up*, Chrome briefly holds the profile lock before
        // releasing it for additional instances — falling straight
        // through on the first locked check drops the user into the
        // empty opencrabs fallback profile and silently loses all
        // their logins/cookies. Cap at ~10s total wait
        // (250ms → 500 → 1000 → 2000 → 4000 ≈ 7.75s; next retry
        // would exceed the cap so we stop).
        let native_profile = detected.as_ref().and_then(|b| b.user_data_dir.clone());
        let used_native;
        let profile_dir = match native_profile {
            Some(p) if p.exists() && wait_for_profile_unlock(&p, 10_000).await => {
                used_native = true;
                p
            }
            _ => {
                used_native = false;
                let fallback = crate::config::opencrabs_home().join("chrome-profile");
                if !fallback.exists() {
                    let _ = std::fs::create_dir_all(&fallback);
                }
                fallback
            }
        };

        // Sweep stale lock files in our OWN fallback profile before launch.
        // The 2026-04-11 / 17 logs all had the same failure: a previous
        // opencrabs Chrome process crashed, leaving `SingletonLock` behind
        // in `~/.opencrabs/chrome-profile`, and the next launch refused to
        // start with "Failed to create SingletonLock: File exists (17)".
        // Restricted to the opencrabs-owned fallback path — never touch
        // the user's native Chrome/Brave profile locks (that's their
        // running browser).
        let fallback_root = crate::config::opencrabs_home().join("chrome-profile");
        if profile_dir == fallback_root {
            clean_stale_locks(&profile_dir);
        }

        tracing::info!(
            "Browser profile: {} ({})",
            profile_dir.display(),
            if used_native {
                "native — has user logins/cookies"
            } else {
                "fallback — fresh, no user state"
            },
        );
        builder = builder.user_data_dir(profile_dir);

        // Stealth flags — reduce bot detection fingerprinting
        builder = builder
            .arg("--disable-blink-features=AutomationControlled")
            .arg("--disable-features=AutomationControlled")
            .arg("--disable-infobars")
            .arg("--disable-background-timer-throttling")
            .arg("--disable-backgrounding-occluded-windows")
            .arg("--disable-renderer-backgrounding")
            .arg("--disable-ipc-flooding-protection")
            .arg("--lang=en-US,en");

        let config = builder
            .build()
            .map_err(|e| anyhow::anyhow!("BrowserConfig error: {e}"))?;

        // Error message says the actual browser name we tried to launch
        // (Brave / Chrome / Edge / etc.). Hardcoding "Chrome" here was
        // confusing — users saw "Failed to launch Chrome" while we'd
        // actually been launching Brave, and assumed we'd ignored their
        // default browser entirely.
        let (browser, mut handler) = Browser::launch(config)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to launch {browser_name}: {e}"))?;

        let handle = tokio::spawn(async move {
            while let Some(event) = handler.next().await {
                if event.is_err() {
                    tracing::warn!("CDP handler error, browser connection may be lost");
                    break;
                }
            }
        });

        inner.browser = Some(browser);
        inner.handler_handle = Some(handle);
        tracing::info!("{mode} {browser_name} launched successfully");
        Ok(())
    }

    /// Get or create a page keyed on an agent session id. Each agent
    /// session gets its own tab so concurrent turns on different
    /// sessions can't stomp on each other's DOM state (fixes P5 from
    /// the 2026-04-19 browser audit).
    pub async fn get_or_create_session_page(&self, session_id: uuid::Uuid) -> anyhow::Result<Page> {
        self.get_or_create_page(Some(&Self::page_name_for_session(session_id)))
            .await
    }

    /// Format a session id as the tab-name key the manager stores. The
    /// `session-` prefix is load-bearing — it keeps session tabs out
    /// of the old "default" namespace so a pre-P5 caller and a
    /// session-aware caller never collide on the same key.
    pub(crate) fn page_name_for_session(session_id: uuid::Uuid) -> String {
        format!("session-{}", session_id)
    }

    /// Get or create a named page (tab). Default name is "default".
    pub async fn get_or_create_page(&self, name: Option<&str>) -> anyhow::Result<Page> {
        self.ensure_browser().await?;
        let session_name = name.unwrap_or("default").to_string();

        let mut inner = self.inner.lock().await;
        if let Some(page) = inner.pages.get(&session_name) {
            return Ok(page.clone());
        }

        let browser = inner
            .browser
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Browser not initialized"))?;

        let page = browser
            .new_page("about:blank")
            .await
            .map_err(|e| anyhow::anyhow!("Failed to create page: {e}"))?;

        // Register stealth patches via CDP's addScriptToEvaluateOnNewDocument
        // so they re-apply automatically on every navigation — including
        // cross-origin hops. Previously this was a one-shot `page.evaluate`
        // on page creation, so the patches survived same-document updates
        // but got reset on any full navigation (the JS context is
        // destroyed + rebuilt). Anti-bot scanners detect the half-patched
        // state; the new-document registration fixes this.
        Self::install_stealth_on_new_document(&page).await;

        inner.pages.insert(session_name, page.clone());
        Ok(page)
    }

    /// Register stealth JS via `Page.addScriptToEvaluateOnNewDocument`
    /// so Chrome runs it on every document creation — including full
    /// cross-origin navigations — without the caller needing to
    /// re-inject after each `goto`.
    async fn install_stealth_on_new_document(page: &Page) {
        if let Err(e) = page
            .add_script_to_evaluate_on_new_document(Some(STEALTH_JS.to_string()))
            .await
        {
            tracing::warn!("Stealth JS injection failed: {e}");
        }
    }

    /// Attach a screenshot to `result` for the given session's page.
    /// On success pushes the image and records `screenshot=ok` in the
    /// metadata. On failure appends a short explanatory note to the
    /// tool output and records `screenshot=failed` — the model used to
    /// see the primary text reply but had no way to know the visual
    /// it expected was missing.
    pub async fn attach_screenshot(
        &self,
        session_id: uuid::Uuid,
        result: &mut crate::brain::tools::ToolResult,
    ) {
        match self.take_screenshot_for_session(session_id).await {
            Some(img) => {
                result.images.push(img);
                result
                    .metadata
                    .insert("screenshot".to_string(), "ok".to_string());
            }
            None => {
                result
                    .output
                    .push_str("\n\n[screenshot unavailable — the page may not be rendered yet]");
                result
                    .metadata
                    .insert("screenshot".to_string(), "failed".to_string());
            }
        }
    }

    /// Take a screenshot of the session's page and return
    /// (media_type, base64_data). Never errors out — returns None if
    /// no page exists for the session or the capture fails.
    pub async fn take_screenshot_for_session(
        &self,
        session_id: uuid::Uuid,
    ) -> Option<(String, String)> {
        let key = Self::page_name_for_session(session_id);
        // Clone the Page handle while holding the lock briefly, then drop
        // the guard BEFORE awaiting the CDP screenshot call. Holding the
        // mutex across `.screenshot().await` blocks every other task that
        // needs the same mutex (handler events, page creation, page
        // close) for the entire round-trip — a deadlock hazard whenever
        // the CDP handler task wants to acquire the lock during the
        // screenshot. Page is an Arc-wrapped handle so the clone is
        // cheap.
        let page = {
            let inner = self.inner.lock().await;
            inner.pages.get(&key)?.clone()
        };
        let bytes = page
            .screenshot(
                chromiumoxide::cdp::browser_protocol::page::CaptureScreenshotParams::builder()
                    .format(
                        chromiumoxide::cdp::browser_protocol::page::CaptureScreenshotFormat::Png,
                    )
                    .build(),
            )
            .await
            .ok()?;
        let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
        Some(("image/png".to_string(), b64))
    }

    /// Legacy: take a screenshot of the hardcoded "default" page.
    /// Kept for any non-session-aware caller; session-aware tools
    /// should use `take_screenshot_for_session`.
    pub async fn take_screenshot(&self) -> Option<(String, String)> {
        // Same clone-then-drop-lock pattern as
        // `take_screenshot_for_session` to avoid holding the mutex across
        // the awaited CDP call.
        let page = {
            let inner = self.inner.lock().await;
            inner.pages.get("default")?.clone()
        };
        let bytes = page
            .screenshot(
                chromiumoxide::cdp::browser_protocol::page::CaptureScreenshotParams::builder()
                    .format(
                        chromiumoxide::cdp::browser_protocol::page::CaptureScreenshotFormat::Png,
                    )
                    .build(),
            )
            .await
            .ok()?;
        let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
        Some(("image/png".to_string(), b64))
    }

    /// Close a named page session.
    ///
    /// Removes the Page handle from the HashMap AND issues
    /// `Target.closeTarget` over CDP so the actual Chrome tab closes —
    /// dropping the Arc-wrapped Page alone may not trigger the close on
    /// chromiumoxide's side. Returns true if a session by that name
    /// existed; the CDP close itself is best-effort and logged on
    /// failure (the tab may have already been closed externally).
    pub async fn close_page(&self, name: &str) -> bool {
        // Take the page out of the HashMap while holding the lock briefly.
        let removed = {
            let mut inner = self.inner.lock().await;
            inner.pages.remove(name)
        };
        match removed {
            Some(page) => {
                if let Err(e) = page.close().await {
                    tracing::warn!(
                        "browser: CDP close_target failed for page '{name}' \
                         (tab may already be closed externally): {e}"
                    );
                }
                true
            }
            None => false,
        }
    }

    /// Close the page for a given agent session.
    pub async fn close_page_for_session(&self, session_id: uuid::Uuid) -> bool {
        self.close_page(&Self::page_name_for_session(session_id))
            .await
    }

    /// List active page session names.
    pub async fn list_pages(&self) -> Vec<String> {
        let inner = self.inner.lock().await;
        inner.pages.keys().cloned().collect()
    }

    /// Hash some screenshot bytes — used by `browser_screenshot` to detect
    /// no-op repeats. SipHash 1-3 (std DefaultHasher) is plenty for
    /// "are these two PNG byte vectors identical".
    pub fn hash_screenshot_bytes(bytes: &[u8]) -> u64 {
        use std::hash::{Hash, Hasher};
        let mut h = std::collections::hash_map::DefaultHasher::new();
        bytes.hash(&mut h);
        h.finish()
    }

    /// Returns the previous hash for a session, if any. Lets the screenshot
    /// tool compare against the last capture and decide whether to short-
    /// circuit with a "page unchanged" error.
    pub async fn last_screenshot_hash(&self, session_id: uuid::Uuid) -> Option<u64> {
        self.inner
            .lock()
            .await
            .last_screenshot_hash
            .get(&session_id)
            .copied()
    }

    /// Record the hash of a screenshot for `session_id`. Subsequent calls
    /// to `last_screenshot_hash` return this value until a new capture
    /// overwrites it.
    pub async fn set_last_screenshot_hash(&self, session_id: uuid::Uuid, hash: u64) {
        self.inner
            .lock()
            .await
            .last_screenshot_hash
            .insert(session_id, hash);
    }

    /// Shut down the browser entirely.
    pub async fn shutdown(&self) {
        let mut inner = self.inner.lock().await;
        inner.pages.clear();
        inner.browser.take();
        if let Some(handle) = inner.handler_handle.take() {
            handle.abort();
        }
        tracing::info!("Browser shut down");
    }
}

/// Detected browser info.
struct BrowserInfo {
    name: String,
    path: PathBuf,
    /// The browser's native user-data directory (where cookies/logins live).
    user_data_dir: Option<PathBuf>,
}

/// All known Chromium-based browsers with their executable paths and profile dirs.
struct BrowserCandidate {
    name: &'static str,
    /// Bundle ID (macOS) or desktop file (Linux) or ProgId (Windows) for default detection.
    #[cfg(target_os = "macos")]
    bundle_id: &'static str,
    #[cfg(target_os = "linux")]
    desktop_file: &'static str,
    #[cfg(target_os = "windows")]
    prog_id: &'static str,
    paths: &'static [&'static str],
    /// PATH lookup names (e.g. "brave-browser", "google-chrome").
    which_names: &'static [&'static str],
    /// User data dir relative to platform config root.
    #[cfg(target_os = "macos")]
    profile_dir: Option<&'static str>,
    #[cfg(target_os = "linux")]
    profile_dir: Option<&'static str>,
    #[cfg(target_os = "windows")]
    profile_dir: Option<&'static str>,
}

/// Known Chromium-based browsers in preference order (most popular first).
fn known_browsers() -> Vec<BrowserCandidate> {
    vec![
        BrowserCandidate {
            name: "Google Chrome",
            #[cfg(target_os = "macos")]
            bundle_id: "com.google.chrome",
            #[cfg(target_os = "linux")]
            desktop_file: "google-chrome.desktop",
            #[cfg(target_os = "windows")]
            prog_id: "ChromeHTML",
            paths: if cfg!(target_os = "macos") {
                &["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"]
            } else if cfg!(target_os = "windows") {
                &[
                    r"C:\Program Files\Google\Chrome\Application\chrome.exe",
                    r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
                ]
            } else {
                &["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome"]
            },
            which_names: &["google-chrome-stable", "google-chrome"],
            #[cfg(target_os = "macos")]
            profile_dir: Some("Google/Chrome"),
            #[cfg(target_os = "linux")]
            profile_dir: Some("google-chrome"),
            #[cfg(target_os = "windows")]
            profile_dir: Some(r"Google\Chrome\User Data"),
        },
        BrowserCandidate {
            name: "Brave",
            #[cfg(target_os = "macos")]
            bundle_id: "com.brave.Browser",
            #[cfg(target_os = "linux")]
            desktop_file: "brave-browser.desktop",
            #[cfg(target_os = "windows")]
            prog_id: "BraveHTML",
            paths: if cfg!(target_os = "macos") {
                &["/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"]
            } else if cfg!(target_os = "windows") {
                &[r"C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe"]
            } else {
                &[
                    "/usr/bin/brave-browser",
                    "/usr/bin/brave",
                    "/opt/brave.com/brave/brave",
                ]
            },
            which_names: &["brave-browser", "brave"],
            #[cfg(target_os = "macos")]
            profile_dir: Some("BraveSoftware/Brave-Browser"),
            #[cfg(target_os = "linux")]
            profile_dir: Some("BraveSoftware/Brave-Browser"),
            #[cfg(target_os = "windows")]
            profile_dir: Some(r"BraveSoftware\Brave-Browser\User Data"),
        },
        BrowserCandidate {
            name: "Microsoft Edge",
            #[cfg(target_os = "macos")]
            bundle_id: "com.microsoft.edgemac",
            #[cfg(target_os = "linux")]
            desktop_file: "microsoft-edge.desktop",
            #[cfg(target_os = "windows")]
            prog_id: "MSEdgeHTM",
            paths: if cfg!(target_os = "macos") {
                &["/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"]
            } else if cfg!(target_os = "windows") {
                &[
                    r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
                    r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
                ]
            } else {
                &["/usr/bin/microsoft-edge", "/opt/microsoft/msedge/msedge"]
            },
            which_names: &["microsoft-edge", "msedge"],
            #[cfg(target_os = "macos")]
            profile_dir: Some("Microsoft Edge"),
            #[cfg(target_os = "linux")]
            profile_dir: Some("microsoft-edge"),
            #[cfg(target_os = "windows")]
            profile_dir: Some(r"Microsoft\Edge\User Data"),
        },
        BrowserCandidate {
            name: "Arc",
            #[cfg(target_os = "macos")]
            bundle_id: "company.thebrowser.Browser",
            #[cfg(target_os = "linux")]
            desktop_file: "",
            #[cfg(target_os = "windows")]
            prog_id: "",
            paths: if cfg!(target_os = "macos") {
                &["/Applications/Arc.app/Contents/MacOS/Arc"]
            } else {
                &[]
            },
            which_names: &[],
            #[cfg(target_os = "macos")]
            profile_dir: Some("Arc/User Data"),
            #[cfg(target_os = "linux")]
            profile_dir: None,
            #[cfg(target_os = "windows")]
            profile_dir: None,
        },
        BrowserCandidate {
            name: "Vivaldi",
            #[cfg(target_os = "macos")]
            bundle_id: "com.vivaldi.Vivaldi",
            #[cfg(target_os = "linux")]
            desktop_file: "vivaldi-stable.desktop",
            #[cfg(target_os = "windows")]
            prog_id: "VivaldiHTM",
            paths: if cfg!(target_os = "macos") {
                &["/Applications/Vivaldi.app/Contents/MacOS/Vivaldi"]
            } else if cfg!(target_os = "windows") {
                &[r"C:\Program Files\Vivaldi\Application\vivaldi.exe"]
            } else {
                &["/usr/bin/vivaldi", "/opt/vivaldi/vivaldi"]
            },
            which_names: &["vivaldi"],
            #[cfg(target_os = "macos")]
            profile_dir: Some("Vivaldi"),
            #[cfg(target_os = "linux")]
            profile_dir: Some("vivaldi"),
            #[cfg(target_os = "windows")]
            profile_dir: Some(r"Vivaldi\User Data"),
        },
        BrowserCandidate {
            name: "Opera",
            #[cfg(target_os = "macos")]
            bundle_id: "com.operasoftware.Opera",
            #[cfg(target_os = "linux")]
            desktop_file: "opera.desktop",
            #[cfg(target_os = "windows")]
            prog_id: "OperaStable",
            paths: if cfg!(target_os = "macos") {
                &["/Applications/Opera.app/Contents/MacOS/Opera"]
            } else if cfg!(target_os = "windows") {
                &[r"C:\Program Files\Opera\launcher.exe"]
            } else {
                &["/usr/bin/opera"]
            },
            which_names: &["opera"],
            #[cfg(target_os = "macos")]
            profile_dir: Some("com.operasoftware.Opera"),
            #[cfg(target_os = "linux")]
            profile_dir: Some("opera"),
            #[cfg(target_os = "windows")]
            profile_dir: Some(r"Opera Software\Opera Stable"),
        },
        BrowserCandidate {
            name: "Chromium",
            #[cfg(target_os = "macos")]
            bundle_id: "org.chromium.Chromium",
            #[cfg(target_os = "linux")]
            desktop_file: "chromium-browser.desktop",
            #[cfg(target_os = "windows")]
            prog_id: "ChromiumHTM",
            paths: if cfg!(target_os = "macos") {
                &["/Applications/Chromium.app/Contents/MacOS/Chromium"]
            } else if cfg!(target_os = "windows") {
                &[r"C:\Program Files\Chromium\Application\chrome.exe"]
            } else {
                &["/usr/bin/chromium-browser", "/usr/bin/chromium"]
            },
            which_names: &["chromium-browser", "chromium"],
            #[cfg(target_os = "macos")]
            profile_dir: Some("Chromium"),
            #[cfg(target_os = "linux")]
            profile_dir: Some("chromium"),
            #[cfg(target_os = "windows")]
            profile_dir: Some(r"Chromium\User Data"),
        },
    ]
}

/// Find the executable path for a browser candidate.
fn find_executable(candidate: &BrowserCandidate) -> Option<PathBuf> {
    // Check known paths first
    for path in candidate.paths {
        let p = PathBuf::from(path);
        if p.exists() {
            return Some(p);
        }
    }
    // Fall back to PATH lookup
    for name in candidate.which_names {
        if let Ok(p) = which::which(name) {
            return Some(p);
        }
    }
    None
}

/// Resolve the browser's native user-data directory.
fn resolve_profile_dir(candidate: &BrowserCandidate) -> Option<PathBuf> {
    #[cfg(target_os = "macos")]
    let base = dirs::home_dir()?.join("Library/Application Support");
    #[cfg(target_os = "linux")]
    let base = dirs::config_dir()?;
    #[cfg(target_os = "windows")]
    let base = dirs::data_local_dir()?;

    let rel = candidate.profile_dir?;
    let dir = base.join(rel);
    if dir.exists() { Some(dir) } else { None }
}

/// Check if a profile directory is locked by a running browser instance.
fn is_profile_locked(profile_dir: &std::path::Path) -> bool {
    // Chrome-family browsers create a "SingletonLock" or "lockfile" when running
    let lock = profile_dir.join("SingletonLock");
    if lock.exists() {
        return true;
    }
    // Some browsers use "Lock" instead
    let lock2 = profile_dir.join("Lock");
    if lock2.exists() {
        return true;
    }
    // macOS: check for SingletonSocket too
    profile_dir.join("SingletonSocket").exists()
}

/// Names of the lock artefacts Chrome writes under `--user-data-dir`.
/// Kept as a module-level constant so the test module can exercise the
/// exact same list.
pub(crate) const LOCK_FILES: &[&str] = &["SingletonLock", "SingletonSocket", "Lock"];

/// Stealth JavaScript registered via CDP's
/// `Page.addScriptToEvaluateOnNewDocument` so Chrome runs it on every
/// document creation — including full cross-origin navigations. Hides
/// the most common automation fingerprints: `navigator.webdriver`,
/// missing `chrome.runtime`, empty `navigator.plugins`, and the
/// notifications-permission probe used by bot detection libraries.
///
/// Exported `pub(crate)` for `src/tests/browser_stealth_test.rs` which
/// pins the presence of each patch as a regression guard.
pub(crate) const STEALTH_JS: &str = r#"
    // Hide navigator.webdriver
    Object.defineProperty(navigator, 'webdriver', { get: () => undefined });

    // Fake chrome.runtime (present in real Chrome, missing in automation)
    if (!window.chrome) { window.chrome = {}; }
    if (!window.chrome.runtime) {
        window.chrome.runtime = {
            connect: function() {},
            sendMessage: function() {},
            id: undefined
        };
    }

    // Fake plugins array (headless has 0 plugins)
    Object.defineProperty(navigator, 'plugins', {
        get: () => [
            { name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer' },
            { name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai' },
            { name: 'Native Client', filename: 'internal-nacl-plugin' }
        ]
    });

    // Fake languages
    Object.defineProperty(navigator, 'languages', {
        get: () => ['en-US', 'en']
    });

    // Remove automation-related properties from navigator
    const originalQuery = window.navigator.permissions.query;
    window.navigator.permissions.query = (parameters) =>
        parameters.name === 'notifications'
            ? Promise.resolve({ state: Notification.permission })
            : originalQuery(parameters);
"#;

/// Remove stale Chrome singleton lock files from the OPENCRABS-OWNED
/// profile directory. A previous opencrabs Chrome process that crashed
/// leaves these files behind — the next launch then refuses to start
/// with "Failed to create SingletonLock: File exists (17)" (see
/// 2026-04-11 16:57 / 2026-04-17 15:00 logs).
///
/// This is safe to call unconditionally on our own profile: if a live
/// process genuinely holds the lock, the caller has already checked
/// `is_profile_locked` and is about to launch anyway — the OS-level
/// re-create will still be atomic. Restrict callers to paths that are
/// NEVER the user's native browser profile (doing this on a live
/// Chrome's profile would crash their main browser).
/// Decide whether the CDP handler task is dead and the cached Browser
/// handle should be discarded. Pure function over the handler's state
/// so `src/tests/browser_health_test.rs` can exercise both branches
/// without spawning a real Chrome.
///
/// Returns `true` when:
///   - the handler handle is `None` (never launched, or already torn down), or
///   - the handle exists but `is_finished()` — the task exited, usually
///     because the underlying Chrome process died (OS kill / OOM / user
///     closed the window / CDP socket break).
///
/// The production path calls this after the Browser Option is confirmed
/// Some, so `None` handle while browser is Some means "we forgot to
/// store the handle" — treat it as dead and relaunch (safer than
/// proceeding with an un-polled event stream).
pub(crate) fn handler_is_dead(handle: Option<&tokio::task::JoinHandle<()>>) -> bool {
    handle.map(|h| h.is_finished()).unwrap_or(true)
}

/// Poll `is_profile_locked` on `profile_dir` with exponential backoff
/// up to `cap_ms` total wait. Returns true once the profile becomes
/// unlocked, false if the cap elapses first.
///
/// When the user's main browser is starting up, Chrome briefly holds
/// the profile lock before releasing it for additional instances.
/// Checking once and falling straight through drops the user into the
/// empty fallback profile and silently loses all their
/// logins/cookies. Waiting a few seconds gets the native profile
/// back almost every time, at the cost of a small first-launch delay.
///
/// Delays: 250ms, 500, 1000, 2000, 4000 (capped at 4000ms per step).
pub(crate) async fn wait_for_profile_unlock(profile_dir: &std::path::Path, cap_ms: u64) -> bool {
    let mut waited_ms: u64 = 0;
    let mut delay_ms: u64 = 250;
    loop {
        if !is_profile_locked(profile_dir) {
            return true;
        }
        if waited_ms >= cap_ms {
            tracing::debug!(
                "browser: profile {} still locked after {}ms — caller falls back",
                profile_dir.display(),
                waited_ms
            );
            return false;
        }
        let step = delay_ms.min(cap_ms.saturating_sub(waited_ms));
        tracing::debug!(
            "browser: profile {} locked, retrying in {}ms",
            profile_dir.display(),
            step
        );
        tokio::time::sleep(std::time::Duration::from_millis(step)).await;
        waited_ms += step;
        delay_ms = (delay_ms * 2).min(4000);
    }
}

pub(crate) fn clean_stale_locks(profile_dir: &std::path::Path) {
    for name in LOCK_FILES {
        let path = profile_dir.join(name);
        if path.exists()
            && let Err(e) = std::fs::remove_file(&path)
        {
            tracing::warn!(
                "browser: failed to clean stale lock {}: {}",
                path.display(),
                e
            );
        }
    }
}

/// Detect the user's default browser (macOS).
///
/// Parses the `LSHandlers` array from LaunchServices. The plist output is
/// an array of dicts — we want the one with `LSHandlerURLScheme = https`
/// and read its `LSHandlerRoleAll` value.
///
/// The old parser walked the text line-by-line looking for a
/// `LSHandlerURLScheme = https` token and then grabbing the next
/// `LSHandlerRoleAll`. That was broken in two ways:
///
/// 1. Each entry starts with a nested `LSHandlerPreferredVersions` dict
///    whose contents include `LSHandlerRoleAll = "-";` as a placeholder.
///    The old parser grabbed that placeholder instead of the real role.
/// 2. Within each entry the role line appears BEFORE the scheme line,
///    so the `found_scheme` flag never fired on the correct role.
///
/// Result on this user's machine: the parser returned `"-"` as the
/// identifier, no candidate matched, detect_browser() fell through to
/// the first Chromium candidate (Google Chrome) — even when the user's
/// actual default browser is Brave. The fix is block-aware parsing:
/// track brace depth, accumulate fields at depth 2 only (skipping the
/// nested PreferredVersions dict at depth 3), and emit the pair
/// `(scheme, role)` when the block closes.
#[cfg(target_os = "macos")]
fn detect_default_browser_id() -> Option<String> {
    let output = std::process::Command::new("defaults")
        .args([
            "read",
            "com.apple.LaunchServices/com.apple.launchservices.secure",
            "LSHandlers",
        ])
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&output.stdout);
    parse_ls_handlers(&text)
}

/// Pure parser for the `defaults read … LSHandlers` plist output.
/// Extracted so unit tests can feed fixtures without spawning `defaults`.
///
/// The `defaults` output wraps LSHandlers in `( … )` (plist array),
/// not `{ … }`. So each LSHandler dict entry `{ … }` opens at brace
/// depth 1, not 2. Fields at depth 1 are the entry's own keys; depth
/// 2 is inside a nested dict like LSHandlerPreferredVersions which we
/// skip. Entry closes when depth returns to 0.
///
/// We accept either `LSHandlerURLScheme = https` or
/// `LSHandlerContentType = "com.apple.default-app.web-browser"` as
/// the "default web browser" marker — System Settings → General →
/// Default web browser writes the content-type form; per-scheme
/// associations write the URL-scheme form.
#[cfg(target_os = "macos")]
pub(crate) fn parse_ls_handlers(text: &str) -> Option<String> {
    // Extract a quoted-or-unquoted value after `=` from a plist line.
    // Handles both `key = "value";` and `key = value;` forms.
    fn parse_value(line: &str) -> Option<String> {
        let eq = line.find('=')?;
        let rest = line[eq + 1..].trim().trim_end_matches(';').trim();
        let unquoted = rest.trim_matches('"').trim();
        if unquoted.is_empty() {
            None
        } else {
            Some(unquoted.to_string())
        }
    }

    let mut depth: i32 = 0;
    let mut block_scheme: Option<String> = None;
    let mut block_content_type: Option<String> = None;
    let mut block_role: Option<String> = None;

    for line in text.lines() {
        let trimmed = line.trim();

        if depth == 1 {
            if trimmed.starts_with("LSHandlerURLScheme") {
                block_scheme = parse_value(trimmed);
            } else if trimmed.starts_with("LSHandlerContentType") {
                block_content_type = parse_value(trimmed);
            } else if trimmed.starts_with("LSHandlerRoleAll") {
                block_role = parse_value(trimmed);
            }
        }

        depth += trimmed.matches('{').count() as i32;
        depth -= trimmed.matches('}').count() as i32;

        // Block boundary: returning to depth 0 means the entry closed.
        if depth == 0 {
            let scheme = block_scheme.take();
            let content_type = block_content_type.take();
            let role = block_role.take();
            let is_web_default = scheme.as_deref().map(|s| s.eq_ignore_ascii_case("https"))
                == Some(true)
                || content_type.as_deref() == Some("com.apple.default-app.web-browser");
            if is_web_default
                && let Some(r) = role
                && r != "-"
            {
                return Some(r.to_lowercase());
            }
        }
    }

    None
}

/// Detect the user's default browser (Linux).
#[cfg(target_os = "linux")]
fn detect_default_browser_id() -> Option<String> {
    let output = std::process::Command::new("xdg-settings")
        .args(["get", "default-web-browser"])
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&output.stdout);
    parse_xdg_default_browser(&text)
}

/// Pure parser for `xdg-settings get default-web-browser` output.
/// Extracted so unit tests can feed fixtures without spawning the
/// xdg-settings binary. Trims, lowercases, and rejects empty strings.
#[cfg(target_os = "linux")]
pub(crate) fn parse_xdg_default_browser(text: &str) -> Option<String> {
    let trimmed = text.trim().to_lowercase();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed)
    }
}

/// Detect the user's default browser (Windows).
#[cfg(target_os = "windows")]
fn detect_default_browser_id() -> Option<String> {
    let output = std::process::Command::new("reg")
        .args([
            "query",
            r"HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice",
            "/v", "ProgId",
        ])
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&output.stdout);
    parse_windows_reg_prog_id(&text)
}

/// Pure parser for `reg query … /v ProgId` output. Example input line:
/// `    ProgId    REG_SZ    ChromeHTML`. Returns the lowercased ProgId
/// value, or None if no ProgId line was found.
///
/// Extracted so unit tests can feed fixtures without shelling out to
/// `reg`. Matches the line containing "ProgId" and takes the last
/// whitespace-delimited token as the value — this works for the
/// standard `reg query` format on Windows 10/11.
#[cfg(target_os = "windows")]
pub(crate) fn parse_windows_reg_prog_id(text: &str) -> Option<String> {
    for line in text.lines() {
        let trimmed = line.trim();
        // Skip the "ProgId" header line that some reg versions emit
        // without a value (shouldn't happen for REG_SZ queries, but
        // guard anyway).
        if trimmed.starts_with("ProgId") || trimmed.contains("    ProgId    ") {
            let parts: Vec<&str> = trimmed.split_whitespace().collect();
            // Expect at least: ["ProgId", "REG_SZ", "<value>"]
            if parts.len() >= 3 {
                return Some(parts.last().unwrap().to_lowercase());
            }
        }
    }
    None
}

/// Case-insensitive equality check used by `matches_default` and the
/// associated tests. The actual comparison is split out so we can pin
/// it in a unit test without exposing the full `BrowserCandidate`
/// struct (which is platform-cfg-tangled). The 2026-04-19 macOS
/// fixtures showed `defaults` reporting `"com.brave.browser"`
/// (lowercase b) while our candidate carries `"com.brave.Browser"`
/// (capital B); without this case-insensitive compare we'd fall
/// through to Chrome.
pub(crate) fn id_matches_default(candidate_id: &str, default_id: &str) -> bool {
    candidate_id.eq_ignore_ascii_case(default_id)
}

/// Check if a browser candidate matches the detected default browser ID.
fn matches_default(candidate: &BrowserCandidate, default_id: &str) -> bool {
    #[cfg(target_os = "macos")]
    {
        id_matches_default(candidate.bundle_id, default_id)
    }
    #[cfg(target_os = "linux")]
    {
        id_matches_default(candidate.desktop_file, default_id)
    }
    #[cfg(target_os = "windows")]
    {
        id_matches_default(candidate.prog_id, default_id)
    }
}

/// Smart browser detection: finds the user's default browser, then falls back
/// to the first installed Chromium-based browser.
fn detect_browser() -> Option<BrowserInfo> {
    let browsers = known_browsers();

    // 1. Try the user's default browser first
    if let Some(default_id) = detect_default_browser_id() {
        tracing::debug!("Default browser identifier: {default_id}");
        for candidate in &browsers {
            if matches_default(candidate, &default_id)
                && let Some(path) = find_executable(candidate)
            {
                tracing::info!(
                    "Default browser detected: {} ({})",
                    candidate.name,
                    default_id
                );
                return Some(BrowserInfo {
                    name: candidate.name.to_string(),
                    path,
                    user_data_dir: resolve_profile_dir(candidate),
                });
            }
        }
        tracing::debug!("Default browser '{default_id}' is not Chromium-based or not found");
    }

    // 2. Fall back to first installed Chromium browser
    for candidate in &browsers {
        if let Some(path) = find_executable(candidate) {
            tracing::info!("Found Chromium browser: {}", candidate.name);
            return Some(BrowserInfo {
                name: candidate.name.to_string(),
                path,
                user_data_dir: resolve_profile_dir(candidate),
            });
        }
    }

    tracing::warn!("No Chromium-based browser found on system");
    None
}

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

    #[test]
    fn test_manager_new() {
        let mgr = BrowserManager::new(Default::default());
        let _ = mgr.clone();
    }

    #[test]
    fn test_manager_with_headless() {
        let mgr = BrowserManager::with_headless(false, Default::default());
        let _ = mgr.clone();
    }

    #[tokio::test]
    async fn test_is_headless_default() {
        let mgr = BrowserManager::with_headless(true, Default::default());
        assert!(mgr.is_headless().await);
    }

    #[tokio::test]
    async fn test_is_headless_false() {
        let mgr = BrowserManager::with_headless(false, Default::default());
        assert!(!mgr.is_headless().await);
    }

    #[tokio::test]
    async fn test_set_headless_no_change() {
        let mgr = BrowserManager::with_headless(true, Default::default());
        // Already headless — no change
        assert!(!mgr.set_headless(true).await);
    }

    #[tokio::test]
    async fn test_set_headless_switch() {
        let mgr = BrowserManager::with_headless(true, Default::default());
        assert!(mgr.is_headless().await);

        if BrowserManager::has_display() {
            // Has display — switching to headed should succeed
            assert!(mgr.set_headless(false).await);
            assert!(!mgr.is_headless().await);
            // Switch back
            assert!(mgr.set_headless(true).await);
            assert!(mgr.is_headless().await);
        } else {
            // No display — switching to headed should be rejected, stays headless
            assert!(!mgr.set_headless(false).await);
            assert!(mgr.is_headless().await);
        }
    }

    #[tokio::test]
    async fn test_list_pages_empty() {
        let mgr = BrowserManager::new(Default::default());
        assert!(mgr.list_pages().await.is_empty());
    }

    #[tokio::test]
    async fn test_close_nonexistent() {
        let mgr = BrowserManager::new(Default::default());
        assert!(!mgr.close_page("nonexistent").await);
    }

    #[test]
    fn test_detect_browser_finds_something() {
        // On dev machines there should be at least one Chromium browser
        let result = detect_browser();
        if let Some(info) = result {
            assert!(!info.name.is_empty());
            assert!(info.path.exists());
            tracing::info!("Detected: {} at {}", info.name, info.path.display());
        }
        // On CI with no browser installed, None is acceptable
    }

    #[test]
    fn test_known_browsers_not_empty() {
        let browsers = known_browsers();
        assert!(browsers.len() >= 7); // Chrome, Brave, Edge, Arc, Vivaldi, Opera, Chromium
    }

    #[test]
    fn test_is_profile_locked_nonexistent() {
        let dir = std::path::PathBuf::from("/tmp/nonexistent-browser-profile-test");
        assert!(!is_profile_locked(&dir));
    }

    #[test]
    fn test_detect_default_browser_id() {
        // Just ensure it doesn't panic; the result depends on system config.
        let _ = detect_default_browser_id();
    }
}