Skip to main content

rightkit_browser/
page.rs

1use crate::act::{ActResult, ActionWatch, NodeChange, NodeState, ObservationDiff, RefAction};
2use crate::cdp_ext::{
3    command_for, download_params, page_scale_params, parse_ax_tree, run_interceptor, summarize_ax,
4    AxNode, AxSummary, DownloadBehavior, InterceptDecision, InterceptFailure, InterceptedRequest,
5    PageException, PausedCommand, RequestInterceptor, INTERCEPTOR_TIMEOUT, MAX_EXCEPTIONS,
6};
7use crate::cookies::{self, NetscapeCookie};
8use crate::design_mode::{self, DesignModeBridge, DesignModeSession, NativeGestureLatch};
9use crate::error::{cdp, BrowserError, Result};
10use crate::keys::{self, KeyDef};
11use crate::policy::{ActionKind, AdmissionRequest, BlockedRequest, Guard, LifecycleKind};
12use chromiumoxide::cdp::browser_protocol::accessibility::GetFullAxTreeParams;
13use chromiumoxide::cdp::browser_protocol::dom::SetFileInputFilesParams;
14use chromiumoxide::cdp::browser_protocol::emulation::SetUserAgentOverrideParams;
15use chromiumoxide::cdp::browser_protocol::fetch::{
16    EnableParams as FetchEnableParams, EventRequestPaused, FailRequestParams, RequestPattern,
17};
18use chromiumoxide::cdp::browser_protocol::input::{
19    DispatchKeyEventParams, DispatchKeyEventType, DispatchMouseEventParams, DispatchMouseEventType,
20    MouseButton,
21};
22use chromiumoxide::cdp::browser_protocol::inspector::{
23    EnableParams as InspectorEnableParams, EventTargetCrashed,
24};
25use chromiumoxide::cdp::browser_protocol::network::{
26    ErrorReason, Headers, SetCookiesParams, SetExtraHttpHeadersParams,
27};
28use chromiumoxide::cdp::browser_protocol::page::CreateIsolatedWorldParams;
29use chromiumoxide::cdp::browser_protocol::page::{
30    CaptureScreenshotFormat, CaptureScreenshotParams, Viewport,
31};
32use chromiumoxide::cdp::js_protocol::runtime::{
33    AddBindingParams, EvaluateParams, EventBindingCalled, EventConsoleApiCalled,
34    EventExceptionThrown, ExecutionContextId,
35};
36use chromiumoxide::page::{Page, ScreenshotParams};
37use futures::StreamExt;
38use serde::{Deserialize, Serialize};
39use serde_json::Value;
40use std::collections::HashMap;
41use std::path::{Path, PathBuf};
42use std::sync::atomic::{AtomicBool, Ordering};
43use std::sync::{Arc, Mutex as StdMutex};
44use std::time::{Duration, Instant};
45use tokio::sync::{broadcast, Mutex};
46use tokio::task::JoinHandle;
47
48pub const MAX_CONSOLE_LINES: usize = 500;
49const MAX_UPLOAD_BYTES: u64 = 64 * 1024 * 1024;
50
51#[derive(Clone, Debug, Serialize)]
52pub struct ConsoleLine {
53    pub level: String,
54    pub text: String,
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
58pub struct Rect {
59    pub x: f64,
60    pub y: f64,
61    pub width: f64,
62    pub height: f64,
63}
64
65#[derive(Clone, Debug, Serialize)]
66pub struct ObservedNode {
67    /// `r<epoch>.<n>`; valid only while the page stays unchanged.
68    pub node_ref: String,
69    pub role: String,
70    /// Masked (`••••••••`) when `sensitive` is true.
71    pub name: String,
72    pub tag: String,
73    pub selector: String,
74    pub visible: bool,
75    pub disabled: bool,
76    /// True for password-like fields (`type=password`, `current-password`, `new-password`).
77    /// Their name is masked; callers should mask any value they show.
78    pub sensitive: bool,
79    /// CDP frame id of the document the node was read from. An observation reads the main
80    /// document only (iframe contents are not enumerated, see the changelog), so this is the
81    /// main frame's id for every node; it does not make iframe controls observable.
82    pub frame_id: String,
83    /// Stable across consecutive observations of the same document for the same selector.
84    /// `0` when the node has no selector (such nodes cannot be targeted by ref either).
85    pub stable_id: u64,
86    pub bounds: Rect,
87}
88
89#[derive(Clone, Debug, Serialize)]
90pub struct Observation {
91    pub page_id: String,
92    pub epoch: u64,
93    pub url: String,
94    pub title: String,
95    pub viewport: Rect,
96    pub nodes: Vec<ObservedNode>,
97    /// Accessibility summary of the main frame, bounded to depth [`OBSERVE_AX_DEPTH`].
98    pub ax: Vec<AxSummary>,
99    pub console_errors: usize,
100    /// Refs/roles/names added, removed, or changed since the previous observation.
101    pub added: Vec<String>,
102    pub removed: Vec<String>,
103}
104
105/// Depth bound for the accessibility summary in an [`Observation`].
106pub const OBSERVE_AX_DEPTH: u32 = 12;
107
108/// How long a history traversal waits for a navigation event before returning. A traversal
109/// that fires no navigation (bfcache restore, same-document entry) must not hang the caller.
110const HISTORY_NAVIGATION_WAIT: Duration = Duration::from_secs(10);
111
112/// Longest accepted user-agent string, in bytes.
113pub const MAX_USER_AGENT_BYTES: usize = 1024;
114/// Most extra HTTP headers one [`BrowserPage::set_extra_headers`] call accepts.
115pub const MAX_EXTRA_HEADERS: usize = 32;
116/// Longest accepted extra-header value, in bytes.
117pub const MAX_HEADER_VALUE_BYTES: usize = 8192;
118
119/// Screenshot options for [`BrowserPage::screenshot_with`]. The default is the viewport as PNG.
120#[derive(Clone, Copy, Debug, Default, PartialEq)]
121pub struct ScreenshotOptions {
122    /// Capture with a transparent background (PNG only). Pair with
123    /// [`BrowserPage::set_transparent_background`] for a fully transparent page.
124    pub omit_background: bool,
125    /// Image format; PNG by default.
126    pub format: ScreenshotFormat,
127    /// Capture only this region, in CSS pixels of the page. `None` captures the visible viewport
128    /// (or, with a `scale`, the whole visual viewport).
129    pub clip: Option<ScreenshotClip>,
130    /// Output scale of the capture, a positive finite factor (`1.0` when `None`). Use it with
131    /// `clip` or alone to produce a smaller image, for example a 1280 px wide frame of a wider
132    /// viewport.
133    pub scale: Option<f64>,
134}
135
136/// Image format of a screenshot.
137#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
138pub enum ScreenshotFormat {
139    /// Lossless PNG.
140    #[default]
141    Png,
142    /// JPEG at `quality`, 1 to 100.
143    Jpeg { quality: u8 },
144}
145
146/// A capture region in CSS pixels of the page. `x` and `y` are at least zero; `width` and
147/// `height` are positive.
148#[derive(Clone, Copy, Debug, PartialEq)]
149pub struct ScreenshotClip {
150    pub x: f64,
151    pub y: f64,
152    pub width: f64,
153    pub height: f64,
154}
155
156impl ScreenshotClip {
157    fn validate(&self) -> Result<()> {
158        let finite = [self.x, self.y, self.width, self.height]
159            .iter()
160            .all(|v| v.is_finite());
161        if !finite || self.x < 0.0 || self.y < 0.0 || self.width <= 0.0 || self.height <= 0.0 {
162            return Err(BrowserError::Invalid(
163                "screenshot clip needs finite x and y of at least 0 and a positive width and height"
164                    .into(),
165            ));
166        }
167        Ok(())
168    }
169}
170
171/// RFC 9110 token characters, the only bytes a header name may contain.
172fn is_header_token(name: &str) -> bool {
173    !name.is_empty()
174        && name
175            .bytes()
176            .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
177}
178
179fn has_control(value: &str) -> bool {
180    value.chars().any(|c| c.is_control())
181}
182
183/// What an action addresses.
184#[derive(Clone, Debug)]
185pub enum Target {
186    /// Ref from [`BrowserPage::observe`]; checked for staleness.
187    Ref(String),
188    /// A CSS selector that must match exactly one element.
189    Selector(String),
190    /// Viewport coordinates.
191    Point(f64, f64),
192}
193
194impl Target {
195    pub fn css(s: impl Into<String>) -> Self {
196        Target::Selector(s.into())
197    }
198    pub fn node_ref(s: impl Into<String>) -> Self {
199        Target::Ref(s.into())
200    }
201}
202
203#[derive(Clone, Debug, Deserialize)]
204struct RawNode {
205    role: String,
206    name: String,
207    tag: String,
208    selector: String,
209    visible: bool,
210    disabled: bool,
211    #[serde(default)]
212    sensitive: bool,
213    bounds: Rect,
214}
215
216#[derive(Clone, Debug)]
217struct RefEntry {
218    selector: String,
219    tag: String,
220    role: String,
221    name: String,
222}
223
224#[derive(Default)]
225struct ObsState {
226    epoch: u64,
227    fingerprint: String,
228    refs: HashMap<String, RefEntry>,
229    previous: HashMap<String, String>,
230    /// Stable ids of the previous observation's selectors (bounded by its node count).
231    stable: HashMap<String, u64>,
232    next_stable: u64,
233    /// Identity (frame id and loader id) of the main document the refs were read from. A navigation or
234    /// reload changes the loader, so a ref from before it is refused.
235    frame: Option<String>,
236    /// State of each selectable element in the latest observation, for the diff [`BrowserPage::act`] returns.
237    sigs: HashMap<String, NodeState>,
238}
239
240/// What the request-interception pump has done on one page. Reported when a navigation
241/// fails, so a timeout says how far the navigation got: no request paused (it never reached
242/// the network stage), paused but not answered (the policy check did not return), or
243/// continued (the request left the browser and the proxy or the server did not finish it).
244#[derive(Default)]
245struct InterceptStats {
246    paused: std::sync::atomic::AtomicUsize,
247    continued: std::sync::atomic::AtomicUsize,
248    fulfilled: std::sync::atomic::AtomicUsize,
249    refused: std::sync::atomic::AtomicUsize,
250    errors: std::sync::atomic::AtomicUsize,
251    last_error: StdMutex<Option<String>>,
252}
253
254impl InterceptStats {
255    fn summary(&self) -> String {
256        use std::sync::atomic::Ordering::Relaxed;
257        let mut text = format!(
258            "requests paused {}, continued {}, refused {}",
259            self.paused.load(Relaxed),
260            self.continued.load(Relaxed),
261            self.refused.load(Relaxed)
262        );
263        let fulfilled = self.fulfilled.load(Relaxed);
264        if fulfilled > 0 {
265            text.push_str(&format!(", fulfilled {fulfilled}"));
266        }
267        let errors = self.errors.load(Relaxed);
268        if errors > 0 {
269            let last = self.last_error.lock().unwrap().clone().unwrap_or_default();
270            text.push_str(&format!(", {errors} not answered: {last}"));
271        }
272        text
273    }
274}
275
276pub struct BrowserPage {
277    id: String,
278    /// CDP target id: the stable identity of the tab (`id` is the session's own sequence).
279    target_id: String,
280    inner: Page,
281    console: Arc<Mutex<Vec<ConsoleLine>>>,
282    obs: StdMutex<ObsState>,
283    mouse: StdMutex<(f64, f64)>,
284    buttons: StdMutex<i64>,
285    /// Serializes mutations so concurrent callers commit in order.
286    lane: Mutex<()>,
287    upload_root: Option<PathBuf>,
288    pumps: StdMutex<Vec<JoinHandle<()>>>,
289    guard: Arc<Guard>,
290    blocked: Arc<StdMutex<Vec<BlockedRequest>>>,
291    intercept: Arc<InterceptStats>,
292    /// Caller hook consulted after the network policy; see [`BrowserPage::set_request_interceptor`].
293    interceptor: Arc<StdMutex<Option<RequestInterceptor>>>,
294    /// True once this page's request-interception pump (and `Fetch.enable`) is running.
295    pump_running: AtomicBool,
296    /// The fixture session owns `Fetch` on this page; a caller hook cannot share it.
297    fixture_fetch_owner: bool,
298    exceptions: Arc<StdMutex<Vec<PageException>>>,
299    exception_tx: broadcast::Sender<PageException>,
300    /// Latest native input gesture (pointer press, key down) this page dispatched.
301    design_gesture: Arc<NativeGestureLatch>,
302    /// Isolated-world context of the design-mode picker, once enabled.
303    design_context: StdMutex<Option<ExecutionContextId>>,
304    /// Repeat counter behind the action-loop watchdog of [`BrowserPage::act`].
305    watch: StdMutex<ActionWatch>,
306}
307
308/// Buffered capacity of an exception subscription; a slower receiver sees `Lagged`.
309const EXCEPTION_CHANNEL: usize = 64;
310
311impl BrowserPage {
312    pub(crate) async fn attach(
313        id: String,
314        inner: Page,
315        upload_root: Option<PathBuf>,
316        guard: Arc<Guard>,
317        fixture_fetch_owner: bool,
318    ) -> Result<Self> {
319        let console = Arc::new(Mutex::new(Vec::new()));
320        let mut pumps = Vec::new();
321        let mut ev = inner
322            .event_listener::<EventConsoleApiCalled>()
323            .await
324            .map_err(cdp)?;
325        let sink = console.clone();
326        pumps.push(tokio::spawn(async move {
327            while let Some(e) = ev.next().await {
328                let text = e
329                    .args
330                    .iter()
331                    .map(|a| match (&a.value, &a.description) {
332                        (Some(Value::String(s)), _) => s.clone(),
333                        (Some(v), _) => v.to_string(),
334                        (None, Some(d)) => d.clone(),
335                        _ => String::new(),
336                    })
337                    .collect::<Vec<_>>()
338                    .join(" ");
339                push_capped(
340                    &sink,
341                    ConsoleLine {
342                        level: format!("{:?}", e.r#type).to_lowercase(),
343                        text,
344                    },
345                )
346                .await;
347            }
348        }));
349        let mut ex = inner
350            .event_listener::<EventExceptionThrown>()
351            .await
352            .map_err(cdp)?;
353        let sink = console.clone();
354        let exceptions = Arc::new(StdMutex::new(Vec::new()));
355        let (exception_tx, _) = broadcast::channel(EXCEPTION_CHANNEL);
356        let (ex_log, ex_tx) = (exceptions.clone(), exception_tx.clone());
357        pumps.push(tokio::spawn(async move {
358            while let Some(e) = ex.next().await {
359                if let Some(parsed) = serde_json::to_value(&*e)
360                    .ok()
361                    .and_then(|v| PageException::from_cdp_value(&v))
362                {
363                    {
364                        let mut log = ex_log.lock().unwrap();
365                        if log.len() >= MAX_EXCEPTIONS {
366                            log.remove(0);
367                        }
368                        log.push(parsed.clone());
369                    }
370                    // No receiver is the normal case; the buffered list still has it.
371                    let _ = ex_tx.send(parsed);
372                }
373                let d = &e.exception_details;
374                let text = d
375                    .exception
376                    .as_ref()
377                    .and_then(|x| x.description.clone())
378                    .unwrap_or_else(|| d.text.clone());
379                push_capped(
380                    &sink,
381                    ConsoleLine {
382                        level: "exception".into(),
383                        text,
384                    },
385                )
386                .await;
387            }
388        }));
389        // Renderer crash -> `Crash` lifecycle event for this page.
390        let mut crashed = inner
391            .event_listener::<EventTargetCrashed>()
392            .await
393            .map_err(cdp)?;
394        let (g, page_id) = (guard.clone(), id.clone());
395        pumps.push(tokio::spawn(async move {
396            while crashed.next().await.is_some() {
397                g.emit_kind(LifecycleKind::Crash, "renderer crashed", |e| {
398                    e.page_id = Some(page_id.clone());
399                });
400            }
401        }));
402        inner
403            .execute(InspectorEnableParams::default())
404            .await
405            .map_err(cdp)?;
406        let blocked = Arc::new(StdMutex::new(Vec::new()));
407        let intercept = Arc::new(InterceptStats::default());
408        let interceptor = Arc::new(StdMutex::new(None));
409        let mut pump_running = false;
410        if !guard.network.unrestricted && !fixture_fetch_owner {
411            // Pause every request (document, redirect hops, subresources) and
412            // decide before it leaves the browser. Enabled before any navigation.
413            pumps.push(
414                start_intercept_pump(
415                    &inner,
416                    &id,
417                    &guard,
418                    blocked.clone(),
419                    intercept.clone(),
420                    interceptor.clone(),
421                )
422                .await?,
423            );
424            pump_running = true;
425        }
426        let target_id = inner.target_id().as_ref().to_string();
427        Ok(Self {
428            id,
429            target_id,
430            inner,
431            console,
432            obs: StdMutex::new(ObsState::default()),
433            mouse: StdMutex::new((0.0, 0.0)),
434            buttons: StdMutex::new(0),
435            lane: Mutex::new(()),
436            upload_root,
437            pumps: StdMutex::new(pumps),
438            guard,
439            blocked,
440            intercept,
441            interceptor,
442            pump_running: AtomicBool::new(pump_running),
443            fixture_fetch_owner,
444            exceptions,
445            exception_tx,
446            design_gesture: Arc::new(NativeGestureLatch::new()),
447            design_context: StdMutex::new(None),
448            watch: StdMutex::new(ActionWatch::default()),
449        })
450    }
451
452    pub fn id(&self) -> &str {
453        &self.id
454    }
455
456    /// The CDP target id of this tab. Unlike [`BrowserPage::id`], it is Chrome's own identity
457    /// for the tab and does not change when the session renumbers pages.
458    pub fn target_id(&self) -> &str {
459        &self.target_id
460    }
461
462    /// Frame ids of every frame in the page (CDP `Page.getFrameTree`), read-only.
463    pub async fn frames(&self) -> Result<Vec<String>> {
464        let frames = self.inner.frames().await.map_err(cdp)?;
465        Ok(frames.iter().map(|f| f.as_ref().to_string()).collect())
466    }
467
468    /// Install (or with `None`, remove) a caller hook that answers every request this page
469    /// makes: continue, continue with changes, fulfil from memory, or fail. Redirect hops arrive
470    /// as separate requests with [`InterceptedRequest::redirected_from`] set, so a hook that pins
471    /// an origin revalidates each hop.
472    ///
473    /// The session's network policy runs first and its refusals are final; the hook only
474    /// narrows what the policy allows. A hook that takes longer than 30 s fails the request.
475    /// Turns on `Fetch` interception for this page when the policy had not (an unrestricted
476    /// session); requests already in flight are not affected. Removing the hook lets requests
477    /// through unchanged but leaves interception running. Not available on a fixture page, whose
478    /// session owns `Fetch`: returns [`BrowserError::Invalid`].
479    pub async fn set_request_interceptor(&self, hook: Option<RequestInterceptor>) -> Result<()> {
480        if self.fixture_fetch_owner {
481            return Err(BrowserError::Invalid(
482                "a fixture page's session owns request interception".into(),
483            ));
484        }
485        let install = hook.is_some();
486        *self.interceptor.lock().unwrap() = hook;
487        if install && !self.pump_running.swap(true, Ordering::SeqCst) {
488            match start_intercept_pump(
489                &self.inner,
490                &self.id,
491                &self.guard,
492                self.blocked.clone(),
493                self.intercept.clone(),
494                self.interceptor.clone(),
495            )
496            .await
497            {
498                Ok(pump) => self.pumps.lock().unwrap().push(pump),
499                Err(e) => {
500                    self.pump_running.store(false, Ordering::SeqCst);
501                    *self.interceptor.lock().unwrap() = None;
502                    return Err(e);
503                }
504            }
505        }
506        Ok(())
507    }
508
509    /// The page's full accessibility tree (`Accessibility.getFullAXTree`), root frame, in CDP
510    /// order. Ignored nodes are included and flagged. Read-only.
511    pub async fn accessibility_tree(&self) -> Result<Vec<AxNode>> {
512        self.ax_tree(None).await
513    }
514
515    /// The accessibility tree cut off below `depth` (root is depth 0). Use it on heavy pages,
516    /// where the full tree costs too much. Read-only, like [`BrowserPage::accessibility_tree`].
517    pub async fn accessibility_tree_with(&self, depth: u32) -> Result<Vec<AxNode>> {
518        self.ax_tree(Some(depth)).await
519    }
520
521    async fn ax_tree(&self, depth: Option<u32>) -> Result<Vec<AxNode>> {
522        let params = GetFullAxTreeParams {
523            depth: depth.map(i64::from),
524            ..Default::default()
525        };
526        let r = self.inner.execute(params).await.map_err(cdp)?;
527        let wire = serde_json::to_value(&r.result).map_err(cdp)?;
528        Ok(parse_ax_tree(&wire))
529    }
530
531    /// Make the page background transparent (`Emulation.setDefaultBackgroundColorOverride`
532    /// with alpha 0), or restore Chrome's default with `false`. Pair with
533    /// [`BrowserPage::screenshot_with`] and `omit_background` to capture alpha. Like
534    /// [`BrowserPage::set_page_scale`], this changes rendering only and is not admitted.
535    pub async fn set_transparent_background(&self, transparent: bool) -> Result<()> {
536        use chromiumoxide::cdp::browser_protocol::dom::Rgba;
537        use chromiumoxide::cdp::browser_protocol::emulation::SetDefaultBackgroundColorOverrideParams;
538        let params = if transparent {
539            SetDefaultBackgroundColorOverrideParams::builder()
540                .color(Rgba {
541                    r: 0,
542                    g: 0,
543                    b: 0,
544                    a: Some(0.0),
545                })
546                .build()
547        } else {
548            SetDefaultBackgroundColorOverrideParams::builder().build()
549        };
550        self.inner.execute(params).await.map_err(cdp)?;
551        Ok(())
552    }
553
554    /// Uncaught exceptions and unhandled rejections seen so far (`Runtime.exceptionThrown`),
555    /// oldest first, at most [`MAX_EXCEPTIONS`](crate::MAX_EXCEPTIONS). Collected from the moment
556    /// the page exists, so nothing from its first navigation is missed.
557    pub fn exceptions(&self) -> Vec<PageException> {
558        self.exceptions.lock().unwrap().clone()
559    }
560
561    pub fn clear_exceptions(&self) {
562        self.exceptions.lock().unwrap().clear();
563    }
564
565    /// Live stream of exceptions from now on. The page exists before its first navigation, so a
566    /// subscriber taken before `goto` sees every exception it raises. A receiver that falls more
567    /// than 64 behind gets `RecvError::Lagged`; [`BrowserPage::exceptions`] still has them.
568    pub fn subscribe_exceptions(&self) -> broadcast::Receiver<PageException> {
569        self.exception_tx.subscribe()
570    }
571
572    /// Set the page scale factor (pinch zoom, `Emulation.setPageScaleFactor`). Must be positive
573    /// and finite. Distinct from the device scale factor of [`BrowserPage::set_viewport`].
574    pub async fn set_page_scale(&self, scale: f64) -> Result<()> {
575        self.inner
576            .execute(page_scale_params(scale)?)
577            .await
578            .map_err(cdp)?;
579        Ok(())
580    }
581
582    /// Choose what happens to downloads (`Browser.setDownloadBehavior`). `Allow` and
583    /// `AllowAndName` need an absolute, existing directory; downloads go nowhere else.
584    /// Admitted as an `Eval`-kind effect (detail `download_behavior ...`) because it lets pages
585    /// write files. Applies to the browser's default context, so it covers every page of a
586    /// session; a later call replaces an earlier one.
587    pub async fn set_download_behavior(&self, behavior: &DownloadBehavior) -> Result<()> {
588        let params = download_params(behavior)?;
589        self.admit(
590            ActionKind::Eval,
591            None,
592            None,
593            Some(format!("download_behavior {behavior:?}")),
594        )
595        .await?;
596        self.inner.execute(params).await.map_err(cdp)?;
597        Ok(())
598    }
599
600    /// Override the user agent of this page (`Emulation.setUserAgentOverride`), and optionally
601    /// its `Accept-Language`. Applies to this page's later requests and scripts. Admitted as an
602    /// `Eval`-kind effect (detail `user_agent`).
603    pub async fn set_user_agent(
604        &self,
605        user_agent: &str,
606        accept_language: Option<&str>,
607    ) -> Result<()> {
608        let ua = user_agent.trim();
609        if ua.is_empty() || ua.len() > MAX_USER_AGENT_BYTES || has_control(ua) {
610            return Err(BrowserError::Invalid(format!(
611                "user agent must be 1 to {MAX_USER_AGENT_BYTES} bytes without control characters"
612            )));
613        }
614        let mut builder = SetUserAgentOverrideParams::builder().user_agent(ua);
615        if let Some(lang) = accept_language {
616            let lang = lang.trim();
617            if lang.is_empty() || lang.len() > MAX_HEADER_VALUE_BYTES || has_control(lang) {
618                return Err(BrowserError::Invalid(
619                    "accept-language must be non-empty and free of control characters".into(),
620                ));
621            }
622            builder = builder.accept_language(lang);
623        }
624        let params = builder
625            .build()
626            .map_err(|e| BrowserError::Invalid(format!("user agent override: {e}")))?;
627        self.admit(ActionKind::Eval, None, None, Some("user_agent".into()))
628            .await?;
629        self.inner.execute(params).await.map_err(cdp)?;
630        Ok(())
631    }
632
633    /// Send `headers` with every later request of this page (`Network.setExtraHTTPHeaders`).
634    /// Each call replaces the previous set; an empty slice clears it. Names are case-insensitive
635    /// and must be unique; values may not contain control characters. Admitted as an `Eval`-kind
636    /// effect whose detail carries the count only: header values are never logged.
637    pub async fn set_extra_headers(&self, headers: &[(String, String)]) -> Result<()> {
638        if headers.len() > MAX_EXTRA_HEADERS {
639            return Err(BrowserError::Invalid(format!(
640                "set_extra_headers takes at most {MAX_EXTRA_HEADERS} headers"
641            )));
642        }
643        let mut map = serde_json::Map::new();
644        for (name, value) in headers {
645            if !is_header_token(name) {
646                return Err(BrowserError::Invalid(
647                    "extra header names must be non-empty HTTP tokens".into(),
648                ));
649            }
650            if value.len() > MAX_HEADER_VALUE_BYTES || value.contains(['\r', '\n', '\0']) {
651                return Err(BrowserError::Invalid(format!(
652                    "extra header value must be at most {MAX_HEADER_VALUE_BYTES} bytes without CR, LF or NUL"
653                )));
654            }
655            let key = name.to_ascii_lowercase();
656            if map.contains_key(&key) {
657                return Err(BrowserError::Invalid("duplicate extra header name".into()));
658            }
659            map.insert(key, Value::String(value.clone()));
660        }
661        self.admit(
662            ActionKind::Eval,
663            None,
664            None,
665            Some(format!("extra_headers {} names", headers.len())),
666        )
667        .await?;
668        self.inner
669            .execute(SetExtraHttpHeadersParams::new(Headers::new(Value::Object(
670                map,
671            ))))
672            .await
673            .map_err(cdp)?;
674        Ok(())
675    }
676
677    /// Set `cookies` in the browser profile this page belongs to (`Network.setCookies`) and
678    /// return how many were set. The cookies apply to the whole profile, not to this page, and
679    /// persist with a named or directory profile. A subdomain-matching cookie gets a leading dot
680    /// on its domain; a host-only cookie does not. Chrome rejects the whole batch if one cookie
681    /// is invalid (for example a `__Secure-` name without `secure`); the error then sets none
682    /// and its text never contains a cookie value.
683    ///
684    /// Domain filtering, user consent and file selection belong to the caller: this sets exactly
685    /// what it is given. Admitted as an `Eval`-kind effect (detail `import_cookies`, the count
686    /// and the distinct domains; never names or values). An empty slice returns `Ok(0)` without
687    /// contacting the browser; more than [`MAX_COOKIES`](crate::cookies::MAX_COOKIES) is refused.
688    pub async fn import_cookies(&self, cookies: &[NetscapeCookie]) -> Result<usize> {
689        if cookies.is_empty() {
690            return Ok(0);
691        }
692        if cookies.len() > cookies::MAX_COOKIES {
693            return Err(BrowserError::Invalid(format!(
694                "import_cookies takes at most {} cookies",
695                cookies::MAX_COOKIES
696            )));
697        }
698        self.admit(
699            ActionKind::Eval,
700            None,
701            None,
702            Some(cookies::admission_detail(cookies)),
703        )
704        .await?;
705        let _l = self.lane.lock().await;
706        let params = SetCookiesParams::new(cookies::to_cdp_params(cookies));
707        self.inner.execute(params).await.map_err(|e| {
708            BrowserError::Cdp(format!(
709                "Network.setCookies: {}",
710                cookies::scrub(&e.to_string(), cookies)
711            ))
712        })?;
713        Ok(cookies.len())
714    }
715
716    /// Requests the network policy refused on this page (redirect hops and subresources included).
717    pub fn blocked_requests(&self) -> Vec<BlockedRequest> {
718        self.blocked.lock().unwrap().clone()
719    }
720
721    /// Typed pre-effect admission. Reads no page state beyond the current URL.
722    async fn admit(
723        &self,
724        action: ActionKind,
725        url: Option<String>,
726        target: Option<String>,
727        detail: Option<String>,
728    ) -> Result<()> {
729        let url = match url {
730            Some(u) => Some(u),
731            None if self.guard.admission.is_some() => Some(self.url().await),
732            None => None,
733        };
734        self.guard
735            .admit(AdmissionRequest {
736                session_id: self.guard.session_id.clone(),
737                page_id: self.id.clone(),
738                action,
739                url,
740                target,
741                detail,
742            })
743            .await
744    }
745
746    /// Escape hatch to the underlying chromiumoxide page.
747    pub fn raw(&self) -> &Page {
748        &self.inner
749    }
750
751    pub(crate) fn abort_pumps(&self) {
752        if let Ok(mut p) = self.pumps.lock() {
753            for h in p.drain(..) {
754                h.abort();
755            }
756        }
757    }
758
759    pub(crate) async fn close_inner(&self) -> Result<()> {
760        self.abort_pumps();
761        self.inner.clone().close().await.map_err(cdp)
762    }
763
764    pub async fn bring_to_front(&self) -> Result<()> {
765        self.inner.bring_to_front().await.map_err(cdp)?;
766        Ok(())
767    }
768
769    // ---- navigation ------------------------------------------------------
770
771    fn invalidate(&self) {
772        let mut o = self.obs.lock().unwrap();
773        o.epoch += 1;
774        o.refs.clear();
775        o.fingerprint.clear();
776        o.frame = None;
777        o.sigs.clear();
778        // A navigation starts a new document: its selectors do not carry stable ids over.
779        o.stable.clear();
780    }
781
782    /// Waits until this new tab's own first navigation (to about:blank) has committed.
783    ///
784    /// A tab is created at about:blank and that navigation commits a little later. A
785    /// navigation sent before then is discarded by that commit: Chrome answers it with
786    /// `net::ERR_ABORTED` and no load ever follows, so the caller waits out its whole request
787    /// timeout. Seen on Windows, where a new tab's renderer starts more slowly.
788    ///
789    /// Before the commit the tab's committed history entry has an empty URL. The tab counts
790    /// as settled when that entry has a URL and the main frame's loader is the same on two
791    /// consecutive polls. Bounded at two seconds, and it stops at once if Chrome does not
792    /// answer, so a browser that behaves differently is not waited on.
793    pub(crate) async fn settle_initial_document(&self) {
794        use chromiumoxide::cdp::browser_protocol::page::{
795            GetFrameTreeParams, GetNavigationHistoryParams,
796        };
797        use std::time::{Duration, Instant};
798        let deadline = Instant::now() + Duration::from_secs(2);
799        let mut seen: Option<String> = None;
800        while Instant::now() < deadline {
801            let Ok(history) = self
802                .inner
803                .execute(GetNavigationHistoryParams::default())
804                .await
805            else {
806                return;
807            };
808            let Ok(tree) = self.inner.execute(GetFrameTreeParams::default()).await else {
809                return;
810            };
811            let committed = usize::try_from(history.result.current_index)
812                .ok()
813                .and_then(|index| history.result.entries.get(index))
814                .is_some_and(|entry| !entry.url.is_empty());
815            let loader = format!("{:?}", tree.result.frame_tree.frame.loader_id);
816            if !committed {
817                seen = None;
818            } else if seen.as_deref() == Some(loader.as_str()) {
819                return;
820            } else {
821                seen = Some(loader);
822            }
823            tokio::time::sleep(Duration::from_millis(10)).await;
824        }
825    }
826
827    pub async fn goto(&self, url: &str) -> Result<()> {
828        // EFF-001 order: policy, then approval; both before any side effect.
829        self.guard
830            .check_url(Some(&self.id), url, "Navigation")
831            .await?;
832        self.admit(ActionKind::Navigate, Some(url.to_string()), None, None)
833            .await?;
834        let _l = self.lane.lock().await;
835        self.inner.goto(url).await.map_err(|e| {
836            BrowserError::Cdp(format!(
837                "navigate '{url}': {e} ({})",
838                self.intercept.summary()
839            ))
840        })?;
841        self.inner.wait_for_navigation().await.map_err(cdp)?;
842        self.invalidate();
843        Ok(())
844    }
845
846    pub async fn reload(&self) -> Result<()> {
847        self.admit(ActionKind::Reload, None, None, None).await?;
848        let _l = self.lane.lock().await;
849        self.inner.reload().await.map_err(cdp)?;
850        self.inner.wait_for_navigation().await.map_err(cdp)?;
851        self.invalidate();
852        Ok(())
853    }
854
855    pub async fn history(&self, delta: i32) -> Result<()> {
856        self.admit(
857            ActionKind::History,
858            None,
859            None,
860            Some(format!("delta={delta}")),
861        )
862        .await?;
863        let _l = self.lane.lock().await;
864        self.inner
865            .evaluate(format!("history.go({delta})"))
866            .await
867            .map_err(cdp)?;
868        tokio::time::sleep(Duration::from_millis(150)).await;
869        // Bounded: a traversal that fires no navigation event (bfcache, same-document entry)
870        // returns once the wait elapses; the page is then read as it is.
871        if let Ok(waited) =
872            tokio::time::timeout(HISTORY_NAVIGATION_WAIT, self.inner.wait_for_navigation()).await
873        {
874            waited.map_err(cdp)?;
875        }
876        self.invalidate();
877        Ok(())
878    }
879
880    pub async fn url(&self) -> String {
881        self.inner.url().await.ok().flatten().unwrap_or_default()
882    }
883
884    pub async fn title(&self) -> String {
885        self.inner
886            .get_title()
887            .await
888            .ok()
889            .flatten()
890            .unwrap_or_default()
891    }
892
893    /// Rendered text (`document.body.innerText`).
894    pub async fn text(&self) -> Result<String> {
895        self.eval_internal("document.body ? document.body.innerText : ''")
896            .await
897            .map(|v| v.as_str().unwrap_or_default().to_string())
898    }
899
900    /// Evaluate a JS expression and return its JSON value. Script can navigate and
901    /// act, so it is admitted like any other effect.
902    pub async fn eval(&self, expr: &str) -> Result<Value> {
903        self.admit(
904            ActionKind::Eval,
905            None,
906            None,
907            Some(expr.chars().take(2000).collect()),
908        )
909        .await?;
910        self.eval_internal(expr).await
911    }
912
913    /// Runtime-owned evaluation (observation, geometry); never user script.
914    async fn eval_internal(&self, expr: &str) -> Result<Value> {
915        let r = self.inner.evaluate(expr).await.map_err(cdp)?;
916        Ok(r.value().cloned().unwrap_or(Value::Null))
917    }
918
919    pub async fn set_viewport(&self, width: u32, height: u32, scale: f64) -> Result<()> {
920        use chromiumoxide::cdp::browser_protocol::emulation::SetDeviceMetricsOverrideParams;
921        self.inner
922            .execute(SetDeviceMetricsOverrideParams::new(
923                i64::from(width),
924                i64::from(height),
925                scale,
926                false,
927            ))
928            .await
929            .map_err(cdp)?;
930        Ok(())
931    }
932
933    // ---- design mode -----------------------------------------------------
934
935    /// Enable the element picker for the current document. It runs in a fresh isolated world
936    /// and reports through a `Runtime.addBinding` function bound only to that world, so page
937    /// script can neither see nor forge picker messages. Prompt submissions are delivered only
938    /// when one native input gesture (a pointer press or key down this page dispatched)
939    /// authorizes them; see [`DesignModeBridge`]. Call once per document; navigation ends the
940    /// picker and requires a new call with a new nonce.
941    pub async fn enable_design_mode(&self, nonce: &str) -> Result<DesignModeSession> {
942        let script = design_mode::build_design_mode_script(nonce)?;
943        let mut bridge = DesignModeBridge::new(nonce)?;
944        let frame_id = self
945            .inner
946            .mainframe()
947            .await
948            .map_err(cdp)?
949            .ok_or_else(|| BrowserError::Invalid("no main frame".into()))?;
950        let mut events = self
951            .inner
952            .event_listener::<EventBindingCalled>()
953            .await
954            .map_err(cdp)?;
955        let mut add = AddBindingParams::new(bridge.binding_name());
956        add.execution_context_name = Some(bridge.world_name());
957        self.inner.execute(add).await.map_err(cdp)?;
958        let mut world = CreateIsolatedWorldParams::new(frame_id);
959        world.world_name = Some(bridge.world_name());
960        world.grant_univeral_access = Some(false);
961        let context = self
962            .inner
963            .execute(world)
964            .await
965            .map_err(cdp)?
966            .result
967            .execution_context_id;
968        *self.design_context.lock().unwrap() = Some(context);
969        let eval = EvaluateParams::builder()
970            .expression(script)
971            .context_id(context)
972            .build()
973            .map_err(BrowserError::Invalid)?;
974        self.inner.execute(eval).await.map_err(cdp)?;
975        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
976        let gesture = self.design_gesture.clone();
977        let pump = tokio::spawn(async move {
978            while let Some(e) = events.next().await {
979                let marker = bridge.accept(
980                    &e.name,
981                    &e.payload,
982                    e.execution_context_id == context,
983                    &gesture,
984                    design_mode::now_ms(),
985                );
986                if let Some(marker) = marker {
987                    if tx.send(marker).is_err() {
988                        break;
989                    }
990                }
991            }
992        });
993        self.pumps.lock().unwrap().push(pump);
994        Ok(DesignModeSession { events: rx })
995    }
996
997    /// Show the outcome of a submission in the picker popup (`window.__omniOnDesignResult`
998    /// in the picker's isolated world).
999    pub async fn design_mode_result(&self, id: u64, ok: bool, message: &str) -> Result<()> {
1000        let context = (*self.design_context.lock().unwrap())
1001            .ok_or_else(|| BrowserError::Invalid("design mode is not enabled".into()))?;
1002        let arg = serde_json::json!({"id": id, "ok": ok, "message": message});
1003        let eval = EvaluateParams::builder()
1004            .expression(format!(
1005                "window.__omniOnDesignResult && window.__omniOnDesignResult({arg})"
1006            ))
1007            .context_id(context)
1008            .build()
1009            .map_err(BrowserError::Invalid)?;
1010        self.inner.execute(eval).await.map_err(cdp)?;
1011        Ok(())
1012    }
1013
1014    // ---- observation -----------------------------------------------------
1015
1016    /// Compact tree of the page's controls, each with a ref (`r<epoch>.<n>`). A ref is accepted only in the
1017    /// epoch it was issued in, for the document it was read from, and while the element behind it still has
1018    /// the tag, role and name it had here; see [`BrowserPage::act`].
1019    pub async fn observe(&self) -> Result<Observation> {
1020        let _l = self.lane.lock().await;
1021        self.observe_locked().await
1022    }
1023
1024    /// Caller holds the lane.
1025    async fn observe_locked(&self) -> Result<Observation> {
1026        let frame_sig = self.frame_signature().await?;
1027        let frame_id = self
1028            .inner
1029            .mainframe()
1030            .await
1031            .map_err(cdp)?
1032            .map(|f| f.as_ref().to_string())
1033            .unwrap_or_default();
1034        let ax = summarize_ax(&self.ax_tree(Some(OBSERVE_AX_DEPTH)).await?);
1035        let raw: Vec<RawNode> = self
1036            .inner
1037            .evaluate(observe_js())
1038            .await
1039            .map_err(cdp)?
1040            .into_value()
1041            .map_err(|e| BrowserError::Cdp(format!("decode observation: {e}")))?;
1042        let viewport: Rect = self
1043            .inner
1044            .evaluate("({x:0,y:0,width:window.innerWidth,height:window.innerHeight})")
1045            .await
1046            .map_err(cdp)?
1047            .into_value()
1048            .map_err(cdp)?;
1049        let fingerprint = raw
1050            .iter()
1051            .map(|n| {
1052                format!(
1053                    "{}|{}|{}|{}|{}",
1054                    n.selector, n.role, n.name, n.visible, n.disabled
1055                )
1056            })
1057            .collect::<Vec<_>>()
1058            .join("\n");
1059        // The document must be the same one at the end of the read as at the start, or the nodes and the
1060        // identity above describe two different pages.
1061        if self.frame_signature().await? != frame_sig {
1062            return Err(BrowserError::Cdp(
1063                "the document was replaced during observation; observe again".into(),
1064            ));
1065        }
1066        let (epoch, nodes, added, removed) = {
1067            let mut o = self.obs.lock().unwrap();
1068            // A replaced document advances the epoch even when its controls look the same, so refs from the
1069            // old document are refused rather than matched by selector in the new one.
1070            if o.fingerprint != fingerprint || o.frame.as_deref() != Some(frame_sig.as_str()) {
1071                o.epoch += 1;
1072                o.fingerprint = fingerprint;
1073            }
1074            o.frame = Some(frame_sig.clone());
1075            let epoch = o.epoch;
1076            o.refs.clear();
1077            let mut cur = HashMap::new();
1078            let mut cur_stable: HashMap<String, u64> = HashMap::new();
1079            let mut cur_sigs: HashMap<String, NodeState> = HashMap::new();
1080            let mut nodes = Vec::new();
1081            for (i, n) in raw.into_iter().enumerate() {
1082                let name = if n.sensitive {
1083                    "••••••••".to_string()
1084                } else {
1085                    n.name.clone()
1086                };
1087                let node_ref = format!("r{epoch}.{}", i + 1);
1088                let stable_id = if n.selector.is_empty() {
1089                    0
1090                } else {
1091                    let existing = o.stable.get(&n.selector).copied();
1092                    let id = match existing {
1093                        Some(id) => id,
1094                        None => {
1095                            o.next_stable += 1;
1096                            o.next_stable
1097                        }
1098                    };
1099                    cur_stable.insert(n.selector.clone(), id);
1100                    id
1101                };
1102                if !n.selector.is_empty() {
1103                    o.refs.insert(
1104                        node_ref.clone(),
1105                        RefEntry {
1106                            selector: n.selector.clone(),
1107                            tag: n.tag.clone(),
1108                            role: n.role.clone(),
1109                            name: name.clone(),
1110                        },
1111                    );
1112                    cur.insert(n.selector.clone(), format!("{}|{}", n.role, name));
1113                }
1114                let node = ObservedNode {
1115                    node_ref,
1116                    role: n.role,
1117                    name,
1118                    tag: n.tag,
1119                    selector: n.selector,
1120                    visible: n.visible,
1121                    disabled: n.disabled,
1122                    sensitive: n.sensitive,
1123                    frame_id: frame_id.clone(),
1124                    stable_id,
1125                    bounds: n.bounds,
1126                };
1127                if !node.selector.is_empty() {
1128                    cur_sigs.insert(node.selector.clone(), NodeState::of(&node));
1129                }
1130                nodes.push(node);
1131            }
1132            o.stable = cur_stable;
1133            o.sigs = cur_sigs;
1134            let added = cur
1135                .keys()
1136                .filter(|k| !o.previous.contains_key(*k))
1137                .cloned()
1138                .collect();
1139            let removed = o
1140                .previous
1141                .keys()
1142                .filter(|k| !cur.contains_key(*k))
1143                .cloned()
1144                .collect();
1145            o.previous = cur;
1146            (epoch, nodes, added, removed)
1147        };
1148        let console_errors = self
1149            .console
1150            .lock()
1151            .await
1152            .iter()
1153            .filter(|l| matches!(l.level.as_str(), "error" | "exception"))
1154            .count();
1155        Ok(Observation {
1156            page_id: self.id.clone(),
1157            epoch,
1158            url: self.url().await,
1159            title: self.title().await,
1160            viewport,
1161            nodes,
1162            ax,
1163            console_errors,
1164            added,
1165            removed,
1166        })
1167    }
1168
1169    /// Resolve a target to a unique CSS selector, rejecting stale refs.
1170    async fn resolve(&self, target: &Target) -> Result<Option<String>> {
1171        match target {
1172            Target::Point(..) => Ok(None),
1173            Target::Selector(s) => {
1174                self.unique(s).await?;
1175                Ok(Some(s.clone()))
1176            }
1177            Target::Ref(r) => {
1178                let (entry, current_epoch) = {
1179                    let o = self.obs.lock().unwrap();
1180                    (o.refs.get(r).cloned(), o.epoch)
1181                };
1182                let entry = entry.ok_or_else(|| BrowserError::StaleRef(r.clone()))?;
1183                let ref_epoch: u64 = r
1184                    .trim_start_matches('r')
1185                    .split('.')
1186                    .next()
1187                    .and_then(|e| e.parse().ok())
1188                    .unwrap_or(0);
1189                if ref_epoch != current_epoch {
1190                    return Err(BrowserError::StaleRef(r.clone()));
1191                }
1192                // The document the ref was read from must still be the page's document: a navigation or
1193                // reload replaced the frame, and a selector can match a different element in the new one.
1194                let seen = self.obs.lock().unwrap().frame.clone();
1195                if seen.as_deref() != Some(self.frame_signature().await?.as_str()) {
1196                    return Err(BrowserError::StaleRef(r.clone()));
1197                }
1198                // Identity check: the element behind the selector must still have the tag, the role and the
1199                // name it had when it was observed, else the page changed under the ref. Role is compared
1200                // as `observe` computed it (the `role` attribute, else the tag's implied role), so a
1201                // same-tag element that takes over a selector with another role is refused.
1202                let script = ELEMENT_IDENTITY_JS
1203                    .replace("__ROLE__", ROLE_EXPR)
1204                    .replace("__SELECTOR__", &js(&entry.selector));
1205                let sig = self.eval(&script).await?;
1206                let text = |k: &str| sig.get(k).and_then(Value::as_str);
1207                let same_tag = text("tag") == Some(entry.tag.as_str());
1208                let same_role = text("role") == Some(entry.role.as_str());
1209                let same_name = text("name") == Some(entry.name.as_str());
1210                // An editable control's text changes as the user types, so its name is not compared.
1211                let editable = matches!(entry.tag.as_str(), "input" | "textarea" | "select");
1212                if !(same_tag && same_role && (same_name || editable)) {
1213                    return Err(BrowserError::StaleRef(r.clone()));
1214                }
1215                Ok(Some(entry.selector))
1216            }
1217        }
1218    }
1219
1220    /// Identity of the main document: its frame id and its loader id. A navigation or reload gives the frame a
1221    /// new loader; a same-document change (history API, hash) does not.
1222    async fn frame_signature(&self) -> Result<String> {
1223        use chromiumoxide::cdp::browser_protocol::page::GetFrameTreeParams;
1224        let tree = self
1225            .inner
1226            .execute(GetFrameTreeParams::default())
1227            .await
1228            .map_err(cdp)?;
1229        let frame = &tree.result.frame_tree.frame;
1230        Ok(format!("{:?}|{:?}", frame.id, frame.loader_id))
1231    }
1232
1233    /// Run one action on an observed ref and return what it changed.
1234    ///
1235    /// Before anything happens the ref is checked: it must be from the page's current epoch, the document it
1236    /// was read from must still be the page's document, and the element behind it must still have the tag,
1237    /// role and name it had at observe. Any mismatch is [`BrowserError::StaleRef`]. The action is then
1238    /// admitted (the hook sees the ref and the element's role and name), run under the page lane, and the
1239    /// page is observed again under that same lane hold, so nothing else acts in between. The returned
1240    /// [`ObservationDiff`] says what appeared, disappeared or changed; when the epoch moved, earlier refs are
1241    /// refused and the diff carries the new refs of what is new.
1242    ///
1243    /// The watchdog counts an action that left no diff (or failed) against its ref. After
1244    /// [`DEFAULT_ACTION_LOOP_LIMIT`](crate::DEFAULT_ACTION_LOOP_LIMIT) such repeats (see
1245    /// [`BrowserPage::set_action_loop_limit`]) the next identical action is refused with
1246    /// [`BrowserError::ActionLoop`], and so is every action after it until
1247    /// [`BrowserPage::reset_action_watch`].
1248    pub async fn act(&self, node_ref: &str, action: &RefAction) -> Result<ActResult> {
1249        let key = action.watch_key(node_ref);
1250        self.watch.lock().unwrap().before(&key)?;
1251        match self.act_once(node_ref, action).await {
1252            Ok(mut result) => {
1253                result.repeats = self
1254                    .watch
1255                    .lock()
1256                    .unwrap()
1257                    .after(key, result.diff.is_empty());
1258                Ok(result)
1259            }
1260            Err(e) => {
1261                self.watch.lock().unwrap().after(key, true);
1262                Err(e)
1263            }
1264        }
1265    }
1266
1267    /// Set how many identical no-diff actions [`BrowserPage::act`] allows (at least 1).
1268    pub fn set_action_loop_limit(&self, limit: u32) -> Result<()> {
1269        self.watch.lock().unwrap().set_limit(limit)
1270    }
1271
1272    /// Clear the watchdog's count and its stop. Call it when a person or the host decided the run may go on.
1273    pub fn reset_action_watch(&self) {
1274        self.watch.lock().unwrap().reset();
1275    }
1276
1277    async fn act_once(&self, node_ref: &str, action: &RefAction) -> Result<ActResult> {
1278        let target = Target::Ref(node_ref.to_string());
1279        let element = {
1280            let o = self.obs.lock().unwrap();
1281            o.refs
1282                .get(node_ref)
1283                .map(|e| format!("element role={} name={}", e.role, e.name))
1284        };
1285        let (kind, detail) = action.admission();
1286        let detail = match (detail, element) {
1287            (Some(d), Some(e)) => Some(format!("{d}; {e}")),
1288            (Some(d), None) => Some(d),
1289            (None, e) => e,
1290        };
1291        self.admit(kind, None, Some(describe(&target)), detail)
1292            .await?;
1293        let _l = self.lane.lock().await;
1294        let url_before = self.url().await;
1295        let (epoch_before, before, frame_before) = {
1296            let o = self.obs.lock().unwrap();
1297            (o.epoch, o.sigs.clone(), o.frame.clone())
1298        };
1299        match action {
1300            RefAction::Click => self.click_n(&target, 1).await?,
1301            RefAction::DoubleClick => self.click_n(&target, 2).await?,
1302            RefAction::Hover => {
1303                let (x, y) = self.point_of(&target).await?;
1304                self.move_to(x, y).await?;
1305            }
1306            RefAction::Fill { text, clear } => self.fill_locked(&target, text, *clear).await?,
1307            RefAction::SelectOption { value } => self.select_locked(&target, value).await?,
1308        }
1309        let obs = self.observe_after_action().await?;
1310        let document_replaced = self.obs.lock().unwrap().frame != frame_before;
1311        let mut added = Vec::new();
1312        let mut changed = Vec::new();
1313        let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
1314        for n in &obs.nodes {
1315            if n.selector.is_empty() {
1316                continue;
1317            }
1318            seen.insert(n.selector.as_str());
1319            match before.get(&n.selector) {
1320                None => added.push(n.clone()),
1321                Some(b) => {
1322                    let a = NodeState::of(n);
1323                    if *b != a {
1324                        changed.push(NodeChange {
1325                            node_ref: n.node_ref.clone(),
1326                            selector: n.selector.clone(),
1327                            before: b.clone(),
1328                            after: a,
1329                        });
1330                    }
1331                }
1332            }
1333        }
1334        let mut removed: Vec<String> = before
1335            .keys()
1336            .filter(|k| !seen.contains(k.as_str()))
1337            .cloned()
1338            .collect();
1339        removed.sort();
1340        Ok(ActResult {
1341            page_id: obs.page_id.clone(),
1342            node_ref: node_ref.to_string(),
1343            epoch: obs.epoch,
1344            diff: ObservationDiff {
1345                epoch_before,
1346                epoch_after: obs.epoch,
1347                url_before,
1348                url_after: obs.url.clone(),
1349                document_replaced,
1350                added,
1351                removed,
1352                changed,
1353            },
1354            repeats: 0,
1355        })
1356    }
1357
1358    /// Observe once the action's effect has settled. An action can start a navigation; an observation that
1359    /// straddles the document swap fails, so it is tried again a few times. Caller holds the lane.
1360    async fn observe_after_action(&self) -> Result<Observation> {
1361        let mut last = None;
1362        for attempt in 0..4u32 {
1363            if attempt > 0 {
1364                tokio::time::sleep(Duration::from_millis(150)).await;
1365            }
1366            match self.observe_locked().await {
1367                Ok(obs) => return Ok(obs),
1368                Err(e) => last = Some(e),
1369            }
1370        }
1371        Err(BrowserError::Cdp(format!(
1372            "the action ran, but the page could not be observed afterwards: {}",
1373            last.map(|e| e.to_string()).unwrap_or_default()
1374        )))
1375    }
1376
1377    async fn unique(&self, selector: &str) -> Result<()> {
1378        let n = self
1379            .eval_internal(&format!(
1380                "document.querySelectorAll({}).length",
1381                js(selector)
1382            ))
1383            .await?
1384            .as_u64()
1385            .unwrap_or(0);
1386        match n {
1387            1 => Ok(()),
1388            0 => Err(BrowserError::NoElement(selector.into())),
1389            n => Err(BrowserError::Ambiguous(selector.into(), n)),
1390        }
1391    }
1392
1393    /// Scroll into view, return the centre point, and verify nothing covers it.
1394    async fn point_of(&self, target: &Target) -> Result<(f64, f64)> {
1395        if let Target::Point(x, y) = target {
1396            return Ok((*x, *y));
1397        }
1398        let sel = self.resolve(target).await?.expect("selector");
1399        let v = self
1400            .eval(&format!(
1401                "(()=>{{const e=document.querySelector({s});e.scrollIntoView({{block:'center',inline:'center'}});\
1402                 const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return null;\
1403                 const x=r.x+r.width/2,y=r.y+r.height/2;const t=document.elementFromPoint(x,y);\
1404                 const hit=!!t&&(t===e||e.contains(t)||t.contains(e));return {{x,y,hit}}}})()",
1405                s = js(&sel)
1406            ))
1407            .await?;
1408        if v.is_null() {
1409            return Err(BrowserError::NotInteractable(sel));
1410        }
1411        if v.get("hit").and_then(Value::as_bool) != Some(true) {
1412            return Err(BrowserError::NotInteractable(format!(
1413                "{sel} (covered by another element)"
1414            )));
1415        }
1416        Ok((
1417            v["x"].as_f64().unwrap_or(0.0),
1418            v["y"].as_f64().unwrap_or(0.0),
1419        ))
1420    }
1421
1422    // ---- real pointer input ----------------------------------------------
1423
1424    async fn mouse_event(
1425        &self,
1426        kind: DispatchMouseEventType,
1427        x: f64,
1428        y: f64,
1429        button: MouseButton,
1430        click_count: i64,
1431    ) -> Result<()> {
1432        if matches!(kind, DispatchMouseEventType::MousePressed) {
1433            self.design_gesture.stamp();
1434        }
1435        let mut p = DispatchMouseEventParams::new(kind.clone(), x, y);
1436        p.button = Some(button);
1437        p.click_count = Some(click_count);
1438        p.buttons = Some(match kind {
1439            DispatchMouseEventType::MousePressed => 1,
1440            DispatchMouseEventType::MouseReleased => 0,
1441            _ => *self.buttons.lock().unwrap(),
1442        });
1443        self.inner.execute(p).await.map_err(cdp)?;
1444        *self.mouse.lock().unwrap() = (x, y);
1445        Ok(())
1446    }
1447
1448    async fn move_to(&self, x: f64, y: f64) -> Result<()> {
1449        self.mouse_event(
1450            DispatchMouseEventType::MouseMoved,
1451            x,
1452            y,
1453            MouseButton::None,
1454            0,
1455        )
1456        .await
1457    }
1458
1459    pub async fn hover(&self, target: &Target) -> Result<()> {
1460        self.admit(ActionKind::Hover, None, Some(describe(target)), None)
1461            .await?;
1462        let _l = self.lane.lock().await;
1463        let (x, y) = self.point_of(target).await?;
1464        self.move_to(x, y).await
1465    }
1466
1467    pub async fn click(&self, target: &Target) -> Result<()> {
1468        self.admit(ActionKind::Click, None, Some(describe(target)), None)
1469            .await?;
1470        let _l = self.lane.lock().await;
1471        self.click_n(target, 1).await
1472    }
1473
1474    pub async fn double_click(&self, target: &Target) -> Result<()> {
1475        self.admit(ActionKind::DoubleClick, None, Some(describe(target)), None)
1476            .await?;
1477        let _l = self.lane.lock().await;
1478        self.click_n(target, 2).await
1479    }
1480
1481    /// Caller holds the lane.
1482    async fn click_n(&self, target: &Target, count: i64) -> Result<()> {
1483        let (x, y) = self.point_of(target).await?;
1484        self.move_to(x, y).await?;
1485        for n in 1..=count {
1486            self.mouse_event(
1487                DispatchMouseEventType::MousePressed,
1488                x,
1489                y,
1490                MouseButton::Left,
1491                n,
1492            )
1493            .await?;
1494            self.mouse_event(
1495                DispatchMouseEventType::MouseReleased,
1496                x,
1497                y,
1498                MouseButton::Left,
1499                n,
1500            )
1501            .await?;
1502        }
1503        Ok(())
1504    }
1505
1506    /// Press at `from`, move in `steps` increments, release at `to`.
1507    pub async fn drag(&self, from: &Target, to: &Target, steps: u32) -> Result<()> {
1508        self.admit(
1509            ActionKind::Drag,
1510            None,
1511            Some(format!("{} -> {}", describe(from), describe(to))),
1512            None,
1513        )
1514        .await?;
1515        let _l = self.lane.lock().await;
1516        let (x0, y0) = self.point_of(from).await?;
1517        let (x1, y1) = self.point_of(to).await?;
1518        self.move_to(x0, y0).await?;
1519        self.mouse_event(
1520            DispatchMouseEventType::MousePressed,
1521            x0,
1522            y0,
1523            MouseButton::Left,
1524            1,
1525        )
1526        .await?;
1527        *self.buttons.lock().unwrap() = 1;
1528        let steps = steps.max(1);
1529        for i in 1..=steps {
1530            let t = f64::from(i) / f64::from(steps);
1531            self.mouse_event(
1532                DispatchMouseEventType::MouseMoved,
1533                x0 + (x1 - x0) * t,
1534                y0 + (y1 - y0) * t,
1535                MouseButton::Left,
1536                0,
1537            )
1538            .await?;
1539        }
1540        *self.buttons.lock().unwrap() = 0;
1541        self.mouse_event(
1542            DispatchMouseEventType::MouseReleased,
1543            x1,
1544            y1,
1545            MouseButton::Left,
1546            1,
1547        )
1548        .await
1549    }
1550
1551    /// Mouse-wheel scroll at the target (or viewport centre when `None`).
1552    pub async fn wheel(&self, at: Option<&Target>, dx: f64, dy: f64) -> Result<()> {
1553        self.admit(
1554            ActionKind::Wheel,
1555            None,
1556            at.map(describe),
1557            Some(format!("dx={dx} dy={dy}")),
1558        )
1559        .await?;
1560        let _l = self.lane.lock().await;
1561        let (x, y) = match at {
1562            Some(t) => self.point_of(t).await?,
1563            None => {
1564                let v = self
1565                    .eval_internal("({x:innerWidth/2,y:innerHeight/2})")
1566                    .await?;
1567                (
1568                    v["x"].as_f64().unwrap_or(100.0),
1569                    v["y"].as_f64().unwrap_or(100.0),
1570                )
1571            }
1572        };
1573        let mut p = DispatchMouseEventParams::new(DispatchMouseEventType::MouseWheel, x, y);
1574        p.delta_x = Some(dx);
1575        p.delta_y = Some(dy);
1576        self.inner.execute(p).await.map_err(cdp)?;
1577        Ok(())
1578    }
1579
1580    /// Programmatic scroll (`scrollBy`) of the element at `target`, or of the window when
1581    /// `None`. Use it where a wheel event at the element's centre is wrong: a covered element,
1582    /// or one that is not scrollable under the pointer. Selectors and refs must resolve to one
1583    /// element; a point scrolls the element under it. No element at a point is an error.
1584    pub async fn scroll_by(&self, target: Option<&Target>, dx: f64, dy: f64) -> Result<()> {
1585        if !dx.is_finite() || !dy.is_finite() {
1586            return Err(BrowserError::Invalid(format!(
1587                "scroll offsets must be finite, got dx={dx} dy={dy}"
1588            )));
1589        }
1590        self.admit(
1591            ActionKind::Wheel,
1592            None,
1593            target.map(describe),
1594            Some(format!("scroll_by dx={dx} dy={dy}")),
1595        )
1596        .await?;
1597        let _l = self.lane.lock().await;
1598        let offset = format!("{{left:{dx},top:{dy}}}");
1599        let found = match target {
1600            None => {
1601                self.eval_internal(&format!(
1602                    "(()=>{{window.scrollBy({offset});return true}})()"
1603                ))
1604                .await?
1605            }
1606            Some(Target::Point(x, y)) => {
1607                if !x.is_finite() || !y.is_finite() {
1608                    return Err(BrowserError::Invalid(format!(
1609                        "scroll point must be finite, got {x},{y}"
1610                    )));
1611                }
1612                self.eval_internal(&format!(
1613                    "(()=>{{const e=document.elementFromPoint({x},{y});if(!e)return false;e.scrollBy({offset});return true}})()"
1614                ))
1615                .await?
1616            }
1617            Some(t) => {
1618                let sel = self.resolve(t).await?.expect("selector");
1619                self.eval_internal(&format!(
1620                    "(()=>{{const e=document.querySelector({});if(!e)return false;e.scrollBy({offset});return true}})()",
1621                    js(&sel)
1622                ))
1623                .await?
1624            }
1625        };
1626        if found.as_bool() != Some(true) {
1627            return Err(BrowserError::NoElement(
1628                target.map(describe).unwrap_or_default(),
1629            ));
1630        }
1631        Ok(())
1632    }
1633
1634    // ---- real keyboard input ---------------------------------------------
1635
1636    async fn key_event(
1637        &self,
1638        kind: DispatchKeyEventType,
1639        d: &KeyDef,
1640        mods: i64,
1641        with_text: bool,
1642    ) -> Result<()> {
1643        if matches!(
1644            kind,
1645            DispatchKeyEventType::KeyDown | DispatchKeyEventType::RawKeyDown
1646        ) {
1647            self.design_gesture.stamp();
1648        }
1649        let mut p = DispatchKeyEventParams::new(kind);
1650        p.modifiers = Some(mods);
1651        p.key = Some(d.key.clone());
1652        if !d.code.is_empty() {
1653            p.code = Some(d.code.clone());
1654        }
1655        p.windows_virtual_key_code = Some(d.vk);
1656        p.native_virtual_key_code = Some(d.vk);
1657        if with_text {
1658            p.text = d.text.clone();
1659            p.unmodified_text = d.text.clone();
1660        }
1661        self.inner.execute(p).await.map_err(cdp)?;
1662        Ok(())
1663    }
1664
1665    async fn press_locked(&self, spec: &str) -> Result<()> {
1666        let (mods, mod_keys, def) = keys::parse_chord(spec)?;
1667        for (_, m) in &mod_keys {
1668            self.key_event(DispatchKeyEventType::RawKeyDown, m, mods, false)
1669                .await?;
1670        }
1671        // Shortcut chords (Ctrl/Meta/Alt) carry no text.
1672        let text = mods & (keys::CTRL | keys::META | keys::ALT) == 0;
1673        let kind = if text && def.text.is_some() {
1674            DispatchKeyEventType::KeyDown
1675        } else {
1676            DispatchKeyEventType::RawKeyDown
1677        };
1678        self.key_event(kind, &def, mods, text).await?;
1679        self.key_event(DispatchKeyEventType::KeyUp, &def, mods, false)
1680            .await?;
1681        for (_, m) in mod_keys.iter().rev() {
1682            self.key_event(DispatchKeyEventType::KeyUp, m, 0, false)
1683                .await?;
1684        }
1685        Ok(())
1686    }
1687
1688    /// Press a key or chord (`Enter`, `Tab`, `Control+a`) on the focused element.
1689    pub async fn press(&self, spec: &str) -> Result<()> {
1690        self.admit(ActionKind::Press, None, Some(spec.to_string()), None)
1691            .await?;
1692        let _l = self.lane.lock().await;
1693        self.press_locked(spec).await
1694    }
1695
1696    /// Type text one key event at a time into the focused element.
1697    pub async fn type_text(&self, text: &str) -> Result<()> {
1698        self.admit(
1699            ActionKind::TypeText,
1700            None,
1701            None,
1702            Some(format!("chars={}", text.chars().count())),
1703        )
1704        .await?;
1705        let _l = self.lane.lock().await;
1706        self.type_locked(text).await
1707    }
1708
1709    async fn type_locked(&self, text: &str) -> Result<()> {
1710        for c in text.chars() {
1711            let d = keys::char_key(c);
1712            self.key_event(DispatchKeyEventType::KeyDown, &d, 0, true)
1713                .await?;
1714            self.key_event(DispatchKeyEventType::KeyUp, &d, 0, false)
1715                .await?;
1716        }
1717        Ok(())
1718    }
1719
1720    /// Click the target to focus it, then type.
1721    pub async fn fill(&self, target: &Target, text: &str, clear: bool) -> Result<()> {
1722        self.admit(
1723            ActionKind::Fill,
1724            None,
1725            Some(describe(target)),
1726            Some(format!("chars={} clear={clear}", text.chars().count())),
1727        )
1728        .await?;
1729        let _l = self.lane.lock().await;
1730        self.fill_locked(target, text, clear).await
1731    }
1732
1733    /// Caller holds the lane.
1734    async fn fill_locked(&self, target: &Target, text: &str, clear: bool) -> Result<()> {
1735        self.click_n(target, 1).await?;
1736        if clear {
1737            let sel_all = if cfg!(target_os = "macos") {
1738                "Meta+a"
1739            } else {
1740                "Control+a"
1741            };
1742            self.press_locked(sel_all).await?;
1743            self.press_locked("Backspace").await?;
1744        }
1745        self.type_locked(text).await
1746    }
1747
1748    // ---- other actions -----------------------------------------------------
1749
1750    /// Choose a `<select>` option by value/label. Native popups cannot be driven
1751    /// over CDP, so this sets the value and fires `input`/`change` (documented gap).
1752    pub async fn select_option(&self, target: &Target, value: &str) -> Result<()> {
1753        self.admit(
1754            ActionKind::Select,
1755            None,
1756            Some(describe(target)),
1757            Some(format!("value={value}")),
1758        )
1759        .await?;
1760        let _l = self.lane.lock().await;
1761        self.select_locked(target, value).await
1762    }
1763
1764    /// Caller holds the lane.
1765    async fn select_locked(&self, target: &Target, value: &str) -> Result<()> {
1766        let sel = self
1767            .resolve(target)
1768            .await?
1769            .ok_or_else(|| BrowserError::Invalid("select needs an element".into()))?;
1770        let r = self
1771            .eval(&format!(
1772                "(()=>{{const e=document.querySelector({s});const w={v};\
1773                 const o=[...e.options].find(o=>o.value===w||o.label===w||o.text.trim()===w);if(!o)return 'nooption';\
1774                 e.value=o.value;e.dispatchEvent(new Event('input',{{bubbles:true}}));e.dispatchEvent(new Event('change',{{bubbles:true}}));return 'ok'}})()",
1775                s = js(&sel),
1776                v = js(value)
1777            ))
1778            .await?;
1779        if r.as_str() == Some("ok") {
1780            Ok(())
1781        } else {
1782            Err(BrowserError::Invalid(format!(
1783                "'{sel}' has no option '{value}'"
1784            )))
1785        }
1786    }
1787
1788    pub async fn upload(&self, target: &Target, file: &Path) -> Result<()> {
1789        self.admit(
1790            ActionKind::Upload,
1791            None,
1792            Some(describe(target)),
1793            Some(file.display().to_string()),
1794        )
1795        .await?;
1796        let _l = self.lane.lock().await;
1797        let file = file.canonicalize()?;
1798        if !file.is_file() {
1799            return Err(BrowserError::Invalid(
1800                "upload must be a regular file".into(),
1801            ));
1802        }
1803        if let Some(root) = &self.upload_root {
1804            if !file.starts_with(root.canonicalize()?) {
1805                return Err(BrowserError::Invalid(
1806                    "upload outside the configured upload root".into(),
1807                ));
1808            }
1809        }
1810        if std::fs::metadata(&file)?.len() > MAX_UPLOAD_BYTES {
1811            return Err(BrowserError::Invalid("upload exceeds 64 MiB".into()));
1812        }
1813        let sel = self
1814            .resolve(target)
1815            .await?
1816            .ok_or_else(|| BrowserError::Invalid("upload needs an element".into()))?;
1817        let el = self
1818            .inner
1819            .find_element(sel.as_str())
1820            .await
1821            .map_err(|_| BrowserError::NoElement(sel.clone()))?;
1822        let node = el.description().await.map_err(cdp)?;
1823        self.inner
1824            .execute(
1825                SetFileInputFilesParams::builder()
1826                    .file(file.to_string_lossy().to_string())
1827                    .backend_node_id(node.backend_node_id)
1828                    .build()
1829                    .map_err(BrowserError::Invalid)?,
1830            )
1831            .await
1832            .map_err(cdp)?;
1833        Ok(())
1834    }
1835
1836    pub async fn wait_for(&self, selector: &str, timeout: Duration) -> Result<()> {
1837        self.wait_eval(
1838            &format!("!!document.querySelector({})", js(selector)),
1839            timeout,
1840        )
1841        .await
1842    }
1843
1844    /// Poll a JS expression until truthy.
1845    pub async fn wait_eval(&self, expr: &str, timeout: Duration) -> Result<()> {
1846        self.admit(
1847            ActionKind::Eval,
1848            None,
1849            None,
1850            Some(expr.chars().take(2000).collect()),
1851        )
1852        .await?;
1853        let deadline = Instant::now() + timeout;
1854        loop {
1855            let v = self.eval_internal(expr).await?;
1856            if v.as_bool()
1857                .unwrap_or(!v.is_null() && v != Value::Bool(false))
1858            {
1859                return Ok(());
1860            }
1861            if Instant::now() >= deadline {
1862                return Err(BrowserError::Timeout(expr.to_string()));
1863            }
1864            tokio::time::sleep(Duration::from_millis(50)).await;
1865        }
1866    }
1867
1868    pub async fn screenshot(&self) -> Result<Vec<u8>> {
1869        self.screenshot_with(ScreenshotOptions::default()).await
1870    }
1871
1872    /// PNG screenshot of the viewport with options; `ScreenshotOptions::default()` matches
1873    /// [`BrowserPage::screenshot`].
1874    pub async fn screenshot_with(&self, options: ScreenshotOptions) -> Result<Vec<u8>> {
1875        let params = self.screenshot_params(&options).await?;
1876        self.inner.screenshot(params).await.map_err(cdp)
1877    }
1878
1879    /// Build the CDP capture request for `options`. A scale without a clip captures the visual
1880    /// viewport (`Page.getLayoutMetrics`) at that scale, so the output is `scale` times its CSS size.
1881    async fn screenshot_params(&self, options: &ScreenshotOptions) -> Result<ScreenshotParams> {
1882        let mut params_builder = CaptureScreenshotParams::builder();
1883        match options.format {
1884            ScreenshotFormat::Png => {
1885                params_builder = params_builder.format(CaptureScreenshotFormat::Png);
1886            }
1887            ScreenshotFormat::Jpeg { quality } => {
1888                if !(1..=100).contains(&quality) {
1889                    return Err(BrowserError::Invalid(
1890                        "JPEG screenshot quality must be 1 to 100".into(),
1891                    ));
1892                }
1893                if options.omit_background {
1894                    return Err(BrowserError::Invalid(
1895                        "omit_background needs a PNG screenshot".into(),
1896                    ));
1897                }
1898                params_builder = params_builder
1899                    .format(CaptureScreenshotFormat::Jpeg)
1900                    .quality(i64::from(quality));
1901            }
1902        }
1903        let scale = match options.scale {
1904            None => None,
1905            Some(s) if s.is_finite() && s > 0.0 => Some(s),
1906            Some(_) => {
1907                return Err(BrowserError::Invalid(
1908                    "screenshot scale must be positive and finite".into(),
1909                ))
1910            }
1911        };
1912        if let Some(region) = &options.clip {
1913            region.validate()?;
1914        }
1915        let clip = match (options.clip, scale) {
1916            (None, None) => None,
1917            (region, scale) => {
1918                let (x, y, width, height) = match region {
1919                    Some(r) => (r.x, r.y, r.width, r.height),
1920                    None => {
1921                        let metrics = self.inner.layout_metrics().await.map_err(cdp)?;
1922                        let v = metrics.css_visual_viewport;
1923                        (v.page_x, v.page_y, v.client_width, v.client_height)
1924                    }
1925                };
1926                Some(Viewport {
1927                    x,
1928                    y,
1929                    width,
1930                    height,
1931                    scale: scale.unwrap_or(1.0),
1932                })
1933            }
1934        };
1935        if let Some(clip) = clip {
1936            params_builder = params_builder.clip(clip);
1937        }
1938        Ok(ScreenshotParams {
1939            cdp_params: params_builder.build(),
1940            full_page: None,
1941            omit_background: Some(options.omit_background),
1942        })
1943    }
1944
1945    pub async fn screenshot_to(&self, path: &Path) -> Result<()> {
1946        std::fs::write(path, self.screenshot().await?)?;
1947        Ok(())
1948    }
1949
1950    pub async fn console(&self) -> Vec<ConsoleLine> {
1951        self.console.lock().await.clone()
1952    }
1953
1954    pub async fn clear_console(&self) {
1955        self.console.lock().await.clear();
1956    }
1957}
1958
1959/// Register the `Fetch.requestPaused` listener, then enable `Fetch` for every URL, in that
1960/// order so no request is paused without a listener. One short task per request: the network
1961/// policy first (its refusal is final), then the caller's hook when one is installed.
1962async fn start_intercept_pump(
1963    inner: &Page,
1964    page_id: &str,
1965    guard: &Arc<Guard>,
1966    sink: Arc<StdMutex<Vec<BlockedRequest>>>,
1967    stats: Arc<InterceptStats>,
1968    hook_slot: Arc<StdMutex<Option<RequestInterceptor>>>,
1969) -> Result<JoinHandle<()>> {
1970    let mut paused = inner
1971        .event_listener::<EventRequestPaused>()
1972        .await
1973        .map_err(cdp)?;
1974    let page = inner.clone();
1975    let g = guard.clone();
1976    let page_id = page_id.to_string();
1977    let pump = tokio::spawn(async move {
1978        use std::sync::atomic::Ordering::Relaxed;
1979        while let Some(e) = paused.next().await {
1980            let stats = stats.clone();
1981            stats.paused.fetch_add(1, Relaxed);
1982            let page = page.clone();
1983            let g = g.clone();
1984            let sink = sink.clone();
1985            let pid = page_id.clone();
1986            let hook_slot = hook_slot.clone();
1987            tokio::spawn(async move {
1988                let kind = format!("{:?}", e.resource_type);
1989                match g.check_request(&e.request.url, &kind).await {
1990                    Ok(()) => {
1991                        let hook = hook_slot.lock().unwrap().clone();
1992                        let decision = match hook {
1993                            None => InterceptDecision::Continue,
1994                            Some(hook) => {
1995                                match serde_json::to_value(&*e)
1996                                    .ok()
1997                                    .and_then(|v| InterceptedRequest::from_cdp_value(&v))
1998                                {
1999                                    Some(request) => {
2000                                        run_interceptor(&hook, request, INTERCEPTOR_TIMEOUT).await
2001                                    }
2002                                    None => InterceptDecision::Fail(InterceptFailure::Failed),
2003                                }
2004                            }
2005                        };
2006                        let hook_failed = matches!(decision, InterceptDecision::Fail(_));
2007                        let (counter, result) = match command_for(e.request_id.clone(), decision) {
2008                            PausedCommand::Continue(p) => {
2009                                (&stats.continued, page.execute(p).await.map(|_| ()))
2010                            }
2011                            PausedCommand::Fulfill(p) => {
2012                                (&stats.fulfilled, page.execute(p).await.map(|_| ()))
2013                            }
2014                            PausedCommand::Fail(p) => {
2015                                (&stats.refused, page.execute(p).await.map(|_| ()))
2016                            }
2017                        };
2018                        match result {
2019                            Ok(()) => {
2020                                counter.fetch_add(1, Relaxed);
2021                                if hook_failed {
2022                                    let mut b = sink.lock().unwrap();
2023                                    if b.len() < 500 {
2024                                        b.push(BlockedRequest {
2025                                            url: e.request.url.clone(),
2026                                            reason: "failed by the request interceptor".into(),
2027                                        });
2028                                    }
2029                                }
2030                            }
2031                            Err(error) => {
2032                                stats.errors.fetch_add(1, Relaxed);
2033                                *stats.last_error.lock().unwrap() = Some(error.to_string());
2034                            }
2035                        }
2036                    }
2037                    Err(reason) => {
2038                        let _ = page
2039                            .execute(FailRequestParams::new(
2040                                e.request_id.clone(),
2041                                ErrorReason::BlockedByClient,
2042                            ))
2043                            .await;
2044                        stats.refused.fetch_add(1, Relaxed);
2045                        g.denied_network(Some(&pid), &kind, &reason);
2046                        let mut b = sink.lock().unwrap();
2047                        if b.len() < 500 {
2048                            b.push(BlockedRequest {
2049                                url: e.request.url.clone(),
2050                                reason: reason.to_string(),
2051                            });
2052                        }
2053                    }
2054                }
2055            });
2056        }
2057    });
2058    let en = FetchEnableParams {
2059        patterns: Some(vec![RequestPattern {
2060            url_pattern: Some("*".into()),
2061            resource_type: None,
2062            request_stage: None,
2063        }]),
2064        ..Default::default()
2065    };
2066    if let Err(e) = inner.execute(en).await {
2067        pump.abort();
2068        return Err(cdp(e));
2069    }
2070    Ok(pump)
2071}
2072
2073async fn push_capped(sink: &Arc<Mutex<Vec<ConsoleLine>>>, line: ConsoleLine) {
2074    let mut g = sink.lock().await;
2075    if g.len() >= MAX_CONSOLE_LINES {
2076        g.remove(0);
2077    }
2078    g.push(line);
2079}
2080
2081fn describe(t: &Target) -> String {
2082    match t {
2083        Target::Ref(r) => format!("ref:{r}"),
2084        Target::Selector(s) => format!("css:{s}"),
2085        Target::Point(x, y) => format!("point:{x},{y}"),
2086    }
2087}
2088
2089fn js(s: &str) -> String {
2090    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into())
2091}
2092
2093const OBSERVE_JS_TEMPLATE: &str = r#"(() => {
2094  const esc = globalThis.CSS?.escape || (v => String(v).replace(/[^a-zA-Z0-9_-]/g, '\\$&'));
2095  const unique = c => { if (!c) return null; try { return document.querySelectorAll(c).length === 1 ? c : null; } catch (_) { return null; } };
2096  const selectorFor = el => {
2097    if (el.id) { const s = unique('#' + esc(el.id)); if (s) return s; }
2098    for (const a of ['data-testid', 'name', 'aria-label']) {
2099      const v = el.getAttribute(a);
2100      if (v) { const s = unique(el.tagName.toLowerCase() + '[' + a + '="' + esc(v) + '"]'); if (s) return s; }
2101    }
2102    const parts = [];
2103    for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
2104      let p = n.tagName.toLowerCase();
2105      const sib = n.parentElement ? [...n.parentElement.children].filter(x => x.tagName === n.tagName) : [];
2106      if (sib.length > 1) p += ':nth-of-type(' + (sib.indexOf(n) + 1) + ')';
2107      parts.unshift(p);
2108      const c = parts.join(' > ');
2109      if (unique(c)) return c;
2110    }
2111    return '';
2112  };
2113  const sel = 'a[href],button,input,select,textarea,[role],[tabindex],[contenteditable="true"],[onclick]';
2114  return [...document.querySelectorAll(sel)].slice(0, 300).map(el => {
2115    const r = el.getBoundingClientRect();
2116    const ac = (el.getAttribute('autocomplete') || '').trim().toLowerCase();
2117    const sensitive = (el instanceof HTMLInputElement && el.type.toLowerCase() === 'password') || ac === 'current-password' || ac === 'new-password';
2118    const visible = (() => {
2119      for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
2120        const s = getComputedStyle(n);
2121        if (n.hidden || n.getAttribute('aria-hidden') === 'true' || s.visibility === 'hidden' || s.display === 'none' || s.opacity === '0') return false;
2122      }
2123      return r.width > 0 && r.height > 0;
2124    })();
2125    return {
2126      role: __ROLE__,
2127      name: (el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('placeholder') || '').trim().slice(0, 160),
2128      tag: el.tagName.toLowerCase(), selector: selectorFor(el), visible,
2129      disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true', sensitive,
2130      bounds: {x: r.x, y: r.y, width: r.width, height: r.height}
2131    };
2132  });
2133})()"#;
2134
2135/// The role of `el`, exactly as `observe` reports it: the `role` attribute, else the tag's implied role, else
2136/// the tag name. The ref check evaluates this same text, so the two cannot disagree.
2137const ROLE_EXPR: &str = "el.getAttribute('role') || ({A:'link',BUTTON:'button',INPUT:'textbox',SELECT:'combobox',TEXTAREA:'textbox'}[el.tagName] || el.tagName.toLowerCase())";
2138
2139fn observe_js() -> String {
2140    OBSERVE_JS_TEMPLATE.replace("__ROLE__", ROLE_EXPR)
2141}
2142
2143/// Reads the one element a ref's selector matches: its tag, role and name, as `observe` computes them.
2144/// `null` when the selector no longer matches exactly one element.
2145const ELEMENT_IDENTITY_JS: &str = r#"(()=>{const l=document.querySelectorAll(__SELECTOR__);if(l.length!==1)return null;const el=l[0];
2146return {tag:el.tagName.toLowerCase(),role:__ROLE__,name:(el.getAttribute('aria-label')||el.innerText||el.value||el.getAttribute('placeholder')||'').trim().slice(0,160)}})()"#;
2147
2148/// The `http` or `https` origin of `url` (scheme, host, non-default port; lower case; no userinfo, path,
2149/// query or fragment), or `None` for any other kind of address.
2150#[cfg(feature = "secret-fill")]
2151fn origin_of(url: &str) -> Option<String> {
2152    let (scheme, rest) = url.trim().split_once("://")?;
2153    let scheme = scheme.to_ascii_lowercase();
2154    if scheme != "http" && scheme != "https" {
2155        return None;
2156    }
2157    let authority = rest.split(['/', '?', '#']).next()?;
2158    let host_port = authority
2159        .rsplit_once('@')
2160        .map_or(authority, |(_, host)| host)
2161        .to_ascii_lowercase();
2162    if host_port.is_empty() || host_port.contains(char::is_whitespace) {
2163        return None;
2164    }
2165    let (host, port) = match host_port.rsplit_once(':') {
2166        Some((host, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => {
2167            (host, Some(port))
2168        }
2169        _ => (host_port.as_str(), None),
2170    };
2171    if host.is_empty() {
2172        return None;
2173    }
2174    let default = if scheme == "https" { "443" } else { "80" };
2175    Some(match port {
2176        Some(port) if port != default => format!("{scheme}://{host}:{port}"),
2177        _ => format!("{scheme}://{host}"),
2178    })
2179}
2180
2181/// True for an `<input>` that is a password or a card field: `type=password`, or an `autocomplete`
2182/// token of `current-password`, `new-password` or starting `cc-`. Takes the selector as a JS string literal.
2183#[cfg(feature = "secret-fill")]
2184const CREDENTIAL_FIELD_JS: &str = r#"(()=>{const e=document.querySelector(__SELECTOR__);
2185if(!e||e.tagName!=='INPUT')return false;
2186if((e.type||'').toLowerCase()==='password')return true;
2187return (e.getAttribute('autocomplete')||'').toLowerCase().split(/\s+/).some(t=>t==='current-password'||t==='new-password'||t.startsWith('cc-'))})()"#;
2188
2189#[cfg(feature = "secret-fill")]
2190impl BrowserPage {
2191    /// Type a secret into a password or card field of this page (feature `secret-fill`; works on every
2192    /// platform the crate runs on, Linux included).
2193    ///
2194    /// Refused, with nothing typed, unless: `claimed_origin` is an `http` or `https` address whose origin
2195    /// equals the origin of the page's own current address (the page is asked, never the caller's word
2196    /// about it), and `target` resolves to one `<input>` that is `type=password` or has an `autocomplete`
2197    /// of `current-password`, `new-password` or `cc-*`. The audit record carries only the character count
2198    /// (as for `fill`). The secret is a [`rightkit_crypto::Secret`], wiped when dropped; it is typed one
2199    /// key event at a time, and the per-key event descriptors this makes are not wiped (a limit).
2200    pub async fn fill_secret(
2201        &self,
2202        target: &Target,
2203        secret: &rightkit_crypto::Secret,
2204        claimed_origin: &str,
2205        clear: bool,
2206    ) -> Result<()> {
2207        let claimed = origin_of(claimed_origin).ok_or_else(|| {
2208            BrowserError::Invalid("the claimed origin is not an http or https address".into())
2209        })?;
2210        let actual = origin_of(&self.url().await)
2211            .ok_or_else(|| BrowserError::Denied("the page has no http or https origin".into()))?;
2212        if claimed != actual {
2213            return Err(BrowserError::Denied(
2214                "the page origin is not the claimed origin".into(),
2215            ));
2216        }
2217        let text = std::str::from_utf8(secret.expose())
2218            .map_err(|_| BrowserError::Invalid("the secret is not text".into()))?;
2219        self.admit(
2220            ActionKind::Fill,
2221            None,
2222            Some(describe(target)),
2223            Some(format!(
2224                "chars={} clear={clear} secret",
2225                text.chars().count()
2226            )),
2227        )
2228        .await?;
2229        let _l = self.lane.lock().await;
2230        let selector = self
2231            .resolve(target)
2232            .await?
2233            .ok_or_else(|| BrowserError::Invalid("fill_secret needs an element".into()))?;
2234        let is_credential = self
2235            .eval_internal(&CREDENTIAL_FIELD_JS.replace("__SELECTOR__", &js(&selector)))
2236            .await?;
2237        if is_credential.as_bool() != Some(true) {
2238            return Err(BrowserError::Denied(
2239                "the field is not a password or card field".into(),
2240            ));
2241        }
2242        self.fill_locked(target, text, clear).await
2243    }
2244}