vs-engine-webkit 0.2.19

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
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
//! Linux backend — real `WebKitGTK 6` driven via `webkit6` + `glib`.
//!
//! # Threading model
//!
//! WebKitGTK is bound to the GLib main context of the thread that
//! initialized GTK. Methods on [`WpeBackend`] must be called from that
//! thread; the type is `!Send`. Production wiring (follow-up):
//! `vs-cli::serve` on Linux must put GTK on the OS main thread and
//! dispatch engine calls there via `MainContext::invoke`.
//!
//! # Status
//!
//! Real WebKitGTK-backed implementation of every primitive on the
//! [`Engine`] trait: open / close / snapshot / act / wait / layout /
//! set_viewport / save_auth / load_auth — plus inspector capture
//! (console + network) wired through the `UserContentManager` script-
//! message bridge. `capture` is the only outstanding piece (a TODO in
//! a follow-up that calls `WebView::snapshot`).
//!
//! Verified on Linux CI with `libwebkitgtk-6.0-dev` + `libgtk-4-dev`
//! installed; this file is not built on macOS.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::path::PathBuf;
use std::rc::Rc;
use std::time::Duration;

use glib::prelude::*;
// `gtk4` is a direct dep so we can enable its `v4_10` feature (webkit6
// needs `gtk::Accessible`); alias it to `gtk` to keep the existing refs.
use gtk4 as gtk;
use webkit6::prelude::*;
use webkit6::{LoadEvent, UserContentInjectedFrames, UserScript, UserScriptInjectionTime, WebView};

use vs_protocol::{Ref, Tree};

use crate::engine::{
    ActTarget, Action, AuthBlob, CaptureScope, CursorOp, DataStore, Download, DownloadEntry,
    DownloadSource, Engine, EngineCapabilities, EngineError, EngineResult, InputMode, LayoutBox,
    OpenStart, PageHandle, Viewport, WaitCondition,
};

// =============================================================================
// Per-page state
// =============================================================================

struct WpePage {
    web_view: WebView,
    /// Hidden host window that owns `web_view` as its single child.
    /// Required so the WebView has a `GdkSurface` on the X display —
    /// without it XTest's synthetic input has no window to land on.
    /// Created in `open()`, dropped on `close()`.
    window: gtk::Window,
    inspector: super::inspector_bridge::InspectorSlots,
    /// True if the inspector install path actually succeeded for this
    /// page (script + handlers registered without bail). Read by
    /// `Engine::capabilities()` and the daemon `vs_inspect` gate.
    inspector_installed: bool,
    cookie_baseline: std::cell::RefCell<Option<Vec<super::auth::CookieData>>>,
    cookie_next_seq: std::cell::RefCell<u64>,
    /// Last known cursor position in screen-absolute CSS px. Updated
    /// after every `cursor_op` so the next humanized lead-in starts
    /// where the previous one ended. Defaults to (0, 0) on `open`.
    last_mouse: Cell<vs_humanize::Point>,
    /// A new-window navigation (`target="_blank"`, `window.open()`)
    /// the page asked for and we have not loaded yet. Set by the
    /// `create` handler installed in `open`.
    new_window: Rc<RefCell<Option<webkit6::URIRequest>>>,
    /// Downloads this page's responses turned into.
    downloads: SharedDownloads,
    /// The shared network session's `download-started` handler for
    /// this page. Disconnected on close.
    download_hook: Option<(webkit6::NetworkSession, glib::SignalHandlerId)>,
    /// HTTP response of the latest main-frame navigation. Kept by the
    /// `load-changed` handler from `install_response_capture`.
    main_response: Rc<RefCell<Option<crate::inspector::MainResponse>>>,
    /// The page's session asked for real popups (`Engine::set_popups`):
    /// a new window becomes a page, `window.close()` releases it, and
    /// dialogs wait for an answer. Read by the view's signal handlers.
    popups_on: Rc<Cell<bool>>,
    /// The page's own handle, for those handlers (set once allocated).
    me: Rc<Cell<Option<PageHandle>>>,
    /// Subframe agents, for evaluating in one frame (`wpe_frames`).
    frames: Option<super::wpe_frames::FrameAgents>,
    /// Screen position of the host window's top-left corner: its tile
    /// (see `WpeBackend::place`), or the origin.
    origin: Cell<(f64, f64)>,
}

type Popups = super::wpe_popups::Popups<WpePage>;

/// Size of the screen tile each page window gets when the display is
/// large enough for several (see `WpeBackend::place`). Larger than any
/// usual viewport, so a page's window stays inside its tile.
const TILE_W: i32 = 1600;
const TILE_H: i32 = 1000;

// =============================================================================
// Backend
// =============================================================================

/// Real WebKitGTK 6 backend. Construct on the GTK main thread; all
/// subsequent calls must come from the same thread.
pub struct WpeBackend {
    pages: HashMap<PageHandle, WpePage>,
    /// Popups and closed pages from the views' signal handlers, the
    /// popup feed, and the page-handle counter.
    popups: Popups,
    captures_dir: Option<PathBuf>,
    /// Ephemeral network sessions for isolated sessions, by key. One
    /// per key so every page of the session shares cookies and storage.
    isolated_sessions: HashMap<String, webkit6::NetworkSession>,
    /// Which page holds which screen tile (see `place`).
    tiles: HashMap<i32, PageHandle>,
    /// Pages whose first load is still running, by ticket (see
    /// `open_start`), and the next ticket.
    opening: HashMap<u64, Opening>,
    next_ticket: u64,
}

/// A page `open_start` began whose first load has not ended yet.
struct Opening {
    page: WpePage,
    /// Set by the load-finished or load-failed handler.
    slot: Rc<RefCell<Option<Result<(), String>>>>,
    signals: Vec<glib::SignalHandlerId>,
    deadline: std::time::Instant,
    budget: Duration,
}

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

impl WpeBackend {
    /// Build a backend. Caller must already have initialized GTK on
    /// this thread (via `gtk4::init()`); production wiring lives in
    /// `vs-cli::serve` on Linux. Constructing on a non-GTK thread will
    /// panic the first time a `WebView` operation runs.
    #[must_use]
    pub fn new() -> Self {
        Self {
            pages: HashMap::new(),
            popups: Popups::default(),
            captures_dir: None,
            isolated_sessions: HashMap::new(),
            tiles: HashMap::new(),
            opening: HashMap::new(),
            next_ticket: 0,
        }
    }

    /// Pin the directory where `capture` writes PNGs. Defaults to a
    /// system temp subdirectory.
    #[must_use]
    pub fn with_capture_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.captures_dir = Some(dir.into());
        self
    }

    fn alloc_handle(&mut self) -> PageHandle {
        self.popups.borrow_mut().alloc()
    }

    /// Take in the windows pages opened and release the pages that
    /// closed themselves since the last call. Runs before any page
    /// lookup, so a popup's handle works as soon as it is reported.
    fn sync_popups(&mut self) {
        let (born, closed) = {
            let mut s = self.popups.borrow_mut();
            (std::mem::take(&mut s.born), std::mem::take(&mut s.closed))
        };
        for b in born {
            self.pages.insert(b.handle, b.page);
            self.place(b.handle);
        }
        for h in closed {
            let _ = self.close(h);
        }
    }

    /// Give a new page's window a screen tile of its own, when the
    /// display has room for several. XTest input goes by screen
    /// position and X has one pointer and one stacking order, so with
    /// windows stacked at one spot, pages took each other's clicks and
    /// hover state; apart, the pointer over one page is over no other.
    /// On a smaller display the windows stay at the origin and input
    /// raises its window first. Then park the pointer off every window,
    /// so the page does not open hovered.
    ///
    /// Tile 0, at the screen's origin, is where new windows show while
    /// their first load runs (the engine serves other pages meanwhile),
    /// so no page keeps it: a page there took clicks meant for it on
    /// the window that opened on top.
    fn place(&mut self, handle: PageHandle) {
        let Ok(input) = super::wpe_input::dispatcher() else {
            return;
        };
        let Some((width, height)) = input.screen_size() else {
            return;
        };
        let (cols, rows) = (width / TILE_W, height / TILE_H);
        let title = window_title(handle);
        let free = (1..cols * rows).find(|i| !self.tiles.contains_key(i));
        // Where to park the page's pointer: past its window inside its
        // tile, or past every window at the screen's far corner.
        let mut park = (width - 1, height - 1);
        if let (true, Some(slot), Some(page)) = (cols * rows >= 2, free, self.pages.get(&handle)) {
            let (left, top) = ((slot % cols) * TILE_W, (slot / cols) * TILE_H);
            // GTK sends the title on its own connection; make sure the
            // server has it before looking the window up by it.
            gtk::prelude::WidgetExt::display(&page.window).sync();
            if input.place_window(&title, left, top) {
                page.origin.set((f64::from(left), f64::from(top)));
                self.tiles.insert(slot, handle);
                park = (left + TILE_W - 1, top + TILE_H - 1);
            }
        }
        // The page's own pointer (where the display has several) starts
        // off its window, so the page does not open hovered.
        input.use_page_pointer(&title);
        let _ = input.dispatch(super::wpe_input::InputEvent::Move(
            super::wpe_input::ScreenPoint {
                x: park.0,
                y: park.1,
            },
        ));
        park_core_pointer(input, (width, height));
    }

    fn page_mut(&mut self, h: PageHandle) -> EngineResult<&mut WpePage> {
        self.sync_popups();
        self.pages.get_mut(&h).ok_or(EngineError::NotFound {
            kind: "page",
            id: h.0.to_string(),
        })
    }
}

