ferridriver 0.3.0

Browser automation in Rust with a Playwright-compatible API. Four pluggable backends: CDP pipe, CDP WebSocket, Playwright WebKit, Firefox BiDi.
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
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
//! Browser state management with instance→context→page hierarchy.
//!
//! Design principles:
//! - Instance = Chrome process (owns chrome flags)
//! - Context = isolated browser context within an instance (isolated cookies, storage)
//! - Page = tab within a context
//! - Composite session key: `"<instance>:<context>"` (backwards compat: bare name = default instance)
//! - No global "active page" -- every tool call specifies its session key
//! - No races possible: there is no shared mutable selection state

use std::sync::Arc;

use crate::backend::{AnyBrowser, AnyPage, BackendKind};
use crate::context::BrowserContext;
use crate::error::{FerriError, Result};
use rustc_hash::FxHashMap as HashMap;

/// Default viewport dimensions -- consistent across all backends.
pub const DEFAULT_VIEWPORT_WIDTH: i64 = 1280;
pub const DEFAULT_VIEWPORT_HEIGHT: i64 = 720;

// Re-export log types from context (they live there now).
pub use crate::console_message::ConsoleMessage;
pub use crate::context::DialogEvent;
pub use crate::network::Request;

/// Arc handles to a context's log collections, usable without holding the `BrowserState` lock.
#[derive(Clone)]
pub struct ContextLogHandles {
  pub console: std::sync::Arc<tokio::sync::RwLock<Vec<ConsoleMessage>>>,
  pub network: std::sync::Arc<tokio::sync::RwLock<Vec<Request>>>,
  pub dialog: std::sync::Arc<tokio::sync::RwLock<Vec<DialogEvent>>>,
}

// ── SessionKey ──────────────────────────────────────────────────────────────

/// Parsed composite session key: `"<instance>:<context>"`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionKey {
  pub instance: Arc<str>,
  pub context: Arc<str>,
}

impl SessionKey {
  /// Parse a composite key string.
  ///
  /// - `"default"` → instance="default", context="default"
  /// - `"myctx"` → instance="default", context="myctx"
  /// - `"staging:admin"` → instance="staging", context="admin"
  #[must_use]
  pub fn parse(raw: &str) -> Self {
    if let Some((inst, ctx)) = raw.split_once(':') {
      SessionKey {
        instance: Arc::from(inst),
        context: Arc::from(ctx),
      }
    } else if raw == "default" {
      SessionKey {
        instance: Arc::from("default"),
        context: Arc::from("default"),
      }
    } else {
      // Backwards compat: bare name → default instance, name as context
      SessionKey {
        instance: Arc::from("default"),
        context: Arc::from(raw),
      }
    }
  }

  /// Reconstruct the composite key string.
  #[must_use]
  pub fn to_composite(&self) -> String {
    format!("{}:{}", self.instance, self.context)
  }
}

// ── BrowserInstance ─────────────────────────────────────────────────────────

/// A single Chrome process and its isolated contexts.
struct BrowserInstance {
  browser: AnyBrowser,
  contexts: HashMap<String, BrowserContext>,
  /// Monotonic id assigned when this instance was (re)created. A
  /// consumer that caches state derived from a browser session (e.g. the
  /// MCP per-session script VM, which may hold JS handles into pages)
  /// stores the generation it built against and discards that state when
  /// the generation changes — a relaunch/reconnect under the same
  /// instance name is a *different* browser session.
  generation: u64,
}

#[derive(Clone)]
pub struct PageOpenPlan {
  pub browser: AnyBrowser,
  pub viewport: Option<crate::options::ViewportConfig>,
  pub browser_context_id: Option<String>,
}

impl BrowserInstance {
  fn context(&self, name: &str) -> Result<&BrowserContext> {
    self
      .contexts
      .get(name)
      .ok_or_else(|| FerriError::invalid_argument("context", format!("'{name}' not found in this instance")))
  }

  fn context_mut(&mut self, name: &str) -> &mut BrowserContext {
    self
      .contexts
      .entry(name.to_string())
      .or_insert_with(|| BrowserContext::new(name.to_string()))
  }

  fn context_mut_checked(&mut self, name: &str) -> Result<&mut BrowserContext> {
    self
      .contexts
      .get_mut(name)
      .ok_or_else(|| FerriError::invalid_argument("context", format!("'{name}' not found")))
  }

  fn remove_context(&mut self, name: &str) {
    self.contexts.remove(name);
  }
}

// ── BrowserState ────────────────────────────────────────────────────────────

/// Callback type for per-instance chrome args.
pub type InstanceArgsFn = Box<dyn Fn(&str) -> Vec<String> + Send + Sync>;

/// Callback type for resolving how to connect to a browser instance.
///
/// When an instance is requested, this resolver is called first. If it returns
/// `Some(ConnectMode)`, that mode is used instead of the default `connect_mode`.
/// This allows consumers to route certain instances to existing browsers
/// (e.g. "staging" -> connect to a browser already running with debugging enabled)
/// while launching fresh browsers for others.
///
/// Return `None` to fall through to the default `connect_mode`.
pub type InstanceResolverFn = Box<dyn Fn(&str) -> Option<ConnectMode> + Send + Sync>;

/// All browser state -- manages multiple Chrome instances, each with contexts and pages.
pub struct BrowserState {
  instances: HashMap<String, BrowserInstance>,
  /// Monotonic source for [`BrowserInstance::generation`]. Bumped on
  /// every instance (re)creation so consumers can detect a browser
  /// session swap under a reused instance name.
  instance_generation_counter: u64,
  chromium_path: String,
  connect_mode: ConnectMode,
  backend_kind: BackendKind,
  /// Base Chrome flags applied to ALL instances.
  pub extra_args: Vec<String>,
  /// Per-instance additional chrome args. Called with instance name when launching.
  instance_args_fn: Option<InstanceArgsFn>,
  /// Per-instance connect mode resolver. Called before launching to check if
  /// an existing browser should be connected to instead.
  instance_resolver_fn: Option<InstanceResolverFn>,
  /// Whether to run headless.
  pub headless: bool,
  /// Custom user data directory.
  pub user_data_dir: Option<String>,
  /// Default viewport for new pages.
  pub default_viewport: Option<crate::options::ViewportConfig>,
  /// Reason passed to the most recent `Browser::close({ reason })` call,
  /// surfaced on `TargetClosed` errors emitted after shutdown.
  close_reason: Option<String>,
  /// Per-context-name event emitter registry. Every [`crate::ContextRef`]
  /// constructed with the same composite session key must share the
  /// same `ContextEventEmitter` so that `context.on('weberror', cb)`
  /// and the per-page → per-context `PageError` → `WebError` bridge
  /// dispatch through the same broadcast channel. The registry is a
  /// sync `std::sync::Mutex` (not tokio) so `ContextRef::new` can
  /// lazily init the entry without needing to own the tokio `RwLock`
  /// guard — `get_or_create_context_events` is called on every
  /// `ContextRef::new` for its composite key.
  pub context_events: Arc<std::sync::Mutex<HashMap<String, crate::events::ContextEventEmitter>>>,
  /// Per-context `recordVideo` configuration registry. Mirrors
  /// `context_events` above: sync `std::sync::Mutex` so the
  /// non-async setter (`ContextRef::set_record_video`) can write
  /// without the tokio `RwLock` and `register_opened_page` can read
  /// without awaiting. Populated by `ContextRef::set_record_video`;
  /// consumed by `register_opened_page` when attaching a
  /// [`crate::video::Video`] handle to the new page. §4.1's
  /// `BrowserContextOptions` bag will fold this into a single
  /// options struct.
  pub record_video: Arc<std::sync::Mutex<HashMap<String, crate::options::RecordVideoOptions>>>,
  /// Per-context `BrowserContextOptions` registry. Populated by
  /// [`Self::set_context_options`] when the caller constructs a
  /// context via `Browser::new_context(Some(options))`; consumed by
  /// `ContextRef::new_page` to apply emulation/permissions/headers on
  /// every fresh page. Sync mutex so non-async construction paths
  /// can write without owning a tokio guard.
  pub context_options: Arc<std::sync::Mutex<HashMap<String, crate::options::BrowserContextOptions>>>,
  /// Sync-readable connection flag mirroring `!instances.is_empty()`.
  /// Set true when an instance is ensured, false on `shutdown`, so
  /// `Browser::is_connected()` stays sync like Playwright's.
  pub connected: Arc<std::sync::atomic::AtomicBool>,
  /// Per-context `storageState` hydration flag. Set the first time a
  /// page opens in a context whose options bag carries a
  /// `storageState` — subsequent pages in the same context skip the
  /// hydration (cookies are context-scoped; localStorage persists per
  /// origin across subsequent pages). Mirrors Playwright's
  /// "set storage state once at context creation".
  pub storage_state_hydrated: Arc<std::sync::Mutex<rustc_hash::FxHashSet<String>>>,
  /// Set by [`crate::BrowserType::launch_persistent_context`] to mark
  /// this `BrowserState` as backing a persistent-context launch.
  /// When the persistent default context closes, the whole browser
  /// must shut down — Playwright's contract:
  /// "Closing this context will automatically close the browser."
  /// (`/tmp/playwright/packages/playwright-core/types/types.d.ts:15199`).
  pub persistent_context: bool,
}

