Skip to main content

vs_engine_webkit/
engine.rs

1//! The [`Engine`] trait — the daemon's view of "a browser".
2//!
3//! The trait is small, synchronous, and platform-agnostic. The daemon
4//! drives an `Engine` from a Tokio context but never directly: every
5//! call is dispatched onto the engine's dedicated thread (see
6//! [`crate::runtime`]), where the platform-specific WebKit port runs.
7//!
8//! For the live wire types — [`Tree`], [`Node`], [`Ref`], [`Role`],
9//! [`Op`] — see [`vs_protocol`].
10
11use std::path::PathBuf;
12use std::time::Duration;
13
14use vs_protocol::{Op, Ref, Tree};
15
16/// Default `User-Agent` the engine sets on each page. Mirrors a recent
17/// shipping Safari on macOS so anti-bot fingerprinters that match on
18/// the WKWebView default (which lacks the `Version/X Safari/X`
19/// suffix) don't flag every request. Backends that support
20/// per-webview UA (WKWebView via `setCustomUserAgent`, WebKitGTK via
21/// `webkit_settings_set_user_agent`, WebView2 via `Profile2` /
22/// `coreWebView2.Settings.UserAgent`) apply this string at construction.
23#[cfg(target_os = "macos")]
24pub const DEFAULT_USER_AGENT: &str =
25    "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) AppleWebKit/605.1.15 \
26     (KHTML, like Gecko) Version/17.5 Safari/605.1.15";
27
28/// WebKitGTK is WebKit, so the Safari family is honest — but the OS
29/// token has to say Linux. Claiming `Macintosh` here contradicted
30/// `navigator.platform`, which reports the real platform: an
31/// inconsistency any fingerprinter cross-checks, and one we created.
32#[cfg(target_os = "linux")]
33pub const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 \
34     (KHTML, like Gecko) Version/17.5 Safari/605.1.15";
35
36/// Windows runs WebView2, which *is* Chromium. There is no honest
37/// Safari string for it, and the engine's own default already names
38/// the right browser and OS — see `webview2.rs`, which no longer
39/// overrides it. This constant exists only so the shared code
40/// compiles; nothing applies it on Windows.
41#[cfg(target_os = "windows")]
42pub const DEFAULT_USER_AGENT: &str = "";
43
44/// An opaque engine-side handle to a page. The daemon associates each
45/// `PageHandle` with one `pages` row in [`vs-store`](vs_protocol).
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
47pub struct PageHandle(pub u64);
48
49/// What [`Engine::act`] targets on a page.
50///
51/// Only refs reach the engine. A mark is a store concept, scoped to a
52/// session the engine knows nothing about, so the daemon resolves one
53/// to the ref that carries it now before calling in.
54#[derive(Debug, Clone)]
55pub enum ActTarget {
56    /// A live ref from the most recent snapshot.
57    Ref(Ref),
58}
59
60/// Coordinate-addressed input operations: `vs move-to`, `vs click-at`,
61/// `vs hover-at`, `vs drag`. Native event dispatch on backends that
62/// support it (macOS today; Linux + Windows fall through to
63/// `ENGINE_UNSUPPORTED` until M7 wires GDK / CDP input).
64#[derive(Debug, Clone, Copy)]
65pub enum CursorOp {
66    /// Move the pointer to `(x, y)` without clicking.
67    MoveTo { x: f64, y: f64 },
68    /// Click at `(x, y)`. Includes a humanized lead-in from the last
69    /// known cursor position when the mode is `Human`.
70    ClickAt { x: f64, y: f64 },
71    /// Hover (mouseover) at `(x, y)`.
72    HoverAt { x: f64, y: f64 },
73    /// Press at `(x1, y1)`, drag along a humanized path to `(x2, y2)`,
74    /// release.
75    Drag { x1: f64, y1: f64, x2: f64, y2: f64 },
76    /// Click at `(x, y)` with another button, a click count above one
77    /// or modifier keys held: native events throughout, so the page
78    /// sees trusted `mousedown`/`mouseup`/`click` (`auxclick`,
79    /// `contextmenu`, `dblclick`) with `detail`, `button` and the
80    /// modifier flags set.
81    Click { x: f64, y: f64, opts: ClickOpts },
82    /// Move to `(x, y)`, then turn the wheel by `(dx, dy)` CSS px
83    /// (positive `dy` scrolls down, positive `dx` right), as a native
84    /// wheel event: the page sees a trusted `wheel` and scrolls the
85    /// element under the pointer.
86    Wheel { x: f64, y: f64, dx: f64, dy: f64 },
87}
88
89pub use crate::backend::auth::CookieData;
90
91/// What [`Engine::cookies`] does to the jar.
92#[derive(Debug, Clone)]
93pub enum CookieOp {
94    List,
95    /// Add these, replacing any with the same name, domain and path.
96    Set(Vec<CookieData>),
97    /// Delete every cookie.
98    Clear,
99}
100
101/// What [`Engine::drop_data`] drops onto a page: files from disk and
102/// string items keyed by MIME type, as a drag from another application
103/// would carry them.
104#[derive(Debug, Clone, Default)]
105pub struct DropData {
106    pub files: Vec<std::path::PathBuf>,
107    pub items: Vec<(String, String)>,
108}
109
110/// Which mouse button a [`CursorOp::Click`] presses.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum MouseButton {
113    Left,
114    Right,
115    Middle,
116}
117
118/// Modifier keys held during a [`CursorOp::Click`].
119#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
120#[allow(clippy::struct_excessive_bools)]
121pub struct Modifiers {
122    pub shift: bool,
123    pub ctrl: bool,
124    pub alt: bool,
125    pub meta: bool,
126}
127
128impl Modifiers {
129    /// `shift,ctrl,alt,meta` in any order and subset (`control`,
130    /// `option`, `cmd`/`command` accepted); `None` for an unknown name.
131    #[must_use]
132    pub fn parse(s: &str) -> Option<Self> {
133        let mut m = Self::default();
134        for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
135            match part.to_ascii_lowercase().as_str() {
136                "shift" => m.shift = true,
137                "ctrl" | "control" => m.ctrl = true,
138                "alt" | "option" => m.alt = true,
139                "meta" | "cmd" | "command" => m.meta = true,
140                _ => return None,
141            }
142        }
143        Some(m)
144    }
145
146    #[must_use]
147    pub fn any(self) -> bool {
148        self.shift || self.ctrl || self.alt || self.meta
149    }
150}
151
152/// Button, count and modifiers of a [`CursorOp::Click`].
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub struct ClickOpts {
155    pub button: MouseButton,
156    /// 1 for a click, 2 for a double click, 3 for a triple click.
157    pub count: u8,
158    pub modifiers: Modifiers,
159}
160
161/// Input humanization mode. Wire form: `--mode={human,careful,robotic}`.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub enum InputMode {
164    Human,
165    Careful,
166    Robotic,
167}
168
169impl InputMode {
170    #[must_use]
171    pub fn parse(s: &str) -> Option<Self> {
172        match s.to_ascii_lowercase().as_str() {
173            "human" | "h" => Some(Self::Human),
174            "careful" | "c" => Some(Self::Careful),
175            "robotic" | "r" => Some(Self::Robotic),
176            _ => None,
177        }
178    }
179    #[must_use]
180    pub fn as_str(self) -> &'static str {
181        match self {
182            Self::Human => "human",
183            Self::Careful => "careful",
184            Self::Robotic => "robotic",
185        }
186    }
187}
188
189/// What [`Engine::act`] does at the target.
190#[derive(Debug, Clone)]
191pub enum Action {
192    /// Activate (mouse click or `Enter`).
193    Click,
194    /// Replace the text content of an editable target.
195    Fill { value: String },
196    /// Scroll the target into view.
197    Scroll,
198    /// Send a key chord (`Enter`, `Ctrl+K`, …).
199    Key { chord: String },
200    /// Submit the enclosing form.
201    Submit,
202    /// Move the pointer over the target.
203    Hover,
204    /// Move keyboard focus.
205    Focus,
206}
207
208impl Action {
209    /// The protocol [`Op`](vs_protocol::Op) corresponding to this action.
210    #[must_use]
211    pub fn op(&self) -> Op {
212        match self {
213            Self::Click => Op::Click,
214            Self::Fill { .. } => Op::Fill,
215            Self::Scroll => Op::Scroll,
216            Self::Key { .. } => Op::Key,
217            Self::Submit => Op::Submit,
218            Self::Hover => Op::Hover,
219            Self::Focus => Op::Focus,
220        }
221    }
222}
223
224/// A condition for [`Engine::wait`].
225#[derive(Debug, Clone)]
226pub enum WaitCondition {
227    /// A11y tree stable for 250ms.
228    Stable,
229    /// Network idle (`<= 0` in-flight requests for 500ms).
230    NetIdle,
231    /// `Ref(r)` appears in the tree.
232    RefAppears(Ref),
233    /// `Ref(r)` disappears from the tree.
234    RefGone(Ref),
235    /// Substring matches anywhere in the tree.
236    Text(String),
237    /// `state_token` changes.
238    TokenChange,
239}
240
241/// Scope of a [`Engine::capture`] call.
242#[derive(Debug, Clone)]
243pub enum CaptureScope {
244    Viewport,
245    Element(Ref),
246    FullPage,
247}
248
249/// A viewport definition. Sizes are in CSS pixels; `dpr` is the
250/// device-pixel ratio.
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252pub struct Viewport {
253    pub width: u32,
254    pub height: u32,
255    pub dpr: u32,
256}
257
258impl Viewport {
259    pub const MOBILE_S: Self = Self::new(320, 568, 2);
260    pub const MOBILE: Self = Self::new(390, 844, 2);
261    pub const MOBILE_L: Self = Self::new(414, 896, 2);
262    pub const TABLET: Self = Self::new(768, 1024, 2);
263    pub const TABLET_L: Self = Self::new(1024, 768, 2);
264    pub const LAPTOP: Self = Self::new(1366, 768, 2);
265    pub const DESKTOP: Self = Self::new(1920, 1080, 2);
266    pub const DESKTOP_XL: Self = Self::new(2560, 1440, 2);
267    pub const WIDE: Self = Self::new(3440, 1440, 2);
268
269    #[must_use]
270    pub const fn new(width: u32, height: u32, dpr: u32) -> Self {
271        Self { width, height, dpr }
272    }
273
274    /// Look up a preset by its protocol name (e.g. `"mobile"`,
275    /// `"desktop-xl"`). Returns `None` for unknown presets.
276    #[must_use]
277    pub fn preset(name: &str) -> Option<Self> {
278        match name {
279            "mobile-s" => Some(Self::MOBILE_S),
280            "mobile" => Some(Self::MOBILE),
281            "mobile-l" => Some(Self::MOBILE_L),
282            "tablet" => Some(Self::TABLET),
283            "tablet-l" => Some(Self::TABLET_L),
284            "laptop" => Some(Self::LAPTOP),
285            "desktop" => Some(Self::DESKTOP),
286            "desktop-xl" => Some(Self::DESKTOP_XL),
287            "wide" => Some(Self::WIDE),
288            _ => None,
289        }
290    }
291}
292
293/// What [`Engine::download`] should hand back.
294#[derive(Debug, Clone)]
295pub enum DownloadSource {
296    /// Read `url` from inside the page, with the page's own cookies and
297    /// referer. Relative URLs resolve against the current document.
298    Url(String),
299    /// Drain the newest download the page *tried* to perform (a
300    /// `download` anchor, a `blob:` navigation, a viewer's save button)
301    /// and that the shim captured. `id` selects a specific buffered
302    /// entry; `None` takes the newest completed one.
303    Captured { id: Option<u64> },
304}
305
306/// One download the engine holds in memory, on its way to disk.
307#[derive(Debug, Clone)]
308pub struct Download {
309    pub bytes: Vec<u8>,
310    /// Suggested file name, from `Content-Disposition`, the anchor's
311    /// `download` attribute, or the URL's last path segment.
312    pub filename: String,
313    /// MIME type as reported by the blob or the response. May be empty.
314    pub mime: String,
315    /// The URL the bytes came from. `blob:` for in-page saves.
316    pub url: String,
317}
318
319/// A captured download intent, without its payload. Listed by
320/// [`Engine::download_list`] so an agent can see what the page tried
321/// to save before committing to reading any of it.
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct DownloadEntry {
324    pub id: u64,
325    pub filename: String,
326    pub mime: String,
327    pub url: String,
328    pub size: u64,
329    /// `Some(msg)` when the capture failed (revoked blob, HTTP error,
330    /// over the size cap). The entry is kept so the failure is visible
331    /// instead of the download silently vanishing.
332    pub error: Option<String>,
333    pub done: bool,
334}
335
336/// Result of [`Engine::layout`]: the computed box for a single ref.
337#[derive(Debug, Clone, Copy, PartialEq)]
338pub struct LayoutBox {
339    pub r: Ref,
340    pub x: f64,
341    pub y: f64,
342    pub width: f64,
343    pub height: f64,
344    pub visible: bool,
345    pub z_index: i32,
346}
347
348/// What an engine declares it can and cannot do.
349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
350#[allow(clippy::struct_excessive_bools)]
351pub struct EngineCapabilities {
352    /// Renders pixels (pages are visually realized; `capture` works).
353    pub renders: bool,
354    /// Honors `set_viewport` requests.
355    pub honors_viewport: bool,
356    /// Computes layout boxes (`layout` works).
357    pub measures_layout: bool,
358    /// Persists and restores cookies / storage (`save_auth` / `load_auth` work).
359    pub persists_auth: bool,
360    /// Captures `console.*` and uncaught exceptions in a ring buffer
361    /// (M5.7 PR1+). Surfaced via `vs_inspect console`.
362    pub inspector_console: bool,
363    /// Captures network requests in a ring buffer (M5.7 PR1+).
364    /// Surfaced via `vs_inspect network`.
365    pub inspector_network: bool,
366    /// Captures cookie-store ADD/REMOVE events in a ring buffer
367    /// (v0.1.6+). Surfaced via `vs_inspect cookie-events`. macOS and
368    /// Linux only — Windows reports `false` because `webview2-com` has
369    /// no cookie-changed observer.
370    pub inspector_cookie_events: bool,
371    /// Short identifier reported in `vs_status`.
372    pub name: &'static str,
373    /// Engine version string. Empty for the stub.
374    pub version: &'static str,
375}
376
377impl EngineCapabilities {
378    /// Capabilities advertised by the in-memory `TestEngine` (in
379    /// `test_support`). Sealed behind the `test-support` Cargo
380    /// feature; production builds of the daemon never see this.
381    pub const TEST: Self = Self {
382        renders: true,
383        honors_viewport: true,
384        measures_layout: true,
385        persists_auth: true,
386        inspector_console: true,
387        inspector_network: true,
388        inspector_cookie_events: true,
389        name: "test",
390        version: "",
391    };
392}
393
394/// Opaque encrypted-by-the-engine auth payload. The daemon hands the
395/// bytes to [`vs_store`](vs_protocol) for at-rest encryption.
396#[derive(Debug, Clone, PartialEq, Eq)]
397pub struct AuthBlob {
398    pub bytes: Vec<u8>,
399}
400
401/// What can go wrong when driving an engine.
402#[derive(Debug, Clone, thiserror::Error)]
403#[non_exhaustive]
404pub enum EngineError {
405    /// The engine cannot service this primitive on this platform.
406    #[error("engine `{engine}` does not support `{primitive}`")]
407    Unsupported {
408        engine: &'static str,
409        primitive: &'static str,
410    },
411
412    /// Operation exceeded its deadline.
413    ///
414    /// `detail` is empty for the historical two-argument wire form.
415    /// Navigation timeouts say which phase died (`web process did not
416    /// start` versus `navigation did not finish`) so a caller can tell
417    /// a cold web process from a page that hung.
418    #[error("timeout after {budget:?}: {primitive} {detail}")]
419    Timeout {
420        budget: Duration,
421        primitive: &'static str,
422        detail: &'static str,
423    },
424
425    /// The named ref or mark is not present.
426    #[error("not found: {kind} {id}")]
427    NotFound { kind: &'static str, id: String },
428
429    /// The engine thread panicked or is otherwise non-responsive.
430    #[error("engine thread crashed")]
431    Crashed,
432
433    /// The engine has shut down and is no longer accepting commands.
434    #[error("engine has shut down")]
435    Closed,
436
437    /// Backend recognizes the primitive but has not implemented it.
438    /// Distinct from [`Self::Unsupported`]: the platform *can* support
439    /// it, the port just isn't there yet.
440    #[error("engine `{engine}` has not implemented `{primitive}`")]
441    NotImplemented {
442        engine: &'static str,
443        primitive: &'static str,
444    },
445
446    /// Anything else (engine-specific failure mode).
447    #[error("{0}")]
448    Other(String),
449}
450
451/// Convenience [`Result`] with [`EngineError`] as the error type.
452pub type EngineResult<T> = std::result::Result<T, EngineError>;
453
454/// One recorded frame streamed from the engine during automation.
455///
456/// `record_begin` sets up a channel; the backend then captures a frame
457/// at each input step (mouse move, keystroke, click settle) and sends
458/// it here without releasing the main thread. `cx`/`cy` are the cursor
459/// position in *frame pixels* (already scaled to the recorded frame's
460/// resolution) so the recorder can composite a pointer, and `click` is
461/// a ripple phase (`1.0` at press, decaying to `0.0`; `0.0` = no ripple).
462/// This is what lets a recording show real, continuous mouse motion
463/// instead of a before/after slideshow: the frames are grabbed *inside*
464/// the move loop, not by a poller that is blocked behind it.
465pub struct RecFrame {
466    pub png: Vec<u8>,
467    pub cx: f64,
468    pub cy: f64,
469    pub click: f32,
470    /// Intended elapsed time (ms) this frame represents on the input
471    /// path, independent of how long the synchronous capture actually
472    /// took. The recorder advances its media clock by this so motion
473    /// plays at natural speed even though each snapshot inflates the real
474    /// wall-clock of the move. `0` = use real elapsed time (idle frames).
475    pub dt_ms: u32,
476}
477
478/// Which browser data store (cookies, localStorage, IndexedDB, cache)
479/// a new page uses.
480#[derive(Debug, Clone, PartialEq, Eq, Hash)]
481pub enum DataStore {
482    /// The default persistent store every non-isolated page shares.
483    Shared,
484    /// A private in-memory store, keyed by the owning session's id.
485    /// Pages opened with the same key share it; nothing outside that
486    /// key sees it. [`Engine::drop_store`] discards it, and it never
487    /// outlives the engine.
488    Isolated(String),
489    /// An isolated store, keyed like [`Self::Isolated`], whose network
490    /// traffic goes through the HTTP proxy at `127.0.0.1:<port>`. Every
491    /// engine binds proxy settings to the store (macOS data store,
492    /// WebKitGTK network session, WebView2 environment), which is why a
493    /// proxied page cannot share the default store.
494    ///
495    /// `ca` is the proxy's CA certificate (DER). The proxy answers the
496    /// browser's TLS with leaves it signs, so the engine trusts it for
497    /// this store's pages, and only for them. `spki_pins` lists the
498    /// base64 SHA-256 of the leaf and CA public keys (comma-separated),
499    /// for engines that pin keys rather than anchors.
500    Proxied {
501        key: String,
502        port: u16,
503        ca: Vec<u8>,
504        spki_pins: String,
505    },
506}
507
508impl DataStore {
509    /// The isolation key, for the isolated and proxied variants.
510    #[must_use]
511    pub fn key(&self) -> Option<&str> {
512        match self {
513            Self::Shared => None,
514            Self::Isolated(key) | Self::Proxied { key, .. } => Some(key),
515        }
516    }
517
518    /// The local proxy port, for the proxied variant.
519    #[must_use]
520    pub fn proxy_port(&self) -> Option<u16> {
521        match self {
522            Self::Proxied { port, .. } => Some(*port),
523            _ => None,
524        }
525    }
526
527    /// The proxy's CA certificate (DER), for the proxied variant.
528    #[must_use]
529    pub fn proxy_ca(&self) -> Option<&[u8]> {
530        match self {
531            Self::Proxied { ca, .. } => Some(ca),
532            _ => None,
533        }
534    }
535}
536
537/// How [`Engine::open_start`] went: the page is open, or its first load
538/// is still running and [`Engine::open_poll`] with this ticket finishes
539/// it.
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub enum OpenStart {
542    Done(PageHandle),
543    Pending(u64),
544}
545
546/// The browser engine, as the daemon sees it.
547///
548/// All methods are synchronous from the daemon's perspective. The
549/// [`runtime`](crate::runtime) layer dispatches calls onto a dedicated
550/// thread that owns the platform run loop; implementations should
551/// assume they are running on that thread.
552pub trait Engine {
553    /// Open a fresh page navigated to `url`, in data store `store`.
554    fn open(&mut self, url: &str, store: &DataStore) -> EngineResult<PageHandle>;
555
556    /// Start opening a page and return without waiting for its first
557    /// load, so the engine thread serves other pages meanwhile (a new
558    /// page's web process takes tens of milliseconds to start, all of
559    /// it idle on this thread). The default opens synchronously.
560    fn open_start(&mut self, url: &str, store: &DataStore) -> EngineResult<OpenStart> {
561        self.open(url, store).map(OpenStart::Done)
562    }
563
564    /// Finish an open that [`Engine::open_start`] left pending: `None`
565    /// while its load is still running, then the page or the error.
566    /// Polled from the engine thread between jobs.
567    fn open_poll(&mut self, _ticket: u64) -> Option<EngineResult<PageHandle>> {
568        Some(Err(EngineError::Other("no open is pending".into())))
569    }
570
571    /// Discard the isolated data store keyed `key`, once its pages are
572    /// closed. Unknown keys are a no-op.
573    fn drop_store(&mut self, _key: &str) -> EngineResult<()> {
574        Ok(())
575    }
576
577    /// Navigate an existing page to `url` in place, reusing its
578    /// web view (and web-content process) instead of creating a new
579    /// one. The page handle is unchanged; the document is replaced, so
580    /// callers must re-baseline (all refs are fresh). Much cheaper than
581    /// `open` for successive navigations.
582    fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()>;
583
584    /// Load `html` as the page's document under `url`: the document
585    /// has that URL and origin, but nothing is fetched and no response
586    /// headers apply. A test runner uses it to serve a routed main
587    /// document for a host the proxy cannot see (loopback on macOS).
588    fn load_html(&mut self, _page: PageHandle, _url: &str, _html: &str) -> EngineResult<()> {
589        Err(EngineError::Unsupported {
590            engine: self.capabilities().name,
591            primitive: "vs_goto --html",
592        })
593    }
594
595    /// Install a virtual WebAuthn authenticator on `page`: a pure-JS
596    /// software authenticator that overrides `navigator.credentials`
597    /// so passkey registration and login work headlessly, with no
598    /// platform authenticator and no automation protocol. Applies to
599    /// the current document and (where the backend supports it) to
600    /// subsequent navigations in the same page.
601    fn enable_webauthn(&mut self, page: PageHandle) -> EngineResult<()>;
602
603    /// Run `source` at document start in every frame of every later
604    /// document in `page`, before the page's own scripts. The current
605    /// document is not touched (same as Playwright's addInitScript).
606    /// Scripts accumulate in the order they were added and are not
607    /// subject to the page's Content Security Policy.
608    fn add_init_script(&mut self, page: PageHandle, source: &str) -> EngineResult<()>;
609
610    /// Close a page. Idempotent — closing a closed page is a no-op.
611    fn close(&mut self, page: PageHandle) -> EngineResult<()>;
612
613    /// Snapshot the a11y tree at `page`.
614    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree>;
615
616    /// Perform `action` on `target` at `page`.
617    fn act(
618        &mut self,
619        page: PageHandle,
620        target: ActTarget,
621        action: Action,
622        mode: InputMode,
623    ) -> EngineResult<()>;
624
625    /// Wait for `cond` at `page` until satisfied or `budget` elapses.
626    fn wait(&mut self, page: PageHandle, cond: WaitCondition, budget: Duration)
627        -> EngineResult<()>;
628
629    /// Take a screenshot. Returns the path on disk where the image was
630    /// written.
631    fn capture(&mut self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf>;
632
633    /// Capture a live frame (watch / record) at a reduced width
634    /// (`max_width` px, `0` = full resolution). Cheaper to produce and
635    /// encode than a full-resolution screenshot. The default delegates
636    /// to [`Self::capture`]; backends that can render a smaller snapshot
637    /// override it.
638    fn capture_live(&mut self, page: PageHandle, _max_width: u32) -> EngineResult<PathBuf> {
639        self.capture(page, CaptureScope::Viewport)
640    }
641
642    /// Begin streaming recording frames for `page`. While active, the
643    /// backend captures a frame at each input step (mouse move,
644    /// keystroke, click) and sends it on `tx` with the cursor position,
645    /// so the recorder composites a pointer and encodes smooth motion
646    /// without a poller racing the automation. `max_width` downscales
647    /// each frame (`0` = full resolution). The default is unsupported so
648    /// the daemon can fall back to time-based polling.
649    fn record_begin(
650        &mut self,
651        _page: PageHandle,
652        _tx: std::sync::mpsc::Sender<RecFrame>,
653        _fps: u32,
654        _max_width: u32,
655    ) -> EngineResult<()> {
656        Err(EngineError::Unsupported {
657            engine: "generic",
658            primitive: "record_begin",
659        })
660    }
661
662    /// Stop streaming recording frames for `page` (drops the sender so
663    /// the recorder's drain loop ends). Idempotent.
664    fn record_end(&mut self, _page: PageHandle) -> EngineResult<()> {
665        Ok(())
666    }
667
668    /// Compute layout boxes for `refs` at `page`.
669    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>>;
670
671    /// Read a file out of `page` — either a URL fetched with the page's
672    /// credentials, or a download the page itself initiated and the
673    /// capture shim parked. Returns the bytes; the daemon owns where
674    /// they land on disk.
675    ///
676    /// Headless web views have no download delegate, so a download the
677    /// page starts is otherwise dropped without an event. Backends with
678    /// a working JS bridge get this for free via
679    /// [`common::run_download`](crate::backend); the default is
680    /// unsupported.
681    fn download(
682        &mut self,
683        _page: PageHandle,
684        _source: DownloadSource,
685        _budget: Duration,
686    ) -> EngineResult<Download> {
687        Err(EngineError::Unsupported {
688            engine: self.capabilities().name,
689            primitive: "download",
690        })
691    }
692
693    /// List the download intents the shim has captured on `page`,
694    /// payloads excluded.
695    fn download_list(&mut self, _page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
696        Err(EngineError::Unsupported {
697            engine: self.capabilities().name,
698            primitive: "download",
699        })
700    }
701
702    /// Set the viewport at `page`. Triggers a re-baseline for the next
703    /// `snapshot`.
704    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()>;
705
706    /// Snapshot cookies/storage for `page` as an opaque [`AuthBlob`].
707    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob>;
708
709    /// Apply a previously saved [`AuthBlob`] to `page`.
710    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()>;
711
712    /// Snapshot the always-captured console ring buffer for `page`.
713    /// Default impl returns empty (engines without console capture).
714    fn console_entries(
715        &mut self,
716        _page: PageHandle,
717    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
718        Ok(Vec::new())
719    }
720
721    /// Snapshot the always-captured network ring buffer for `page`.
722    /// Default impl returns empty (engines without network capture).
723    fn network_entries(
724        &mut self,
725        _page: PageHandle,
726    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
727        Ok(Vec::new())
728    }
729
730    /// Look up the full detail (headers + bodies) for a single
731    /// captured network request. Returns `None` if the seq isn't in
732    /// the buffer. Default impl returns `None`.
733    fn request_detail(
734        &mut self,
735        _page: PageHandle,
736        _seq: u64,
737    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
738        Ok(None)
739    }
740
741    /// Evaluate `expr` in main world. Default impl returns
742    /// `EvalResult::Thrown { kind: "NotImplemented", ... }`.
743    fn eval_js(
744        &mut self,
745        _page: PageHandle,
746        _expr: &str,
747    ) -> EngineResult<crate::inspector::EvalResult> {
748        Ok(crate::inspector::EvalResult::Thrown {
749            kind: "NotImplemented".into(),
750            message: "engine does not implement vs_inspect eval".into(),
751        })
752    }
753
754    /// [`Self::eval_js`] in one subframe of `page`, including a
755    /// cross-origin one the page's own script cannot reach. `frame` is
756    /// the frame's URL (the newest frame with it wins), or `#N` for the
757    /// Nth subframe, newest first.
758    fn eval_js_in_frame(
759        &mut self,
760        _page: PageHandle,
761        _frame: &str,
762        _expr: &str,
763    ) -> EngineResult<crate::inspector::EvalResult> {
764        Err(EngineError::Unsupported {
765            engine: self.capabilities().name,
766            primitive: "vs_inspect eval --frame",
767        })
768    }
769
770    /// List storage entries for the requested scope.
771    fn storage(
772        &mut self,
773        _page: PageHandle,
774        _scope: crate::inspector::StorageScope,
775    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
776        Ok(Vec::new())
777    }
778
779    /// List cookie store ADD/REMOVE events observed since the page
780    /// opened. Engines without a cookie-changed observer (Windows, the
781    /// stub) return an empty vec or `ENGINE_UNSUPPORTED` via their
782    /// capability flag.
783    fn cookie_events(
784        &mut self,
785        _page: PageHandle,
786    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
787        Ok(Vec::new())
788    }
789
790    /// Page zoom: CSS px are drawn `zoom` view px wide, so the page lays
791    /// out `view width / zoom` CSS px wide (a mobile layout viewport,
792    /// fit to the screen). 1.0 is normal.
793    fn set_zoom(&mut self, _page: PageHandle, _zoom: f64) -> EngineResult<()> {
794        Err(EngineError::Unsupported {
795            engine: "unknown",
796            primitive: "zoom",
797        })
798    }
799
800    /// Drop `data` onto `page` at view point (`x`, `y`) as a native drag
801    /// from another application: the page sees trusted `dragenter`,
802    /// `dragover` and, when its `dragover` accepts, `drop` (otherwise
803    /// `dragleave`). Returns whether the drop was accepted.
804    fn drop_data(
805        &mut self,
806        _page: PageHandle,
807        _x: f64,
808        _y: f64,
809        _data: &DropData,
810    ) -> EngineResult<bool> {
811        Err(EngineError::Unsupported {
812            engine: "unknown",
813            primitive: "drop",
814        })
815    }
816
817    /// Kill `page`'s web content process, to test crash handling.
818    fn crash(&mut self, _page: PageHandle) -> EngineResult<()> {
819        Err(EngineError::Unsupported {
820            engine: "unknown",
821            primitive: "crash",
822        })
823    }
824
825    /// Read, add to or empty the cookie jar `page` uses (its data
826    /// store: every page of an isolated session shares it), HttpOnly
827    /// cookies included. Returns the jar after the change.
828    fn cookies(&mut self, _page: PageHandle, _op: CookieOp) -> EngineResult<Vec<CookieData>> {
829        Err(EngineError::Unsupported {
830            engine: "unknown",
831            primitive: "cookies",
832        })
833    }
834
835    /// Trusted keyboard typing into the focused element. Sends real
836    /// per-character key events (KeyDown/KeyUp) so the page sees
837    /// isTrusted=true keydown → beforeinput → input, which
838    /// rich-text editors (DraftJS/ProseMirror/contenteditable) and
839    /// framework-controlled inputs require — the prototype-setter
840    /// `fill` path bypasses their change pipeline. The caller places
841    /// the caret first (e.g. `vs_click_at`). Backends without native
842    /// keyboard dispatch fall through to `ENGINE_UNSUPPORTED`.
843    fn type_text(&mut self, _page: PageHandle, _text: &str, _mode: InputMode) -> EngineResult<()> {
844        Err(EngineError::Unsupported {
845            engine: self.capabilities().name,
846            primitive: "type_text",
847        })
848    }
849
850    /// Coordinate-addressed cursor operation. Backends that don't
851    /// implement native input dispatch fall through to the default
852    /// `ENGINE_UNSUPPORTED` here; agents see `! ENGINE_UNSUPPORTED`
853    /// on the wire and can switch to ref-based `vs act` instead.
854    fn cursor_op(
855        &mut self,
856        _page: PageHandle,
857        _op: CursorOp,
858        _mode: InputMode,
859    ) -> EngineResult<()> {
860        Err(EngineError::Unsupported {
861            engine: self.capabilities().name,
862            primitive: "cursor_op",
863        })
864    }
865    /// List scripts loaded by the page.
866    fn scripts(&mut self, _page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
867        Ok(Vec::new())
868    }
869
870    /// Source of one script by `seq`. Returns `None` if the seq isn't
871    /// in the script registry.
872    fn script_source(
873        &mut self,
874        _page: PageHandle,
875        _seq: u64,
876    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
877        Ok(None)
878    }
879
880    /// Outer HTML + computed styles for a ref. Caller-requested
881    /// computed properties land in `extra_props`; the engine merges
882    /// them with its default property set. Returns `None` for unknown
883    /// refs.
884    fn dom(
885        &mut self,
886        _page: PageHandle,
887        _r: vs_protocol::Ref,
888        _extra_props: &[String],
889    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
890        Ok(None)
891    }
892
893    /// Web Vitals + heap + DOM stats. Returns zero-filled defaults if
894    /// the engine can't measure them.
895    fn performance(
896        &mut self,
897        _page: PageHandle,
898    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
899        Ok(crate::inspector::PerformanceMetrics::default())
900    }
901
902    /// HTTP response of the latest main-frame navigation. `None` when
903    /// the engine has not recorded one (non-HTTP load, failed load,
904    /// engine without support).
905    fn main_response(
906        &mut self,
907        _page: PageHandle,
908    ) -> EngineResult<Option<crate::inspector::MainResponse>> {
909        Ok(None)
910    }
911
912    /// Give `page` real popup windows: a `target="_blank"` link or
913    /// form, or `window.open()`, opens a new engine page with an
914    /// `opener`, instead of loading in `page`. Popups of a popup
915    /// inherit the setting. Engines without support keep loading in
916    /// place.
917    fn set_popups(&mut self, _page: PageHandle, _on: bool) -> EngineResult<()> {
918        Ok(())
919    }
920
921    /// Where pages with real popups report windows they open and
922    /// pages that close themselves. Readable from any thread, so the
923    /// daemon learns of a popup without waiting for the engine thread,
924    /// which may be busy with the click that opened it. The engine
925    /// handle in an event is usable at once.
926    fn popup_feed(&mut self) -> Option<std::sync::Arc<PopupFeed>> {
927        None
928    }
929
930    /// Capabilities the daemon should advertise for this engine.
931    fn capabilities(&self) -> EngineCapabilities;
932}
933
934/// A page another page opened (see [`Engine::set_popups`]).
935#[derive(Debug, Clone, PartialEq, Eq)]
936pub struct Popup {
937    /// `None` when the opener was not an engine page (it closed).
938    pub opener: Option<PageHandle>,
939    pub page: PageHandle,
940    /// The URL it was asked to load (empty for `window.open()` with none).
941    pub url: String,
942}
943
944/// One entry of a [`PopupFeed`].
945#[derive(Debug, Clone, PartialEq, Eq)]
946pub enum PopupEvent {
947    Opened(Popup),
948    /// The page called `window.close()`; the engine releases it.
949    Closed(PageHandle),
950    /// The page's web content process died (a crash or the OS killing
951    /// it). The page stays; its next load starts a new process.
952    Crashed(PageHandle),
953    /// The page opened `alert()`, `confirm()` or `prompt()` and waits
954    /// for [`PopupFeed::answer`] (dismissed after [`DIALOG_TIMEOUT`]).
955    Dialog(Dialog),
956}
957
958/// A JavaScript dialog a page is blocked on.
959#[derive(Debug, Clone, PartialEq, Eq)]
960pub struct Dialog {
961    pub page: PageHandle,
962    pub id: u64,
963    /// `alert`, `confirm` or `prompt`.
964    pub kind: &'static str,
965    pub message: String,
966    /// A prompt's default text.
967    pub default: String,
968}
969
970/// How a dialog is closed: OK (with a prompt's text) or Cancel.
971#[derive(Debug, Clone, PartialEq, Eq)]
972pub struct DialogAnswer {
973    pub accept: bool,
974    pub text: Option<String>,
975}
976
977/// A dialog nobody answers is dismissed after this long, so a page is
978/// never left blocked.
979pub const DIALOG_TIMEOUT: Duration = Duration::from_secs(10);
980
981/// See [`Engine::popup_feed`]. Carries dialogs too: they need the same
982/// off-thread path, since the page's script is blocked until answered.
983#[derive(Debug, Default)]
984pub struct PopupFeed {
985    events: std::sync::Mutex<Vec<PopupEvent>>,
986    raised: std::sync::atomic::AtomicU64,
987    answers: std::sync::Mutex<std::collections::HashMap<u64, DialogAnswer>>,
988    last_dialog: std::sync::atomic::AtomicU64,
989}
990
991impl PopupFeed {
992    /// A fresh dialog id.
993    pub fn next_dialog_id(&self) -> u64 {
994        self.last_dialog
995            .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
996            + 1
997    }
998
999    /// Answer dialog `id`. The engine applies it on its next check
1000    /// (within a few milliseconds), from any thread.
1001    pub fn answer(&self, id: u64, answer: DialogAnswer) {
1002        self.answers.lock().expect("poisoned").insert(id, answer);
1003    }
1004
1005    /// The answer for `id`, once given.
1006    pub fn take_answer(&self, id: u64) -> Option<DialogAnswer> {
1007        self.answers.lock().expect("poisoned").remove(&id)
1008    }
1009
1010    pub fn push(&self, e: PopupEvent) {
1011        self.events.lock().expect("poisoned").push(e);
1012        self.raised
1013            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1014    }
1015
1016    /// Events since the last drain, oldest first.
1017    pub fn drain(&self) -> Vec<PopupEvent> {
1018        std::mem::take(&mut *self.events.lock().expect("poisoned"))
1019    }
1020
1021    /// Events pushed so far.
1022    pub fn raised(&self) -> u64 {
1023        self.raised.load(std::sync::atomic::Ordering::SeqCst)
1024    }
1025}
1026
1027/// The role a node in `Node` would carry — re-exported for convenience.
1028pub use vs_protocol::Role as NodeRole;
1029
1030#[cfg(test)]
1031mod tests {
1032    use super::DEFAULT_USER_AGENT;
1033
1034    /// Pins the UA contract: must look like a current shipping
1035    /// Safari, including the `Version/X` and `Safari/Y` suffixes.
1036    /// The whole reason this constant exists is that the WKWebView
1037    /// default UA drops both — sites that fingerprint UAs (Google,
1038    /// Cloudflare, etc.) flag every request without them.
1039    ///
1040    /// If this test fails because you bumped the version, that's
1041    /// fine — update the literal. If it fails because the format
1042    /// changed, think hard before relaxing it.
1043    #[test]
1044    fn default_user_agent_has_safari_suffix() {
1045        let ua = DEFAULT_USER_AGENT;
1046        assert!(
1047            ua.starts_with("Mozilla/5.0 "),
1048            "UA should start with `Mozilla/5.0 `; got {ua:?}",
1049        );
1050        assert!(
1051            ua.contains("AppleWebKit/"),
1052            "UA should advertise WebKit; got {ua:?}",
1053        );
1054        assert!(
1055            ua.contains("Version/"),
1056            "UA missing `Version/X` — anti-bot will flag it; got {ua:?}",
1057        );
1058        assert!(
1059            ua.contains("Safari/"),
1060            "UA missing `Safari/X` — anti-bot will flag it; got {ua:?}",
1061        );
1062        // Single-line — extra whitespace inside is fine, but no
1063        // newlines / tabs.
1064        assert!(
1065            !ua.contains('\n') && !ua.contains('\r') && !ua.contains('\t'),
1066            "UA must be a single line; got {ua:?}",
1067        );
1068    }
1069}