// =============================================================================
// Run-loop helper: pump the GLib main context until a predicate fires
// =============================================================================

fn run_loop_until<F: FnMut() -> bool>(mut done: F, budget: Duration) -> bool {
    let main_ctx = glib::MainContext::default();
    let deadline = std::time::Instant::now() + budget;
    loop {
        let now = std::time::Instant::now();
        if now >= deadline {
            break;
        }
        if done() {
            return true;
        }
        if main_ctx.iteration(false) {
            continue;
        }
        // Nothing ready: block until a source fires or the slice ends.
        // A fixed sleep here noticed every eval result and input event
        // up to 10ms late.
        let left = deadline.duration_since(now).min(Duration::from_millis(50));
        let fired = std::rc::Rc::new(Cell::new(false));
        let flag = fired.clone();
        let timer = glib::timeout_add_local_once(left, move || flag.set(true));
        main_ctx.iteration(true);
        if !fired.get() {
            timer.remove();
        }
    }
    done()
}

// =============================================================================
// Shared payloads + parsers
// =============================================================================

use super::common::{parse_snapshot, SNAPSHOT_DOM_WALKER_JS as SNAPSHOT_JS};
use super::native_download::{
    is_attachment, name_from_disposition, temp_path, SharedDownloads, MAX_BYTES,
};

// =============================================================================
// Engine impl
// =============================================================================

impl Engine for WpeBackend {
    fn open(&mut self, url: &str, store: &DataStore) -> EngineResult<PageHandle> {
        let ticket = match self.open_start(url, store)? {
            OpenStart::Done(page) => return Ok(page),
            OpenStart::Pending(ticket) => ticket,
        };
        if let Some(slot) = self.opening.get(&ticket).map(|o| o.slot.clone()) {
            let budget = super::common::nav_budget();
            let _ = run_loop_until(move || slot.borrow().is_some(), budget);
        }
        loop {
            if let Some(result) = self.open_poll(ticket) {
                return result;
            }
            let _ = run_loop_until(|| false, Duration::from_millis(5));
        }
    }

