runtime-foxdriver 0.1.0

Firefox browser automation via WebDriver BiDi (rustenium)
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
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
//! Firefox browser automation via rustenium (WebDriver BiDi).

use anyhow::{anyhow, Result};
use base64::Engine as _;
use rustenium::browsers::{
    firefox, BidiBrowser, EvaluateScriptOptionsBuilder, FirefoxBrowser, FirefoxCapabilities,
    FirefoxConfig, FirefoxLaunchMode,
};
use rustenium::input::{
    Mouse, MouseButton, MouseClickOptions, MouseMoveOptions, MouseOptions, MouseWheelOptions, Point,
};
use rustenium::nodes::Node;
use rustenium_bidi_definitions::browsing_context::commands::HandleUserPrompt;
use rustenium_bidi_definitions::browsing_context::types::{CssLocator, CssLocatorType, Locator};
use rustenium_bidi_definitions::network::types::{BytesValue, SameSite, StringValue, StringValueType};
use rustenium_bidi_definitions::input::commands::SetFiles;
use rustenium_bidi_definitions::script::types::{ContextTarget, RemoteValue, SharedReference, Target};
use rustenium_bidi_definitions::session::types::{UnhandledPromptBehavior, UserPromptHandlerType};
use rustenium_bidi_definitions::storage::commands::{GetCookies, SetCookie, SetCookieParams};
use rustenium_bidi_definitions::storage::types::PartialCookie;
use serde::de::DeserializeOwned;
use std::collections::HashSet;

/// Wrapper around rustenium's `FirefoxBrowser`.
pub struct Page {
    browser: tokio::sync::Mutex<Option<FoxBrowser>>,
    profile_dir: Option<String>,
    /// Child process when foxdriver spawned the browser itself (the
    /// [`launch_firefox_self_managed`] / Remote-attach path). In the normal
    /// `SpawnAndAttach` path rustenium owns the process (`kill_on_drop`), so
    /// this is `None`; when foxdriver owns the spawn it must kill it here.
    child: std::sync::Mutex<Option<std::process::Child>>,
}

impl Drop for Page {
    fn drop(&mut self) {
        // Best-effort synchronous cleanup: take the browser out of the
        // mutex and drop it.  The underlying `Process` is spawned with
        // `kill_on_drop(true)`, so dropping kills the Firefox process.
        if let Ok(mut guard) = self.browser.try_lock() {
            let _ = guard.take();
        }
        // A self-managed child (Remote-attach path) is not owned by rustenium —
        // kill it explicitly so a self-spawned reynard/Camoufox never leaks.
        if let Ok(mut child) = self.child.try_lock() {
            if let Some(mut c) = child.take() {
                let _ = c.kill();
            }
        }
    }
}

/// Opaque handle to a browsing context (tab or iframe).
pub type FrameId = rustenium_bidi_definitions::browsing_context::types::BrowsingContext;

/// A browsing context (frame) with the metadata the agent needs to target it:
/// the opaque `id` to pass back on a frame-scoped command, plus its `url` and
/// `name` for disambiguation. Returned by [`Page::list_frames`].
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct FrameInfo {
    /// Opaque browsing-context id — pass this back as the `frame` target.
    pub id: String,
    /// The frame's current document URL (`about:blank` for a fresh frame).
    pub url: String,
    /// The frame's `window.name`, empty when unset.
    pub name: String,
    /// `true` for the top-level document, `false` for an iframe.
    pub is_main: bool,
}

/// A parsed frame target — the pure classification of a `frame=` spec, factored
/// out of [`Page::resolve_frame`] so the parsing rules are unit-testable without
/// a live browser.
#[derive(Debug, Clone, PartialEq)]
enum FrameSpec {
    /// The top-level document (`""`, `main`, `top`).
    Main,
    /// Strictly a 0-based index into the frame list (`index:<n>`).
    Index(usize),
    /// A bare all-digit spec: Firefox BiDi context ids are ALSO all-digits
    /// (e.g. `10737418241`), so this is ambiguous — resolve as an exact id
    /// FIRST, then fall back to the index. `0` carries the parsed index.
    IdOrIndex(String, usize),
    /// Exact browsing-context id, with a URL-substring fallback.
    Id(String),
    /// First frame whose URL contains this substring (`url:<substr>`).
    UrlContains(String),
    /// First frame whose `window.name` equals this (`name:<name>`).
    NameEquals(String),
}

impl FrameSpec {
    fn parse(spec: &str) -> Self {
        let s = spec.trim();
        if s.is_empty() || s.eq_ignore_ascii_case("main") || s.eq_ignore_ascii_case("top") {
            return FrameSpec::Main;
        }
        if let Some(rest) = s.strip_prefix("url:") {
            return FrameSpec::UrlContains(rest.trim().to_string());
        }
        if let Some(rest) = s.strip_prefix("name:") {
            return FrameSpec::NameEquals(rest.trim().to_string());
        }
        if let Some(rest) = s.strip_prefix("index:") {
            if let Ok(n) = rest.trim().parse::<usize>() {
                return FrameSpec::Index(n);
            }
        }
        // A bare integer is ambiguous: a small one is probably a list index, but
        // a Firefox BiDi context id is also a (large) all-digit string. Try the
        // exact id first, then the index — so echoing a numeric list_frames id
        // back works, and `2` still means "the third frame".
        if let Ok(n) = s.parse::<usize>() {
            return FrameSpec::IdOrIndex(s.to_string(), n);
        }
        FrameSpec::Id(s.to_string())
    }
}

/// Result of evaluating JavaScript in the page.
#[derive(Debug, Clone)]
pub struct EvaluationResult {
    inner: RemoteValue,
}

impl EvaluationResult {
    pub fn new(inner: RemoteValue) -> Self {
        Self { inner }
    }

    /// Attempt to deserialize the evaluation result into `T`.
    pub fn into_value<T: DeserializeOwned>(self) -> serde_json::Result<T> {
        let json = remote_value_to_json(&self.inner);
        serde_json::from_value(json)
    }

    /// Raw BiDi remote value.
    pub fn remote_value(&self) -> &RemoteValue {
        &self.inner
    }
}

/// Convert a raw BiDi wire-format `serde_json::Value` into a plain JSON value.
fn bidi_wire_value_to_json(v: &serde_json::Value) -> serde_json::Value {
    match v.get("type").and_then(|t| t.as_str()) {
        Some("string") => v
            .get("value")
            .and_then(|v| v.as_str())
            .map(|s| serde_json::Value::String(s.to_string()))
            .unwrap_or(serde_json::Value::Null),
        Some("number") => v.get("value").cloned().unwrap_or(serde_json::Value::Null),
        Some("boolean") => v
            .get("value")
            .and_then(|v| v.as_bool())
            .map(serde_json::Value::Bool)
            .unwrap_or(serde_json::Value::Null),
        Some("null") | Some("undefined") => serde_json::Value::Null,
        Some("bigint") => v
            .get("value")
            .and_then(|v| v.as_str())
            .map(|s| serde_json::Value::String(s.to_string()))
            .unwrap_or(serde_json::Value::Null),
        Some("object") => {
            let mut map = serde_json::Map::new();
            if let Some(serde_json::Value::Array(pairs)) = v.get("value") {
                for pair in pairs {
                    if let Some(serde_json::Value::Array(items)) = Some(pair) {
                        if items.len() >= 2 {
                            if let (Some(k), Some(val)) =
                                (items[0].as_str(), items.get(1))
                            {
                                map.insert(k.to_string(), bidi_wire_value_to_json(val));
                            }
                        }
                    }
                }
            }
            serde_json::Value::Object(map)
        }
        Some("array") => {
            let arr: Vec<serde_json::Value> = v
                .get("value")
                .and_then(|v| v.as_array())
                .map(|a| a.iter().map(bidi_wire_value_to_json).collect())
                .unwrap_or_default();
            serde_json::Value::Array(arr)
        }
        _ => v.clone(),
    }
}

/// Convert a BiDi `RemoteValue` into a plain `serde_json::Value`.
fn remote_value_to_json(rv: &RemoteValue) -> serde_json::Value {
    match rv {
        RemoteValue::PrimitiveProtocolValue(p) => match p {
            rustenium_bidi_definitions::script::types::PrimitiveProtocolValue::StringValue(s) => {
                serde_json::Value::String(s.value.clone())
            }
            rustenium_bidi_definitions::script::types::PrimitiveProtocolValue::NumberValue(n) => {
                match &n.value {
                    serde_json::Value::Number(num) => serde_json::Value::Number(num.clone()),
                    _ => serde_json::Value::Null,
                }
            }
            rustenium_bidi_definitions::script::types::PrimitiveProtocolValue::BooleanValue(b) => {
                serde_json::Value::Bool(b.value)
            }
            rustenium_bidi_definitions::script::types::PrimitiveProtocolValue::NullValue(_) => {
                serde_json::Value::Null
            }
            rustenium_bidi_definitions::script::types::PrimitiveProtocolValue::UndefinedValue(_) => {
                serde_json::Value::Null
            }
            rustenium_bidi_definitions::script::types::PrimitiveProtocolValue::BigIntValue(b) => {
                serde_json::Value::String(b.value.clone())
            }
        },
        RemoteValue::ArrayRemoteValue(a) => {
            let arr: Vec<serde_json::Value> = a
                .value
                .as_ref()
                .map(|v| v.inner().iter().map(remote_value_to_json).collect())
                .unwrap_or_default();
            serde_json::Value::Array(arr)
        }
        RemoteValue::ObjectRemoteValue(o) => {
            let mut map = serde_json::Map::new();
            if let Some(ref mapping) = o.value {
                for pair in mapping.inner() {
                    if pair.len() >= 2 {
                        if let (Some(serde_json::Value::String(k)), Some(v)) =
                            (pair.first(), pair.get(1))
                        {
                            map.insert(k.clone(), bidi_wire_value_to_json(v));
                        }
                    }
                }
            }
            serde_json::Value::Object(map)
        }
        _ => serde_json::Value::Null,
    }
}

