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