    fn open_start(&mut self, url: &str, store: &DataStore) -> EngineResult<OpenStart> {
        // An isolated session's pages share one ephemeral (in-memory)
        // network session; everyone else gets the default persistent
        // one. The download hook below connects to whichever session
        // the view ends up with.
        //
        // A proxied session's network session also sends every request
        // through the daemon's proxy. The ignore list is empty, so
        // loopback is proxied too.
        let web_view = match store.key() {
            None => WebView::new(),
            Some(key) => {
                let port = store.proxy_port();
                let session = self
                    .isolated_sessions
                    .entry(key.to_string())
                    .or_insert_with(|| {
                        let s = webkit6::NetworkSession::new_ephemeral();
                        if let Some(port) = port {
                            let uri = format!("http://127.0.0.1:{port}");
                            let settings = webkit6::NetworkProxySettings::new(Some(&uri), &[]);
                            s.set_proxy_settings(
                                webkit6::NetworkProxyMode::Custom,
                                Some(&settings),
                            );
                            // The proxy answers TLS with leaves from the
                            // daemon's CA, made per host, so they cannot
                            // be allowed one by one up front. Every TLS
                            // connection of this session ends at the
                            // proxy, which verifies upstream itself, so
                            // certificate errors are ignored here, for
                            // this network session only.
                            s.set_tls_errors_policy(webkit6::TLSErrorsPolicy::Ignore);
                        }
                        s
                    });
                WebView::builder().network_session(session).build()
            }
        };

        // Hidden host window for the WebView. v0.1.11 added native
        // input dispatch (XTest / libei) for the cursor primitives;
        // both require the WebView to have a real `GdkSurface` on the
        // display server so the synthetic event has somewhere to land.
        // `WebView::new()` alone renders to an internal offscreen
        // surface with no display-server window — XTest events would
        // disappear into the void. Wrapping each WebView in a
        // decorated-off `gtk::Window` and presenting it gives us that
        // surface; under `xvfb` (CI) the window has no visual effect.
        let page = host_page(&web_view, &self.popups);
        web_view.load_uri(url);

        // Wait for LoadEvent::Finished or LoadEvent::Failed via signal.
        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
        let slot_for_signal = slot.clone();
        let signal_id = web_view.connect_load_changed(move |_view, event| {
            if event == LoadEvent::Finished {
                *slot_for_signal.borrow_mut() = Some(Ok(()));
            }
        });
        let slot_fail = slot.clone();
        let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
            *slot_fail.borrow_mut() = Some(load_result(err));
            // Stop event propagation: we have handled it.
            true
        });

        // The load runs in the page's web process (a new one takes tens
        // of milliseconds to start); `open_poll` finishes the open, and
        // the engine thread serves other pages meanwhile.
        let budget = super::common::nav_budget();
        let ticket = self.next_ticket;
        self.next_ticket += 1;
        self.opening.insert(
            ticket,
            Opening {
                page,
                slot,
                signals: vec![signal_id, fail_id],
                deadline: std::time::Instant::now() + budget,
                budget,
            },
        );
        Ok(OpenStart::Pending(ticket))
    }

    fn open_poll(&mut self, ticket: u64) -> Option<EngineResult<PageHandle>> {
        let Some(o) = self.opening.get(&ticket) else {
            return Some(Err(EngineError::Other("no open is pending".into())));
        };
        if o.slot.borrow().is_none() && std::time::Instant::now() < o.deadline {
            return None;
        }
        let o = self.opening.remove(&ticket)?;
        // Disconnect the handlers: the WebView outlives the open.
        for id in o.signals {
            o.page.web_view.disconnect(id);
        }
        let outcome = o.slot.borrow_mut().take();
        match outcome {
            None => {
                return Some(Err(EngineError::Timeout {
                    budget: o.budget,
                    primitive: "open",
                    detail: "",
                }))
            }
            Some(Err(msg)) => {
                return Some(Err(EngineError::Other(format!("navigation failed: {msg}"))))
            }
            Some(Ok(())) => {}
        }
        let page = o.page;
        let handle = self.alloc_handle();
        page.me.set(Some(handle));
        page.window.set_title(Some(&window_title(handle)));
        self.pages.insert(handle, page);
        self.place(handle);
        Some(Ok(handle))
    }

    fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()> {
        // Same wait as `open`, on a WebView that already exists. The
        // inspector bridge and download shim were installed at
        // document-start and survive the navigation, so this only has
        // to load and wait.
        let web_view = self.page_mut(page)?.web_view.clone();
        web_view.load_uri(url);
        wait_for_load(&web_view, "navigate")
    }

    fn load_html(&mut self, page: PageHandle, url: &str, html: &str) -> EngineResult<()> {
        let web_view = self.page_mut(page)?.web_view.clone();
        web_view.load_html(html, Some(url));
        wait_for_load(&web_view, "load_html")
    }

    fn add_init_script(&mut self, page: PageHandle, source: &str) -> EngineResult<()> {
        let manager = self
            .page_mut(page)?
            .web_view
            .user_content_manager()
            .ok_or_else(|| EngineError::Other("WebView has no UserContentManager".into()))?;
        manager.add_script(&UserScript::new(
            source,
            UserContentInjectedFrames::AllFrames,
            UserScriptInjectionTime::Start,
            &[],
            &[],
        ));
        Ok(())
    }

    fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
        Err(EngineError::NotImplemented {
            engine: "wpe",
            primitive: "enable_webauthn",
        })
    }

    fn close(&mut self, page: PageHandle) -> EngineResult<()> {
        self.tiles.retain(|_, h| *h != page);
        if let Ok(input) = super::wpe_input::dispatcher() {
            input.drop_page_pointer(&window_title(page));
        }
        if let Some(mut p) = self.pages.remove(&page) {
            if let Some((session, id)) = p.download_hook.take() {
                session.disconnect(id);
            }
            // Dismiss the hidden host window so its `GdkSurface` is
            // unmapped from the display server. `close()` queues the
            // destroy; the GLib main context completes it on the next
            // iteration.
            p.window.close();
        }
        Ok(())
    }

    fn drop_store(&mut self, key: &str) -> EngineResult<()> {
        // The session lives on while a closed view still references it;
        // dropping ours lets GLib free it with the last one.
        self.isolated_sessions.remove(key);
        Ok(())
    }

    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree> {
        let p = self.page_mut(page)?;
        let json = eval_js_string(&p.web_view, SNAPSHOT_JS, Duration::from_secs(5))?;
        parse_snapshot(&json).map_err(EngineError::Other)
    }

    fn act(
        &mut self,
        page: PageHandle,
        target: ActTarget,
        action: Action,
        _mode: InputMode,
    ) -> EngineResult<()> {
        self.forget_new_window(page)?;
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        super::common::run_act(
            move |js, budget| eval_js_string(&web_view, js, budget),
            &target,
            &action,
        )?;
        self.follow_new_window(page, super::common::may_open_window(&action))
    }

    fn wait(
        &mut self,
        page: PageHandle,
        cond: WaitCondition,
        budget: Duration,
    ) -> EngineResult<()> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        super::common::run_wait(
            |js, budget| eval_js_string(&web_view, js, budget),
            &cond,
            budget,
            || {
                let _ = run_loop_until(|| false, Duration::from_millis(50));
            },
        )
    }
    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        super::common::run_layout(
            move |js, budget| eval_js_string(&web_view, js, budget),
            refs,
        )
    }

    fn download(
        &mut self,
        page: PageHandle,
        source: DownloadSource,
        budget: Duration,
    ) -> EngineResult<Download> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        let native = p.downloads.clone();
        super::common::run_download(
            |js, budget| eval_js_string(&web_view, js, budget),
            || {
                let _ = run_loop_until(|| false, Duration::from_millis(50));
            },
            &source,
            budget,
            &native,
        )
    }

    fn download_list(&mut self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        let native = p.downloads.clone();
        super::common::run_download_list(
            move |js, budget| eval_js_string(&web_view, js, budget),
            &native,
        )
    }
    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
        let p = self.page_mut(page)?;
        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
        // The host `gtk::Window` constrains its child WebView's
        // allocation, so resizing the WebView via `set_size_request`
        // alone is shadowed by the (1280x800) host. Resize both: the
        // window's default size for the surface, and the WebView's
        // size request so its render target matches the requested
        // viewport.
        p.window.set_default_size(w, h);
        p.web_view.set_size_request(w, h);
        // Pin the sized view to the window's top-left corner: a viewport
        // smaller than the window must not be centered, or pointer input
        // at page coordinates would miss by the gap. (Without a size
        // request the view fills the window, so this is only set here.)
        p.web_view.set_halign(gtk::Align::Start);
        p.web_view.set_valign(gtk::Align::Start);
        Ok(())
    }

    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
        let _ = std::fs::create_dir_all(&captures_dir);
        let path = captures_dir.join(format!("capture-{}.png", page.0));
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        let out_path = path.clone();

        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
        let slot_for_cb = slot.clone();
        web_view.snapshot(
            webkit6::SnapshotRegion::FullDocument,
            webkit6::SnapshotOptions::NONE,
            None::<&webkit6::gio::Cancellable>,
            move |result| {
                *slot_for_cb.borrow_mut() = Some(match result {
                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
                    Err(e) => Err(e.to_string()),
                });
            },
        );

        let slot_check = slot.clone();
        let ok = run_loop_until(
            move || slot_check.borrow().is_some(),
            Duration::from_secs(10),
        );
        if !ok {
            return Err(EngineError::Timeout {
                budget: Duration::from_secs(10),
                primitive: "capture",
                detail: "",
            });
        }
        let result = slot.borrow_mut().take();
        match result {
            Some(Ok(())) => Ok(path),
            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
            None => Err(EngineError::Other(
                "capture completed without a result".into(),
            )),
        }
    }

    fn crash(&mut self, page: PageHandle) -> EngineResult<()> {
        let p = self.page_mut(page)?;
        p.web_view.terminate_web_process();
        let _ = run_loop_until(|| false, Duration::from_millis(200));
        Ok(())
    }

    fn drop_data(
        &mut self,
        page: PageHandle,
        x: f64,
        y: f64,
        data: &crate::engine::DropData,
    ) -> EngineResult<bool> {
        self.forget_new_window(page)?;
        let dispatcher = super::wpe_input::dispatcher()?;
        let (web_view, home) = {
            let p = self.page_mut(page)?;
            (p.web_view.clone(), p.origin.get())
        };
        let title = window_title(page);
        // XDND needs an X11 window; a pure Wayland session has no
        // protocol for an outside drag, so the drop arrives by script.
        let Some(target) = dispatcher.x11_window(&title) else {
            return Err(EngineError::Unsupported {
                engine: "webkitgtk-wayland",
                primitive: "drop",
            });
        };
        let (ox, oy) = input_origin(dispatcher, page, home);
        dispatcher.raise_window(&title);
        if let Some(js) = super::drop_shim::install_js(data) {
            eval_js_string(&web_view, &js, Duration::from_secs(2))?;
        }
        let accepted = super::wpe_xdnd::drop_data(target, ox + x, oy + y, data, |d| {
            let _ = run_loop_until(|| false, d);
        });
        let accepted = accepted?;
        self.follow_new_window(page, false)?;
        Ok(accepted)
    }

    fn set_zoom(&mut self, page: PageHandle, zoom: f64) -> EngineResult<()> {
        let p = self.page_mut(page)?;
        p.web_view.set_zoom_level(zoom);
        Ok(())
    }

    fn cookies(
        &mut self,
        page: PageHandle,
        op: crate::engine::CookieOp,
    ) -> EngineResult<Vec<crate::engine::CookieData>> {
        let web_view = self.page_mut(page)?.web_view.clone();
        match op {
            crate::engine::CookieOp::List => {}
            crate::engine::CookieOp::Set(list) => wpe_cookies::set_cookies(&web_view, &list)?,
            crate::engine::CookieOp::Clear => wpe_cookies::delete_all(&web_view)?,
        }
        wpe_cookies::get_all_cookies(&web_view)
    }

    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        // Cookies: host-side via CookieManager so HttpOnly entries
        // are captured. localStorage/sessionStorage: JS shim.
        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
        let storage = super::common::run_save_storage_only(
            move |js, budget| eval_js_string(&web_view, js, budget),
            || {
                let _ = run_loop_until(|| false, Duration::from_millis(50));
            },
        )?;
        let blob = super::auth::AuthBlobV2 {
            version: 2,
            url: storage.url,
            origin: storage.origin,
            cookies,
            local_storage: storage.local_storage,
            indexed_db: storage.indexed_db,
            indexed_db_skipped: storage.indexed_db_skipped,
            indexed_db_incomplete: storage.indexed_db_incomplete,
            session_storage: storage.session_storage,
        };
        super::auth::encode(&blob)
    }

    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        let parsed = super::auth::decode(blob)?;
        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
        super::common::run_load_storage_only(
            move |js, budget| eval_js_string(&web_view, js, budget),
            &parsed.local_storage,
            &parsed.session_storage,
            &parsed.indexed_db,
            || {
                let _ = run_loop_until(|| false, Duration::from_millis(50));
            },
        )
    }

    fn console_entries(
        &mut self,
        page: PageHandle,
    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
        let p = self.page_mut(page)?;
        Ok(p.inspector.console.borrow().snapshot())
    }

    fn network_entries(
        &mut self,
        page: PageHandle,
    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
        let p = self.page_mut(page)?;
        Ok(p.inspector.network.borrow().snapshot())
    }

    fn request_detail(
        &mut self,
        page: PageHandle,
        seq: u64,
    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
        let p = self.page_mut(page)?;
        Ok(p.inspector.details.borrow().get(seq).cloned())
    }

    fn eval_js(
        &mut self,
        page: PageHandle,
        expr: &str,
    ) -> EngineResult<crate::inspector::EvalResult> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        super::common::run_eval(
            move |js, budget| eval_js_string(&web_view, js, budget),
            expr,
        )
    }

    fn storage(
        &mut self,
        page: PageHandle,
        scope: crate::inspector::StorageScope,
    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        if matches!(scope, crate::inspector::StorageScope::Cookies) {
            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
            return Ok(cookies
                .iter()
                .map(super::common::cookie_to_storage_entry)
                .collect());
        }
        super::common::run_storage(
            move |js, budget| eval_js_string(&web_view, js, budget),
            scope,
        )
    }

    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
    }

    fn script_source(
        &mut self,
        page: PageHandle,
        seq: u64,
    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        super::common::run_script_source(
            move |js, budget| eval_js_string(&web_view, js, budget),
            seq,
        )
    }

    fn dom(
        &mut self,
        page: PageHandle,
        r: Ref,
        extra_props: &[String],
    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        super::common::run_dom(
            move |js, budget| eval_js_string(&web_view, js, budget),
            r,
            extra_props,
        )
    }

    fn performance(
        &mut self,
        page: PageHandle,
    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
    }

    fn main_response(
        &mut self,
        page: PageHandle,
    ) -> EngineResult<Option<crate::inspector::MainResponse>> {
        Ok(self.page_mut(page)?.main_response.borrow().clone())
    }

    fn cookie_events(
        &mut self,
        page: PageHandle,
    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
        let p = self.page_mut(page)?;
        let web_view = p.web_view.clone();
        let current = wpe_cookies::get_all_cookies(&web_view)?;
        let previous = p.cookie_baseline.borrow().clone();
        let mut seq = p.cookie_next_seq.borrow_mut();
        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
        *p.cookie_baseline.borrow_mut() = Some(current);
        Ok(events)
    }

    fn type_text(&mut self, page: PageHandle, text: &str, mode: InputMode) -> EngineResult<()> {
        // Addressing the page validates it and keeps the error shape
        // the same as every other page op, even though the keys go to
        // whatever holds focus rather than to a page handle.
        self.forget_new_window(page)?;
        let (cursor, tile) = {
            let p = self.page_mut(page)?;
            (p.last_mouse.get(), p.origin.get())
        };
        let dispatcher = super::wpe_input::dispatcher()?;
        let origin = input_origin(dispatcher, page, tile);
        // Pump GLib rather than sleep: this runs on the main thread,
        // so a plain sleep would stop WebKit processing the very keys
        // we are sending.
        let settle = |d: Duration| {
            let _ = run_loop_until(|| false, d);
        };
        // Put the pointer where we believe it already is before asking
        // for focus. X hands keys to the focused window, and a
        // headless session has no window manager to focus anything, so
        // the pointer is what we have to go on. The caller has
        // normally just clicked to place the caret, which means the
        // right window is already under it.
        #[allow(clippy::cast_possible_truncation)]
        let at = super::wpe_input::ScreenPoint {
            x: (origin.0 + cursor.x) as i32,
            y: (origin.1 + cursor.y) as i32,
        };
        dispatcher.raise_window(&window_title(page));
        // Keys go through the core keyboard (toolkits take them from it
        // only), focused on this page's window by the core pointer.
        dispatcher.use_core_pointer();
        let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(at));
        let _ = dispatcher.flush();
        dispatcher.focus_pointer_window();

        let (base_delay, span) = match mode {
            InputMode::Robotic => (0_u64, 0_u64),
            InputMode::Careful => (120, 0),
            // ±40% of base, so repeated typing is not metronomic.
            InputMode::Human => (45, 18),
        };
        let mut jitter = text
            .chars()
            .map(|c| c as u64)
            .fold(0x9e37_79b9_u64, |a, c| a.wrapping_mul(31).wrapping_add(c))
            | 1;

        let typed = (|| -> EngineResult<()> {
            for ch in text.chars() {
                let hold = if base_delay == 0 { 1 } else { base_delay / 3 };
                dispatcher.key_down(ch, &settle)?;
                settle(Duration::from_millis(hold.max(1)));
                dispatcher.key_up(ch)?;
                if base_delay > 0 {
                    jitter ^= jitter << 13;
                    jitter ^= jitter >> 7;
                    jitter ^= jitter << 17;
                    let extra = if span == 0 {
                        0
                    } else {
                        jitter % (span * 2 + 1)
                    };
                    let wait = base_delay.saturating_sub(span).saturating_add(extra);
                    settle(Duration::from_millis(wait.max(1)));
                } else {
                    settle(Duration::from_millis(1));
                }
            }
            Ok(())
        })();

        // Give the borrowed keycode back whether the run finished or
        // failed halfway: a stray binding would change what the user's
        // own keyboard does for the rest of the session.
        let restored = dispatcher.end_typing();
        typed?;
        restored?;

        // Let the last keyUp turn into beforeinput/input before the
        // caller reads the page back.
        let _ = run_loop_until(|| false, Duration::from_millis(150));
        // The core pointer must not stay over this page (or end up over
        // the next one placed here) once typing is done.
        if let Some(size) = dispatcher.screen_size() {
            park_core_pointer(dispatcher, size);
        }
        self.follow_new_window(page, false)
    }

    #[allow(clippy::too_many_lines)]
    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
        self.forget_new_window(page)?;
        let p = self.page_mut(page)?;
        let dispatcher = super::wpe_input::dispatcher()?;
        let humanize_mode = match mode {
            InputMode::Human => vs_humanize::InputMode::Human,
            InputMode::Careful => vs_humanize::InputMode::Careful,
            InputMode::Robotic => vs_humanize::InputMode::Robotic,
        };
        // Screen origin of the hidden host window. v0.1.11 assumes
        // (0, 0) — true under `xvfb` (CI) and any session without a
        // window manager. With a WM, the WM may have translated the
        // window elsewhere; a follow-up PR will query
        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
        // real origin. Until then, page-local CSS px == screen px,
        // which is fine for CI and most headless setups.
        // The web view fills the window, or is pinned to its top-left
        // once sized (set_viewport): page coordinates are window
        // coordinates either way.
        let (origin_x, origin_y) = input_origin(dispatcher, page, p.origin.get());
        // Every page's window is at the origin; put this one on top so
        // the input reaches it and not another page's.
        dispatcher.raise_window(&window_title(page));
        dispatcher.use_page_pointer(&window_title(page));
        let start = p.last_mouse.get();
        let seed = humanize_seed(op);
        let landed = match op {
            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => cursor_move_along_path(
                dispatcher,
                start,
                vs_humanize::Point { x, y },
                (origin_x, origin_y),
                humanize_mode,
                seed,
                false,
            )?,
            CursorOp::ClickAt { x, y } => {
                let landed = cursor_move_along_path(
                    dispatcher,
                    start,
                    vs_humanize::Point { x, y },
                    (origin_x, origin_y),
                    humanize_mode,
                    seed,
                    false,
                )?;
                cursor_press_release(dispatcher, landed, (origin_x, origin_y), humanize_mode)?;
                landed
            }
            CursorOp::Drag { x1, y1, x2, y2 } => {
                let start_pt = vs_humanize::Point { x: x1, y: y1 };
                let target = vs_humanize::Point { x: x2, y: y2 };
                let pre = cursor_move_along_path(
                    dispatcher,
                    start,
                    start_pt,
                    (origin_x, origin_y),
                    humanize_mode,
                    seed,
                    false,
                )?;
                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
                    super::wpe_input::Button::Left,
                ))?;
                std::thread::sleep(Duration::from_millis(15));
                let landed = cursor_move_along_path(
                    dispatcher,
                    pre,
                    target,
                    (origin_x, origin_y),
                    humanize_mode,
                    seed,
                    true,
                )?;
                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
                    super::wpe_input::Button::Left,
                ))?;
                dispatcher.flush()?;
                // After the OS-level drag, fire the HTML5 DragEvent
                // chain in JS so react-dnd / React-Flow HTML5 targets
                // observe the drop.
                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
                let web_view = p.web_view.clone();
                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
                landed
            }
            CursorOp::Click { x, y, opts } => {
                let landed = cursor_move_along_path(
                    dispatcher,
                    start,
                    vs_humanize::Point { x, y },
                    (origin_x, origin_y),
                    humanize_mode,
                    seed,
                    false,
                )?;
                click_with(dispatcher, opts)?;
                landed
            }
            CursorOp::Wheel { x, y, dx, dy } => {
                let landed = cursor_move_along_path(
                    dispatcher,
                    start,
                    vs_humanize::Point { x, y },
                    (origin_x, origin_y),
                    humanize_mode,
                    seed,
                    false,
                )?;
                // One click that WebKit's handler takes as the exact
                // turn (see wpe_wheel); the XTest step stays the
                // fallback when that hook is not in place.
                // The portal's axis events are exact already.
                if dispatcher.backend_name() == "xtest" {
                    super::wpe_wheel::arm(dx, dy, (p.web_view.width(), p.web_view.height()));
                    dispatcher.dispatch(super::wpe_input::InputEvent::Wheel {
                        dx: if dy == 0.0 { dx.signum() } else { 0.0 },
                        dy: dy.signum(),
                        step: (1.0, 1.0),
                    })?;
                } else {
                    dispatcher.dispatch(super::wpe_input::InputEvent::Wheel {
                        dx,
                        dy,
                        step: (1.0, 1.0),
                    })?;
                }
                dispatcher.flush()?;
                deliver_input(dispatcher, &p.window);
                super::wpe_wheel::disarm();
                landed
            }
        };
        p.last_mouse.set(landed);
        deliver_input(dispatcher, &p.window);
        self.follow_new_window(
            page,
            matches!(op, CursorOp::ClickAt { .. } | CursorOp::Click { .. }),
        )
    }

    fn set_popups(&mut self, page: PageHandle, on: bool) -> EngineResult<()> {
        self.page_mut(page)?.popups_on.set(on);
        Ok(())
    }

    fn eval_js_in_frame(
        &mut self,
        page: PageHandle,
        frame: &str,
        expr: &str,
    ) -> EngineResult<crate::inspector::EvalResult> {
        let agents = self
            .page_mut(page)?
            .frames
            .clone()
            .ok_or(EngineError::Unsupported {
                engine: "wpe",
                primitive: "vs_inspect eval --frame",
            })?;
        let not_found = || EngineError::NotFound {
            kind: "frame",
            id: frame.to_string(),
        };
        // A frame still loading has no agent yet; give it a moment.
        let probe = agents.clone();
        let wanted = frame.to_string();
        if !run_loop_until(
            move || super::wpe_frames::has_agent(&probe, &wanted),
            Duration::from_millis(500),
        ) {
            return Err(not_found());
        }
        super::common::run_eval(
            |js, budget| {
                let id = super::wpe_frames::dispatch(&agents, frame, js).ok_or_else(not_found)?;
                let out: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
                let (sink, src) = (out.clone(), agents.clone());
                let done = run_loop_until(
                    move || {
                        if let Some(r) = super::wpe_frames::take_result(&src, id) {
                            *sink.borrow_mut() = Some(r);
                        }
                        sink.borrow().is_some()
                    },
                    budget,
                );
                if !done {
                    return Err(EngineError::Timeout {
                        budget,
                        primitive: "eval",
                        detail: "",
                    });
                }
                let result = out.borrow_mut().take();
                match result {
                    Some(Ok(v)) => Ok(v),
                    Some(Err(e)) => Err(EngineError::Other(e)),
                    None => Err(not_found()),
                }
            },
            expr,
        )
    }

    fn popup_feed(&mut self) -> Option<std::sync::Arc<crate::engine::PopupFeed>> {
        Some(self.popups.borrow().feed.clone())
    }

    fn capabilities(&self) -> EngineCapabilities {
        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
        EngineCapabilities {
            renders: true,
            honors_viewport: true,
            measures_layout: true,
            persists_auth: true,
            inspector_console: any_inspector,
            inspector_network: any_inspector,
            inspector_cookie_events: true,
            name: "wpe",
            version: "Linux WebKitGTK 6 (webkit6)",
        }
    }
}

