vs-engine-webkit 0.2.16

Browser engine bindings for vibesurfer.
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
//! Backend-shared helpers — no platform deps.
//!
//! All three real backends (`webkit`, `wpe`, `webview2`) inject the
//! same DOM-walker JS and parse the same JSON shape into a
//! [`Tree`]. This module holds the parser so each backend doesn't
//! carry its own copy.
//!
//! The module is unconditionally compiled (no `cfg`) so the helpers
//! are available regardless of target.

use std::collections::{BTreeMap, BTreeSet};

use vs_protocol::{Node, Op, Ref, Role, Tree};

use super::native_download::{SharedDownloads, NATIVE_ID_BASE};

pub(crate) fn parse_role(s: &str) -> Role {
    match s {
        "doc" => Role::Doc,
        "btn" => Role::Btn,
        "lnk" => Role::Lnk,
        "tf" => Role::Tf,
        "ta" => Role::Ta,
        "sel" => Role::Sel,
        "chk" => Role::Chk,
        "rad" => Role::Rad,
        "img" => Role::Img,
        "hd" => Role::Hd,
        "p" => Role::P,
        "li" => Role::Li,
        "lst" => Role::Lst,
        "tbl" => Role::Tbl,
        "row" => Role::Row,
        "cell" => Role::Cell,
        "hdr" => Role::Hdr,
        "nav" => Role::Nav,
        "frm" => Role::Frm,
        "dlg" => Role::Dlg,
        "itm" => Role::Itm,
        "sec" => Role::Sec,
        "art" => Role::Art,
        "mn" => Role::Mn,
        "ifr" => Role::Ifr,
        _ => Role::El,
    }
}

pub(crate) fn ops_for_role(role: Role) -> BTreeSet<Op> {
    let mut s = BTreeSet::new();
    match role {
        Role::Btn | Role::Lnk | Role::Chk | Role::Rad => {
            s.insert(Op::Click);
            s.insert(Op::Focus);
        }
        Role::Tf | Role::Ta => {
            s.insert(Op::Fill);
            s.insert(Op::Focus);
        }
        Role::Sel => {
            s.insert(Op::Focus);
        }
        Role::Frm => {
            s.insert(Op::Submit);
        }
        _ => {}
    }
    s
}

/// Parse the JSON output of [`SNAPSHOT_JS`](super) into a [`Tree`].
/// `json` is whatever the backend's JS-eval returned — either a raw
/// JSON object or a doubly-encoded JSON string. We unwrap one level
/// of string quoting if present.
pub(crate) fn parse_snapshot(json: &str) -> Result<Tree, String> {
    let unwrapped: String =
        serde_json::from_str::<String>(json).unwrap_or_else(|_| json.to_string());
    let v: serde_json::Value =
        serde_json::from_str(&unwrapped).map_err(|e| format!("invalid snapshot json: {e}"))?;
    let root = build_node(&v).ok_or_else(|| "missing root".to_string())?;
    Ok(Tree { roots: vec![root] })
}

fn build_node(v: &serde_json::Value) -> Option<Node> {
    // A ref beyond u32 means the page emitted a snapshot we can't
    // represent — drop the node rather than silently aliasing Ref(0).
    let r = u32::try_from(v.get("r")?.as_u64()?).ok()?;
    let role_s = v.get("role")?.as_str()?;
    let label = v.get("label").and_then(|x| x.as_str()).unwrap_or("");
    let role = parse_role(role_s);
    let mut children = Vec::new();
    if let Some(arr) = v.get("children").and_then(|x| x.as_array()) {
        for c in arr {
            if let Some(n) = build_node(c) {
                children.push(n);
            }
        }
    }
    let mut attrs = BTreeMap::new();
    if v.get("hid").and_then(serde_json::Value::as_u64) == Some(1) {
        attrs.insert("hid".to_string(), "1".to_string());
    }
    // `level=N` on a heading (h1-h6 or aria-level).
    if let Some(l) = v.get("lvl").and_then(serde_json::Value::as_u64) {
        attrs.insert("level".to_string(), l.to_string());
    }
    // `lbl=<text>` on a form field with a <label> or aria-labelledby.
    // The node's label stays the field's value.
    if let Some(l) = v.get("flbl").and_then(serde_json::Value::as_str) {
        attrs.insert("lbl".to_string(), l.to_string());
    }
    // `checked=1` on a checked checkbox or radio; absent when unchecked.
    if v.get("chk").and_then(serde_json::Value::as_u64) == Some(1) {
        attrs.insert("checked".to_string(), "1".to_string());
    }
    // `challenge=<provider>:<state>` on a bot-check widget. `pending`
    // means unsolved, and is usually one trusted click away from
    // solved — see `challenge_box` below. Providers draw into a closed
    // shadow root, so the widget itself never appears in the tree.
    if let Some(chal) = v.get("chal").and_then(serde_json::Value::as_str) {
        attrs.insert("challenge".to_string(), chal.to_string());
    }
    // `challenge_box=x,y,w,h` — the widget's viewport rect, so an agent
    // can drive `vs click-at` straight at it.
    if let Some(b) = v.get("chalbox").and_then(serde_json::Value::as_str) {
        attrs.insert("challenge_box".to_string(), b.to_string());
    }
    Some(Node {
        r: Ref(r),
        role,
        label: label.to_string(),
        ops: ops_for_role(role),
        attrs,
        children,
    })
}

/// JS that snapshots cookies + localStorage + sessionStorage as a JSON
/// blob. Used by `save_auth` on every backend.
#[allow(dead_code)] // used by wpe + webview2; WkBackend moved to host-side cookie store
pub(crate) const AUTH_SAVE_JS: &str = include_str!("auth_save.js");

/// JS that restores the JSON blob produced by [`AUTH_SAVE_JS`]. The
/// caller wraps this in an IIFE that defines `blob` from
/// `JSON.parse(<payload>)`.
#[allow(dead_code)]
pub(crate) const AUTH_LOAD_BODY_JS: &str = include_str!("auth_load_body.js");

/// JS that snapshots only localStorage + sessionStorage. The cookie
/// portion is handled by the host-side cookie store API (which sees
/// HttpOnly cookies; `document.cookie` does not).
pub(crate) const STORAGE_SAVE_JS: &str = include_str!("storage_save.js");

/// JS that restores localStorage + sessionStorage from `payload`.
pub(crate) const STORAGE_LOAD_BODY_JS: &str = include_str!("storage_load_body.js");

/// Kickoff-and-poll dump of every IndexedDB database on the origin.
pub(crate) const IDB_SAVE_JS: &str = include_str!("idb_save.js");

/// Kickoff-and-poll restore of the databases `IDB_SAVE_JS` captured.
pub(crate) const IDB_LOAD_BODY_JS: &str = include_str!("idb_load.js");

/// Shared DOM-walker JS payload. All three real backends evaluate this
/// and parse the result with [`parse_snapshot`].
pub(crate) const SNAPSHOT_DOM_WALKER_JS: &str = include_str!("snapshot_dom_walker.js");

/// Download-capture shim. Injected at document-start into every frame
/// on every backend, and re-evaluated on demand by [`run_download`] for
/// documents that predate the injection. See the file header for why
/// interception happens above the engine's download machinery.
pub(crate) const DOWNLOAD_SHIM_JS: &str = include_str!("download_shim.js");