/// DOM element handle.
pub struct Element {
    pub(crate) node: tokio::sync::Mutex<FoxNode>,
    pub(crate) selector: String,
}

impl Element {
    /// Click the element using BiDi pointer actions.
    pub async fn click(&self) -> Result<()> {
        let mut node = self.node.lock().await;
        node.mouse_click()
            .await
            .map_err(|e| anyhow!("element click failed: {e:?}"))?;
        Ok(())
    }

    /// Return the CSS selector used to locate this element.
    pub fn selector(&self) -> &str {
        &self.selector
    }

    /// Type text into this element.
    pub async fn type_text(&self, text: &str) -> Result<()> {
        let mut node = self.node.lock().await;
        node.type_text(text.to_string())
            .await
            .map_err(|e| anyhow!("element type_text failed: {e:?}"))?;
        Ok(())
    }

    /// Alias for [`type_text`].
    pub async fn type_str(&self, text: &str) -> Result<()> {
        self.type_text(text).await
    }
}

// Internal aliases.
type FoxBrowser = FirefoxBrowser;
type FoxNode = rustenium::nodes::FirefoxNode<rustenium_core::transport::WebsocketConnectionTransport>;

/// Direction for realistic scroll simulation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollDirection {
    Up,
    Down,
}

impl Page {
    /// Launch a new Firefox instance and return its first page.
    pub async fn launch(config: Option<FoxBrowserConfig>) -> Result<Self> {
        launch_firefox(config.unwrap_or_default()).await
    }

