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