#[derive(Clone)]
pub enum ConnectMode {
  /// Launch a new browser (default)
  Launch,
  /// Connect to browser at explicit ws:// or http:// URL
  ConnectUrl(String),
  /// Auto-connect to running Chrome by reading `DevToolsActivePort` file
  AutoConnect {
    channel: String,
    user_data_dir: Option<String>,
  },
}

impl BrowserState {
  /// Construct a `BrowserState` from an internal
  /// [`LaunchPlan`](crate::options::LaunchPlan). This is the single
  /// construction path — there used to be a parallel `new(mode,
  /// backend)` shortcut that hard-coded `headless = false`, which
  /// silently launched full Google Chrome for MCP servers even when
  /// the CLI passed `--headless`. Full Chrome inherits the macOS
  /// system appearance (including `prefers-color-scheme: dark` on
  /// dark-mode hosts), which broke `emulateMedia` reset behaviour
  /// tested via `run_script`. Funneling everyone through `LaunchPlan`
  /// guarantees binary resolution stays aligned with the caller's
  /// headless intent.
  ///
  /// `LaunchPlan` is the internal sister of the public Playwright-
  /// shaped [`crate::options::LaunchOptions`]; the
  /// [`crate::BrowserType`] factory is the only place that builds a
  /// plan from public options.
  #[must_use]
  pub fn with_plan(connect_mode: ConnectMode, plan: crate::options::LaunchPlan) -> Self {
    let chromium_path = if let Some(path) = plan.executable_path {
      path
    } else {
      match plan.kind {
        crate::options::BrowserKind::Firefox => std::env::var("FIREFOX_PATH")
          .or_else(|_| detect_firefox().map_err(|_| std::env::VarError::NotPresent))
          .unwrap_or_else(|_| resolve_chromium(plan.headless)),
        _ => resolve_chromium(plan.headless),
      }
    };
    Self {
      instances: HashMap::default(),
      instance_generation_counter: 0,
      chromium_path,
      connect_mode,
      backend_kind: plan.backend,
      extra_args: plan.args,
      instance_args_fn: None,
      instance_resolver_fn: None,
      headless: plan.headless,
      user_data_dir: plan.user_data_dir,
      default_viewport: plan.default_viewport,
      close_reason: None,
      context_events: Arc::new(std::sync::Mutex::new(HashMap::default())),
      record_video: Arc::new(std::sync::Mutex::new(HashMap::default())),
      context_options: Arc::new(std::sync::Mutex::new(HashMap::default())),
      connected: Arc::new(std::sync::atomic::AtomicBool::new(false)),
      storage_state_hydrated: Arc::new(std::sync::Mutex::new(rustc_hash::FxHashSet::default())),
      persistent_context: false,
    }
  }

  /// The backend kind this state was constructed with. Cached at
  /// `with_plan` time and never mutated, so callers don't need to
  /// take the outer `RwLock` read guard to ask the question.
  #[must_use]
  pub fn backend_kind(&self) -> BackendKind {
    self.backend_kind
  }

  /// Mark a context composite-key as having had its storageState
  /// hydrated. Returns `true` if this is the first call (hydration
  /// should run); `false` if already hydrated.
  #[must_use]
  pub fn claim_storage_state_hydration(&self, composite_key: &str) -> bool {
    let mut set = match self.storage_state_hydrated.lock() {
      Ok(g) => g,
      Err(p) => p.into_inner(),
    };
    set.insert(composite_key.to_string())
  }

  /// Install the [`crate::options::BrowserContextOptions`] bag for a
  /// composite session key. Any fields that also live in the older
  /// per-field registries (currently `record_video`) are mirrored
  /// there too so existing consumers keep working.
  pub fn set_context_options(&self, composite_key: &str, opts: crate::options::BrowserContextOptions) {
    if let Some(ref rv) = opts.record_video {
      self.set_record_video(composite_key, rv.clone());
    }
    let mut map = match self.context_options.lock() {
      Ok(g) => g,
      Err(p) => p.into_inner(),
    };
    map.insert(composite_key.to_string(), opts);
  }

  /// Fetch a clone of the options bag for a composite key, if any.
  #[must_use]
  pub fn get_context_options(&self, composite_key: &str) -> Option<crate::options::BrowserContextOptions> {
    let map = self.context_options.lock().ok()?;
    map.get(composite_key).cloned()
  }

  /// Enable `recordVideo` for every page opened under `composite_key`
  /// (format: `"<instance>:<context>"`). Playwright equivalent:
  /// `browser.newContext({ recordVideo: { dir, size? } })`. Calls
  /// after the setter propagate to pages opened thereafter; pages
  /// already opened in the context do NOT retroactively start
  /// recording (matches Playwright's behaviour of binding the
  /// option at context-creation time).
  pub fn set_record_video(&self, composite_key: &str, opts: crate::options::RecordVideoOptions) {
    let mut map = match self.record_video.lock() {
      Ok(g) => g,
      Err(p) => p.into_inner(),
    };
    map.insert(composite_key.to_string(), opts);
  }

  /// Fetch the `recordVideo` configuration for a composite key, if
  /// any. Returns a clone — the stored options are rarely
  /// mutated after the initial set.
  #[must_use]
  pub fn get_record_video(&self, composite_key: &str) -> Option<crate::options::RecordVideoOptions> {
    let map = self.record_video.lock().ok()?;
    map.get(composite_key).cloned()
  }

  /// Look up (or lazily create) the `ContextEventEmitter` for a
  /// composite session key. All `ContextRef` clones with the same key
  /// receive the same emitter so `context.on('weberror', cb)`
  /// observers and the per-page page-error bridge dispatch through
  /// the same broadcast channel.
  #[must_use]
  pub fn get_or_create_context_events(&self, key: &str) -> crate::events::ContextEventEmitter {
    let mut map = match self.context_events.lock() {
      Ok(g) => g,
      Err(poisoned) => poisoned.into_inner(),
    };
    map
      .entry(key.to_string())
      .or_insert_with(crate::events::ContextEventEmitter::new)
      .clone()
  }

  /// Record the reason given to `Browser::close({ reason })` so downstream
  /// `TargetClosed` errors can carry it through to consumers.
  pub fn set_close_reason(&mut self, reason: String) {
    self.close_reason = Some(reason);
  }

  /// Current close reason, if any.
  #[must_use]
  pub fn close_reason(&self) -> Option<&str> {
    self.close_reason.as_deref()
  }

  /// Set a callback for per-instance additional chrome args.
  /// Called with the instance name when launching a new Chrome process.
  pub fn set_instance_args_fn(&mut self, f: InstanceArgsFn) {
    self.instance_args_fn = Some(f);
  }

  /// Set a callback to resolve how to connect to a specific instance.
  ///
  /// When `ensure_instance("name")` is called, the resolver runs first.
  /// If it returns `Some(ConnectMode)`, that mode is used instead of launching.
  /// This decouples browser discovery from ferridriver -- the consumer provides
  /// the discovery logic (reading `DevToolsActivePort` files, querying a registry, etc.).
  pub fn set_instance_resolver_fn(&mut self, f: InstanceResolverFn) {
    self.instance_resolver_fn = Some(f);
  }

  // ── Instance management ─────────────────────────────────────────────────

