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/// The browser engine, as the daemon sees it.
455///
456/// All methods are synchronous from the daemon's perspective. The
457/// [`runtime`](crate::runtime) layer dispatches calls onto a dedicated
458/// thread that owns the platform run loop; implementations should
459/// assume they are running on that thread.
460pub trait Engine {
461 /// Open a fresh page navigated to `url`, in data store `store`.
462 fn open(&mut self, url: &str, store: &DataStore) -> EngineResult<PageHandle>;
463
464 /// Discard the isolated data store keyed `key`, once its pages are
465 /// closed. Unknown keys are a no-op.
466 fn drop_store(&mut self, _key: &str) -> EngineResult<()> {
467 Ok(())
468 }
469
470 /// Navigate an existing page to `url` in place, reusing its
471 /// web view (and web-content process) instead of creating a new
472 /// one. The page handle is unchanged; the document is replaced, so
473 /// callers must re-baseline (all refs are fresh). Much cheaper than
474 /// `open` for successive navigations.
475 fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()>;
476
477 /// Load `html` as the page's document under `url`: the document
478 /// has that URL and origin, but nothing is fetched and no response
479 /// headers apply. A test runner uses it to serve a routed main
480 /// document for a host the proxy cannot see (loopback on macOS).
481 fn load_html(&mut self, _page: PageHandle, _url: &str, _html: &str) -> EngineResult<()> {
482 Err(EngineError::Unsupported {
483 engine: self.capabilities().name,
484 primitive: "vs_goto --html",
485 })
486 }
487
488 /// Install a virtual WebAuthn authenticator on `page`: a pure-JS
489 /// software authenticator that overrides `navigator.credentials`
490 /// so passkey registration and login work headlessly, with no
491 /// platform authenticator and no automation protocol. Applies to
492 /// the current document and (where the backend supports it) to
493 /// subsequent navigations in the same page.
494 fn enable_webauthn(&mut self, page: PageHandle) -> EngineResult<()>;
495
496 /// Run `source` at document start in every frame of every later
497 /// document in `page`, before the page's own scripts. The current
498 /// document is not touched (same as Playwright's addInitScript).
499 /// Scripts accumulate in the order they were added and are not
500 /// subject to the page's Content Security Policy.
501 fn add_init_script(&mut self, page: PageHandle, source: &str) -> EngineResult<()>;
502
503 /// Close a page. Idempotent — closing a closed page is a no-op.
504 fn close(&mut self, page: PageHandle) -> EngineResult<()>;
505
506 /// Snapshot the a11y tree at `page`.
507 fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree>;
508
509 /// Perform `action` on `target` at `page`.
510 fn act(
511 &mut self,
512 page: PageHandle,
513 target: ActTarget,
514 action: Action,
515 mode: InputMode,
516 ) -> EngineResult<()>;
517
518 /// Wait for `cond` at `page` until satisfied or `budget` elapses.
519 fn wait(&mut self, page: PageHandle, cond: WaitCondition, budget: Duration)
520 -> EngineResult<()>;
521
522 /// Take a screenshot. Returns the path on disk where the image was
523 /// written.
524 fn capture(&mut self, page: PageHandle, scope: CaptureScope) -> EngineResult<PathBuf>;
525
526 /// Capture a live frame (watch / record) at a reduced width
527 /// (`max_width` px, `0` = full resolution). Cheaper to produce and
528 /// encode than a full-resolution screenshot. The default delegates
529 /// to [`Self::capture`]; backends that can render a smaller snapshot
530 /// override it.
531 fn capture_live(&mut self, page: PageHandle, _max_width: u32) -> EngineResult<PathBuf> {
532 self.capture(page, CaptureScope::Viewport)
533 }
534
535 /// Begin streaming recording frames for `page`. While active, the
536 /// backend captures a frame at each input step (mouse move,
537 /// keystroke, click) and sends it on `tx` with the cursor position,
538 /// so the recorder composites a pointer and encodes smooth motion
539 /// without a poller racing the automation. `max_width` downscales
540 /// each frame (`0` = full resolution). The default is unsupported so
541 /// the daemon can fall back to time-based polling.
542 fn record_begin(
543 &mut self,
544 _page: PageHandle,
545 _tx: std::sync::mpsc::Sender<RecFrame>,
546 _fps: u32,
547 _max_width: u32,
548 ) -> EngineResult<()> {
549 Err(EngineError::Unsupported {
550 engine: "generic",
551 primitive: "record_begin",
552 })
553 }
554
555 /// Stop streaming recording frames for `page` (drops the sender so
556 /// the recorder's drain loop ends). Idempotent.
557 fn record_end(&mut self, _page: PageHandle) -> EngineResult<()> {
558 Ok(())
559 }
560
561 /// Compute layout boxes for `refs` at `page`.
562 fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>>;
563
564 /// Read a file out of `page` — either a URL fetched with the page's
565 /// credentials, or a download the page itself initiated and the
566 /// capture shim parked. Returns the bytes; the daemon owns where
567 /// they land on disk.
568 ///
569 /// Headless web views have no download delegate, so a download the
570 /// page starts is otherwise dropped without an event. Backends with
571 /// a working JS bridge get this for free via
572 /// [`common::run_download`](crate::backend); the default is
573 /// unsupported.
574 fn download(
575 &mut self,
576 _page: PageHandle,
577 _source: DownloadSource,
578 _budget: Duration,
579 ) -> EngineResult<Download> {
580 Err(EngineError::Unsupported {
581 engine: self.capabilities().name,
582 primitive: "download",
583 })
584 }
585
586 /// List the download intents the shim has captured on `page`,
587 /// payloads excluded.
588 fn download_list(&mut self, _page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
589 Err(EngineError::Unsupported {
590 engine: self.capabilities().name,
591 primitive: "download",
592 })
593 }
594
595 /// Set the viewport at `page`. Triggers a re-baseline for the next
596 /// `snapshot`.
597 fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()>;
598
599 /// Snapshot cookies/storage for `page` as an opaque [`AuthBlob`].
600 fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob>;
601
602 /// Apply a previously saved [`AuthBlob`] to `page`.
603 fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()>;
604
605 /// Snapshot the always-captured console ring buffer for `page`.
606 /// Default impl returns empty (engines without console capture).
607 fn console_entries(
608 &mut self,
609 _page: PageHandle,
610 ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
611 Ok(Vec::new())
612 }
613
614 /// Snapshot the always-captured network ring buffer for `page`.
615 /// Default impl returns empty (engines without network capture).
616 fn network_entries(
617 &mut self,
618 _page: PageHandle,
619 ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
620 Ok(Vec::new())
621 }
622
623 /// Look up the full detail (headers + bodies) for a single
624 /// captured network request. Returns `None` if the seq isn't in
625 /// the buffer. Default impl returns `None`.
626 fn request_detail(
627 &mut self,
628 _page: PageHandle,
629 _seq: u64,
630 ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
631 Ok(None)
632 }
633
634 /// Evaluate `expr` in main world. Default impl returns
635 /// `EvalResult::Thrown { kind: "NotImplemented", ... }`.
636 fn eval_js(
637 &mut self,
638 _page: PageHandle,
639 _expr: &str,
640 ) -> EngineResult<crate::inspector::EvalResult> {
641 Ok(crate::inspector::EvalResult::Thrown {
642 kind: "NotImplemented".into(),
643 message: "engine does not implement vs_inspect eval".into(),
644 })
645 }
646
647 /// [`Self::eval_js`] in one subframe of `page`, including a
648 /// cross-origin one the page's own script cannot reach. `frame` is
649 /// the frame's URL (the newest frame with it wins), or `#N` for the
650 /// Nth subframe, newest first.
651 fn eval_js_in_frame(
652 &mut self,
653 _page: PageHandle,
654 _frame: &str,
655 _expr: &str,
656 ) -> EngineResult<crate::inspector::EvalResult> {
657 Err(EngineError::Unsupported {
658 engine: self.capabilities().name,
659 primitive: "vs_inspect eval --frame",
660 })
661 }
662
663 /// List storage entries for the requested scope.
664 fn storage(
665 &mut self,
666 _page: PageHandle,
667 _scope: crate::inspector::StorageScope,
668 ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
669 Ok(Vec::new())
670 }
671
672 /// List cookie store ADD/REMOVE events observed since the page
673 /// opened. Engines without a cookie-changed observer (Windows, the
674 /// stub) return an empty vec or `ENGINE_UNSUPPORTED` via their
675 /// capability flag.
676 fn cookie_events(
677 &mut self,
678 _page: PageHandle,
679 ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
680 Ok(Vec::new())
681 }
682
683 /// Trusted keyboard typing into the focused element. Sends real
684 /// per-character key events (KeyDown/KeyUp) so the page sees
685 /// isTrusted=true keydown → beforeinput → input, which
686 /// rich-text editors (DraftJS/ProseMirror/contenteditable) and
687 /// framework-controlled inputs require — the prototype-setter
688 /// `fill` path bypasses their change pipeline. The caller places
689 /// the caret first (e.g. `vs_click_at`). Backends without native
690 /// keyboard dispatch fall through to `ENGINE_UNSUPPORTED`.
691 fn type_text(&mut self, _page: PageHandle, _text: &str, _mode: InputMode) -> EngineResult<()> {
692 Err(EngineError::Unsupported {
693 engine: self.capabilities().name,
694 primitive: "type_text",
695 })
696 }
697
698 /// Coordinate-addressed cursor operation. Backends that don't
699 /// implement native input dispatch fall through to the default
700 /// `ENGINE_UNSUPPORTED` here; agents see `! ENGINE_UNSUPPORTED`
701 /// on the wire and can switch to ref-based `vs act` instead.
702 fn cursor_op(
703 &mut self,
704 _page: PageHandle,
705 _op: CursorOp,
706 _mode: InputMode,
707 ) -> EngineResult<()> {
708 Err(EngineError::Unsupported {
709 engine: self.capabilities().name,
710 primitive: "cursor_op",
711 })
712 }
713 /// List scripts loaded by the page.
714 fn scripts(&mut self, _page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
715 Ok(Vec::new())
716 }
717
718 /// Source of one script by `seq`. Returns `None` if the seq isn't
719 /// in the script registry.
720 fn script_source(
721 &mut self,
722 _page: PageHandle,
723 _seq: u64,
724 ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
725 Ok(None)
726 }
727
728 /// Outer HTML + computed styles for a ref. Caller-requested
729 /// computed properties land in `extra_props`; the engine merges
730 /// them with its default property set. Returns `None` for unknown
731 /// refs.
732 fn dom(
733 &mut self,
734 _page: PageHandle,
735 _r: vs_protocol::Ref,
736 _extra_props: &[String],
737 ) -> EngineResult<Option<crate::inspector::DomDetail>> {
738 Ok(None)
739 }
740
741 /// Web Vitals + heap + DOM stats. Returns zero-filled defaults if
742 /// the engine can't measure them.
743 fn performance(
744 &mut self,
745 _page: PageHandle,
746 ) -> EngineResult<crate::inspector::PerformanceMetrics> {
747 Ok(crate::inspector::PerformanceMetrics::default())
748 }
749
750 /// HTTP response of the latest main-frame navigation. `None` when
751 /// the engine has not recorded one (non-HTTP load, failed load,
752 /// engine without support).
753 fn main_response(
754 &mut self,
755 _page: PageHandle,
756 ) -> EngineResult<Option<crate::inspector::MainResponse>> {
757 Ok(None)
758 }
759
760 /// Give `page` real popup windows: a `target="_blank"` link or
761 /// form, or `window.open()`, opens a new engine page with an
762 /// `opener`, instead of loading in `page`. Popups of a popup
763 /// inherit the setting. Engines without support keep loading in
764 /// place.
765 fn set_popups(&mut self, _page: PageHandle, _on: bool) -> EngineResult<()> {
766 Ok(())
767 }
768
769 /// Where pages with real popups report windows they open and
770 /// pages that close themselves. Readable from any thread, so the
771 /// daemon learns of a popup without waiting for the engine thread,
772 /// which may be busy with the click that opened it. The engine
773 /// handle in an event is usable at once.
774 fn popup_feed(&mut self) -> Option<std::sync::Arc<PopupFeed>> {
775 None
776 }
777
778 /// Capabilities the daemon should advertise for this engine.
779 fn capabilities(&self) -> EngineCapabilities;
780}
781
782/// A page another page opened (see [`Engine::set_popups`]).
783#[derive(Debug, Clone, PartialEq, Eq)]
784pub struct Popup {
785 /// `None` when the opener was not an engine page (it closed).
786 pub opener: Option<PageHandle>,
787 pub page: PageHandle,
788 /// The URL it was asked to load (empty for `window.open()` with none).
789 pub url: String,
790}
791
792/// One entry of a [`PopupFeed`].
793#[derive(Debug, Clone, PartialEq, Eq)]
794pub enum PopupEvent {
795 Opened(Popup),
796 /// The page called `window.close()`; the engine releases it.
797 Closed(PageHandle),
798 /// The page opened `alert()`, `confirm()` or `prompt()` and waits
799 /// for [`PopupFeed::answer`] (dismissed after [`DIALOG_TIMEOUT`]).
800 Dialog(Dialog),
801}
802
803/// A JavaScript dialog a page is blocked on.
804#[derive(Debug, Clone, PartialEq, Eq)]
805pub struct Dialog {
806 pub page: PageHandle,
807 pub id: u64,
808 /// `alert`, `confirm` or `prompt`.
809 pub kind: &'static str,
810 pub message: String,
811 /// A prompt's default text.
812 pub default: String,
813}
814
815/// How a dialog is closed: OK (with a prompt's text) or Cancel.
816#[derive(Debug, Clone, PartialEq, Eq)]
817pub struct DialogAnswer {
818 pub accept: bool,
819 pub text: Option<String>,
820}
821
822/// A dialog nobody answers is dismissed after this long, so a page is
823/// never left blocked.
824pub const DIALOG_TIMEOUT: Duration = Duration::from_secs(10);
825
826/// See [`Engine::popup_feed`]. Carries dialogs too: they need the same
827/// off-thread path, since the page's script is blocked until answered.
828#[derive(Debug, Default)]
829pub struct PopupFeed {
830 events: std::sync::Mutex<Vec<PopupEvent>>,
831 raised: std::sync::atomic::AtomicU64,
832 answers: std::sync::Mutex<std::collections::HashMap<u64, DialogAnswer>>,
833 last_dialog: std::sync::atomic::AtomicU64,
834}
835
836impl PopupFeed {
837 /// A fresh dialog id.
838 pub fn next_dialog_id(&self) -> u64 {
839 self.last_dialog
840 .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
841 + 1
842 }
843
844 /// Answer dialog `id`. The engine applies it on its next check
845 /// (within a few milliseconds), from any thread.
846 pub fn answer(&self, id: u64, answer: DialogAnswer) {
847 self.answers.lock().expect("poisoned").insert(id, answer);
848 }
849
850 /// The answer for `id`, once given.
851 pub fn take_answer(&self, id: u64) -> Option<DialogAnswer> {
852 self.answers.lock().expect("poisoned").remove(&id)
853 }
854
855 pub fn push(&self, e: PopupEvent) {
856 self.events.lock().expect("poisoned").push(e);
857 self.raised
858 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
859 }
860
861 /// Events since the last drain, oldest first.
862 pub fn drain(&self) -> Vec<PopupEvent> {
863 std::mem::take(&mut *self.events.lock().expect("poisoned"))
864 }
865
866 /// Events pushed so far.
867 pub fn raised(&self) -> u64 {
868 self.raised.load(std::sync::atomic::Ordering::SeqCst)
869 }
870}
871
872/// The role a node in `Node` would carry — re-exported for convenience.
873pub use vs_protocol::Role as NodeRole;
874
875#[cfg(test)]
876mod tests {
877 use super::DEFAULT_USER_AGENT;
878
879 /// Pins the UA contract: must look like a current shipping
880 /// Safari, including the `Version/X` and `Safari/Y` suffixes.
881 /// The whole reason this constant exists is that the WKWebView
882 /// default UA drops both — sites that fingerprint UAs (Google,
883 /// Cloudflare, etc.) flag every request without them.
884 ///
885 /// If this test fails because you bumped the version, that's
886 /// fine — update the literal. If it fails because the format
887 /// changed, think hard before relaxing it.
888 #[test]
889 fn default_user_agent_has_safari_suffix() {
890 let ua = DEFAULT_USER_AGENT;
891 assert!(
892 ua.starts_with("Mozilla/5.0 "),
893 "UA should start with `Mozilla/5.0 `; got {ua:?}",
894 );
895 assert!(
896 ua.contains("AppleWebKit/"),
897 "UA should advertise WebKit; got {ua:?}",
898 );
899 assert!(
900 ua.contains("Version/"),
901 "UA missing `Version/X` — anti-bot will flag it; got {ua:?}",
902 );
903 assert!(
904 ua.contains("Safari/"),
905 "UA missing `Safari/X` — anti-bot will flag it; got {ua:?}",
906 );
907 // Single-line — extra whitespace inside is fine, but no
908 // newlines / tabs.
909 assert!(
910 !ua.contains('\n') && !ua.contains('\r') && !ua.contains('\t'),
911 "UA must be a single line; got {ua:?}",
912 );
913 }
914}