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#[derive(Debug, Clone)]
51pub enum ActTarget {
52    /// A live ref from the most recent snapshot.
53    Ref(Ref),
54    /// A persistent mark, identified by name.
55    Mark(String),
56}
57
58/// Coordinate-addressed input operations: `vs move-to`, `vs click-at`,
59/// `vs hover-at`, `vs drag`. Native event dispatch on backends that
60/// support it (macOS today; Linux + Windows fall through to
61/// `ENGINE_UNSUPPORTED` until M7 wires GDK / CDP input).
62#[derive(Debug, Clone, Copy)]
63pub enum CursorOp {
64    /// Move the pointer to `(x, y)` without clicking.
65    MoveTo { x: f64, y: f64 },
66    /// Click at `(x, y)`. Includes a humanized lead-in from the last
67    /// known cursor position when the mode is `Human`.
68    ClickAt { x: f64, y: f64 },
69    /// Hover (mouseover) at `(x, y)`.
70    HoverAt { x: f64, y: f64 },
71    /// Press at `(x1, y1)`, drag along a humanized path to `(x2, y2)`,
72    /// release.
73    Drag { x1: f64, y1: f64, x2: f64, y2: f64 },
74}
75
76/// Input humanization mode. Wire form: `--mode={human,careful,robotic}`.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum InputMode {
79    Human,
80    Careful,
81    Robotic,
82}
83
84impl InputMode {
85    #[must_use]
86    pub fn parse(s: &str) -> Option<Self> {
87        match s.to_ascii_lowercase().as_str() {
88            "human" | "h" => Some(Self::Human),
89            "careful" | "c" => Some(Self::Careful),
90            "robotic" | "r" => Some(Self::Robotic),
91            _ => None,
92        }
93    }
94    #[must_use]
95    pub fn as_str(self) -> &'static str {
96        match self {
97            Self::Human => "human",
98            Self::Careful => "careful",
99            Self::Robotic => "robotic",
100        }
101    }
102}
103
104/// What [`Engine::act`] does at the target.
105#[derive(Debug, Clone)]
106pub enum Action {
107    /// Activate (mouse click or `Enter`).
108    Click,
109    /// Replace the text content of an editable target.
110    Fill { value: String },
111    /// Scroll the target into view.
112    Scroll,
113    /// Send a key chord (`Enter`, `Ctrl+K`, …).
114    Key { chord: String },
115    /// Submit the enclosing form.
116    Submit,
117    /// Move the pointer over the target.
118    Hover,
119    /// Move keyboard focus.
120    Focus,
121}
122
123impl Action {
124    /// The protocol [`Op`](vs_protocol::Op) corresponding to this action.
125    #[must_use]
126    pub fn op(&self) -> Op {
127        match self {
128            Self::Click => Op::Click,
129            Self::Fill { .. } => Op::Fill,
130            Self::Scroll => Op::Scroll,
131            Self::Key { .. } => Op::Key,
132            Self::Submit => Op::Submit,
133            Self::Hover => Op::Hover,
134            Self::Focus => Op::Focus,
135        }
136    }
137}
138
139/// A condition for [`Engine::wait`].
140#[derive(Debug, Clone)]
141pub enum WaitCondition {
142    /// A11y tree stable for 250ms.
143    Stable,
144    /// Network idle (`<= 0` in-flight requests for 500ms).
145    NetIdle,
146    /// `Ref(r)` appears in the tree.
147    RefAppears(Ref),
148    /// `Ref(r)` disappears from the tree.
149    RefGone(Ref),
150    /// Substring matches anywhere in the tree.
151    Text(String),
152    /// `state_token` changes.
153    TokenChange,
154}
155
156/// Scope of a [`Engine::capture`] call.
157#[derive(Debug, Clone)]
158pub enum CaptureScope {
159    Viewport,
160    Element(Ref),
161    FullPage,
162}
163
164/// A viewport definition. Sizes are in CSS pixels; `dpr` is the
165/// device-pixel ratio.
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub struct Viewport {
168    pub width: u32,
169    pub height: u32,
170    pub dpr: u32,
171}
172
173impl Viewport {
174    pub const MOBILE_S: Self = Self::new(320, 568, 2);
175    pub const MOBILE: Self = Self::new(390, 844, 2);
176    pub const MOBILE_L: Self = Self::new(414, 896, 2);
177    pub const TABLET: Self = Self::new(768, 1024, 2);
178    pub const TABLET_L: Self = Self::new(1024, 768, 2);
179    pub const LAPTOP: Self = Self::new(1366, 768, 2);
180    pub const DESKTOP: Self = Self::new(1920, 1080, 2);
181    pub const DESKTOP_XL: Self = Self::new(2560, 1440, 2);
182    pub const WIDE: Self = Self::new(3440, 1440, 2);
183
184    #[must_use]
185    pub const fn new(width: u32, height: u32, dpr: u32) -> Self {
186        Self { width, height, dpr }
187    }
188
189    /// Look up a preset by its protocol name (e.g. `"mobile"`,
190    /// `"desktop-xl"`). Returns `None` for unknown presets.
191    #[must_use]
192    pub fn preset(name: &str) -> Option<Self> {
193        match name {
194            "mobile-s" => Some(Self::MOBILE_S),
195            "mobile" => Some(Self::MOBILE),
196            "mobile-l" => Some(Self::MOBILE_L),
197            "tablet" => Some(Self::TABLET),
198            "tablet-l" => Some(Self::TABLET_L),
199            "laptop" => Some(Self::LAPTOP),
200            "desktop" => Some(Self::DESKTOP),
201            "desktop-xl" => Some(Self::DESKTOP_XL),
202            "wide" => Some(Self::WIDE),
203            _ => None,
204        }
205    }
206}
207
208/// What [`Engine::download`] should hand back.
209#[derive(Debug, Clone)]
210pub enum DownloadSource {
211    /// Read `url` from inside the page, with the page's own cookies and
212    /// referer. Relative URLs resolve against the current document.
213    Url(String),
214    /// Drain the newest download the page *tried* to perform (a
215    /// `download` anchor, a `blob:` navigation, a viewer's save button)
216    /// and that the shim captured. `id` selects a specific buffered
217    /// entry; `None` takes the newest completed one.
218    Captured { id: Option<u64> },
219}
220
221/// One download the engine holds in memory, on its way to disk.
222#[derive(Debug, Clone)]
223pub struct Download {
224    pub bytes: Vec<u8>,
225    /// Suggested file name, from `Content-Disposition`, the anchor's
226    /// `download` attribute, or the URL's last path segment.
227    pub filename: String,
228    /// MIME type as reported by the blob or the response. May be empty.
229    pub mime: String,
230    /// The URL the bytes came from. `blob:` for in-page saves.
231    pub url: String,
232}
233
234/// A captured download intent, without its payload. Listed by
235/// [`Engine::download_list`] so an agent can see what the page tried
236/// to save before committing to reading any of it.
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub struct DownloadEntry {
239    pub id: u64,
240    pub filename: String,
241    pub mime: String,
242    pub url: String,
243    pub size: u64,
244    /// `Some(msg)` when the capture failed (revoked blob, HTTP error,
245    /// over the size cap). The entry is kept so the failure is visible
246    /// instead of the download silently vanishing.
247    pub error: Option<String>,
248    pub done: bool,
249}
250
251/// Result of [`Engine::layout`]: the computed box for a single ref.
252#[derive(Debug, Clone, Copy, PartialEq)]
253pub struct LayoutBox {
254    pub r: Ref,
255    pub x: f64,
256    pub y: f64,
257    pub width: f64,
258    pub height: f64,
259    pub visible: bool,
260    pub z_index: i32,
261}
262
263/// What an engine declares it can and cannot do.
264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
265#[allow(clippy::struct_excessive_bools)]
266pub struct EngineCapabilities {
267    /// Renders pixels (pages are visually realized; `capture` works).
268    pub renders: bool,
269    /// Honors `set_viewport` requests.
270    pub honors_viewport: bool,
271    /// Computes layout boxes (`layout` works).
272    pub measures_layout: bool,
273    /// Persists and restores cookies / storage (`save_auth` / `load_auth` work).
274    pub persists_auth: bool,
275    /// Captures `console.*` and uncaught exceptions in a ring buffer
276    /// (M5.7 PR1+). Surfaced via `vs_inspect console`.
277    pub inspector_console: bool,
278    /// Captures network requests in a ring buffer (M5.7 PR1+).
279    /// Surfaced via `vs_inspect network`.
280    pub inspector_network: bool,
281    /// Captures cookie-store ADD/REMOVE events in a ring buffer
282    /// (v0.1.6+). Surfaced via `vs_inspect cookie-events`. macOS and
283    /// Linux only — Windows reports `false` because `webview2-com` has
284    /// no cookie-changed observer.
285    pub inspector_cookie_events: bool,
286    /// Short identifier reported in `vs_status`.
287    pub name: &'static str,
288    /// Engine version string. Empty for the stub.
289    pub version: &'static str,
290}
291
292impl EngineCapabilities {
293    /// Capabilities advertised by the in-memory `TestEngine` (in
294    /// `test_support`). Sealed behind the `test-support` Cargo
295    /// feature; production builds of the daemon never see this.
296    pub const TEST: Self = Self {
297        renders: true,
298        honors_viewport: true,
299        measures_layout: true,
300        persists_auth: true,
301        inspector_console: true,
302        inspector_network: true,
303        inspector_cookie_events: true,
304        name: "test",
305        version: "",
306    };
307}
308
309/// Opaque encrypted-by-the-engine auth payload. The daemon hands the
310/// bytes to [`vs_store`](vs_protocol) for at-rest encryption.
311#[derive(Debug, Clone, PartialEq, Eq)]
312pub struct AuthBlob {
313    pub bytes: Vec<u8>,
314}
315
316/// What can go wrong when driving an engine.
317#[derive(Debug, Clone, thiserror::Error)]
318#[non_exhaustive]
319pub enum EngineError {
320    /// The engine cannot service this primitive on this platform.
321    #[error("engine `{engine}` does not support `{primitive}`")]
322    Unsupported {
323        engine: &'static str,
324        primitive: &'static str,
325    },
326
327    /// Operation exceeded its deadline.
328    #[error("timeout after {budget:?}: {primitive}")]
329    Timeout {
330        budget: Duration,
331        primitive: &'static str,
332    },
333
334    /// The named ref or mark is not present.
335    #[error("not found: {kind} {id}")]
336    NotFound { kind: &'static str, id: String },
337
338    /// The engine thread panicked or is otherwise non-responsive.
339    #[error("engine thread crashed")]
340    Crashed,
341
342    /// The engine has shut down and is no longer accepting commands.
343    #[error("engine has shut down")]
344    Closed,
345
346    /// Backend recognizes the primitive but has not implemented it.
347    /// Distinct from [`Self::Unsupported`]: the platform *can* support
348    /// it, the port just isn't there yet.
349    #[error("engine `{engine}` has not implemented `{primitive}`")]
350    NotImplemented {
351        engine: &'static str,
352        primitive: &'static str,
353    },
354
355    /// Anything else (engine-specific failure mode).
356    #[error("{0}")]
357    Other(String),
358}
359
360/// Convenience [`Result`] with [`EngineError`] as the error type.
361pub type EngineResult<T> = std::result::Result<T, EngineError>;
362
363/// One recorded frame streamed from the engine during automation.
364///
365/// `record_begin` sets up a channel; the backend then captures a frame
366/// at each input step (mouse move, keystroke, click settle) and sends
367/// it here without releasing the main thread. `cx`/`cy` are the cursor
368/// position in *frame pixels* (already scaled to the recorded frame's
369/// resolution) so the recorder can composite a pointer, and `click` is
370/// a ripple phase (`1.0` at press, decaying to `0.0`; `0.0` = no ripple).
371/// This is what lets a recording show real, continuous mouse motion
372/// instead of a before/after slideshow: the frames are grabbed *inside*
373/// the move loop, not by a poller that is blocked behind it.
374pub struct RecFrame {
375    pub png: Vec<u8>,
376    pub cx: f64,
377    pub cy: f64,
378    pub click: f32,
379    /// Intended elapsed time (ms) this frame represents on the input
380    /// path, independent of how long the synchronous capture actually
381    /// took. The recorder advances its media clock by this so motion
382    /// plays at natural speed even though each snapshot inflates the real
383    /// wall-clock of the move. `0` = use real elapsed time (idle frames).
384    pub dt_ms: u32,
385}
386
387/// The browser engine, as the daemon sees it.
388///
389/// All methods are synchronous from the daemon's perspective. The
390/// [`runtime`](crate::runtime) layer dispatches calls onto a dedicated
391/// thread that owns the platform run loop; implementations should
392/// assume they are running on that thread.
393pub trait Engine {
394    /// Open a fresh page navigated to `url`.
395    fn open(&mut self, url: &str) -> EngineResult<PageHandle>;
396
397    /// Navigate an existing page to `url` in place, reusing its
398    /// web view (and web-content process) instead of creating a new
399    /// one. The page handle is unchanged; the document is replaced, so
400    /// callers must re-baseline (all refs are fresh). Much cheaper than
401    /// `open` for successive navigations.
402    fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()>;
403
404    /// Install a virtual WebAuthn authenticator on `page`: a pure-JS
405    /// software authenticator that overrides `navigator.credentials`
406    /// so passkey registration and login work headlessly, with no
407    /// platform authenticator and no automation protocol. Applies to
408    /// the current document and (where the backend supports it) to
409    /// subsequent navigations in the same page.
410    fn enable_webauthn(&mut self, page: PageHandle) -> EngineResult<()>;
411
412    /// Close a page. Idempotent — closing a closed page is a no-op.
413    fn close(&mut self, page: PageHandle) -> EngineResult<()>;
414
415    /// Snapshot the a11y tree at `page`.
416    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree>;
417
418    /// Perform `action` on `target` at `page`.
419    fn act(
420        &mut self,
421        page: PageHandle,
422        target: ActTarget,
423        action: Action,
424        mode: InputMode,
425    ) -> EngineResult<()>;
426
427    /// Wait for `cond` at `page` until satisfied or `budget` elapses.
428    fn wait(&mut self, page: PageHandle, cond: WaitCondition, budget: Duration)
429        -> EngineResult<()>;
430
431    /// Take a screenshot. Returns the path on disk where the image was
432    /// written.
433    fn capture(&mut self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf>;
434
435    /// Capture a live frame (watch / record) at a reduced width
436    /// (`max_width` px, `0` = full resolution). Cheaper to produce and
437    /// encode than a full-resolution screenshot. The default delegates
438    /// to [`Self::capture`]; backends that can render a smaller snapshot
439    /// override it.
440    fn capture_live(&mut self, page: PageHandle, _max_width: u32) -> EngineResult<PathBuf> {
441        self.capture(page, CaptureScope::Viewport)
442    }
443
444    /// Begin streaming recording frames for `page`. While active, the
445    /// backend captures a frame at each input step (mouse move,
446    /// keystroke, click) and sends it on `tx` with the cursor position,
447    /// so the recorder composites a pointer and encodes smooth motion
448    /// without a poller racing the automation. `max_width` downscales
449    /// each frame (`0` = full resolution). The default is unsupported so
450    /// the daemon can fall back to time-based polling.
451    fn record_begin(
452        &mut self,
453        _page: PageHandle,
454        _tx: std::sync::mpsc::Sender<RecFrame>,
455        _fps: u32,
456        _max_width: u32,
457    ) -> EngineResult<()> {
458        Err(EngineError::Unsupported {
459            engine: "generic",
460            primitive: "record_begin",
461        })
462    }
463
464    /// Stop streaming recording frames for `page` (drops the sender so
465    /// the recorder's drain loop ends). Idempotent.
466    fn record_end(&mut self, _page: PageHandle) -> EngineResult<()> {
467        Ok(())
468    }
469
470    /// Compute layout boxes for `refs` at `page`.
471    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>>;
472
473    /// Read a file out of `page` — either a URL fetched with the page's
474    /// credentials, or a download the page itself initiated and the
475    /// capture shim parked. Returns the bytes; the daemon owns where
476    /// they land on disk.
477    ///
478    /// Headless web views have no download delegate, so a download the
479    /// page starts is otherwise dropped without an event. Backends with
480    /// a working JS bridge get this for free via
481    /// [`common::run_download`](crate::backend); the default is
482    /// unsupported.
483    fn download(
484        &mut self,
485        _page: PageHandle,
486        _source: DownloadSource,
487        _budget: Duration,
488    ) -> EngineResult<Download> {
489        Err(EngineError::Unsupported {
490            engine: self.capabilities().name,
491            primitive: "download",
492        })
493    }
494
495    /// List the download intents the shim has captured on `page`,
496    /// payloads excluded.
497    fn download_list(&mut self, _page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
498        Err(EngineError::Unsupported {
499            engine: self.capabilities().name,
500            primitive: "download",
501        })
502    }
503
504    /// Set the viewport at `page`. Triggers a re-baseline for the next
505    /// `snapshot`.
506    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()>;
507
508    /// Snapshot cookies/storage for `page` as an opaque [`AuthBlob`].
509    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob>;
510
511    /// Apply a previously saved [`AuthBlob`] to `page`.
512    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()>;
513
514    /// Snapshot the always-captured console ring buffer for `page`.
515    /// Default impl returns empty (engines without console capture).
516    fn console_entries(
517        &mut self,
518        _page: PageHandle,
519    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
520        Ok(Vec::new())
521    }
522
523    /// Snapshot the always-captured network ring buffer for `page`.
524    /// Default impl returns empty (engines without network capture).
525    fn network_entries(
526        &mut self,
527        _page: PageHandle,
528    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
529        Ok(Vec::new())
530    }
531
532    /// Look up the full detail (headers + bodies) for a single
533    /// captured network request. Returns `None` if the seq isn't in
534    /// the buffer. Default impl returns `None`.
535    fn request_detail(
536        &mut self,
537        _page: PageHandle,
538        _seq: u64,
539    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
540        Ok(None)
541    }
542
543    /// Evaluate `expr` in main world. Default impl returns
544    /// `EvalResult::Thrown { kind: "NotImplemented", ... }`.
545    fn eval_js(
546        &mut self,
547        _page: PageHandle,
548        _expr: &str,
549    ) -> EngineResult<crate::inspector::EvalResult> {
550        Ok(crate::inspector::EvalResult::Thrown {
551            kind: "NotImplemented".into(),
552            message: "engine does not implement vs_inspect eval".into(),
553        })
554    }
555
556    /// List storage entries for the requested scope.
557    fn storage(
558        &mut self,
559        _page: PageHandle,
560        _scope: crate::inspector::StorageScope,
561    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
562        Ok(Vec::new())
563    }
564
565    /// List cookie store ADD/REMOVE events observed since the page
566    /// opened. Engines without a cookie-changed observer (Windows, the
567    /// stub) return an empty vec or `ENGINE_UNSUPPORTED` via their
568    /// capability flag.
569    fn cookie_events(
570        &mut self,
571        _page: PageHandle,
572    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
573        Ok(Vec::new())
574    }
575
576    /// Trusted keyboard typing into the focused element. Sends real
577    /// per-character key events (KeyDown/KeyUp) so the page sees
578    /// isTrusted=true keydown → beforeinput → input, which
579    /// rich-text editors (DraftJS/ProseMirror/contenteditable) and
580    /// framework-controlled inputs require — the prototype-setter
581    /// `fill` path bypasses their change pipeline. The caller places
582    /// the caret first (e.g. `vs_click_at`). Backends without native
583    /// keyboard dispatch fall through to `ENGINE_UNSUPPORTED`.
584    fn type_text(&mut self, _page: PageHandle, _text: &str, _mode: InputMode) -> EngineResult<()> {
585        Err(EngineError::Unsupported {
586            engine: self.capabilities().name,
587            primitive: "type_text",
588        })
589    }
590
591    /// Coordinate-addressed cursor operation. Backends that don't
592    /// implement native input dispatch fall through to the default
593    /// `ENGINE_UNSUPPORTED` here; agents see `! ENGINE_UNSUPPORTED`
594    /// on the wire and can switch to ref-based `vs act` instead.
595    fn cursor_op(
596        &mut self,
597        _page: PageHandle,
598        _op: CursorOp,
599        _mode: InputMode,
600    ) -> EngineResult<()> {
601        Err(EngineError::Unsupported {
602            engine: self.capabilities().name,
603            primitive: "cursor_op",
604        })
605    }
606    /// List scripts loaded by the page.
607    fn scripts(&mut self, _page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
608        Ok(Vec::new())
609    }
610
611    /// Source of one script by `seq`. Returns `None` if the seq isn't
612    /// in the script registry.
613    fn script_source(
614        &mut self,
615        _page: PageHandle,
616        _seq: u64,
617    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
618        Ok(None)
619    }
620
621    /// Outer HTML + computed styles for a ref. Caller-requested
622    /// computed properties land in `extra_props`; the engine merges
623    /// them with its default property set. Returns `None` for unknown
624    /// refs.
625    fn dom(
626        &mut self,
627        _page: PageHandle,
628        _r: vs_protocol::Ref,
629        _extra_props: &[String],
630    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
631        Ok(None)
632    }
633
634    /// Web Vitals + heap + DOM stats. Returns zero-filled defaults if
635    /// the engine can't measure them.
636    fn performance(
637        &mut self,
638        _page: PageHandle,
639    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
640        Ok(crate::inspector::PerformanceMetrics::default())
641    }
642    /// Capabilities the daemon should advertise for this engine.
643    fn capabilities(&self) -> EngineCapabilities;
644}
645
646/// The role a node in `Node` would carry — re-exported for convenience.
647pub use vs_protocol::Role as NodeRole;
648
649#[cfg(test)]
650mod tests {
651    use super::DEFAULT_USER_AGENT;
652
653    /// Pins the UA contract: must look like a current shipping
654    /// Safari, including the `Version/X` and `Safari/Y` suffixes.
655    /// The whole reason this constant exists is that the WKWebView
656    /// default UA drops both — sites that fingerprint UAs (Google,
657    /// Cloudflare, etc.) flag every request without them.
658    ///
659    /// If this test fails because you bumped the version, that's
660    /// fine — update the literal. If it fails because the format
661    /// changed, think hard before relaxing it.
662    #[test]
663    fn default_user_agent_has_safari_suffix() {
664        let ua = DEFAULT_USER_AGENT;
665        assert!(
666            ua.starts_with("Mozilla/5.0 "),
667            "UA should start with `Mozilla/5.0 `; got {ua:?}",
668        );
669        assert!(
670            ua.contains("AppleWebKit/"),
671            "UA should advertise WebKit; got {ua:?}",
672        );
673        assert!(
674            ua.contains("Version/"),
675            "UA missing `Version/X` — anti-bot will flag it; got {ua:?}",
676        );
677        assert!(
678            ua.contains("Safari/"),
679            "UA missing `Safari/X` — anti-bot will flag it; got {ua:?}",
680        );
681        // Single-line — extra whitespace inside is fine, but no
682        // newlines / tabs.
683        assert!(
684            !ua.contains('\n') && !ua.contains('\r') && !ua.contains('\t'),
685            "UA must be a single line; got {ua:?}",
686        );
687    }
688}