/// How long `open` and `goto` wait for a navigation to finish once it
/// has started.
///
/// 15 seconds is the right answer for a person waiting on a page, and
/// stays the default. It is not the web-process launch allowance: on
/// macOS that is a separate 45s wait that ends at
/// `didStartProvisionalNavigation`, because a cold `WKWebView` can
/// spend longer than 15s just spawning its process. Charging the
/// spawn against this budget produced `! TIMEOUT 15000ms open` for a
/// navigation that had not begun. `VS_NAV_BUDGET_MS` lets a caller buy
/// more patience for the load itself without making a truly hung page
/// take longer to report for everyone else. The integration harness
/// sets it to 45s.
///
/// macOS and Linux only, because those are the backends that bound a
/// navigation at all. Windows waits on `NavigationCompleted` through
/// `wait_with_pump` with no deadline, so a hung navigation hangs the
/// call there — a real gap, but an older and separate one than this.
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub(crate) fn nav_budget() -> std::time::Duration {
    const DEFAULT_MS: u64 = 15_000;
    let ms = std::env::var("VS_NAV_BUDGET_MS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .filter(|ms| *ms > 0)
        .unwrap_or(DEFAULT_MS);
    std::time::Duration::from_millis(ms)
}

/// How long a click waits for the page's new-window request.
///
/// The engine raises that request (WKUIDelegate `createWebView`,
/// WebKitGTK `create`, WebView2 `NewWindowRequested`) over IPC from the
/// content process, and it can land after the click has returned. The
/// wait only happens when the page's hint (`NEW_WINDOW_HINT_JS`) says a
/// request is coming, and ends as soon as it arrives. Every click used
/// to pay this in full, which cost ~250ms per click.
pub(crate) const NEW_WINDOW_SETTLE: std::time::Duration = std::time::Duration::from_secs(1);

/// Read and clear the page's new-window hint (`__vsNw`, set by the
/// document-start shim when a blank-target link or form or
/// `window.open` fires). The reply carries `vsnw:1` when a new-window
/// request is on its way.
pub(crate) const NEW_WINDOW_HINT_JS: &str =
    "(function(){var v=window.__vsNw;try{window.__vsNw=0;}catch(e){}return v?'vsnw:1':'vsnw:0';})()";

/// Whether to wait for a new-window request after a click, given the
/// hint eval's result. A failed eval waits, as before the hint existed.
pub(crate) fn new_window_hinted(result: &Result<String, impl std::fmt::Debug>) -> bool {
    match result {
        Ok(s) => s.contains("vsnw:1"),
        Err(_) => true,
    }
}

/// Whether `action` can open a new window: a click, a submit, or Enter.
pub(crate) fn may_open_window(action: &crate::engine::Action) -> bool {
    use crate::engine::Action;
    match action {
        Action::Click | Action::Submit => true,
        Action::Key { chord } => chord.eq_ignore_ascii_case("enter"),
        _ => false,
    }
}

// =============================================================================
// Shared primitive logic — dispatched through each backend's eval_js
// =============================================================================
//
// All three real backends (`webkit`, `wpe`, `webview2`) implement a
// per-platform `eval_js(&WebView, js, budget) -> EngineResult<String>`
// helper. The generic functions below take an `eval` closure with that
// signature and implement `act`, `wait`, `layout`, `save_auth`, and
// `load_auth` on top — so the per-backend `Engine` impls shrink to a
// page-lookup + a single call.
//
// `eval` is taken as `Fn` so callers can borrow per-page state across
// multiple invocations (used by `wait`, which polls a JS predicate
// every ~150ms until satisfied or the budget runs out).

use std::time::Duration;

use crate::engine::{
    ActTarget, Action, AuthBlob, Download, DownloadEntry, DownloadSource, EngineError,
    EngineResult, LayoutBox, WaitCondition,
};

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

/// Full mouse-click event sequence for `Action::Click`, dispatched on
/// the resolved element `el`. Coordinates are the element's center so
/// pointer-position-aware handlers behave. The `button`/`buttons`
/// fields follow real semantics (held during down, released by up).
/// Bind the DOM constructors an action script uses to the element's own
/// window. An element inside a same-origin frame belongs to that
/// frame's realm, where `el instanceof HTMLInputElement` against the
/// top window's constructor is false and events built from the top
/// window's constructors carry the wrong `view`.
const REALM: &str = "const W = (el.ownerDocument && el.ownerDocument.defaultView) || window; \
var HTMLInputElement = W.HTMLInputElement, HTMLTextAreaElement = W.HTMLTextAreaElement, \
HTMLSelectElement = W.HTMLSelectElement, Event = W.Event, KeyboardEvent = W.KeyboardEvent, \
MouseEvent = W.MouseEvent, PointerEvent = W.PointerEvent;";

const CLICK_SEQUENCE_JS: &str = "\
const rc = el.getBoundingClientRect(); \
const x = rc.left + rc.width / 2, y = rc.top + rc.height / 2; \
const mk = (b) => ({ bubbles: true, cancelable: true, composed: true, view: W, clientX: x, clientY: y, screenX: x, screenY: y, button: 0, buttons: b }); \
const mkp = (b) => Object.assign(mk(b), { pointerId: 1, pointerType: 'mouse', isPrimary: true, width: 1, height: 1 }); \
try { \
  el.dispatchEvent(new PointerEvent('pointerover', mkp(0))); \
  el.dispatchEvent(new MouseEvent('mouseover', mk(0))); \
  el.dispatchEvent(new PointerEvent('pointermove', mkp(0))); \
  el.dispatchEvent(new PointerEvent('pointerdown', mkp(1))); \
  el.dispatchEvent(new MouseEvent('mousedown', mk(1))); \
  if (typeof el.focus === 'function') { try { el.focus(); } catch (e) {} } \
  el.dispatchEvent(new PointerEvent('pointerup', mkp(0))); \
  el.dispatchEvent(new MouseEvent('mouseup', mk(0))); \
  el.dispatchEvent(new MouseEvent('click', mk(0))); \
} catch (e) { el.click(); } \
return 'ok';";

/// Build the `act` JS for a single ref. Returns the literal `"ok"` on
/// success, `"err:not_found"` if the selector misses, or panics on
/// parser misuse (we trust the inputs).
fn build_act_js(r: Ref, action: &Action) -> String {
    let body = match action {
        // Emit a full, realistic mouse-click event sequence rather than
        // a bare `el.click()` (which fires *only* a synthetic `click`).
        // Libraries that gate behavior on pointer events — Radix UI's
        // Select/dismissable-layer most visibly — select on `pointerup`
        // and dismiss on `pointerdown`; with click-only, the value
        // updated but the popover never closed and its focus-trap
        // overlay then swallowed every later click, wedging the page.
        // This mirrors what a real cursor (and the macOS native path)
        // delivers. Falls back to `el.click()` if `PointerEvent` can't
        // be constructed. NB: macOS routes `Ref+click` through native
        // NSEvents and never reaches here; this is the Linux/Windows
        // (and any JS-dispatched) path.
        Action::Click => CLICK_SEQUENCE_JS.to_string(),
        Action::Fill { value } => format!(
            "el.focus(); \
             if (el instanceof HTMLSelectElement) {{ \
               var want = {v}; \
               var opt = Array.prototype.find.call(el.options, function(o){{ return o.value === want || o.text === want || o.label === want; }}) \
                      || Array.prototype.find.call(el.options, function(o){{ return (o.text || '').trim() === (want || '').trim(); }}); \
               if (!opt) return 'err:no_matching_option'; \
               var ss = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value').set; \
               ss.call(el, opt.value); \
               el.dispatchEvent(new Event('input', {{bubbles: true}})); \
               el.dispatchEvent(new Event('change', {{bubbles: true}})); \
               return 'ok'; \
             }} \
             var p = (el instanceof HTMLTextAreaElement) ? HTMLTextAreaElement.prototype : (el instanceof HTMLInputElement ? HTMLInputElement.prototype : null); if (p) {{ Object.getOwnPropertyDescriptor(p, 'value').set.call(el, {v}); }} else {{ el.value = {v}; }} el.dispatchEvent(new Event('input', {{bubbles: true}})); el.dispatchEvent(new Event('change', {{bubbles: true}})); return 'ok';",
            v = json_string(value)
        ),
        Action::Scroll => {
            "el.scrollIntoView({behavior: 'instant', block: 'center'}); return 'ok';".into()
        }
        Action::Key { chord } => format!(
            "el.focus(); el.dispatchEvent(new KeyboardEvent('keydown', {{key: {c}, bubbles: true}})); el.dispatchEvent(new KeyboardEvent('keyup', {{key: {c}, bubbles: true}})); return 'ok';",
            c = json_string(chord)
        ),
        Action::Submit => "if (el.form) { el.form.submit(); } else if (typeof el.click === 'function') { el.click(); } return 'ok';".into(),
        Action::Hover => "el.dispatchEvent(new MouseEvent('mouseenter', {bubbles: true})); el.dispatchEvent(new MouseEvent('mouseover', {bubbles: true})); return 'ok';".into(),
        Action::Focus => "el.focus(); return 'ok';".into(),
    };
    format!(
        "(function() {{ const el = (window.__vsFindRef ? window.__vsFindRef({r}) : null) || document.querySelector('[data-vs-ref=\"{r}\"]'); if (!el) return 'err:not_found'; {REALM} {body} }})()",
        r = r.0
    )
}

/// Build the JS that fires the HTML5 drag-and-drop event chain for
/// `vs drag`. Browsers' HTML5 dnd pipeline (dragstart → dragenter →
/// dragover → drop → dragend on a `DataTransfer`) needs a real drag
/// session. Synthetic OS-level mouse events can trip WebKit's
/// start-drag heuristic (macOS 27 does), but the headless web view
/// refuses the system drag session (see `webkit/headless_webview.rs`),
/// so no drop ever arrives natively. To cover the
/// `react-dnd` HTML5 backend, native `draggable="true"` widgets, and
/// React-Flow nodes wired to HTML5 dnd, every backend's `CursorOp::Drag`
/// runs the OS-level mouse path (for canvas / mouse-tracking widgets)
/// AND evaluates this JS afterwards. The JS dispatches untrusted but
/// otherwise well-formed `DragEvent`s with a `DataTransfer` attached;
/// library code (react-dnd, react-flow, native handlers) responds to
/// them the same as a real drag because none of them gate on
/// `isTrusted`. A page with no drag handlers absorbs the events as
/// no-ops.
pub(crate) fn build_html5_drag_js(x1: f64, y1: f64, x2: f64, y2: f64) -> String {
    format!(
        r"(function() {{
            var x1 = {x1}, y1 = {y1}, x2 = {x2}, y2 = {y2};
            var src = document.elementFromPoint(x1, y1);
            var dst = document.elementFromPoint(x2, y2);
            if (!src) return 'err:no_source';
            if (!dst) return 'err:no_target';
            var dt;
            try {{ dt = new DataTransfer(); }} catch (e) {{ return 'err:no_datatransfer'; }}
            function fire(target, type, cx, cy) {{
                var ev;
                try {{
                    ev = new DragEvent(type, {{
                        bubbles: true, cancelable: true, composed: true,
                        dataTransfer: dt, clientX: cx, clientY: cy, view: window,
                    }});
                }} catch (_) {{
                    // Fallback for engines where DragEvent's `dataTransfer`
                    // option is unsupported: build a MouseEvent and pin
                    // `dataTransfer` afterwards. Most modern WebKit /
                    // WebView2 builds support the constructor option, so
                    // this branch rarely runs.
                    ev = new MouseEvent(type, {{
                        bubbles: true, cancelable: true, composed: true,
                        clientX: cx, clientY: cy, view: window,
                    }});
                    try {{ Object.defineProperty(ev, 'dataTransfer', {{ value: dt }}); }} catch (_) {{}}
                }}
                target.dispatchEvent(ev);
                return ev;
            }}
            var startEv = fire(src, 'dragstart', x1, y1);
            // If the dragstart handler preventDefault'd, the page is
            // refusing to start a drag — report success but skip the
            // rest of the chain so we don't fabricate a drop the page
            // explicitly opted out of.
            if (startEv.defaultPrevented) return 'ok:cancelled';
            fire(dst, 'dragenter', x2, y2);
            fire(dst, 'dragover', x2, y2);
            // HTML5 spec: `drop` only fires if a handler preventDefault'd
            // the preceding `dragover`. We dispatch it unconditionally —
            // most react-dnd / react-flow targets call preventDefault on
            // dragover; for the rest the drop is a no-op event.
            fire(dst, 'drop', x2, y2);
            fire(src, 'dragend', x2, y2);
            return 'ok';
        }})()"
    )
}