  /// Launch a fresh browser process for the configured `backend_kind`.
  /// Extracted from [`Self::ensure_instance`] to keep the per-backend
  /// match arms out of the ensure-instance hot path.
  async fn launch_browser(&self, all_extra: &[String]) -> Result<AnyBrowser> {
    Ok(match self.backend_kind {
      BackendKind::CdpPipe => {
        use crate::backend::cdp::{CdpBrowser, pipe::PipeTransport};
        let flags = chrome_flags(self.headless, all_extra);
        let browser = match &self.user_data_dir {
          Some(dir) => {
            CdpBrowser::<PipeTransport>::launch_with_flags_in_dir(
              &self.chromium_path,
              &flags,
              std::path::Path::new(dir),
            )
            .await?
          },
          None => CdpBrowser::<PipeTransport>::launch_with_flags(&self.chromium_path, &flags).await?,
        };
        AnyBrowser::CdpPipe(browser)
      },
      BackendKind::CdpRaw => {
        use crate::backend::cdp::{CdpBrowser, ws::WsTransport};
        let flags = chrome_flags(self.headless, all_extra);
        let browser = match &self.user_data_dir {
          Some(dir) => {
            Box::pin(CdpBrowser::<WsTransport>::launch_with_flags_in_dir(
              &self.chromium_path,
              &flags,
              std::path::Path::new(dir),
            ))
            .await?
          },
          None => CdpBrowser::<WsTransport>::launch_with_flags(&self.chromium_path, &flags).await?,
        };
        AnyBrowser::CdpRaw(browser)
      },
      BackendKind::WebKit => {
        use crate::backend::webkit::{LaunchConfig, WebKitBrowser};
        let config = LaunchConfig {
          headless: self.headless,
          ..LaunchConfig::default()
        };
        AnyBrowser::WebKit(Box::pin(WebKitBrowser::launch(&config)).await?)
      },
      BackendKind::Bidi => {
        use crate::backend::bidi::BidiBrowser;
        let mut flags = all_extra.to_vec();
        if self.headless {
          flags.push("--headless".into());
        }
        AnyBrowser::Bidi(Box::pin(BidiBrowser::launch_with_flags(&self.chromium_path, &flags)).await?)
      },
    })
  }

  /// Ensure a browser instance is launched. If it already exists, no-op.
  ///
  /// # Errors
  ///
  /// Returns an error if the browser process fails to start or connection fails.
  pub async fn ensure_instance(&mut self, instance_name: &str) -> Result<()> {
    if self.instances.contains_key(instance_name) {
      return Ok(());
    }

    // Check if the instance resolver can provide a connection mode.
    // This lets consumers route specific instances to existing browsers
    // (e.g. "staging" -> connect to browser managed by another tool).
    let resolved_mode = self.instance_resolver_fn.as_ref().and_then(|f| f(instance_name));

    // Build flags: base + per-instance
    let mut all_extra = self.extra_args.clone();
    if let Some(ref f) = self.instance_args_fn {
      all_extra.extend(f(instance_name));
    }

    // Inject --window-size from viewport config so the browser window matches the
    // viewport dimensions. Skip if the user already supplied --window-size.
    if !all_extra.iter().any(|a| a.starts_with("--window-size")) {
      if let Some(ref vp) = self.default_viewport {
        all_extra.push(format!("--window-size={},{}", vp.width, vp.height));
      }
    }

    // Use resolved mode if available, otherwise fall back to default connect_mode.
    let effective_mode = resolved_mode.as_ref().unwrap_or(&self.connect_mode);

    let browser = match effective_mode {
      // ConnectUrl and AutoConnect always use CdpRaw (WebSocket)
      ConnectMode::ConnectUrl(url) => {
        use crate::backend::cdp::{CdpBrowser, ws::WsTransport};
        let ws_url = if url.starts_with("ws://") || url.starts_with("wss://") {
          url.clone()
        } else {
          discover_ws_from_http(url).await?
        };
        AnyBrowser::CdpRaw(Box::pin(CdpBrowser::<WsTransport>::connect(&ws_url)).await?)
      },
      ConnectMode::AutoConnect { channel, user_data_dir } => {
        use crate::backend::cdp::{CdpBrowser, ws::WsTransport};
        let ws_url = discover_chrome_ws(channel, user_data_dir.as_deref())?;
        AnyBrowser::CdpRaw(Box::pin(CdpBrowser::<WsTransport>::connect(&ws_url)).await?)
      },
      ConnectMode::Launch => self.launch_browser(&all_extra).await?,
    };

    let mut inst = BrowserInstance {
      browser,
      contexts: HashMap::default(),
      generation: 0,
    };

    // Adopt existing pages into the "default" context of this instance.
    // When connecting to an existing browser, skip viewport override to preserve
    // the user's current window size. Only apply viewport for freshly launched browsers.
    let is_connect = matches!(
      effective_mode,
      ConnectMode::ConnectUrl(_) | ConnectMode::AutoConnect { .. }
    );
    // For connect mode, adopt existing pages into the default context.
    // For launch mode, skip default page creation — pages are created on demand
    // by the caller (test runner creates isolated contexts, MCP creates pages lazily).
    if is_connect {
      let existing_pages = Box::pin(inst.browser.pages()).await.unwrap_or_default();
      let ctx = inst.context_mut("default");
      for page in existing_pages {
        page.attach_listeners(ctx.console_log.clone(), ctx.network_log.clone(), ctx.dialog_log.clone());
        ctx.pages.push(page);
      }
    }

    inst.generation = self.next_instance_generation();
    self.instances.insert(instance_name.to_string(), inst);
    self.connected.store(true, std::sync::atomic::Ordering::Relaxed);
    Ok(())
  }

  /// Backwards-compat: ensure the "default" instance.
  ///
  /// # Errors
  ///
  /// Returns an error if the browser process fails to start.
  pub async fn ensure_browser(&mut self) -> Result<()> {
    Box::pin(self.ensure_instance("default")).await
  }

  /// Connect to a running browser at the given WebSocket or HTTP URL.
  /// Creates a new instance with the given name using `CdpRaw` backend.
  ///
  /// # Errors
  ///
  /// Returns an error if the WebSocket connection or page discovery fails.
  pub async fn connect_to_url(&mut self, instance_name: &str, url: &str) -> Result<usize> {
    use crate::backend::cdp::{CdpBrowser, ws::WsTransport};

    // Drop existing instance if any
    self.instances.remove(instance_name);

    let ws_url = if url.starts_with("ws://") || url.starts_with("wss://") {
      url.to_string()
    } else {
      discover_ws_from_http(url).await?
    };

    let browser = AnyBrowser::CdpRaw(Box::pin(CdpBrowser::<WsTransport>::connect(&ws_url)).await?);
    let mut inst = BrowserInstance {
      browser,
      contexts: HashMap::default(),
      generation: 0,
    };

    // Skip viewport override for existing pages — connect_to_url attaches to a
    // user-managed browser whose window size should not be touched.
    let existing_pages = Box::pin(inst.browser.pages()).await.unwrap_or_default();
    let ctx = inst.context_mut("default");
    let page_count = existing_pages.len();
    for page in existing_pages {
      page.attach_listeners(ctx.console_log.clone(), ctx.network_log.clone(), ctx.dialog_log.clone());
      ctx.pages.push(page);
    }

    inst.generation = self.next_instance_generation();
    self.instances.insert(instance_name.to_string(), inst);
    self.connected.store(true, std::sync::atomic::Ordering::Relaxed);
    Ok(page_count)
  }

  /// Auto-discover and connect to a running Chrome instance.
  ///
  /// Checks the instance resolver first (allowing consumers to route
  /// `instance_name` to a managed browser, e.g. connecting to an
  /// environment-specific browser launched by another tool). Falls back
  /// to reading Chrome's `DevToolsActivePort` file for the given
  /// channel/profile.
  ///
  /// The resolver is tried with the full `instance_name` first, then with
  /// the prefix before `:` (supporting composite keys like `"staging:default"`
  /// where only the first segment identifies the browser instance).
  ///
  /// # Errors
  ///
  /// Returns an error if Chrome discovery or connection fails.
  pub async fn connect_auto(
    &mut self,
    instance_name: &str,
    channel: &str,
    user_data_dir: Option<&str>,
  ) -> Result<usize> {
    if let Some(resolved) = self.resolve_via_instance_fn(instance_name) {
      return self.connect_with_resolved_mode(instance_name, resolved).await;
    }

    let ws_url = discover_chrome_ws(channel, user_data_dir)?;
    Box::pin(self.connect_to_url(instance_name, &ws_url)).await
  }

  /// Try the instance resolver with the full name, then with the prefix before `:`.
  fn resolve_via_instance_fn(&self, instance_name: &str) -> Option<ConnectMode> {
    let resolver = self.instance_resolver_fn.as_ref()?;

    // Try full name first
    if let Some(mode) = resolver(instance_name) {
      return Some(mode);
    }

    // Try prefix before ':' (composite keys like "staging:default")
    if let Some(prefix) = instance_name.split(':').next()
      && prefix != instance_name
    {
      return resolver(prefix);
    }

    None
  }

  /// Connect using a resolved mode from the instance resolver.
  async fn connect_with_resolved_mode(&mut self, instance_name: &str, mode: ConnectMode) -> Result<usize> {
    match mode {
      ConnectMode::ConnectUrl(url) => Box::pin(self.connect_to_url(instance_name, &url)).await,
      ConnectMode::AutoConnect { channel, user_data_dir } => {
        let ws_url = discover_chrome_ws(&channel, user_data_dir.as_deref())?;
        Box::pin(self.connect_to_url(instance_name, &ws_url)).await
      },
      // Launch mode is not meaningful for connect_auto -- the caller should
      // launch a browser separately and use ConnectUrl for the result.
      ConnectMode::Launch => Err(FerriError::Backend(format!(
        "Instance resolver returned Launch mode for '{instance_name}', expected ConnectUrl"
      ))),
    }
  }

