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