Skip to main content

rightkit_browser/
page.rs

1use crate::error::{cdp, BrowserError, Result};
2use crate::keys::{self, KeyDef};
3use crate::policy::{ActionKind, AdmissionRequest, BlockedRequest, Guard, LifecycleKind};
4use chromiumoxide::cdp::browser_protocol::dom::SetFileInputFilesParams;
5use chromiumoxide::cdp::browser_protocol::fetch::{
6    ContinueRequestParams, EnableParams as FetchEnableParams, EventRequestPaused,
7    FailRequestParams, RequestPattern,
8};
9use chromiumoxide::cdp::browser_protocol::input::{
10    DispatchKeyEventParams, DispatchKeyEventType, DispatchMouseEventParams, DispatchMouseEventType,
11    MouseButton,
12};
13use chromiumoxide::cdp::browser_protocol::inspector::{
14    EnableParams as InspectorEnableParams, EventTargetCrashed,
15};
16use chromiumoxide::cdp::browser_protocol::network::ErrorReason;
17use chromiumoxide::cdp::browser_protocol::page::CaptureScreenshotFormat;
18use chromiumoxide::cdp::js_protocol::runtime::{EventConsoleApiCalled, EventExceptionThrown};
19use chromiumoxide::page::{Page, ScreenshotParams};
20use futures::StreamExt;
21use serde::{Deserialize, Serialize};
22use serde_json::Value;
23use std::collections::HashMap;
24use std::path::{Path, PathBuf};
25use std::sync::{Arc, Mutex as StdMutex};
26use std::time::{Duration, Instant};
27use tokio::sync::Mutex;
28use tokio::task::JoinHandle;
29
30pub const MAX_CONSOLE_LINES: usize = 500;
31const MAX_UPLOAD_BYTES: u64 = 64 * 1024 * 1024;
32
33#[derive(Clone, Debug, Serialize)]
34pub struct ConsoleLine {
35    pub level: String,
36    pub text: String,
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
40pub struct Rect {
41    pub x: f64,
42    pub y: f64,
43    pub width: f64,
44    pub height: f64,
45}
46
47#[derive(Clone, Debug, Serialize)]
48pub struct ObservedNode {
49    /// `r<epoch>.<n>`; valid only while the page stays unchanged.
50    pub node_ref: String,
51    pub role: String,
52    pub name: String,
53    pub tag: String,
54    pub selector: String,
55    pub visible: bool,
56    pub disabled: bool,
57    pub bounds: Rect,
58}
59
60#[derive(Clone, Debug, Serialize)]
61pub struct Observation {
62    pub page_id: String,
63    pub epoch: u64,
64    pub url: String,
65    pub title: String,
66    pub viewport: Rect,
67    pub nodes: Vec<ObservedNode>,
68    pub console_errors: usize,
69    /// Refs/roles/names added, removed, or changed since the previous observation.
70    pub added: Vec<String>,
71    pub removed: Vec<String>,
72}
73
74/// What an action addresses.
75#[derive(Clone, Debug)]
76pub enum Target {
77    /// Ref from [`BrowserPage::observe`]; checked for staleness.
78    Ref(String),
79    /// A CSS selector that must match exactly one element.
80    Selector(String),
81    /// Viewport coordinates.
82    Point(f64, f64),
83}
84
85impl Target {
86    pub fn css(s: impl Into<String>) -> Self {
87        Target::Selector(s.into())
88    }
89    pub fn node_ref(s: impl Into<String>) -> Self {
90        Target::Ref(s.into())
91    }
92}
93
94#[derive(Clone, Debug, Deserialize)]
95struct RawNode {
96    role: String,
97    name: String,
98    tag: String,
99    selector: String,
100    visible: bool,
101    disabled: bool,
102    #[serde(default)]
103    sensitive: bool,
104    bounds: Rect,
105}
106
107#[derive(Clone, Debug)]
108struct RefEntry {
109    selector: String,
110    tag: String,
111    role: String,
112    name: String,
113}
114
115#[derive(Default)]
116struct ObsState {
117    epoch: u64,
118    fingerprint: String,
119    refs: HashMap<String, RefEntry>,
120    previous: HashMap<String, String>,
121}
122
123/// What the request-interception pump has done on one page. Reported when a navigation
124/// fails, so a timeout says how far the navigation got: no request paused (it never reached
125/// the network stage), paused but not answered (the policy check did not return), or
126/// continued (the request left the browser and the proxy or the server did not finish it).
127#[derive(Default)]
128struct InterceptStats {
129    paused: std::sync::atomic::AtomicUsize,
130    continued: std::sync::atomic::AtomicUsize,
131    refused: std::sync::atomic::AtomicUsize,
132    errors: std::sync::atomic::AtomicUsize,
133    last_error: StdMutex<Option<String>>,
134}
135
136impl InterceptStats {
137    fn summary(&self) -> String {
138        use std::sync::atomic::Ordering::Relaxed;
139        let mut text = format!(
140            "requests paused {}, continued {}, refused {}",
141            self.paused.load(Relaxed),
142            self.continued.load(Relaxed),
143            self.refused.load(Relaxed)
144        );
145        let errors = self.errors.load(Relaxed);
146        if errors > 0 {
147            let last = self.last_error.lock().unwrap().clone().unwrap_or_default();
148            text.push_str(&format!(", {errors} not answered: {last}"));
149        }
150        text
151    }
152}
153
154pub struct BrowserPage {
155    id: String,
156    inner: Page,
157    console: Arc<Mutex<Vec<ConsoleLine>>>,
158    obs: StdMutex<ObsState>,
159    mouse: StdMutex<(f64, f64)>,
160    buttons: StdMutex<i64>,
161    /// Serializes mutations so concurrent callers commit in order.
162    lane: Mutex<()>,
163    upload_root: Option<PathBuf>,
164    pumps: StdMutex<Vec<JoinHandle<()>>>,
165    guard: Arc<Guard>,
166    blocked: Arc<StdMutex<Vec<BlockedRequest>>>,
167    intercept: Arc<InterceptStats>,
168}
169
170impl BrowserPage {
171    pub(crate) async fn attach(
172        id: String,
173        inner: Page,
174        upload_root: Option<PathBuf>,
175        guard: Arc<Guard>,
176        fixture_fetch_owner: bool,
177    ) -> Result<Self> {
178        let console = Arc::new(Mutex::new(Vec::new()));
179        let mut pumps = Vec::new();
180        let mut ev = inner
181            .event_listener::<EventConsoleApiCalled>()
182            .await
183            .map_err(cdp)?;
184        let sink = console.clone();
185        pumps.push(tokio::spawn(async move {
186            while let Some(e) = ev.next().await {
187                let text = e
188                    .args
189                    .iter()
190                    .map(|a| match (&a.value, &a.description) {
191                        (Some(Value::String(s)), _) => s.clone(),
192                        (Some(v), _) => v.to_string(),
193                        (None, Some(d)) => d.clone(),
194                        _ => String::new(),
195                    })
196                    .collect::<Vec<_>>()
197                    .join(" ");
198                push_capped(
199                    &sink,
200                    ConsoleLine {
201                        level: format!("{:?}", e.r#type).to_lowercase(),
202                        text,
203                    },
204                )
205                .await;
206            }
207        }));
208        let mut ex = inner
209            .event_listener::<EventExceptionThrown>()
210            .await
211            .map_err(cdp)?;
212        let sink = console.clone();
213        pumps.push(tokio::spawn(async move {
214            while let Some(e) = ex.next().await {
215                let d = &e.exception_details;
216                let text = d
217                    .exception
218                    .as_ref()
219                    .and_then(|x| x.description.clone())
220                    .unwrap_or_else(|| d.text.clone());
221                push_capped(
222                    &sink,
223                    ConsoleLine {
224                        level: "exception".into(),
225                        text,
226                    },
227                )
228                .await;
229            }
230        }));
231        // Renderer crash -> `Crash` lifecycle event for this page.
232        let mut crashed = inner
233            .event_listener::<EventTargetCrashed>()
234            .await
235            .map_err(cdp)?;
236        let (g, page_id) = (guard.clone(), id.clone());
237        pumps.push(tokio::spawn(async move {
238            while crashed.next().await.is_some() {
239                g.emit_kind(LifecycleKind::Crash, "renderer crashed", |e| {
240                    e.page_id = Some(page_id.clone());
241                });
242            }
243        }));
244        inner
245            .execute(InspectorEnableParams::default())
246            .await
247            .map_err(cdp)?;
248        let blocked = Arc::new(StdMutex::new(Vec::new()));
249        let intercept = Arc::new(InterceptStats::default());
250        if !guard.network.unrestricted && !fixture_fetch_owner {
251            // Pause every request (document, redirect hops, subresources) and
252            // decide before it leaves the browser. Enabled before any navigation.
253            let mut paused = inner
254                .event_listener::<EventRequestPaused>()
255                .await
256                .map_err(cdp)?;
257            let page = inner.clone();
258            let g = guard.clone();
259            let sink = blocked.clone();
260            let page_id = id.clone();
261            let stats = intercept.clone();
262            pumps.push(tokio::spawn(async move {
263                use std::sync::atomic::Ordering::Relaxed;
264                while let Some(e) = paused.next().await {
265                    let stats = stats.clone();
266                    stats.paused.fetch_add(1, Relaxed);
267                    let page = page.clone();
268                    let g = g.clone();
269                    let sink = sink.clone();
270                    let pid = page_id.clone();
271                    tokio::spawn(async move {
272                        let kind = format!("{:?}", e.resource_type);
273                        match g.network.check(&e.request.url, &kind).await {
274                            Ok(()) => {
275                                match page
276                                    .execute(ContinueRequestParams::new(e.request_id.clone()))
277                                    .await
278                                {
279                                    Ok(_) => {
280                                        stats.continued.fetch_add(1, Relaxed);
281                                    }
282                                    Err(error) => {
283                                        stats.errors.fetch_add(1, Relaxed);
284                                        *stats.last_error.lock().unwrap() = Some(error.to_string());
285                                    }
286                                }
287                            }
288                            Err(reason) => {
289                                let _ = page
290                                    .execute(FailRequestParams::new(
291                                        e.request_id.clone(),
292                                        ErrorReason::BlockedByClient,
293                                    ))
294                                    .await;
295                                stats.refused.fetch_add(1, Relaxed);
296                                g.denied_network(Some(&pid), &kind, &reason);
297                                let mut b = sink.lock().unwrap();
298                                if b.len() < 500 {
299                                    b.push(BlockedRequest {
300                                        url: e.request.url.clone(),
301                                        reason: reason.to_string(),
302                                    });
303                                }
304                            }
305                        }
306                    });
307                }
308            }));
309            let en = FetchEnableParams {
310                patterns: Some(vec![RequestPattern {
311                    url_pattern: Some("*".into()),
312                    resource_type: None,
313                    request_stage: None,
314                }]),
315                ..Default::default()
316            };
317            inner.execute(en).await.map_err(cdp)?;
318        }
319        Ok(Self {
320            id,
321            inner,
322            console,
323            obs: StdMutex::new(ObsState::default()),
324            mouse: StdMutex::new((0.0, 0.0)),
325            buttons: StdMutex::new(0),
326            lane: Mutex::new(()),
327            upload_root,
328            pumps: StdMutex::new(pumps),
329            guard,
330            blocked,
331            intercept,
332        })
333    }
334
335    pub fn id(&self) -> &str {
336        &self.id
337    }
338
339    /// Requests the network policy refused on this page (redirect hops and subresources included).
340    pub fn blocked_requests(&self) -> Vec<BlockedRequest> {
341        self.blocked.lock().unwrap().clone()
342    }
343
344    /// Typed pre-effect admission. Reads no page state beyond the current URL.
345    async fn admit(
346        &self,
347        action: ActionKind,
348        url: Option<String>,
349        target: Option<String>,
350        detail: Option<String>,
351    ) -> Result<()> {
352        let url = match url {
353            Some(u) => Some(u),
354            None if self.guard.admission.is_some() => Some(self.url().await),
355            None => None,
356        };
357        self.guard
358            .admit(AdmissionRequest {
359                session_id: self.guard.session_id.clone(),
360                page_id: self.id.clone(),
361                action,
362                url,
363                target,
364                detail,
365            })
366            .await
367    }
368
369    /// Escape hatch to the underlying chromiumoxide page.
370    pub fn raw(&self) -> &Page {
371        &self.inner
372    }
373
374    pub(crate) fn abort_pumps(&self) {
375        if let Ok(mut p) = self.pumps.lock() {
376            for h in p.drain(..) {
377                h.abort();
378            }
379        }
380    }
381
382    pub(crate) async fn close_inner(&self) -> Result<()> {
383        self.abort_pumps();
384        self.inner.clone().close().await.map_err(cdp)
385    }
386
387    pub async fn bring_to_front(&self) -> Result<()> {
388        self.inner.bring_to_front().await.map_err(cdp)?;
389        Ok(())
390    }
391
392    // ---- navigation ------------------------------------------------------
393
394    fn invalidate(&self) {
395        let mut o = self.obs.lock().unwrap();
396        o.epoch += 1;
397        o.refs.clear();
398        o.fingerprint.clear();
399    }
400
401    /// Waits until this new tab's own first navigation (to about:blank) has committed.
402    ///
403    /// A tab is created at about:blank and that navigation commits a little later. A
404    /// navigation sent before then is discarded by that commit: Chrome answers it with
405    /// `net::ERR_ABORTED` and no load ever follows, so the caller waits out its whole request
406    /// timeout. Seen on Windows, where a new tab's renderer starts more slowly.
407    ///
408    /// Before the commit the tab's committed history entry has an empty URL. The tab counts
409    /// as settled when that entry has a URL and the main frame's loader is the same on two
410    /// consecutive polls. Bounded at two seconds, and it stops at once if Chrome does not
411    /// answer, so a browser that behaves differently is not waited on.
412    pub(crate) async fn settle_initial_document(&self) {
413        use chromiumoxide::cdp::browser_protocol::page::{
414            GetFrameTreeParams, GetNavigationHistoryParams,
415        };
416        use std::time::{Duration, Instant};
417        let deadline = Instant::now() + Duration::from_secs(2);
418        let mut seen: Option<String> = None;
419        while Instant::now() < deadline {
420            let Ok(history) = self
421                .inner
422                .execute(GetNavigationHistoryParams::default())
423                .await
424            else {
425                return;
426            };
427            let Ok(tree) = self.inner.execute(GetFrameTreeParams::default()).await else {
428                return;
429            };
430            let committed = usize::try_from(history.result.current_index)
431                .ok()
432                .and_then(|index| history.result.entries.get(index))
433                .is_some_and(|entry| !entry.url.is_empty());
434            let loader = format!("{:?}", tree.result.frame_tree.frame.loader_id);
435            if !committed {
436                seen = None;
437            } else if seen.as_deref() == Some(loader.as_str()) {
438                return;
439            } else {
440                seen = Some(loader);
441            }
442            tokio::time::sleep(Duration::from_millis(10)).await;
443        }
444    }
445
446    pub async fn goto(&self, url: &str) -> Result<()> {
447        // EFF-001 order: policy, then approval; both before any side effect.
448        self.guard
449            .check_url(Some(&self.id), url, "Navigation")
450            .await?;
451        self.admit(ActionKind::Navigate, Some(url.to_string()), None, None)
452            .await?;
453        let _l = self.lane.lock().await;
454        self.inner.goto(url).await.map_err(|e| {
455            BrowserError::Cdp(format!(
456                "navigate '{url}': {e} ({})",
457                self.intercept.summary()
458            ))
459        })?;
460        self.inner.wait_for_navigation().await.map_err(cdp)?;
461        self.invalidate();
462        Ok(())
463    }
464
465    pub async fn reload(&self) -> Result<()> {
466        self.admit(ActionKind::Reload, None, None, None).await?;
467        let _l = self.lane.lock().await;
468        self.inner.reload().await.map_err(cdp)?;
469        self.inner.wait_for_navigation().await.map_err(cdp)?;
470        self.invalidate();
471        Ok(())
472    }
473
474    pub async fn history(&self, delta: i32) -> Result<()> {
475        self.admit(
476            ActionKind::History,
477            None,
478            None,
479            Some(format!("delta={delta}")),
480        )
481        .await?;
482        let _l = self.lane.lock().await;
483        self.inner
484            .evaluate(format!("history.go({delta})"))
485            .await
486            .map_err(cdp)?;
487        tokio::time::sleep(Duration::from_millis(150)).await;
488        self.inner.wait_for_navigation().await.map_err(cdp)?;
489        self.invalidate();
490        Ok(())
491    }
492
493    pub async fn url(&self) -> String {
494        self.inner.url().await.ok().flatten().unwrap_or_default()
495    }
496
497    pub async fn title(&self) -> String {
498        self.inner
499            .get_title()
500            .await
501            .ok()
502            .flatten()
503            .unwrap_or_default()
504    }
505
506    /// Rendered text (`document.body.innerText`).
507    pub async fn text(&self) -> Result<String> {
508        self.eval_internal("document.body ? document.body.innerText : ''")
509            .await
510            .map(|v| v.as_str().unwrap_or_default().to_string())
511    }
512
513    /// Evaluate a JS expression and return its JSON value. Script can navigate and
514    /// act, so it is admitted like any other effect.
515    pub async fn eval(&self, expr: &str) -> Result<Value> {
516        self.admit(
517            ActionKind::Eval,
518            None,
519            None,
520            Some(expr.chars().take(2000).collect()),
521        )
522        .await?;
523        self.eval_internal(expr).await
524    }
525
526    /// Runtime-owned evaluation (observation, geometry); never user script.
527    async fn eval_internal(&self, expr: &str) -> Result<Value> {
528        let r = self.inner.evaluate(expr).await.map_err(cdp)?;
529        Ok(r.value().cloned().unwrap_or(Value::Null))
530    }
531
532    pub async fn set_viewport(&self, width: u32, height: u32, scale: f64) -> Result<()> {
533        use chromiumoxide::cdp::browser_protocol::emulation::SetDeviceMetricsOverrideParams;
534        self.inner
535            .execute(SetDeviceMetricsOverrideParams::new(
536                i64::from(width),
537                i64::from(height),
538                scale,
539                false,
540            ))
541            .await
542            .map_err(cdp)?;
543        Ok(())
544    }
545
546    // ---- observation -----------------------------------------------------
547
548    pub async fn observe(&self) -> Result<Observation> {
549        let _l = self.lane.lock().await;
550        let raw: Vec<RawNode> = self
551            .inner
552            .evaluate(OBSERVE_JS)
553            .await
554            .map_err(cdp)?
555            .into_value()
556            .map_err(|e| BrowserError::Cdp(format!("decode observation: {e}")))?;
557        let viewport: Rect = self
558            .inner
559            .evaluate("({x:0,y:0,width:window.innerWidth,height:window.innerHeight})")
560            .await
561            .map_err(cdp)?
562            .into_value()
563            .map_err(cdp)?;
564        let fingerprint = raw
565            .iter()
566            .map(|n| {
567                format!(
568                    "{}|{}|{}|{}|{}",
569                    n.selector, n.role, n.name, n.visible, n.disabled
570                )
571            })
572            .collect::<Vec<_>>()
573            .join("\n");
574        let (epoch, nodes, added, removed) = {
575            let mut o = self.obs.lock().unwrap();
576            if o.fingerprint != fingerprint {
577                o.epoch += 1;
578                o.fingerprint = fingerprint;
579            }
580            let epoch = o.epoch;
581            o.refs.clear();
582            let mut cur = HashMap::new();
583            let mut nodes = Vec::new();
584            for (i, n) in raw.into_iter().enumerate() {
585                let name = if n.sensitive {
586                    "••••••••".to_string()
587                } else {
588                    n.name.clone()
589                };
590                let node_ref = format!("r{epoch}.{}", i + 1);
591                if !n.selector.is_empty() {
592                    o.refs.insert(
593                        node_ref.clone(),
594                        RefEntry {
595                            selector: n.selector.clone(),
596                            tag: n.tag.clone(),
597                            role: n.role.clone(),
598                            name: name.clone(),
599                        },
600                    );
601                    cur.insert(n.selector.clone(), format!("{}|{}", n.role, name));
602                }
603                nodes.push(ObservedNode {
604                    node_ref,
605                    role: n.role,
606                    name,
607                    tag: n.tag,
608                    selector: n.selector,
609                    visible: n.visible,
610                    disabled: n.disabled,
611                    bounds: n.bounds,
612                });
613            }
614            let added = cur
615                .keys()
616                .filter(|k| !o.previous.contains_key(*k))
617                .cloned()
618                .collect();
619            let removed = o
620                .previous
621                .keys()
622                .filter(|k| !cur.contains_key(*k))
623                .cloned()
624                .collect();
625            o.previous = cur;
626            (epoch, nodes, added, removed)
627        };
628        let console_errors = self
629            .console
630            .lock()
631            .await
632            .iter()
633            .filter(|l| matches!(l.level.as_str(), "error" | "exception"))
634            .count();
635        Ok(Observation {
636            page_id: self.id.clone(),
637            epoch,
638            url: self.url().await,
639            title: self.title().await,
640            viewport,
641            nodes,
642            console_errors,
643            added,
644            removed,
645        })
646    }
647
648    /// Resolve a target to a unique CSS selector, rejecting stale refs.
649    async fn resolve(&self, target: &Target) -> Result<Option<String>> {
650        match target {
651            Target::Point(..) => Ok(None),
652            Target::Selector(s) => {
653                self.unique(s).await?;
654                Ok(Some(s.clone()))
655            }
656            Target::Ref(r) => {
657                let (entry, current_epoch) = {
658                    let o = self.obs.lock().unwrap();
659                    (o.refs.get(r).cloned(), o.epoch)
660                };
661                let entry = entry.ok_or_else(|| BrowserError::StaleRef(r.clone()))?;
662                let ref_epoch: u64 = r
663                    .trim_start_matches('r')
664                    .split('.')
665                    .next()
666                    .and_then(|e| e.parse().ok())
667                    .unwrap_or(0);
668                if ref_epoch != current_epoch {
669                    return Err(BrowserError::StaleRef(r.clone()));
670                }
671                // Identity check: the element behind the selector must still look
672                // like what was observed, else the page changed under the ref.
673                let sig = self
674                    .eval(&format!(
675                        "(()=>{{const l=document.querySelectorAll({s});if(l.length!==1)return null;const e=l[0];\
676                         return {{tag:e.tagName.toLowerCase(),name:(e.getAttribute('aria-label')||e.innerText||e.value||e.getAttribute('placeholder')||'').trim().slice(0,160)}}}})()",
677                        s = js(&entry.selector)
678                    ))
679                    .await?;
680                let ok = sig.get("tag").and_then(Value::as_str) == Some(entry.tag.as_str())
681                    && sig.get("name").and_then(Value::as_str) == Some(entry.name.as_str())
682                    || (sig.get("tag").and_then(Value::as_str) == Some(entry.tag.as_str())
683                        && matches!(entry.tag.as_str(), "input" | "textarea" | "select")); // value changes as the user types
684                if !ok {
685                    return Err(BrowserError::StaleRef(r.clone()));
686                }
687                let _ = &entry.role;
688                Ok(Some(entry.selector))
689            }
690        }
691    }
692
693    async fn unique(&self, selector: &str) -> Result<()> {
694        let n = self
695            .eval_internal(&format!(
696                "document.querySelectorAll({}).length",
697                js(selector)
698            ))
699            .await?
700            .as_u64()
701            .unwrap_or(0);
702        match n {
703            1 => Ok(()),
704            0 => Err(BrowserError::NoElement(selector.into())),
705            n => Err(BrowserError::Ambiguous(selector.into(), n)),
706        }
707    }
708
709    /// Scroll into view, return the centre point, and verify nothing covers it.
710    async fn point_of(&self, target: &Target) -> Result<(f64, f64)> {
711        if let Target::Point(x, y) = target {
712            return Ok((*x, *y));
713        }
714        let sel = self.resolve(target).await?.expect("selector");
715        let v = self
716            .eval(&format!(
717                "(()=>{{const e=document.querySelector({s});e.scrollIntoView({{block:'center',inline:'center'}});\
718                 const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return null;\
719                 const x=r.x+r.width/2,y=r.y+r.height/2;const t=document.elementFromPoint(x,y);\
720                 const hit=!!t&&(t===e||e.contains(t)||t.contains(e));return {{x,y,hit}}}})()",
721                s = js(&sel)
722            ))
723            .await?;
724        if v.is_null() {
725            return Err(BrowserError::NotInteractable(sel));
726        }
727        if v.get("hit").and_then(Value::as_bool) != Some(true) {
728            return Err(BrowserError::NotInteractable(format!(
729                "{sel} (covered by another element)"
730            )));
731        }
732        Ok((
733            v["x"].as_f64().unwrap_or(0.0),
734            v["y"].as_f64().unwrap_or(0.0),
735        ))
736    }
737
738    // ---- real pointer input ----------------------------------------------
739
740    async fn mouse_event(
741        &self,
742        kind: DispatchMouseEventType,
743        x: f64,
744        y: f64,
745        button: MouseButton,
746        click_count: i64,
747    ) -> Result<()> {
748        let mut p = DispatchMouseEventParams::new(kind.clone(), x, y);
749        p.button = Some(button);
750        p.click_count = Some(click_count);
751        p.buttons = Some(match kind {
752            DispatchMouseEventType::MousePressed => 1,
753            DispatchMouseEventType::MouseReleased => 0,
754            _ => *self.buttons.lock().unwrap(),
755        });
756        self.inner.execute(p).await.map_err(cdp)?;
757        *self.mouse.lock().unwrap() = (x, y);
758        Ok(())
759    }
760
761    async fn move_to(&self, x: f64, y: f64) -> Result<()> {
762        self.mouse_event(
763            DispatchMouseEventType::MouseMoved,
764            x,
765            y,
766            MouseButton::None,
767            0,
768        )
769        .await
770    }
771
772    pub async fn hover(&self, target: &Target) -> Result<()> {
773        self.admit(ActionKind::Hover, None, Some(describe(target)), None)
774            .await?;
775        let _l = self.lane.lock().await;
776        let (x, y) = self.point_of(target).await?;
777        self.move_to(x, y).await
778    }
779
780    pub async fn click(&self, target: &Target) -> Result<()> {
781        self.admit(ActionKind::Click, None, Some(describe(target)), None)
782            .await?;
783        let _l = self.lane.lock().await;
784        self.click_n(target, 1).await
785    }
786
787    pub async fn double_click(&self, target: &Target) -> Result<()> {
788        self.admit(ActionKind::DoubleClick, None, Some(describe(target)), None)
789            .await?;
790        let _l = self.lane.lock().await;
791        self.click_n(target, 2).await
792    }
793
794    /// Caller holds the lane.
795    async fn click_n(&self, target: &Target, count: i64) -> Result<()> {
796        let (x, y) = self.point_of(target).await?;
797        self.move_to(x, y).await?;
798        for n in 1..=count {
799            self.mouse_event(
800                DispatchMouseEventType::MousePressed,
801                x,
802                y,
803                MouseButton::Left,
804                n,
805            )
806            .await?;
807            self.mouse_event(
808                DispatchMouseEventType::MouseReleased,
809                x,
810                y,
811                MouseButton::Left,
812                n,
813            )
814            .await?;
815        }
816        Ok(())
817    }
818
819    /// Press at `from`, move in `steps` increments, release at `to`.
820    pub async fn drag(&self, from: &Target, to: &Target, steps: u32) -> Result<()> {
821        self.admit(
822            ActionKind::Drag,
823            None,
824            Some(format!("{} -> {}", describe(from), describe(to))),
825            None,
826        )
827        .await?;
828        let _l = self.lane.lock().await;
829        let (x0, y0) = self.point_of(from).await?;
830        let (x1, y1) = self.point_of(to).await?;
831        self.move_to(x0, y0).await?;
832        self.mouse_event(
833            DispatchMouseEventType::MousePressed,
834            x0,
835            y0,
836            MouseButton::Left,
837            1,
838        )
839        .await?;
840        *self.buttons.lock().unwrap() = 1;
841        let steps = steps.max(1);
842        for i in 1..=steps {
843            let t = f64::from(i) / f64::from(steps);
844            self.mouse_event(
845                DispatchMouseEventType::MouseMoved,
846                x0 + (x1 - x0) * t,
847                y0 + (y1 - y0) * t,
848                MouseButton::Left,
849                0,
850            )
851            .await?;
852        }
853        *self.buttons.lock().unwrap() = 0;
854        self.mouse_event(
855            DispatchMouseEventType::MouseReleased,
856            x1,
857            y1,
858            MouseButton::Left,
859            1,
860        )
861        .await
862    }
863
864    /// Mouse-wheel scroll at the target (or viewport centre when `None`).
865    pub async fn wheel(&self, at: Option<&Target>, dx: f64, dy: f64) -> Result<()> {
866        self.admit(
867            ActionKind::Wheel,
868            None,
869            at.map(describe),
870            Some(format!("dx={dx} dy={dy}")),
871        )
872        .await?;
873        let _l = self.lane.lock().await;
874        let (x, y) = match at {
875            Some(t) => self.point_of(t).await?,
876            None => {
877                let v = self
878                    .eval_internal("({x:innerWidth/2,y:innerHeight/2})")
879                    .await?;
880                (
881                    v["x"].as_f64().unwrap_or(100.0),
882                    v["y"].as_f64().unwrap_or(100.0),
883                )
884            }
885        };
886        let mut p = DispatchMouseEventParams::new(DispatchMouseEventType::MouseWheel, x, y);
887        p.delta_x = Some(dx);
888        p.delta_y = Some(dy);
889        self.inner.execute(p).await.map_err(cdp)?;
890        Ok(())
891    }
892
893    // ---- real keyboard input ---------------------------------------------
894
895    async fn key_event(
896        &self,
897        kind: DispatchKeyEventType,
898        d: &KeyDef,
899        mods: i64,
900        with_text: bool,
901    ) -> Result<()> {
902        let mut p = DispatchKeyEventParams::new(kind);
903        p.modifiers = Some(mods);
904        p.key = Some(d.key.clone());
905        if !d.code.is_empty() {
906            p.code = Some(d.code.clone());
907        }
908        p.windows_virtual_key_code = Some(d.vk);
909        p.native_virtual_key_code = Some(d.vk);
910        if with_text {
911            p.text = d.text.clone();
912            p.unmodified_text = d.text.clone();
913        }
914        self.inner.execute(p).await.map_err(cdp)?;
915        Ok(())
916    }
917
918    async fn press_locked(&self, spec: &str) -> Result<()> {
919        let (mods, mod_keys, def) = keys::parse_chord(spec)?;
920        for (_, m) in &mod_keys {
921            self.key_event(DispatchKeyEventType::RawKeyDown, m, mods, false)
922                .await?;
923        }
924        // Shortcut chords (Ctrl/Meta/Alt) carry no text.
925        let text = mods & (keys::CTRL | keys::META | keys::ALT) == 0;
926        let kind = if text && def.text.is_some() {
927            DispatchKeyEventType::KeyDown
928        } else {
929            DispatchKeyEventType::RawKeyDown
930        };
931        self.key_event(kind, &def, mods, text).await?;
932        self.key_event(DispatchKeyEventType::KeyUp, &def, mods, false)
933            .await?;
934        for (_, m) in mod_keys.iter().rev() {
935            self.key_event(DispatchKeyEventType::KeyUp, m, 0, false)
936                .await?;
937        }
938        Ok(())
939    }
940
941    /// Press a key or chord (`Enter`, `Tab`, `Control+a`) on the focused element.
942    pub async fn press(&self, spec: &str) -> Result<()> {
943        self.admit(ActionKind::Press, None, Some(spec.to_string()), None)
944            .await?;
945        let _l = self.lane.lock().await;
946        self.press_locked(spec).await
947    }
948
949    /// Type text one key event at a time into the focused element.
950    pub async fn type_text(&self, text: &str) -> Result<()> {
951        self.admit(
952            ActionKind::TypeText,
953            None,
954            None,
955            Some(format!("chars={}", text.chars().count())),
956        )
957        .await?;
958        let _l = self.lane.lock().await;
959        self.type_locked(text).await
960    }
961
962    async fn type_locked(&self, text: &str) -> Result<()> {
963        for c in text.chars() {
964            let d = keys::char_key(c);
965            self.key_event(DispatchKeyEventType::KeyDown, &d, 0, true)
966                .await?;
967            self.key_event(DispatchKeyEventType::KeyUp, &d, 0, false)
968                .await?;
969        }
970        Ok(())
971    }
972
973    /// Click the target to focus it, then type.
974    pub async fn fill(&self, target: &Target, text: &str, clear: bool) -> Result<()> {
975        self.admit(
976            ActionKind::Fill,
977            None,
978            Some(describe(target)),
979            Some(format!("chars={} clear={clear}", text.chars().count())),
980        )
981        .await?;
982        let _l = self.lane.lock().await;
983        self.click_n(target, 1).await?;
984        if clear {
985            let sel_all = if cfg!(target_os = "macos") {
986                "Meta+a"
987            } else {
988                "Control+a"
989            };
990            self.press_locked(sel_all).await?;
991            self.press_locked("Backspace").await?;
992        }
993        self.type_locked(text).await
994    }
995
996    // ---- other actions -----------------------------------------------------
997
998    /// Choose a `<select>` option by value/label. Native popups cannot be driven
999    /// over CDP, so this sets the value and fires `input`/`change` (documented gap).
1000    pub async fn select_option(&self, target: &Target, value: &str) -> Result<()> {
1001        self.admit(
1002            ActionKind::Select,
1003            None,
1004            Some(describe(target)),
1005            Some(format!("value={value}")),
1006        )
1007        .await?;
1008        let _l = self.lane.lock().await;
1009        let sel = self
1010            .resolve(target)
1011            .await?
1012            .ok_or_else(|| BrowserError::Invalid("select needs an element".into()))?;
1013        let r = self
1014            .eval(&format!(
1015                "(()=>{{const e=document.querySelector({s});const w={v};\
1016                 const o=[...e.options].find(o=>o.value===w||o.label===w||o.text.trim()===w);if(!o)return 'nooption';\
1017                 e.value=o.value;e.dispatchEvent(new Event('input',{{bubbles:true}}));e.dispatchEvent(new Event('change',{{bubbles:true}}));return 'ok'}})()",
1018                s = js(&sel),
1019                v = js(value)
1020            ))
1021            .await?;
1022        if r.as_str() == Some("ok") {
1023            Ok(())
1024        } else {
1025            Err(BrowserError::Invalid(format!(
1026                "'{sel}' has no option '{value}'"
1027            )))
1028        }
1029    }
1030
1031    pub async fn upload(&self, target: &Target, file: &Path) -> Result<()> {
1032        self.admit(
1033            ActionKind::Upload,
1034            None,
1035            Some(describe(target)),
1036            Some(file.display().to_string()),
1037        )
1038        .await?;
1039        let _l = self.lane.lock().await;
1040        let file = file.canonicalize()?;
1041        if !file.is_file() {
1042            return Err(BrowserError::Invalid(
1043                "upload must be a regular file".into(),
1044            ));
1045        }
1046        if let Some(root) = &self.upload_root {
1047            if !file.starts_with(root.canonicalize()?) {
1048                return Err(BrowserError::Invalid(
1049                    "upload outside the configured upload root".into(),
1050                ));
1051            }
1052        }
1053        if std::fs::metadata(&file)?.len() > MAX_UPLOAD_BYTES {
1054            return Err(BrowserError::Invalid("upload exceeds 64 MiB".into()));
1055        }
1056        let sel = self
1057            .resolve(target)
1058            .await?
1059            .ok_or_else(|| BrowserError::Invalid("upload needs an element".into()))?;
1060        let el = self
1061            .inner
1062            .find_element(sel.as_str())
1063            .await
1064            .map_err(|_| BrowserError::NoElement(sel.clone()))?;
1065        let node = el.description().await.map_err(cdp)?;
1066        self.inner
1067            .execute(
1068                SetFileInputFilesParams::builder()
1069                    .file(file.to_string_lossy().to_string())
1070                    .backend_node_id(node.backend_node_id)
1071                    .build()
1072                    .map_err(BrowserError::Invalid)?,
1073            )
1074            .await
1075            .map_err(cdp)?;
1076        Ok(())
1077    }
1078
1079    pub async fn wait_for(&self, selector: &str, timeout: Duration) -> Result<()> {
1080        self.wait_eval(
1081            &format!("!!document.querySelector({})", js(selector)),
1082            timeout,
1083        )
1084        .await
1085    }
1086
1087    /// Poll a JS expression until truthy.
1088    pub async fn wait_eval(&self, expr: &str, timeout: Duration) -> Result<()> {
1089        self.admit(
1090            ActionKind::Eval,
1091            None,
1092            None,
1093            Some(expr.chars().take(2000).collect()),
1094        )
1095        .await?;
1096        let deadline = Instant::now() + timeout;
1097        loop {
1098            let v = self.eval_internal(expr).await?;
1099            if v.as_bool()
1100                .unwrap_or(!v.is_null() && v != Value::Bool(false))
1101            {
1102                return Ok(());
1103            }
1104            if Instant::now() >= deadline {
1105                return Err(BrowserError::Timeout(expr.to_string()));
1106            }
1107            tokio::time::sleep(Duration::from_millis(50)).await;
1108        }
1109    }
1110
1111    pub async fn screenshot(&self) -> Result<Vec<u8>> {
1112        self.inner
1113            .screenshot(
1114                ScreenshotParams::builder()
1115                    .format(CaptureScreenshotFormat::Png)
1116                    .build(),
1117            )
1118            .await
1119            .map_err(cdp)
1120    }
1121
1122    pub async fn screenshot_to(&self, path: &Path) -> Result<()> {
1123        std::fs::write(path, self.screenshot().await?)?;
1124        Ok(())
1125    }
1126
1127    pub async fn console(&self) -> Vec<ConsoleLine> {
1128        self.console.lock().await.clone()
1129    }
1130
1131    pub async fn clear_console(&self) {
1132        self.console.lock().await.clear();
1133    }
1134}
1135
1136async fn push_capped(sink: &Arc<Mutex<Vec<ConsoleLine>>>, line: ConsoleLine) {
1137    let mut g = sink.lock().await;
1138    if g.len() >= MAX_CONSOLE_LINES {
1139        g.remove(0);
1140    }
1141    g.push(line);
1142}
1143
1144fn describe(t: &Target) -> String {
1145    match t {
1146        Target::Ref(r) => format!("ref:{r}"),
1147        Target::Selector(s) => format!("css:{s}"),
1148        Target::Point(x, y) => format!("point:{x},{y}"),
1149    }
1150}
1151
1152fn js(s: &str) -> String {
1153    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into())
1154}
1155
1156const OBSERVE_JS: &str = r#"(() => {
1157  const esc = globalThis.CSS?.escape || (v => String(v).replace(/[^a-zA-Z0-9_-]/g, '\\$&'));
1158  const unique = c => { if (!c) return null; try { return document.querySelectorAll(c).length === 1 ? c : null; } catch (_) { return null; } };
1159  const selectorFor = el => {
1160    if (el.id) { const s = unique('#' + esc(el.id)); if (s) return s; }
1161    for (const a of ['data-testid', 'name', 'aria-label']) {
1162      const v = el.getAttribute(a);
1163      if (v) { const s = unique(el.tagName.toLowerCase() + '[' + a + '="' + esc(v) + '"]'); if (s) return s; }
1164    }
1165    const parts = [];
1166    for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
1167      let p = n.tagName.toLowerCase();
1168      const sib = n.parentElement ? [...n.parentElement.children].filter(x => x.tagName === n.tagName) : [];
1169      if (sib.length > 1) p += ':nth-of-type(' + (sib.indexOf(n) + 1) + ')';
1170      parts.unshift(p);
1171      const c = parts.join(' > ');
1172      if (unique(c)) return c;
1173    }
1174    return '';
1175  };
1176  const sel = 'a[href],button,input,select,textarea,[role],[tabindex],[contenteditable="true"],[onclick]';
1177  return [...document.querySelectorAll(sel)].slice(0, 300).map(el => {
1178    const r = el.getBoundingClientRect();
1179    const ac = (el.getAttribute('autocomplete') || '').trim().toLowerCase();
1180    const sensitive = (el instanceof HTMLInputElement && el.type.toLowerCase() === 'password') || ac === 'current-password' || ac === 'new-password';
1181    const visible = (() => {
1182      for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
1183        const s = getComputedStyle(n);
1184        if (n.hidden || n.getAttribute('aria-hidden') === 'true' || s.visibility === 'hidden' || s.display === 'none' || s.opacity === '0') return false;
1185      }
1186      return r.width > 0 && r.height > 0;
1187    })();
1188    return {
1189      role: el.getAttribute('role') || ({A:'link',BUTTON:'button',INPUT:'textbox',SELECT:'combobox',TEXTAREA:'textbox'}[el.tagName] || el.tagName.toLowerCase()),
1190      name: (el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('placeholder') || '').trim().slice(0, 160),
1191      tag: el.tagName.toLowerCase(), selector: selectorFor(el), visible,
1192      disabled: !!el.disabled || el.getAttribute('aria-disabled') === 'true', sensitive,
1193      bounds: {x: r.x, y: r.y, width: r.width, height: r.height}
1194    };
1195  });
1196})()"#;