rightkit-browser 0.3.12

Shared Chrome DevTools Protocol browser runtime for Right Suite: multi-page sessions, named profiles, real CDP input, observations with stale-ref checks.
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
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
use crate::act::{ActResult, ActionWatch, NodeChange, NodeState, ObservationDiff, RefAction};
use crate::cdp_ext::{
    command_for, download_params, page_scale_params, parse_ax_tree, run_interceptor, summarize_ax,
    AxNode, AxSummary, DownloadBehavior, InterceptDecision, InterceptFailure, InterceptedRequest,
    PageException, PausedCommand, RequestInterceptor, INTERCEPTOR_TIMEOUT, MAX_EXCEPTIONS,
};
use crate::cookies::{self, NetscapeCookie};
use crate::design_mode::{self, DesignModeBridge, DesignModeSession, NativeGestureLatch};
use crate::error::{cdp, BrowserError, Result};
use crate::keys::{self, KeyDef};
use crate::policy::{ActionKind, AdmissionRequest, BlockedRequest, Guard, LifecycleKind};
use chromiumoxide::cdp::browser_protocol::accessibility::GetFullAxTreeParams;
use chromiumoxide::cdp::browser_protocol::dom::SetFileInputFilesParams;
use chromiumoxide::cdp::browser_protocol::emulation::SetUserAgentOverrideParams;
use chromiumoxide::cdp::browser_protocol::fetch::{
    EnableParams as FetchEnableParams, EventRequestPaused, FailRequestParams, RequestPattern,
};
use chromiumoxide::cdp::browser_protocol::input::{
    DispatchKeyEventParams, DispatchKeyEventType, DispatchMouseEventParams, DispatchMouseEventType,
    MouseButton,
};
use chromiumoxide::cdp::browser_protocol::inspector::{
    EnableParams as InspectorEnableParams, EventTargetCrashed,
};
use chromiumoxide::cdp::browser_protocol::network::{
    ErrorReason, Headers, SetCookiesParams, SetExtraHttpHeadersParams,
};
use chromiumoxide::cdp::browser_protocol::page::CreateIsolatedWorldParams;
use chromiumoxide::cdp::browser_protocol::page::{
    CaptureScreenshotFormat, CaptureScreenshotParams, Viewport,
};
use chromiumoxide::cdp::js_protocol::runtime::{
    AddBindingParams, EvaluateParams, EventBindingCalled, EventConsoleApiCalled,
    EventExceptionThrown, ExecutionContextId,
};
use chromiumoxide::page::{Page, ScreenshotParams};
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex as StdMutex};
use std::time::{Duration, Instant};
use tokio::sync::{broadcast, Mutex};
use tokio::task::JoinHandle;

pub const MAX_CONSOLE_LINES: usize = 500;
const MAX_UPLOAD_BYTES: u64 = 64 * 1024 * 1024;

#[derive(Clone, Debug, Serialize)]
pub struct ConsoleLine {
    pub level: String,
    pub text: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Rect {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

#[derive(Clone, Debug, Serialize)]
pub struct ObservedNode {
    /// `r<epoch>.<n>`; valid only while the page stays unchanged.
    pub node_ref: String,
    pub role: String,
    /// Masked (`••••••••`) when `sensitive` is true.
    pub name: String,
    pub tag: String,
    pub selector: String,
    pub visible: bool,
    pub disabled: bool,
    /// True for password-like fields (`type=password`, `current-password`, `new-password`).
    /// Their name is masked; callers should mask any value they show.
    pub sensitive: bool,
    /// CDP frame id of the document the node was read from. An observation reads the main
    /// document only (iframe contents are not enumerated, see the changelog), so this is the
    /// main frame's id for every node; it does not make iframe controls observable.
    pub frame_id: String,
    /// Stable across consecutive observations of the same document for the same selector.
    /// `0` when the node has no selector (such nodes cannot be targeted by ref either).
    pub stable_id: u64,
    pub bounds: Rect,
}

#[derive(Clone, Debug, Serialize)]
pub struct Observation {
    pub page_id: String,
    pub epoch: u64,
    pub url: String,
    pub title: String,
    pub viewport: Rect,
    pub nodes: Vec<ObservedNode>,
    /// Accessibility summary of the main frame, bounded to depth [`OBSERVE_AX_DEPTH`].
    pub ax: Vec<AxSummary>,
    pub console_errors: usize,
    /// Refs/roles/names added, removed, or changed since the previous observation.
    pub added: Vec<String>,
    pub removed: Vec<String>,
}

/// Depth bound for the accessibility summary in an [`Observation`].
pub const OBSERVE_AX_DEPTH: u32 = 12;

/// How long a history traversal waits for a navigation event before returning. A traversal
/// that fires no navigation (bfcache restore, same-document entry) must not hang the caller.
const HISTORY_NAVIGATION_WAIT: Duration = Duration::from_secs(10);

/// Longest accepted user-agent string, in bytes.
pub const MAX_USER_AGENT_BYTES: usize = 1024;
/// Most extra HTTP headers one [`BrowserPage::set_extra_headers`] call accepts.
pub const MAX_EXTRA_HEADERS: usize = 32;
/// Longest accepted extra-header value, in bytes.
pub const MAX_HEADER_VALUE_BYTES: usize = 8192;

/// Screenshot options for [`BrowserPage::screenshot_with`]. The default is the viewport as PNG.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ScreenshotOptions {
    /// Capture with a transparent background (PNG only). Pair with
    /// [`BrowserPage::set_transparent_background`] for a fully transparent page.
    pub omit_background: bool,
    /// Image format; PNG by default.
    pub format: ScreenshotFormat,
    /// Capture only this region, in CSS pixels of the page. `None` captures the visible viewport
    /// (or, with a `scale`, the whole visual viewport).
    pub clip: Option<ScreenshotClip>,
    /// Output scale of the capture, a positive finite factor (`1.0` when `None`). Use it with
    /// `clip` or alone to produce a smaller image, for example a 1280 px wide frame of a wider
    /// viewport.
    pub scale: Option<f64>,
}

/// Image format of a screenshot.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ScreenshotFormat {
    /// Lossless PNG.
    #[default]
    Png,
    /// JPEG at `quality`, 1 to 100.
    Jpeg { quality: u8 },
}

/// A capture region in CSS pixels of the page. `x` and `y` are at least zero; `width` and
/// `height` are positive.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScreenshotClip {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

impl ScreenshotClip {
    fn validate(&self) -> Result<()> {
        let finite = [self.x, self.y, self.width, self.height]
            .iter()
            .all(|v| v.is_finite());
        if !finite || self.x < 0.0 || self.y < 0.0 || self.width <= 0.0 || self.height <= 0.0 {
            return Err(BrowserError::Invalid(
                "screenshot clip needs finite x and y of at least 0 and a positive width and height"
                    .into(),
            ));
        }
        Ok(())
    }
}

/// RFC 9110 token characters, the only bytes a header name may contain.
fn is_header_token(name: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
}

fn has_control(value: &str) -> bool {
    value.chars().any(|c| c.is_control())
}

/// What an action addresses.
#[derive(Clone, Debug)]
pub enum Target {
    /// Ref from [`BrowserPage::observe`]; checked for staleness.
    Ref(String),
    /// A CSS selector that must match exactly one element.
    Selector(String),
    /// Viewport coordinates.
    Point(f64, f64),
}

impl Target {
    pub fn css(s: impl Into<String>) -> Self {
        Target::Selector(s.into())
    }
    pub fn node_ref(s: impl Into<String>) -> Self {
        Target::Ref(s.into())
    }
}

#[derive(Clone, Debug, Deserialize)]
struct RawNode {
    role: String,
    name: String,
    tag: String,
    selector: String,
    visible: bool,
    disabled: bool,
    #[serde(default)]
    sensitive: bool,
    bounds: Rect,
}

#[derive(Clone, Debug)]
struct RefEntry {
    selector: String,
    tag: String,
    role: String,
    name: String,
}

#[derive(Default)]
struct ObsState {
    epoch: u64,
    fingerprint: String,
    refs: HashMap<String, RefEntry>,
    previous: HashMap<String, String>,
    /// Stable ids of the previous observation's selectors (bounded by its node count).
    stable: HashMap<String, u64>,
    next_stable: u64,
    /// Identity (frame id and loader id) of the main document the refs were read from. A navigation or
    /// reload changes the loader, so a ref from before it is refused.
    frame: Option<String>,
    /// State of each selectable element in the latest observation, for the diff [`BrowserPage::act`] returns.
    sigs: HashMap<String, NodeState>,
}

/// What the request-interception pump has done on one page. Reported when a navigation
/// fails, so a timeout says how far the navigation got: no request paused (it never reached
/// the network stage), paused but not answered (the policy check did not return), or
/// continued (the request left the browser and the proxy or the server did not finish it).
#[derive(Default)]
struct InterceptStats {
    paused: std::sync::atomic::AtomicUsize,
    continued: std::sync::atomic::AtomicUsize,
    fulfilled: std::sync::atomic::AtomicUsize,
    refused: std::sync::atomic::AtomicUsize,
    errors: std::sync::atomic::AtomicUsize,
    last_error: StdMutex<Option<String>>,
}

impl InterceptStats {
    fn summary(&self) -> String {
        use std::sync::atomic::Ordering::Relaxed;
        let mut text = format!(
            "requests paused {}, continued {}, refused {}",
            self.paused.load(Relaxed),
            self.continued.load(Relaxed),
            self.refused.load(Relaxed)
        );
        let fulfilled = self.fulfilled.load(Relaxed);
        if fulfilled > 0 {
            text.push_str(&format!(", fulfilled {fulfilled}"));
        }
        let errors = self.errors.load(Relaxed);
        if errors > 0 {
            let last = self.last_error.lock().unwrap().clone().unwrap_or_default();
            text.push_str(&format!(", {errors} not answered: {last}"));
        }
        text
    }
}

