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/// The browser engine, as the daemon sees it.
396///
397/// All methods are synchronous from the daemon's perspective. The
398/// [`runtime`](crate::runtime) layer dispatches calls onto a dedicated
399/// thread that owns the platform run loop; implementations should
400/// assume they are running on that thread.
401pub trait Engine {
402    /// Open a fresh page navigated to `url`.
403    fn open(&mut self, url: &str) -> EngineResult<PageHandle>;
404
405    /// Navigate an existing page to `url` in place, reusing its
406    /// web view (and web-content process) instead of creating a new
407    /// one. The page handle is unchanged; the document is replaced, so
408    /// callers must re-baseline (all refs are fresh). Much cheaper than
409    /// `open` for successive navigations.
410    fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()>;
411
412    /// Install a virtual WebAuthn authenticator on `page`: a pure-JS
413    /// software authenticator that overrides `navigator.credentials`
414    /// so passkey registration and login work headlessly, with no
415    /// platform authenticator and no automation protocol. Applies to
416    /// the current document and (where the backend supports it) to
417    /// subsequent navigations in the same page.
418    fn enable_webauthn(&mut self, page: PageHandle) -> EngineResult<()>;
419
420    /// Run `source` at document start in every frame of every later
421    /// document in `page`, before the page's own scripts. The current
422    /// document is not touched (same as Playwright's addInitScript).
423    /// Scripts accumulate in the order they were added and are not
424    /// subject to the page's Content Security Policy.
425    fn add_init_script(&mut self, page: PageHandle, source: &str) -> EngineResult<()>;
426
427    /// Close a page. Idempotent — closing a closed page is a no-op.
428    fn close(&mut self, page: PageHandle) -> EngineResult<()>;
429
430    /// Snapshot the a11y tree at `page`.
431    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree>;
432
433    /// Perform `action` on `target` at `page`.
434    fn act(
435        &mut self,
436        page: PageHandle,
437        target: ActTarget,
438        action: Action,
439        mode: InputMode,
440    ) -> EngineResult<()>;
441
442    /// Wait for `cond` at `page` until satisfied or `budget` elapses.
443    fn wait(&mut self, page: PageHandle, cond: WaitCondition, budget: Duration)
444        -> EngineResult<()>;
445
446    /// Take a screenshot. Returns the path on disk where the image was
447    /// written.
448    fn capture(&mut self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf>;
449
450    /// Capture a live frame (watch / record) at a reduced width
451    /// (`max_width` px, `0` = full resolution). Cheaper to produce and
452    /// encode than a full-resolution screenshot. The default delegates
453    /// to [`Self::capture`]; backends that can render a smaller snapshot
454    /// override it.
455    fn capture_live(&mut self, page: PageHandle, _max_width: u32) -> EngineResult<PathBuf> {
456        self.capture(page, CaptureScope::Viewport)
457    }
458
459    /// Begin streaming recording frames for `page`. While active, the
460    /// backend captures a frame at each input step (mouse move,
461    /// keystroke, click) and sends it on `tx` with the cursor position,
462    /// so the recorder composites a pointer and encodes smooth motion
463    /// without a poller racing the automation. `max_width` downscales
464    /// each frame (`0` = full resolution). The default is unsupported so
465    /// the daemon can fall back to time-based polling.
466    fn record_begin(
467        &mut self,
468        _page: PageHandle,
469        _tx: std::sync::mpsc::Sender<RecFrame>,
470        _fps: u32,
471        _max_width: u32,
472    ) -> EngineResult<()> {
473        Err(EngineError::Unsupported {
474            engine: "generic",
475            primitive: "record_begin",
476        })
477    }
478
479    /// Stop streaming recording frames for `page` (drops the sender so
480    /// the recorder's drain loop ends). Idempotent.
481    fn record_end(&mut self, _page: PageHandle) -> EngineResult<()> {
482        Ok(())
483    }
484
485    /// Compute layout boxes for `refs` at `page`.
486    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>>;
487
488    /// Read a file out of `page` — either a URL fetched with the page's
489    /// credentials, or a download the page itself initiated and the
490    /// capture shim parked. Returns the bytes; the daemon owns where
491    /// they land on disk.
492    ///
493    /// Headless web views have no download delegate, so a download the
494    /// page starts is otherwise dropped without an event. Backends with
495    /// a working JS bridge get this for free via
496    /// [`common::run_download`](crate::backend); the default is
497    /// unsupported.
498    fn download(
499        &mut self,
500        _page: PageHandle,
501        _source: DownloadSource,
502        _budget: Duration,
503    ) -> EngineResult<Download> {
504        Err(EngineError::Unsupported {
505            engine: self.capabilities().name,
506            primitive: "download",
507        })
508    }
509
510    /// List the download intents the shim has captured on `page`,
511    /// payloads excluded.
512    fn download_list(&mut self, _page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
513        Err(EngineError::Unsupported {
514            engine: self.capabilities().name,
515            primitive: "download",
516        })
517    }
518
519    /// Set the viewport at `page`. Triggers a re-baseline for the next
520    /// `snapshot`.
521    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()>;
522
523    /// Snapshot cookies/storage for `page` as an opaque [`AuthBlob`].
524    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob>;
525
526    /// Apply a previously saved [`AuthBlob`] to `page`.
527    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()>;
528
529    /// Snapshot the always-captured console ring buffer for `page`.
530    /// Default impl returns empty (engines without console capture).
531    fn console_entries(
532        &mut self,
533        _page: PageHandle,
534    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
535        Ok(Vec::new())
536    }
537
538    /// Snapshot the always-captured network ring buffer for `page`.
539    /// Default impl returns empty (engines without network capture).
540    fn network_entries(
541        &mut self,
542        _page: PageHandle,
543    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
544        Ok(Vec::new())
545    }
546
547    /// Look up the full detail (headers + bodies) for a single
548    /// captured network request. Returns `None` if the seq isn't in
549    /// the buffer. Default impl returns `None`.
550    fn request_detail(
551        &mut self,
552        _page: PageHandle,
553        _seq: u64,
554    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
555        Ok(None)
556    }
557
558    /// Evaluate `expr` in main world. Default impl returns
559    /// `EvalResult::Thrown { kind: "NotImplemented", ... }`.
560    fn eval_js(
561        &mut self,
562        _page: PageHandle,
563        _expr: &str,
564    ) -> EngineResult<crate::inspector::EvalResult> {
565        Ok(crate::inspector::EvalResult::Thrown {
566            kind: "NotImplemented".into(),
567            message: "engine does not implement vs_inspect eval".into(),
568        })
569    }
570
571    /// List storage entries for the requested scope.
572    fn storage(
573        &mut self,
574        _page: PageHandle,
575        _scope: crate::inspector::StorageScope,
576    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
577        Ok(Vec::new())
578    }
579
580    /// List cookie store ADD/REMOVE events observed since the page
581    /// opened. Engines without a cookie-changed observer (Windows, the
582    /// stub) return an empty vec or `ENGINE_UNSUPPORTED` via their
583    /// capability flag.
584    fn cookie_events(
585        &mut self,
586        _page: PageHandle,
587    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
588        Ok(Vec::new())
589    }
590
591    /// Trusted keyboard typing into the focused element. Sends real
592    /// per-character key events (KeyDown/KeyUp) so the page sees
593    /// isTrusted=true keydown → beforeinput → input, which
594    /// rich-text editors (DraftJS/ProseMirror/contenteditable) and
595    /// framework-controlled inputs require — the prototype-setter
596    /// `fill` path bypasses their change pipeline. The caller places
597    /// the caret first (e.g. `vs_click_at`). Backends without native
598    /// keyboard dispatch fall through to `ENGINE_UNSUPPORTED`.
599    fn type_text(&mut self, _page: PageHandle, _text: &str, _mode: InputMode) -> EngineResult<()> {
600        Err(EngineError::Unsupported {
601            engine: self.capabilities().name,
602            primitive: "type_text",
603        })
604    }
605
606    /// Coordinate-addressed cursor operation. Backends that don't
607    /// implement native input dispatch fall through to the default
608    /// `ENGINE_UNSUPPORTED` here; agents see `! ENGINE_UNSUPPORTED`
609    /// on the wire and can switch to ref-based `vs act` instead.
610    fn cursor_op(
611        &mut self,
612        _page: PageHandle,
613        _op: CursorOp,
614        _mode: InputMode,
615    ) -> EngineResult<()> {
616        Err(EngineError::Unsupported {
617            engine: self.capabilities().name,
618            primitive: "cursor_op",
619        })
620    }
621    /// List scripts loaded by the page.
622    fn scripts(&mut self, _page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
623        Ok(Vec::new())
624    }
625
626    /// Source of one script by `seq`. Returns `None` if the seq isn't
627    /// in the script registry.
628    fn script_source(
629        &mut self,
630        _page: PageHandle,
631        _seq: u64,
632    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
633        Ok(None)
634    }
635
636    /// Outer HTML + computed styles for a ref. Caller-requested
637    /// computed properties land in `extra_props`; the engine merges
638    /// them with its default property set. Returns `None` for unknown
639    /// refs.
640    fn dom(
641        &mut self,
642        _page: PageHandle,
643        _r: vs_protocol::Ref,
644        _extra_props: &[String],
645    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
646        Ok(None)
647    }
648
649    /// Web Vitals + heap + DOM stats. Returns zero-filled defaults if
650    /// the engine can't measure them.
651    fn performance(
652        &mut self,
653        _page: PageHandle,
654    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
655        Ok(crate::inspector::PerformanceMetrics::default())
656    }
657    /// Capabilities the daemon should advertise for this engine.
658    fn capabilities(&self) -> EngineCapabilities;
659}
660
661/// The role a node in `Node` would carry — re-exported for convenience.
662pub use vs_protocol::Role as NodeRole;
663
664#[cfg(test)]
665mod tests {
666    use super::DEFAULT_USER_AGENT;
667
668    /// Pins the UA contract: must look like a current shipping
669    /// Safari, including the `Version/X` and `Safari/Y` suffixes.
670    /// The whole reason this constant exists is that the WKWebView
671    /// default UA drops both — sites that fingerprint UAs (Google,
672    /// Cloudflare, etc.) flag every request without them.
673    ///
674    /// If this test fails because you bumped the version, that's
675    /// fine — update the literal. If it fails because the format
676    /// changed, think hard before relaxing it.
677    #[test]
678    fn default_user_agent_has_safari_suffix() {
679        let ua = DEFAULT_USER_AGENT;
680        assert!(
681            ua.starts_with("Mozilla/5.0 "),
682            "UA should start with `Mozilla/5.0 `; got {ua:?}",
683        );
684        assert!(
685            ua.contains("AppleWebKit/"),
686            "UA should advertise WebKit; got {ua:?}",
687        );
688        assert!(
689            ua.contains("Version/"),
690            "UA missing `Version/X` — anti-bot will flag it; got {ua:?}",
691        );
692        assert!(
693            ua.contains("Safari/"),
694            "UA missing `Safari/X` — anti-bot will flag it; got {ua:?}",
695        );
696        // Single-line — extra whitespace inside is fine, but no
697        // newlines / tabs.
698        assert!(
699            !ua.contains('\n') && !ua.contains('\r') && !ua.contains('\t'),
700            "UA must be a single line; got {ua:?}",
701        );
702    }
703}