Skip to main content

rightkit_browser/
page.rs

1use crate::cdp_ext::{
2    command_for, download_params, page_scale_params, parse_ax_tree, run_interceptor, summarize_ax,
3    AxNode, AxSummary, DownloadBehavior, InterceptDecision, InterceptFailure, InterceptedRequest,
4    PageException, PausedCommand, RequestInterceptor, INTERCEPTOR_TIMEOUT, MAX_EXCEPTIONS,
5};
6use crate::cookies::{self, NetscapeCookie};
7use crate::design_mode::{self, DesignModeBridge, DesignModeSession, NativeGestureLatch};
8use crate::error::{cdp, BrowserError, Result};
9use crate::keys::{self, KeyDef};
10use crate::policy::{ActionKind, AdmissionRequest, BlockedRequest, Guard, LifecycleKind};
11use chromiumoxide::cdp::browser_protocol::accessibility::GetFullAxTreeParams;
12use chromiumoxide::cdp::browser_protocol::dom::SetFileInputFilesParams;
13use chromiumoxide::cdp::browser_protocol::fetch::{
14    EnableParams as FetchEnableParams, EventRequestPaused, FailRequestParams, RequestPattern,
15};
16use chromiumoxide::cdp::browser_protocol::input::{
17    DispatchKeyEventParams, DispatchKeyEventType, DispatchMouseEventParams, DispatchMouseEventType,
18    MouseButton,
19};
20use chromiumoxide::cdp::browser_protocol::inspector::{
21    EnableParams as InspectorEnableParams, EventTargetCrashed,
22};
23use chromiumoxide::cdp::browser_protocol::network::{ErrorReason, SetCookiesParams};
24use chromiumoxide::cdp::browser_protocol::page::CaptureScreenshotFormat;
25use chromiumoxide::cdp::browser_protocol::page::CreateIsolatedWorldParams;
26use chromiumoxide::cdp::js_protocol::runtime::{
27    AddBindingParams, EvaluateParams, EventBindingCalled, EventConsoleApiCalled,
28    EventExceptionThrown, ExecutionContextId,
29};
30use chromiumoxide::page::{Page, ScreenshotParams};
31use futures::StreamExt;
32use serde::{Deserialize, Serialize};
33use serde_json::Value;
34use std::collections::HashMap;
35use std::path::{Path, PathBuf};
36use std::sync::atomic::{AtomicBool, Ordering};
37use std::sync::{Arc, Mutex as StdMutex};
38use std::time::{Duration, Instant};
39use tokio::sync::{broadcast, Mutex};
40use tokio::task::JoinHandle;
41
42pub const MAX_CONSOLE_LINES: usize = 500;
43const MAX_UPLOAD_BYTES: u64 = 64 * 1024 * 1024;
44
45#[derive(Clone, Debug, Serialize)]
46pub struct ConsoleLine {
47    pub level: String,
48    pub text: String,
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
52pub struct Rect {
53    pub x: f64,
54    pub y: f64,
55    pub width: f64,
56    pub height: f64,
57}
58
59#[derive(Clone, Debug, Serialize)]
60pub struct ObservedNode {
61    /// `r<epoch>.<n>`; valid only while the page stays unchanged.
62    pub node_ref: String,
63    pub role: String,
64    /// Masked (`••••••••`) when `sensitive` is true.
65    pub name: String,
66    pub tag: String,
67    pub selector: String,
68    pub visible: bool,
69    pub disabled: bool,
70    /// True for password-like fields (`type=password`, `current-password`, `new-password`).
71    /// Their name is masked; callers should mask any value they show.
72    pub sensitive: bool,
73    /// CDP frame id of the document the node was read from. An observation reads the main
74    /// document only (iframe contents are not enumerated, see the changelog), so this is the
75    /// main frame's id for every node; it does not make iframe controls observable.
76    pub frame_id: String,
77    /// Stable across consecutive observations of the same document for the same selector.
78    /// `0` when the node has no selector (such nodes cannot be targeted by ref either).
79    pub stable_id: u64,
80    pub bounds: Rect,
81}
82
83#[derive(Clone, Debug, Serialize)]
84pub struct Observation {
85    pub page_id: String,
86    pub epoch: u64,
87    pub url: String,
88    pub title: String,
89    pub viewport: Rect,
90    pub nodes: Vec<ObservedNode>,
91    /// Accessibility summary of the main frame, bounded to depth [`OBSERVE_AX_DEPTH`].
92    pub ax: Vec<AxSummary>,
93    pub console_errors: usize,
94    /// Refs/roles/names added, removed, or changed since the previous observation.
95    pub added: Vec<String>,
96    pub removed: Vec<String>,
97}
98
99/// Depth bound for the accessibility summary in an [`Observation`].
100pub const OBSERVE_AX_DEPTH: u32 = 12;
101
102/// How long a history traversal waits for a navigation event before returning. A traversal
103/// that fires no navigation (bfcache restore, same-document entry) must not hang the caller.
104const HISTORY_NAVIGATION_WAIT: Duration = Duration::from_secs(10);
105
106/// Screenshot options for [`BrowserPage::screenshot_with`].
107#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
108pub struct ScreenshotOptions {
109    /// Capture with a transparent background. Pair with
110    /// [`BrowserPage::set_transparent_background`] for a fully transparent page.
111    pub omit_background: bool,
112}
113
114/// What an action addresses.
115#[derive(Clone, Debug)]
116pub enum Target {
117    /// Ref from [`BrowserPage::observe`]; checked for staleness.
118    Ref(String),
119    /// A CSS selector that must match exactly one element.
120    Selector(String),
121    /// Viewport coordinates.
122    Point(f64, f64),
123}
124
125impl Target {
126    pub fn css(s: impl Into<String>) -> Self {
127        Target::Selector(s.into())
128    }
129    pub fn node_ref(s: impl Into<String>) -> Self {
130        Target::Ref(s.into())
131    }
132}
133
134#[derive(Clone, Debug, Deserialize)]
135struct RawNode {
136    role: String,
137    name: String,
138    tag: String,
139    selector: String,
140    visible: bool,
141    disabled: bool,
142    #[serde(default)]
143    sensitive: bool,
144    bounds: Rect,
145}
146
147#[derive(Clone, Debug)]
148struct RefEntry {
149    selector: String,
150    tag: String,
151    role: String,
152    name: String,
153}
154
155#[derive(Default)]
156struct ObsState {
157    epoch: u64,
158    fingerprint: String,
159    refs: HashMap<String, RefEntry>,
160    previous: HashMap<String, String>,
161    /// Stable ids of the previous observation's selectors (bounded by its node count).
162    stable: HashMap<String, u64>,
163    next_stable: u64,
164}
165
166/// What the request-interception pump has done on one page. Reported when a navigation
167/// fails, so a timeout says how far the navigation got: no request paused (it never reached
168/// the network stage), paused but not answered (the policy check did not return), or
169/// continued (the request left the browser and the proxy or the server did not finish it).
170#[derive(Default)]
171struct InterceptStats {
172    paused: std::sync::atomic::AtomicUsize,
173    continued: std::sync::atomic::AtomicUsize,
174    fulfilled: std::sync::atomic::AtomicUsize,
175    refused: std::sync::atomic::AtomicUsize,
176    errors: std::sync::atomic::AtomicUsize,
177    last_error: StdMutex<Option<String>>,
178}
179
180impl InterceptStats {
181    fn summary(&self) -> String {
182        use std::sync::atomic::Ordering::Relaxed;
183        let mut text = format!(
184            "requests paused {}, continued {}, refused {}",
185            self.paused.load(Relaxed),
186            self.continued.load(Relaxed),
187            self.refused.load(Relaxed)
188        );
189        let fulfilled = self.fulfilled.load(Relaxed);
190        if fulfilled > 0 {
191            text.push_str(&format!(", fulfilled {fulfilled}"));
192        }
193        let errors = self.errors.load(Relaxed);
194        if errors > 0 {
195            let last = self.last_error.lock().unwrap().clone().unwrap_or_default();
196            text.push_str(&format!(", {errors} not answered: {last}"));
197        }
198        text
199    }
200}
201
202pub struct BrowserPage {
203    id: String,
204    /// CDP target id: the stable identity of the tab (`id` is the session's own sequence).
205    target_id: String,
206    inner: Page,
207    console: Arc<Mutex<Vec<ConsoleLine>>>,
208    obs: StdMutex<ObsState>,
209    mouse: StdMutex<(f64, f64)>,
210    buttons: StdMutex<i64>,
211    /// Serializes mutations so concurrent callers commit in order.
212    lane: Mutex<()>,
213    upload_root: Option<PathBuf>,
214    pumps: StdMutex<Vec<JoinHandle<()>>>,
215    guard: Arc<Guard>,
216    blocked: Arc<StdMutex<Vec<BlockedRequest>>>,
217    intercept: Arc<InterceptStats>,
218    /// Caller hook consulted after the network policy; see [`BrowserPage::set_request_interceptor`].
219    interceptor: Arc<StdMutex<Option<RequestInterceptor>>>,
220    /// True once this page's request-interception pump (and `Fetch.enable`) is running.
221    pump_running: AtomicBool,
222    /// The fixture session owns `Fetch` on this page; a caller hook cannot share it.
223    fixture_fetch_owner: bool,
224    exceptions: Arc<StdMutex<Vec<PageException>>>,
225    exception_tx: broadcast::Sender<PageException>,
226    /// Latest native input gesture (pointer press, key down) this page dispatched.
227    design_gesture: Arc<NativeGestureLatch>,
228    /// Isolated-world context of the design-mode picker, once enabled.
229    design_context: StdMutex<Option<ExecutionContextId>>,
230}
231
232/// Buffered capacity of an exception subscription; a slower receiver sees `Lagged`.
233const EXCEPTION_CHANNEL: usize = 64;
234
235impl BrowserPage {
236    pub(crate) async fn attach(
237        id: String,
238        inner: Page,
239        upload_root: Option<PathBuf>,
240        guard: Arc<Guard>,
241        fixture_fetch_owner: bool,
242    ) -> Result<Self> {
243        let console = Arc::new(Mutex::new(Vec::new()));
244        let mut pumps = Vec::new();
245        let mut ev = inner
246            .event_listener::<EventConsoleApiCalled>()
247            .await
248            .map_err(cdp)?;
249        let sink = console.clone();
250        pumps.push(tokio::spawn(async move {
251            while let Some(e) = ev.next().await {
252                let text = e
253                    .args
254                    .iter()
255                    .map(|a| match (&a.value, &a.description) {
256                        (Some(Value::String(s)), _) => s.clone(),
257                        (Some(v), _) => v.to_string(),
258                        (None, Some(d)) => d.clone(),
259                        _ => String::new(),
260                    })
261                    .collect::<Vec<_>>()
262                    .join(" ");
263                push_capped(
264                    &sink,
265                    ConsoleLine {
266                        level: format!("{:?}", e.r#type).to_lowercase(),
267                        text,
268                    },
269                )
270                .await;
271            }
272        }));
273        let mut ex = inner
274            .event_listener::<EventExceptionThrown>()
275            .await
276            .map_err(cdp)?;
277        let sink = console.clone();
278        let exceptions = Arc::new(StdMutex::new(Vec::new()));
279        let (exception_tx, _) = broadcast::channel(EXCEPTION_CHANNEL);
280        let (ex_log, ex_tx) = (exceptions.clone(), exception_tx.clone());
281        pumps.push(tokio::spawn(async move {
282            while let Some(e) = ex.next().await {
283                if let Some(parsed) = serde_json::to_value(&*e)
284                    .ok()
285                    .and_then(|v| PageException::from_cdp_value(&v))
286                {
287                    {
288                        let mut log = ex_log.lock().unwrap();
289                        if log.len() >= MAX_EXCEPTIONS {
290                            log.remove(0);
291                        }
292                        log.push(parsed.clone());
293                    }
294                    // No receiver is the normal case; the buffered list still has it.
295                    let _ = ex_tx.send(parsed);
296                }
297                let d = &e.exception_details;
298                let text = d
299                    .exception
300                    .as_ref()
301                    .and_then(|x| x.description.clone())
302                    .unwrap_or_else(|| d.text.clone());
303                push_capped(
304                    &sink,
305                    ConsoleLine {
306                        level: "exception".into(),
307                        text,
308                    },
309                )
310                .await;
311            }
312        }));
313        // Renderer crash -> `Crash` lifecycle event for this page.
314        let mut crashed = inner
315            .event_listener::<EventTargetCrashed>()
316            .await
317            .map_err(cdp)?;
318        let (g, page_id) = (guard.clone(), id.clone());
319        pumps.push(tokio::spawn(async move {
320            while crashed.next().await.is_some() {
321                g.emit_kind(LifecycleKind::Crash, "renderer crashed", |e| {
322                    e.page_id = Some(page_id.clone());
323                });
324            }
325        }));
326        inner
327            .execute(InspectorEnableParams::default())
328            .await
329            .map_err(cdp)?;
330        let blocked = Arc::new(StdMutex::new(Vec::new()));
331        let intercept = Arc::new(InterceptStats::default());
332        let interceptor = Arc::new(StdMutex::new(None));
333        let mut pump_running = false;
334        if !guard.network.unrestricted && !fixture_fetch_owner {
335            // Pause every request (document, redirect hops, subresources) and
336            // decide before it leaves the browser. Enabled before any navigation.
337            pumps.push(
338                start_intercept_pump(
339                    &inner,
340                    &id,
341                    &guard,
342                    blocked.clone(),
343                    intercept.clone(),
344                    interceptor.clone(),
345                )
346                .await?,
347            );
348            pump_running = true;
349        }
350        let target_id = inner.target_id().as_ref().to_string();
351        Ok(Self {
352            id,
353            target_id,
354            inner,
355            console,
356            obs: StdMutex::new(ObsState::default()),
357            mouse: StdMutex::new((0.0, 0.0)),
358            buttons: StdMutex::new(0),
359            lane: Mutex::new(()),
360            upload_root,
361            pumps: StdMutex::new(pumps),
362            guard,
363            blocked,
364            intercept,
365            interceptor,
366            pump_running: AtomicBool::new(pump_running),
367            fixture_fetch_owner,
368            exceptions,
369            exception_tx,
370            design_gesture: Arc::new(NativeGestureLatch::new()),
371            design_context: StdMutex::new(None),
372        })
373    }
374
375    pub fn id(&self) -> &str {
376        &self.id
377    }
378
379    /// The CDP target id of this tab. Unlike [`BrowserPage::id`], it is Chrome's own identity
380    /// for the tab and does not change when the session renumbers pages.
381    pub fn target_id(&self) -> &str {
382        &self.target_id
383    }
384
385    /// Frame ids of every frame in the page (CDP `Page.getFrameTree`), read-only.
386    pub async fn frames(&self) -> Result<Vec<String>> {
387        let frames = self.inner.frames().await.map_err(cdp)?;
388        Ok(frames.iter().map(|f| f.as_ref().to_string()).collect())
389    }
390
391    /// Install (or with `None`, remove) a caller hook that answers every request this page
392    /// makes: continue, continue with changes, fulfil from memory, or fail. Redirect hops arrive
393    /// as separate requests with [`InterceptedRequest::redirected_from`] set, so a hook that pins
394    /// an origin revalidates each hop.
395    ///
396    /// The session's network policy runs first and its refusals are final; the hook only
397    /// narrows what the policy allows. A hook that takes longer than 30 s fails the request.
398    /// Turns on `Fetch` interception for this page when the policy had not (an unrestricted
399    /// session); requests already in flight are not affected. Removing the hook lets requests
400    /// through unchanged but leaves interception running. Not available on a fixture page, whose
401    /// session owns `Fetch`: returns [`BrowserError::Invalid`].
402    pub async fn set_request_interceptor(&self, hook: Option<RequestInterceptor>) -> Result<()> {
403        if self.fixture_fetch_owner {
404            return Err(BrowserError::Invalid(
405                "a fixture page's session owns request interception".into(),
406            ));
407        }
408        let install = hook.is_some();
409        *self.interceptor.lock().unwrap() = hook;
410        if install && !self.pump_running.swap(true, Ordering::SeqCst) {
411            match start_intercept_pump(
412                &self.inner,
413                &self.id,
414                &self.guard,
415                self.blocked.clone(),
416                self.intercept.clone(),
417                self.interceptor.clone(),
418            )
419            .await
420            {
421                Ok(pump) => self.pumps.lock().unwrap().push(pump),
422                Err(e) => {
423                    self.pump_running.store(false, Ordering::SeqCst);
424                    *self.interceptor.lock().unwrap() = None;
425                    return Err(e);
426                }
427            }
428        }
429        Ok(())
430    }
431
432    /// The page's full accessibility tree (`Accessibility.getFullAXTree`), root frame, in CDP
433    /// order. Ignored nodes are included and flagged. Read-only.
434    pub async fn accessibility_tree(&self) -> Result<Vec<AxNode>> {
435        self.ax_tree(None).await
436    }
437
438    /// The accessibility tree cut off below `depth` (root is depth 0). Use it on heavy pages,
439    /// where the full tree costs too much. Read-only, like [`BrowserPage::accessibility_tree`].
440    pub async fn accessibility_tree_with(&self, depth: u32) -> Result<Vec<AxNode>> {
441        self.ax_tree(Some(depth)).await
442    }
443
444    async fn ax_tree(&self, depth: Option<u32>) -> Result<Vec<AxNode>> {
445        let params = GetFullAxTreeParams {
446            depth: depth.map(i64::from),
447            ..Default::default()
448        };
449        let r = self.inner.execute(params).await.map_err(cdp)?;
450        let wire = serde_json::to_value(&r.result).map_err(cdp)?;
451        Ok(parse_ax_tree(&wire))
452    }
453
454    /// Make the page background transparent (`Emulation.setDefaultBackgroundColorOverride`
455    /// with alpha 0), or restore Chrome's default with `false`. Pair with
456    /// [`BrowserPage::screenshot_with`] and `omit_background` to capture alpha. Like
457    /// [`BrowserPage::set_page_scale`], this changes rendering only and is not admitted.
458    pub async fn set_transparent_background(&self, transparent: bool) -> Result<()> {
459        use chromiumoxide::cdp::browser_protocol::dom::Rgba;
460        use chromiumoxide::cdp::browser_protocol::emulation::SetDefaultBackgroundColorOverrideParams;
461        let params = if transparent {
462            SetDefaultBackgroundColorOverrideParams::builder()
463                .color(Rgba {
464                    r: 0,
465                    g: 0,
466                    b: 0,
467                    a: Some(0.0),
468                })
469                .build()
470        } else {
471            SetDefaultBackgroundColorOverrideParams::builder().build()
472        };
473        self.inner.execute(params).await.map_err(cdp)?;
474        Ok(())
475    }
476
477    /// Uncaught exceptions and unhandled rejections seen so far (`Runtime.exceptionThrown`),
478    /// oldest first, at most [`MAX_EXCEPTIONS`](crate::MAX_EXCEPTIONS). Collected from the moment
479    /// the page exists, so nothing from its first navigation is missed.
480    pub fn exceptions(&self) -> Vec<PageException> {
481        self.exceptions.lock().unwrap().clone()
482    }
483
484    pub fn clear_exceptions(&self) {
485        self.exceptions.lock().unwrap().clear();
486    }
487
488    /// Live stream of exceptions from now on. The page exists before its first navigation, so a
489    /// subscriber taken before `goto` sees every exception it raises. A receiver that falls more
490    /// than 64 behind gets `RecvError::Lagged`; [`BrowserPage::exceptions`] still has them.
491    pub fn subscribe_exceptions(&self) -> broadcast::Receiver<PageException> {
492        self.exception_tx.subscribe()
493    }
494
495    /// Set the page scale factor (pinch zoom, `Emulation.setPageScaleFactor`). Must be positive
496    /// and finite. Distinct from the device scale factor of [`BrowserPage::set_viewport`].
497    pub async fn set_page_scale(&self, scale: f64) -> Result<()> {
498        self.inner
499            .execute(page_scale_params(scale)?)
500            .await
501            .map_err(cdp)?;
502        Ok(())
503    }
504
505    /// Choose what happens to downloads (`Browser.setDownloadBehavior`). `Allow` and
506    /// `AllowAndName` need an absolute, existing directory; downloads go nowhere else.
507    /// Admitted as an `Eval`-kind effect (detail `download_behavior ...`) because it lets pages
508    /// write files. Applies to the browser's default context, so it covers every page of a
509    /// session; a later call replaces an earlier one.
510    pub async fn set_download_behavior(&self, behavior: &DownloadBehavior) -> Result<()> {
511        let params = download_params(behavior)?;
512        self.admit(
513            ActionKind::Eval,
514            None,
515            None,
516            Some(format!("download_behavior {behavior:?}")),
517        )
518        .await?;
519        self.inner.execute(params).await.map_err(cdp)?;
520        Ok(())
521    }
522
523    /// Set `cookies` in the browser profile this page belongs to (`Network.setCookies`) and
524    /// return how many were set. The cookies apply to the whole profile, not to this page, and
525    /// persist with a named or directory profile. A subdomain-matching cookie gets a leading dot
526    /// on its domain; a host-only cookie does not. Chrome rejects the whole batch if one cookie
527    /// is invalid (for example a `__Secure-` name without `secure`); the error then sets none
528    /// and its text never contains a cookie value.
529    ///
530    /// Domain filtering, user consent and file selection belong to the caller: this sets exactly
531    /// what it is given. Admitted as an `Eval`-kind effect (detail `import_cookies`, the count
532    /// and the distinct domains; never names or values). An empty slice returns `Ok(0)` without
533    /// contacting the browser; more than [`MAX_COOKIES`](crate::cookies::MAX_COOKIES) is refused.
534    pub async fn import_cookies(&self, cookies: &[NetscapeCookie]) -> Result<usize> {
535        if cookies.is_empty() {
536            return Ok(0);
537        }
538        if cookies.len() > cookies::MAX_COOKIES {
539            return Err(BrowserError::Invalid(format!(
540                "import_cookies takes at most {} cookies",
541                cookies::MAX_COOKIES
542            )));
543        }
544        self.admit(
545            ActionKind::Eval,
546            None,
547            None,
548            Some(cookies::admission_detail(cookies)),
549        )
550        .await?;
551        let _l = self.lane.lock().await;
552        let params = SetCookiesParams::new(cookies::to_cdp_params(cookies));
553        self.inner.execute(params).await.map_err(|e| {
554            BrowserError::Cdp(format!(
555                "Network.setCookies: {}",
556                cookies::scrub(&e.to_string(), cookies)
557            ))
558        })?;
559        Ok(cookies.len())
560    }
561
562    /// Requests the network policy refused on this page (redirect hops and subresources included).
563    pub fn blocked_requests(&self) -> Vec<BlockedRequest> {
564        self.blocked.lock().unwrap().clone()
565    }
566
567    /// Typed pre-effect admission. Reads no page state beyond the current URL.
568    async fn admit(
569        &self,
570        action: ActionKind,
571        url: Option<String>,
572        target: Option<String>,
573        detail: Option<String>,
574    ) -> Result<()> {
575        let url = match url {
576            Some(u) => Some(u),
577            None if self.guard.admission.is_some() => Some(self.url().await),
578            None => None,
579        };
580        self.guard
581            .admit(AdmissionRequest {
582                session_id: self.guard.session_id.clone(),
583                page_id: self.id.clone(),
584                action,
585                url,
586                target,
587                detail,
588            })
589            .await
590    }
591
592    /// Escape hatch to the underlying chromiumoxide page.
593    pub fn raw(&self) -> &Page {
594        &self.inner
595    }
596
597    pub(crate) fn abort_pumps(&self) {
598        if let Ok(mut p) = self.pumps.lock() {
599            for h in p.drain(..) {
600                h.abort();
601            }
602        }
603    }
604
605    pub(crate) async fn close_inner(&self) -> Result<()> {
606        self.abort_pumps();
607        self.inner.clone().close().await.map_err(cdp)
608    }
609
610    pub async fn bring_to_front(&self) -> Result<()> {
611        self.inner.bring_to_front().await.map_err(cdp)?;
612        Ok(())
613    }
614
615    // ---- navigation ------------------------------------------------------
616
617    fn invalidate(&self) {
618        let mut o = self.obs.lock().unwrap();
619        o.epoch += 1;
620        o.refs.clear();
621        o.fingerprint.clear();
622        // A navigation starts a new document: its selectors do not carry stable ids over.
623        o.stable.clear();
624    }
625
626    /// Waits until this new tab's own first navigation (to about:blank) has committed.
627    ///
628    /// A tab is created at about:blank and that navigation commits a little later. A
629    /// navigation sent before then is discarded by that commit: Chrome answers it with
630    /// `net::ERR_ABORTED` and no load ever follows, so the caller waits out its whole request
631    /// timeout. Seen on Windows, where a new tab's renderer starts more slowly.
632    ///
633    /// Before the commit the tab's committed history entry has an empty URL. The tab counts
634    /// as settled when that entry has a URL and the main frame's loader is the same on two
635    /// consecutive polls. Bounded at two seconds, and it stops at once if Chrome does not
636    /// answer, so a browser that behaves differently is not waited on.
637    pub(crate) async fn settle_initial_document(&self) {
638        use chromiumoxide::cdp::browser_protocol::page::{
639            GetFrameTreeParams, GetNavigationHistoryParams,
640        };
641        use std::time::{Duration, Instant};
642        let deadline = Instant::now() + Duration::from_secs(2);
643        let mut seen: Option<String> = None;
644        while Instant::now() < deadline {
645            let Ok(history) = self
646                .inner
647                .execute(GetNavigationHistoryParams::default())
648                .await
649            else {
650                return;
651            };
652            let Ok(tree) = self.inner.execute(GetFrameTreeParams::default()).await else {
653                return;
654            };
655            let committed = usize::try_from(history.result.current_index)
656                .ok()
657                .and_then(|index| history.result.entries.get(index))
658                .is_some_and(|entry| !entry.url.is_empty());
659            let loader = format!("{:?}", tree.result.frame_tree.frame.loader_id);
660            if !committed {
661                seen = None;
662            } else if seen.as_deref() == Some(loader.as_str()) {
663                return;
664            } else {
665                seen = Some(loader);
666            }
667            tokio::time::sleep(Duration::from_millis(10)).await;
668        }
669    }
670
671    pub async fn goto(&self, url: &str) -> Result<()> {
672        // EFF-001 order: policy, then approval; both before any side effect.
673        self.guard
674            .check_url(Some(&self.id), url, "Navigation")
675            .await?;
676        self.admit(ActionKind::Navigate, Some(url.to_string()), None, None)
677            .await?;
678        let _l = self.lane.lock().await;
679        self.inner.goto(url).await.map_err(|e| {
680            BrowserError::Cdp(format!(
681                "navigate '{url}': {e} ({})",
682                self.intercept.summary()
683            ))
684        })?;
685        self.inner.wait_for_navigation().await.map_err(cdp)?;
686        self.invalidate();
687        Ok(())
688    }
689
690    pub async fn reload(&self) -> Result<()> {
691        self.admit(ActionKind::Reload, None, None, None).await?;
692        let _l = self.lane.lock().await;
693        self.inner.reload().await.map_err(cdp)?;
694        self.inner.wait_for_navigation().await.map_err(cdp)?;
695        self.invalidate();
696        Ok(())
697    }
698
699    pub async fn history(&self, delta: i32) -> Result<()> {
700        self.admit(
701            ActionKind::History,
702            None,
703            None,
704            Some(format!("delta={delta}")),
705        )
706        .await?;
707        let _l = self.lane.lock().await;
708        self.inner
709            .evaluate(format!("history.go({delta})"))
710            .await
711            .map_err(cdp)?;
712        tokio::time::sleep(Duration::from_millis(150)).await;
713        // Bounded: a traversal that fires no navigation event (bfcache, same-document entry)
714        // returns once the wait elapses; the page is then read as it is.
715        if let Ok(waited) =
716            tokio::time::timeout(HISTORY_NAVIGATION_WAIT, self.inner.wait_for_navigation()).await
717        {
718            waited.map_err(cdp)?;
719        }
720        self.invalidate();
721        Ok(())
722    }
723
724    pub async fn url(&self) -> String {
725        self.inner.url().await.ok().flatten().unwrap_or_default()
726    }
727
728    pub async fn title(&self) -> String {
729        self.inner
730            .get_title()
731            .await
732            .ok()
733            .flatten()
734            .unwrap_or_default()
735    }
736
737    /// Rendered text (`document.body.innerText`).
738    pub async fn text(&self) -> Result<String> {
739        self.eval_internal("document.body ? document.body.innerText : ''")
740            .await
741            .map(|v| v.as_str().unwrap_or_default().to_string())
742    }
743
744    /// Evaluate a JS expression and return its JSON value. Script can navigate and
745    /// act, so it is admitted like any other effect.
746    pub async fn eval(&self, expr: &str) -> Result<Value> {
747        self.admit(
748            ActionKind::Eval,
749            None,
750            None,
751            Some(expr.chars().take(2000).collect()),
752        )
753        .await?;
754        self.eval_internal(expr).await
755    }
756
757    /// Runtime-owned evaluation (observation, geometry); never user script.
758    async fn eval_internal(&self, expr: &str) -> Result<Value> {
759        let r = self.inner.evaluate(expr).await.map_err(cdp)?;
760        Ok(r.value().cloned().unwrap_or(Value::Null))
761    }
762
763    pub async fn set_viewport(&self, width: u32, height: u32, scale: f64) -> Result<()> {
764        use chromiumoxide::cdp::browser_protocol::emulation::SetDeviceMetricsOverrideParams;
765        self.inner
766            .execute(SetDeviceMetricsOverrideParams::new(
767                i64::from(width),
768                i64::from(height),
769                scale,
770                false,
771            ))
772            .await
773            .map_err(cdp)?;
774        Ok(())
775    }
776
777    // ---- design mode -----------------------------------------------------
778
779    /// Enable the element picker for the current document. It runs in a fresh isolated world
780    /// and reports through a `Runtime.addBinding` function bound only to that world, so page
781    /// script can neither see nor forge picker messages. Prompt submissions are delivered only
782    /// when one native input gesture (a pointer press or key down this page dispatched)
783    /// authorizes them; see [`DesignModeBridge`]. Call once per document; navigation ends the
784    /// picker and requires a new call with a new nonce.
785    pub async fn enable_design_mode(&self, nonce: &str) -> Result<DesignModeSession> {
786        let script = design_mode::build_design_mode_script(nonce)?;
787        let mut bridge = DesignModeBridge::new(nonce)?;
788        let frame_id = self
789            .inner
790            .mainframe()
791            .await
792            .map_err(cdp)?
793            .ok_or_else(|| BrowserError::Invalid("no main frame".into()))?;
794        let mut events = self
795            .inner
796            .event_listener::<EventBindingCalled>()
797            .await
798            .map_err(cdp)?;
799        let mut add = AddBindingParams::new(bridge.binding_name());
800        add.execution_context_name = Some(bridge.world_name());
801        self.inner.execute(add).await.map_err(cdp)?;
802        let mut world = CreateIsolatedWorldParams::new(frame_id);
803        world.world_name = Some(bridge.world_name());
804        world.grant_univeral_access = Some(false);
805        let context = self
806            .inner
807            .execute(world)
808            .await
809            .map_err(cdp)?
810            .result
811            .execution_context_id;
812        *self.design_context.lock().unwrap() = Some(context);
813        let eval = EvaluateParams::builder()
814            .expression(script)
815            .context_id(context)
816            .build()
817            .map_err(BrowserError::Invalid)?;
818        self.inner.execute(eval).await.map_err(cdp)?;
819        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
820        let gesture = self.design_gesture.clone();
821        let pump = tokio::spawn(async move {
822            while let Some(e) = events.next().await {
823                let marker = bridge.accept(
824                    &e.name,
825                    &e.payload,
826                    e.execution_context_id == context,
827                    &gesture,
828                    design_mode::now_ms(),
829                );
830                if let Some(marker) = marker {
831                    if tx.send(marker).is_err() {
832                        break;
833                    }
834                }
835            }
836        });
837        self.pumps.lock().unwrap().push(pump);
838        Ok(DesignModeSession { events: rx })
839    }
840
841    /// Show the outcome of a submission in the picker popup (`window.__omniOnDesignResult`
842    /// in the picker's isolated world).
843    pub async fn design_mode_result(&self, id: u64, ok: bool, message: &str) -> Result<()> {
844        let context = (*self.design_context.lock().unwrap())
845            .ok_or_else(|| BrowserError::Invalid("design mode is not enabled".into()))?;
846        let arg = serde_json::json!({"id": id, "ok": ok, "message": message});
847        let eval = EvaluateParams::builder()
848            .expression(format!(
849                "window.__omniOnDesignResult && window.__omniOnDesignResult({arg})"
850            ))
851            .context_id(context)
852            .build()
853            .map_err(BrowserError::Invalid)?;
854        self.inner.execute(eval).await.map_err(cdp)?;
855        Ok(())
856    }
857
858    // ---- observation -----------------------------------------------------
859
860    pub async fn observe(&self) -> Result<Observation> {
861        let _l = self.lane.lock().await;
862        let frame_id = self
863            .inner
864            .mainframe()
865            .await
866            .map_err(cdp)?
867            .map(|f| f.as_ref().to_string())
868            .unwrap_or_default();
869        let ax = summarize_ax(&self.ax_tree(Some(OBSERVE_AX_DEPTH)).await?);
870        let raw: Vec<RawNode> = self
871            .inner
872            .evaluate(OBSERVE_JS)
873            .await
874            .map_err(cdp)?
875            .into_value()
876            .map_err(|e| BrowserError::Cdp(format!("decode observation: {e}")))?;
877        let viewport: Rect = self
878            .inner
879            .evaluate("({x:0,y:0,width:window.innerWidth,height:window.innerHeight})")
880            .await
881            .map_err(cdp)?
882            .into_value()
883            .map_err(cdp)?;
884        let fingerprint = raw
885            .iter()
886            .map(|n| {
887                format!(
888                    "{}|{}|{}|{}|{}",
889                    n.selector, n.role, n.name, n.visible, n.disabled
890                )
891            })
892            .collect::<Vec<_>>()
893            .join("\n");
894        let (epoch, nodes, added, removed) = {
895            let mut o = self.obs.lock().unwrap();
896            if o.fingerprint != fingerprint {
897                o.epoch += 1;
898                o.fingerprint = fingerprint;
899            }
900            let epoch = o.epoch;
901            o.refs.clear();
902            let mut cur = HashMap::new();
903            let mut cur_stable: HashMap<String, u64> = HashMap::new();
904            let mut nodes = Vec::new();
905            for (i, n) in raw.into_iter().enumerate() {
906                let name = if n.sensitive {
907                    "••••••••".to_string()
908                } else {
909                    n.name.clone()
910                };
911                let node_ref = format!("r{epoch}.{}", i + 1);
912                let stable_id = if n.selector.is_empty() {
913                    0
914                } else {
915                    let existing = o.stable.get(&n.selector).copied();
916                    let id = match existing {
917                        Some(id) => id,
918                        None => {
919                            o.next_stable += 1;
920                            o.next_stable
921                        }
922                    };
923                    cur_stable.insert(n.selector.clone(), id);
924                    id
925                };
926                if !n.selector.is_empty() {
927                    o.refs.insert(
928                        node_ref.clone(),
929                        RefEntry {
930                            selector: n.selector.clone(),
931                            tag: n.tag.clone(),
932                            role: n.role.clone(),
933                            name: name.clone(),
934                        },
935                    );
936                    cur.insert(n.selector.clone(), format!("{}|{}", n.role, name));
937                }
938                nodes.push(ObservedNode {
939                    node_ref,
940                    role: n.role,
941                    name,
942                    tag: n.tag,
943                    selector: n.selector,
944                    visible: n.visible,
945                    disabled: n.disabled,
946                    sensitive: n.sensitive,
947                    frame_id: frame_id.clone(),
948                    stable_id,
949                    bounds: n.bounds,
950                });
951            }
952            o.stable = cur_stable;
953            let added = cur
954                .keys()
955                .filter(|k| !o.previous.contains_key(*k))
956                .cloned()
957                .collect();
958            let removed = o
959                .previous
960                .keys()
961                .filter(|k| !cur.contains_key(*k))
962                .cloned()
963                .collect();
964            o.previous = cur;
965            (epoch, nodes, added, removed)
966        };
967        let console_errors = self
968            .console
969            .lock()
970            .await
971            .iter()
972            .filter(|l| matches!(l.level.as_str(), "error" | "exception"))
973            .count();
974        Ok(Observation {
975            page_id: self.id.clone(),
976            epoch,
977            url: self.url().await,
978            title: self.title().await,
979            viewport,
980            nodes,
981            ax,
982            console_errors,
983            added,
984            removed,
985        })
986    }
987
988    /// Resolve a target to a unique CSS selector, rejecting stale refs.
989    async fn resolve(&self, target: &Target) -> Result<Option<String>> {
990        match target {
991            Target::Point(..) => Ok(None),
992            Target::Selector(s) => {
993                self.unique(s).await?;
994                Ok(Some(s.clone()))
995            }
996            Target::Ref(r) => {
997                let (entry, current_epoch) = {
998                    let o = self.obs.lock().unwrap();
999                    (o.refs.get(r).cloned(), o.epoch)
1000                };
1001                let entry = entry.ok_or_else(|| BrowserError::StaleRef(r.clone()))?;
1002                let ref_epoch: u64 = r
1003                    .trim_start_matches('r')
1004                    .split('.')
1005                    .next()
1006                    .and_then(|e| e.parse().ok())
1007                    .unwrap_or(0);
1008                if ref_epoch != current_epoch {
1009                    return Err(BrowserError::StaleRef(r.clone()));
1010                }
1011                // Identity check: the element behind the selector must still look
1012                // like what was observed, else the page changed under the ref.
1013                let sig = self
1014                    .eval(&format!(
1015                        "(()=>{{const l=document.querySelectorAll({s});if(l.length!==1)return null;const e=l[0];\
1016                         return {{tag:e.tagName.toLowerCase(),name:(e.getAttribute('aria-label')||e.innerText||e.value||e.getAttribute('placeholder')||'').trim().slice(0,160)}}}})()",
1017                        s = js(&entry.selector)
1018                    ))
1019                    .await?;
1020                let ok = sig.get("tag").and_then(Value::as_str) == Some(entry.tag.as_str())
1021                    && sig.get("name").and_then(Value::as_str) == Some(entry.name.as_str())
1022                    || (sig.get("tag").and_then(Value::as_str) == Some(entry.tag.as_str())
1023                        && matches!(entry.tag.as_str(), "input" | "textarea" | "select")); // value changes as the user types
1024                if !ok {
1025                    return Err(BrowserError::StaleRef(r.clone()));
1026                }
1027                let _ = &entry.role;
1028                Ok(Some(entry.selector))
1029            }
1030        }
1031    }
1032
1033    async fn unique(&self, selector: &str) -> Result<()> {
1034        let n = self
1035            .eval_internal(&format!(
1036                "document.querySelectorAll({}).length",
1037                js(selector)
1038            ))
1039            .await?
1040            .as_u64()
1041            .unwrap_or(0);
1042        match n {
1043            1 => Ok(()),
1044            0 => Err(BrowserError::NoElement(selector.into())),
1045            n => Err(BrowserError::Ambiguous(selector.into(), n)),
1046        }
1047    }
1048
1049    /// Scroll into view, return the centre point, and verify nothing covers it.
1050    async fn point_of(&self, target: &Target) -> Result<(f64, f64)> {
1051        if let Target::Point(x, y) = target {
1052            return Ok((*x, *y));
1053        }
1054        let sel = self.resolve(target).await?.expect("selector");
1055        let v = self
1056            .eval(&format!(
1057                "(()=>{{const e=document.querySelector({s});e.scrollIntoView({{block:'center',inline:'center'}});\
1058                 const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return null;\
1059                 const x=r.x+r.width/2,y=r.y+r.height/2;const t=document.elementFromPoint(x,y);\
1060                 const hit=!!t&&(t===e||e.contains(t)||t.contains(e));return {{x,y,hit}}}})()",
1061                s = js(&sel)
1062            ))
1063            .await?;
1064        if v.is_null() {
1065            return Err(BrowserError::NotInteractable(sel));
1066        }
1067        if v.get("hit").and_then(Value::as_bool) != Some(true) {
1068            return Err(BrowserError::NotInteractable(format!(
1069                "{sel} (covered by another element)"
1070            )));
1071        }
1072        Ok((
1073            v["x"].as_f64().unwrap_or(0.0),
1074            v["y"].as_f64().unwrap_or(0.0),
1075        ))
1076    }
1077
1078    // ---- real pointer input ----------------------------------------------
1079
1080    async fn mouse_event(
1081        &self,
1082        kind: DispatchMouseEventType,
1083        x: f64,
1084        y: f64,
1085        button: MouseButton,
1086        click_count: i64,
1087    ) -> Result<()> {
1088        if matches!(kind, DispatchMouseEventType::MousePressed) {
1089            self.design_gesture.stamp();
1090        }
1091        let mut p = DispatchMouseEventParams::new(kind.clone(), x, y);
1092        p.button = Some(button);
1093        p.click_count = Some(click_count);
1094        p.buttons = Some(match kind {
1095            DispatchMouseEventType::MousePressed => 1,
1096            DispatchMouseEventType::MouseReleased => 0,
1097            _ => *self.buttons.lock().unwrap(),
1098        });
1099        self.inner.execute(p).await.map_err(cdp)?;
1100        *self.mouse.lock().unwrap() = (x, y);
1101        Ok(())
1102    }
1103
1104    async fn move_to(&self, x: f64, y: f64) -> Result<()> {
1105        self.mouse_event(
1106            DispatchMouseEventType::MouseMoved,
1107            x,
1108            y,
1109            MouseButton::None,
1110            0,
1111        )
1112        .await
1113    }
1114
1115    pub async fn hover(&self, target: &Target) -> Result<()> {
1116        self.admit(ActionKind::Hover, None, Some(describe(target)), None)
1117            .await?;
1118        let _l = self.lane.lock().await;
1119        let (x, y) = self.point_of(target).await?;
1120        self.move_to(x, y).await
1121    }
1122
1123    pub async fn click(&self, target: &Target) -> Result<()> {
1124        self.admit(ActionKind::Click, None, Some(describe(target)), None)
1125            .await?;
1126        let _l = self.lane.lock().await;
1127        self.click_n(target, 1).await
1128    }
1129
1130    pub async fn double_click(&self, target: &Target) -> Result<()> {
1131        self.admit(ActionKind::DoubleClick, None, Some(describe(target)), None)
1132            .await?;
1133        let _l = self.lane.lock().await;
1134        self.click_n(target, 2).await
1135    }
1136
1137    /// Caller holds the lane.
1138    async fn click_n(&self, target: &Target, count: i64) -> Result<()> {
1139        let (x, y) = self.point_of(target).await?;
1140        self.move_to(x, y).await?;
1141        for n in 1..=count {
1142            self.mouse_event(
1143                DispatchMouseEventType::MousePressed,
1144                x,
1145                y,
1146                MouseButton::Left,
1147                n,
1148            )
1149            .await?;
1150            self.mouse_event(
1151                DispatchMouseEventType::MouseReleased,
1152                x,
1153                y,
1154                MouseButton::Left,
1155                n,
1156            )
1157            .await?;
1158        }
1159        Ok(())
1160    }
1161
1162    /// Press at `from`, move in `steps` increments, release at `to`.
1163    pub async fn drag(&self, from: &Target, to: &Target, steps: u32) -> Result<()> {
1164        self.admit(
1165            ActionKind::Drag,
1166            None,
1167            Some(format!("{} -> {}", describe(from), describe(to))),
1168            None,
1169        )
1170        .await?;
1171        let _l = self.lane.lock().await;
1172        let (x0, y0) = self.point_of(from).await?;
1173        let (x1, y1) = self.point_of(to).await?;
1174        self.move_to(x0, y0).await?;
1175        self.mouse_event(
1176            DispatchMouseEventType::MousePressed,
1177            x0,
1178            y0,
1179            MouseButton::Left,
1180            1,
1181        )
1182        .await?;
1183        *self.buttons.lock().unwrap() = 1;
1184        let steps = steps.max(1);
1185        for i in 1..=steps {
1186            let t = f64::from(i) / f64::from(steps);
1187            self.mouse_event(
1188                DispatchMouseEventType::MouseMoved,
1189                x0 + (x1 - x0) * t,
1190                y0 + (y1 - y0) * t,
1191                MouseButton::Left,
1192                0,
1193            )
1194            .await?;
1195        }
1196        *self.buttons.lock().unwrap() = 0;
1197        self.mouse_event(
1198            DispatchMouseEventType::MouseReleased,
1199            x1,
1200            y1,
1201            MouseButton::Left,
1202            1,
1203        )
1204        .await
1205    }
1206
1207    /// Mouse-wheel scroll at the target (or viewport centre when `None`).
1208    pub async fn wheel(&self, at: Option<&Target>, dx: f64, dy: f64) -> Result<()> {
1209        self.admit(
1210            ActionKind::Wheel,
1211            None,
1212            at.map(describe),
1213            Some(format!("dx={dx} dy={dy}")),
1214        )
1215        .await?;
1216        let _l = self.lane.lock().await;
1217        let (x, y) = match at {
1218            Some(t) => self.point_of(t).await?,
1219            None => {
1220                let v = self
1221                    .eval_internal("({x:innerWidth/2,y:innerHeight/2})")
1222                    .await?;
1223                (
1224                    v["x"].as_f64().unwrap_or(100.0),
1225                    v["y"].as_f64().unwrap_or(100.0),
1226                )
1227            }
1228        };
1229        let mut p = DispatchMouseEventParams::new(DispatchMouseEventType::MouseWheel, x, y);
1230        p.delta_x = Some(dx);
1231        p.delta_y = Some(dy);
1232        self.inner.execute(p).await.map_err(cdp)?;
1233        Ok(())
1234    }
1235
1236    /// Programmatic scroll (`scrollBy`) of the element at `target`, or of the window when
1237    /// `None`. Use it where a wheel event at the element's centre is wrong: a covered element,
1238    /// or one that is not scrollable under the pointer. Selectors and refs must resolve to one
1239    /// element; a point scrolls the element under it. No element at a point is an error.
1240    pub async fn scroll_by(&self, target: Option<&Target>, dx: f64, dy: f64) -> Result<()> {
1241        if !dx.is_finite() || !dy.is_finite() {
1242            return Err(BrowserError::Invalid(format!(
1243                "scroll offsets must be finite, got dx={dx} dy={dy}"
1244            )));
1245        }
1246        self.admit(
1247            ActionKind::Wheel,
1248            None,
1249            target.map(describe),
1250            Some(format!("scroll_by dx={dx} dy={dy}")),
1251        )
1252        .await?;
1253        let _l = self.lane.lock().await;
1254        let offset = format!("{{left:{dx},top:{dy}}}");
1255        let found = match target {
1256            None => {
1257                self.eval_internal(&format!(
1258                    "(()=>{{window.scrollBy({offset});return true}})()"
1259                ))
1260                .await?
1261            }
1262            Some(Target::Point(x, y)) => {
1263                if !x.is_finite() || !y.is_finite() {
1264                    return Err(BrowserError::Invalid(format!(
1265                        "scroll point must be finite, got {x},{y}"
1266                    )));
1267                }
1268                self.eval_internal(&format!(
1269                    "(()=>{{const e=document.elementFromPoint({x},{y});if(!e)return false;e.scrollBy({offset});return true}})()"
1270                ))
1271                .await?
1272            }
1273            Some(t) => {
1274                let sel = self.resolve(t).await?.expect("selector");
1275                self.eval_internal(&format!(
1276                    "(()=>{{const e=document.querySelector({});if(!e)return false;e.scrollBy({offset});return true}})()",
1277                    js(&sel)
1278                ))
1279                .await?
1280            }
1281        };
1282        if found.as_bool() != Some(true) {
1283            return Err(BrowserError::NoElement(
1284                target.map(describe).unwrap_or_default(),
1285            ));
1286        }
1287        Ok(())
1288    }
1289
1290    // ---- real keyboard input ---------------------------------------------
1291
1292    async fn key_event(
1293        &self,
1294        kind: DispatchKeyEventType,
1295        d: &KeyDef,
1296        mods: i64,
1297        with_text: bool,
1298    ) -> Result<()> {
1299        if matches!(
1300            kind,
1301            DispatchKeyEventType::KeyDown | DispatchKeyEventType::RawKeyDown
1302        ) {
1303            self.design_gesture.stamp();
1304        }
1305        let mut p = DispatchKeyEventParams::new(kind);
1306        p.modifiers = Some(mods);
1307        p.key = Some(d.key.clone());
1308        if !d.code.is_empty() {
1309            p.code = Some(d.code.clone());
1310        }
1311        p.windows_virtual_key_code = Some(d.vk);
1312        p.native_virtual_key_code = Some(d.vk);
1313        if with_text {
1314            p.text = d.text.clone();
1315            p.unmodified_text = d.text.clone();
1316        }
1317        self.inner.execute(p).await.map_err(cdp)?;
1318        Ok(())
1319    }
1320
1321    async fn press_locked(&self, spec: &str) -> Result<()> {
1322        let (mods, mod_keys, def) = keys::parse_chord(spec)?;
1323        for (_, m) in &mod_keys {
1324            self.key_event(DispatchKeyEventType::RawKeyDown, m, mods, false)
1325                .await?;
1326        }
1327        // Shortcut chords (Ctrl/Meta/Alt) carry no text.
1328        let text = mods & (keys::CTRL | keys::META | keys::ALT) == 0;
1329        let kind = if text && def.text.is_some() {
1330            DispatchKeyEventType::KeyDown
1331        } else {
1332            DispatchKeyEventType::RawKeyDown
1333        };
1334        self.key_event(kind, &def, mods, text).await?;
1335        self.key_event(DispatchKeyEventType::KeyUp, &def, mods, false)
1336            .await?;
1337        for (_, m) in mod_keys.iter().rev() {
1338            self.key_event(DispatchKeyEventType::KeyUp, m, 0, false)
1339                .await?;
1340        }
1341        Ok(())
1342    }
1343
1344    /// Press a key or chord (`Enter`, `Tab`, `Control+a`) on the focused element.
1345    pub async fn press(&self, spec: &str) -> Result<()> {
1346        self.admit(ActionKind::Press, None, Some(spec.to_string()), None)
1347            .await?;
1348        let _l = self.lane.lock().await;
1349        self.press_locked(spec).await
1350    }
1351
1352    /// Type text one key event at a time into the focused element.
1353    pub async fn type_text(&self, text: &str) -> Result<()> {
1354        self.admit(
1355            ActionKind::TypeText,
1356            None,
1357            None,
1358            Some(format!("chars={}", text.chars().count())),
1359        )
1360        .await?;
1361        let _l = self.lane.lock().await;
1362        self.type_locked(text).await
1363    }
1364
1365    async fn type_locked(&self, text: &str) -> Result<()> {
1366        for c in text.chars() {
1367            let d = keys::char_key(c);
1368            self.key_event(DispatchKeyEventType::KeyDown, &d, 0, true)
1369                .await?;
1370            self.key_event(DispatchKeyEventType::KeyUp, &d, 0, false)
1371                .await?;
1372        }
1373        Ok(())
1374    }
1375
1376    /// Click the target to focus it, then type.
1377    pub async fn fill(&self, target: &Target, text: &str, clear: bool) -> Result<()> {
1378        self.admit(
1379            ActionKind::Fill,
1380            None,
1381            Some(describe(target)),
1382            Some(format!("chars={} clear={clear}", text.chars().count())),
1383        )
1384        .await?;
1385        let _l = self.lane.lock().await;
1386        self.click_n(target, 1).await?;
1387        if clear {
1388            let sel_all = if cfg!(target_os = "macos") {
1389                "Meta+a"
1390            } else {
1391                "Control+a"
1392            };
1393            self.press_locked(sel_all).await?;
1394            self.press_locked("Backspace").await?;
1395        }
1396        self.type_locked(text).await
1397    }
1398
1399    // ---- other actions -----------------------------------------------------
1400
1401    /// Choose a `<select>` option by value/label. Native popups cannot be driven
1402    /// over CDP, so this sets the value and fires `input`/`change` (documented gap).
1403    pub async fn select_option(&self, target: &Target, value: &str) -> Result<()> {
1404        self.admit(
1405            ActionKind::Select,
1406            None,
1407            Some(describe(target)),
1408            Some(format!("value={value}")),
1409        )
1410        .await?;
1411        let _l = self.lane.lock().await;
1412        let sel = self
1413            .resolve(target)
1414            .await?
1415            .ok_or_else(|| BrowserError::Invalid("select needs an element".into()))?;
1416        let r = self
1417            .eval(&format!(
1418                "(()=>{{const e=document.querySelector({s});const w={v};\
1419                 const o=[...e.options].find(o=>o.value===w||o.label===w||o.text.trim()===w);if(!o)return 'nooption';\
1420                 e.value=o.value;e.dispatchEvent(new Event('input',{{bubbles:true}}));e.dispatchEvent(new Event('change',{{bubbles:true}}));return 'ok'}})()",
1421                s = js(&sel),
1422                v = js(value)
1423            ))
1424            .await?;
1425        if r.as_str() == Some("ok") {
1426            Ok(())
1427        } else {
1428            Err(BrowserError::Invalid(format!(
1429                "'{sel}' has no option '{value}'"
1430            )))
1431        }
1432    }
1433
1434    pub async fn upload(&self, target: &Target, file: &Path) -> Result<()> {
1435        self.admit(
1436            ActionKind::Upload,
1437            None,
1438            Some(describe(target)),
1439            Some(file.display().to_string()),
1440        )
1441        .await?;
1442        let _l = self.lane.lock().await;
1443        let file = file.canonicalize()?;
1444        if !file.is_file() {
1445            return Err(BrowserError::Invalid(
1446                "upload must be a regular file".into(),
1447            ));
1448        }
1449        if let Some(root) = &self.upload_root {
1450            if !file.starts_with(root.canonicalize()?) {
1451                return Err(BrowserError::Invalid(
1452                    "upload outside the configured upload root".into(),
1453                ));
1454            }
1455        }
1456        if std::fs::metadata(&file)?.len() > MAX_UPLOAD_BYTES {
1457            return Err(BrowserError::Invalid("upload exceeds 64 MiB".into()));
1458        }
1459        let sel = self
1460            .resolve(target)
1461            .await?
1462            .ok_or_else(|| BrowserError::Invalid("upload needs an element".into()))?;
1463        let el = self
1464            .inner
1465            .find_element(sel.as_str())
1466            .await
1467            .map_err(|_| BrowserError::NoElement(sel.clone()))?;
1468        let node = el.description().await.map_err(cdp)?;
1469        self.inner
1470            .execute(
1471                SetFileInputFilesParams::builder()
1472                    .file(file.to_string_lossy().to_string())
1473                    .backend_node_id(node.backend_node_id)
1474                    .build()
1475                    .map_err(BrowserError::Invalid)?,
1476            )
1477            .await
1478            .map_err(cdp)?;
1479        Ok(())
1480    }
1481
1482    pub async fn wait_for(&self, selector: &str, timeout: Duration) -> Result<()> {
1483        self.wait_eval(
1484            &format!("!!document.querySelector({})", js(selector)),
1485            timeout,
1486        )
1487        .await
1488    }
1489
1490    /// Poll a JS expression until truthy.
1491    pub async fn wait_eval(&self, expr: &str, timeout: Duration) -> Result<()> {
1492        self.admit(
1493            ActionKind::Eval,
1494            None,
1495            None,
1496            Some(expr.chars().take(2000).collect()),
1497        )
1498        .await?;
1499        let deadline = Instant::now() + timeout;
1500        loop {
1501            let v = self.eval_internal(expr).await?;
1502            if v.as_bool()
1503                .unwrap_or(!v.is_null() && v != Value::Bool(false))
1504            {
1505                return Ok(());
1506            }
1507            if Instant::now() >= deadline {
1508                return Err(BrowserError::Timeout(expr.to_string()));
1509            }
1510            tokio::time::sleep(Duration::from_millis(50)).await;
1511        }
1512    }
1513
1514    pub async fn screenshot(&self) -> Result<Vec<u8>> {
1515        self.screenshot_with(ScreenshotOptions::default()).await
1516    }
1517
1518    /// PNG screenshot of the viewport with options; `ScreenshotOptions::default()` matches
1519    /// [`BrowserPage::screenshot`].
1520    pub async fn screenshot_with(&self, options: ScreenshotOptions) -> Result<Vec<u8>> {
1521        self.inner
1522            .screenshot(
1523                ScreenshotParams::builder()
1524                    .format(CaptureScreenshotFormat::Png)
1525                    .omit_background(options.omit_background)
1526                    .build(),
1527            )
1528            .await
1529            .map_err(cdp)
1530    }
1531
1532    pub async fn screenshot_to(&self, path: &Path) -> Result<()> {
1533        std::fs::write(path, self.screenshot().await?)?;
1534        Ok(())
1535    }
1536
1537    pub async fn console(&self) -> Vec<ConsoleLine> {
1538        self.console.lock().await.clone()
1539    }
1540
1541    pub async fn clear_console(&self) {
1542        self.console.lock().await.clear();
1543    }
1544}
1545
1546/// Register the `Fetch.requestPaused` listener, then enable `Fetch` for every URL, in that
1547/// order so no request is paused without a listener. One short task per request: the network
1548/// policy first (its refusal is final), then the caller's hook when one is installed.
1549async fn start_intercept_pump(
1550    inner: &Page,
1551    page_id: &str,
1552    guard: &Arc<Guard>,
1553    sink: Arc<StdMutex<Vec<BlockedRequest>>>,
1554    stats: Arc<InterceptStats>,
1555    hook_slot: Arc<StdMutex<Option<RequestInterceptor>>>,
1556) -> Result<JoinHandle<()>> {
1557    let mut paused = inner
1558        .event_listener::<EventRequestPaused>()
1559        .await
1560        .map_err(cdp)?;
1561    let page = inner.clone();
1562    let g = guard.clone();
1563    let page_id = page_id.to_string();
1564    let pump = tokio::spawn(async move {
1565        use std::sync::atomic::Ordering::Relaxed;
1566        while let Some(e) = paused.next().await {
1567            let stats = stats.clone();
1568            stats.paused.fetch_add(1, Relaxed);
1569            let page = page.clone();
1570            let g = g.clone();
1571            let sink = sink.clone();
1572            let pid = page_id.clone();
1573            let hook_slot = hook_slot.clone();
1574            tokio::spawn(async move {
1575                let kind = format!("{:?}", e.resource_type);
1576                match g.check_request(&e.request.url, &kind).await {
1577                    Ok(()) => {
1578                        let hook = hook_slot.lock().unwrap().clone();
1579                        let decision = match hook {
1580                            None => InterceptDecision::Continue,
1581                            Some(hook) => {
1582                                match serde_json::to_value(&*e)
1583                                    .ok()
1584                                    .and_then(|v| InterceptedRequest::from_cdp_value(&v))
1585                                {
1586                                    Some(request) => {
1587                                        run_interceptor(&hook, request, INTERCEPTOR_TIMEOUT).await
1588                                    }
1589                                    None => InterceptDecision::Fail(InterceptFailure::Failed),
1590                                }
1591                            }
1592                        };
1593                        let hook_failed = matches!(decision, InterceptDecision::Fail(_));
1594                        let (counter, result) = match command_for(e.request_id.clone(), decision) {
1595                            PausedCommand::Continue(p) => {
1596                                (&stats.continued, page.execute(p).await.map(|_| ()))
1597                            }
1598                            PausedCommand::Fulfill(p) => {
1599                                (&stats.fulfilled, page.execute(p).await.map(|_| ()))
1600                            }
1601                            PausedCommand::Fail(p) => {
1602                                (&stats.refused, page.execute(p).await.map(|_| ()))
1603                            }
1604                        };
1605                        match result {
1606                            Ok(()) => {
1607                                counter.fetch_add(1, Relaxed);
1608                                if hook_failed {
1609                                    let mut b = sink.lock().unwrap();
1610                                    if b.len() < 500 {
1611                                        b.push(BlockedRequest {
1612                                            url: e.request.url.clone(),
1613                                            reason: "failed by the request interceptor".into(),
1614                                        });
1615                                    }
1616                                }
1617                            }
1618                            Err(error) => {
1619                                stats.errors.fetch_add(1, Relaxed);
1620                                *stats.last_error.lock().unwrap() = Some(error.to_string());
1621                            }
1622                        }
1623                    }
1624                    Err(reason) => {
1625                        let _ = page
1626                            .execute(FailRequestParams::new(
1627                                e.request_id.clone(),
1628                                ErrorReason::BlockedByClient,
1629                            ))
1630                            .await;
1631                        stats.refused.fetch_add(1, Relaxed);
1632                        g.denied_network(Some(&pid), &kind, &reason);
1633                        let mut b = sink.lock().unwrap();
1634                        if b.len() < 500 {
1635                            b.push(BlockedRequest {
1636                                url: e.request.url.clone(),
1637                                reason: reason.to_string(),
1638                            });
1639                        }
1640                    }
1641                }
1642            });
1643        }
1644    });
1645    let en = FetchEnableParams {
1646        patterns: Some(vec![RequestPattern {
1647            url_pattern: Some("*".into()),
1648            resource_type: None,
1649            request_stage: None,
1650        }]),
1651        ..Default::default()
1652    };
1653    if let Err(e) = inner.execute(en).await {
1654        pump.abort();
1655        return Err(cdp(e));
1656    }
1657    Ok(pump)
1658}
1659
1660async fn push_capped(sink: &Arc<Mutex<Vec<ConsoleLine>>>, line: ConsoleLine) {
1661    let mut g = sink.lock().await;
1662    if g.len() >= MAX_CONSOLE_LINES {
1663        g.remove(0);
1664    }
1665    g.push(line);
1666}
1667
1668fn describe(t: &Target) -> String {
1669    match t {
1670        Target::Ref(r) => format!("ref:{r}"),
1671        Target::Selector(s) => format!("css:{s}"),
1672        Target::Point(x, y) => format!("point:{x},{y}"),
1673    }
1674}
1675
1676fn js(s: &str) -> String {
1677    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into())
1678}
1679
1680const OBSERVE_JS: &str = r#"(() => {
1681  const esc = globalThis.CSS?.escape || (v => String(v).replace(/[^a-zA-Z0-9_-]/g, '\\$&'));
1682  const unique = c => { if (!c) return null; try { return document.querySelectorAll(c).length === 1 ? c : null; } catch (_) { return null; } };
1683  const selectorFor = el => {
1684    if (el.id) { const s = unique('#' + esc(el.id)); if (s) return s; }
1685    for (const a of ['data-testid', 'name', 'aria-label']) {
1686      const v = el.getAttribute(a);
1687      if (v) { const s = unique(el.tagName.toLowerCase() + '[' + a + '="' + esc(v) + '"]'); if (s) return s; }
1688    }
1689    const parts = [];
1690    for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
1691      let p = n.tagName.toLowerCase();
1692      const sib = n.parentElement ? [...n.parentElement.children].filter(x => x.tagName === n.tagName) : [];
1693      if (sib.length > 1) p += ':nth-of-type(' + (sib.indexOf(n) + 1) + ')';
1694      parts.unshift(p);
1695      const c = parts.join(' > ');
1696      if (unique(c)) return c;
1697    }
1698    return '';
1699  };
1700  const sel = 'a[href],button,input,select,textarea,[role],[tabindex],[contenteditable="true"],[onclick]';
1701  return [...document.querySelectorAll(sel)].slice(0, 300).map(el => {
1702    const r = el.getBoundingClientRect();
1703    const ac = (el.getAttribute('autocomplete') || '').trim().toLowerCase();
1704    const sensitive = (el instanceof HTMLInputElement && el.type.toLowerCase() === 'password') || ac === 'current-password' || ac === 'new-password';
1705    const visible = (() => {
1706      for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
1707        const s = getComputedStyle(n);
1708        if (n.hidden || n.getAttribute('aria-hidden') === 'true' || s.visibility === 'hidden' || s.display === 'none' || s.opacity === '0') return false;
1709      }
1710      return r.width > 0 && r.height > 0;
1711    })();
1712    return {
1713      role: el.getAttribute('role') || ({A:'link',BUTTON:'button',INPUT:'textbox',SELECT:'combobox',TEXTAREA:'textbox'}[el.tagName] || el.tagName.toLowerCase()),
1714      name: (el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('placeholder') || '').trim().slice(0, 160),
1715      tag: el.tagName.toLowerCase(), selector: selectorFor(el), visible,
1716      disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true', sensitive,
1717      bounds: {x: r.x, y: r.y, width: r.width, height: r.height}
1718    };
1719  });
1720})()"#;