    /// Navigate the active browsing context to `url`.
    pub async fn goto(&self, url: &str) -> Result<()> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        browser
            .navigate(url)
            .await
            .map_err(|e| anyhow!("navigate failed: {e:?}"))?;
        Ok(())
    }

    /// Evaluate a JavaScript expression in the active context.
    pub async fn evaluate(&self, expr: impl Into<String>) -> Result<EvaluationResult> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let result = browser
            .evaluate_script(expr.into(), false)
            .await
            .map_err(|e| anyhow!("evaluate failed: {e:?}"))?;
        Ok(EvaluationResult::new(result.result))
    }

    /// Evaluate in a specific browsing context (frame).
    pub async fn evaluate_in_context(
        &self,
        expr: impl Into<String>,
        context: &FrameId,
    ) -> Result<EvaluationResult> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let options = EvaluateScriptOptionsBuilder::default()
            .target(Target::ContextTarget(ContextTarget::new(context.clone())))
            .build();
        let result = browser
            .evaluate_script_with_options(expr.into(), false, options)
            .await
            .map_err(|e| anyhow!("evaluate_in_context failed: {e:?}"))?;
        Ok(EvaluationResult::new(result.result))
    }

    /// Find the first element matching `selector`.
    pub async fn find_element(&self, selector: &str) -> Result<Element> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let locator = Locator::CssLocator(CssLocator::new(
            CssLocatorType::Css,
            selector.to_string(),
        ));
        match browser.find_node(locator).await {
            Ok(Some(node)) => {
                Ok(Element {
                    node: tokio::sync::Mutex::new(node),
                    selector: selector.to_string(),
                })
            }
            Ok(None) => Err(anyhow!("find_element: no element matched '{}'", selector)),
            Err(e) => Err(anyhow!("find_element failed: {e:?}")),
        }
    }

    /// Find all elements matching `selector`.
    pub async fn find_elements(&self, selector: &str) -> Result<Vec<Element>> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let locator = Locator::CssLocator(CssLocator::new(
            CssLocatorType::Css,
            selector.to_string(),
        ));
        let nodes = browser
            .find_nodes(locator)
            .await
            .map_err(|e| anyhow!("find_elements failed: {e:?}"))?;
        Ok(nodes
            .into_iter()
            .map(|n| Element {
                node: tokio::sync::Mutex::new(n),
                selector: selector.to_string(),
            })
            .collect())
    }

    /// Set the file(s) on a `<input type=file>` element via BiDi `input.setFiles`.
    ///
    /// This is the trusted file-upload primitive: it attaches real local files to
    /// the input the same way a human's file picker does (no synthetic events), so
    /// the entire file-upload attack surface — path-traversal filenames,
    /// content-type bypass, SVG/XML XXE, RCE-via-upload, SSRF — becomes testable.
    /// `selector` must resolve to the file input; `files` are absolute local paths.
    pub async fn set_files(&self, selector: &str, files: Vec<String>) -> Result<()> {
        if files.is_empty() {
            return Err(anyhow!("set_files: no files provided"));
        }
        // Resolve the input element to its shared node reference + owning context
        // (releases the browser lock before we re-acquire it for the command). Using
        // the node's own context means a file input inside an iframe works too.
        let element = self.find_element(selector).await?;
        let (shared_id, context) = {
            let node = element.node.lock().await;
            let id = node.get_shared_id().cloned().ok_or_else(|| {
                anyhow!("set_files: '{selector}' is not a resolvable element (no shared id)")
            })?;
            (id, node.get_context_id().clone())
        };
        let element_ref: SharedReference = SharedReference::builder()
            .shared_id(shared_id)
            .build()
            .map_err(|e| anyhow!("set_files: build shared reference: {e}"))?;
        let command = SetFiles::builder()
            .context(context)
            .element(element_ref)
            .files(files)
            .build()
            .map_err(|e| anyhow!("set_files: build command: {e}"))?;
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser {
            Some(b) => b,
            None => return Err(anyhow!("browser closed")),
        };
        let response = browser
            .driver_mut()
            .send_command(command)
            .await
            .map_err(|e| anyhow!("set_files BiDi command failed: {e:?}"))?;
        let _result: rustenium_bidi_definitions::input::results::SetFilesResult = response
            .result
            .try_into()
            .map_err(|e| anyhow!("set_files result parse failed: {e}"))?;
        Ok(())
    }

    /// Capture a viewport screenshot and return raw PNG bytes.
    pub async fn screenshot(&self) -> Result<Vec<u8>> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let b64 = browser
            .screenshot()
            .await
            .map_err(|e| anyhow!("screenshot failed: {e:?}"))?;
        base64::engine::general_purpose::STANDARD
            .decode(b64)
            .map_err(|e| anyhow!("base64 decode failed: {e}"))
    }

    /// Reload the active context.
    pub async fn reload(&self) -> Result<()> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        browser
            .evaluate_script("location.reload()".to_string(), false)
            .await
            .map_err(|e| anyhow!("reload failed: {e:?}"))?;
        Ok(())
    }

    /// Current URL of the active context.
    pub async fn url(&self) -> Result<String> {
        let eval = self.evaluate("document.URL").await?;
        eval.into_value::<String>()
            .map_err(|e| anyhow!("url deserialize failed: {e}"))
    }

    /// Document title of the active context.
    pub async fn title(&self) -> Result<String> {
        let eval = self.evaluate("document.title").await?;
        eval.into_value::<String>()
            .map_err(|e| anyhow!("title deserialize failed: {e}"))
    }

    /// List all browsing-context IDs (main page + every iframe).
    pub async fn frames(&self) -> Result<Vec<FrameId>> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let contexts = browser
            .driver()
            .browsing_contexts
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .map(|c| c.id().clone())
            .collect();
        Ok(contexts)
    }

    /// Return the active (main) browsing context.
    pub async fn mainframe(&self) -> Result<Option<FrameId>> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        match browser.driver().get_active_context_id() {
            Ok(ctx) => Ok(Some(ctx)),
            Err(e) => {
                tracing::debug!("get_active_context_id failed: {e:?}");
                Ok(None)
            }
        }
    }

    /// Verify a browsing context still exists.
    pub async fn frame_execution_context(
        &self,
        frame_id: FrameId,
    ) -> Result<Option<FrameId>> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let exists = browser
            .driver()
            .browsing_contexts
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .any(|c| c.id() == &frame_id);
        Ok(if exists { Some(frame_id) } else { None })
    }

    /// List every browsing context (main document + all iframes) with the
    /// metadata an agent needs to target one: opaque `id`, current `url`,
    /// `window.name`, and whether it is the main frame.
    ///
    /// This is the discovery primitive for cross-origin iframe interaction —
    /// embedded apps, OAuth/payment widgets, postMessage surfaces, captcha tiles.
    /// Pass a returned `id` back as the `frame` target to
    /// [`Page::eval_in_frame`] / [`Page::click_in_frame`] /
    /// [`Page::type_in_frame`].
    pub async fn list_frames(&self) -> Result<Vec<FrameInfo>> {
        let frame_ids = self.frames().await?;
        let main = self.mainframe().await?;
        let mut out = Vec::with_capacity(frame_ids.len());
        for fid in frame_ids {
            // Read url + name from inside the frame's own context so a
            // cross-origin iframe (where parent JS would throw SecurityError)
            // still reports correctly. A frame that vanished mid-walk is skipped.
            let (url, name) = match self
                .evaluate_in_context(
                    "({u: document.URL, n: (window.name || \"\")})",
                    &fid,
                )
                .await
            {
                Ok(eval) => match eval.into_value::<serde_json::Value>() {
                    Ok(v) => (
                        v["u"].as_str().unwrap_or("").to_string(),
                        v["n"].as_str().unwrap_or("").to_string(),
                    ),
                    Err(_) => (String::new(), String::new()),
                },
                Err(e) => {
                    tracing::debug!("frame {:?} unreadable during list_frames: {}", fid, e);
                    (String::new(), String::new())
                }
            };
            out.push(FrameInfo {
                is_main: Some(&fid) == main.as_ref(),
                id: fid.inner().to_string(),
                url,
                name,
            });
        }
        Ok(out)
    }

    /// Resolve a frame target spec to a concrete [`FrameId`], polling briefly so
    /// an iframe that attaches asynchronously (captcha widgets, lazy embeds,
    /// post-navigation frames) is found rather than racing to a "no such frame".
    ///
    /// Accepts every shape an agent naturally has on hand — so it never has to
    /// call `list_frames` first:
    /// - exact browsing-context id (from [`Page::list_frames`])
    /// - `index:<n>` or a bare 0-based integer into the frame list
    /// - `url:<substr>` — first frame whose URL contains the substring
    /// - `name:<name>` — first frame whose `window.name` equals it
    /// - any other string — tried as an exact id, then as a URL substring
    /// - empty / `main` / `top` → the main document
    pub async fn resolve_frame(&self, spec: &str) -> Result<FrameId> {
        self.resolve_frame_within(spec, crate::frame::DEFAULT_FRAME_RETRY_TIMEOUT)
            .await
    }

    /// [`Page::resolve_frame`] with an explicit overall timeout for the attach
    /// poll. `timeout` of zero means a single attempt.
    pub async fn resolve_frame_within(
        &self,
        spec: &str,
        timeout: std::time::Duration,
    ) -> Result<FrameId> {
        let parsed = FrameSpec::parse(spec);
        let deadline = std::time::Instant::now() + timeout;
        loop {
            if let Some(fid) = self.try_resolve_frame(&parsed).await? {
                return Ok(fid);
            }
            if std::time::Instant::now() >= deadline {
                return Err(anyhow!(
                    "resolve_frame: no frame matches '{spec}' (use a list_frames id, index:<n>, url:<substr>, or name:<name>)"
                ));
            }
            tokio::time::sleep(crate::frame::DEFAULT_FRAME_RETRY_INTERVAL).await;
        }
    }

    /// One non-retrying resolution attempt. `Ok(None)` means "not found yet"
    /// (caller may retry); `Err` is a hard failure (browser closed, bad index).
    async fn try_resolve_frame(&self, parsed: &FrameSpec) -> Result<Option<FrameId>> {
        if matches!(parsed, FrameSpec::Main) {
            return Ok(self.mainframe().await?);
        }
        let frames = self.frames().await?;
        match parsed {
            FrameSpec::Main => unreachable!(),
            FrameSpec::Index(idx) => Ok(frames.get(*idx).cloned()),
            FrameSpec::IdOrIndex(id, idx) => {
                // Exact (numeric) id first; then the list index.
                if let Some(fid) = frames.iter().find(|f| f.inner() == id) {
                    return Ok(Some(fid.clone()));
                }
                Ok(frames.get(*idx).cloned())
            }
            FrameSpec::Id(id) => {
                if let Some(fid) = frames.iter().find(|f| f.inner() == id) {
                    return Ok(Some(fid.clone()));
                }
                // Fall back to a URL-substring match so a bare iframe URL works
                // without the explicit `url:` prefix.
                self.frame_by_url_contains(id).await
            }
            FrameSpec::UrlContains(sub) => self.frame_by_url_contains(sub).await,
            FrameSpec::NameEquals(name) => {
                for info in self.list_frames().await? {
                    if &info.name == name {
                        return Ok(Some(FrameId::new(info.id)));
                    }
                }
                Ok(None)
            }
        }
    }

    /// First frame whose current URL contains `sub`. Main frame included so
    /// `url:` can also target the top document.
    async fn frame_by_url_contains(&self, sub: &str) -> Result<Option<FrameId>> {
        for info in self.list_frames().await? {
            if info.url.contains(sub) {
                return Ok(Some(FrameId::new(info.id)));
            }
        }
        Ok(None)
    }

    /// Evaluate `expr` inside the frame named by `spec` (id, index, or
    /// main/top). Full read/write JS runs in that frame's own context, so the
    /// agent can read or mutate a cross-origin iframe's DOM, drive postMessage,
    /// or land a DOM-XSS PoC inside an embedded document.
    pub async fn eval_in_frame(
        &self,
        spec: &str,
        expr: impl Into<String>,
    ) -> Result<EvaluationResult> {
        let fid = self.resolve_frame(spec).await?;
        self.evaluate_in_context(expr, &fid).await
    }

    /// TRUSTED click on `selector` inside the frame named by `spec`.
    ///
    /// Resolves the element's centre in the frame's own viewport, then dispatches
    /// a real BiDi pointer event in that context via [`Page::click_at_in`] — so
    /// `event.isTrusted` is `true` even for a cross-origin iframe. Returns an
    /// error if the selector matches nothing visible in the frame.
    pub async fn click_in_frame(&self, spec: &str, selector: &str) -> Result<()> {
        let fid = self.resolve_frame(spec).await?;
        let escaped = selector.replace('\\', "\\\\").replace('\'', "\\'");
        let js = format!(
            r#"(function() {{
                const el = document.querySelector('{escaped}');
                if (!el) return null;
                const r = el.getBoundingClientRect();
                if (r.width <= 0 || r.height <= 0) return null;
                return {{ x: r.left + r.width / 2, y: r.top + r.height / 2 }};
            }})()"#
        );
        // Poll for the element's visible rect — it may render a beat after the
        // frame attaches (lazy widgets, post-XHR content).
        let deadline = std::time::Instant::now() + crate::frame::DEFAULT_FRAME_RETRY_TIMEOUT;
        loop {
            if let Ok(eval) = self.evaluate_in_context(&js, &fid).await {
                if let Ok(val) = eval.into_value::<serde_json::Value>() {
                    if let (Some(x), Some(y)) = (val["x"].as_f64(), val["y"].as_f64()) {
                        return self.click_at_in(&fid, x, y).await;
                    }
                }
            }
            if std::time::Instant::now() >= deadline {
                return Err(anyhow!(
                    "click_in_frame: '{selector}' not found or not visible in frame '{spec}'"
                ));
            }
            tokio::time::sleep(crate::frame::DEFAULT_FRAME_RETRY_INTERVAL).await;
        }
    }

    /// Focus `selector` inside the frame named by `spec` and type `text` into it
    /// with human-like timing. The keystrokes are dispatched in the frame's own
    /// context so they land in the cross-origin iframe's focused element.
    pub async fn type_in_frame(&self, spec: &str, selector: &str, text: &str) -> Result<()> {
        let fid = self.resolve_frame(spec).await?;
        let escaped = selector.replace('\\', "\\\\").replace('\'', "\\'");
        let focus_js = format!(
            r#"(function() {{
                const el = document.querySelector('{escaped}');
                if (!el) return false;
                el.focus();
                return document.activeElement === el;
            }})()"#
        );
        // Poll for the field to exist + accept focus before typing.
        let deadline = std::time::Instant::now() + crate::frame::DEFAULT_FRAME_RETRY_TIMEOUT;
        loop {
            let focused = self
                .evaluate_in_context(&focus_js, &fid)
                .await
                .ok()
                .and_then(|e| e.into_value::<bool>().ok())
                .unwrap_or(false);
            if focused {
                break;
            }
            if std::time::Instant::now() >= deadline {
                return Err(anyhow!(
                    "type_in_frame: could not focus '{selector}' in frame '{spec}'"
                ));
            }
            tokio::time::sleep(crate::frame::DEFAULT_FRAME_RETRY_INTERVAL).await;
        }
        let browser = self.browser.lock().await;
        let browser = match &*browser {
            Some(b) => b,
            None => return Err(anyhow!("browser closed")),
        };
        browser
            .keyboard()
            .type_text(text, &fid, None)
            .await
            .map_err(|e| anyhow!("type_in_frame: type failed: {e:?}"))?;
        Ok(())
    }

    // ------------------------------------------------------------------
    // Dialogs (alert / confirm / prompt / beforeunload) + downloads
    // ------------------------------------------------------------------

    /// Start capturing JS dialogs and page-initiated downloads via BiDi
    /// `browsingContext.*` events. Returns a [`crate::dialog::DialogLog`] handle
    /// (cheap to clone) that accumulates events for the life of the page.
    ///
    /// This is how the agent confirms alert-based XSS (the `alert()` message is
    /// recorded even when the prompt auto-handles, so there is no hang), reads
    /// `confirm`/`prompt` text, and inspects downloads. Pair with
    /// [`Page::handle_user_prompt`] to answer a prompt left open by the `ignore`
    /// handler. Mirrors [`Page::start_network_log`].
    pub async fn start_dialog_log(&self) -> Result<crate::dialog::DialogLog> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser {
            Some(b) => b,
            None => return Err(anyhow!("browser closed")),
        };
        let log = crate::dialog::DialogLog::new();
        let handler = crate::dialog::make_dialog_handler(log.clone());
        let events: HashSet<&str> = crate::dialog::DIALOG_EVENTS.iter().copied().collect();
        browser
            .subscribe_events(events, handler)
            .await
            .map_err(|e| anyhow!("failed to subscribe to dialog/download events: {e:?}"))?;
        Ok(log)
    }

    // ------------------------------------------------------------------
    // Sensor grid (the "Omniscient Page")
    // ------------------------------------------------------------------

    /// Install the passive instrumentation grid (see [`crate::sensors`]) so the
    /// page reports DOM-XSS sink writes, console output, uncaught errors, CSP
    /// violations, and inbound postMessage on its own.
    ///
    /// Injected twice: as a preload (runs in the MAIN world before page scripts
    /// on every future navigation) AND evaluated once on the current document so
    /// a page already loaded at launch is covered. The script is idempotent, so
    /// the double-install is safe. Read what it captured with
    /// [`Page::read_signals`]. Mirrors [`Page::start_network_log`].
    pub async fn start_sensors(&self) -> Result<String> {
        let id = self.add_preload_script(crate::sensors::SENSOR_SCRIPT).await?;
        // Best-effort cover the already-loaded document; a fresh tab on
        // about:blank may not accept eval yet, which is fine — the preload will
        // fire on the first real navigation.
        let _ = self.evaluate(crate::sensors::SENSOR_SCRIPT).await;
        Ok(id)
    }

    /// Read the captured signal buffer. With `clear` true the buffer is emptied
    /// after the snapshot so the next read returns only NEW signals (deltas) —
    /// the basis for "what did my last action trigger?" telemetry.
    pub async fn read_signals(&self, clear: bool) -> Result<serde_json::Value> {
        let eval = self.evaluate(crate::sensors::sensor_reader(clear)).await?;
        eval.into_value::<serde_json::Value>()
            .map_err(|e| anyhow!("read_signals: decode failed: {e}"))
    }

    /// Answer an open JS user prompt in `context` (or the active frame when
    /// `None`): `accept` true clicks OK / accepts `beforeunload`; `user_text`
    /// fills a `prompt()` box before accepting. Only effective when the page was
    /// launched with the `ignore` prompt handler (otherwise Firefox auto-handles
    /// the prompt before this runs). Mirrors the [`Page::set_files`] command path.
    pub async fn handle_user_prompt(
        &self,
        context: Option<&FrameId>,
        accept: bool,
        user_text: Option<&str>,
    ) -> Result<()> {
        let ctx = match context {
            Some(c) => c.clone(),
            None => self
                .mainframe()
                .await?
                .ok_or_else(|| anyhow!("handle_user_prompt: no active browsing context"))?,
        };
        let mut builder = HandleUserPrompt::builder().context(ctx).accept(accept);
        if let Some(text) = user_text {
            builder = builder.user_text(text.to_string());
        }
        let command = builder
            .build()
            .map_err(|e| anyhow!("handle_user_prompt: build command: {e}"))?;
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser {
            Some(b) => b,
            None => return Err(anyhow!("browser closed")),
        };
        let response = browser
            .driver_mut()
            .send_command(command)
            .await
            .map_err(|e| anyhow!("handle_user_prompt BiDi command failed: {e:?}"))?;
        let _result: rustenium_bidi_definitions::browsing_context::results::HandleUserPromptResult =
            response
                .result
                .try_into()
                .map_err(|e| anyhow!("handle_user_prompt result parse failed: {e}"))?;
        Ok(())
    }

    // ------------------------------------------------------------------
    // Input
    // ------------------------------------------------------------------

    /// Move the mouse from `(x0, y0)` to `(x1, y1)` using human-like curves.
    pub async fn mouse_move_human(&self, x0: f64, y0: f64, x1: f64, y1: f64) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let context = browser
            .driver()
            .get_active_context_id()
            .map_err(|e| anyhow!("{e:?}"))?;
        let hm = browser.human_mouse();
        hm.set_last_position(Point { x: x0, y: y0 });
        hm.move_to(Point { x: x1, y: y1 }, &context, MouseMoveOptions::default())
            .await
            .map_err(|e| anyhow!("mouse_move_human failed: {e:?}"))?;
        Ok(())
    }

    /// Mouse-down at `(x, y)` in the active context.
    pub async fn mouse_down(&self, x: f64, y: f64) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let context = browser
            .driver()
            .get_active_context_id()
            .map_err(|e| anyhow!("{e:?}"))?;
        let hm = browser.human_mouse();
        hm.move_to(Point { x, y }, &context, MouseMoveOptions::default())
            .await
            .map_err(|e| anyhow!("mouse_down move failed: {e:?}"))?;
        hm.down(&context, MouseOptions {
            button: Some(MouseButton::Left),
        })
        .await
        .map_err(|e| anyhow!("mouse_down failed: {e:?}"))?;
        Ok(())
    }

    /// Mouse-up at `(x, y)` in the active context.
    pub async fn mouse_up(&self, _x: f64, _y: f64) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let context = browser
            .driver()
            .get_active_context_id()
            .map_err(|e| anyhow!("{e:?}"))?;
        let hm = browser.human_mouse();
        hm.up(&context, MouseOptions {
            button: Some(MouseButton::Left),
        })
        .await
        .map_err(|e| anyhow!("mouse_up failed: {e:?}"))?;
        Ok(())
    }

    /// Click at `(x, y)` in the active (top-level) context with realistic
    /// press/release timing.
    ///
    /// NOTE: for a target inside a cross-origin iframe (the production captcha
    /// case — Turnstile/hCaptcha/reCAPTCHA all render their checkbox in an
    /// OOPIF), prefer [`Page::click_at_in`] with the iframe's context. A
    /// pointer action dispatched in the *top* context does not reliably route
    /// across a Fission process boundary, which is why a top-context viewport
    /// click on a captcha checkbox silently fails to deliver.
    pub async fn click_at(&self, x: f64, y: f64) -> Result<()> {
        let context = self
            .mainframe()
            .await?
            .ok_or_else(|| anyhow!("click_at: no active browsing context"))?;
        self.click_at_in(&context, x, y).await
    }

    /// Click at `(x, y)` within a SPECIFIC browsing context.
    ///
    /// This is the cross-origin-correct click path: BiDi
    /// `input.performActions` is dispatched in `context`, so the *trusted*
    /// pointer event is delivered into that frame's content process. For a
    /// cross-origin iframe checkbox, pass the iframe's [`FrameId`] (from
    /// [`Page::frames`]) with coordinates in that frame's own viewport space
    /// (origin at the iframe's top-left). Because the event is real BiDi input
    /// (not a synthetic JS `MouseEvent`), `event.isTrusted` is `true` — the
    /// property every modern captcha gates its checkbox on.
    pub async fn click_at_in(&self, context: &FrameId, x: f64, y: f64) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let hm = browser.human_mouse();
        // Seed the cursor origin INSIDE the target context's viewport. The
        // shared HumanMouse remembers its last position across calls; that
        // position is in whatever viewport the previous action used (often the
        // top frame, which is larger than a captcha iframe). Moving from a
        // stale top-frame coordinate into a small iframe viewport makes Firefox
        // BiDi reject the action with MoveTargetOutOfBounds. Anchoring at the
        // target keeps every dispatched coordinate within the iframe's bounds.
        hm.set_last_position(Point { x, y });
        let options = MouseClickOptions {
            button: Some(MouseButton::Left),
            count: Some(1),
            delay: Some(80),
            origin: Some(rustenium_bidi_definitions::input::types::Origin::Viewport),
        };
        hm.click(Some(Point { x, y }), context, options)
            .await
            .map_err(|e| anyhow!("click_at_in failed: {e:?}"))?;
        Ok(())
    }

    /// Move the pointer to an absolute viewport coordinate as a single
    /// TRUSTED BiDi `input.performActions` PointerMove (no synthetic JS
    /// `MouseEvent`).
    ///
    /// This is the trusted primitive that human-trajectory generators must
    /// dispatch each interpolated point through. A `document.dispatchEvent(new
    /// MouseEvent('mousemove', …))` produces `isTrusted === false`, which every
    /// modern anti-bot scorer flags on sight — so a beautifully shaped but
    /// JS-dispatched path is worse than useless. Routing each point through
    /// here makes the whole trajectory trusted and lets it cross into
    /// cross-origin frames by viewport hit-test.
    pub async fn move_mouse_to(&self, x: f64, y: f64) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let context = browser
            .driver()
            .get_active_context_id()
            .map_err(|e| anyhow!("{e:?}"))?;
        browser
            .mouse()
            .move_to(
                Point { x, y },
                &context,
                MouseMoveOptions {
                    steps: Some(0),
                    origin: Some(rustenium_bidi_definitions::input::types::Origin::Viewport),
                },
            )
            .await
            .map_err(|e| anyhow!("move_mouse_to failed: {e:?}"))?;
        Ok(())
    }

    /// Scroll the wheel at the current mouse position.
    pub async fn scroll(&self, dx: i64, dy: i64) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let context = browser
            .driver()
            .get_active_context_id()
            .map_err(|e| anyhow!("{e:?}"))?;
        browser
            .mouse()
            .wheel(
                &context,
                MouseWheelOptions {
                    delta_x: Some(dx),
                    delta_y: Some(dy),
                },
            )
            .await
            .map_err(|e| anyhow!("scroll failed: {e:?}"))?;
        Ok(())
    }

    /// Human-like scroll (smooth easing with noise).
    pub async fn scroll_realistic(&self, direction: ScrollDirection, amount: u32) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let context = browser
            .driver()
            .get_active_context_id()
            .map_err(|e| anyhow!("{e:?}"))?;
        let y_distance = match direction {
            ScrollDirection::Down => amount as i32,
            ScrollDirection::Up => -(amount as i32),
        };
        browser
            .human_mouse()
            .scroll(y_distance, 0, &context)
            .await
            .map_err(|e| anyhow!("scroll_realistic failed: {e:?}"))?;
        Ok(())
    }

    /// Type `text` into the active context with human-like delays.
    pub async fn type_text(&self, text: &str) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let context = browser
            .driver()
            .get_active_context_id()
            .map_err(|e| anyhow!("{e:?}"))?;
        browser
            .keyboard()
            .type_text(text, &context, None)
            .await
            .map_err(|e| anyhow!("type_text failed: {e:?}"))?;
        Ok(())
    }

    /// Press a key down in the active context.
    pub async fn key_down(&self, key: &str) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let context = browser
            .driver()
            .get_active_context_id()
            .map_err(|e| anyhow!("{e:?}"))?;
        browser
            .keyboard()
            .down(key, &context)
            .await
            .map_err(|e| anyhow!("key_down failed: {e:?}"))?;
        Ok(())
    }

    /// Release a key in the active context.
    pub async fn key_up(&self, key: &str) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let context = browser
            .driver()
            .get_active_context_id()
            .map_err(|e| anyhow!("{e:?}"))?;
        browser
            .keyboard()
            .up(key, &context)
            .await
            .map_err(|e| anyhow!("key_up failed: {e:?}"))?;
        Ok(())
    }

    /// Press and release a key in the active context.
    pub async fn key_press(&self, key: &str) -> Result<()> {
        let browser = self.browser.lock().await;
        let browser = match &*browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let context = browser
            .driver()
            .get_active_context_id()
            .map_err(|e| anyhow!("{e:?}"))?;
        browser
            .keyboard()
            .press(key, &context, None)
            .await
            .map_err(|e| anyhow!("key_press failed: {e:?}"))?;
        Ok(())
    }

    // ------------------------------------------------------------------
    // Stealth / scripting
    // ------------------------------------------------------------------

    /// Inject a preload script that runs in the page's main world before any
    /// page script, on every new document.
    ///
    /// `source` is a SCRIPT BODY (statements), matching CDP's
    /// `Page.addScriptToEvaluateOnNewDocument` semantics. WebDriver BiDi's
    /// `script.addPreloadScript` instead takes a `functionDeclaration` that it
    /// *invokes* as a function — so a bare body, or a self-invoking IIFE like
    /// `(() => {…})()` (which evaluates to `undefined`, not a callable), is
    /// silently never run, nullifying the script. We therefore wrap the body in
    /// an arrow function here so callers can pass a plain body and have it
    /// actually execute. This is the single point that made guise's stealth
    /// preloads (all written as IIFE bodies) no-ops.
    pub async fn add_preload_script(&self, source: &str) -> Result<String> {
        let function_declaration = format!("() => {{\n{source}\n}}");
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let id = browser
            .add_preload_script(function_declaration)
            .await
            .map_err(|e| anyhow!("add_preload_script failed: {e:?}"))?;
        Ok(id)
    }

    /// Capture all cookies (including HttpOnly) via BiDi `storage.getCookies`.
    pub async fn get_cookies(&self) -> Result<Vec<crate::cookies::CapturedCookie>> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let response = browser
            .driver_mut()
            .send_command(GetCookies {
                method: rustenium_bidi_definitions::storage::commands::GetCookiesMethod::GetCookies,
                params: Default::default(),
            })
            .await
            .map_err(|e| anyhow!("get_cookies BiDi command failed: {e:?}"))?;
        let result: rustenium_bidi_definitions::storage::results::GetCookiesResult =
            response
                .result
                .try_into()
                .map_err(|e| anyhow!("get_cookies result parse failed: {e}"))?;
        Ok(result
            .cookies
            .into_iter()
            .map(|c| crate::cookies::CapturedCookie {
                name: c.name,
                value: match c.value {
                    BytesValue::StringValue(s) => s.value,
                    BytesValue::Base64Value(b) => b.value,
                },
                domain: c.domain,
                path: c.path,
                expires: c.expiry.map(|e| e as i64),
                secure: c.secure,
                http_only: c.http_only,
                same_site: Some(format!("{:?}", c.same_site).to_lowercase()),
            })
            .collect())
    }

    /// Set a cookie via BiDi `storage.setCookie`.
    pub async fn set_cookie(
        &self,
        name: &str,
        value: &str,
        domain: &str,
        path: Option<&str>,
        expires: Option<u64>,
        secure: Option<bool>,
        http_only: Option<bool>,
        same_site: Option<SameSite>,
    ) -> Result<()> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser { Some(b) => b, None => return Err(anyhow!("browser closed")), };
        let cookie = PartialCookie {
            name: name.to_string(),
            value: BytesValue::StringValue(StringValue::new(
                StringValueType::String,
                value.to_string(),
            )),
            domain: domain.to_string(),
            path: path.map(|p| p.to_string()),
            http_only,
            secure,
            same_site,
            expiry: expires,
            extensible: Default::default(),
        };
        let response = browser
            .driver_mut()
            .send_command(SetCookie {
                method: rustenium_bidi_definitions::storage::commands::SetCookieMethod::SetCookie,
                params: SetCookieParams::new(cookie),
            })
            .await
            .map_err(|e| anyhow!("set_cookie BiDi command failed: {e:?}"))?;
        let _result: rustenium_bidi_definitions::storage::results::SetCookieResult = response
            .result
            .try_into()
            .map_err(|e| anyhow!("set_cookie result parse failed: {e}"))?;
        Ok(())
    }

    /// Return the Firefox profile directory path, if known.
    pub fn profile_dir(&self) -> Option<&str> {
        self.profile_dir.as_deref()
    }

    /// Start capturing all network traffic (requests + responses) via BiDi.
    ///
    /// Returns a [`crate::network::NetworkLog`] handle that can be queried at
    /// any time while the browser is alive.  The log is shared (Clone is cheap)
    /// and accumulates events until the page is closed.
    ///
    /// # Example
    /// ```ignore
    /// let log = page.start_network_log().await?;
    /// page.goto("https://example.com").await?;
    /// let entries = log.entries().await;
    /// let tokens = log.extract_tokens().await;
    /// ```
    pub async fn start_network_log(&self) -> Result<crate::network::NetworkLog> {
        let mut browser = self.browser.lock().await;
        let browser = match &mut *browser {
            Some(b) => b,
            None => return Err(anyhow!("browser closed")),
        };
        let log = crate::network::NetworkLog::new();
        let handler = crate::network::make_network_handler(log.clone());
        let events: HashSet<&str> = [
            "network.beforeRequestSent",
            "network.responseCompleted",
            "network.fetchError",
        ]
        .into_iter()
        .collect();
        browser
            .subscribe_events(events, handler)
            .await
            .map_err(|e| anyhow!("failed to subscribe to network events: {e:?}"))?;
        Ok(log)
    }

    /// Close the browser (best-effort, capped at 5 s).
    pub async fn close(&self) -> Result<()> {
        if let Some(browser) = self.browser.lock().await.take() {
            let _ = tokio::time::timeout(std::time::Duration::from_secs(5), browser.close()).await;
        }
        // Kill a self-managed child (Remote-attach path); rustenium's `close`
        // only ends the BiDi session for a process it does not own.
        if let Ok(mut child) = self.child.lock() {
            if let Some(mut c) = child.take() {
                let _ = c.kill();
                let _ = c.wait();
            }
        }
        Ok(())
    }
}

