Skip to main content

vs_engine_webkit/
inspector.rs

1//! Inspector capture types — `ConsoleEntry`, `NetworkEntry`, ring
2//! buffer + level/status enums.
3//!
4//! Engine implementations capture these in always-on ring buffers
5//! (bounded; FIFO eviction). The agent reads them via the
6//! `vs_inspect` primitive (M5.7 PR2+).
7//!
8//! WebKit Inspector protocol is **internal only** — it never appears
9//! on the agent-facing wire. See ADR 0008.
10
11use std::collections::VecDeque;
12use std::time::SystemTime;
13
14/// Default ring-buffer capacity per kind, per page. Configurable via
15/// `Daemon::with_inspector_buffer_capacity`.
16pub const DEFAULT_BUFFER_CAPACITY: usize = 1000;
17
18/// Console levels observable by `vs_inspect console`. Mirrors the
19/// browser's `console.<level>(...)` family plus the synthetic
20/// `error` level we use for uncaught exceptions and unhandled
21/// rejections.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23pub enum ConsoleLevel {
24    Error,
25    Warn,
26    Info,
27    Log,
28    Debug,
29}
30
31impl ConsoleLevel {
32    /// Wire-format string (lowercase).
33    #[must_use]
34    pub fn as_str(self) -> &'static str {
35        match self {
36            Self::Error => "error",
37            Self::Warn => "warn",
38            Self::Info => "info",
39            Self::Log => "log",
40            Self::Debug => "debug",
41        }
42    }
43
44    /// Parse a level name (case-insensitive). Returns `None` if the
45    /// name doesn't match a known level.
46    #[must_use]
47    pub fn parse(s: &str) -> Option<Self> {
48        match s.to_ascii_lowercase().as_str() {
49            "error" | "err" => Some(Self::Error),
50            "warn" | "warning" => Some(Self::Warn),
51            "info" => Some(Self::Info),
52            "log" => Some(Self::Log),
53            "debug" | "trace" => Some(Self::Debug),
54            _ => None,
55        }
56    }
57}
58
59/// One captured console event.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct ConsoleEntry {
62    /// Wall-clock when the event was captured.
63    pub timestamp: SystemTime,
64    pub level: ConsoleLevel,
65    /// The serialized message. Multiple `console.log("a", "b")` args
66    /// are joined with a single space, matching DevTools' rendering.
67    pub message: String,
68    /// Optional stack trace (one frame per line). Present for
69    /// uncaught exceptions and `console.error`/`trace`; `None`
70    /// otherwise.
71    pub stack: Option<String>,
72}
73
74/// One captured network event.
75#[derive(Debug, Clone)]
76pub struct NetworkEntry {
77    /// Per-page sequential id, formatted on the wire as `n_<seq>`.
78    pub seq: u64,
79    pub timestamp: SystemTime,
80    pub method: String,
81    pub url: String,
82    pub status: NetworkStatus,
83    /// Total transfer size in bytes (response body, after
84    /// decompression). 0 if not yet available.
85    pub size: u64,
86    /// End-to-end latency. `None` while the request is still pending.
87    pub latency_ms: Option<u64>,
88}
89
90/// Status of a captured network request.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum NetworkStatus {
93    /// HTTP status code.
94    Code(u16),
95    /// Request still in flight.
96    Pending,
97    /// Browser aborted the request.
98    Abort,
99    /// CORS preflight or response policy blocked the request.
100    Cors,
101    /// Blocked by content-security-policy or similar.
102    Blocked,
103}
104
105impl NetworkStatus {
106    /// Wire-format representation.
107    #[must_use]
108    pub fn as_str(&self) -> String {
109        match self {
110            Self::Code(c) => c.to_string(),
111            Self::Pending => "pending".into(),
112            Self::Abort => "abort".into(),
113            Self::Cors => "cors".into(),
114            Self::Blocked => "blocked".into(),
115        }
116    }
117}
118
119/// One request/response header pair, captured for `vs_inspect request`.
120#[derive(Debug, Clone)]
121pub struct Header {
122    pub name: String,
123    pub value: String,
124}
125
126/// Full detail for one captured network request — headers + bodies for
127/// both the request and response. Returned by [`crate::Engine::request_detail`]
128/// when the agent calls `vs_inspect request <id>`.
129#[derive(Debug, Clone)]
130pub struct RequestDetail {
131    pub seq: u64,
132    pub method: String,
133    pub url: String,
134    pub status: NetworkStatus,
135    pub request_headers: Vec<Header>,
136    pub request_body: Option<String>,
137    pub response_headers: Vec<Header>,
138    pub response_body: Option<String>,
139}
140
141/// Result of `Engine::eval_js`. The `Ok` variant carries a JSON-
142/// serialized value (or empty for `undefined`/`null`); errors are
143/// distinguished by *kind* so the agent can react differently to a
144/// thrown exception vs. a SyntaxError vs. a binding/IO failure.
145#[derive(Debug, Clone)]
146pub enum EvalResult {
147    Ok {
148        /// JSON-serialized value (or `"null"` / `"undefined"` literal).
149        value: String,
150        /// JS typeof string: `"string"`, `"number"`, `"object"`, etc.
151        js_type: String,
152    },
153    /// Runtime error thrown during evaluation.
154    Thrown { kind: String, message: String },
155    /// Parser error — the expression was syntactically invalid.
156    Syntax { message: String },
157}
158
159/// Storage scope for `Engine::storage`.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum StorageScope {
162    Cookies,
163    Local,
164    Session,
165    IndexedDb,
166}
167
168impl StorageScope {
169    /// Wire-format identifier.
170    #[must_use]
171    pub fn as_str(self) -> &'static str {
172        match self {
173            Self::Cookies => "cookies",
174            Self::Local => "local",
175            Self::Session => "session",
176            Self::IndexedDb => "indexeddb",
177        }
178    }
179
180    /// Parse from a wire-format identifier.
181    #[must_use]
182    pub fn parse(s: &str) -> Option<Self> {
183        match s {
184            "cookies" => Some(Self::Cookies),
185            "local" | "localStorage" => Some(Self::Local),
186            "session" | "sessionStorage" => Some(Self::Session),
187            "indexeddb" | "idb" => Some(Self::IndexedDb),
188            _ => None,
189        }
190    }
191}
192
193/// One entry returned by `Engine::storage`. Cookies use the optional
194/// flag fields; key/value stores use only `key` and `value`; IndexedDB
195/// uses `key` (db name) and `value` (version + object store names
196/// joined). The agent doesn't need a sum type — a uniform shape keeps
197/// the wire format simple.
198#[derive(Debug, Clone)]
199pub struct StorageEntry {
200    pub key: String,
201    pub value: String,
202    /// Cookies only. `secure`, `httponly`, `samesite=...`, `expires=...`.
203    pub flags: Vec<String>,
204    /// True when the value should be redacted unless `--unsafe-log`.
205    /// Cookies match the auth-header redactor; storage entries match
206    /// keys like `token`, `auth`, `secret`, `key` (in their name).
207    pub sensitive: bool,
208}
209
210/// Cookie store change event captured by `Engine::cookie_events`.
211/// macOS uses `WKHTTPCookieStoreObserver`, Linux uses the
212/// `WebKitCookieManager::changed` signal; both diff snapshots to
213/// produce per-cookie Added/Removed events. Windows currently has no
214/// observer in `webview2-com`, so the engine reports
215/// `inspector_cookie_events = false` and the primitive returns
216/// `ENGINE_UNSUPPORTED`.
217#[derive(Debug, Clone)]
218pub struct CookieEvent {
219    /// Per-page monotonic sequence (formatted on the wire as `c_<seq>`).
220    pub seq: u64,
221    /// Milliseconds since Unix epoch when the event was observed.
222    pub ts_ms: u64,
223    pub action: CookieAction,
224    pub name: String,
225    pub domain: String,
226    pub path: String,
227    /// Same `secure`/`httponly`/`samesite=`/`expires=` flag vocabulary
228    /// as [`StorageEntry::flags`].
229    pub flags: Vec<String>,
230}
231
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum CookieAction {
234    Added,
235    Removed,
236}
237
238impl CookieAction {
239    #[must_use]
240    pub fn as_str(self) -> &'static str {
241        match self {
242            Self::Added => "added",
243            Self::Removed => "removed",
244        }
245    }
246}
247
248/// The HTTP response of the page's latest main-frame navigation, from
249/// `Engine::main_response`. `None` there means no HTTP response is
250/// known: `about:blank`, `data:`, `file:`, a failed load.
251#[derive(Debug, Clone, Default, PartialEq, Eq)]
252pub struct MainResponse {
253    /// Final URL, after redirects.
254    pub url: String,
255    pub status: u16,
256    /// Reason phrase. Empty when neither the engine nor
257    /// `reason_phrase` knows one.
258    pub status_text: String,
259    /// `(lower-cased name, value)`, duplicates kept as separate entries.
260    pub headers: Vec<(String, String)>,
261}
262
263/// Standard reason phrase for `status`, for engines that do not
264/// expose the one the server sent (WKWebView). Empty if unknown.
265#[must_use]
266pub fn reason_phrase(status: u16) -> &'static str {
267    match status {
268        100 => "Continue",
269        101 => "Switching Protocols",
270        200 => "OK",
271        201 => "Created",
272        202 => "Accepted",
273        203 => "Non-Authoritative Information",
274        204 => "No Content",
275        205 => "Reset Content",
276        206 => "Partial Content",
277        300 => "Multiple Choices",
278        301 => "Moved Permanently",
279        302 => "Found",
280        303 => "See Other",
281        304 => "Not Modified",
282        307 => "Temporary Redirect",
283        308 => "Permanent Redirect",
284        400 => "Bad Request",
285        401 => "Unauthorized",
286        402 => "Payment Required",
287        403 => "Forbidden",
288        404 => "Not Found",
289        405 => "Method Not Allowed",
290        406 => "Not Acceptable",
291        407 => "Proxy Authentication Required",
292        408 => "Request Timeout",
293        409 => "Conflict",
294        410 => "Gone",
295        411 => "Length Required",
296        412 => "Precondition Failed",
297        413 => "Payload Too Large",
298        414 => "URI Too Long",
299        415 => "Unsupported Media Type",
300        416 => "Range Not Satisfiable",
301        417 => "Expectation Failed",
302        418 => "I'm a teapot",
303        421 => "Misdirected Request",
304        422 => "Unprocessable Entity",
305        425 => "Too Early",
306        426 => "Upgrade Required",
307        428 => "Precondition Required",
308        429 => "Too Many Requests",
309        431 => "Request Header Fields Too Large",
310        451 => "Unavailable For Legal Reasons",
311        500 => "Internal Server Error",
312        501 => "Not Implemented",
313        502 => "Bad Gateway",
314        503 => "Service Unavailable",
315        504 => "Gateway Timeout",
316        505 => "HTTP Version Not Supported",
317        511 => "Network Authentication Required",
318        _ => "",
319    }
320}
321
322/// One loaded script in `Engine::scripts`.
323#[derive(Debug, Clone)]
324pub struct ScriptEntry {
325    /// Per-page sequential id, formatted on the wire as `s_<seq>`.
326    pub seq: u64,
327    /// Source URL, or `inline:doc[<index>]` for inline scripts.
328    pub source: String,
329    /// Approximate source size in bytes.
330    pub size: u64,
331    pub state: ScriptState,
332}
333
334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
335pub enum ScriptState {
336    Parsed,
337    Loading,
338    Error,
339    BlockedCsp,
340    BlockedPolicy,
341}
342
343impl ScriptState {
344    #[must_use]
345    pub fn as_str(self) -> &'static str {
346        match self {
347            Self::Parsed => "parsed",
348            Self::Loading => "loading",
349            Self::Error => "error",
350            Self::BlockedCsp => "blocked-csp",
351            Self::BlockedPolicy => "blocked-policy",
352        }
353    }
354}
355
356/// Source of one script (returned by `Engine::script_source`).
357#[derive(Debug, Clone)]
358pub struct ScriptSource {
359    pub seq: u64,
360    pub source_url: String,
361    pub body: String,
362}
363
364/// Detail returned by `Engine::dom`: outer HTML + computed-style
365/// pairs for one ref.
366#[derive(Debug, Clone)]
367pub struct DomDetail {
368    pub r: u32,
369    pub outer_html: String,
370    /// Computed style pairs in iteration order. Default + caller-
371    /// requested properties only.
372    pub computed: Vec<(String, String)>,
373}
374
375/// Web Vitals + heap + DOM-stat block returned by
376/// `Engine::performance`. Floats use 2 decimals on the wire; missing
377/// metrics are emitted as `0` rather than dropped (keeps the line
378/// shape stable).
379#[derive(Debug, Clone, Default)]
380pub struct PerformanceMetrics {
381    pub ttfb_ms: f64,
382    pub fcp_ms: f64,
383    pub lcp_ms: f64,
384    pub cls: f64,
385    pub fid_ms: f64,
386    pub long_tasks: u32,
387    pub total_blocking_ms: f64,
388    pub js_heap_mb: f64,
389    pub dom_nodes: u32,
390}
391
392/// Bounded FIFO ring buffer for inspector captures. Adding to a full
393/// buffer evicts the oldest entry. Reads return a snapshot in
394/// chronological order (oldest first).
395#[derive(Debug, Clone)]
396pub struct RingBuffer<T> {
397    items: VecDeque<T>,
398    capacity: usize,
399}
400
401impl<T: Clone> RingBuffer<T> {
402    /// Build a new buffer. Capacity must be > 0; capacity 0 is clamped
403    /// to 1 to keep `push` infallible.
404    #[must_use]
405    pub fn new(capacity: usize) -> Self {
406        let capacity = capacity.max(1);
407        Self {
408            items: VecDeque::with_capacity(capacity),
409            capacity,
410        }
411    }
412
413    /// Push `item`; if the buffer was full, return the evicted oldest
414    /// entry. Callers that maintain side-tables keyed off the entry
415    /// (the inspector bridge's `details` map keyed by seq) use the
416    /// returned item to clean up in lockstep so the side-table never
417    /// grows past the ring's capacity.
418    pub fn push(&mut self, item: T) -> Option<T> {
419        let evicted = if self.items.len() == self.capacity {
420            self.items.pop_front()
421        } else {
422            None
423        };
424        self.items.push_back(item);
425        evicted
426    }
427
428    #[must_use]
429    pub fn snapshot(&self) -> Vec<T> {
430        self.items.iter().cloned().collect()
431    }
432
433    #[must_use]
434    pub fn len(&self) -> usize {
435        self.items.len()
436    }
437
438    #[must_use]
439    pub fn is_empty(&self) -> bool {
440        self.items.is_empty()
441    }
442
443    #[must_use]
444    pub fn capacity(&self) -> usize {
445        self.capacity
446    }
447}
448
449#[cfg(test)]
450mod tests {
451    use super::*;
452
453    #[test]
454    fn ring_buffer_evicts_fifo() {
455        let mut rb: RingBuffer<u32> = RingBuffer::new(3);
456        for i in 0..5 {
457            rb.push(i);
458        }
459        assert_eq!(rb.snapshot(), vec![2, 3, 4]);
460        assert_eq!(rb.len(), 3);
461    }
462
463    #[test]
464    fn ring_buffer_capacity_zero_is_clamped() {
465        let mut rb: RingBuffer<u8> = RingBuffer::new(0);
466        rb.push(1);
467        assert_eq!(rb.snapshot(), vec![1]);
468    }
469
470    #[test]
471    fn console_level_parse() {
472        assert_eq!(ConsoleLevel::parse("error"), Some(ConsoleLevel::Error));
473        assert_eq!(ConsoleLevel::parse("WARN"), Some(ConsoleLevel::Warn));
474        assert_eq!(ConsoleLevel::parse("garbage"), None);
475    }
476
477    #[test]
478    fn network_status_str() {
479        assert_eq!(NetworkStatus::Code(200).as_str(), "200");
480        assert_eq!(NetworkStatus::Pending.as_str(), "pending");
481        assert_eq!(NetworkStatus::Cors.as_str(), "cors");
482    }
483}