// =============================================================================
// JS evaluation helper
// =============================================================================

// =============================================================================
// Cursor primitive helpers (XTest / libei input dispatch)
// =============================================================================

/// Deterministic seed for the humanize Bezier path so the same
/// `cursor_op` invocation produces the same trajectory on every run.
/// Press and release `opts.button` `opts.count` times at the pointer,
/// with the modifier keys held around the clicks. Clicks this close
/// together are one double (or triple) click to GTK.
fn click_with(
    dispatcher: &dyn super::wpe_input::InputDispatcher,
    opts: crate::engine::ClickOpts,
) -> EngineResult<()> {
    use super::wpe_input::{Button, InputEvent};
    use crate::engine::MouseButton;
    // Shift_L, Control_L, Alt_L, Super_L.
    let held: Vec<u32> = [
        (opts.modifiers.shift, 0xffe1),
        (opts.modifiers.ctrl, 0xffe3),
        (opts.modifiers.alt, 0xffe9),
        (opts.modifiers.meta, 0xffeb),
    ]
    .into_iter()
    .filter_map(|(on, k)| on.then_some(k))
    .collect();
    for &k in &held {
        dispatcher.modifier(k, true)?;
    }
    let button = match opts.button {
        MouseButton::Left => Button::Left,
        MouseButton::Right => Button::Right,
        MouseButton::Middle => Button::Middle,
    };
    for _ in 0..opts.count.max(1) {
        dispatcher.dispatch(InputEvent::Press(button))?;
        dispatcher.dispatch(InputEvent::Release(button))?;
    }
    for &k in held.iter().rev() {
        dispatcher.modifier(k, false)?;
    }
    dispatcher.flush()
}