// ------------------------------------------------------------------
// Browser launch configuration
// ------------------------------------------------------------------

/// Upstream proxy transport for a launched Firefox.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProxyScheme {
    /// HTTP/HTTPS proxy (`network.proxy.http` + `ssl`, shared).
    #[default]
    Http,
    /// SOCKS5 proxy (`network.proxy.socks`, remote DNS on).
    Socks5,
}

/// A proxy to route a launched Firefox through. Emitted as `network.proxy.*`
/// prefs into the profile `user.js` at launch — the right place, since Firefox
/// has no `--proxy-server` flag.
///
/// IP-whitelisted gateways work fully via prefs. Firefox cannot carry
/// **proxy-auth credentials** in prefs (it would prompt), so `username`/
/// `password` are plumbed but require a local unauthenticated relay (e.g.
/// `proxywire`) in front of the authenticated upstream; [`proxy_prefs`] logs a
/// warning rather than silently dropping them.
#[derive(Debug, Clone, Default)]
pub struct ProxyConfig {
    pub scheme: ProxyScheme,
    pub host: String,
    pub port: u16,
    pub username: Option<String>,
    pub password: Option<String>,
}

impl ProxyConfig {
    /// Parse `scheme://[user:pass@]host:port`. Scheme defaults to `http`;
    /// `socks5`/`socks` selects SOCKS5.
    pub fn from_url(url: &str) -> Result<Self> {
        let (scheme, rest) = match url.split_once("://") {
            Some((s, r)) => (s.to_ascii_lowercase(), r),
            None => ("http".to_string(), url),
        };
        let scheme = match scheme.as_str() {
            "socks5" | "socks" | "socks5h" => ProxyScheme::Socks5,
            "http" | "https" => ProxyScheme::Http,
            other => return Err(anyhow!("unsupported proxy scheme: {other}")),
        };
        let (auth, hostport) = match rest.rsplit_once('@') {
            Some((a, hp)) => (Some(a), hp),
            None => (None, rest),
        };
        let (username, password) = match auth {
            Some(a) => match a.split_once(':') {
                Some((u, p)) => (Some(u.to_string()), Some(p.to_string())),
                None => (Some(a.to_string()), None),
            },
            None => (None, None),
        };
        let (host, port) = hostport
            .rsplit_once(':')
            .ok_or_else(|| anyhow!("proxy URL missing host:port: {url}"))?;
        let port: u16 = port
            .parse()
            .map_err(|_| anyhow!("invalid proxy port in {url}"))?;
        if host.is_empty() {
            return Err(anyhow!("proxy URL missing host: {url}"));
        }
        Ok(Self {
            scheme,
            host: host.to_string(),
            port,
            username,
            password,
        })
    }
}