  // ── Routing helpers ─────────────────────────────────────────────────────

  fn instance(&self, name: &str) -> Result<&BrowserInstance> {
    self.instances.get(name).ok_or_else(|| {
      FerriError::invalid_argument(
        "instance",
        format!("'{name}' not found. It will be created on first use."),
      )
    })
  }

  /// Access the default instance's backend browser handle. Used by
  /// `Browser::version()` to read the cached CDP `Browser.getVersion().product`.
  pub(crate) fn default_browser(&self) -> Option<&AnyBrowser> {
    self.instances.get("default").map(|i| &i.browser)
  }

  fn instance_mut(&mut self, name: &str) -> Result<&mut BrowserInstance> {
    self
      .instances
      .get_mut(name)
      .ok_or_else(|| FerriError::invalid_argument("instance", format!("'{name}' not found")))
  }

  // ── Public methods (all parse composite keys) ───────────────────────────

  /// Open a new page in a context. `context` is a composite key like `"staging:admin"`.
  ///
  /// # Errors
  ///
  /// Returns an error if the instance or page creation fails.
  /// Create a new page in the given context. Returns the `AnyPage` directly
  /// (no second lookup needed).
  pub async fn open_page(&mut self, context: &str, url: &str) -> Result<AnyPage> {
    let key = SessionKey::parse(context);
    Box::pin(self.open_page_keyed(&key, url)).await
  }

  /// Snapshot the immutable data needed to open a page without holding the
  /// global browser-state write lock across protocol round-trips.
  ///
  /// # Errors
  ///
  /// Returns an error if the browser instance does not exist.
  pub fn page_open_plan(&self, key: &SessionKey) -> Result<PageOpenPlan> {
    let inst = self.instance(&key.instance)?;
    let browser_context_id = if &*key.context == "default" {
      None
    } else {
      inst
        .contexts
        .get(&*key.context)
        .and_then(|ctx| ctx.cdp_context_id.clone())
    };

    Ok(PageOpenPlan {
      browser: inst.browser.clone(),
      viewport: self.default_viewport.clone(),
      browser_context_id,
    })
  }

  /// Register a newly created page back into the state after off-lock backend work.
  ///
  /// # Errors
  ///
  /// Returns an error if the browser instance or context does not exist.
  pub fn register_opened_page(
    &mut self,
    key: &SessionKey,
    page: AnyPage,
    browser_context_id: Option<String>,
  ) -> Result<()> {
    // Pull the context-event emitter for this session key BEFORE
    // taking the mutable instance borrow, so we can hand it to the
    // per-page → per-context `PageError` → `WebError` bridge spawned
    // below. Every `ContextRef` cloned with the same composite key
    // receives the same emitter via the registry, so listeners
    // registered anywhere (NAPI `context.on('weberror')`, QuickJS
    // `context.waitForEvent('weberror')`, etc.) all observe events
    // fanned out here.
    let composite = key.to_composite();
    let context_events = self.get_or_create_context_events(&composite);

    let inst = self.instance_mut(&key.instance)?;
    let ctx = inst.context_mut(&key.context);
    if let Some(id) = browser_context_id {
      ctx.cdp_context_id = Some(id);
    }
    page.attach_listeners(ctx.console_log.clone(), ctx.network_log.clone(), ctx.dialog_log.clone());

    // Spawn the page→context bridge exactly once per registered page.
    // Runs independently of any `ContextRef` or `Page` wrapper
    // lifetime — forwards as long as the backend's broadcast
    // channel stays open (i.e. the page is alive).
    let mut rx = page.events().subscribe();
    tokio::spawn(async move {
      while let Ok(event) = rx.recv().await {
        if let crate::events::PageEvent::PageError(err) = event {
          context_events.emit(crate::events::ContextEvent::WebError(err));
        }
      }
    });

    ctx.pages.push(page);
    ctx.active_page_idx = ctx.pages.len() - 1;
    Ok(())
  }

  /// Same as `open_page` but accepts a pre-parsed `SessionKey` (avoids re-parsing).
  ///
  /// # Errors
  ///
  /// Returns an error if the browser instance or page creation fails.
  pub async fn open_page_keyed(&mut self, key: &SessionKey, url: &str) -> Result<AnyPage> {
    if !self.instances.contains_key(&*key.instance) {
      Box::pin(self.ensure_instance(&key.instance)).await?;
    }

    let plan = self.page_open_plan(key)?;
    let (page, cdp_ctx_id) = if &*key.context == "default" {
      (
        Box::pin(
          plan
            .browser
            .new_page(url, plan.browser_context_id.as_deref(), plan.viewport.as_ref()),
        )
        .await?,
        None,
      )
    } else if let Some(existing_ctx_id) = plan.browser_context_id.clone() {
      (
        Box::pin(
          plan
            .browser
            .new_page(url, Some(&existing_ctx_id), plan.viewport.as_ref()),
        )
        .await?,
        Some(existing_ctx_id),
      )
    } else {
      // Legacy `open_page_keyed` path — no options bag flows through
      // here (used by older MCP call sites that don't go via
      // `ContextRef::new_page`). Proxy wiring happens on the
      // `ContextRef` path exclusively.
      let ctx_id = plan.browser.new_context(None).await?;
      let p = Box::pin(plan.browser.new_page(url, Some(&ctx_id), plan.viewport.as_ref())).await?;
      (p, Some(ctx_id))
    };

    self.register_opened_page(key, page.clone(), cdp_ctx_id)?;
    Ok(page)
  }

  /// # Errors
  ///
  /// Returns an error if the instance, context, or page does not exist.
  pub fn active_page(&self, context: &str) -> Result<&AnyPage> {
    let key = SessionKey::parse(context);
    let inst = self.instance(&key.instance)?;
    let ctx = inst.context(&key.context)?;
    ctx
      .active_page()
      .ok_or_else(|| FerriError::invalid_argument("context", format!("no pages in context '{context}'")))
  }

  /// # Errors
  ///
  /// Returns an error if the instance or context does not exist.
  pub fn context(&self, context: &str) -> Result<&BrowserContext> {
    let key = SessionKey::parse(context);
    let inst = self.instance(&key.instance)?;
    inst.context(&key.context)
  }

  /// # Errors
  ///
  /// Returns an error if the instance or context does not exist.
  pub fn context_mut_checked(&mut self, context: &str) -> Result<&mut BrowserContext> {
    let key = SessionKey::parse(context);
    let inst = self.instance_mut(&key.instance)?;
    inst.context_mut_checked(&key.context)
  }

  /// Remove a context. If it has a CDP browser context ID, dispose it
  /// (one CDP call kills the context + all pages, matching Playwright's doClose).
  pub async fn remove_context(&mut self, context: &str) {
    let key = SessionKey::parse(context);
    if let Some(inst) = self.instances.get_mut(&*key.instance) {
      if let Ok(ctx) = inst.context(&key.context) {
        if let Some(ref ctx_id) = ctx.cdp_context_id {
          let _ = inst.browser.dispose_context(ctx_id).await;
        }
      }
      inst.remove_context(&key.context);
    }
  }

  /// # Errors
  ///
  /// Returns an error if the context does not exist or the page index is out of range.
  pub fn select_page(&mut self, context: &str, page_idx: usize) -> Result<()> {
    let key = SessionKey::parse(context);
    let inst = self.instance_mut(&key.instance)?;
    let ctx = inst.context_mut_checked(&key.context)?;
    if page_idx >= ctx.pages.len() {
      return Err(FerriError::Backend(format!(
        "Page index {page_idx} out of range (context '{context}' has {} pages)",
        ctx.pages.len()
      )));
    }
    ctx.active_page_idx = page_idx;
    Ok(())
  }

  /// # Errors
  ///
  /// Returns an error if this is the last page, context does not exist, or index is out of range.
  pub fn close_page(&mut self, context: &str, page_idx: usize) -> Result<()> {
    let key = SessionKey::parse(context);
    let inst = self.instance_mut(&key.instance)?;
    let ctx = inst.context_mut_checked(&key.context)?;
    if ctx.pages.len() <= 1 {
      return Err(FerriError::invalid_argument(
        "page",
        "Cannot close the last page in a context",
      ));
    }
    if page_idx >= ctx.pages.len() {
      return Err(FerriError::Backend(format!("Page index {page_idx} out of range")));
    }
    ctx.pages.remove(page_idx);
    if ctx.active_page_idx >= ctx.pages.len() {
      ctx.active_page_idx = ctx.pages.len() - 1;
    }
    Ok(())
  }