pub(crate) fn run_act<F>(eval: F, target: &ActTarget, action: &Action) -> EngineResult<()>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    let ActTarget::Ref(r) = target;
    let js = build_act_js(*r, action);
    let result = eval(&js, Duration::from_secs(5))?;
    let unwrapped = serde_json::from_str::<String>(&result).unwrap_or(result);
    if unwrapped == "ok" {
        Ok(())
    } else if let Some(rest) = unwrapped.strip_prefix("err:") {
        Err(EngineError::NotFound {
            kind: "ref",
            id: rest.to_string(),
        })
    } else {
        Err(EngineError::Other(format!(
            "unexpected act result: {unwrapped}"
        )))
    }
}

/// Build the JS predicate for a wait condition. Always returns a
/// well-formed expression — every condition has a real implementation
/// after M6.
fn build_wait_predicate(cond: &WaitCondition) -> String {
    match cond {
        WaitCondition::Stable => {
            "(function() { return document.readyState === 'complete' ? '1' : '0'; })()".into()
        }
        WaitCondition::Text(t) => format!(
            "(function() {{ return document.body && document.body.innerText && document.body.innerText.indexOf({q}) >= 0 ? '1' : '0'; }})()",
            q = json_string(t)
        ),
        WaitCondition::RefAppears(r) => format!(
            "(function() {{ const el = (window.__vsFindRef ? window.__vsFindRef({r}) : null) || document.querySelector('[data-vs-ref=\"{r}\"]'); return el ? '1' : '0'; }})()",
            r = r.0
        ),
        WaitCondition::RefGone(r) => format!(
            "(function() {{ const el = (window.__vsFindRef ? window.__vsFindRef({r}) : null) || document.querySelector('[data-vs-ref=\"{r}\"]'); return el ? '0' : '1'; }})()",
            r = r.0
        ),
        WaitCondition::NetIdle => {
            // Net-idle = no resource activity in the last 500ms. The
            // self-installing watcher tracks both PerformanceObserver
            // resource ticks and a fetch wrap. First call is the
            // installer; that initializes lastActivity to "now" so the
            // first poll always returns "0" — the predicate must wait
            // for a real quiet window before reporting idle.
            r"(function() {
              if (!window.__vsNetWatch) {
                window.__vsNetWatch = { lastActivity: performance.now() };
                if (window.PerformanceObserver) {
                  try {
                    var obs = new PerformanceObserver(function(list) {
                      window.__vsNetWatch.lastActivity = performance.now();
                    });
                    obs.observe({ type: 'resource', buffered: true });
                  } catch (e) {}
                }
                var origFetch = window.fetch;
                if (origFetch) {
                  window.fetch = function() {
                    window.__vsNetWatch.lastActivity = performance.now();
                    return origFetch.apply(this, arguments);
                  };
                }
                var XHR = window.XMLHttpRequest;
                if (XHR && XHR.prototype) {
                  var origSend = XHR.prototype.send;
                  XHR.prototype.send = function() {
                    window.__vsNetWatch.lastActivity = performance.now();
                    return origSend.apply(this, arguments);
                  };
                }
              }
              return (performance.now() - window.__vsNetWatch.lastActivity) > 500 ? '1' : '0';
            })()"
                .into()
        }
        WaitCondition::TokenChange => {
            // A new state-token is produced when the DOM observably
            // changes. Approximate via a MutationObserver installed on
            // first call; report '1' once any subtree mutation has
            // fired since installation.
            r"(function() {
              if (!window.__vsTokWatch) {
                window.__vsTokWatch = { changed: false };
                try {
                  var obs = new MutationObserver(function() {
                    window.__vsTokWatch.changed = true;
                  });
                  obs.observe(document.documentElement, {
                    subtree: true,
                    childList: true,
                    attributes: true,
                    characterData: true,
                  });
                } catch (e) {}
              }
              return window.__vsTokWatch.changed ? '1' : '0';
            })()"
                .into()
        }
    }
}

/// Ceiling for a single wait-predicate eval. Generous on purpose: it
/// bounds a wedged eval without turning a merely-slow one into a
/// failed wait. The pacing between polls comes from `tick`, and the
/// wait's own `budget` is what actually ends the loop.
const POLL_EVAL_BUDGET: Duration = Duration::from_secs(5);

/// Run a `wait` primitive: poll a JS predicate until it returns `"1"`
/// or `budget` elapses. The `tick` closure is called between polls so
/// the caller can pump its platform run loop.
pub(crate) fn run_wait<F, T>(
    eval: F,
    cond: &WaitCondition,
    budget: Duration,
    mut tick: T,
) -> EngineResult<()>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
    T: FnMut(),
{
    let predicate = build_wait_predicate(cond);
    let deadline = std::time::Instant::now() + budget;
    loop {
        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
        if remaining.is_zero() {
            return Err(EngineError::Timeout {
                budget,
                primitive: "wait",
                detail: "",
            });
        }
        // Budget for *this* poll's eval, distinct from how often we
        // poll. These used to be the same 150ms value, which made a
        // single slow eval fatal: `eval` returned
        // `Timeout { primitive: "eval" }`, `?` propagated it, and the
        // caller saw `! TIMEOUT 150ms eval` — a failed wait on a page
        // that was merely busy. On a loaded CI runner that was the
        // whole of `cell_wait_gone`'s flakiness.
        let one = POLL_EVAL_BUDGET.min(remaining);
        match eval(&predicate, one) {
            Ok(result) => {
                let unwrapped = serde_json::from_str::<String>(&result).unwrap_or(result);
                if unwrapped == "1" {
                    return Ok(());
                }
            }
            // A poll that timed out is "not satisfied yet", not a
            // failure. Keep polling; the wait's own deadline above is
            // what bounds this loop.
            Err(EngineError::Timeout { .. }) => {}
            Err(e) => return Err(e),
        }
        tick();
    }
}