fn humanize_seed(op: CursorOp) -> u64 {
    // Hash the op's coordinates into a u64. Trivial mixer; replays
    // need determinism, not cryptographic spread.
    let (a, b, c, d) = match op {
        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
            (x, y, 0.0, 0.0)
        }
        CursorOp::Wheel { x, y, dx, dy } => (x, y, dx, dy),
        CursorOp::Click { x, y, .. } => (x, y, 0.0, 0.0),
        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
    };
    let bits = |v: f64| v.to_bits();
    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
        ^ bits(d)
}

/// The X window title of a page's host window. XTest input goes by
/// screen position, so the input path finds a page's window by this
/// name to place it in its tile, raise it, and give it its own pointer.
fn window_title(page: PageHandle) -> String {
    // The daemon's pid, so two daemons on one display never share a
    // name (and `wpe_input` can tell a dead daemon's leftovers).
    format!("vs-page-{}-{}", std::process::id(), page.0)
}

/// Hand the input just sent to WebKit before returning. XTest events go
/// from the server to GTK's own connection, and GTK handles them on a
/// later main-loop pass; a read of the page sent right after (an eval)
/// could reach the web process first and see the page from before the
/// click. A display sync makes sure GTK has received every event the
/// server generated so far; dispatching what is pending then passes the
/// events to WebKit, whose messages to the web process keep that order.
fn deliver_input(dispatcher: &dyn super::wpe_input::InputDispatcher, window: &gtk::Window) {
    let _ = dispatcher.flush();
    gtk::prelude::WidgetExt::display(window).sync();
    let ctx = glib::MainContext::default();
    for _ in 0..64 {
        if !ctx.iteration(false) {
            break;
        }
    }
}

/// Move the display's core pointer to the screen's far corner, past
/// every page window and tile, and leave input routed through it.
fn park_core_pointer(dispatcher: &dyn super::wpe_input::InputDispatcher, size: (i32, i32)) {
    dispatcher.use_core_pointer();
    let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(
        super::wpe_input::ScreenPoint {
            x: size.0 - 1,
            y: size.1 - 1,
        },
    ));
    let _ = dispatcher.flush();
}