  pub async fn list_contexts(&self) -> Vec<ContextInfo> {
    let mut result = Vec::new();
    for (inst_name, inst) in &self.instances {
      for (ctx_name, ctx) in &inst.contexts {
        let mut pages = Vec::new();
        for (i, page) in ctx.pages.iter().enumerate() {
          let url = page.url().await.ok().flatten().unwrap_or_default();
          let title = page.title().await.ok().flatten().unwrap_or_default();
          pages.push(PageInfo {
            index: i,
            url,
            title,
            active: i == ctx.active_page_idx,
          });
        }
        // Use composite name for non-default instances, bare name for default
        let name = if inst_name == "default" {
          ctx_name.clone()
        } else {
          format!("{inst_name}:{ctx_name}")
        };
        result.push(ContextInfo {
          name,
          instance: inst_name.clone(),
          context: ctx_name.clone(),
          pages,
        });
      }
    }
    result.sort_by(|a, b| a.name.cmp(&b.name));
    result
  }

  /// Store a new ref map for the given context (atomic, no `&mut self` needed).
  pub fn set_ref_map(&self, context: &str, ref_map: HashMap<String, i64>) {
    let key = SessionKey::parse(context);
    if let Some(inst) = self.instances.get(&*key.instance) {
      if let Some(ctx) = inst.contexts.get(&*key.context) {
        ctx.ref_map.store(std::sync::Arc::new(ref_map));
      }
    }
  }

  #[must_use]
  pub fn ref_map(&self, context: &str) -> HashMap<String, i64> {
    let key = SessionKey::parse(context);
    self
      .instances
      .get(&*key.instance)
      .and_then(|inst| inst.contexts.get(&*key.context))
      .map(|c| (**c.ref_map.load()).clone())
      .unwrap_or_default()
  }

  /// Get an `Arc` handle to a context's ref map `ArcSwap` for lock-free access.
  #[must_use]
  pub fn ref_map_handle(&self, context: &str) -> Option<std::sync::Arc<arc_swap::ArcSwap<HashMap<String, i64>>>> {
    let key = SessionKey::parse(context);
    self
      .instances
      .get(&*key.instance)
      .and_then(|inst| inst.contexts.get(&*key.context))
      .map(|c| std::sync::Arc::clone(&c.ref_map))
  }

  /// Get `Arc` handles to a context's log collections for lock-free access.
  #[must_use]
  pub fn log_handles(&self, context: &str) -> Option<ContextLogHandles> {
    let key = SessionKey::parse(context);
    self
      .instances
      .get(&*key.instance)
      .and_then(|inst| inst.contexts.get(&*key.context))
      .map(|ctx| ContextLogHandles {
        console: std::sync::Arc::clone(&ctx.console_log),
        network: std::sync::Arc::clone(&ctx.network_log),
        dialog: std::sync::Arc::clone(&ctx.dialog_log),
      })
  }

  /// # Errors
  ///
  /// Returns an error if the instance or context does not exist.
  pub async fn console_messages(
    &self,
    context: &str,
    level: Option<&str>,
    limit: usize,
  ) -> Result<Vec<ConsoleMessage>> {
    let key = SessionKey::parse(context);
    let inst = self.instance(&key.instance)?;
    let ctx = inst.context(&key.context)?;
    Ok(ctx.console_messages(level, limit).await)
  }

  /// # Errors
  ///
  /// Returns an error if the instance or context does not exist.
  pub async fn network_requests(&self, context: &str, limit: usize) -> Result<Vec<Request>> {
    let key = SessionKey::parse(context);
    let inst = self.instance(&key.instance)?;
    let ctx = inst.context(&key.context)?;
    Ok(ctx.network_requests(limit).await)
  }

  /// # Errors
  ///
  /// Returns an error if the instance or context does not exist, or page discovery fails.
  pub async fn refresh_pages(&mut self, context: &str) -> Result<usize> {
    let key = SessionKey::parse(context);
    let inst = self.instance_mut(&key.instance)?;
    let current_pages = Box::pin(inst.browser.pages()).await?;
    let ctx = inst.context_mut_checked(&key.context)?;

    let existing_count = ctx.pages.len();
    if current_pages.len() > existing_count {
      for page in current_pages.into_iter().skip(existing_count) {
        page.attach_listeners(ctx.console_log.clone(), ctx.network_log.clone(), ctx.dialog_log.clone());
        ctx.pages.push(page);
      }
    }
    Ok(ctx.pages.len())
  }

  /// # Errors
  ///
  /// Returns an error if the instance or context does not exist.
  pub async fn dialog_messages(&self, context: &str, limit: usize) -> Result<Vec<DialogEvent>> {
    let key = SessionKey::parse(context);
    let inst = self.instance(&key.instance)?;
    let ctx = inst.context(&key.context)?;
    Ok(ctx.dialog_messages(limit).await)
  }

  pub async fn shutdown(&mut self) {
    self.connected.store(false, std::sync::atomic::Ordering::Relaxed);
    for (_, mut inst) in self.instances.drain() {
      inst.contexts.clear();
      let _ = inst.browser.close().await;
    }
  }

  #[must_use]
  pub fn is_connected(&self) -> bool {
    !self.instances.is_empty()
  }

  fn next_instance_generation(&mut self) -> u64 {
    self.instance_generation_counter += 1;
    self.instance_generation_counter
  }

  /// Current generation of the named instance, or `None` if no instance
  /// by that name is live. A changed value (including `Some`→`None`→
  /// `Some`) means the browser session was swapped: any state a consumer
  /// cached against the old session is stale.
  #[must_use]
  pub fn instance_generation(&self, instance: &str) -> Option<u64> {
    self.instances.get(instance).map(|i| i.generation)
  }
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct ContextInfo {
  pub name: String,
  pub instance: String,
  pub context: String,
  pub pages: Vec<PageInfo>,
}

// Backward-compat alias for code that still references SessionInfo.
pub type SessionInfo = ContextInfo;

#[derive(Debug, Clone, serde::Serialize)]
pub struct PageInfo {
  pub index: usize,
  pub url: String,
  pub title: String,
  pub active: bool,
}

/// Discover the WebSocket URL from an HTTP debug endpoint.
async fn discover_ws_from_http(http_url: &str) -> Result<String> {
  use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};

  let url = http_url.trim_end_matches('/');
  let host_port = url
    .strip_prefix("http://")
    .ok_or_else(|| FerriError::invalid_argument("url", format!("Expected http:// URL, got {http_url}")))?;

  let stream = tokio::net::TcpStream::connect(host_port)
    .await
    .map_err(|e| FerriError::backend(format!("Cannot connect to {host_port}: {e}")))?;
  let (reader, mut writer) = stream.into_split();
  let req = format!("GET /json/version HTTP/1.1\r\nHost: {host_port}\r\nConnection: close\r\n\r\n");
  writer
    .write_all(req.as_bytes())
    .await
    .map_err(|e| FerriError::backend(format!("Write: {e}")))?;

  let mut buf_reader = BufReader::new(reader);
  let mut content_length: usize = 0;
  loop {
    let mut line = String::new();
    buf_reader
      .read_line(&mut line)
      .await
      .map_err(|e| FerriError::backend(format!("Read header: {e}")))?;
    let trimmed = line.trim();
    if trimmed.is_empty() {
      break;
    }
    if let Some(val) = trimmed.strip_prefix("Content-Length:") {
      content_length = val.trim().parse().unwrap_or(0);
    }
    if let Some(val) = trimmed.strip_prefix("content-length:") {
      content_length = val.trim().parse().unwrap_or(0);
    }
  }

  let mut body = vec![0u8; content_length.max(4096)];
  let n = buf_reader
    .read(&mut body)
    .await
    .map_err(|e| FerriError::backend(format!("Read body: {e}")))?;
  let body_str = String::from_utf8_lossy(&body[..n]);

  let json: serde_json::Value =
    serde_json::from_str(&body_str).map_err(|e| FerriError::Backend(format!("Parse /json/version: {e}")))?;

  json
    .get("webSocketDebuggerUrl")
    .and_then(|v| v.as_str())
    .map(std::string::ToString::to_string)
    .ok_or_else(|| FerriError::backend("No webSocketDebuggerUrl in /json/version"))
}