/// Run a `layout` primitive: query `getBoundingClientRect` for each
/// ref, parse the JSON result.
pub(crate) fn run_layout<F>(eval: F, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    let refs_json = serde_json::to_string(&refs.iter().map(|r| r.0).collect::<Vec<_>>())
        .unwrap_or_else(|_| "[]".into());
    let js = format!(
        r#"(function() {{
            const refs = {refs_json};
            const out = refs.map(r => {{
                const el = (window.__vsFindRef ? window.__vsFindRef(r) : null) || document.querySelector(`[data-vs-ref="${{r}}"]`);
                if (!el) return {{r, found: false}};
                const rect = window.__vsTopRect ? window.__vsTopRect(el) : el.getBoundingClientRect();
                const cs = (el.ownerDocument.defaultView || window).getComputedStyle(el);
                const z = parseInt(cs.zIndex, 10);
                return {{
                    r, found: true,
                    x: rect.x, y: rect.y, w: rect.width, h: rect.height,
                    visible: rect.width > 0 && rect.height > 0 && cs.visibility !== 'hidden' && cs.display !== 'none',
                    z: Number.isFinite(z) ? z : 0,
                }};
            }});
            return JSON.stringify(out);
        }})()"#
    );
    let json = eval(&js, Duration::from_secs(5))?;
    let unwrapped = serde_json::from_str::<String>(&json).unwrap_or(json);
    let v: serde_json::Value =
        serde_json::from_str(&unwrapped).map_err(|e| EngineError::Other(e.to_string()))?;
    let arr = v
        .as_array()
        .ok_or_else(|| EngineError::Other("expected array".into()))?;
    let mut out = Vec::with_capacity(arr.len());
    for entry in arr {
        let r_v = entry
            .get("r")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(0);
        let r = Ref(u32::try_from(r_v).unwrap_or(0));
        let found = entry
            .get("found")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false);
        if !found {
            continue;
        }
        out.push(LayoutBox {
            r,
            x: entry
                .get("x")
                .and_then(serde_json::Value::as_f64)
                .unwrap_or(0.0),
            y: entry
                .get("y")
                .and_then(serde_json::Value::as_f64)
                .unwrap_or(0.0),
            width: entry
                .get("w")
                .and_then(serde_json::Value::as_f64)
                .unwrap_or(0.0),
            height: entry
                .get("h")
                .and_then(serde_json::Value::as_f64)
                .unwrap_or(0.0),
            visible: entry
                .get("visible")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(false),
            z_index: entry
                .get("z")
                .and_then(serde_json::Value::as_i64)
                .and_then(|n| i32::try_from(n).ok())
                .unwrap_or(0),
        });
    }
    Ok(out)
}

/// Raw bytes pulled per `__vsDl.read` call. 768 KiB in → 1 MiB of
/// base64 out, which keeps every eval round-trip (and the NSString /
/// GVariant / PCWSTR conversion behind it) bounded no matter how large
/// the file is.
const DOWNLOAD_CHUNK: usize = 768 * 1024;

/// Largest download the engine will materialize. Mirrors `MAX_BYTES`
/// in `download_shim.js`; kept in both places because the shim refuses
/// the capture and this refuses the read-back.
const MAX_DOWNLOAD_BYTES: usize = 64 * 1024 * 1024;

/// Strip the one layer of JSON-string quoting some eval bridges wrap
/// around a returned string.
fn eval_str(raw: String) -> String {
    serde_json::from_str::<String>(&raw).unwrap_or(raw)
}

/// Install [`DOWNLOAD_SHIM_JS`] if this document doesn't already have
/// it. Pages opened before the shim was registered as a document-start
/// script — and any backend where that registration silently failed —
/// still get a working `vs_download` this way.
fn ensure_download_shim<F>(eval: &F) -> EngineResult<()>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    let probe = |e: &F| -> EngineResult<String> {
        Ok(eval_str(e(
            "(typeof window.__vsDl)",
            Duration::from_secs(5),
        )?))
    };
    if probe(eval)? == "object" {
        return Ok(());
    }
    eval(DOWNLOAD_SHIM_JS, Duration::from_secs(5))?;
    if probe(eval)? == "object" {
        Ok(())
    } else {
        Err(EngineError::Other(
            "download shim failed to install on this page".into(),
        ))
    }
}

fn parse_download_entry(v: &serde_json::Value) -> DownloadEntry {
    let s = |k: &str| {
        v.get(k)
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string()
    };
    DownloadEntry {
        id: v.get("id").and_then(serde_json::Value::as_u64).unwrap_or(0),
        filename: s("name"),
        mime: s("mime"),
        url: s("url"),
        size: v
            .get("size")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(0),
        error: v
            .get("err")
            .and_then(serde_json::Value::as_str)
            .map(ToString::to_string),
        done: v
            .get("done")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false),
    }
}

/// Run `download`: resolve the source to a buffered entry, wait for it
/// to complete, then pull its payload out of the page in chunks.
///
/// The bytes never touch the wire — the daemon writes them to disk and
/// reports only the path. `tick` pumps the platform run loop between
/// polls, exactly as in [`run_wait`].
pub(crate) fn run_download<F, T>(
    eval: F,
    mut tick: T,
    source: &DownloadSource,
    budget: Duration,
    native: &SharedDownloads,
) -> EngineResult<Download>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
    T: FnMut(),
{
    use base64::Engine as _;

    ensure_download_shim(&eval)?;
    let deadline = std::time::Instant::now() + budget;
    let timeout = || EngineError::Timeout {
        budget,
        primitive: "download",
        detail: "",
    };

    let id = match source {
        DownloadSource::Url(url) => {
            let js = format!("window.__vsDl.fetch({}, null)", json_string(url));
            let raw = eval_str(eval(&js, Duration::from_secs(10))?);
            raw.trim().parse::<u64>().map_err(|_| {
                EngineError::Other(format!("download: shim returned no id ({raw:?})"))
            })?
        }
        DownloadSource::Captured { id: Some(id) } if *id >= NATIVE_ID_BASE => {
            return wait_native(native, *id, deadline, timeout, &mut tick);
        }
        DownloadSource::Captured { id: Some(id) } => *id,
        // Newest of either buffer. A server-sent attachment lands in
        // the native buffer, a page-script save in the shim's; an
        // `<a download>` to an http URL can land in both, and then the
        // shim's copy wins so the agent gets one file, not two.
        DownloadSource::Captured { id: None } => {
            match newest_either(&eval, native, deadline, timeout, &mut tick)? {
                Newest::Shim(id) => id,
                Newest::Native(id) => return wait_native(native, id, deadline, timeout, &mut tick),
            }
        }
    };

    let meta = loop {
        let raw = eval_str(eval(
            &format!("window.__vsDl.meta({id})"),
            Duration::from_secs(5),
        )?);
        if raw != "null" && !raw.is_empty() {
            let v: serde_json::Value = serde_json::from_str(&raw)
                .map_err(|e| EngineError::Other(format!("download: bad meta {raw:?}: {e}")))?;
            let entry = parse_download_entry(&v);
            if entry.done {
                break entry;
            }
        }
        if std::time::Instant::now() >= deadline {
            return Err(EngineError::Timeout {
                budget,
                primitive: "download",
                detail: "",
            });
        }
        tick();
    };

    if let Some(err) = meta.error {
        return Err(EngineError::Other(format!("download failed: {err}")));
    }

    // The shim caps a capture at MAX_DOWNLOAD_BYTES, but `size` is
    // read back out of the page and a page can overwrite `__vsDl`
    // wholesale. Re-check before reserving, so a bogus length is an
    // error rather than a multi-gigabyte allocation.
    let size = usize::try_from(meta.size).unwrap_or(usize::MAX);
    if size > MAX_DOWNLOAD_BYTES {
        return Err(EngineError::Other(format!(
            "download too large: {size} bytes (cap {MAX_DOWNLOAD_BYTES})"
        )));
    }
    let mut bytes: Vec<u8> = Vec::with_capacity(size);
    while bytes.len() < size {
        let off = bytes.len();
        let len = DOWNLOAD_CHUNK.min(size - off);
        let js = format!("window.__vsDl.read({}, {off}, {len})", meta.id);
        let b64 = eval_str(eval(&js, Duration::from_secs(30))?);
        if b64.is_empty() {
            break;
        }
        let chunk = base64::engine::general_purpose::STANDARD
            .decode(b64.as_bytes())
            .map_err(|e| EngineError::Other(format!("download: bad base64 chunk: {e}")))?;
        if chunk.is_empty() {
            break;
        }
        bytes.extend_from_slice(&chunk);
    }
    // Release the page-side copy; the buffer is small and holding a
    // second copy of a large file in the web content process is waste.
    let _ = eval(
        &format!("window.__vsDl.drop({})", meta.id),
        Duration::from_secs(5),
    );

    if bytes.len() != size {
        return Err(EngineError::Other(format!(
            "download truncated: read {} of {size} bytes",
            bytes.len()
        )));
    }
    Ok(Download {
        bytes,
        filename: meta.filename,
        mime: meta.mime,
        url: meta.url,
    })
}

/// Run `download_list`: the captured download intents, payloads
/// excluded.
pub(crate) fn run_download_list<F>(
    eval: F,
    native: &SharedDownloads,
) -> EngineResult<Vec<DownloadEntry>>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    ensure_download_shim(&eval)?;
    let raw = eval_str(eval("window.__vsDl.index()", Duration::from_secs(5))?);
    let v: serde_json::Value = serde_json::from_str(&raw)
        .map_err(|e| EngineError::Other(format!("download list: bad json {raw:?}: {e}")))?;
    let mut out: Vec<DownloadEntry> = v
        .as_array()
        .map(|a| a.iter().map(parse_download_entry).collect())
        .unwrap_or_default();
    // An `<a download>` to an http URL can be caught by both; list it once.
    let nat = native.lock().map_err(poisoned)?.entries();
    for e in nat {
        if !out.iter().any(|j| j.url == e.url) {
            out.push(e);
        }
    }
    Ok(out)
}

