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