/// Discover a running Chrome instance by reading its `DevToolsActivePort` file.
fn discover_chrome_ws(channel: &str, explicit_user_data_dir: Option<&str>) -> Result<String> {
  let user_data_dir = if let Some(dir) = explicit_user_data_dir {
    std::path::PathBuf::from(dir)
  } else {
    chrome_default_user_data_dir(channel)?
  };

  let port_file = user_data_dir.join("DevToolsActivePort");
  let content = std::fs::read_to_string(&port_file).map_err(|e| {
    format!(
      "Cannot read {}: {e}. Ensure Chrome ({channel}) is running and \
             remote debugging is enabled at chrome://inspect/#remote-debugging",
      port_file.display()
    )
  })?;

  let lines: Vec<&str> = content.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
  if lines.len() < 2 {
    return Err(FerriError::Backend(format!(
      "Invalid DevToolsActivePort content: {content:?}"
    )));
  }

  let port: u16 = lines[0]
    .parse()
    .map_err(|_| FerriError::Backend(format!("Invalid port '{}' in DevToolsActivePort", lines[0])))?;
  let path = lines[1];

  Ok(format!("ws://127.0.0.1:{port}{path}"))
}

fn chrome_default_user_data_dir(channel: &str) -> Result<std::path::PathBuf> {
  let home = std::env::var("HOME")
    .or_else(|_| std::env::var("USERPROFILE"))
    .map_err(|_| FerriError::backend("Cannot determine home directory"))?;

  let os = std::env::consts::OS;
  let suffix = match channel {
    "stable" | "chrome" => "",
    "beta" => " Beta",
    "dev" => " Dev",
    "canary" => " Canary",
    other => {
      return Err(FerriError::invalid_argument(
        "channel",
        format!("unknown Chrome channel: {other}"),
      ));
    },
  };

  let path = match os {
    "linux" => {
      let dir_name = if suffix.is_empty() {
        "google-chrome".to_string()
      } else {
        format!("google-chrome{}", suffix.to_lowercase().replace(' ', "-"))
      };
      std::path::PathBuf::from(&home).join(".config").join(dir_name)
    },
    "macos" => std::path::PathBuf::from(&home)
      .join("Library/Application Support")
      .join(format!("Google/Chrome{suffix}")),
    "windows" => {
      let local_app_data = std::env::var("LOCALAPPDATA").unwrap_or_else(|_| format!("{home}/AppData/Local"));
      std::path::PathBuf::from(local_app_data).join(format!("Google/Chrome{suffix}/User Data"))
    },
    _ => {
      return Err(FerriError::unsupported(format!("OS: {os}")));
    },
  };

  if !path.exists() {
    let chromium_path = match os {
      "linux" => std::path::PathBuf::from(&home).join(".config/chromium"),
      "macos" => std::path::PathBuf::from(&home).join("Library/Application Support/Chromium"),
      _ => {
        return Err(FerriError::Backend(format!(
          "Chrome user data dir not found: {}",
          path.display()
        )));
      },
    };
    if chromium_path.exists() {
      return Ok(chromium_path);
    }
    return Err(FerriError::Backend(format!(
      "Chrome user data dir not found at {} or {}",
      path.display(),
      chromium_path.display()
    )));
  }

  Ok(path)
}

/// Common Chrome/Chromium launch flags used by cdp-pipe and cdp-raw backends.
#[must_use]
/// Build Chrome flags matching Playwright's launch sequence exactly.
/// Order: chromiumSwitches → headless flags → sandbox → user args.
pub fn chrome_flags(headless: bool, extra_args: &[String]) -> Vec<String> {
  let mut flags: Vec<String> = Vec::with_capacity(40 + extra_args.len());

  // 1. Base chromiumSwitches (from Playwright's chromiumSwitches.ts)
  for f in CHROMIUM_SWITCHES {
    flags.push((*f).into());
  }

  // 2. Always added after base switches
  flags.push("--enable-unsafe-swiftshader".into());

  // 3. Headless flags (Playwright adds these when headless=true).
  // Playwright passes bare `--headless` too — Chrome maps to
  // `--headless=old` on full chrome. The 2x perf gap on Regular
  // Chrome lives elsewhere, not in this flag (verified via
  // playwright-core/lib/server/chromium/chromium.js:288).
  if headless {
    flags.push("--headless".into());
    flags.push("--hide-scrollbars".into());
    flags.push("--mute-audio".into());
    // `preferredColorScheme=1` pins Blink's "no override" baseline to
    // light. Without it, headless Chrome inherits the host's GTK / KDE
    // dark-mode setting, which causes `matchMedia('(prefers-color-scheme:
    // dark)').matches` to stay `true` even after
    // `page.emulateMedia({colorScheme: null})` clears the override —
    // the override is gone but the system fallback is still dark.
    // Tests that rely on "null reset returns to light" only pass on
    // light-mode hosts otherwise. Playwright's own chromiumSwitches
    // skip this because their CI runs on light-mode hosts; we cover
    // both.
    flags.push(
      "--blink-settings=primaryHoverType=2,availableHoverTypes=2,primaryPointerType=4,availablePointerTypes=4,preferredColorScheme=1".into(),
    );
  }

  // 4. Sandbox control (Playwright disables by default unless chromiumSandbox=true)
  flags.push("--no-sandbox".into());

  // 5. User-provided args
  for arg in extra_args {
    flags.push(arg.clone());
  }

  flags
}

/// Chrome switches matching Playwright's `chromiumSwitches()` exactly.
/// See: playwright/packages/playwright-core/src/server/chromium/chromiumSwitches.ts
const CHROMIUM_SWITCHES: &[&str] = &[
  "--disable-field-trial-config",
  "--disable-background-networking",
  "--disable-background-timer-throttling",
  "--disable-backgrounding-occluded-windows",
  "--disable-back-forward-cache",
  "--disable-breakpad",
  "--disable-client-side-phishing-detection",
  "--disable-component-extensions-with-background-pages",
  "--disable-component-update",
  "--no-default-browser-check",
  "--disable-default-apps",
  "--disable-dev-shm-usage",
  "--disable-edgeupdater",
  "--disable-extensions",
  "--disable-features=AvoidUnnecessaryBeforeUnloadCheckSync,BlockInsecurePrivateNetworkRequests,BoundaryEventDispatchTracksNodeRemoval,DestroyProfileOnBrowserClose,DialMediaRouteProvider,GlobalMediaControls,HttpsUpgrades,LensOverlay,MediaRouter,PaintHolding,PrivateNetworkAccessSendPreflights,ThirdPartyStoragePartitioning,Translate,AutoDeElevate,RenderDocument,OptimizationHints,msForceBrowserSignIn,msEdgeUpdateLaunchServicesPreferredVersion",
  "--enable-features=CDPScreenshotNewSurface",
  "--allow-pre-commit-input",
  "--disable-hang-monitor",
  "--disable-ipc-flooding-protection",
  "--disable-popup-blocking",
  "--disable-prompt-on-repost",
  "--disable-renderer-backgrounding",
  "--force-color-profile=srgb",
  "--metrics-recording-only",
  "--no-first-run",
  "--password-store=basic",
  "--use-mock-keychain",
  "--no-service-autorun",
  "--export-tagged-pdf",
  "--disable-search-engine-choice-screen",
  "--unsafely-disable-devtools-self-xss-warnings",
  "--edge-skip-compat-layer-relaunch",
  "--enable-automation",
  "--disable-infobars",
  "--disable-sync",
];

/// Resolve the Chrome binary to use, respecting env vars and headless mode.
///
/// Follows Playwright's resolution strategy:
/// - `executablePath` (handled by caller before this function) always wins.
/// - Explicit env vars (`CHROMIUM_HEADLESS_SHELL_PATH`, `CHROMIUM_PATH`) override auto-detection.
/// - When headless and no explicit path is set, prefer Chrome Headless Shell (lighter, faster).
/// - Fall back to full Chrome/Chromium otherwise.
///
/// Precedence (headless=true):
/// 1. `CHROMIUM_HEADLESS_SHELL_PATH` env var
/// 2. `CHROMIUM_PATH` env var (explicit user override always wins over auto-detection)
/// 3. Auto-detect headless shell (Playwright cache, ferridriver cache)
/// 4. Auto-detect regular Chrome (`detect_chromium()`)
///
/// Precedence (headless=false):
/// 1. `CHROMIUM_PATH` env var
/// 2. Auto-detect regular Chrome (`detect_chromium()`)
#[must_use]
pub fn resolve_chromium(headless: bool) -> String {
  if headless {
    // Explicit headless shell path
    if let Ok(p) = std::env::var("CHROMIUM_HEADLESS_SHELL_PATH") {
      if std::path::Path::new(&p).exists() {
        return p;
      }
    }

    // Explicit chrome path -- user chose a specific binary, respect it
    if let Ok(p) = std::env::var("CHROMIUM_PATH") {
      if std::path::Path::new(&p).exists() {
        return p;
      }
    }

    // Auto-detect headless shell (Playwright cache, ferridriver cache)
    if let Some(p) = detect_chromium_headless_shell() {
      return p;
    }
  }

  // Headed mode, or no headless shell found: use regular Chrome
  detect_chromium()
}