fn poisoned<T>(_: std::sync::PoisonError<T>) -> EngineError {
    EngineError::Other("download buffer lock poisoned".into())
}

/// The shim's newest entry, done or not.
struct ShimNewest {
    id: u64,
    t0: u64,
    url: String,
}

fn shim_newest<F>(eval: &F) -> EngineResult<Option<ShimNewest>>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    let raw = eval_str(eval("window.__vsDl.meta(0)", Duration::from_secs(5))?);
    if raw == "null" || raw.is_empty() {
        return Ok(None);
    }
    let v: serde_json::Value = serde_json::from_str(&raw)
        .map_err(|e| EngineError::Other(format!("download: bad meta {raw:?}: {e}")))?;
    let num = |k: &str| v.get(k).and_then(serde_json::Value::as_u64).unwrap_or(0);
    Ok(Some(ShimNewest {
        id: num("id"),
        t0: num("t0").max(num("ts")),
        url: v
            .get("url")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string(),
    }))
}

enum Newest {
    Shim(u64),
    Native(u64),
}

/// Wait until either buffer has something to drain and say which.
fn newest_either<F, T>(
    eval: &F,
    native: &SharedDownloads,
    deadline: std::time::Instant,
    timeout: impl Fn() -> EngineError,
    tick: &mut T,
) -> EngineResult<Newest>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
    T: FnMut(),
{
    loop {
        let js = shim_newest(eval)?;
        let nat = native.lock().map_err(poisoned)?.newest_with_url();
        match (nat, js) {
            (Some(n), j)
                if j.as_ref()
                    .is_none_or(|j| n.started_ms >= j.t0 && n.url != j.url) =>
            {
                if n.done {
                    return Ok(Newest::Native(n.id));
                }
            }
            (_, Some(j)) => return Ok(Newest::Shim(j.id)),
            (_, None) => {}
        }
        if std::time::Instant::now() >= deadline {
            return Err(timeout());
        }
        tick();
    }
}

/// Wait for a native download to settle, then take it.
fn wait_native<T: FnMut()>(
    native: &SharedDownloads,
    id: u64,
    deadline: std::time::Instant,
    timeout: impl Fn() -> EngineError,
    tick: &mut T,
) -> EngineResult<Download> {
    loop {
        let done = native.lock().map_err(poisoned)?.is_done(id);
        match done {
            None => {
                return Err(EngineError::Other(format!(
                    "download: no captured download with id {id}"
                )))
            }
            Some(true) => {
                let taken = native.lock().map_err(poisoned)?.take(id);
                return match taken {
                    Some(Ok(d)) => Ok(d),
                    Some(Err(e)) => Err(EngineError::Other(format!("download failed: {e}"))),
                    None => Err(EngineError::Other(format!(
                        "download: no captured download with id {id}"
                    ))),
                };
            }
            Some(false) => {}
        }
        if std::time::Instant::now() >= deadline {
            return Err(timeout());
        }
        tick();
    }
}

/// Run `save_auth`: eval the snapshot JS, capture the JSON blob.
#[allow(dead_code)]
pub(crate) fn run_save_auth<F>(eval: F) -> EngineResult<AuthBlob>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    let json = eval(AUTH_SAVE_JS, Duration::from_secs(5))?;
    let payload = serde_json::from_str::<String>(&json).unwrap_or(json);
    Ok(AuthBlob {
        bytes: payload.into_bytes(),
    })
}

/// Run `load_auth`: rebuild the IIFE with the payload baked in, eval,
/// expect the literal `"ok"`.
#[allow(dead_code)]
pub(crate) fn run_load_auth<F>(eval: F, blob: &AuthBlob) -> EngineResult<()>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    let payload = std::str::from_utf8(&blob.bytes)
        .map_err(|e| EngineError::Other(format!("auth blob not utf8: {e}")))?;
    let payload_lit = serde_json::to_string(payload)
        .map_err(|e| EngineError::Other(format!("auth blob json-encode: {e}")))?;
    let body = AUTH_LOAD_BODY_JS;
    let js = format!("(function() {{ const blob = JSON.parse({payload_lit}); {body} }})()");
    let result = eval(&js, Duration::from_secs(5))?;
    let unwrapped = serde_json::from_str::<String>(&result).unwrap_or(result);
    if unwrapped == "ok" {
        Ok(())
    } else {
        Err(EngineError::Other(format!(
            "load_auth: unexpected: {unwrapped}"
        )))
    }
}

/// Run `eval_js`: wrap the user source in a try/catch that returns a
/// tagged JSON record, then map back to [`EvalResult`].
///
/// Two wrappers are tried in order:
/// 1. **expression mode** — `(function(){ return <expr>; })()`. The
///    common case; works under strict CSP (no `eval`) and returns the
///    value of a single expression.
/// 2. **program mode** — `(0, eval)(<source as string literal>)`,
///    reached only when expression mode fails to even parse (a
///    multiline statement block like `const a=1; f(); a`). Indirect
///    `eval` evaluates the source as a *program* and yields the
///    completion value of its last statement (REPL semantics), and any
///    SyntaxError/throw is caught inside the wrapper so the caller gets
///    a clean `Syntax`/`Thrown` result instead of an opaque engine
///    error. Passing the source as a JSON-encoded string literal keeps
///    its newlines from breaking the wrapper's own parse.
pub(crate) fn run_eval<F>(eval: F, expr: &str) -> EngineResult<crate::inspector::EvalResult>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    let expr_wrapper = format!(
        r"(function() {{
            try {{
                var __v = (function() {{ return {expr}; }})();
                return JSON.stringify({{
                    kind: 'ok',
                    type: typeof __v,
                    value: (typeof __v === 'string') ? __v : JSON.stringify(__v),
                }});
            }} catch (e) {{
                var msg = (e && e.message) || String(e);
                var name = (e && e.name) || 'Error';
                if (name === 'SyntaxError') {{
                    return JSON.stringify({{ kind: 'syntax', message: msg }});
                }}
                return JSON.stringify({{ kind: 'thrown', name: name, message: msg }});
            }}
        }})()"
    );
    // Expression mode. When `expr` is a statement block the wrapper
    // itself fails to compile, and engines signal that differently:
    // WebKit / WebKitGTK return an `Err`, while WebView2's
    // `ExecuteScript` returns the JSON string `"null"` (it reports an
    // uncompilable or throwing script as JSON null rather than an
    // error). Treat *both* — an `Err`, or an `Ok` whose payload doesn't
    // parse as our tagged record — as "expression mode didn't apply"
    // and fall through to program mode.
    if let Ok(json) = eval(&expr_wrapper, Duration::from_secs(5)) {
        if let Ok(result) = parse_eval_json(&json) {
            return Ok(result);
        }
    }

    // Program mode via indirect `eval`: evaluates the source as a
    // program (REPL completion-value semantics) and catches any
    // SyntaxError / throw inside the wrapper, so a statement block
    // resolves and malformed input comes back as a clean
    // Syntax/Thrown record instead of an opaque engine error.
    let src_literal = serde_json::to_string(expr).unwrap_or_else(|_| "\"\"".to_string());
    let program_wrapper = format!(
        r"(function() {{
            try {{
                var __v = (0, eval)({src_literal});
                return JSON.stringify({{
                    kind: 'ok',
                    type: typeof __v,
                    value: (typeof __v === 'string') ? __v : JSON.stringify(__v),
                }});
            }} catch (e) {{
                var msg = (e && e.message) || String(e);
                var name = (e && e.name) || 'Error';
                if (name === 'SyntaxError') {{
                    return JSON.stringify({{ kind: 'syntax', message: msg }});
                }}
                return JSON.stringify({{ kind: 'thrown', name: name, message: msg }});
            }}
        }})()"
    );
    let json = eval(&program_wrapper, Duration::from_secs(5))?;
    parse_eval_json(&json)
}

/// Decode the tagged JSON record emitted by the `run_eval` wrappers.
/// Returns `Err` if `json` isn't one of those records — e.g. the bare
/// `"null"` WebView2 hands back when a wrapper fails to compile — which
/// the caller uses as the signal to fall through to program mode.
fn parse_eval_json(json: &str) -> EngineResult<crate::inspector::EvalResult> {
    use crate::inspector::EvalResult;
    let unwrapped = serde_json::from_str::<String>(json).unwrap_or_else(|_| json.to_string());
    let v: serde_json::Value = serde_json::from_str(&unwrapped)
        .map_err(|e| EngineError::Other(format!("eval: invalid wrapper json: {e}")))?;
    let kind = v.get("kind").and_then(|x| x.as_str()).unwrap_or("");
    match kind {
        "ok" => {
            let js_type = v
                .get("type")
                .and_then(|x| x.as_str())
                .unwrap_or("undefined")
                .to_string();
            let value = v
                .get("value")
                .and_then(|x| x.as_str())
                .unwrap_or("undefined")
                .to_string();
            Ok(EvalResult::Ok { value, js_type })
        }
        "thrown" => {
            let kind = v
                .get("name")
                .and_then(|x| x.as_str())
                .unwrap_or("Error")
                .to_string();
            let message = v
                .get("message")
                .and_then(|x| x.as_str())
                .unwrap_or("")
                .to_string();
            Ok(EvalResult::Thrown { kind, message })
        }
        "syntax" => {
            let message = v
                .get("message")
                .and_then(|x| x.as_str())
                .unwrap_or("")
                .to_string();
            Ok(EvalResult::Syntax { message })
        }
        other => Err(EngineError::Other(format!("eval: unexpected kind {other}"))),
    }
}