pub struct BrowserPage {
    id: String,
    /// CDP target id: the stable identity of the tab (`id` is the session's own sequence).
    target_id: String,
    inner: Page,
    console: Arc<Mutex<Vec<ConsoleLine>>>,
    obs: StdMutex<ObsState>,
    mouse: StdMutex<(f64, f64)>,
    buttons: StdMutex<i64>,
    /// Serializes mutations so concurrent callers commit in order.
    lane: Mutex<()>,
    upload_root: Option<PathBuf>,
    pumps: StdMutex<Vec<JoinHandle<()>>>,
    guard: Arc<Guard>,
    blocked: Arc<StdMutex<Vec<BlockedRequest>>>,
    intercept: Arc<InterceptStats>,
    /// Caller hook consulted after the network policy; see [`BrowserPage::set_request_interceptor`].
    interceptor: Arc<StdMutex<Option<RequestInterceptor>>>,
    /// True once this page's request-interception pump (and `Fetch.enable`) is running.
    pump_running: AtomicBool,
    /// The fixture session owns `Fetch` on this page; a caller hook cannot share it.
    fixture_fetch_owner: bool,
    exceptions: Arc<StdMutex<Vec<PageException>>>,
    exception_tx: broadcast::Sender<PageException>,
    /// Latest native input gesture (pointer press, key down) this page dispatched.
    design_gesture: Arc<NativeGestureLatch>,
    /// Isolated-world context of the design-mode picker, once enabled.
    design_context: StdMutex<Option<ExecutionContextId>>,
    /// Repeat counter behind the action-loop watchdog of [`BrowserPage::act`].
    watch: StdMutex<ActionWatch>,
}

/// Buffered capacity of an exception subscription; a slower receiver sees `Lagged`.
const EXCEPTION_CHANNEL: usize = 64;