/// Build the Firefox `network.proxy.*` `user_pref` lines for `proxy`.
pub fn proxy_prefs(proxy: &ProxyConfig) -> String {
    if proxy.username.is_some() || proxy.password.is_some() {
        tracing::warn!(
            "ProxyConfig carries credentials, but Firefox cannot apply proxy auth via prefs; \
             front the upstream with a local unauthenticated relay (e.g. proxywire) and point \
             foxdriver at that. Emitting host:port prefs only."
        );
    }
    let mut lines = vec![r#"user_pref("network.proxy.type", 1);"#.to_string()];
    match proxy.scheme {
        ProxyScheme::Http => {
            lines.push(format!(
                r#"user_pref("network.proxy.http", "{}");"#,
                proxy.host
            ));
            lines.push(format!(
                r#"user_pref("network.proxy.http_port", {});"#,
                proxy.port
            ));
            lines.push(format!(r#"user_pref("network.proxy.ssl", "{}");"#, proxy.host));
            lines.push(format!(
                r#"user_pref("network.proxy.ssl_port", {});"#,
                proxy.port
            ));
            lines.push(r#"user_pref("network.proxy.share_proxy_settings", true);"#.to_string());
        }
        ProxyScheme::Socks5 => {
            lines.push(format!(
                r#"user_pref("network.proxy.socks", "{}");"#,
                proxy.host
            ));
            lines.push(format!(
                r#"user_pref("network.proxy.socks_port", {});"#,
                proxy.port
            ));
            lines.push(r#"user_pref("network.proxy.socks_version", 5);"#.to_string());
            lines.push(r#"user_pref("network.proxy.socks_remote_dns", true);"#.to_string());
        }
    }
    // Do not bypass the proxy for localhost — a residential run must egress
    // every request through the upstream, including any IP-echo check.
    lines.push(r#"user_pref("network.proxy.no_proxies_on", "");"#.to_string());
    lines.push('\n'.to_string());
    lines.join("\n")
}

#[derive(Debug, Clone, Default)]
pub struct FoxBrowserConfig {
    pub executable_path: Option<String>,
    pub profile_dir: Option<String>,
    pub headless: bool,
    pub viewport_width: u32,
    pub viewport_height: u32,
    pub user_agent: Option<String>,
    /// Raw `user.js` content to write into the profile directory before
    /// Firefox starts. The caller (typically `guise`) is responsible for
    /// building this string from profile overrides.
    pub user_js_content: Option<String>,
    /// Optional upstream proxy. Emitted as `network.proxy.*` prefs appended to
    /// `user_js_content` at launch (requires `profile_dir`).
    pub proxy: Option<ProxyConfig>,
    /// How Firefox handles JS user prompts (`alert`/`confirm`/`prompt`/
    /// `beforeunload`). One of `accept`, `dismiss`, `ignore`, `dismiss and
    /// notify`. `None` keeps the BiDi default (`dismiss and notify`), which
    /// never hangs and still emits the events the dialog log records. Set
    /// `ignore` to keep prompts OPEN so [`Page::handle_user_prompt`] can answer
    /// them; set `accept` to auto-accept (a `confirm()` guard returns true,
    /// `beforeunload` never blocks navigation).
    pub unhandled_prompt_behavior: Option<String>,
}

/// Map a prompt-behavior string to the typed BiDi capability value. Returns
/// `None` for an unrecognized value so launch falls back to the BiDi default
/// rather than failing.
fn prompt_behavior_capability(s: &str) -> Option<UnhandledPromptBehavior> {
    let handler = match s.trim().to_ascii_lowercase().as_str() {
        "accept" | "accept and notify" => UserPromptHandlerType::Accept,
        "dismiss" => UserPromptHandlerType::Dismiss,
        "ignore" => UserPromptHandlerType::Ignore,
        "dismiss and notify" | "dismiss_and_notify" | "notify" => {
            UserPromptHandlerType::DismissAndNotify
        }
        _ => return None,
    };
    Some(UnhandledPromptBehavior::UserPromptHandlerType(handler))
}

/// Write `user.js` into the given profile directory.
fn write_user_js(profile_dir: &str, content: &str) -> Result<()> {
    let dir = std::path::Path::new(profile_dir);
    std::fs::create_dir_all(dir)
        .map_err(|e| anyhow!("failed to create profile dir {:?}: {}", dir, e))?;
    let path = dir.join("user.js");
    std::fs::write(&path, content)
        .map_err(|e| anyhow!("failed to write user.js to {:?}: {}", path, e))?;
    Ok(())
}

/// Launch Firefox with the given config and return a `Page` handle.
pub async fn launch_firefox(config: FoxBrowserConfig) -> Result<Page> {
    let mut caps = FirefoxCapabilities::default();
    caps.accept_insecure_certs(true);
    if let Some(behavior) = config
        .unhandled_prompt_behavior
        .as_deref()
        .and_then(prompt_behavior_capability)
    {
        caps.unhandled_prompt_behavior(behavior);
    }

    let mut args = Vec::new();
    if config.headless {
        args.push("--headless".to_string());
    }
    if let Some(ref ua) = config.user_agent {
        args.push(format!("--user-agent={}", ua));
    }
    if config.viewport_width > 0 {
        args.push(format!("--width={}", config.viewport_width));
    }
    if config.viewport_height > 0 {
        args.push(format!("--height={}", config.viewport_height));
    }

    // Assemble the final user.js: caller-supplied prefs plus, if a proxy is
    // configured, the network.proxy.* lines. Written before launch so prefs are
    // live from the first request (a proxied run must NOT leak the real IP on
    // the initial navigation).
    let mut user_js = config.user_js_content.clone().unwrap_or_default();
    if let Some(ref proxy) = config.proxy {
        if !user_js.is_empty() && !user_js.ends_with('\n') {
            user_js.push('\n');
        }
        user_js.push_str(&proxy_prefs(proxy));
    }
    if !user_js.is_empty() {
        if let Some(ref profile_dir) = &config.profile_dir {
            if let Err(e) = write_user_js(profile_dir, &user_js) {
                tracing::warn!("failed to write user.js for profile: {e}");
            }
        } else {
            tracing::warn!("user.js prefs (incl. proxy) ignored because profile_dir is not set");
        }
    }

    let profile_dir = config.profile_dir.clone();
    let cfg = FirefoxConfig {
        capabilities: caps,
        firefox_executable_path: config.executable_path,
        profile_dir: config.profile_dir,
        browser_flags: Some(args),
        ..Default::default()
    };

    let browser = tokio::time::timeout(std::time::Duration::from_secs(30), firefox(Some(cfg)))
        .await
        .map_err(|_| anyhow!("Firefox launch timed out after 30s — check that Firefox is installed and not already running with a locked profile"))?;
    Ok(Page {
        browser: tokio::sync::Mutex::new(Some(browser)),
        profile_dir,
        child: std::sync::Mutex::new(None),
    })
}

/// Reserve an ephemeral TCP port by binding `127.0.0.1:0` and reading back the
/// OS-assigned port, then releasing it. There is an unavoidable TOCTOU window
/// between release and the browser binding it; in practice the browser claims it
/// within milliseconds and a collision surfaces as a clean readiness-timeout.
fn reserve_local_port() -> Result<u16> {
    let listener = std::net::TcpListener::bind("127.0.0.1:0")
        .map_err(|e| anyhow!("failed to reserve a local port: {e}"))?;
    let port = listener
        .local_addr()
        .map_err(|e| anyhow!("failed to read reserved port: {e}"))?
        .port();
    Ok(port)
}

/// Resolve the Firefox binary: the caller's explicit `executable_path` if set,
/// otherwise the first match on `PATH` and then the standard install locations.
///
/// [`launch_firefox`] gets PATH resolution for free because it hands a possibly-
/// `None` path to rustenium, which finds Firefox itself. When foxdriver owns the
/// spawn ([`launch_firefox_self_managed`]) it must do the same so the robust
/// readiness-poll launcher is a true drop-in — a caller that relies on
/// Firefox-on-PATH (e.g. captchaforge's `drive_browser`) can adopt it without
/// hard-coding a path.
fn resolve_firefox_binary(explicit: Option<String>) -> Result<String> {
    if let Some(p) = explicit {
        return Ok(p);
    }
    const NAMES: &[&str] = &["firefox", "firefox-esr", "firefox-bin", "firefox.exe"];
    if let Ok(path) = std::env::var("PATH") {
        let sep = if cfg!(windows) { ';' } else { ':' };
        for dir in path.split(sep).filter(|d| !d.is_empty()) {
            for name in NAMES {
                let cand = std::path::Path::new(dir).join(name);
                if cand.is_file() {
                    return Ok(cand.to_string_lossy().into_owned());
                }
            }
        }
    }
    // Standard locations that are not always on PATH (snap/opt/macOS/Windows).
    const FIXED: &[&str] = &[
        "/usr/local/bin/firefox",
        "/usr/bin/firefox",
        "/opt/firefox/firefox",
        "/snap/bin/firefox",
        "/Applications/Firefox.app/Contents/MacOS/firefox",
        "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
        "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
    ];
    for p in FIXED {
        if std::path::Path::new(p).is_file() {
            return Ok((*p).to_string());
        }
    }
    Err(anyhow!(
        "could not find a Firefox binary — set FoxBrowserConfig.executable_path or install Firefox on PATH"
    ))
}

/// Launch Firefox where **foxdriver owns the spawn and the readiness wait**, then
/// attaches over BiDi in rustenium `Remote` mode.
///
/// The default [`launch_firefox`] delegates spawning to rustenium, which sleeps a
/// fixed 500 ms after exec before connecting to the BiDi WebSocket. That races any
/// build whose remote agent binds slowly — a freshly-built Camoufox/reynard takes
/// ~1 s — yielding a `ConnectionRefused` panic. Here foxdriver spawns the process,
/// polls the debugging port until it actually accepts a connection (Law-7:
/// readiness, never a fixed sleep), and only then hands rustenium an already-live
/// port via [`FirefoxLaunchMode::Remote`]. The spawned [`std::process::Child`] is
/// owned by the returned [`Page`] and killed on `close`/drop.
///
/// `config.executable_path` is resolved via [`resolve_firefox_binary`] — the
/// explicit path if set, else PATH / standard install locations (this path never
/// auto-downloads Firefox).
pub async fn launch_firefox_self_managed(config: FoxBrowserConfig) -> Result<Page> {
    let exe = resolve_firefox_binary(config.executable_path.clone())?;

    let host = "127.0.0.1".to_string();
    let port = reserve_local_port()?;

    // Profile dir: caller-supplied or a unique temp dir. Written with the same
    // user.js (incl. proxy prefs) as the managed path so prefs are live from the
    // first request.
    let profile_dir = config.profile_dir.clone().unwrap_or_else(|| {
        std::env::temp_dir()
            .join(format!("foxdriver-self-{}-{}", std::process::id(), port))
            .display()
            .to_string()
    });
    std::fs::create_dir_all(&profile_dir)
        .map_err(|e| anyhow!("failed to create profile dir {profile_dir:?}: {e}"))?;

    let mut user_js = config.user_js_content.clone().unwrap_or_default();
    if let Some(ref proxy) = config.proxy {
        if !user_js.is_empty() && !user_js.ends_with('\n') {
            user_js.push('\n');
        }
        user_js.push_str(&proxy_prefs(proxy));
    }
    if !user_js.is_empty() {
        write_user_js(&profile_dir, &user_js)?;
    }

    // Assemble args. `--no-remote` + the explicit debugging port mirror what
    // rustenium would pass in SpawnAndAttach; the rest come from the viewport /
    // headless / UA config.
    let mut args = vec![
        format!("--remote-debugging-port={port}"),
        "--profile".to_string(),
        profile_dir.clone(),
        "--no-remote".to_string(),
    ];
    if config.headless {
        args.push("--headless".to_string());
    }
    if let Some(ref ua) = config.user_agent {
        args.push(format!("--user-agent={ua}"));
    }
    if config.viewport_width > 0 {
        args.push(format!("--width={}", config.viewport_width));
    }
    if config.viewport_height > 0 {
        args.push(format!("--height={}", config.viewport_height));
    }

    // Spawn the process. The parent env is inherited (so a launch wrapper's
    // exported config / sandbox toggles propagate); match rustenium's
    // MOZ_LAUNCHER_PROCESS=0 so the parent PID is the actual browser.
    let child = std::process::Command::new(&exe)
        .args(&args)
        .env("MOZ_LAUNCHER_PROCESS", "0")
        .spawn()
        .map_err(|e| anyhow!("failed to spawn browser {exe:?}: {e}"))?;

    // Poll the debugging port until it accepts a connection, or time out. This is
    // the wait rustenium's fixed 500 ms sleep gets wrong for slow-binding builds.
    let addr: std::net::SocketAddr = format!("{host}:{port}")
        .parse()
        .map_err(|e| anyhow!("bad debug addr {host}:{port}: {e}"))?;
    let start = std::time::Instant::now();
    let ready_timeout = std::time::Duration::from_secs(30);
    loop {
        if std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(250)).is_ok()
        {
            break;
        }
        if start.elapsed() >= ready_timeout {
            return Err(anyhow!(
                "browser debug port {port} never came up within {}s — the spawn likely failed (check {exe:?})",
                ready_timeout.as_secs()
            ));
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }

    // Attach over BiDi to the already-live port — no spawn, no fixed-sleep race.
    //
    // A SINGLE attach: rustenium's `BidiSession::new` waits a hardcoded 5 s for
    // the `session.new` response and PANICS on timeout, but the session is still
    // CREATED on the browser — and a BiDi browser allows only one active session,
    // so a retry just hits "Maximum number of active sessions". The right lever is
    // therefore to give the engine enough head start that its single `session.new`
    // answers within that window (see the post-readiness settle below), not to
    // retry. The attach runs in a task so a timeout surfaces as a clean error
    // instead of unwinding this function.
    let cfg = FirefoxConfig {
        host: Some(host.clone()),
        capabilities: {
            let mut caps = FirefoxCapabilities::default();
            caps.accept_insecure_certs(true);
            if let Some(behavior) = config
                .unhandled_prompt_behavior
                .as_deref()
                .and_then(prompt_behavior_capability)
            {
                caps.unhandled_prompt_behavior(behavior);
            }
            caps
        },
        launch_mode: FirefoxLaunchMode::Remote(port),
        remote_debugging_port: Some(port),
        ..Default::default()
    };
    let attach = tokio::spawn(async move {
        tokio::time::timeout(std::time::Duration::from_secs(30), firefox(Some(cfg))).await
    });
    let browser = match attach.await {
        Ok(Ok(b)) => b,
        Ok(Err(_elapsed)) => return Err(anyhow!("BiDi attach to self-managed browser timed out after 30s")),
        Err(join) => return Err(anyhow!("BiDi attach to self-managed browser failed: {join}")),
    };

    Ok(Page {
        browser: tokio::sync::Mutex::new(Some(browser)),
        profile_dir: Some(profile_dir),
        child: std::sync::Mutex::new(Some(child)),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustenium_bidi_definitions::script::types::{
        ArrayRemoteValue, ArrayRemoteValueType, BigIntValue, BigIntValueType,
        BooleanValue, BooleanValueType, ListRemoteValue, MappingRemoteValue,
        NullValue, NullValueType, NumberValue, NumberValueType,
        ObjectRemoteValue, ObjectRemoteValueType, PrimitiveProtocolValue,
        StringValue, StringValueType, UndefinedValue, UndefinedValueType,
    };

    // ─── FrameSpec::parse ───

    #[test]
    fn frame_spec_main_aliases() {
        assert_eq!(FrameSpec::parse(""), FrameSpec::Main);
        assert_eq!(FrameSpec::parse("  "), FrameSpec::Main);
        assert_eq!(FrameSpec::parse("main"), FrameSpec::Main);
        assert_eq!(FrameSpec::parse("TOP"), FrameSpec::Main);
    }

    #[test]
    fn frame_spec_index_forms() {
        // Bare digits are ambiguous (numeric BiDi id OR index) → IdOrIndex.
        assert_eq!(FrameSpec::parse("0"), FrameSpec::IdOrIndex("0".into(), 0));
        assert_eq!(FrameSpec::parse("3"), FrameSpec::IdOrIndex("3".into(), 3));
        // A large numeric Firefox context id is still resolvable by exact id.
        assert_eq!(
            FrameSpec::parse("10737418241"),
            FrameSpec::IdOrIndex("10737418241".into(), 10737418241)
        );
        // `index:` forces a strict index.
        assert_eq!(FrameSpec::parse("index:2"), FrameSpec::Index(2));
    }

    #[test]
    fn frame_spec_url_and_name_prefixes() {
        assert_eq!(
            FrameSpec::parse("url:recaptcha/api2"),
            FrameSpec::UrlContains("recaptcha/api2".into())
        );
        assert_eq!(
            FrameSpec::parse("name:checkout-frame"),
            FrameSpec::NameEquals("checkout-frame".into())
        );
        // Whitespace inside the value is trimmed.
        assert_eq!(
            FrameSpec::parse("url:  https://x.com "),
            FrameSpec::UrlContains("https://x.com".into())
        );
    }

    #[test]
    fn frame_spec_bare_id_falls_through() {
        // An opaque BiDi context id (non-numeric, no prefix) is an Id.
        assert_eq!(
            FrameSpec::parse("10737418241-abc"),
            FrameSpec::Id("10737418241-abc".into())
        );
        // A bare URL with no prefix is also an Id (resolve falls back to URL match).
        assert_eq!(
            FrameSpec::parse("https://w.com/f"),
            FrameSpec::Id("https://w.com/f".into())
        );
    }

    // ─── prompt_behavior_capability ───

    #[test]
    fn prompt_behavior_maps_known_values() {
        for s in ["accept", "ACCEPT", "dismiss", "ignore", "dismiss and notify", "notify"] {
            assert!(
                prompt_behavior_capability(s).is_some(),
                "'{s}' should map to a capability"
            );
        }
    }

    #[test]
    fn prompt_behavior_rejects_unknown() {
        assert!(prompt_behavior_capability("").is_none());
        assert!(prompt_behavior_capability("bogus").is_none());
    }

    #[test]
    fn prompt_behavior_ignore_is_user_prompt_handler_type() {
        match prompt_behavior_capability("ignore") {
            Some(UnhandledPromptBehavior::UserPromptHandlerType(UserPromptHandlerType::Ignore)) => {}
            other => panic!("ignore should map to UserPromptHandlerType::Ignore, got {other:?}"),
        }
    }

    // ─── bidi_wire_value_to_json ───

    #[test]
    fn wire_string_extracts_value() {
        let v = serde_json::json!({"type": "string", "value": "hello"});
        assert_eq!(bidi_wire_value_to_json(&v), serde_json::json!("hello"));
    }

    #[test]
    fn wire_number_passthrough() {
        let v = serde_json::json!({"type": "number", "value": 42.5});
        assert_eq!(bidi_wire_value_to_json(&v), serde_json::json!(42.5));
    }

    #[test]
    fn wire_boolean_extracts_bool() {
        let v = serde_json::json!({"type": "boolean", "value": true});
        assert_eq!(bidi_wire_value_to_json(&v), serde_json::json!(true));
    }

    #[test]
    fn wire_null_returns_null() {
        let v = serde_json::json!({"type": "null"});
        assert_eq!(bidi_wire_value_to_json(&v), serde_json::Value::Null);
    }

    #[test]
    fn wire_undefined_returns_null() {
        let v = serde_json::json!({"type": "undefined"});
        assert_eq!(bidi_wire_value_to_json(&v), serde_json::Value::Null);
    }

    #[test]
    fn wire_bigint_returns_string() {
        let v = serde_json::json!({"type": "bigint", "value": "9007199254740993"});
        assert_eq!(
            bidi_wire_value_to_json(&v),
            serde_json::json!("9007199254740993")
        );
    }

    #[test]
    fn wire_object_recurse() {
        let v = serde_json::json!({
            "type": "object",
            "value": [
                ["a", {"type": "string", "value": "alpha"}],
                ["b", {"type": "number", "value": 2}]
            ]
        });
        let out = bidi_wire_value_to_json(&v);
        assert_eq!(out["a"], "alpha");
        assert_eq!(out["b"], 2);
    }

    #[test]
    fn wire_array_recurse() {
        let v = serde_json::json!({
            "type": "array",
            "value": [
                {"type": "string", "value": "x"},
                {"type": "number", "value": 1}
            ]
        });
        let out = bidi_wire_value_to_json(&v);
        assert_eq!(out, serde_json::json!(["x", 1]));
    }

    #[test]
    fn wire_unknown_type_clones_raw() {
        let v = serde_json::json!({"type": "special", "payload": 99});
        assert_eq!(bidi_wire_value_to_json(&v), v);
    }

    #[test]
    fn wire_missing_type_clones_raw() {
        let v = serde_json::json!({"payload": 99});
        assert_eq!(bidi_wire_value_to_json(&v), v);
    }

    // ─── remote_value_to_json ───

    #[test]
    fn rv_string_value() {
        let rv = RemoteValue::PrimitiveProtocolValue(PrimitiveProtocolValue::StringValue(
            StringValue::new(StringValueType::String, "hi"),
        ));
        assert_eq!(remote_value_to_json(&rv), serde_json::json!("hi"));
    }

    #[test]
    fn rv_number_value() {
        let rv = RemoteValue::PrimitiveProtocolValue(PrimitiveProtocolValue::NumberValue(
            NumberValue::new(NumberValueType::Number, 3.14),
        ));
        assert_eq!(remote_value_to_json(&rv), serde_json::json!(3.14));
    }

    #[test]
    fn rv_boolean_value() {
        let rv = RemoteValue::PrimitiveProtocolValue(PrimitiveProtocolValue::BooleanValue(
            BooleanValue::new(BooleanValueType::Boolean, true),
        ));
        assert_eq!(remote_value_to_json(&rv), serde_json::json!(true));
    }

    #[test]
    fn rv_null_value() {
        let rv = RemoteValue::PrimitiveProtocolValue(PrimitiveProtocolValue::NullValue(
            NullValue::new(NullValueType::Null),
        ));
        assert_eq!(remote_value_to_json(&rv), serde_json::Value::Null);
    }

    #[test]
    fn rv_undefined_value() {
        let rv = RemoteValue::PrimitiveProtocolValue(PrimitiveProtocolValue::UndefinedValue(
            UndefinedValue::new(UndefinedValueType::Undefined),
        ));
        assert_eq!(remote_value_to_json(&rv), serde_json::Value::Null);
    }

    #[test]
    fn rv_bigint_value() {
        let rv = RemoteValue::PrimitiveProtocolValue(PrimitiveProtocolValue::BigIntValue(
            BigIntValue::new(BigIntValueType::Bigint, "999n"),
        ));
        assert_eq!(remote_value_to_json(&rv), serde_json::json!("999n"));
    }

    #[test]
    fn rv_array_value() {
        let inner = RemoteValue::PrimitiveProtocolValue(PrimitiveProtocolValue::StringValue(
            StringValue::new(StringValueType::String, "item"),
        ));
        let arr = ArrayRemoteValue {
            r#type: ArrayRemoteValueType::Array,
            handle: None,
            internal_id: None,
            value: Some(ListRemoteValue::new(vec![inner])),
        };
        let rv = RemoteValue::ArrayRemoteValue(arr);
        assert_eq!(remote_value_to_json(&rv), serde_json::json!(["item"]));
    }

    #[test]
    fn rv_object_value() {
        let obj = ObjectRemoteValue {
            r#type: ObjectRemoteValueType::Object,
            handle: None,
            internal_id: None,
            value: Some(MappingRemoteValue::new(vec![vec![
                serde_json::json!("key"),
                serde_json::json!({"type": "string", "value": "val"}),
            ]])),
        };
        let rv = RemoteValue::ObjectRemoteValue(obj);
        let out = remote_value_to_json(&rv);
        assert_eq!(out["key"], "val");
    }

    #[test]
    fn rv_unsupported_returns_null() {
        let sym = rustenium_bidi_definitions::script::types::SymbolRemoteValue::new(
            rustenium_bidi_definitions::script::types::SymbolRemoteValueType::Symbol,
        );
        let rv = RemoteValue::SymbolRemoteValue(sym);
        assert_eq!(remote_value_to_json(&rv), serde_json::Value::Null);
    }

    // ─── EvaluationResult ───

    #[test]
    fn eval_result_into_value_deserializes() {
        let rv = RemoteValue::PrimitiveProtocolValue(PrimitiveProtocolValue::StringValue(
            StringValue::new(StringValueType::String, "deserialized"),
        ));
        let er = EvaluationResult::new(rv);
        let s: String = er.into_value().unwrap();
        assert_eq!(s, "deserialized");
    }

    #[test]
    fn eval_result_into_value_number() {
        let rv = RemoteValue::PrimitiveProtocolValue(PrimitiveProtocolValue::NumberValue(
            NumberValue::new(NumberValueType::Number, 42i32),
        ));
        let er = EvaluationResult::new(rv);
        let n: i32 = er.into_value().unwrap();
        assert_eq!(n, 42);
    }

    #[test]
    fn eval_result_remote_value_accessor() {
        let rv = RemoteValue::PrimitiveProtocolValue(PrimitiveProtocolValue::BooleanValue(
            BooleanValue::new(BooleanValueType::Boolean, false),
        ));
        let er = EvaluationResult::new(rv.clone());
        assert_eq!(er.remote_value(), &rv);
    }

    // ─── FoxBrowserConfig ───

    #[test]
    fn fox_browser_config_default_is_headless_false() {
        let cfg = FoxBrowserConfig::default();
        assert!(!cfg.headless);
        assert!(cfg.executable_path.is_none());
        assert!(cfg.profile_dir.is_none());
        assert_eq!(cfg.viewport_width, 0);
        assert_eq!(cfg.viewport_height, 0);
        assert!(cfg.user_agent.is_none());
        assert!(cfg.user_js_content.is_none());
    }

    // ─── write_user_js ───

    #[test]
    fn write_user_js_creates_file() {
        let tmp = std::env::temp_dir().join(format!("foxdriver_test_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&tmp);
        let content = "user_pref(\"test\", true);\n";
        write_user_js(tmp.to_str().unwrap(), content).unwrap();
        let path = tmp.join("user.js");
        assert!(path.exists());
        let read = std::fs::read_to_string(&path).unwrap();
        assert_eq!(read, content);
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn write_user_js_creates_nested_dirs() {
        let tmp = std::env::temp_dir().join(format!("foxdriver_nested_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&tmp);
        let nested = tmp.join("a").join("b");
        write_user_js(nested.to_str().unwrap(), "pref").unwrap();
        assert!(nested.join("user.js").exists());
        let _ = std::fs::remove_dir_all(&tmp);
    }

    // ─── ProxyConfig / proxy_prefs ───

    #[test]
    fn proxy_from_url_http_no_auth() {
        let p = ProxyConfig::from_url("http://1.2.3.4:8080").unwrap();
        assert_eq!(p.scheme, ProxyScheme::Http);
        assert_eq!(p.host, "1.2.3.4");
        assert_eq!(p.port, 8080);
        assert!(p.username.is_none() && p.password.is_none());
    }

    #[test]
    fn proxy_from_url_socks5_with_auth() {
        let p = ProxyConfig::from_url("socks5://user:pass@gw.residential.net:1080").unwrap();
        assert_eq!(p.scheme, ProxyScheme::Socks5);
        assert_eq!(p.host, "gw.residential.net");
        assert_eq!(p.port, 1080);
        assert_eq!(p.username.as_deref(), Some("user"));
        assert_eq!(p.password.as_deref(), Some("pass"));
    }

    #[test]
    fn proxy_from_url_bare_defaults_http() {
        let p = ProxyConfig::from_url("10.0.0.1:3128").unwrap();
        assert_eq!(p.scheme, ProxyScheme::Http);
        assert_eq!(p.host, "10.0.0.1");
        assert_eq!(p.port, 3128);
    }

    #[test]
    fn proxy_from_url_rejects_missing_port_and_bad_scheme() {
        assert!(ProxyConfig::from_url("http://nohost").is_err());
        assert!(ProxyConfig::from_url("ftp://h:1").is_err());
        assert!(ProxyConfig::from_url("http://h:notaport").is_err());
    }

    #[test]
    fn proxy_prefs_http_emits_http_ssl_and_type() {
        let prefs = proxy_prefs(&ProxyConfig::from_url("http://5.6.7.8:9000").unwrap());
        assert!(prefs.contains(r#"user_pref("network.proxy.type", 1);"#));
        assert!(prefs.contains(r#"user_pref("network.proxy.http", "5.6.7.8");"#));
        assert!(prefs.contains(r#"user_pref("network.proxy.http_port", 9000);"#));
        assert!(prefs.contains(r#"user_pref("network.proxy.ssl", "5.6.7.8");"#));
        assert!(prefs.contains(r#"user_pref("network.proxy.ssl_port", 9000);"#));
        // Negative twin: the HTTP form must NOT emit SOCKS prefs.
        assert!(!prefs.contains("network.proxy.socks"));
    }

    #[test]
    fn proxy_prefs_socks5_emits_socks_and_version() {
        let prefs = proxy_prefs(&ProxyConfig::from_url("socks5://h:1080").unwrap());
        assert!(prefs.contains(r#"user_pref("network.proxy.socks", "h");"#));
        assert!(prefs.contains(r#"user_pref("network.proxy.socks_port", 1080);"#));
        assert!(prefs.contains(r#"user_pref("network.proxy.socks_version", 5);"#));
        // Negative twin: the SOCKS form must NOT emit the HTTP-proxy prefs.
        assert!(!prefs.contains("network.proxy.http_port"));
    }

    // ─── ScrollDirection ───

    #[test]
    fn scroll_direction_up_not_eq_down() {
        assert_ne!(ScrollDirection::Up, ScrollDirection::Down);
    }

    #[test]
    fn scroll_direction_clone_copy() {
        let a = ScrollDirection::Up;
        let b = a;
        assert_eq!(a, b); // copy, not move
    }

    #[test]
    fn scroll_direction_debug() {
        let s = format!("{:?}", ScrollDirection::Down);
        assert!(s.contains("Down"));
    }
}