/// Map a host-side [`auth::CookieData`] to an [`inspector::StorageEntry`].
/// Used by each backend's `storage(Cookies)` path so `vs inspect storage
/// cookies` surfaces HttpOnly entries that `document.cookie` is blind to.
pub(crate) fn cookie_to_storage_entry(
    c: &crate::backend::auth::CookieData,
) -> crate::inspector::StorageEntry {
    let lower = c.name.to_ascii_lowercase();
    let sensitive = ["session_id", "auth", "token", "secret", "password", "csrf"]
        .iter()
        .any(|needle| lower.contains(needle));
    let mut flags = Vec::new();
    if c.secure {
        flags.push("secure".to_string());
    }
    if c.http_only {
        flags.push("httponly".to_string());
    }
    if let Some(ss) = &c.same_site {
        flags.push(format!("samesite={}", ss.to_ascii_lowercase()));
    }
    if let Some(unix) = c.expires_unix {
        flags.push(format!("expires={unix}"));
    }
    crate::inspector::StorageEntry {
        key: c.name.clone(),
        value: c.value.clone(),
        flags,
        sensitive,
    }
}

/// Diff the current cookie snapshot against `previous` and produce
/// `CookieEvent`s for entries that were added or removed. Identity is
/// `(name, domain, path)` — the same triple WebKit / WebKitGTK /
/// WebView2 use to dedupe cookies in their stores. The `next_seq`
/// counter is incremented for each event so per-page sequences stay
/// monotonic across calls.
pub(crate) fn diff_cookies(
    previous: Option<&[crate::backend::auth::CookieData]>,
    current: &[crate::backend::auth::CookieData],
    next_seq: &mut u64,
) -> Vec<crate::inspector::CookieEvent> {
    use crate::inspector::{CookieAction, CookieEvent};
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(0));
    let mut out = Vec::new();
    let key =
        |c: &crate::backend::auth::CookieData| (c.name.clone(), c.domain.clone(), c.path.clone());
    let cur_keys: std::collections::HashSet<_> = current.iter().map(key).collect();
    let prev_keys: std::collections::HashSet<_> = previous
        .map(|p| p.iter().map(key).collect())
        .unwrap_or_default();
    let entry_flags = |c: &crate::backend::auth::CookieData| {
        let mut flags = Vec::new();
        if c.secure {
            flags.push("secure".to_string());
        }
        if c.http_only {
            flags.push("httponly".to_string());
        }
        if let Some(ss) = &c.same_site {
            flags.push(format!("samesite={}", ss.to_ascii_lowercase()));
        }
        if let Some(unix) = c.expires_unix {
            flags.push(format!("expires={unix}"));
        }
        flags
    };
    for c in current {
        if !prev_keys.contains(&key(c)) {
            *next_seq += 1;
            out.push(CookieEvent {
                seq: *next_seq,
                ts_ms: now_ms,
                action: CookieAction::Added,
                name: c.name.clone(),
                domain: c.domain.clone(),
                path: c.path.clone(),
                flags: entry_flags(c),
            });
        }
    }
    if let Some(prev) = previous {
        for c in prev {
            if !cur_keys.contains(&key(c)) {
                *next_seq += 1;
                out.push(CookieEvent {
                    seq: *next_seq,
                    ts_ms: now_ms,
                    action: CookieAction::Removed,
                    name: c.name.clone(),
                    domain: c.domain.clone(),
                    path: c.path.clone(),
                    flags: entry_flags(c),
                });
            }
        }
    }
    out
}

/// Run `storage`: enumerate cookies / localStorage / sessionStorage /
/// indexeddb databases for the page. The response is a `Vec<(key,
/// value, sensitive)>` where `sensitive` flags credential-shaped keys.
pub(crate) fn run_storage<F>(
    eval: F,
    scope: crate::inspector::StorageScope,
) -> EngineResult<Vec<crate::inspector::StorageEntry>>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    use crate::inspector::StorageScope;
    let scope_name = match scope {
        StorageScope::Cookies => "cookies",
        StorageScope::Local => "local",
        StorageScope::Session => "session",
        StorageScope::IndexedDb => "indexeddb",
    };
    let js = format!(
        r"(function() {{
            var scope = {scope_name:?};
            function isSensitive(k) {{
                var lower = String(k).toLowerCase();
                return lower.includes('session_id')
                    || lower.includes('auth')
                    || lower.includes('token')
                    || lower.includes('secret')
                    || lower.includes('password')
                    || lower.includes('csrf');
            }}
            var entries = [];
            if (scope === 'cookies') {{
                var s = document.cookie || '';
                var parts = s.split(';');
                for (var i = 0; i < parts.length; i++) {{
                    var p = parts[i].trim();
                    if (!p) continue;
                    var idx = p.indexOf('=');
                    var k = idx >= 0 ? p.slice(0, idx) : p;
                    var v = idx >= 0 ? p.slice(idx + 1) : '';
                    entries.push({{ key: k, value: v, sensitive: isSensitive(k) }});
                }}
            }} else if (scope === 'local') {{
                for (var i = 0; i < localStorage.length; i++) {{
                    var k = localStorage.key(i);
                    var v = localStorage.getItem(k) || '';
                    entries.push({{ key: k, value: v, sensitive: isSensitive(k) }});
                }}
            }} else if (scope === 'session') {{
                for (var i = 0; i < sessionStorage.length; i++) {{
                    var k = sessionStorage.key(i);
                    var v = sessionStorage.getItem(k) || '';
                    entries.push({{ key: k, value: v, sensitive: isSensitive(k) }});
                }}
            }} else if (scope === 'indexeddb') {{
                // indexedDB.databases() is async (returns a Promise)
                // and WKWebView's evaluateJavaScript can't await it.
                // Each call returns the last snapshot and re-arms a
                // refresh, so call → settle → call converges on fresh
                // data. (A one-shot watcher used to cache the first
                // resolution forever — an empty list if queried before
                // the page created its db.)
                if (!window.__vsIdbList) {{
                    window.__vsIdbList = [];
                }}
                if (indexedDB && indexedDB.databases) {{
                    try {{
                        indexedDB.databases().then(function(dbs) {{
                            window.__vsIdbList = dbs.map(function(d) {{
                                return {{ name: d.name || '', version: d.version || 0 }};
                            }});
                        }});
                    }} catch (e) {{}}
                }}
                for (var i = 0; i < window.__vsIdbList.length; i++) {{
                    var d = window.__vsIdbList[i];
                    entries.push({{
                        key: d.name,
                        value: String(d.version || ''),
                        sensitive: false,
                    }});
                }}
            }}
            return JSON.stringify(entries);
        }})()"
    );
    let json = eval(&js, Duration::from_secs(5))?;
    Ok(parse_storage_entries(&json))
}

/// Decode the JSON-encoded array produced by the storage probe.
/// Lenient — bad input drops to an empty list rather than erroring,
/// matching the wider "engine should never crash on bad page JS"
/// principle.
fn parse_storage_entries(json: &str) -> Vec<crate::inspector::StorageEntry> {
    let unwrapped = serde_json::from_str::<String>(json).unwrap_or_else(|_| json.to_string());
    let Ok(v) = serde_json::from_str::<serde_json::Value>(&unwrapped) else {
        return Vec::new();
    };
    let Some(arr) = v.as_array() else {
        return Vec::new();
    };
    let mut out = Vec::with_capacity(arr.len());
    for e in arr {
        let key = e
            .get("key")
            .and_then(|x| x.as_str())
            .unwrap_or("")
            .to_string();
        let value = e
            .get("value")
            .and_then(|x| x.as_str())
            .unwrap_or("")
            .to_string();
        let sensitive = e
            .get("sensitive")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false);
        out.push(crate::inspector::StorageEntry {
            key,
            value,
            flags: Vec::new(),
            sensitive,
        });
    }
    out
}