impl BrowserPage {
    pub(crate) async fn attach(
        id: String,
        inner: Page,
        upload_root: Option<PathBuf>,
        guard: Arc<Guard>,
        fixture_fetch_owner: bool,
    ) -> Result<Self> {
        let console = Arc::new(Mutex::new(Vec::new()));
        let mut pumps = Vec::new();
        let mut ev = inner
            .event_listener::<EventConsoleApiCalled>()
            .await
            .map_err(cdp)?;
        let sink = console.clone();
        pumps.push(tokio::spawn(async move {
            while let Some(e) = ev.next().await {
                let text = e
                    .args
                    .iter()
                    .map(|a| match (&a.value, &a.description) {
                        (Some(Value::String(s)), _) => s.clone(),
                        (Some(v), _) => v.to_string(),
                        (None, Some(d)) => d.clone(),
                        _ => String::new(),
                    })
                    .collect::<Vec<_>>()
                    .join(" ");
                push_capped(
                    &sink,
                    ConsoleLine {
                        level: format!("{:?}", e.r#type).to_lowercase(),
                        text,
                    },
                )
                .await;
            }
        }));
        let mut ex = inner
            .event_listener::<EventExceptionThrown>()
            .await
            .map_err(cdp)?;
        let sink = console.clone();
        let exceptions = Arc::new(StdMutex::new(Vec::new()));
        let (exception_tx, _) = broadcast::channel(EXCEPTION_CHANNEL);
        let (ex_log, ex_tx) = (exceptions.clone(), exception_tx.clone());
        pumps.push(tokio::spawn(async move {
            while let Some(e) = ex.next().await {
                if let Some(parsed) = serde_json::to_value(&*e)
                    .ok()
                    .and_then(|v| PageException::from_cdp_value(&v))
                {
                    {
                        let mut log = ex_log.lock().unwrap();
                        if log.len() >= MAX_EXCEPTIONS {
                            log.remove(0);
                        }
                        log.push(parsed.clone());
                    }
                    // No receiver is the normal case; the buffered list still has it.
                    let _ = ex_tx.send(parsed);
                }
                let d = &e.exception_details;
                let text = d
                    .exception
                    .as_ref()
                    .and_then(|x| x.description.clone())
                    .unwrap_or_else(|| d.text.clone());
                push_capped(
                    &sink,
                    ConsoleLine {
                        level: "exception".into(),
                        text,
                    },
                )
                .await;
            }
        }));
        // Renderer crash -> `Crash` lifecycle event for this page.
        let mut crashed = inner
            .event_listener::<EventTargetCrashed>()
            .await
            .map_err(cdp)?;
        let (g, page_id) = (guard.clone(), id.clone());
        pumps.push(tokio::spawn(async move {
            while crashed.next().await.is_some() {
                g.emit_kind(LifecycleKind::Crash, "renderer crashed", |e| {
                    e.page_id = Some(page_id.clone());
                });
            }
        }));
        inner
            .execute(InspectorEnableParams::default())
            .await
            .map_err(cdp)?;
        let blocked = Arc::new(StdMutex::new(Vec::new()));
        let intercept = Arc::new(InterceptStats::default());
        let interceptor = Arc::new(StdMutex::new(None));
        let mut pump_running = false;
        if !guard.network.unrestricted && !fixture_fetch_owner {
            // Pause every request (document, redirect hops, subresources) and
            // decide before it leaves the browser. Enabled before any navigation.
            pumps.push(
                start_intercept_pump(
                    &inner,
                    &id,
                    &guard,
                    blocked.clone(),
                    intercept.clone(),
                    interceptor.clone(),
                )
                .await?,
            );
            pump_running = true;
        }
        let target_id = inner.target_id().as_ref().to_string();
        Ok(Self {
            id,
            target_id,
            inner,
            console,
            obs: StdMutex::new(ObsState::default()),
            mouse: StdMutex::new((0.0, 0.0)),
            buttons: StdMutex::new(0),
            lane: Mutex::new(()),
            upload_root,
            pumps: StdMutex::new(pumps),
            guard,
            blocked,
            intercept,
            interceptor,
            pump_running: AtomicBool::new(pump_running),
            fixture_fetch_owner,
            exceptions,
            exception_tx,
            design_gesture: Arc::new(NativeGestureLatch::new()),
            design_context: StdMutex::new(None),
            watch: StdMutex::new(ActionWatch::default()),
        })
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    /// The CDP target id of this tab. Unlike [`BrowserPage::id`], it is Chrome's own identity
    /// for the tab and does not change when the session renumbers pages.
    pub fn target_id(&self) -> &str {
        &self.target_id
    }

    /// Frame ids of every frame in the page (CDP `Page.getFrameTree`), read-only.
    pub async fn frames(&self) -> Result<Vec<String>> {
        let frames = self.inner.frames().await.map_err(cdp)?;
        Ok(frames.iter().map(|f| f.as_ref().to_string()).collect())
    }

    /// Install (or with `None`, remove) a caller hook that answers every request this page
    /// makes: continue, continue with changes, fulfil from memory, or fail. Redirect hops arrive
    /// as separate requests with [`InterceptedRequest::redirected_from`] set, so a hook that pins
    /// an origin revalidates each hop.
    ///
    /// The session's network policy runs first and its refusals are final; the hook only
    /// narrows what the policy allows. A hook that takes longer than 30 s fails the request.
    /// Turns on `Fetch` interception for this page when the policy had not (an unrestricted
    /// session); requests already in flight are not affected. Removing the hook lets requests
    /// through unchanged but leaves interception running. Not available on a fixture page, whose
    /// session owns `Fetch`: returns [`BrowserError::Invalid`].
    pub async fn set_request_interceptor(&self, hook: Option<RequestInterceptor>) -> Result<()> {
        if self.fixture_fetch_owner {
            return Err(BrowserError::Invalid(
                "a fixture page's session owns request interception".into(),
            ));
        }
        let install = hook.is_some();
        *self.interceptor.lock().unwrap() = hook;
        if install && !self.pump_running.swap(true, Ordering::SeqCst) {
            match start_intercept_pump(
                &self.inner,
                &self.id,
                &self.guard,
                self.blocked.clone(),
                self.intercept.clone(),
                self.interceptor.clone(),
            )
            .await
            {
                Ok(pump) => self.pumps.lock().unwrap().push(pump),
                Err(e) => {
                    self.pump_running.store(false, Ordering::SeqCst);
                    *self.interceptor.lock().unwrap() = None;
                    return Err(e);
                }
            }
        }
        Ok(())
    }

    /// The page's full accessibility tree (`Accessibility.getFullAXTree`), root frame, in CDP
    /// order. Ignored nodes are included and flagged. Read-only.
    pub async fn accessibility_tree(&self) -> Result<Vec<AxNode>> {
        self.ax_tree(None).await
    }

    /// The accessibility tree cut off below `depth` (root is depth 0). Use it on heavy pages,
    /// where the full tree costs too much. Read-only, like [`BrowserPage::accessibility_tree`].
    pub async fn accessibility_tree_with(&self, depth: u32) -> Result<Vec<AxNode>> {
        self.ax_tree(Some(depth)).await
    }

    async fn ax_tree(&self, depth: Option<u32>) -> Result<Vec<AxNode>> {
        let params = GetFullAxTreeParams {
            depth: depth.map(i64::from),
            ..Default::default()
        };
        let r = self.inner.execute(params).await.map_err(cdp)?;
        let wire = serde_json::to_value(&r.result).map_err(cdp)?;
        Ok(parse_ax_tree(&wire))
    }

    /// Make the page background transparent (`Emulation.setDefaultBackgroundColorOverride`
    /// with alpha 0), or restore Chrome's default with `false`. Pair with
    /// [`BrowserPage::screenshot_with`] and `omit_background` to capture alpha. Like
    /// [`BrowserPage::set_page_scale`], this changes rendering only and is not admitted.
    pub async fn set_transparent_background(&self, transparent: bool) -> Result<()> {
        use chromiumoxide::cdp::browser_protocol::dom::Rgba;
        use chromiumoxide::cdp::browser_protocol::emulation::SetDefaultBackgroundColorOverrideParams;
        let params = if transparent {
            SetDefaultBackgroundColorOverrideParams::builder()
                .color(Rgba {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: Some(0.0),
                })
                .build()
        } else {
            SetDefaultBackgroundColorOverrideParams::builder().build()
        };
        self.inner.execute(params).await.map_err(cdp)?;
        Ok(())
    }

    /// Uncaught exceptions and unhandled rejections seen so far (`Runtime.exceptionThrown`),
    /// oldest first, at most [`MAX_EXCEPTIONS`](crate::MAX_EXCEPTIONS). Collected from the moment
    /// the page exists, so nothing from its first navigation is missed.
    pub fn exceptions(&self) -> Vec<PageException> {
        self.exceptions.lock().unwrap().clone()
    }

    pub fn clear_exceptions(&self) {
        self.exceptions.lock().unwrap().clear();
    }

    /// Live stream of exceptions from now on. The page exists before its first navigation, so a
    /// subscriber taken before `goto` sees every exception it raises. A receiver that falls more
    /// than 64 behind gets `RecvError::Lagged`; [`BrowserPage::exceptions`] still has them.
    pub fn subscribe_exceptions(&self) -> broadcast::Receiver<PageException> {
        self.exception_tx.subscribe()
    }

    /// Set the page scale factor (pinch zoom, `Emulation.setPageScaleFactor`). Must be positive
    /// and finite. Distinct from the device scale factor of [`BrowserPage::set_viewport`].
    pub async fn set_page_scale(&self, scale: f64) -> Result<()> {
        self.inner
            .execute(page_scale_params(scale)?)
            .await
            .map_err(cdp)?;
        Ok(())
    }

    /// Choose what happens to downloads (`Browser.setDownloadBehavior`). `Allow` and
    /// `AllowAndName` need an absolute, existing directory; downloads go nowhere else.
    /// Admitted as an `Eval`-kind effect (detail `download_behavior ...`) because it lets pages
    /// write files. Applies to the browser's default context, so it covers every page of a
    /// session; a later call replaces an earlier one.
    pub async fn set_download_behavior(&self, behavior: &DownloadBehavior) -> Result<()> {
        let params = download_params(behavior)?;
        self.admit(
            ActionKind::Eval,
            None,
            None,
            Some(format!("download_behavior {behavior:?}")),
        )
        .await?;
        self.inner.execute(params).await.map_err(cdp)?;
        Ok(())
    }

    /// Override the user agent of this page (`Emulation.setUserAgentOverride`), and optionally
    /// its `Accept-Language`. Applies to this page's later requests and scripts. Admitted as an
    /// `Eval`-kind effect (detail `user_agent`).
    pub async fn set_user_agent(
        &self,
        user_agent: &str,
        accept_language: Option<&str>,
    ) -> Result<()> {
        let ua = user_agent.trim();
        if ua.is_empty() || ua.len() > MAX_USER_AGENT_BYTES || has_control(ua) {
            return Err(BrowserError::Invalid(format!(
                "user agent must be 1 to {MAX_USER_AGENT_BYTES} bytes without control characters"
            )));
        }
        let mut builder = SetUserAgentOverrideParams::builder().user_agent(ua);
        if let Some(lang) = accept_language {
            let lang = lang.trim();
            if lang.is_empty() || lang.len() > MAX_HEADER_VALUE_BYTES || has_control(lang) {
                return Err(BrowserError::Invalid(
                    "accept-language must be non-empty and free of control characters".into(),
                ));
            }
            builder = builder.accept_language(lang);
        }
        let params = builder
            .build()
            .map_err(|e| BrowserError::Invalid(format!("user agent override: {e}")))?;
        self.admit(ActionKind::Eval, None, None, Some("user_agent".into()))
            .await?;
        self.inner.execute(params).await.map_err(cdp)?;
        Ok(())
    }

    /// Send `headers` with every later request of this page (`Network.setExtraHTTPHeaders`).
    /// Each call replaces the previous set; an empty slice clears it. Names are case-insensitive
    /// and must be unique; values may not contain control characters. Admitted as an `Eval`-kind
    /// effect whose detail carries the count only: header values are never logged.
    pub async fn set_extra_headers(&self, headers: &[(String, String)]) -> Result<()> {
        if headers.len() > MAX_EXTRA_HEADERS {
            return Err(BrowserError::Invalid(format!(
                "set_extra_headers takes at most {MAX_EXTRA_HEADERS} headers"
            )));
        }
        let mut map = serde_json::Map::new();
        for (name, value) in headers {
            if !is_header_token(name) {
                return Err(BrowserError::Invalid(
                    "extra header names must be non-empty HTTP tokens".into(),
                ));
            }
            if value.len() > MAX_HEADER_VALUE_BYTES || value.contains(['\r', '\n', '\0']) {
                return Err(BrowserError::Invalid(format!(
                    "extra header value must be at most {MAX_HEADER_VALUE_BYTES} bytes without CR, LF or NUL"
                )));
            }
            let key = name.to_ascii_lowercase();
            if map.contains_key(&key) {
                return Err(BrowserError::Invalid("duplicate extra header name".into()));
            }
            map.insert(key, Value::String(value.clone()));
        }
        self.admit(
            ActionKind::Eval,
            None,
            None,
            Some(format!("extra_headers {} names", headers.len())),
        )
        .await?;
        self.inner
            .execute(SetExtraHttpHeadersParams::new(Headers::new(Value::Object(
                map,
            ))))
            .await
            .map_err(cdp)?;
        Ok(())
    }

    /// Set `cookies` in the browser profile this page belongs to (`Network.setCookies`) and
    /// return how many were set. The cookies apply to the whole profile, not to this page, and
    /// persist with a named or directory profile. A subdomain-matching cookie gets a leading dot
    /// on its domain; a host-only cookie does not. Chrome rejects the whole batch if one cookie
    /// is invalid (for example a `__Secure-` name without `secure`); the error then sets none
    /// and its text never contains a cookie value.
    ///
    /// Domain filtering, user consent and file selection belong to the caller: this sets exactly
    /// what it is given. Admitted as an `Eval`-kind effect (detail `import_cookies`, the count
    /// and the distinct domains; never names or values). An empty slice returns `Ok(0)` without
    /// contacting the browser; more than [`MAX_COOKIES`](crate::cookies::MAX_COOKIES) is refused.
    pub async fn import_cookies(&self, cookies: &[NetscapeCookie]) -> Result<usize> {
        if cookies.is_empty() {
            return Ok(0);
        }
        if cookies.len() > cookies::MAX_COOKIES {
            return Err(BrowserError::Invalid(format!(
                "import_cookies takes at most {} cookies",
                cookies::MAX_COOKIES
            )));
        }
        self.admit(
            ActionKind::Eval,
            None,
            None,
            Some(cookies::admission_detail(cookies)),
        )
        .await?;
        let _l = self.lane.lock().await;
        let params = SetCookiesParams::new(cookies::to_cdp_params(cookies));
        self.inner.execute(params).await.map_err(|e| {
            BrowserError::Cdp(format!(
                "Network.setCookies: {}",
                cookies::scrub(&e.to_string(), cookies)
            ))
        })?;
        Ok(cookies.len())
    }

    /// Requests the network policy refused on this page (redirect hops and subresources included).
    pub fn blocked_requests(&self) -> Vec<BlockedRequest> {
        self.blocked.lock().unwrap().clone()
    }

    /// Typed pre-effect admission. Reads no page state beyond the current URL.
    async fn admit(
        &self,
        action: ActionKind,
        url: Option<String>,
        target: Option<String>,
        detail: Option<String>,
    ) -> Result<()> {
        let url = match url {
            Some(u) => Some(u),
            None if self.guard.admission.is_some() => Some(self.url().await),
            None => None,
        };
        self.guard
            .admit(AdmissionRequest {
                session_id: self.guard.session_id.clone(),
                page_id: self.id.clone(),
                action,
                url,
                target,
                detail,
            })
            .await
    }

    /// Escape hatch to the underlying chromiumoxide page.
    pub fn raw(&self) -> &Page {
        &self.inner
    }

    pub(crate) fn abort_pumps(&self) {
        if let Ok(mut p) = self.pumps.lock() {
            for h in p.drain(..) {
                h.abort();
            }
        }
    }

    pub(crate) async fn close_inner(&self) -> Result<()> {
        self.abort_pumps();
        self.inner.clone().close().await.map_err(cdp)
    }

    pub async fn bring_to_front(&self) -> Result<()> {
        self.inner.bring_to_front().await.map_err(cdp)?;
        Ok(())
    }

    // ---- navigation ------------------------------------------------------

    fn invalidate(&self) {
        let mut o = self.obs.lock().unwrap();
        o.epoch += 1;
        o.refs.clear();
        o.fingerprint.clear();
        o.frame = None;
        o.sigs.clear();
        // A navigation starts a new document: its selectors do not carry stable ids over.
        o.stable.clear();
    }

    /// Waits until this new tab's own first navigation (to about:blank) has committed.
    ///
    /// A tab is created at about:blank and that navigation commits a little later. A
    /// navigation sent before then is discarded by that commit: Chrome answers it with
    /// `net::ERR_ABORTED` and no load ever follows, so the caller waits out its whole request
    /// timeout. Seen on Windows, where a new tab's renderer starts more slowly.
    ///
    /// Before the commit the tab's committed history entry has an empty URL. The tab counts
    /// as settled when that entry has a URL and the main frame's loader is the same on two
    /// consecutive polls. Bounded at two seconds, and it stops at once if Chrome does not
    /// answer, so a browser that behaves differently is not waited on.
    pub(crate) async fn settle_initial_document(&self) {
        use chromiumoxide::cdp::browser_protocol::page::{
            GetFrameTreeParams, GetNavigationHistoryParams,
        };
        use std::time::{Duration, Instant};
        let deadline = Instant::now() + Duration::from_secs(2);
        let mut seen: Option<String> = None;
        while Instant::now() < deadline {
            let Ok(history) = self
                .inner
                .execute(GetNavigationHistoryParams::default())
                .await
            else {
                return;
            };
            let Ok(tree) = self.inner.execute(GetFrameTreeParams::default()).await else {
                return;
            };
            let committed = usize::try_from(history.result.current_index)
                .ok()
                .and_then(|index| history.result.entries.get(index))
                .is_some_and(|entry| !entry.url.is_empty());
            let loader = format!("{:?}", tree.result.frame_tree.frame.loader_id);
            if !committed {
                seen = None;
            } else if seen.as_deref() == Some(loader.as_str()) {
                return;
            } else {
                seen = Some(loader);
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }

    pub async fn goto(&self, url: &str) -> Result<()> {
        // EFF-001 order: policy, then approval; both before any side effect.
        self.guard
            .check_url(Some(&self.id), url, "Navigation")
            .await?;
        self.admit(ActionKind::Navigate, Some(url.to_string()), None, None)
            .await?;
        let _l = self.lane.lock().await;
        self.inner.goto(url).await.map_err(|e| {
            BrowserError::Cdp(format!(
                "navigate '{url}': {e} ({})",
                self.intercept.summary()
            ))
        })?;
        self.inner.wait_for_navigation().await.map_err(cdp)?;
        self.invalidate();
        Ok(())
    }

    pub async fn reload(&self) -> Result<()> {
        self.admit(ActionKind::Reload, None, None, None).await?;
        let _l = self.lane.lock().await;
        self.inner.reload().await.map_err(cdp)?;
        self.inner.wait_for_navigation().await.map_err(cdp)?;
        self.invalidate();
        Ok(())
    }

    pub async fn history(&self, delta: i32) -> Result<()> {
        self.admit(
            ActionKind::History,
            None,
            None,
            Some(format!("delta={delta}")),
        )
        .await?;
        let _l = self.lane.lock().await;
        self.inner
            .evaluate(format!("history.go({delta})"))
            .await
            .map_err(cdp)?;
        tokio::time::sleep(Duration::from_millis(150)).await;
        // Bounded: a traversal that fires no navigation event (bfcache, same-document entry)
        // returns once the wait elapses; the page is then read as it is.
        if let Ok(waited) =
            tokio::time::timeout(HISTORY_NAVIGATION_WAIT, self.inner.wait_for_navigation()).await
        {
            waited.map_err(cdp)?;
        }
        self.invalidate();
        Ok(())
    }

    pub async fn url(&self) -> String {
        self.inner.url().await.ok().flatten().unwrap_or_default()
    }

    pub async fn title(&self) -> String {
        self.inner
            .get_title()
            .await
            .ok()
            .flatten()
            .unwrap_or_default()
    }

    /// Rendered text (`document.body.innerText`).
    pub async fn text(&self) -> Result<String> {
        self.eval_internal("document.body ? document.body.innerText : ''")
            .await
            .map(|v| v.as_str().unwrap_or_default().to_string())
    }

    /// Evaluate a JS expression and return its JSON value. Script can navigate and
    /// act, so it is admitted like any other effect.
    pub async fn eval(&self, expr: &str) -> Result<Value> {
        self.admit(
            ActionKind::Eval,
            None,
            None,
            Some(expr.chars().take(2000).collect()),
        )
        .await?;
        self.eval_internal(expr).await
    }

    /// Runtime-owned evaluation (observation, geometry); never user script.
    async fn eval_internal(&self, expr: &str) -> Result<Value> {
        let r = self.inner.evaluate(expr).await.map_err(cdp)?;
        Ok(r.value().cloned().unwrap_or(Value::Null))
    }

    pub async fn set_viewport(&self, width: u32, height: u32, scale: f64) -> Result<()> {
        use chromiumoxide::cdp::browser_protocol::emulation::SetDeviceMetricsOverrideParams;
        self.inner
            .execute(SetDeviceMetricsOverrideParams::new(
                i64::from(width),
                i64::from(height),
                scale,
                false,
            ))
            .await
            .map_err(cdp)?;
        Ok(())
    }

    // ---- design mode -----------------------------------------------------

    /// Enable the element picker for the current document. It runs in a fresh isolated world
    /// and reports through a `Runtime.addBinding` function bound only to that world, so page
    /// script can neither see nor forge picker messages. Prompt submissions are delivered only
    /// when one native input gesture (a pointer press or key down this page dispatched)
    /// authorizes them; see [`DesignModeBridge`]. Call once per document; navigation ends the
    /// picker and requires a new call with a new nonce.
    pub async fn enable_design_mode(&self, nonce: &str) -> Result<DesignModeSession> {
        let script = design_mode::build_design_mode_script(nonce)?;
        let mut bridge = DesignModeBridge::new(nonce)?;
        let frame_id = self
            .inner
            .mainframe()
            .await
            .map_err(cdp)?
            .ok_or_else(|| BrowserError::Invalid("no main frame".into()))?;
        let mut events = self
            .inner
            .event_listener::<EventBindingCalled>()
            .await
            .map_err(cdp)?;
        let mut add = AddBindingParams::new(bridge.binding_name());
        add.execution_context_name = Some(bridge.world_name());
        self.inner.execute(add).await.map_err(cdp)?;
        let mut world = CreateIsolatedWorldParams::new(frame_id);
        world.world_name = Some(bridge.world_name());
        world.grant_univeral_access = Some(false);
        let context = self
            .inner
            .execute(world)
            .await
            .map_err(cdp)?
            .result
            .execution_context_id;
        *self.design_context.lock().unwrap() = Some(context);
        let eval = EvaluateParams::builder()
            .expression(script)
            .context_id(context)
            .build()
            .map_err(BrowserError::Invalid)?;
        self.inner.execute(eval).await.map_err(cdp)?;
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        let gesture = self.design_gesture.clone();
        let pump = tokio::spawn(async move {
            while let Some(e) = events.next().await {
                let marker = bridge.accept(
                    &e.name,
                    &e.payload,
                    e.execution_context_id == context,
                    &gesture,
                    design_mode::now_ms(),
                );
                if let Some(marker) = marker {
                    if tx.send(marker).is_err() {
                        break;
                    }
                }
            }
        });
        self.pumps.lock().unwrap().push(pump);
        Ok(DesignModeSession { events: rx })
    }

    /// Show the outcome of a submission in the picker popup (`window.__omniOnDesignResult`
    /// in the picker's isolated world).
    pub async fn design_mode_result(&self, id: u64, ok: bool, message: &str) -> Result<()> {
        let context = (*self.design_context.lock().unwrap())
            .ok_or_else(|| BrowserError::Invalid("design mode is not enabled".into()))?;
        let arg = serde_json::json!({"id": id, "ok": ok, "message": message});
        let eval = EvaluateParams::builder()
            .expression(format!(
                "window.__omniOnDesignResult && window.__omniOnDesignResult({arg})"
            ))
            .context_id(context)
            .build()
            .map_err(BrowserError::Invalid)?;
        self.inner.execute(eval).await.map_err(cdp)?;
        Ok(())
    }

    // ---- observation -----------------------------------------------------

    /// Compact tree of the page's controls, each with a ref (`r<epoch>.<n>`). A ref is accepted only in the
    /// epoch it was issued in, for the document it was read from, and while the element behind it still has
    /// the tag, role and name it had here; see [`BrowserPage::act`].
    pub async fn observe(&self) -> Result<Observation> {
        let _l = self.lane.lock().await;
        self.observe_locked().await
    }

    /// Caller holds the lane.
    async fn observe_locked(&self) -> Result<Observation> {
        let frame_sig = self.frame_signature().await?;
        let frame_id = self
            .inner
            .mainframe()
            .await
            .map_err(cdp)?
            .map(|f| f.as_ref().to_string())
            .unwrap_or_default();
        let ax = summarize_ax(&self.ax_tree(Some(OBSERVE_AX_DEPTH)).await?);
        let raw: Vec<RawNode> = self
            .inner
            .evaluate(observe_js())
            .await
            .map_err(cdp)?
            .into_value()
            .map_err(|e| BrowserError::Cdp(format!("decode observation: {e}")))?;
        let viewport: Rect = self
            .inner
            .evaluate("({x:0,y:0,width:window.innerWidth,height:window.innerHeight})")
            .await
            .map_err(cdp)?
            .into_value()
            .map_err(cdp)?;
        let fingerprint = raw
            .iter()
            .map(|n| {
                format!(
                    "{}|{}|{}|{}|{}",
                    n.selector, n.role, n.name, n.visible, n.disabled
                )
            })
            .collect::<Vec<_>>()
            .join("\n");
        // The document must be the same one at the end of the read as at the start, or the nodes and the
        // identity above describe two different pages.
        if self.frame_signature().await? != frame_sig {
            return Err(BrowserError::Cdp(
                "the document was replaced during observation; observe again".into(),
            ));
        }
        let (epoch, nodes, added, removed) = {
            let mut o = self.obs.lock().unwrap();
            // A replaced document advances the epoch even when its controls look the same, so refs from the
            // old document are refused rather than matched by selector in the new one.
            if o.fingerprint != fingerprint || o.frame.as_deref() != Some(frame_sig.as_str()) {
                o.epoch += 1;
                o.fingerprint = fingerprint;
            }
            o.frame = Some(frame_sig.clone());
            let epoch = o.epoch;
            o.refs.clear();
            let mut cur = HashMap::new();
            let mut cur_stable: HashMap<String, u64> = HashMap::new();
            let mut cur_sigs: HashMap<String, NodeState> = HashMap::new();
            let mut nodes = Vec::new();
            for (i, n) in raw.into_iter().enumerate() {
                let name = if n.sensitive {
                    "••••••••".to_string()
                } else {
                    n.name.clone()
                };
                let node_ref = format!("r{epoch}.{}", i + 1);
                let stable_id = if n.selector.is_empty() {
                    0
                } else {
                    let existing = o.stable.get(&n.selector).copied();
                    let id = match existing {
                        Some(id) => id,
                        None => {
                            o.next_stable += 1;
                            o.next_stable
                        }
                    };
                    cur_stable.insert(n.selector.clone(), id);
                    id
                };
                if !n.selector.is_empty() {
                    o.refs.insert(
                        node_ref.clone(),
                        RefEntry {
                            selector: n.selector.clone(),
                            tag: n.tag.clone(),
                            role: n.role.clone(),
                            name: name.clone(),
                        },
                    );
                    cur.insert(n.selector.clone(), format!("{}|{}", n.role, name));
                }
                let node = ObservedNode {
                    node_ref,
                    role: n.role,
                    name,
                    tag: n.tag,
                    selector: n.selector,
                    visible: n.visible,
                    disabled: n.disabled,
                    sensitive: n.sensitive,
                    frame_id: frame_id.clone(),
                    stable_id,
                    bounds: n.bounds,
                };
                if !node.selector.is_empty() {
                    cur_sigs.insert(node.selector.clone(), NodeState::of(&node));
                }
                nodes.push(node);
            }
            o.stable = cur_stable;
            o.sigs = cur_sigs;
            let added = cur
                .keys()
                .filter(|k| !o.previous.contains_key(*k))
                .cloned()
                .collect();
            let removed = o
                .previous
                .keys()
                .filter(|k| !cur.contains_key(*k))
                .cloned()
                .collect();
            o.previous = cur;
            (epoch, nodes, added, removed)
        };
        let console_errors = self
            .console
            .lock()
            .await
            .iter()
            .filter(|l| matches!(l.level.as_str(), "error" | "exception"))
            .count();
        Ok(Observation {
            page_id: self.id.clone(),
            epoch,
            url: self.url().await,
            title: self.title().await,
            viewport,
            nodes,
            ax,
            console_errors,
            added,
            removed,
        })
    }

    /// Resolve a target to a unique CSS selector, rejecting stale refs.
    async fn resolve(&self, target: &Target) -> Result<Option<String>> {
        match target {
            Target::Point(..) => Ok(None),
            Target::Selector(s) => {
                self.unique(s).await?;
                Ok(Some(s.clone()))
            }
            Target::Ref(r) => {
                let (entry, current_epoch) = {
                    let o = self.obs.lock().unwrap();
                    (o.refs.get(r).cloned(), o.epoch)
                };
                let entry = entry.ok_or_else(|| BrowserError::StaleRef(r.clone()))?;
                let ref_epoch: u64 = r
                    .trim_start_matches('r')
                    .split('.')
                    .next()
                    .and_then(|e| e.parse().ok())
                    .unwrap_or(0);
                if ref_epoch != current_epoch {
                    return Err(BrowserError::StaleRef(r.clone()));
                }
                // The document the ref was read from must still be the page's document: a navigation or
                // reload replaced the frame, and a selector can match a different element in the new one.
                let seen = self.obs.lock().unwrap().frame.clone();
                if seen.as_deref() != Some(self.frame_signature().await?.as_str()) {
                    return Err(BrowserError::StaleRef(r.clone()));
                }
                // Identity check: the element behind the selector must still have the tag, the role and the
                // name it had when it was observed, else the page changed under the ref. Role is compared
                // as `observe` computed it (the `role` attribute, else the tag's implied role), so a
                // same-tag element that takes over a selector with another role is refused.
                let script = ELEMENT_IDENTITY_JS
                    .replace("__ROLE__", ROLE_EXPR)
                    .replace("__SELECTOR__", &js(&entry.selector));
                let sig = self.eval(&script).await?;
                let text = |k: &str| sig.get(k).and_then(Value::as_str);
                let same_tag = text("tag") == Some(entry.tag.as_str());
                let same_role = text("role") == Some(entry.role.as_str());
                let same_name = text("name") == Some(entry.name.as_str());
                // An editable control's text changes as the user types, so its name is not compared.
                let editable = matches!(entry.tag.as_str(), "input" | "textarea" | "select");
                if !(same_tag && same_role && (same_name || editable)) {
                    return Err(BrowserError::StaleRef(r.clone()));
                }
                Ok(Some(entry.selector))
            }
        }
    }

    /// Identity of the main document: its frame id and its loader id. A navigation or reload gives the frame a
    /// new loader; a same-document change (history API, hash) does not.
    async fn frame_signature(&self) -> Result<String> {
        use chromiumoxide::cdp::browser_protocol::page::GetFrameTreeParams;
        let tree = self
            .inner
            .execute(GetFrameTreeParams::default())
            .await
            .map_err(cdp)?;
        let frame = &tree.result.frame_tree.frame;
        Ok(format!("{:?}|{:?}", frame.id, frame.loader_id))
    }

    /// Run one action on an observed ref and return what it changed.
    ///
    /// Before anything happens the ref is checked: it must be from the page's current epoch, the document it
    /// was read from must still be the page's document, and the element behind it must still have the tag,
    /// role and name it had at observe. Any mismatch is [`BrowserError::StaleRef`]. The action is then
    /// admitted (the hook sees the ref and the element's role and name), run under the page lane, and the
    /// page is observed again under that same lane hold, so nothing else acts in between. The returned
    /// [`ObservationDiff`] says what appeared, disappeared or changed; when the epoch moved, earlier refs are
    /// refused and the diff carries the new refs of what is new.
    ///
    /// The watchdog counts an action that left no diff (or failed) against its ref. After
    /// [`DEFAULT_ACTION_LOOP_LIMIT`](crate::DEFAULT_ACTION_LOOP_LIMIT) such repeats (see
    /// [`BrowserPage::set_action_loop_limit`]) the next identical action is refused with
    /// [`BrowserError::ActionLoop`], and so is every action after it until
    /// [`BrowserPage::reset_action_watch`].
    pub async fn act(&self, node_ref: &str, action: &RefAction) -> Result<ActResult> {
        let key = action.watch_key(node_ref);
        self.watch.lock().unwrap().before(&key)?;
        match self.act_once(node_ref, action).await {
            Ok(mut result) => {
                result.repeats = self
                    .watch
                    .lock()
                    .unwrap()
                    .after(key, result.diff.is_empty());
                Ok(result)
            }
            Err(e) => {
                self.watch.lock().unwrap().after(key, true);
                Err(e)
            }
        }
    }

    /// Set how many identical no-diff actions [`BrowserPage::act`] allows (at least 1).
    pub fn set_action_loop_limit(&self, limit: u32) -> Result<()> {
        self.watch.lock().unwrap().set_limit(limit)
    }

    /// Clear the watchdog's count and its stop. Call it when a person or the host decided the run may go on.
    pub fn reset_action_watch(&self) {
        self.watch.lock().unwrap().reset();
    }

    async fn act_once(&self, node_ref: &str, action: &RefAction) -> Result<ActResult> {
        let target = Target::Ref(node_ref.to_string());
        let element = {
            let o = self.obs.lock().unwrap();
            o.refs
                .get(node_ref)
                .map(|e| format!("element role={} name={}", e.role, e.name))
        };
        let (kind, detail) = action.admission();
        let detail = match (detail, element) {
            (Some(d), Some(e)) => Some(format!("{d}; {e}")),
            (Some(d), None) => Some(d),
            (None, e) => e,
        };
        self.admit(kind, None, Some(describe(&target)), detail)
            .await?;
        let _l = self.lane.lock().await;
        let url_before = self.url().await;
        let (epoch_before, before, frame_before) = {
            let o = self.obs.lock().unwrap();
            (o.epoch, o.sigs.clone(), o.frame.clone())
        };
        match action {
            RefAction::Click => self.click_n(&target, 1).await?,
            RefAction::DoubleClick => self.click_n(&target, 2).await?,
            RefAction::Hover => {
                let (x, y) = self.point_of(&target).await?;
                self.move_to(x, y).await?;
            }
            RefAction::Fill { text, clear } => self.fill_locked(&target, text, *clear).await?,
            RefAction::SelectOption { value } => self.select_locked(&target, value).await?,
        }
        let obs = self.observe_after_action().await?;
        let document_replaced = self.obs.lock().unwrap().frame != frame_before;
        let mut added = Vec::new();
        let mut changed = Vec::new();
        let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
        for n in &obs.nodes {
            if n.selector.is_empty() {
                continue;
            }
            seen.insert(n.selector.as_str());
            match before.get(&n.selector) {
                None => added.push(n.clone()),
                Some(b) => {
                    let a = NodeState::of(n);
                    if *b != a {
                        changed.push(NodeChange {
                            node_ref: n.node_ref.clone(),
                            selector: n.selector.clone(),
                            before: b.clone(),
                            after: a,
                        });
                    }
                }
            }
        }
        let mut removed: Vec<String> = before
            .keys()
            .filter(|k| !seen.contains(k.as_str()))
            .cloned()
            .collect();
        removed.sort();
        Ok(ActResult {
            page_id: obs.page_id.clone(),
            node_ref: node_ref.to_string(),
            epoch: obs.epoch,
            diff: ObservationDiff {
                epoch_before,
                epoch_after: obs.epoch,
                url_before,
                url_after: obs.url.clone(),
                document_replaced,
                added,
                removed,
                changed,
            },
            repeats: 0,
        })
    }

    /// Observe once the action's effect has settled. An action can start a navigation; an observation that
    /// straddles the document swap fails, so it is tried again a few times. Caller holds the lane.
    async fn observe_after_action(&self) -> Result<Observation> {
        let mut last = None;
        for attempt in 0..4u32 {
            if attempt > 0 {
                tokio::time::sleep(Duration::from_millis(150)).await;
            }
            match self.observe_locked().await {
                Ok(obs) => return Ok(obs),
                Err(e) => last = Some(e),
            }
        }
        Err(BrowserError::Cdp(format!(
            "the action ran, but the page could not be observed afterwards: {}",
            last.map(|e| e.to_string()).unwrap_or_default()
        )))
    }

    async fn unique(&self, selector: &str) -> Result<()> {
        let n = self
            .eval_internal(&format!(
                "document.querySelectorAll({}).length",
                js(selector)
            ))
            .await?
            .as_u64()
            .unwrap_or(0);
        match n {
            1 => Ok(()),
            0 => Err(BrowserError::NoElement(selector.into())),
            n => Err(BrowserError::Ambiguous(selector.into(), n)),
        }
    }

    /// Scroll into view, return the centre point, and verify nothing covers it.
    async fn point_of(&self, target: &Target) -> Result<(f64, f64)> {
        if let Target::Point(x, y) = target {
            return Ok((*x, *y));
        }
        let sel = self.resolve(target).await?.expect("selector");
        let v = self
            .eval(&format!(
                "(()=>{{const e=document.querySelector({s});e.scrollIntoView({{block:'center',inline:'center'}});\
                 const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return null;\
                 const x=r.x+r.width/2,y=r.y+r.height/2;const t=document.elementFromPoint(x,y);\
                 const hit=!!t&&(t===e||e.contains(t)||t.contains(e));return {{x,y,hit}}}})()",
                s = js(&sel)
            ))
            .await?;
        if v.is_null() {
            return Err(BrowserError::NotInteractable(sel));
        }
        if v.get("hit").and_then(Value::as_bool) != Some(true) {
            return Err(BrowserError::NotInteractable(format!(
                "{sel} (covered by another element)"
            )));
        }
        Ok((
            v["x"].as_f64().unwrap_or(0.0),
            v["y"].as_f64().unwrap_or(0.0),
        ))
    }

    // ---- real pointer input ----------------------------------------------

    async fn mouse_event(
        &self,
        kind: DispatchMouseEventType,
        x: f64,
        y: f64,
        button: MouseButton,
        click_count: i64,
    ) -> Result<()> {
        if matches!(kind, DispatchMouseEventType::MousePressed) {
            self.design_gesture.stamp();
        }
        let mut p = DispatchMouseEventParams::new(kind.clone(), x, y);
        p.button = Some(button);
        p.click_count = Some(click_count);
        p.buttons = Some(match kind {
            DispatchMouseEventType::MousePressed => 1,
            DispatchMouseEventType::MouseReleased => 0,
            _ => *self.buttons.lock().unwrap(),
        });
        self.inner.execute(p).await.map_err(cdp)?;
        *self.mouse.lock().unwrap() = (x, y);
        Ok(())
    }

    async fn move_to(&self, x: f64, y: f64) -> Result<()> {
        self.mouse_event(
            DispatchMouseEventType::MouseMoved,
            x,
            y,
            MouseButton::None,
            0,
        )
        .await
    }

    pub async fn hover(&self, target: &Target) -> Result<()> {
        self.admit(ActionKind::Hover, None, Some(describe(target)), None)
            .await?;
        let _l = self.lane.lock().await;
        let (x, y) = self.point_of(target).await?;
        self.move_to(x, y).await
    }

    pub async fn click(&self, target: &Target) -> Result<()> {
        self.admit(ActionKind::Click, None, Some(describe(target)), None)
            .await?;
        let _l = self.lane.lock().await;
        self.click_n(target, 1).await
    }

    pub async fn double_click(&self, target: &Target) -> Result<()> {
        self.admit(ActionKind::DoubleClick, None, Some(describe(target)), None)
            .await?;
        let _l = self.lane.lock().await;
        self.click_n(target, 2).await
    }

    /// Caller holds the lane.
    async fn click_n(&self, target: &Target, count: i64) -> Result<()> {
        let (x, y) = self.point_of(target).await?;
        self.move_to(x, y).await?;
        for n in 1..=count {
            self.mouse_event(
                DispatchMouseEventType::MousePressed,
                x,
                y,
                MouseButton::Left,
                n,
            )
            .await?;
            self.mouse_event(
                DispatchMouseEventType::MouseReleased,
                x,
                y,
                MouseButton::Left,
                n,
            )
            .await?;
        }
        Ok(())
    }

    /// Press at `from`, move in `steps` increments, release at `to`.
    pub async fn drag(&self, from: &Target, to: &Target, steps: u32) -> Result<()> {
        self.admit(
            ActionKind::Drag,
            None,
            Some(format!("{} -> {}", describe(from), describe(to))),
            None,
        )
        .await?;
        let _l = self.lane.lock().await;
        let (x0, y0) = self.point_of(from).await?;
        let (x1, y1) = self.point_of(to).await?;
        self.move_to(x0, y0).await?;
        self.mouse_event(
            DispatchMouseEventType::MousePressed,
            x0,
            y0,
            MouseButton::Left,
            1,
        )
        .await?;
        *self.buttons.lock().unwrap() = 1;
        let steps = steps.max(1);
        for i in 1..=steps {
            let t = f64::from(i) / f64::from(steps);
            self.mouse_event(
                DispatchMouseEventType::MouseMoved,
                x0 + (x1 - x0) * t,
                y0 + (y1 - y0) * t,
                MouseButton::Left,
                0,
            )
            .await?;
        }
        *self.buttons.lock().unwrap() = 0;
        self.mouse_event(
            DispatchMouseEventType::MouseReleased,
            x1,
            y1,
            MouseButton::Left,
            1,
        )
        .await
    }

    /// Mouse-wheel scroll at the target (or viewport centre when `None`).
    pub async fn wheel(&self, at: Option<&Target>, dx: f64, dy: f64) -> Result<()> {
        self.admit(
            ActionKind::Wheel,
            None,
            at.map(describe),
            Some(format!("dx={dx} dy={dy}")),
        )
        .await?;
        let _l = self.lane.lock().await;
        let (x, y) = match at {
            Some(t) => self.point_of(t).await?,
            None => {
                let v = self
                    .eval_internal("({x:innerWidth/2,y:innerHeight/2})")
                    .await?;
                (
                    v["x"].as_f64().unwrap_or(100.0),
                    v["y"].as_f64().unwrap_or(100.0),
                )
            }
        };
        let mut p = DispatchMouseEventParams::new(DispatchMouseEventType::MouseWheel, x, y);
        p.delta_x = Some(dx);
        p.delta_y = Some(dy);
        self.inner.execute(p).await.map_err(cdp)?;
        Ok(())
    }

    /// Programmatic scroll (`scrollBy`) of the element at `target`, or of the window when
    /// `None`. Use it where a wheel event at the element's centre is wrong: a covered element,
    /// or one that is not scrollable under the pointer. Selectors and refs must resolve to one
    /// element; a point scrolls the element under it. No element at a point is an error.
    pub async fn scroll_by(&self, target: Option<&Target>, dx: f64, dy: f64) -> Result<()> {
        if !dx.is_finite() || !dy.is_finite() {
            return Err(BrowserError::Invalid(format!(
                "scroll offsets must be finite, got dx={dx} dy={dy}"
            )));
        }
        self.admit(
            ActionKind::Wheel,
            None,
            target.map(describe),
            Some(format!("scroll_by dx={dx} dy={dy}")),
        )
        .await?;
        let _l = self.lane.lock().await;
        let offset = format!("{{left:{dx},top:{dy}}}");
        let found = match target {
            None => {
                self.eval_internal(&format!(
                    "(()=>{{window.scrollBy({offset});return true}})()"
                ))
                .await?
            }
            Some(Target::Point(x, y)) => {
                if !x.is_finite() || !y.is_finite() {
                    return Err(BrowserError::Invalid(format!(
                        "scroll point must be finite, got {x},{y}"
                    )));
                }
                self.eval_internal(&format!(
                    "(()=>{{const e=document.elementFromPoint({x},{y});if(!e)return false;e.scrollBy({offset});return true}})()"
                ))
                .await?
            }
            Some(t) => {
                let sel = self.resolve(t).await?.expect("selector");
                self.eval_internal(&format!(
                    "(()=>{{const e=document.querySelector({});if(!e)return false;e.scrollBy({offset});return true}})()",
                    js(&sel)
                ))
                .await?
            }
        };
        if found.as_bool() != Some(true) {
            return Err(BrowserError::NoElement(
                target.map(describe).unwrap_or_default(),
            ));
        }
        Ok(())
    }

    // ---- real keyboard input ---------------------------------------------

    async fn key_event(
        &self,
        kind: DispatchKeyEventType,
        d: &KeyDef,
        mods: i64,
        with_text: bool,
    ) -> Result<()> {
        if matches!(
            kind,
            DispatchKeyEventType::KeyDown | DispatchKeyEventType::RawKeyDown
        ) {
            self.design_gesture.stamp();
        }
        let mut p = DispatchKeyEventParams::new(kind);
        p.modifiers = Some(mods);
        p.key = Some(d.key.clone());
        if !d.code.is_empty() {
            p.code = Some(d.code.clone());
        }
        p.windows_virtual_key_code = Some(d.vk);
        p.native_virtual_key_code = Some(d.vk);
        if with_text {
            p.text = d.text.clone();
            p.unmodified_text = d.text.clone();
        }
        self.inner.execute(p).await.map_err(cdp)?;
        Ok(())
    }

    async fn press_locked(&self, spec: &str) -> Result<()> {
        let (mods, mod_keys, def) = keys::parse_chord(spec)?;
        for (_, m) in &mod_keys {
            self.key_event(DispatchKeyEventType::RawKeyDown, m, mods, false)
                .await?;
        }
        // Shortcut chords (Ctrl/Meta/Alt) carry no text.
        let text = mods & (keys::CTRL | keys::META | keys::ALT) == 0;
        let kind = if text && def.text.is_some() {
            DispatchKeyEventType::KeyDown
        } else {
            DispatchKeyEventType::RawKeyDown
        };
        self.key_event(kind, &def, mods, text).await?;
        self.key_event(DispatchKeyEventType::KeyUp, &def, mods, false)
            .await?;
        for (_, m) in mod_keys.iter().rev() {
            self.key_event(DispatchKeyEventType::KeyUp, m, 0, false)
                .await?;
        }
        Ok(())
    }

    /// Press a key or chord (`Enter`, `Tab`, `Control+a`) on the focused element.
    pub async fn press(&self, spec: &str) -> Result<()> {
        self.admit(ActionKind::Press, None, Some(spec.to_string()), None)
            .await?;
        let _l = self.lane.lock().await;
        self.press_locked(spec).await
    }

    /// Type text one key event at a time into the focused element.
    pub async fn type_text(&self, text: &str) -> Result<()> {
        self.admit(
            ActionKind::TypeText,
            None,
            None,
            Some(format!("chars={}", text.chars().count())),
        )
        .await?;
        let _l = self.lane.lock().await;
        self.type_locked(text).await
    }

    async fn type_locked(&self, text: &str) -> Result<()> {
        for c in text.chars() {
            let d = keys::char_key(c);
            self.key_event(DispatchKeyEventType::KeyDown, &d, 0, true)
                .await?;
            self.key_event(DispatchKeyEventType::KeyUp, &d, 0, false)
                .await?;
        }
        Ok(())
    }

    /// Click the target to focus it, then type.
    pub async fn fill(&self, target: &Target, text: &str, clear: bool) -> Result<()> {
        self.admit(
            ActionKind::Fill,
            None,
            Some(describe(target)),
            Some(format!("chars={} clear={clear}", text.chars().count())),
        )
        .await?;
        let _l = self.lane.lock().await;
        self.fill_locked(target, text, clear).await
    }

    /// Caller holds the lane.
    async fn fill_locked(&self, target: &Target, text: &str, clear: bool) -> Result<()> {
        self.click_n(target, 1).await?;
        if clear {
            let sel_all = if cfg!(target_os = "macos") {
                "Meta+a"
            } else {
                "Control+a"
            };
            self.press_locked(sel_all).await?;
            self.press_locked("Backspace").await?;
        }
        self.type_locked(text).await
    }

    // ---- other actions -----------------------------------------------------

    /// Choose a `<select>` option by value/label. Native popups cannot be driven
    /// over CDP, so this sets the value and fires `input`/`change` (documented gap).
    pub async fn select_option(&self, target: &Target, value: &str) -> Result<()> {
        self.admit(
            ActionKind::Select,
            None,
            Some(describe(target)),
            Some(format!("value={value}")),
        )
        .await?;
        let _l = self.lane.lock().await;
        self.select_locked(target, value).await
    }

    /// Caller holds the lane.
    async fn select_locked(&self, target: &Target, value: &str) -> Result<()> {
        let sel = self
            .resolve(target)
            .await?
            .ok_or_else(|| BrowserError::Invalid("select needs an element".into()))?;
        let r = self
            .eval(&format!(
                "(()=>{{const e=document.querySelector({s});const w={v};\
                 const o=[...e.options].find(o=>o.value===w||o.label===w||o.text.trim()===w);if(!o)return 'nooption';\
                 e.value=o.value;e.dispatchEvent(new Event('input',{{bubbles:true}}));e.dispatchEvent(new Event('change',{{bubbles:true}}));return 'ok'}})()",
                s = js(&sel),
                v = js(value)
            ))
            .await?;
        if r.as_str() == Some("ok") {
            Ok(())
        } else {
            Err(BrowserError::Invalid(format!(
                "'{sel}' has no option '{value}'"
            )))
        }
    }

    pub async fn upload(&self, target: &Target, file: &Path) -> Result<()> {
        self.admit(
            ActionKind::Upload,
            None,
            Some(describe(target)),
            Some(file.display().to_string()),
        )
        .await?;
        let _l = self.lane.lock().await;
        let file = file.canonicalize()?;
        if !file.is_file() {
            return Err(BrowserError::Invalid(
                "upload must be a regular file".into(),
            ));
        }
        if let Some(root) = &self.upload_root {
            if !file.starts_with(root.canonicalize()?) {
                return Err(BrowserError::Invalid(
                    "upload outside the configured upload root".into(),
                ));
            }
        }
        if std::fs::metadata(&file)?.len() > MAX_UPLOAD_BYTES {
            return Err(BrowserError::Invalid("upload exceeds 64 MiB".into()));
        }
        let sel = self
            .resolve(target)
            .await?
            .ok_or_else(|| BrowserError::Invalid("upload needs an element".into()))?;
        let el = self
            .inner
            .find_element(sel.as_str())
            .await
            .map_err(|_| BrowserError::NoElement(sel.clone()))?;
        let node = el.description().await.map_err(cdp)?;
        self.inner
            .execute(
                SetFileInputFilesParams::builder()
                    .file(file.to_string_lossy().to_string())
                    .backend_node_id(node.backend_node_id)
                    .build()
                    .map_err(BrowserError::Invalid)?,
            )
            .await
            .map_err(cdp)?;
        Ok(())
    }

    pub async fn wait_for(&self, selector: &str, timeout: Duration) -> Result<()> {
        self.wait_eval(
            &format!("!!document.querySelector({})", js(selector)),
            timeout,
        )
        .await
    }

    /// Poll a JS expression until truthy.
    pub async fn wait_eval(&self, expr: &str, timeout: Duration) -> Result<()> {
        self.admit(
            ActionKind::Eval,
            None,
            None,
            Some(expr.chars().take(2000).collect()),
        )
        .await?;
        let deadline = Instant::now() + timeout;
        loop {
            let v = self.eval_internal(expr).await?;
            if v.as_bool()
                .unwrap_or(!v.is_null() && v != Value::Bool(false))
            {
                return Ok(());
            }
            if Instant::now() >= deadline {
                return Err(BrowserError::Timeout(expr.to_string()));
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    }

    pub async fn screenshot(&self) -> Result<Vec<u8>> {
        self.screenshot_with(ScreenshotOptions::default()).await
    }

    /// PNG screenshot of the viewport with options; `ScreenshotOptions::default()` matches
    /// [`BrowserPage::screenshot`].
    pub async fn screenshot_with(&self, options: ScreenshotOptions) -> Result<Vec<u8>> {
        let params = self.screenshot_params(&options).await?;
        self.inner.screenshot(params).await.map_err(cdp)
    }

    /// Build the CDP capture request for `options`. A scale without a clip captures the visual
    /// viewport (`Page.getLayoutMetrics`) at that scale, so the output is `scale` times its CSS size.
    async fn screenshot_params(&self, options: &ScreenshotOptions) -> Result<ScreenshotParams> {
        let mut params_builder = CaptureScreenshotParams::builder();
        match options.format {
            ScreenshotFormat::Png => {
                params_builder = params_builder.format(CaptureScreenshotFormat::Png);
            }
            ScreenshotFormat::Jpeg { quality } => {
                if !(1..=100).contains(&quality) {
                    return Err(BrowserError::Invalid(
                        "JPEG screenshot quality must be 1 to 100".into(),
                    ));
                }
                if options.omit_background {
                    return Err(BrowserError::Invalid(
                        "omit_background needs a PNG screenshot".into(),
                    ));
                }
                params_builder = params_builder
                    .format(CaptureScreenshotFormat::Jpeg)
                    .quality(i64::from(quality));
            }
        }
        let scale = match options.scale {
            None => None,
            Some(s) if s.is_finite() && s > 0.0 => Some(s),
            Some(_) => {
                return Err(BrowserError::Invalid(
                    "screenshot scale must be positive and finite".into(),
                ))
            }
        };
        if let Some(region) = &options.clip {
            region.validate()?;
        }
        let clip = match (options.clip, scale) {
            (None, None) => None,
            (region, scale) => {
                let (x, y, width, height) = match region {
                    Some(r) => (r.x, r.y, r.width, r.height),
                    None => {
                        let metrics = self.inner.layout_metrics().await.map_err(cdp)?;
                        let v = metrics.css_visual_viewport;
                        (v.page_x, v.page_y, v.client_width, v.client_height)
                    }
                };
                Some(Viewport {
                    x,
                    y,
                    width,
                    height,
                    scale: scale.unwrap_or(1.0),
                })
            }
        };
        if let Some(clip) = clip {
            params_builder = params_builder.clip(clip);
        }
        Ok(ScreenshotParams {
            cdp_params: params_builder.build(),
            full_page: None,
            omit_background: Some(options.omit_background),
        })
    }

    pub async fn screenshot_to(&self, path: &Path) -> Result<()> {
        std::fs::write(path, self.screenshot().await?)?;
        Ok(())
    }

    pub async fn console(&self) -> Vec<ConsoleLine> {
        self.console.lock().await.clone()
    }

    pub async fn clear_console(&self) {
        self.console.lock().await.clear();
    }
}

/// Register the `Fetch.requestPaused` listener, then enable `Fetch` for every URL, in that
/// order so no request is paused without a listener. One short task per request: the network
/// policy first (its refusal is final), then the caller's hook when one is installed.
async fn start_intercept_pump(
    inner: &Page,
    page_id: &str,
    guard: &Arc<Guard>,
    sink: Arc<StdMutex<Vec<BlockedRequest>>>,
    stats: Arc<InterceptStats>,
    hook_slot: Arc<StdMutex<Option<RequestInterceptor>>>,
) -> Result<JoinHandle<()>> {
    let mut paused = inner
        .event_listener::<EventRequestPaused>()
        .await
        .map_err(cdp)?;
    let page = inner.clone();
    let g = guard.clone();
    let page_id = page_id.to_string();
    let pump = tokio::spawn(async move {
        use std::sync::atomic::Ordering::Relaxed;
        while let Some(e) = paused.next().await {
            let stats = stats.clone();
            stats.paused.fetch_add(1, Relaxed);
            let page = page.clone();
            let g = g.clone();
            let sink = sink.clone();
            let pid = page_id.clone();
            let hook_slot = hook_slot.clone();
            tokio::spawn(async move {
                let kind = format!("{:?}", e.resource_type);
                match g.check_request(&e.request.url, &kind).await {
                    Ok(()) => {
                        let hook = hook_slot.lock().unwrap().clone();
                        let decision = match hook {
                            None => InterceptDecision::Continue,
                            Some(hook) => {
                                match serde_json::to_value(&*e)
                                    .ok()
                                    .and_then(|v| InterceptedRequest::from_cdp_value(&v))
                                {
                                    Some(request) => {
                                        run_interceptor(&hook, request, INTERCEPTOR_TIMEOUT).await
                                    }
                                    None => InterceptDecision::Fail(InterceptFailure::Failed),
                                }
                            }
                        };
                        let hook_failed = matches!(decision, InterceptDecision::Fail(_));
                        let (counter, result) = match command_for(e.request_id.clone(), decision) {
                            PausedCommand::Continue(p) => {
                                (&stats.continued, page.execute(p).await.map(|_| ()))
                            }
                            PausedCommand::Fulfill(p) => {
                                (&stats.fulfilled, page.execute(p).await.map(|_| ()))
                            }
                            PausedCommand::Fail(p) => {
                                (&stats.refused, page.execute(p).await.map(|_| ()))
                            }
                        };
                        match result {
                            Ok(()) => {
                                counter.fetch_add(1, Relaxed);
                                if hook_failed {
                                    let mut b = sink.lock().unwrap();
                                    if b.len() < 500 {
                                        b.push(BlockedRequest {
                                            url: e.request.url.clone(),
                                            reason: "failed by the request interceptor".into(),
                                        });
                                    }
                                }
                            }
                            Err(error) => {
                                stats.errors.fetch_add(1, Relaxed);
                                *stats.last_error.lock().unwrap() = Some(error.to_string());
                            }
                        }
                    }
                    Err(reason) => {
                        let _ = page
                            .execute(FailRequestParams::new(
                                e.request_id.clone(),
                                ErrorReason::BlockedByClient,
                            ))
                            .await;
                        stats.refused.fetch_add(1, Relaxed);
                        g.denied_network(Some(&pid), &kind, &reason);
                        let mut b = sink.lock().unwrap();
                        if b.len() < 500 {
                            b.push(BlockedRequest {
                                url: e.request.url.clone(),
                                reason: reason.to_string(),
                            });
                        }
                    }
                }
            });
        }
    });
    let en = FetchEnableParams {
        patterns: Some(vec![RequestPattern {
            url_pattern: Some("*".into()),
            resource_type: None,
            request_stage: None,
        }]),
        ..Default::default()
    };
    if let Err(e) = inner.execute(en).await {
        pump.abort();
        return Err(cdp(e));
    }
    Ok(pump)
}

async fn push_capped(sink: &Arc<Mutex<Vec<ConsoleLine>>>, line: ConsoleLine) {
    let mut g = sink.lock().await;
    if g.len() >= MAX_CONSOLE_LINES {
        g.remove(0);
    }
    g.push(line);
}

fn describe(t: &Target) -> String {
    match t {
        Target::Ref(r) => format!("ref:{r}"),
        Target::Selector(s) => format!("css:{s}"),
        Target::Point(x, y) => format!("point:{x},{y}"),
    }
}

fn js(s: &str) -> String {
    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into())
}

const OBSERVE_JS_TEMPLATE: &str = r#"(() => {
  const esc = globalThis.CSS?.escape || (v => String(v).replace(/[^a-zA-Z0-9_-]/g, '\\$&'));
  const unique = c => { if (!c) return null; try { return document.querySelectorAll(c).length === 1 ? c : null; } catch (_) { return null; } };
  const selectorFor = el => {
    if (el.id) { const s = unique('#' + esc(el.id)); if (s) return s; }
    for (const a of ['data-testid', 'name', 'aria-label']) {
      const v = el.getAttribute(a);
      if (v) { const s = unique(el.tagName.toLowerCase() + '[' + a + '="' + esc(v) + '"]'); if (s) return s; }
    }
    const parts = [];
    for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
      let p = n.tagName.toLowerCase();
      const sib = n.parentElement ? [...n.parentElement.children].filter(x => x.tagName === n.tagName) : [];
      if (sib.length > 1) p += ':nth-of-type(' + (sib.indexOf(n) + 1) + ')';
      parts.unshift(p);
      const c = parts.join(' > ');
      if (unique(c)) return c;
    }
    return '';
  };
  const sel = 'a[href],button,input,select,textarea,[role],[tabindex],[contenteditable="true"],[onclick]';
  return [...document.querySelectorAll(sel)].slice(0, 300).map(el => {
    const r = el.getBoundingClientRect();
    const ac = (el.getAttribute('autocomplete') || '').trim().toLowerCase();
    const sensitive = (el instanceof HTMLInputElement && el.type.toLowerCase() === 'password') || ac === 'current-password' || ac === 'new-password';
    const visible = (() => {
      for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
        const s = getComputedStyle(n);
        if (n.hidden || n.getAttribute('aria-hidden') === 'true' || s.visibility === 'hidden' || s.display === 'none' || s.opacity === '0') return false;
      }
      return r.width > 0 && r.height > 0;
    })();
    return {
      role: __ROLE__,
      name: (el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('placeholder') || '').trim().slice(0, 160),
      tag: el.tagName.toLowerCase(), selector: selectorFor(el), visible,
      disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true', sensitive,
      bounds: {x: r.x, y: r.y, width: r.width, height: r.height}
    };
  });
})()"#;

/// The role of `el`, exactly as `observe` reports it: the `role` attribute, else the tag's implied role, else
/// the tag name. The ref check evaluates this same text, so the two cannot disagree.
const ROLE_EXPR: &str = "el.getAttribute('role') || ({A:'link',BUTTON:'button',INPUT:'textbox',SELECT:'combobox',TEXTAREA:'textbox'}[el.tagName] || el.tagName.toLowerCase())";

fn observe_js() -> String {
    OBSERVE_JS_TEMPLATE.replace("__ROLE__", ROLE_EXPR)
}

/// Reads the one element a ref's selector matches: its tag, role and name, as `observe` computes them.
/// `null` when the selector no longer matches exactly one element.
const ELEMENT_IDENTITY_JS: &str = r#"(()=>{const l=document.querySelectorAll(__SELECTOR__);if(l.length!==1)return null;const el=l[0];
return {tag:el.tagName.toLowerCase(),role:__ROLE__,name:(el.getAttribute('aria-label')||el.innerText||el.value||el.getAttribute('placeholder')||'').trim().slice(0,160)}})()"#;