/// The screen origin to add to page coordinates for input. GTK moves a
/// window back to where it thinks it is when it resizes (`vs viewport`),
/// so put a drifted window back into its tile first; otherwise trust
/// where X says the window is.
fn input_origin(
    dispatcher: &dyn super::wpe_input::InputDispatcher,
    page: PageHandle,
    home: (f64, f64),
) -> (f64, f64) {
    let title = window_title(page);
    let Some((x, y)) = dispatcher.window_origin(&title) else {
        return home;
    };
    let now = (f64::from(x), f64::from(y));
    #[allow(clippy::cast_possible_truncation)]
    let moved_back = home != (0.0, 0.0)
        && now != home
        && dispatcher.place_window(&title, home.0 as i32, home.1 as i32);
    if moved_back {
        home
    } else {
        now
    }
}

/// Everything a web view needs to be a page: a host window on the X
/// display, the user agent, the inspector bridge, download and response
/// capture, and the new-window, close and dialog handlers. Used for
/// pages `open` creates and for windows a page opens (`create`), so a
/// popup is the same kind of page. The caller sets `me` and the window
/// title once the page has a handle.
#[allow(clippy::too_many_lines)]
fn host_page(web_view: &WebView, popups: &Popups) -> WpePage {
    // No native context menu: the page still gets its contextmenu
    // event, and no menu stays open to take the next click.
    web_view.connect_context_menu(|_, _, _| true);
    super::wpe_wheel::install(web_view);
    // Hidden host window: XTest input needs a real surface on the
    // display server to land on (see `open`). It shows at the screen's
    // origin until `place` moves it; no placed page keeps that tile.
    let window = gtk::Window::new();
    window.set_decorated(false);
    window.set_default_size(1280, 800);
    window.set_child(Some(web_view));
    window.present();

    // Pin the User-Agent to a current Safari string so anti-bot
    // fingerprinters don't flag the WebKitGTK default. See the commit
    // log for `crate::engine::DEFAULT_USER_AGENT` rationale.
    if let Some(settings) = WebViewExt::settings(web_view) {
        settings.set_user_agent(Some(crate::engine::DEFAULT_USER_AGENT));
        // Expose `navigator.mediaDevices`. WebKitGTK gates the
        // MediaDevices surface off by default, so the object is simply
        // absent and anything feature-detecting camera or mic support
        // sees a browser that cannot exist.
        settings.set_enable_media_stream(true);
        // `act click` on this engine is a JS click, not a user gesture,
        // so blank-target navigation has to be allowed without one.
        settings.set_javascript_can_open_windows_automatically(true);
    }

    // Inspector capture wiring — install the user script and register
    // both message channels before any load, so the bridge is live by
    // document-start.
    let inspector =
        super::inspector_bridge::InspectorSlots::new(crate::inspector::DEFAULT_BUFFER_CAPACITY);
    let inspector_installed = install_inspector(web_view, &inspector);
    install_download_shim(web_view);
    let frames = super::wpe_frames::install(web_view);

    let popups_on = Rc::new(Cell::new(false));
    let me: Rc<Cell<Option<PageHandle>>> = Rc::new(Cell::new(None));

    // A new window (`target="_blank"`, `window.open()`). With popups on
    // it becomes a page of its own, built on a related view (same
    // network session and web process, so `window.opener` works) and
    // reported on the feed. Otherwise there is no second window: park
    // the request, and the input primitive that caused it loads it in
    // this page (`follow_new_window`).
    let new_window: Rc<RefCell<Option<webkit6::URIRequest>>> = Rc::new(RefCell::new(None));
    {
        let parked = new_window.clone();
        let on = popups_on.clone();
        let me = me.clone();
        let popups = popups.clone();
        web_view.connect_create(move |view, action| {
            if !on.get() {
                *parked.borrow_mut() = action.request();
                return None;
            }
            let url = action
                .request()
                .and_then(|r| r.uri())
                .map(|u| u.to_string())
                .unwrap_or_default();
            let child = WebView::builder().related_view(view).build();
            let page = host_page(&child, &popups);
            page.popups_on.set(true);
            let mut s = popups.borrow_mut();
            let handle = s.alloc();
            page.me.set(Some(handle));
            page.window.set_title(Some(&window_title(handle)));
            s.born.push(super::wpe_popups::Born { handle, page });
            s.feed
                .push(crate::engine::PopupEvent::Opened(crate::engine::Popup {
                    opener: me.get(),
                    page: handle,
                    url,
                }));
            Some(child.upcast())
        });
    }
    // `window.close()`: with popups on, report it; the backend releases
    // the page on its next lookup.
    {
        let on = popups_on.clone();
        let me = me.clone();
        let popups = popups.clone();
        web_view.connect_close(move |_| {
            if let (true, Some(h)) = (on.get(), me.get()) {
                let mut s = popups.borrow_mut();
                s.closed.push(h);
                s.feed.push(crate::engine::PopupEvent::Closed(h));
            }
        });
    }
    // The web process died: report it.
    {
        let on = popups_on.clone();
        let me = me.clone();
        let popups = popups.clone();
        web_view.connect_web_process_terminated(move |_, _| {
            if let (true, Some(h)) = (on.get(), me.get()) {
                popups
                    .borrow_mut()
                    .feed
                    .push(crate::engine::PopupEvent::Crashed(h));
            }
        });
    }
    // `alert`/`confirm`/`prompt`: with popups on, report and hold for
    // an answer; otherwise dismiss at once, as on macOS.
    {
        let on = popups_on.clone();
        let me = me.clone();
        let popups = popups.clone();
        web_view.connect_script_dialog(move |_, dialog| match (on.get(), me.get()) {
            (true, Some(h)) => {
                let feed = popups.borrow().feed.clone();
                super::wpe_popups::hold_dialog(&feed, h, dialog)
            }
            _ => super::wpe_popups::dismiss_dialog(dialog),
        });
    }

    let downloads = SharedDownloads::default();
    let download_hook = install_download_capture(web_view, &downloads);
    let main_response = install_response_capture(web_view);
    WpePage {
        web_view: web_view.clone(),
        window,
        inspector,
        inspector_installed,
        cookie_baseline: std::cell::RefCell::new(None),
        cookie_next_seq: std::cell::RefCell::new(0),
        last_mouse: Cell::new(vs_humanize::Point { x: 0.0, y: 0.0 }),
        new_window,
        downloads,
        download_hook,
        main_response,
        popups_on,
        me,
        frames,
        origin: Cell::new((0.0, 0.0)),
    }
}

/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
/// per step at the path's prescribed timing. Returns the final point.
/// The `button_down` flag is unused on Linux today (XTest doesn't
/// distinguish drag-move from plain-move — both are `MotionNotify`
/// events; the held button state is tracked at the X server). Kept
/// in the signature so drag callers stay symmetric with the macOS
/// `move_along_path`.
fn cursor_move_along_path(
    dispatcher: &dyn super::wpe_input::InputDispatcher,
    start: vs_humanize::Point,
    end: vs_humanize::Point,
    origin: (f64, f64),
    mode: vs_humanize::InputMode,
    seed: u64,
    _button_down: bool,
) -> EngineResult<vs_humanize::Point> {
    let path = vs_humanize::mouse_path(start, end, mode, seed);
    let mut prev_ms: u128 = 0;
    for step in &path {
        if step.kind != vs_humanize::MouseStepKind::Move {
            continue;
        }
        let screen = super::wpe_input::ScreenPoint {
            #[allow(clippy::cast_possible_truncation)]
            x: (origin.0 + step.point.x).round() as i32,
            #[allow(clippy::cast_possible_truncation)]
            y: (origin.1 + step.point.y).round() as i32,
        };
        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
        let dt = step.at.as_millis().saturating_sub(prev_ms);
        if dt > 0 {
            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
        }
        prev_ms = step.at.as_millis();
    }
    // Final settling move ending exactly at `end`.
    let final_pt = super::wpe_input::ScreenPoint {
        #[allow(clippy::cast_possible_truncation)]
        x: (origin.0 + end.x).round() as i32,
        #[allow(clippy::cast_possible_truncation)]
        y: (origin.1 + end.y).round() as i32,
    };
    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
    dispatcher.flush()?;
    Ok(end)
}