/// Run `scripts`: enumerate `<script>` elements with src + state.
pub(crate) fn run_scripts<F>(eval: F) -> EngineResult<Vec<crate::inspector::ScriptEntry>>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    use crate::inspector::{ScriptEntry, ScriptState};
    let js = r"(function() {
        var out = [];
        var els = document.scripts;
        for (var i = 0; i < els.length; i++) {
            var s = els[i];
            out.push({
                seq: i + 1,
                source: s.src ? s.src : ('inline:doc[' + i + ']'),
                size: (s.src ? 0 : (s.text ? s.text.length : 0)),
            });
        }
        return JSON.stringify(out);
    })()";
    let json = eval(js, Duration::from_secs(5))?;
    let unwrapped = serde_json::from_str::<String>(&json).unwrap_or(json);
    let v: serde_json::Value = match serde_json::from_str(&unwrapped) {
        Ok(v) => v,
        Err(_) => return Ok(Vec::new()),
    };
    let Some(arr) = v.as_array() else {
        return Ok(Vec::new());
    };
    let mut out = Vec::with_capacity(arr.len());
    for e in arr {
        let seq = e
            .get("seq")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(0);
        let source = e
            .get("source")
            .and_then(|x| x.as_str())
            .unwrap_or("")
            .to_string();
        let size = e
            .get("size")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(0);
        out.push(ScriptEntry {
            seq,
            source,
            size,
            state: ScriptState::Parsed,
        });
    }
    Ok(out)
}

/// Run `script_source`: return source text for one script seq (1-based).
pub(crate) fn run_script_source<F>(
    eval: F,
    seq: u64,
) -> EngineResult<Option<crate::inspector::ScriptSource>>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    use crate::inspector::ScriptSource;
    let js = format!(
        r"(function() {{
            var i = {seq} - 1;
            var s = document.scripts[i];
            if (!s) return JSON.stringify(null);
            return JSON.stringify({{
                source_url: s.src || ('inline:doc[' + i + ']'),
                body: s.text || '',
            }});
        }})()"
    );
    let json = eval(&js, Duration::from_secs(5))?;
    let unwrapped = serde_json::from_str::<String>(&json).unwrap_or(json);
    let v: serde_json::Value = match serde_json::from_str(&unwrapped) {
        Ok(v) => v,
        Err(_) => return Ok(None),
    };
    if v.is_null() {
        return Ok(None);
    }
    let source_url = v
        .get("source_url")
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .to_string();
    let body = v
        .get("body")
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .to_string();
    Ok(Some(ScriptSource {
        seq,
        source_url,
        body,
    }))
}

/// Run `dom`: outerHTML + computed style for one ref.
pub(crate) fn run_dom<F>(
    eval: F,
    r: Ref,
    extra_props: &[String],
) -> EngineResult<Option<crate::inspector::DomDetail>>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    use crate::inspector::DomDetail;
    let extras_json = serde_json::to_string(extra_props).unwrap_or_else(|_| "[]".into());
    let js = format!(
        r#"(function() {{
            var el = (window.__vsFindRef ? window.__vsFindRef({r}) : null) || document.querySelector(`[data-vs-ref="${{r}}"]`);
            if (!el) return JSON.stringify(null);
            var cs = getComputedStyle(el);
            var defaultProps = ['display','visibility','position','color','background-color','font-size','z-index'];
            var extras = {extras_json};
            var seen = {{}};
            var pairs = [];
            for (var i = 0; i < defaultProps.length; i++) {{
                var k = defaultProps[i];
                if (seen[k]) continue;
                seen[k] = true;
                pairs.push([k, cs.getPropertyValue(k)]);
            }}
            for (var j = 0; j < extras.length; j++) {{
                var k = extras[j];
                if (seen[k]) continue;
                seen[k] = true;
                pairs.push([k, cs.getPropertyValue(k)]);
            }}
            return JSON.stringify({{
                outer_html: el.outerHTML,
                computed: pairs,
            }});
        }})()"#,
        r = r.0
    );
    let json = eval(&js, Duration::from_secs(5))?;
    let unwrapped = serde_json::from_str::<String>(&json).unwrap_or(json);
    let v: serde_json::Value = match serde_json::from_str(&unwrapped) {
        Ok(v) => v,
        Err(_) => return Ok(None),
    };
    if v.is_null() {
        return Ok(None);
    }
    let outer = v
        .get("outer_html")
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .to_string();
    let mut computed: Vec<(String, String)> = Vec::new();
    if let Some(arr) = v.get("computed").and_then(|x| x.as_array()) {
        for pair in arr {
            if let Some(p) = pair.as_array() {
                let k = p.first().and_then(|x| x.as_str()).unwrap_or("");
                let val = p.get(1).and_then(|x| x.as_str()).unwrap_or("");
                computed.push((k.to_string(), val.to_string()));
            }
        }
    }
    Ok(Some(DomDetail {
        r: r.0,
        outer_html: outer,
        computed,
    }))
}

/// Run `performance`: collect PerformanceObserver-derived Web Vitals.
pub(crate) fn run_performance<F>(eval: F) -> EngineResult<crate::inspector::PerformanceMetrics>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
{
    use crate::inspector::PerformanceMetrics;
    let js = r"(function() {
        var nav = performance.getEntriesByType('navigation')[0] || {};
        var paint = performance.getEntriesByType('paint') || [];
        var fcp = 0;
        for (var i = 0; i < paint.length; i++) {
            if (paint[i].name === 'first-contentful-paint') fcp = paint[i].startTime;
        }
        var lcp = (window.__vsLcp || 0);
        var cls = (window.__vsCls || 0);
        var heap = 0;
        if (performance.memory && performance.memory.usedJSHeapSize) {
            heap = performance.memory.usedJSHeapSize / (1024 * 1024);
        }
        return JSON.stringify({
            ttfb: nav.responseStart || 0,
            fcp: fcp,
            lcp: lcp,
            cls: cls,
            fid: 0,
            long_tasks: 0,
            total_blocking: 0,
            heap_mb: heap,
            dom_nodes: document.getElementsByTagName('*').length,
        });
    })()";
    let json = eval(js, Duration::from_secs(5))?;
    let unwrapped = serde_json::from_str::<String>(&json).unwrap_or(json);
    let v: serde_json::Value = serde_json::from_str(&unwrapped)
        .map_err(|e| EngineError::Other(format!("performance: invalid wrapper json: {e}")))?;
    let f = |k: &str| v.get(k).and_then(serde_json::Value::as_f64).unwrap_or(0.0);
    let u = |k: &str| {
        v.get(k)
            .and_then(serde_json::Value::as_u64)
            .and_then(|n| u32::try_from(n).ok())
            .unwrap_or(0)
    };
    Ok(PerformanceMetrics {
        ttfb_ms: f("ttfb"),
        fcp_ms: f("fcp"),
        lcp_ms: f("lcp"),
        cls: f("cls"),
        fid_ms: f("fid"),
        long_tasks: u("long_tasks"),
        total_blocking_ms: f("total_blocking"),
        js_heap_mb: f("heap_mb"),
        dom_nodes: u("dom_nodes"),
    })
}

/// Captured storage state from `STORAGE_SAVE_JS`. Cookies live in a
/// separate host-side payload because `document.cookie` can't see
/// `HttpOnly`.
pub(crate) struct StorageSnapshot {
    pub url: String,
    pub origin: String,
    pub local_storage: std::collections::BTreeMap<String, String>,
    pub session_storage: std::collections::BTreeMap<String, String>,
    pub indexed_db: Vec<crate::backend::auth::IdbDatabase>,
    /// Records left behind because JSON cannot carry them (a Blob, a
    /// typed array). Reported rather than restored wrong.
    pub indexed_db_skipped: u32,
    /// The dump did not finish. The blob is missing databases it
    /// should have had, which is the one thing this must never be
    /// quiet about: a blob that looks complete and restores a logged
    /// out page is worse than one that says what it lacks.
    pub indexed_db_incomplete: bool,
}

pub(crate) fn run_save_storage_only<F, T>(eval: F, tick: T) -> EngineResult<StorageSnapshot>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
    T: FnMut(),
{
    let json = eval(STORAGE_SAVE_JS, STORAGE_EVAL_BUDGET)?;
    let unwrapped = serde_json::from_str::<String>(&json).unwrap_or(json);
    let v: serde_json::Value = serde_json::from_str(&unwrapped)
        .map_err(|e| EngineError::Other(format!("save_storage parse: {e}")))?;
    let url = v
        .get("url")
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .to_string();
    let origin = v
        .get("origin")
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .to_string();
    let local_storage = parse_storage_map(v.get("localStorage"));
    let session_storage = parse_storage_map(v.get("sessionStorage"));
    let (indexed_db, indexed_db_skipped, indexed_db_incomplete) = run_save_indexed_db(&eval, tick)?;
    Ok(StorageSnapshot {
        url,
        origin,
        local_storage,
        session_storage,
        indexed_db,
        indexed_db_skipped,
        indexed_db_incomplete,
    })
}

/// How long an async storage script is given to reach a verdict.
///
/// A deadline rather than a poll count, because what the loop is
/// really waiting on is the database, and a fixed number of turns
/// means something different on an idle machine than on one running
/// the whole cell suite at once.
///
/// The `tick` between polls is the mechanism that makes any of this
/// work. An eval only pumps the run loop until its own completion
/// handler fires, so a bare poll loop inside one engine job spins
/// through every attempt in microseconds while the database's
/// callbacks — which need run-loop turns on that same thread — never
/// run. Each backend hands in its own pump, exactly as `run_wait`
/// does.
const IDB_SETTLE_BUDGET: Duration = Duration::from_secs(15);