/// The `http` or `https` origin of `url` (scheme, host, non-default port; lower case; no userinfo, path,
/// query or fragment), or `None` for any other kind of address.
#[cfg(feature = "secret-fill")]
fn origin_of(url: &str) -> Option<String> {
    let (scheme, rest) = url.trim().split_once("://")?;
    let scheme = scheme.to_ascii_lowercase();
    if scheme != "http" && scheme != "https" {
        return None;
    }
    let authority = rest.split(['/', '?', '#']).next()?;
    let host_port = authority
        .rsplit_once('@')
        .map_or(authority, |(_, host)| host)
        .to_ascii_lowercase();
    if host_port.is_empty() || host_port.contains(char::is_whitespace) {
        return None;
    }
    let (host, port) = match host_port.rsplit_once(':') {
        Some((host, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => {
            (host, Some(port))
        }
        _ => (host_port.as_str(), None),
    };
    if host.is_empty() {
        return None;
    }
    let default = if scheme == "https" { "443" } else { "80" };
    Some(match port {
        Some(port) if port != default => format!("{scheme}://{host}:{port}"),
        _ => format!("{scheme}://{host}"),
    })
}

/// True for an `<input>` that is a password or a card field: `type=password`, or an `autocomplete`
/// token of `current-password`, `new-password` or starting `cc-`. Takes the selector as a JS string literal.
#[cfg(feature = "secret-fill")]
const CREDENTIAL_FIELD_JS: &str = r#"(()=>{const e=document.querySelector(__SELECTOR__);
if(!e||e.tagName!=='INPUT')return false;
if((e.type||'').toLowerCase()==='password')return true;
return (e.getAttribute('autocomplete')||'').toLowerCase().split(/\s+/).some(t=>t==='current-password'||t==='new-password'||t.startsWith('cc-'))})()"#;

