Skip to main content

vs_engine_webkit/backend/
wpe.rs

1//! Linux backend — real `WebKitGTK 6` driven via `webkit6` + `glib`.
2//!
3//! # Threading model
4//!
5//! WebKitGTK is bound to the GLib main context of the thread that
6//! initialized GTK. Methods on [`WpeBackend`] must be called from that
7//! thread; the type is `!Send`. Production wiring (follow-up):
8//! `vs-cli::serve` on Linux must put GTK on the OS main thread and
9//! dispatch engine calls there via `MainContext::invoke`.
10//!
11//! # Status
12//!
13//! Real WebKitGTK-backed implementation of every primitive on the
14//! [`Engine`] trait: open / close / snapshot / act / wait / layout /
15//! set_viewport / save_auth / load_auth — plus inspector capture
16//! (console + network) wired through the `UserContentManager` script-
17//! message bridge. `capture` is the only outstanding piece (a TODO in
18//! a follow-up that calls `WebView::snapshot`).
19//!
20//! Verified on Linux CI with `libwebkitgtk-6.0-dev` + `libgtk-4-dev`
21//! installed; this file is not built on macOS.
22
23use std::cell::{Cell, RefCell};
24use std::collections::HashMap;
25use std::path::PathBuf;
26use std::rc::Rc;
27use std::time::Duration;
28
29use glib::prelude::*;
30// `gtk4` is a direct dep so we can enable its `v4_10` feature (webkit6
31// needs `gtk::Accessible`); alias it to `gtk` to keep the existing refs.
32use gtk4 as gtk;
33use webkit6::prelude::*;
34use webkit6::{LoadEvent, UserContentInjectedFrames, UserScript, UserScriptInjectionTime, WebView};
35
36use vs_protocol::{Ref, Tree};
37
38use crate::engine::{
39    ActTarget, Action, AuthBlob, CaptureScope, CursorOp, Download, DownloadEntry, DownloadSource,
40    Engine, EngineCapabilities, EngineError, EngineResult, InputMode, LayoutBox, PageHandle,
41    Viewport, WaitCondition,
42};
43
44// =============================================================================
45// Per-page state
46// =============================================================================
47
48struct WpePage {
49    web_view: WebView,
50    /// Hidden host window that owns `web_view` as its single child.
51    /// Required so the WebView has a `GdkSurface` on the X display —
52    /// without it XTest's synthetic input has no window to land on.
53    /// Created in `open()`, dropped on `close()`.
54    window: gtk::Window,
55    inspector: super::inspector_bridge::InspectorSlots,
56    /// True if the inspector install path actually succeeded for this
57    /// page (script + handlers registered without bail). Read by
58    /// `Engine::capabilities()` and the daemon `vs_inspect` gate.
59    inspector_installed: bool,
60    cookie_baseline: std::cell::RefCell<Option<Vec<super::auth::CookieData>>>,
61    cookie_next_seq: std::cell::RefCell<u64>,
62    /// Last known cursor position in screen-absolute CSS px. Updated
63    /// after every `cursor_op` so the next humanized lead-in starts
64    /// where the previous one ended. Defaults to (0, 0) on `open`.
65    last_mouse: Cell<vs_humanize::Point>,
66    /// A new-window navigation (`target="_blank"`, `window.open()`)
67    /// the page asked for and we have not loaded yet. Set by the
68    /// `create` handler installed in `open`.
69    new_window: Rc<RefCell<Option<webkit6::URIRequest>>>,
70    /// Downloads this page's responses turned into.
71    downloads: SharedDownloads,
72    /// The shared network session's `download-started` handler for
73    /// this page. Disconnected on close.
74    download_hook: Option<(webkit6::NetworkSession, glib::SignalHandlerId)>,
75}
76
77// =============================================================================
78// Backend
79// =============================================================================
80
81/// Real WebKitGTK 6 backend. Construct on the GTK main thread; all
82/// subsequent calls must come from the same thread.
83pub struct WpeBackend {
84    pages: HashMap<PageHandle, WpePage>,
85    next_handle: u64,
86    captures_dir: Option<PathBuf>,
87}
88
89impl Default for WpeBackend {
90    fn default() -> Self {
91        Self::new()
92    }
93}
94
95impl WpeBackend {
96    /// Build a backend. Caller must already have initialized GTK on
97    /// this thread (via `gtk4::init()`); production wiring lives in
98    /// `vs-cli::serve` on Linux. Constructing on a non-GTK thread will
99    /// panic the first time a `WebView` operation runs.
100    #[must_use]
101    pub fn new() -> Self {
102        Self {
103            pages: HashMap::new(),
104            next_handle: 1,
105            captures_dir: None,
106        }
107    }
108
109    /// Pin the directory where `capture` writes PNGs. Defaults to a
110    /// system temp subdirectory.
111    #[must_use]
112    pub fn with_capture_dir(mut self, dir: impl Into<PathBuf>) -> Self {
113        self.captures_dir = Some(dir.into());
114        self
115    }
116
117    fn alloc_handle(&mut self) -> PageHandle {
118        let h = PageHandle(self.next_handle);
119        self.next_handle += 1;
120        h
121    }
122
123    fn page_mut(&mut self, h: PageHandle) -> EngineResult<&mut WpePage> {
124        self.pages.get_mut(&h).ok_or(EngineError::NotFound {
125            kind: "page",
126            id: h.0.to_string(),
127        })
128    }
129}
130
131// =============================================================================
132// Run-loop helper: pump the GLib main context until a predicate fires
133// =============================================================================
134
135fn run_loop_until<F: FnMut() -> bool>(mut done: F, budget: Duration) -> bool {
136    let main_ctx = glib::MainContext::default();
137    let deadline = std::time::Instant::now() + budget;
138    while std::time::Instant::now() < deadline {
139        if done() {
140            return true;
141        }
142        // Iterate non-blocking; if no work, sleep briefly.
143        if !main_ctx.iteration(false) {
144            std::thread::sleep(Duration::from_millis(10));
145        }
146    }
147    done()
148}
149
150// =============================================================================
151// Shared payloads + parsers
152// =============================================================================
153
154use super::common::{parse_snapshot, SNAPSHOT_DOM_WALKER_JS as SNAPSHOT_JS};
155use super::native_download::{
156    is_attachment, name_from_disposition, temp_path, SharedDownloads, MAX_BYTES,
157};
158
159// =============================================================================
160// Engine impl
161// =============================================================================
162
163impl Engine for WpeBackend {
164    fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
165        let web_view = WebView::new();
166
167        // Hidden host window for the WebView. v0.1.11 added native
168        // input dispatch (XTest / libei) for the cursor primitives;
169        // both require the WebView to have a real `GdkSurface` on the
170        // display server so the synthetic event has somewhere to land.
171        // `WebView::new()` alone renders to an internal offscreen
172        // surface with no display-server window — XTest events would
173        // disappear into the void. Wrapping each WebView in a
174        // decorated-off `gtk::Window` and presenting it gives us that
175        // surface; under `xvfb` (CI) the window has no visual effect.
176        let window = gtk::Window::new();
177        window.set_decorated(false);
178        window.set_default_size(1280, 800);
179        window.set_child(Some(&web_view));
180        window.present();
181
182        // Pin the User-Agent to a current Safari string so anti-bot
183        // fingerprinters don't flag the WebKitGTK default. See the
184        // commit log for `crate::engine::DEFAULT_USER_AGENT` rationale.
185        if let Some(settings) = WebViewExt::settings(&web_view) {
186            settings.set_user_agent(Some(crate::engine::DEFAULT_USER_AGENT));
187            // Expose `navigator.mediaDevices`. WebKitGTK gates the
188            // MediaDevices surface off by default, so the object is
189            // simply absent and anything feature-detecting camera or
190            // mic support sees a browser that cannot exist. The macOS
191            // backend needed the same switch (there via a WKPreferences
192            // KVC key); here it is public API.
193            settings.set_enable_media_stream(true);
194        }
195
196        // Inspector capture wiring — install the user script + register
197        // both message channels BEFORE load_uri so the bridge is live
198        // by document-start.
199        let inspector =
200            super::inspector_bridge::InspectorSlots::new(crate::inspector::DEFAULT_BUFFER_CAPACITY);
201        let inspector_installed = install_inspector(&web_view, &inspector);
202        install_download_shim(&web_view);
203        // A headless page has no second window. Without a `create`
204        // handler WebKitGTK drops a `target="_blank"` link or form, or
205        // `window.open()`, and the click does nothing. Park the request;
206        // the input primitive that caused it loads it in this page
207        // (`follow_new_window`). `act click` on this engine is a JS
208        // click, not a user gesture, so blank-target navigation also
209        // has to be allowed without one.
210        if let Some(settings) = WebViewExt::settings(&web_view) {
211            settings.set_javascript_can_open_windows_automatically(true);
212        }
213        let new_window: Rc<RefCell<Option<webkit6::URIRequest>>> = Rc::new(RefCell::new(None));
214        let parked = new_window.clone();
215        web_view.connect_create(move |_view, action| {
216            *parked.borrow_mut() = action.request();
217            None
218        });
219        let downloads = SharedDownloads::default();
220        let download_hook = install_download_capture(&web_view, &downloads);
221        web_view.load_uri(url);
222
223        // Wait for LoadEvent::Finished or LoadEvent::Failed via signal.
224        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
225        let slot_for_signal = slot.clone();
226        let signal_id = web_view.connect_load_changed(move |_view, event| {
227            if event == LoadEvent::Finished {
228                *slot_for_signal.borrow_mut() = Some(Ok(()));
229            }
230        });
231        let slot_fail = slot.clone();
232        let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
233            *slot_fail.borrow_mut() = Some(load_result(err));
234            // Stop event propagation: we have handled it.
235            true
236        });
237
238        let slot_check = slot.clone();
239        let budget = super::common::nav_budget();
240        let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
241
242        // Disconnect signal handlers — the WebView outlives this scope.
243        web_view.disconnect(signal_id);
244        web_view.disconnect(fail_id);
245
246        if !ok {
247            return Err(EngineError::Timeout {
248                budget,
249                primitive: "open",
250                detail: "",
251            });
252        }
253        match slot.borrow_mut().take() {
254            Some(Ok(())) => {}
255            Some(Err(msg)) => return Err(EngineError::Other(format!("navigation failed: {msg}"))),
256            None => {
257                return Err(EngineError::Other(
258                    "navigation completed without a result".into(),
259                ))
260            }
261        }
262
263        let handle = self.alloc_handle();
264        self.pages.insert(
265            handle,
266            WpePage {
267                web_view,
268                window,
269                inspector,
270                inspector_installed,
271                cookie_baseline: std::cell::RefCell::new(None),
272                cookie_next_seq: std::cell::RefCell::new(0),
273                last_mouse: Cell::new(vs_humanize::Point { x: 0.0, y: 0.0 }),
274                new_window,
275                downloads,
276                download_hook,
277            },
278        );
279        Ok(handle)
280    }
281
282    fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()> {
283        // Same wait as `open`, on a WebView that already exists. The
284        // inspector bridge and download shim were installed at
285        // document-start and survive the navigation, so this only has
286        // to load and wait.
287        let web_view = self.page_mut(page)?.web_view.clone();
288        web_view.load_uri(url);
289        wait_for_load(&web_view, "navigate")
290    }
291
292    fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
293        Err(EngineError::NotImplemented {
294            engine: "wpe",
295            primitive: "enable_webauthn",
296        })
297    }
298
299    fn close(&mut self, page: PageHandle) -> EngineResult<()> {
300        if let Some(mut p) = self.pages.remove(&page) {
301            if let Some((session, id)) = p.download_hook.take() {
302                session.disconnect(id);
303            }
304            // Dismiss the hidden host window so its `GdkSurface` is
305            // unmapped from the display server. `close()` queues the
306            // destroy; the GLib main context completes it on the next
307            // iteration.
308            p.window.close();
309        }
310        Ok(())
311    }
312
313    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree> {
314        let p = self.page_mut(page)?;
315        let json = eval_js_string(&p.web_view, SNAPSHOT_JS, Duration::from_secs(5))?;
316        parse_snapshot(&json).map_err(EngineError::Other)
317    }
318
319    fn act(
320        &mut self,
321        page: PageHandle,
322        target: ActTarget,
323        action: Action,
324        _mode: InputMode,
325    ) -> EngineResult<()> {
326        self.forget_new_window(page)?;
327        let p = self.page_mut(page)?;
328        let web_view = p.web_view.clone();
329        super::common::run_act(
330            move |js, budget| eval_js_string(&web_view, js, budget),
331            &target,
332            &action,
333        )?;
334        self.follow_new_window(page, super::common::may_open_window(&action))
335    }
336
337    fn wait(
338        &mut self,
339        page: PageHandle,
340        cond: WaitCondition,
341        budget: Duration,
342    ) -> EngineResult<()> {
343        let p = self.page_mut(page)?;
344        let web_view = p.web_view.clone();
345        super::common::run_wait(
346            |js, budget| eval_js_string(&web_view, js, budget),
347            &cond,
348            budget,
349            || {
350                let _ = run_loop_until(|| false, Duration::from_millis(50));
351            },
352        )
353    }
354    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
355        let p = self.page_mut(page)?;
356        let web_view = p.web_view.clone();
357        super::common::run_layout(
358            move |js, budget| eval_js_string(&web_view, js, budget),
359            refs,
360        )
361    }
362
363    fn download(
364        &mut self,
365        page: PageHandle,
366        source: DownloadSource,
367        budget: Duration,
368    ) -> EngineResult<Download> {
369        let p = self.page_mut(page)?;
370        let web_view = p.web_view.clone();
371        let native = p.downloads.clone();
372        super::common::run_download(
373            |js, budget| eval_js_string(&web_view, js, budget),
374            || {
375                let _ = run_loop_until(|| false, Duration::from_millis(50));
376            },
377            &source,
378            budget,
379            &native,
380        )
381    }
382
383    fn download_list(&mut self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
384        let p = self.page_mut(page)?;
385        let web_view = p.web_view.clone();
386        let native = p.downloads.clone();
387        super::common::run_download_list(
388            move |js, budget| eval_js_string(&web_view, js, budget),
389            &native,
390        )
391    }
392    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
393        let p = self.page_mut(page)?;
394        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
395        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
396        // The host `gtk::Window` constrains its child WebView's
397        // allocation, so resizing the WebView via `set_size_request`
398        // alone is shadowed by the (1280x800) host. Resize both: the
399        // window's default size for the surface, and the WebView's
400        // size request so its render target matches the requested
401        // viewport.
402        p.window.set_default_size(w, h);
403        p.web_view.set_size_request(w, h);
404        Ok(())
405    }
406
407    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
408        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
409        let _ = std::fs::create_dir_all(&captures_dir);
410        let path = captures_dir.join(format!("capture-{}.png", page.0));
411        let p = self.page_mut(page)?;
412        let web_view = p.web_view.clone();
413        let out_path = path.clone();
414
415        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
416        let slot_for_cb = slot.clone();
417        web_view.snapshot(
418            webkit6::SnapshotRegion::FullDocument,
419            webkit6::SnapshotOptions::NONE,
420            None::<&webkit6::gio::Cancellable>,
421            move |result| {
422                *slot_for_cb.borrow_mut() = Some(match result {
423                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
424                    Err(e) => Err(e.to_string()),
425                });
426            },
427        );
428
429        let slot_check = slot.clone();
430        let ok = run_loop_until(
431            move || slot_check.borrow().is_some(),
432            Duration::from_secs(10),
433        );
434        if !ok {
435            return Err(EngineError::Timeout {
436                budget: Duration::from_secs(10),
437                primitive: "capture",
438                detail: "",
439            });
440        }
441        let result = slot.borrow_mut().take();
442        match result {
443            Some(Ok(())) => Ok(path),
444            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
445            None => Err(EngineError::Other(
446                "capture completed without a result".into(),
447            )),
448        }
449    }
450
451    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
452        let p = self.page_mut(page)?;
453        let web_view = p.web_view.clone();
454        // Cookies: host-side via CookieManager so HttpOnly entries
455        // are captured. localStorage/sessionStorage: JS shim.
456        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
457        let storage = super::common::run_save_storage_only(
458            move |js, budget| eval_js_string(&web_view, js, budget),
459            || {
460                let _ = run_loop_until(|| false, Duration::from_millis(50));
461            },
462        )?;
463        let blob = super::auth::AuthBlobV2 {
464            version: 2,
465            url: storage.url,
466            origin: storage.origin,
467            cookies,
468            local_storage: storage.local_storage,
469            indexed_db: storage.indexed_db,
470            indexed_db_skipped: storage.indexed_db_skipped,
471            indexed_db_incomplete: storage.indexed_db_incomplete,
472            session_storage: storage.session_storage,
473        };
474        super::auth::encode(&blob)
475    }
476
477    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
478        let p = self.page_mut(page)?;
479        let web_view = p.web_view.clone();
480        let parsed = super::auth::decode(blob)?;
481        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
482        super::common::run_load_storage_only(
483            move |js, budget| eval_js_string(&web_view, js, budget),
484            &parsed.local_storage,
485            &parsed.session_storage,
486            &parsed.indexed_db,
487            || {
488                let _ = run_loop_until(|| false, Duration::from_millis(50));
489            },
490        )
491    }
492
493    fn console_entries(
494        &mut self,
495        page: PageHandle,
496    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
497        let p = self.page_mut(page)?;
498        Ok(p.inspector.console.borrow().snapshot())
499    }
500
501    fn network_entries(
502        &mut self,
503        page: PageHandle,
504    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
505        let p = self.page_mut(page)?;
506        Ok(p.inspector.network.borrow().snapshot())
507    }
508
509    fn request_detail(
510        &mut self,
511        page: PageHandle,
512        seq: u64,
513    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
514        let p = self.page_mut(page)?;
515        Ok(p.inspector.details.borrow().get(seq).cloned())
516    }
517
518    fn eval_js(
519        &mut self,
520        page: PageHandle,
521        expr: &str,
522    ) -> EngineResult<crate::inspector::EvalResult> {
523        let p = self.page_mut(page)?;
524        let web_view = p.web_view.clone();
525        super::common::run_eval(
526            move |js, budget| eval_js_string(&web_view, js, budget),
527            expr,
528        )
529    }
530
531    fn storage(
532        &mut self,
533        page: PageHandle,
534        scope: crate::inspector::StorageScope,
535    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
536        let p = self.page_mut(page)?;
537        let web_view = p.web_view.clone();
538        if matches!(scope, crate::inspector::StorageScope::Cookies) {
539            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
540            return Ok(cookies
541                .iter()
542                .map(super::common::cookie_to_storage_entry)
543                .collect());
544        }
545        super::common::run_storage(
546            move |js, budget| eval_js_string(&web_view, js, budget),
547            scope,
548        )
549    }
550
551    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
552        let p = self.page_mut(page)?;
553        let web_view = p.web_view.clone();
554        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
555    }
556
557    fn script_source(
558        &mut self,
559        page: PageHandle,
560        seq: u64,
561    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
562        let p = self.page_mut(page)?;
563        let web_view = p.web_view.clone();
564        super::common::run_script_source(
565            move |js, budget| eval_js_string(&web_view, js, budget),
566            seq,
567        )
568    }
569
570    fn dom(
571        &mut self,
572        page: PageHandle,
573        r: Ref,
574        extra_props: &[String],
575    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
576        let p = self.page_mut(page)?;
577        let web_view = p.web_view.clone();
578        super::common::run_dom(
579            move |js, budget| eval_js_string(&web_view, js, budget),
580            r,
581            extra_props,
582        )
583    }
584
585    fn performance(
586        &mut self,
587        page: PageHandle,
588    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
589        let p = self.page_mut(page)?;
590        let web_view = p.web_view.clone();
591        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
592    }
593
594    fn cookie_events(
595        &mut self,
596        page: PageHandle,
597    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
598        let p = self.page_mut(page)?;
599        let web_view = p.web_view.clone();
600        let current = wpe_cookies::get_all_cookies(&web_view)?;
601        let previous = p.cookie_baseline.borrow().clone();
602        let mut seq = p.cookie_next_seq.borrow_mut();
603        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
604        *p.cookie_baseline.borrow_mut() = Some(current);
605        Ok(events)
606    }
607
608    fn type_text(&mut self, page: PageHandle, text: &str, mode: InputMode) -> EngineResult<()> {
609        // Addressing the page validates it and keeps the error shape
610        // the same as every other page op, even though the keys go to
611        // whatever holds focus rather than to a page handle.
612        self.forget_new_window(page)?;
613        let cursor = self.page_mut(page)?.last_mouse.get();
614        let dispatcher = super::wpe_input::dispatcher()?;
615        // Pump GLib rather than sleep: this runs on the main thread,
616        // so a plain sleep would stop WebKit processing the very keys
617        // we are sending.
618        let settle = |d: Duration| {
619            let _ = run_loop_until(|| false, d);
620        };
621        // Put the pointer where we believe it already is before asking
622        // for focus. X hands keys to the focused window, and a
623        // headless session has no window manager to focus anything, so
624        // the pointer is what we have to go on. The caller has
625        // normally just clicked to place the caret, which means the
626        // right window is already under it.
627        #[allow(clippy::cast_possible_truncation)]
628        let at = super::wpe_input::ScreenPoint {
629            x: cursor.x as i32,
630            y: cursor.y as i32,
631        };
632        let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(at));
633        let _ = dispatcher.flush();
634        dispatcher.focus_pointer_window();
635
636        let (base_delay, span) = match mode {
637            InputMode::Robotic => (0_u64, 0_u64),
638            InputMode::Careful => (120, 0),
639            // ±40% of base, so repeated typing is not metronomic.
640            InputMode::Human => (45, 18),
641        };
642        let mut jitter = text
643            .chars()
644            .map(|c| c as u64)
645            .fold(0x9e37_79b9_u64, |a, c| a.wrapping_mul(31).wrapping_add(c))
646            | 1;
647
648        let typed = (|| -> EngineResult<()> {
649            for ch in text.chars() {
650                let hold = if base_delay == 0 { 1 } else { base_delay / 3 };
651                dispatcher.key_down(ch, &settle)?;
652                settle(Duration::from_millis(hold.max(1)));
653                dispatcher.key_up(ch)?;
654                if base_delay > 0 {
655                    jitter ^= jitter << 13;
656                    jitter ^= jitter >> 7;
657                    jitter ^= jitter << 17;
658                    let extra = if span == 0 {
659                        0
660                    } else {
661                        jitter % (span * 2 + 1)
662                    };
663                    let wait = base_delay.saturating_sub(span).saturating_add(extra);
664                    settle(Duration::from_millis(wait.max(1)));
665                } else {
666                    settle(Duration::from_millis(1));
667                }
668            }
669            Ok(())
670        })();
671
672        // Give the borrowed keycode back whether the run finished or
673        // failed halfway: a stray binding would change what the user's
674        // own keyboard does for the rest of the session.
675        let restored = dispatcher.end_typing();
676        typed?;
677        restored?;
678
679        // Let the last keyUp turn into beforeinput/input before the
680        // caller reads the page back.
681        let _ = run_loop_until(|| false, Duration::from_millis(150));
682        self.follow_new_window(page, false)
683    }
684
685    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
686        self.forget_new_window(page)?;
687        let p = self.page_mut(page)?;
688        let dispatcher = super::wpe_input::dispatcher()?;
689        let humanize_mode = match mode {
690            InputMode::Human => vs_humanize::InputMode::Human,
691            InputMode::Careful => vs_humanize::InputMode::Careful,
692            InputMode::Robotic => vs_humanize::InputMode::Robotic,
693        };
694        // Screen origin of the hidden host window. v0.1.11 assumes
695        // (0, 0) — true under `xvfb` (CI) and any session without a
696        // window manager. With a WM, the WM may have translated the
697        // window elsewhere; a follow-up PR will query
698        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
699        // real origin. Until then, page-local CSS px == screen px,
700        // which is fine for CI and most headless setups.
701        let (origin_x, origin_y) = (0.0_f64, 0.0_f64);
702        let start = p.last_mouse.get();
703        let seed = humanize_seed(op);
704        let landed = match op {
705            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => cursor_move_along_path(
706                dispatcher,
707                start,
708                vs_humanize::Point { x, y },
709                (origin_x, origin_y),
710                humanize_mode,
711                seed,
712                false,
713            )?,
714            CursorOp::ClickAt { x, y } => {
715                let landed = cursor_move_along_path(
716                    dispatcher,
717                    start,
718                    vs_humanize::Point { x, y },
719                    (origin_x, origin_y),
720                    humanize_mode,
721                    seed,
722                    false,
723                )?;
724                cursor_press_release(dispatcher, landed, (origin_x, origin_y))?;
725                landed
726            }
727            CursorOp::Drag { x1, y1, x2, y2 } => {
728                let start_pt = vs_humanize::Point { x: x1, y: y1 };
729                let target = vs_humanize::Point { x: x2, y: y2 };
730                let pre = cursor_move_along_path(
731                    dispatcher,
732                    start,
733                    start_pt,
734                    (origin_x, origin_y),
735                    humanize_mode,
736                    seed,
737                    false,
738                )?;
739                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
740                    super::wpe_input::Button::Left,
741                ))?;
742                std::thread::sleep(Duration::from_millis(15));
743                let landed = cursor_move_along_path(
744                    dispatcher,
745                    pre,
746                    target,
747                    (origin_x, origin_y),
748                    humanize_mode,
749                    seed,
750                    true,
751                )?;
752                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
753                    super::wpe_input::Button::Left,
754                ))?;
755                dispatcher.flush()?;
756                // After the OS-level drag, fire the HTML5 DragEvent
757                // chain in JS so react-dnd / React-Flow HTML5 targets
758                // observe the drop.
759                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
760                let web_view = p.web_view.clone();
761                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
762                landed
763            }
764        };
765        p.last_mouse.set(landed);
766        self.follow_new_window(page, matches!(op, CursorOp::ClickAt { .. }))
767    }
768
769    fn capabilities(&self) -> EngineCapabilities {
770        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
771        EngineCapabilities {
772            renders: true,
773            honors_viewport: true,
774            measures_layout: true,
775            persists_auth: true,
776            inspector_console: any_inspector,
777            inspector_network: any_inspector,
778            inspector_cookie_events: true,
779            name: "wpe",
780            version: "Linux WebKitGTK 6 (webkit6)",
781        }
782    }
783}
784
785// =============================================================================
786// JS evaluation helper
787// =============================================================================
788
789// =============================================================================
790// Cursor primitive helpers (XTest / libei input dispatch)
791// =============================================================================
792
793/// Deterministic seed for the humanize Bezier path so the same
794/// `cursor_op` invocation produces the same trajectory on every run.
795fn humanize_seed(op: CursorOp) -> u64 {
796    // Hash the op's coordinates into a u64. Trivial mixer; replays
797    // need determinism, not cryptographic spread.
798    let (a, b, c, d) = match op {
799        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
800            (x, y, 0.0, 0.0)
801        }
802        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
803    };
804    let bits = |v: f64| v.to_bits();
805    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
806        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
807        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
808        ^ bits(d)
809}
810
811/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
812/// per step at the path's prescribed timing. Returns the final point.
813/// The `button_down` flag is unused on Linux today (XTest doesn't
814/// distinguish drag-move from plain-move — both are `MotionNotify`
815/// events; the held button state is tracked at the X server). Kept
816/// in the signature so drag callers stay symmetric with the macOS
817/// `move_along_path`.
818fn cursor_move_along_path(
819    dispatcher: &dyn super::wpe_input::InputDispatcher,
820    start: vs_humanize::Point,
821    end: vs_humanize::Point,
822    origin: (f64, f64),
823    mode: vs_humanize::InputMode,
824    seed: u64,
825    _button_down: bool,
826) -> EngineResult<vs_humanize::Point> {
827    let path = vs_humanize::mouse_path(start, end, mode, seed);
828    let mut prev_ms: u128 = 0;
829    for step in &path {
830        if step.kind != vs_humanize::MouseStepKind::Move {
831            continue;
832        }
833        let screen = super::wpe_input::ScreenPoint {
834            #[allow(clippy::cast_possible_truncation)]
835            x: (origin.0 + step.point.x).round() as i32,
836            #[allow(clippy::cast_possible_truncation)]
837            y: (origin.1 + step.point.y).round() as i32,
838        };
839        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
840        let dt = step.at.as_millis().saturating_sub(prev_ms);
841        if dt > 0 {
842            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
843        }
844        prev_ms = step.at.as_millis();
845    }
846    // Final settling move ending exactly at `end`.
847    let final_pt = super::wpe_input::ScreenPoint {
848        #[allow(clippy::cast_possible_truncation)]
849        x: (origin.0 + end.x).round() as i32,
850        #[allow(clippy::cast_possible_truncation)]
851        y: (origin.1 + end.y).round() as i32,
852    };
853    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
854    dispatcher.flush()?;
855    Ok(end)
856}
857
858/// Press-then-release left button at the current pointer position.
859/// Matches the `mouseDown` / 15 ms / `mouseUp` cadence the macOS
860/// backend uses so JS sees a coherent `click` event.
861fn cursor_press_release(
862    dispatcher: &dyn super::wpe_input::InputDispatcher,
863    _at: vs_humanize::Point,
864    _origin: (f64, f64),
865) -> EngineResult<()> {
866    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
867        super::wpe_input::Button::Left,
868    ))?;
869    std::thread::sleep(Duration::from_millis(15));
870    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
871        super::wpe_input::Button::Left,
872    ))?;
873    dispatcher.flush()?;
874    std::thread::sleep(Duration::from_millis(30));
875    Ok(())
876}
877
878fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
879    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
880    let slot_for_cb = slot.clone();
881
882    let cancellable = webkit6::gio::Cancellable::new();
883    web_view.evaluate_javascript(
884        js,
885        None,
886        None,
887        Some(&cancellable),
888        move |result| match result {
889            Ok(value) => {
890                let s = value.to_string();
891                *slot_for_cb.borrow_mut() = Some(Ok(s));
892            }
893            Err(err) => {
894                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
895            }
896        },
897    );
898
899    let slot_check = slot.clone();
900    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
901    if !ok {
902        return Err(EngineError::Timeout {
903            budget,
904            primitive: "eval",
905            detail: "",
906        });
907    }
908    let result = slot.borrow_mut().take();
909    match result {
910        Some(Ok(s)) => Ok(s),
911        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
912        None => Err(EngineError::Other("eval completed without a result".into())),
913    }
914}
915
916// =============================================================================
917// Inspector capture wiring
918// =============================================================================
919
920/// Add the download-capture shim as a document-start script in every
921/// frame. WebKitGTK does emit a `download-started` signal, but the
922/// shim covers what that signal cannot see — an in-page `blob:` save
923/// whose object URL is revoked a tick later — and keeps the capture
924/// buffer identical across all three backends.
925fn install_download_shim(web_view: &WebView) {
926    let Some(manager) = web_view.user_content_manager() else {
927        return;
928    };
929    manager.add_script(&UserScript::new(
930        super::common::DOWNLOAD_SHIM_JS,
931        UserContentInjectedFrames::AllFrames,
932        UserScriptInjectionTime::Start,
933        &[],
934        &[],
935    ));
936}
937
938fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
939    use super::inspector_bridge::{
940        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
941    };
942
943    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
944        return false;
945    }
946
947    let manager = web_view.user_content_manager().expect(
948        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
949    );
950
951    let script = UserScript::new(
952        inspector_bridge::SCRIPT,
953        UserContentInjectedFrames::AllFrames,
954        UserScriptInjectionTime::Start,
955        &[],
956        &[],
957    );
958    manager.add_script(&script);
959
960    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
961        return false;
962    }
963    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
964        return false;
965    }
966
967    let console_slots: InspectorSlots = slots.clone();
968    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
969        let json = value.to_string();
970        let mut buf = console_slots.console.borrow_mut();
971        inspector_bridge::ingest_console(&mut buf, &json);
972    });
973    let network_slots: InspectorSlots = slots.clone();
974    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
975        let json = value.to_string();
976        let mut entries = network_slots.network.borrow_mut();
977        let mut details = network_slots.details.borrow_mut();
978        let mut pending = network_slots.pending.borrow_mut();
979        inspector_bridge::ingest_network(
980            NetworkIngestSlot {
981                entries: &mut entries,
982                details: &mut details,
983                pending: &mut pending,
984            },
985            &json,
986        );
987    });
988    true
989}
990
991// =============================================================================
992// Host-side cookie save/load via WebKitCookieManager
993// =============================================================================
994//
995// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
996// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
997// The v0.1.2 fix routes auth save/load through this path on every
998// platform.
999mod wpe_cookies {
1000    use std::cell::RefCell;
1001    use std::rc::Rc;
1002    use std::time::Duration;
1003
1004    use webkit6::gio;
1005    use webkit6::glib;
1006    use webkit6::prelude::*;
1007    use webkit6::soup;
1008    use webkit6::WebView;
1009
1010    use crate::backend::auth::CookieData;
1011    use crate::engine::{EngineError, EngineResult};
1012
1013    use super::run_loop_until;
1014
1015    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
1016
1017    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
1018        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
1019            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
1020        })?;
1021        session
1022            .cookie_manager()
1023            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
1024    }
1025
1026    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
1027        let manager = cookie_manager(web_view)?;
1028        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
1029        let slot_cb = slot.clone();
1030        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
1031            let cookies = match result {
1032                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
1033                Err(_) => Vec::new(),
1034            };
1035            *slot_cb.borrow_mut() = Some(cookies);
1036        });
1037        let check = slot.clone();
1038        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
1039        if !ok {
1040            return Err(EngineError::Timeout {
1041                budget: ASYNC_BUDGET,
1042                primitive: "save_auth (all_cookies)",
1043                detail: "",
1044            });
1045        }
1046        let result = slot.borrow_mut().take().unwrap_or_default();
1047        Ok(result)
1048    }
1049
1050    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
1051        let manager = cookie_manager(web_view)?;
1052        for c in cookies {
1053            if c.name.is_empty() || c.domain.is_empty() {
1054                continue;
1055            }
1056            let path = if c.path.is_empty() {
1057                "/"
1058            } else {
1059                c.path.as_str()
1060            };
1061            // max_age=-1: session cookie (no expiration). We set
1062            // expires explicitly below if the saved blob carried it.
1063            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
1064            cookie.set_secure(c.secure);
1065            cookie.set_http_only(c.http_only);
1066            if let Some(unix) = c.expires_unix {
1067                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
1068                    cookie.set_expires(&dt);
1069                }
1070            }
1071            if let Some(ss) = c.same_site.as_deref() {
1072                let policy = match ss {
1073                    "Strict" => soup::SameSitePolicy::Strict,
1074                    "None" => soup::SameSitePolicy::None,
1075                    _ => soup::SameSitePolicy::Lax,
1076                };
1077                cookie.set_same_site_policy(policy);
1078            }
1079
1080            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
1081            let done_cb = done.clone();
1082            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
1083                *done_cb.borrow_mut() = true;
1084            });
1085            let check = done.clone();
1086            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
1087            if !ok {
1088                return Err(EngineError::Timeout {
1089                    budget: ASYNC_BUDGET,
1090                    primitive: "load_auth (add_cookie)",
1091                    detail: "",
1092                });
1093            }
1094        }
1095        Ok(())
1096    }
1097
1098    fn serialize(c: &mut soup::Cookie) -> CookieData {
1099        CookieData {
1100            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
1101            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
1102            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
1103            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
1104            expires_unix: c.expires().map(|dt| dt.to_unix()),
1105            secure: c.is_secure(),
1106            http_only: c.is_http_only(),
1107            same_site: match c.same_site_policy() {
1108                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
1109                soup::SameSitePolicy::None => Some("None".to_string()),
1110                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
1111                _ => None,
1112            },
1113        }
1114    }
1115}
1116
1117/// A load that ended because its response became a download left the
1118/// page as it was and put the file in the download buffer. Not a
1119/// failure.
1120fn load_result(err: &glib::Error) -> Result<(), String> {
1121    if err.matches(webkit6::PolicyError::FrameLoadInterruptedByPolicyChange) {
1122        Ok(())
1123    } else {
1124        Err(err.message().to_string())
1125    }
1126}
1127
1128/// Save attachments instead of dropping them.
1129///
1130/// A `Content-Disposition: attachment` response (an export button, a
1131/// form POST answering with a file, a hidden-iframe download) never
1132/// reaches page script. Turn it into a WebKit download, write it to a
1133/// temp file, and move the bytes into `downloads` for `vs_download`.
1134/// The network session is shared by every page, so the
1135/// `download-started` handler checks the download belongs to this one.
1136fn install_download_capture(
1137    web_view: &WebView,
1138    downloads: &SharedDownloads,
1139) -> Option<(webkit6::NetworkSession, glib::SignalHandlerId)> {
1140    web_view.connect_decide_policy(|_view, decision, ty| {
1141        if ty != webkit6::PolicyDecisionType::Response {
1142            return false;
1143        }
1144        let Some(rd) = decision.downcast_ref::<webkit6::ResponsePolicyDecision>() else {
1145            return false;
1146        };
1147        let Some(resp) = rd.response() else {
1148            return false;
1149        };
1150        let uri = resp.uri().map(|u| u.to_string()).unwrap_or_default();
1151        if !(uri.starts_with("http:") || uri.starts_with("https:")) {
1152            return false;
1153        }
1154        let cd = resp
1155            .http_headers()
1156            .and_then(|h| h.one("Content-Disposition"))
1157            .map(|v| v.to_string())
1158            .unwrap_or_default();
1159        if is_attachment(&cd) || !rd.is_mime_type_supported() {
1160            decision.download();
1161            return true;
1162        }
1163        false
1164    });
1165
1166    let session = WebViewExt::network_session(web_view)?;
1167    let weak = web_view.downgrade();
1168    let downloads = downloads.clone();
1169    let id = session.connect_download_started(move |_session, download| {
1170        let Some(view) = weak.upgrade() else { return };
1171        if download.web_view().as_ref() != Some(&view) {
1172            return;
1173        }
1174        let resp = download.response();
1175        let url = resp
1176            .as_ref()
1177            .and_then(webkit6::URIResponse::uri)
1178            .or_else(|| download.request().and_then(|r| r.uri()))
1179            .map(|u| u.to_string())
1180            .unwrap_or_default();
1181        let mime = resp
1182            .as_ref()
1183            .and_then(webkit6::URIResponse::mime_type)
1184            .map(|m| m.to_string())
1185            .unwrap_or_default();
1186        let name = resp
1187            .as_ref()
1188            .and_then(webkit6::URIResponse::http_headers)
1189            .and_then(|h| h.one("Content-Disposition"))
1190            .and_then(|cd| name_from_disposition(&cd))
1191            .unwrap_or_default();
1192        let Ok(id) = downloads.lock().map(|mut d| d.begin(&url, &name, &mime)) else {
1193            return;
1194        };
1195        let path = temp_path(id);
1196        let _ = std::fs::remove_file(&path);
1197
1198        let dl = downloads.clone();
1199        download.connect_decide_destination(move |download, suggested| {
1200            if let Ok(mut d) = dl.lock() {
1201                if name.is_empty() {
1202                    d.set_name(id, suggested);
1203                }
1204            }
1205            let expected = download.response().map_or(0, |r| r.content_length());
1206            if expected > MAX_BYTES {
1207                if let Ok(mut d) = dl.lock() {
1208                    d.finish(
1209                        id,
1210                        Err(format!("download exceeds {MAX_BYTES} bytes ({expected})")),
1211                    );
1212                }
1213                download.cancel();
1214                return true;
1215            }
1216            download.set_destination(&path.to_string_lossy());
1217            true
1218        });
1219        let dl = downloads.clone();
1220        download.connect_failed(move |_download, err| {
1221            if let Ok(mut d) = dl.lock() {
1222                d.finish(id, Err(err.message().to_string()));
1223            }
1224            let _ = std::fs::remove_file(temp_path(id));
1225        });
1226        let dl = downloads.clone();
1227        download.connect_finished(move |_download| {
1228            let path = temp_path(id);
1229            // `failed` is followed by `finished`; the first result wins.
1230            let bytes = std::fs::read(&path).map_err(|e| format!("read {}: {e}", path.display()));
1231            let _ = std::fs::remove_file(&path);
1232            if let Ok(mut d) = dl.lock() {
1233                d.finish(id, bytes);
1234            }
1235        });
1236    });
1237    Some((session, id))
1238}
1239
1240/// Wait for the load already started on `web_view` to finish or fail.
1241fn wait_for_load(web_view: &WebView, primitive: &'static str) -> EngineResult<()> {
1242    let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
1243    let slot_for_signal = slot.clone();
1244    let signal_id = web_view.connect_load_changed(move |_view, event| {
1245        if event == LoadEvent::Finished {
1246            *slot_for_signal.borrow_mut() = Some(Ok(()));
1247        }
1248    });
1249    let slot_fail = slot.clone();
1250    let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
1251        *slot_fail.borrow_mut() = Some(load_result(err));
1252        true
1253    });
1254
1255    let slot_check = slot.clone();
1256    let budget = super::common::nav_budget();
1257    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
1258
1259    web_view.disconnect(signal_id);
1260    web_view.disconnect(fail_id);
1261
1262    if !ok {
1263        return Err(EngineError::Timeout {
1264            budget,
1265            primitive,
1266            detail: "",
1267        });
1268    }
1269    // Taken out of the RefCell before the match, not inside it:
1270    // as the function's tail expression the borrow guard would
1271    // otherwise outlive `slot` itself.
1272    let result = slot.borrow_mut().take();
1273    match result {
1274        Some(Ok(())) => Ok(()),
1275        Some(Err(msg)) => Err(EngineError::Other(format!("navigation failed: {msg}"))),
1276        None => Err(EngineError::Other(
1277            "navigation completed without a result".into(),
1278        )),
1279    }
1280}
1281
1282impl WpeBackend {
1283    /// Drop a new-window request parked before this input primitive
1284    /// started (a popup the page fired on its own), so the primitive
1285    /// only follows what it caused.
1286    fn forget_new_window(&mut self, page: PageHandle) -> EngineResult<()> {
1287        let _ = self.page_mut(page)?.new_window.borrow_mut().take();
1288        Ok(())
1289    }
1290
1291    /// Load a new-window navigation the last input primitive caused, in
1292    /// this page, and wait for it like `goto`. The `create` signal can
1293    /// arrive after the click returns, so after a click (`settle`) pump
1294    /// for up to `NEW_WINDOW_SETTLE` first. No parked request: no-op.
1295    fn follow_new_window(&mut self, page: PageHandle, settle: bool) -> EngineResult<()> {
1296        let p = self.page_mut(page)?;
1297        if settle && p.new_window.borrow().is_none() {
1298            let hint = eval_js_string(
1299                &p.web_view,
1300                super::common::NEW_WINDOW_HINT_JS,
1301                Duration::from_secs(2),
1302            );
1303            if super::common::new_window_hinted(&hint) {
1304                let parked = p.new_window.clone();
1305                let _ = run_loop_until(
1306                    move || parked.borrow().is_some(),
1307                    super::common::NEW_WINDOW_SETTLE,
1308                );
1309            }
1310        }
1311        let Some(request) = p.new_window.borrow_mut().take() else {
1312            return Ok(());
1313        };
1314        let web_view = p.web_view.clone();
1315        web_view.load_request(&request);
1316        wait_for_load(&web_view, "act")
1317    }
1318}