/// Budget for one storage-script hop. Deliberately not 5s: these calls
/// queue behind an engine that may be busy, and on a machine running
/// the whole cell suite at once a correct `vs auth save` was failing
/// `! TIMEOUT 5000ms eval` on scheduling delay alone. A hung page
/// still reports, just later.
const STORAGE_EVAL_BUDGET: Duration = Duration::from_secs(20);

/// Drive [`IDB_SAVE_JS`] to completion. Returns the databases and the
/// count of records JSON could not carry.
fn run_save_indexed_db<F, T>(
    eval: F,
    mut tick: T,
) -> EngineResult<(Vec<crate::backend::auth::IdbDatabase>, u32, bool)>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
    T: FnMut(),
{
    let deadline = std::time::Instant::now() + IDB_SETTLE_BUDGET;
    let mut first = true;
    while std::time::Instant::now() < deadline {
        if !first {
            tick();
        }
        first = false;
        let raw = eval(IDB_SAVE_JS, STORAGE_EVAL_BUDGET)?;
        let unwrapped = serde_json::from_str::<String>(&raw).unwrap_or(raw);
        let Ok(v) = serde_json::from_str::<serde_json::Value>(&unwrapped) else {
            // A page with no IndexedDB at all, or an engine that gave
            // us nothing back: not a reason to fail the whole save.
            return Ok((Vec::new(), 0, false));
        };
        match v.get("state").and_then(serde_json::Value::as_str) {
            Some("pending") => {}
            // An origin that denies IndexedDB (private mode, a
            // policy) saves everything else rather than nothing.
            Some("error") | None => return Ok((Vec::new(), 0, false)),
            Some(_) => {
                let dbs = v
                    .get("dbs")
                    .map(|d| serde_json::from_value(d.clone()).unwrap_or_default())
                    .unwrap_or_default();
                let skipped = v
                    .get("skipped")
                    .and_then(serde_json::Value::as_u64)
                    .and_then(|n| u32::try_from(n).ok())
                    .unwrap_or(0);
                return Ok((dbs, skipped, false));
            }
        }
    }
    // Still working after every poll. Save the rest of the blob —
    // cookies and web storage are worth having — but say that the
    // databases are missing.
    Ok((Vec::new(), 0, true))
}

/// Drive [`IDB_LOAD_BODY_JS`] to completion. A restore that never
/// finishes is reported, not swallowed: the caller is about to act as
/// though it were logged in.
fn run_load_indexed_db<F, T>(
    eval: F,
    dbs: &[crate::backend::auth::IdbDatabase],
    mut tick: T,
) -> EngineResult<()>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
    T: FnMut(),
{
    if dbs.is_empty() {
        return Ok(());
    }
    // The token makes a second `auth load` on the same page start a
    // fresh restore instead of reading the previous one's state.
    let token = format!(
        "{:x}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos())
    );
    let payload = serde_json::json!({ "token": token, "dbs": dbs });
    let payload_lit = serde_json::to_string(&payload.to_string())
        .map_err(|e| EngineError::Other(format!("idb payload encode: {e}")))?;
    let body = IDB_LOAD_BODY_JS;
    // `return` on its own line ahead of the body would be a bare
    // `return;` — the body opens with a comment, and automatic
    // semicolon insertion ends the statement at the newline. Bind it
    // to a variable, where ASI cannot cut in.
    let js = format!(
        "(function() {{ var payload = JSON.parse({payload_lit}); var out = {body}; return out; }})()"
    );
    let deadline = std::time::Instant::now() + IDB_SETTLE_BUDGET;
    let mut first = true;
    while std::time::Instant::now() < deadline {
        if !first {
            tick();
        }
        first = false;
        let raw = eval(&js, STORAGE_EVAL_BUDGET)?;
        let unwrapped = serde_json::from_str::<String>(&raw).unwrap_or(raw);
        let Ok(v) = serde_json::from_str::<serde_json::Value>(&unwrapped) else {
            return Err(EngineError::Other("load_indexed_db: bad reply".into()));
        };
        match v.get("state").and_then(serde_json::Value::as_str) {
            Some("pending") => {}
            Some("done") => {
                // A restore that "succeeded" into an empty database is
                // the one outcome worth shouting about; the script's
                // own breadcrumbs are the only way to see which turn it
                // took, so they ride along on the success path too.
                if std::env::var("VS_IDB_TRACE").is_ok() {
                    if let Some(t) = v.get("trace").and_then(serde_json::Value::as_str) {
                        eprintln!("[vs] idb load trace: {t}");
                    }
                }
                return Ok(());
            }
            _ => {
                let msg = v
                    .get("error")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("unknown");
                return Err(EngineError::Other(format!("load_indexed_db: {msg}")));
            }
        }
    }
    Err(EngineError::Timeout {
        budget: IDB_SETTLE_BUDGET,
        primitive: "auth_load:indexeddb",
        detail: "",
    })
}

fn parse_storage_map(v: Option<&serde_json::Value>) -> std::collections::BTreeMap<String, String> {
    let Some(obj) = v.and_then(serde_json::Value::as_object) else {
        return std::collections::BTreeMap::new();
    };
    obj.iter()
        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
        .collect()
}

pub(crate) fn run_load_storage_only<F, T>(
    eval: F,
    local: &std::collections::BTreeMap<String, String>,
    session: &std::collections::BTreeMap<String, String>,
    indexed_db: &[crate::backend::auth::IdbDatabase],
    tick: T,
) -> EngineResult<()>
where
    F: Fn(&str, Duration) -> EngineResult<String>,
    T: FnMut(),
{
    let payload = serde_json::json!({
        "localStorage": local,
        "sessionStorage": session,
    });
    let payload_lit = serde_json::to_string(&payload.to_string())
        .map_err(|e| EngineError::Other(format!("storage payload encode: {e}")))?;
    let body = STORAGE_LOAD_BODY_JS;
    let js = format!("(function() {{ const payload = JSON.parse({payload_lit}); {body} }})()");
    let result = eval(&js, STORAGE_EVAL_BUDGET)?;
    let unwrapped = serde_json::from_str::<String>(&result).unwrap_or(result);
    if unwrapped != "ok" {
        return Err(EngineError::Other(format!(
            "load_storage: unexpected: {unwrapped}"
        )));
    }
    run_load_indexed_db(eval, indexed_db, tick)
}

#[cfg(test)]
mod eval_tests {
    use super::run_eval;
    use crate::engine::{EngineError, EngineResult};
    use crate::inspector::EvalResult;
    use std::time::Duration;

    // Program-mode wrappers contain `(0, eval)`; expression-mode ones do
    // not. Tests use that to fake each engine's behavior per mode.
    fn is_program_mode(js: &str) -> bool {
        js.contains("(0, eval)")
    }

    #[test]
    fn single_expression_uses_expression_mode() {
        // A plain expression resolves in expression mode — no fallback.
        let eval = |js: &str, _b: Duration| -> EngineResult<String> {
            assert!(!is_program_mode(js), "should not reach program mode");
            Ok(r#"{"kind":"ok","type":"number","value":"2"}"#.to_string())
        };
        match run_eval(eval, "1 + 1").unwrap() {
            EvalResult::Ok { value, .. } => assert_eq!(value, "2"),
            other => panic!("expected Ok(2), got {other:?}"),
        }
    }

    #[test]
    fn webkit_err_triggers_program_fallback() {
        // WKWebView / WebKitGTK: a statement block makes the
        // expression wrapper a syntax error -> the engine returns Err.
        let eval = |js: &str, _b: Duration| -> EngineResult<String> {
            if is_program_mode(js) {
                Ok(r#"{"kind":"ok","type":"number","value":"6"}"#.to_string())
            } else {
                Err(EngineError::Other("SyntaxError: ...".into()))
            }
        };
        match run_eval(eval, "const a=2;\nconst b=3;\na*b").unwrap() {
            EvalResult::Ok { value, .. } => assert_eq!(value, "6"),
            other => panic!("expected Ok(6), got {other:?}"),
        }
    }

    #[test]
    fn webview2_null_triggers_program_fallback() {
        // WebView2: ExecuteScript returns the bare string "null" for an
        // uncompilable wrapper instead of an Err. run_eval must still
        // fall through to program mode rather than surfacing an error.
        let eval = |js: &str, _b: Duration| -> EngineResult<String> {
            if is_program_mode(js) {
                Ok(r#"{"kind":"ok","type":"number","value":"6"}"#.to_string())
            } else {
                Ok("null".to_string())
            }
        };
        match run_eval(eval, "const a=2;\nconst b=3;\na*b").unwrap() {
            EvalResult::Ok { value, .. } => assert_eq!(value, "6"),
            other => panic!("expected Ok(6), got {other:?}"),
        }
    }
}