#[cfg(feature = "secret-fill")]
impl BrowserPage {
    /// Type a secret into a password or card field of this page (feature `secret-fill`; works on every
    /// platform the crate runs on, Linux included).
    ///
    /// Refused, with nothing typed, unless: `claimed_origin` is an `http` or `https` address whose origin
    /// equals the origin of the page's own current address (the page is asked, never the caller's word
    /// about it), and `target` resolves to one `<input>` that is `type=password` or has an `autocomplete`
    /// of `current-password`, `new-password` or `cc-*`. The audit record carries only the character count
    /// (as for `fill`). The secret is a [`rightkit_crypto::Secret`], wiped when dropped; it is typed one
    /// key event at a time, and the per-key event descriptors this makes are not wiped (a limit).
    pub async fn fill_secret(
        &self,
        target: &Target,
        secret: &rightkit_crypto::Secret,
        claimed_origin: &str,
        clear: bool,
    ) -> Result<()> {
        let claimed = origin_of(claimed_origin).ok_or_else(|| {
            BrowserError::Invalid("the claimed origin is not an http or https address".into())
        })?;
        let actual = origin_of(&self.url().await)
            .ok_or_else(|| BrowserError::Denied("the page has no http or https origin".into()))?;
        if claimed != actual {
            return Err(BrowserError::Denied(
                "the page origin is not the claimed origin".into(),
            ));
        }
        let text = std::str::from_utf8(secret.expose())
            .map_err(|_| BrowserError::Invalid("the secret is not text".into()))?;
        self.admit(
            ActionKind::Fill,
            None,
            Some(describe(target)),
            Some(format!(
                "chars={} clear={clear} secret",
                text.chars().count()
            )),
        )
        .await?;
        let _l = self.lane.lock().await;
        let selector = self
            .resolve(target)
            .await?
            .ok_or_else(|| BrowserError::Invalid("fill_secret needs an element".into()))?;
        let is_credential = self
            .eval_internal(&CREDENTIAL_FIELD_JS.replace("__SELECTOR__", &js(&selector)))
            .await?;
        if is_credential.as_bool() != Some(true) {
            return Err(BrowserError::Denied(
                "the field is not a password or card field".into(),
            ));
        }
        self.fill_locked(target, text, clear).await
    }
}