/// Press-then-release left button at the current pointer position.
/// Same cadence as the macOS backend (robotic 2 ms / 6 ms, otherwise
/// 15 ms / 30 ms), so JS sees a coherent `click` event.
fn cursor_press_release(
    dispatcher: &dyn super::wpe_input::InputDispatcher,
    _at: vs_humanize::Point,
    _origin: (f64, f64),
    mode: vs_humanize::InputMode,
) -> EngineResult<()> {
    // Robotic input holds the button briefly, as on macOS; the other
    // modes keep a human press. The waits pump the main loop (a plain
    // sleep stalled GTK, which then saw the events only afterwards).
    let (down_ms, up_ms) = match mode {
        vs_humanize::InputMode::Robotic => (2, 6),
        _ => (15, 30),
    };
    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
        super::wpe_input::Button::Left,
    ))?;
    dispatcher.flush()?;
    let _ = run_loop_until(|| false, Duration::from_millis(down_ms));
    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
        super::wpe_input::Button::Left,
    ))?;
    dispatcher.flush()?;
    let _ = run_loop_until(|| false, Duration::from_millis(up_ms));
    Ok(())
}

fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
    let slot_for_cb = slot.clone();

    let cancellable = webkit6::gio::Cancellable::new();
    web_view.evaluate_javascript(
        js,
        None,
        None,
        Some(&cancellable),
        move |result| match result {
            Ok(value) => {
                let s = value.to_string();
                *slot_for_cb.borrow_mut() = Some(Ok(s));
            }
            Err(err) => {
                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
            }
        },
    );

    let slot_check = slot.clone();
    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
    if !ok {
        return Err(EngineError::Timeout {
            budget,
            primitive: "eval",
            detail: "",
        });
    }
    let result = slot.borrow_mut().take();
    match result {
        Some(Ok(s)) => Ok(s),
        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
        None => Err(EngineError::Other("eval completed without a result".into())),
    }
}

// =============================================================================
// Inspector capture wiring
// =============================================================================

/// Add the download-capture shim as a document-start script in every
/// frame. WebKitGTK does emit a `download-started` signal, but the
/// shim covers what that signal cannot see — an in-page `blob:` save
/// whose object URL is revoked a tick later — and keeps the capture
/// buffer identical across all three backends.
fn install_download_shim(web_view: &WebView) {
    let Some(manager) = web_view.user_content_manager() else {
        return;
    };
    manager.add_script(&UserScript::new(
        super::common::DOWNLOAD_SHIM_JS,
        UserContentInjectedFrames::AllFrames,
        UserScriptInjectionTime::Start,
        &[],
        &[],
    ));
    // No native drags (see NO_NATIVE_DRAG_JS).
    manager.add_script(&UserScript::new(
        super::common::NO_NATIVE_DRAG_JS,
        UserContentInjectedFrames::AllFrames,
        UserScriptInjectionTime::Start,
        &[],
        &[],
    ));
}

fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
    use super::inspector_bridge::{
        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
    };

    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
        return false;
    }

    let manager = web_view.user_content_manager().expect(
        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
    );

    let script = UserScript::new(
        inspector_bridge::SCRIPT,
        UserContentInjectedFrames::AllFrames,
        UserScriptInjectionTime::Start,
        &[],
        &[],
    );
    manager.add_script(&script);

    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
        return false;
    }
    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
        return false;
    }

    let console_slots: InspectorSlots = slots.clone();
    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
        let json = value.to_string();
        let mut buf = console_slots.console.borrow_mut();
        inspector_bridge::ingest_console(&mut buf, &json);
    });
    let network_slots: InspectorSlots = slots.clone();
    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
        let json = value.to_string();
        let mut entries = network_slots.network.borrow_mut();
        let mut details = network_slots.details.borrow_mut();
        let mut pending = network_slots.pending.borrow_mut();
        inspector_bridge::ingest_network(
            NetworkIngestSlot {
                entries: &mut entries,
                details: &mut details,
                pending: &mut pending,
            },
            &json,
        );
    });
    true
}

// =============================================================================
// Host-side cookie save/load via WebKitCookieManager
// =============================================================================
//
// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
// The v0.1.2 fix routes auth save/load through this path on every
// platform.
mod wpe_cookies {
    use std::cell::RefCell;
    use std::rc::Rc;
    use std::time::Duration;

    use webkit6::gio;
    use webkit6::glib;
    use webkit6::prelude::*;
    use webkit6::soup;
    use webkit6::WebView;

    use crate::backend::auth::CookieData;
    use crate::engine::{EngineError, EngineResult};

    use super::run_loop_until;

    const ASYNC_BUDGET: Duration = Duration::from_secs(5);

    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
        })?;
        session
            .cookie_manager()
            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
    }

    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
        let manager = cookie_manager(web_view)?;
        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
        let slot_cb = slot.clone();
        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
            let cookies = match result {
                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
                Err(_) => Vec::new(),
            };
            *slot_cb.borrow_mut() = Some(cookies);
        });
        let check = slot.clone();
        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
        if !ok {
            return Err(EngineError::Timeout {
                budget: ASYNC_BUDGET,
                primitive: "save_auth (all_cookies)",
                detail: "",
            });
        }
        let result = slot.borrow_mut().take().unwrap_or_default();
        Ok(result)
    }

    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
        let manager = cookie_manager(web_view)?;
        for c in cookies {
            if c.name.is_empty() || c.domain.is_empty() {
                continue;
            }
            let path = if c.path.is_empty() {
                "/"
            } else {
                c.path.as_str()
            };
            // max_age=-1: session cookie (no expiration). We set
            // expires explicitly below if the saved blob carried it.
            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
            cookie.set_secure(c.secure);
            cookie.set_http_only(c.http_only);
            if let Some(unix) = c.expires_unix {
                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
                    cookie.set_expires(&dt);
                }
            }
            if let Some(ss) = c.same_site.as_deref() {
                let policy = match ss {
                    "Strict" => soup::SameSitePolicy::Strict,
                    "None" => soup::SameSitePolicy::None,
                    _ => soup::SameSitePolicy::Lax,
                };
                cookie.set_same_site_policy(policy);
            }

            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
            let done_cb = done.clone();
            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
                *done_cb.borrow_mut() = true;
            });
            let check = done.clone();
            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
            if !ok {
                return Err(EngineError::Timeout {
                    budget: ASYNC_BUDGET,
                    primitive: "load_auth (add_cookie)",
                    detail: "",
                });
            }
        }
        Ok(())
    }

    /// Delete every cookie of the web view's network session.
    pub(super) fn delete_all(web_view: &WebView) -> EngineResult<()> {
        let manager = cookie_manager(web_view)?;
        let slot: Rc<RefCell<Option<Vec<soup::Cookie>>>> = Rc::new(RefCell::new(None));
        let slot_cb = slot.clone();
        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
            *slot_cb.borrow_mut() = Some(result.unwrap_or_default());
        });
        let check = slot.clone();
        if !run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET) {
            return Err(EngineError::Timeout {
                budget: ASYNC_BUDGET,
                primitive: "cookies clear (all_cookies)",
                detail: "",
            });
        }
        let all = slot.borrow_mut().take().unwrap_or_default();
        let left = Rc::new(RefCell::new(all.len()));
        for c in &all {
            let left_cb = left.clone();
            manager.delete_cookie(c, None::<&gio::Cancellable>, move |_| {
                *left_cb.borrow_mut() -= 1;
            });
        }
        let check = left.clone();
        if !run_loop_until(move || *check.borrow() == 0, ASYNC_BUDGET) {
            return Err(EngineError::Timeout {
                budget: ASYNC_BUDGET,
                primitive: "cookies clear (delete_cookie)",
                detail: "",
            });
        }
        Ok(())
    }

    fn serialize(c: &mut soup::Cookie) -> CookieData {
        CookieData {
            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
            expires_unix: c.expires().map(|dt| dt.to_unix()),
            secure: c.is_secure(),
            http_only: c.is_http_only(),
            same_site: match c.same_site_policy() {
                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
                soup::SameSitePolicy::None => Some("None".to_string()),
                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
                _ => None,
            },
        }
    }
}

/// A load that ended because its response became a download left the
/// page as it was and put the file in the download buffer. Not a
/// failure.
fn load_result(err: &glib::Error) -> Result<(), String> {
    if err.matches(webkit6::PolicyError::FrameLoadInterruptedByPolicyChange) {
        Ok(())
    } else {
        Err(err.message().to_string())
    }
}