/// Auto-detect Chrome Headless Shell binary on the system.
///
/// Searches Playwright's cache and ferridriver's own cache for installed
/// headless shell binaries. Does NOT check env vars (that's `resolve_chromium()`'s job).
#[must_use]
pub fn detect_chromium_headless_shell() -> Option<String> {
  // Check Playwright's cache for headless shell
  if let Some(p) = find_playwright_headless_shell() {
    return Some(p);
  }

  // Check ferridriver's own cache
  if let Some(p) = crate::install::BrowserInstaller::new().find_installed_headless_shell() {
    return Some(p);
  }

  None
}

/// Detect Chrome/Chromium binary on the system.
#[must_use]
pub fn detect_chromium() -> String {
  if let Ok(p) = std::env::var("CHROMIUM_PATH") {
    if std::path::Path::new(&p).exists() {
      return p;
    }
  }

  // Check for Playwright's bundled Chrome first (most up-to-date, best tested).
  // Follows Playwright's registry logic: PLAYWRIGHT_BROWSERS_PATH, then XDG_CACHE_HOME, then ~/.cache.
  let pw_cache = if let Ok(p) = std::env::var("PLAYWRIGHT_BROWSERS_PATH") {
    Some(std::path::PathBuf::from(p))
  } else {
    std::env::var("XDG_CACHE_HOME")
      .ok()
      .or_else(|| std::env::var("HOME").ok().map(|h| format!("{h}/.cache")))
      .map(|c| std::path::PathBuf::from(c).join("ms-playwright"))
  };
  if let Some(pw_cache) = pw_cache {
    if pw_cache.is_dir() {
      // Find the latest chromium-* directory
      if let Ok(entries) = std::fs::read_dir(&pw_cache) {
        let mut candidates: Vec<_> = entries
          .filter_map(std::result::Result::ok)
          .filter(|e| e.file_name().to_string_lossy().starts_with("chromium-"))
          .collect();
        candidates.sort_by_key(|b| std::cmp::Reverse(b.file_name())); // newest first
        for entry in candidates {
          let chrome = entry.path().join("chrome-linux64/chrome");
          if chrome.exists() {
            return chrome.to_string_lossy().to_string();
          }
          let chrome_mac = entry.path().join("chrome-mac/Chromium.app/Contents/MacOS/Chromium");
          if chrome_mac.exists() {
            return chrome_mac.to_string_lossy().to_string();
          }
        }
      }
    }
  }

  if let Ok(path_var) = std::env::var("PATH") {
    let names = [
      "google-chrome-stable",
      "google-chrome",
      "chromium-browser",
      "chromium",
      "microsoft-edge",
      "chrome",
    ];
    for name in &names {
      for dir in path_var.split(':') {
        let candidate = std::path::PathBuf::from(dir).join(name);
        if candidate.exists() {
          return candidate.to_string_lossy().to_string();
        }
      }
    }
  }

  #[cfg(target_os = "macos")]
  {
    let bundles = [
      "Google Chrome.app/Contents/MacOS/Google Chrome",
      "Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
      "Chromium.app/Contents/MacOS/Chromium",
      "Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
    ];
    for bundle in &bundles {
      let sys = std::path::PathBuf::from("/Applications").join(bundle);
      if sys.exists() {
        return sys.to_string_lossy().to_string();
      }
      if let Ok(home) = std::env::var("HOME") {
        let user = std::path::PathBuf::from(&home).join("Applications").join(bundle);
        if user.exists() {
          return user.to_string_lossy().to_string();
        }
      }
    }
  }

  #[cfg(target_os = "linux")]
  {
    let paths = [
      "/usr/bin/google-chrome-stable",
      "/usr/bin/google-chrome",
      "/usr/bin/chromium-browser",
      "/usr/bin/chromium",
      "/snap/bin/chromium",
      "/usr/bin/microsoft-edge",
    ];
    for path in &paths {
      if std::path::Path::new(path).exists() {
        return path.to_string();
      }
    }
  }

  // Check ferridriver's own browser cache
  if let Some(p) = crate::install::BrowserInstaller::new().find_installed_chromium() {
    return p;
  }

  if let Some(p) = find_playwright_chrome() {
    return p;
  }

  "chromium".to_string()
}

/// Detect Firefox binary on the system.
///
/// Search order (matches Chrome detection pattern):
/// 1. `FIREFOX_PATH` environment variable
/// 2. ferridriver's own browser cache (installed via `install_firefox()`)
/// 3. Playwright's browser cache
/// 4. System-installed Firefox (platform-specific paths)
/// 5. `which firefox` fallback
///
/// # Errors
///
/// Returns an error if no Firefox binary can be found.
pub fn detect_firefox() -> Result<String> {
  // 1. Env var (highest priority)
  if let Ok(p) = std::env::var("FIREFOX_PATH") {
    if std::path::Path::new(&p).exists() {
      return Ok(p);
    }
  }

  // 2. ferridriver's own cache
  if let Some(p) = crate::install::BrowserInstaller::new().find_installed_firefox() {
    return Ok(p);
  }

  // 3. Playwright's Firefox cache
  if let Some(p) = find_playwright_firefox() {
    return Ok(p);
  }

  // 4. System-installed Firefox
  #[cfg(target_os = "macos")]
  {
    let paths = [
      "/Applications/Firefox.app/Contents/MacOS/firefox",
      "/Applications/Firefox Nightly.app/Contents/MacOS/firefox",
      "/Applications/Firefox Developer Edition.app/Contents/MacOS/firefox",
    ];
    for path in &paths {
      if std::path::Path::new(path).exists() {
        return Ok(path.to_string());
      }
    }
  }

  #[cfg(target_os = "linux")]
  {
    // Skip snap-wrapped Firefox builds: Ubuntu 24.04+ ships a snap as
    // /usr/bin/firefox (and the explicit /snap/bin/firefox). Snap's
    // confinement blocks the WebDriver BiDi remote-debugging port and the
    // shim never prints the WebSocket URL on stderr, so detection hangs
    // until the 15s discovery timeout. Treat snap wrappers as
    // "not installed" so callers fall back to ferridriver's own download.
    let paths = [
      "/usr/bin/firefox",
      "/usr/bin/firefox-esr",
      "/snap/bin/firefox",
      "/usr/lib/firefox/firefox",
      "/usr/lib64/firefox/firefox",
    ];
    for path in &paths {
      let p = std::path::Path::new(path);
      if !p.exists() {
        continue;
      }
      let resolved = std::fs::canonicalize(p).map_or_else(|_| path.to_string(), |c| c.to_string_lossy().to_string());
      if resolved.contains("/snap/") {
        continue;
      }
      return Ok(path.to_string());
    }
  }

  #[cfg(target_os = "windows")]
  {
    let paths = [
      r"C:\Program Files\Mozilla Firefox\firefox.exe",
      r"C:\Program Files (x86)\Mozilla Firefox\firefox.exe",
    ];
    for path in &paths {
      if std::path::Path::new(path).exists() {
        return Ok(path.to_string());
      }
    }
  }

  // 5. which/where fallback
  let cmd = if cfg!(windows) { "where" } else { "which" };
  if let Ok(output) = std::process::Command::new(cmd).arg("firefox").output() {
    if output.status.success() {
      let p = String::from_utf8_lossy(&output.stdout)
        .lines()
        .next()
        .unwrap_or("")
        .trim()
        .to_string();
      if !p.is_empty() && std::path::Path::new(&p).exists() {
        return Ok(p);
      }
    }
  }

  Err(FerriError::backend(
    "Firefox not found. Install with `ferridriver install firefox` or set FIREFOX_PATH.",
  ))
}

/// Search Playwright's cache for an installed Firefox binary.
fn find_playwright_firefox() -> Option<String> {
  let home = std::env::var("HOME").ok()?;

  #[cfg(target_os = "macos")]
  let cache_base = std::path::PathBuf::from(&home).join("Library/Caches/ms-playwright");
  #[cfg(target_os = "linux")]
  let cache_base = std::env::var("XDG_CACHE_HOME")
    .map_or_else(
      |_| std::path::PathBuf::from(&home).join(".cache"),
      std::path::PathBuf::from,
    )
    .join("ms-playwright");
  #[cfg(target_os = "windows")]
  let cache_base = std::env::var("LOCALAPPDATA")
    .map(std::path::PathBuf::from)
    .unwrap_or_else(|_| std::path::PathBuf::from(&home))
    .join("ms-playwright");

  let entries = std::fs::read_dir(&cache_base).ok()?;
  let mut firefox_dirs: Vec<_> = entries
    .filter_map(std::result::Result::ok)
    .filter(|e| {
      let name = e.file_name().to_string_lossy().to_string();
      name.starts_with("firefox-")
    })
    .collect();
  firefox_dirs.sort_by_key(|b| std::cmp::Reverse(b.file_name()));

  for dir in firefox_dirs {
    let path = dir.path();
    #[cfg(target_os = "macos")]
    let exe = path.join("Firefox.app/Contents/MacOS/firefox");
    #[cfg(target_os = "linux")]
    let exe = path.join("firefox/firefox");
    #[cfg(target_os = "windows")]
    let exe = path.join("firefox/firefox.exe");

    if exe.exists() {
      return Some(exe.to_string_lossy().to_string());
    }
  }
  None
}