/// Keep the HTTP response of each main-frame navigation.
///
/// `load-changed` fires for the main frame only. The slot is cleared
/// when a load starts, so a failed or non-HTTP load reports nothing,
/// and filled at commit, when the main resource has its response.
fn install_response_capture(
    web_view: &WebView,
) -> Rc<RefCell<Option<crate::inspector::MainResponse>>> {
    let slot: Rc<RefCell<Option<crate::inspector::MainResponse>>> = Rc::new(RefCell::new(None));
    let sink = slot.clone();
    web_view.connect_load_changed(move |view, event| match event {
        LoadEvent::Started => {
            sink.borrow_mut().take();
        }
        LoadEvent::Committed => {
            *sink.borrow_mut() = view
                .main_resource()
                .and_then(|r| r.response())
                .and_then(|r| http_response(&r));
        }
        _ => {}
    });
    slot
}

fn http_response(resp: &webkit6::URIResponse) -> Option<crate::inspector::MainResponse> {
    let url = resp.uri().map(|u| u.to_string()).unwrap_or_default();
    if !(url.starts_with("http:") || url.starts_with("https:")) {
        return None;
    }
    let status = u16::try_from(resp.status_code()).unwrap_or(0);
    if status == 0 {
        return None;
    }
    let mut headers = Vec::new();
    if let Some(h) = resp.http_headers() {
        h.foreach(|name, value| headers.push((name.to_ascii_lowercase(), value.to_string())));
    }
    Some(crate::inspector::MainResponse {
        url,
        status,
        status_text: crate::inspector::reason_phrase(status).to_string(),
        headers,
    })
}

/// Save attachments instead of dropping them.
///
/// A `Content-Disposition: attachment` response (an export button, a
/// form POST answering with a file, a hidden-iframe download) never
/// reaches page script. Turn it into a WebKit download, write it to a
/// temp file, and move the bytes into `downloads` for `vs_download`.
/// The network session is shared by every page of the same store, so
/// the `download-started` handler checks the download belongs to this
/// one.
fn install_download_capture(
    web_view: &WebView,
    downloads: &SharedDownloads,
) -> Option<(webkit6::NetworkSession, glib::SignalHandlerId)> {
    web_view.connect_decide_policy(|_view, decision, ty| {
        if ty != webkit6::PolicyDecisionType::Response {
            return false;
        }
        let Some(rd) = decision.downcast_ref::<webkit6::ResponsePolicyDecision>() else {
            return false;
        };
        let Some(resp) = rd.response() else {
            return false;
        };
        let uri = resp.uri().map(|u| u.to_string()).unwrap_or_default();
        if !(uri.starts_with("http:") || uri.starts_with("https:")) {
            return false;
        }
        let cd = resp
            .http_headers()
            .and_then(|h| h.one("Content-Disposition"))
            .map(|v| v.to_string())
            .unwrap_or_default();
        if is_attachment(&cd) || !rd.is_mime_type_supported() {
            decision.download();
            return true;
        }
        false
    });

    let session = WebViewExt::network_session(web_view)?;
    let weak = web_view.downgrade();
    let downloads = downloads.clone();
    let id = session.connect_download_started(move |_session, download| {
        let Some(view) = weak.upgrade() else { return };
        if download.web_view().as_ref() != Some(&view) {
            return;
        }
        let resp = download.response();
        let url = resp
            .as_ref()
            .and_then(webkit6::URIResponse::uri)
            .or_else(|| download.request().and_then(|r| r.uri()))
            .map(|u| u.to_string())
            .unwrap_or_default();
        let mime = resp
            .as_ref()
            .and_then(webkit6::URIResponse::mime_type)
            .map(|m| m.to_string())
            .unwrap_or_default();
        let name = resp
            .as_ref()
            .and_then(webkit6::URIResponse::http_headers)
            .and_then(|h| h.one("Content-Disposition"))
            .and_then(|cd| name_from_disposition(&cd))
            .unwrap_or_default();
        let Ok(id) = downloads.lock().map(|mut d| d.begin(&url, &name, &mime)) else {
            return;
        };
        let path = temp_path(id);
        let _ = std::fs::remove_file(&path);

        let dl = downloads.clone();
        download.connect_decide_destination(move |download, suggested| {
            if let Ok(mut d) = dl.lock() {
                if name.is_empty() {
                    d.set_name(id, suggested);
                }
            }
            let expected = download.response().map_or(0, |r| r.content_length());
            if expected > MAX_BYTES {
                if let Ok(mut d) = dl.lock() {
                    d.finish(
                        id,
                        Err(format!("download exceeds {MAX_BYTES} bytes ({expected})")),
                    );
                }
                download.cancel();
                return true;
            }
            download.set_destination(&path.to_string_lossy());
            true
        });
        let dl = downloads.clone();
        download.connect_failed(move |_download, err| {
            if let Ok(mut d) = dl.lock() {
                d.finish(id, Err(err.message().to_string()));
            }
            let _ = std::fs::remove_file(temp_path(id));
        });
        let dl = downloads.clone();
        download.connect_finished(move |_download| {
            let path = temp_path(id);
            // `failed` is followed by `finished`; the first result wins.
            let bytes = std::fs::read(&path).map_err(|e| format!("read {}: {e}", path.display()));
            let _ = std::fs::remove_file(&path);
            if let Ok(mut d) = dl.lock() {
                d.finish(id, bytes);
            }
        });
    });
    Some((session, id))
}

/// Wait for the load already started on `web_view` to finish or fail.
fn wait_for_load(web_view: &WebView, primitive: &'static str) -> EngineResult<()> {
    let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
    let slot_for_signal = slot.clone();
    let signal_id = web_view.connect_load_changed(move |_view, event| {
        if event == LoadEvent::Finished {
            *slot_for_signal.borrow_mut() = Some(Ok(()));
        }
    });
    let slot_fail = slot.clone();
    let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
        *slot_fail.borrow_mut() = Some(load_result(err));
        true
    });

    let slot_check = slot.clone();
    let budget = super::common::nav_budget();
    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);

    web_view.disconnect(signal_id);
    web_view.disconnect(fail_id);

    if !ok {
        return Err(EngineError::Timeout {
            budget,
            primitive,
            detail: "",
        });
    }
    // Taken out of the RefCell before the match, not inside it:
    // as the function's tail expression the borrow guard would
    // otherwise outlive `slot` itself.
    let result = slot.borrow_mut().take();
    match result {
        Some(Ok(())) => Ok(()),
        Some(Err(msg)) => Err(EngineError::Other(format!("navigation failed: {msg}"))),
        None => Err(EngineError::Other(
            "navigation completed without a result".into(),
        )),
    }
}

impl WpeBackend {
    /// Drop a new-window request parked before this input primitive
    /// started (a popup the page fired on its own), so the primitive
    /// only follows what it caused.
    fn forget_new_window(&mut self, page: PageHandle) -> EngineResult<()> {
        let _ = self.page_mut(page)?.new_window.borrow_mut().take();
        let mut s = self.popups.borrow_mut();
        s.raised_at_input = s.feed.raised();
        Ok(())
    }

    /// Load a new-window navigation the last input primitive caused, in
    /// this page, and wait for it like `goto`. The `create` signal can
    /// arrive after the click returns, so after a click (`settle`) pump
    /// for up to `NEW_WINDOW_SETTLE` first. No parked request: no-op.
    fn follow_new_window(&mut self, page: PageHandle, settle: bool) -> EngineResult<()> {
        let popups = self.popups.clone();
        let p = self.page_mut(page)?;
        if settle && p.new_window.borrow().is_none() {
            let hint = eval_js_string(
                &p.web_view,
                super::common::NEW_WINDOW_HINT_JS,
                Duration::from_secs(2),
            );
            if super::common::new_window_hinted(&hint) {
                if p.popups_on.get() {
                    // A real window: wait for WebKit to ask for it, so
                    // the popup exists when the click returns.
                    let (feed, before) = {
                        let s = popups.borrow();
                        (s.feed.clone(), s.raised_at_input)
                    };
                    let _ = run_loop_until(
                        move || feed.raised() > before,
                        super::common::NEW_WINDOW_SETTLE,
                    );
                    return Ok(());
                }
                let parked = p.new_window.clone();
                let _ = run_loop_until(
                    move || parked.borrow().is_some(),
                    super::common::NEW_WINDOW_SETTLE,
                );
            }
        }
        let Some(request) = p.new_window.borrow_mut().take() else {
            return Ok(());
        };
        let web_view = p.web_view.clone();
        web_view.load_request(&request);
        wait_for_load(&web_view, "act")
    }
}