/// Search Playwright's cache dir for a Chrome Headless Shell binary.
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn find_playwright_headless_shell() -> Option<String> {
  let home = std::env::var("HOME").ok()?;

  #[cfg(target_os = "macos")]
  let cache_dir = std::path::PathBuf::from(&home).join("Library/Caches/ms-playwright");
  #[cfg(target_os = "linux")]
  let cache_dir = std::path::PathBuf::from(&home).join(".cache/ms-playwright");

  if !cache_dir.exists() {
    return None;
  }

  let mut best_rev: u32 = 0;
  let mut best_name = String::new();
  let prefix = "chromium_headless_shell-";

  if let Ok(entries) = std::fs::read_dir(&cache_dir) {
    for entry in entries.flatten() {
      let name = entry.file_name().to_string_lossy().to_string();
      if let Some(rev_str) = name.strip_prefix(prefix) {
        if let Ok(rev) = rev_str.parse::<u32>() {
          if rev > best_rev {
            best_rev = rev;
            best_name = name;
          }
        }
      }
    }
  }

  if best_rev == 0 {
    return None;
  }

  #[cfg(target_os = "macos")]
  let arch = if cfg!(target_arch = "aarch64") { "arm64" } else { "x64" };
  #[cfg(target_os = "linux")]
  let arch = if cfg!(target_arch = "aarch64") { "arm64" } else { "x64" };

  #[cfg(target_os = "macos")]
  let plat = "mac";
  #[cfg(target_os = "linux")]
  let plat = "linux";

  let cft_binary = cache_dir
    .join(&best_name)
    .join(format!("chrome-headless-shell-{plat}-{arch}"))
    .join("chrome-headless-shell");

  if cft_binary.exists() {
    return Some(cft_binary.to_string_lossy().to_string());
  }

  None
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn find_playwright_headless_shell() -> Option<String> {
  None
}

/// Search Playwright's cache dir for a chromium headless shell binary.
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn find_playwright_chrome() -> Option<String> {
  let home = std::env::var("HOME").ok()?;

  #[cfg(target_os = "macos")]
  let cache_dir = std::path::PathBuf::from(&home).join("Library/Caches/ms-playwright");
  #[cfg(target_os = "linux")]
  let cache_dir = std::path::PathBuf::from(&home).join(".cache/ms-playwright");

  if !cache_dir.exists() {
    return None;
  }

  let mut best_rev: u32 = 0;
  let mut best_name = String::new();
  let prefix = "chromium_headless_shell-";

  if let Ok(entries) = std::fs::read_dir(&cache_dir) {
    for entry in entries.flatten() {
      let name = entry.file_name().to_string_lossy().to_string();
      if let Some(rev_str) = name.strip_prefix(prefix) {
        if let Ok(rev) = rev_str.parse::<u32>() {
          if rev > best_rev {
            best_rev = rev;
            best_name = name;
          }
        }
      }
    }
  }

  if best_rev == 0 {
    return None;
  }

  #[cfg(target_os = "macos")]
  let arch = if cfg!(target_arch = "aarch64") { "arm64" } else { "x64" };
  #[cfg(target_os = "linux")]
  let arch = if cfg!(target_arch = "aarch64") { "arm64" } else { "x64" };

  #[cfg(target_os = "macos")]
  let plat = "mac";
  #[cfg(target_os = "linux")]
  let plat = "linux";

  let cft_binary = cache_dir
    .join(&best_name)
    .join(format!("chrome-headless-shell-{plat}-{arch}"))
    .join("chrome-headless-shell");

  if cft_binary.exists() {
    return Some(cft_binary.to_string_lossy().to_string());
  }

  #[cfg(target_os = "linux")]
  {
    let alt_binary = cache_dir.join(&best_name).join("chrome-linux").join("headless_shell");
    if alt_binary.exists() {
      return Some(alt_binary.to_string_lossy().to_string());
    }
  }

  None
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn find_playwright_chrome() -> Option<String> {
  None
}

#[cfg(test)]
mod tests {
  use std::sync::Arc;

  use super::*;
  use crate::backend::BackendKind;

  /// Test helper: build a `BrowserState` with the minimum `LaunchPlan`
  /// needed to exercise the resolver/args plumbing. Using
  /// `LaunchPlan::default()` keeps these tests in lock-step with the
  /// single production construction path ([`BrowserState::with_plan`]).
  fn test_state(backend: BackendKind) -> BrowserState {
    let kind = match backend {
      BackendKind::Bidi => crate::options::BrowserKind::Firefox,
      _ => crate::options::BrowserKind::Chromium,
    };
    BrowserState::with_plan(
      ConnectMode::Launch,
      crate::options::LaunchPlan {
        backend,
        kind,
        headless: false,
        ..Default::default()
      },
    )
  }

  #[test]
  fn test_instance_resolver_none_by_default() {
    let state = test_state(BackendKind::CdpPipe);
    assert!(state.instance_resolver_fn.is_none());
  }

  #[test]
  fn test_instance_resolver_returns_connect_url() {
    let mut state = test_state(BackendKind::CdpPipe);
    state.set_instance_resolver_fn(Box::new(|instance| match instance {
      "staging" => Some(ConnectMode::ConnectUrl(
        "ws://127.0.0.1:9222/devtools/browser/abc".to_owned(),
      )),
      _ => None,
    }));

    // Resolver returns Some for "staging"
    let resolved = state.instance_resolver_fn.as_ref().unwrap()("staging");
    assert!(matches!(resolved, Some(ConnectMode::ConnectUrl(url)) if url.contains("9222")));

    // Resolver returns None for unknown instance (falls through to default)
    let resolved = state.instance_resolver_fn.as_ref().unwrap()("unknown");
    assert!(resolved.is_none());
  }

  #[test]
  fn test_instance_args_fn_independent_of_resolver() {
    let mut state = test_state(BackendKind::CdpPipe);

    state.set_instance_args_fn(Box::new(|instance| vec![format!("--window-name={instance}")]));

    state.set_instance_resolver_fn(Box::new(|_| None));

    // Both callbacks set independently
    let args = state.instance_args_fn.as_ref().unwrap()("dev");
    assert_eq!(args, vec!["--window-name=dev"]);

    let resolved = state.instance_resolver_fn.as_ref().unwrap()("dev");
    assert!(resolved.is_none());
  }

  #[tokio::test]
  async fn test_ensure_instance_uses_resolver_for_connect() {
    // Bind then drop to get a port that's definitely not listening.
    let port = {
      let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
      l.local_addr().unwrap().port()
      // listener drops here, port is free
    };

    let mut state = test_state(BackendKind::CdpRaw);
    state.set_instance_resolver_fn(Box::new(move |instance| {
      if instance == "test-resolved" {
        Some(ConnectMode::ConnectUrl(format!(
          "ws://127.0.0.1:{port}/devtools/browser/test"
        )))
      } else {
        None
      }
    }));

    // Should attempt WebSocket connection to the dead port (fails fast with
    // "connection refused"), proving the resolver was invoked instead of launching.
    let result = Box::pin(state.ensure_instance("test-resolved")).await;
    assert!(
      result.is_err(),
      "Should fail with connection refused, proving resolver was invoked"
    );
    let err = result.unwrap_err().to_string();
    assert!(
      !err.contains("not found") && !err.contains("No such file"),
      "Error should be connection-related, not binary-not-found: {err}"
    );
  }

  #[tokio::test]
  async fn test_ensure_instance_skips_resolver_when_exists() {
    use std::sync::atomic::{AtomicU32, Ordering};

    let call_count = Arc::new(AtomicU32::new(0));
    let counter = Arc::clone(&call_count);

    let mut state = test_state(BackendKind::CdpPipe);
    state.set_instance_resolver_fn(Box::new(move |_| {
      counter.fetch_add(1, Ordering::Relaxed);
      None // Fall through to default
    }));

    // First call: resolver should be called (but will fall through and try to launch)
    let _ = Box::pin(state.ensure_instance("test")).await;
    // Resolver was called exactly once (regardless of whether launch succeeded)
    assert_eq!(call_count.load(Ordering::Relaxed), 1);
  }
}