zendriver 0.1.3

Async-first, undetectable browser automation via the Chrome DevTools Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
//! [`Element`] actions: `click` / `hover` / `focus` / `scroll_into_view` /
//! `set_value` / `clear` / `upload_files`.
//!
//! Each action wraps its CDP dispatch sequence in an internal "refresh on
//! stale" wrapper so a stale handle (post-navigation, post-React-rerender)
//! transparently re-resolves once and retries.
//!
//! `hover` / `hover_fast`:
//!   1. `scroll_into_view` — bring the element into the viewport so its
//!      bbox center is a real, dispatchable coordinate.
//!   2. Actionability gate (`visible + stable + receives_pointer`) — avoids
//!      mid-transition hover races and overlay occlusion. Pointer events
//!      are dispatched at the geometric center, so the element must be the
//!      actual hit-test target there. `enabled` is left off — hover doesn't
//!      activate the element, so disabled controls still accept mouseover.
//!   3. Compute bbox center (`x + width / 2`, `y + height / 2`).
//!   4. Dispatch the mouse-move via the shared [`crate::input::InputController`].
//!      `hover` uses a realistic Bezier path; `hover_fast` uses a single
//!      teleport dispatch for test/automation paths.
//!
//! `focus`: actionability gate (visible + enabled — no pointer or stability
//! requirement; focus routes through the focused element, not the cursor's
//! position), then `el.focus()` in the main world.
//!
//! `scroll_into_view`: no actionability gate (this *is* the visibility
//! prereq other actions wait for). Calls `el.scrollIntoView({ block:
//! 'center', behavior: 'instant' })`. `block: 'center'` matches Playwright
//! (avoids sticky headers/footers obscuring the element after the scroll);
//! `behavior: 'instant'` skips animation so the post-scroll bbox is final
//! by the time the next CDP call runs.

use std::path::Path;
use std::time::Duration;

use serde_json::json;

use crate::element::Element;
use crate::error::{Result, ZendriverError};
use crate::input::keyboard::KeyModifiers;
use crate::input::mouse::{self, MouseButton};
use crate::query::actionability::{self, ActionabilityCheck};

/// Default deadline for the actionability gate before each action. Matches
/// the value the spec calls out for P3; per-call override land in P4 when
/// the per-action options structs grow.
const DEFAULT_ACTIONABILITY_TIMEOUT: Duration = Duration::from_secs(5);

/// Per-call knobs for [`Element::click_with`].
///
/// `Default` matches the behavior of [`Element::click`]: a left, single,
/// realistic click at the element's bbox center with no modifiers held and
/// full actionability gating. Override fields individually for richer
/// dispatches (right-click, modifier-held click, raw teleport, etc.).
///
/// # Examples
///
/// ```no_run
/// # async fn ex() -> zendriver::Result<()> {
/// use zendriver::{ClickOptions, MouseButton};
/// # let browser = zendriver::Browser::builder().launch().await?;
/// # let tab = browser.main_tab();
/// let el = tab.find().css("button").one().await?;
/// el.click_with(ClickOptions {
///     button: MouseButton::Right,
///     click_count: 2,
///     ..Default::default()
/// }).await?;
/// # Ok(()) }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ClickOptions {
    /// Which mouse button to dispatch. [`MouseButton::Left`] by default.
    pub button: MouseButton,
    /// Modifier keys held during the dispatch. Empty by default.
    pub modifiers: KeyModifiers,
    /// `clickCount` for the CDP dispatch. `1` by default; set `2` for a
    /// double-click in a single `click_with` call.
    pub click_count: u32,
    /// Skip the actionability gate when true. Use sparingly — bypasses the
    /// visibility/stability/pointer checks. Mirrors Playwright's
    /// `force: true`.
    pub force: bool,
    /// Bezier-interpolated cursor path (`true`) vs single teleport
    /// dispatch (`false`). `true` by default; the `click_fast` shortcut
    /// flips this for deterministic test paths.
    pub realistic: bool,
    /// Click position relative to the element's bbox top-left
    /// (`(dx, dy)`). `None` clicks at the bbox center.
    pub position: Option<(f64, f64)>,
}

impl Default for ClickOptions {
    fn default() -> Self {
        Self {
            button: MouseButton::Left,
            modifiers: KeyModifiers::empty(),
            click_count: 1,
            force: false,
            realistic: true,
            position: None,
        }
    }
}

impl Element {
    /// Click this element with realistic defaults.
    ///
    /// Left button, single click, Bezier-path cursor approach, and the full
    /// actionability gate. Equivalent to
    /// `click_with(ClickOptions::default())`. For right-click / modifier-held
    /// / double-click / raw-teleport variations, use [`Element::click_with`].
    ///
    /// # Errors
    ///
    /// Returns [`ZendriverError::NotActionable`] when the actionability gate
    /// times out, [`ZendriverError::ElementStale`] when the handle can't be
    /// refreshed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let btn = tab.find().css("button#submit").one().await?;
    /// btn.click().await?;
    /// # Ok(()) }
    /// ```
    pub async fn click(&self) -> Result<()> {
        self.click_with(ClickOptions::default()).await
    }

    /// Click this element with a deterministic raw teleport.
    ///
    /// Skips the Bezier interpolation [`Element::click`] uses and bypasses
    /// the actionability gate. Equivalent to
    /// `click_with(ClickOptions { realistic: false, force: true, ..Default::default() })`.
    /// Intended for test paths and fast automation flows where realism
    /// and per-action gating get in the way.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let btn = tab.find().css("button").one().await?;
    /// btn.click_fast().await?;
    /// # Ok(()) }
    /// ```
    pub async fn click_fast(&self) -> Result<()> {
        self.click_with(ClickOptions {
            realistic: false,
            force: true,
            ..Default::default()
        })
        .await
    }

    /// Click this element with explicit [`ClickOptions`].
    ///
    /// See module docs for the dispatch sequence — same shape as `hover`
    /// (scroll → gate → bbox math → pointer dispatch) but emits the
    /// `mousePressed` + `mouseReleased` pair after the cursor arrives.
    /// `opts.force` skips the actionability gate; `opts.position` shifts
    /// the click point off bbox-center.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use zendriver::{ClickOptions, MouseButton};
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let row = tab.find().css("tr.contact").one().await?;
    /// row.click_with(ClickOptions {
    ///     button: MouseButton::Right,
    ///     ..Default::default()
    /// }).await?;
    /// # Ok(()) }
    /// ```
    pub async fn click_with(&self, opts: ClickOptions) -> Result<()> {
        self.with_refresh(|| async move {
            self.scroll_into_view().await?;
            if !opts.force {
                actionability::wait_actionable(
                    self,
                    ActionabilityCheck::FULL,
                    DEFAULT_ACTIONABILITY_TIMEOUT,
                )
                .await?;
            }
            let bbox = self
                .bounding_box()
                .await?
                .ok_or_else(|| ZendriverError::Navigation("element has no bounding box".into()))?;
            let (tx, ty) = match opts.position {
                Some((dx, dy)) => (bbox.x + dx, bbox.y + dy),
                None => (bbox.x + bbox.width / 2.0, bbox.y + bbox.height / 2.0),
            };
            let input = self.inner.tab.input().clone();
            mouse::click_at(
                &input,
                &self.inner.tab,
                tx,
                ty,
                opts.button,
                opts.click_count,
                opts.realistic,
            )
            .await
        })
        .await
    }

    /// Hover the cursor over this element's bbox center.
    ///
    /// Uses a realistic Bezier-interpolated mouse path. See module docs for
    /// the full sequence (`scroll_into_view` → actionability gate → bbox
    /// center → dispatch). Use [`Element::hover_fast`] when the cursor path
    /// doesn't matter.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let nav = tab.find().css("nav.dropdown").one().await?;
    /// nav.hover().await?;
    /// # Ok(()) }
    /// ```
    pub async fn hover(&self) -> Result<()> {
        self.with_refresh(|| async move {
            self.scroll_into_view().await?;
            actionability::wait_actionable(
                self,
                ActionabilityCheck {
                    visible: true,
                    stable: true,
                    enabled: false,
                    receives_pointer: true,
                },
                DEFAULT_ACTIONABILITY_TIMEOUT,
            )
            .await?;
            let bbox = self
                .bounding_box()
                .await?
                .ok_or_else(|| ZendriverError::Navigation("element has no bounding box".into()))?;
            let cx = bbox.x + bbox.width / 2.0;
            let cy = bbox.y + bbox.height / 2.0;
            let input = self.inner.tab.input().clone();
            mouse::move_realistic(&input, &self.inner.tab, cx, cy).await
        })
        .await
    }

    /// Hover the cursor over this element's bbox center via a single
    /// teleport.
    ///
    /// Skips the Bezier interpolation [`Element::hover`] does — same
    /// actionability gate + bbox math, but no human-pointer modeling.
    /// Intended for paths where deterministic timing matters more than
    /// realism.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let el = tab.find().css("button").one().await?;
    /// el.hover_fast().await?;
    /// # Ok(()) }
    /// ```
    pub async fn hover_fast(&self) -> Result<()> {
        self.with_refresh(|| async move {
            self.scroll_into_view().await?;
            actionability::wait_actionable(
                self,
                ActionabilityCheck {
                    visible: true,
                    stable: true,
                    enabled: false,
                    receives_pointer: true,
                },
                DEFAULT_ACTIONABILITY_TIMEOUT,
            )
            .await?;
            let bbox = self
                .bounding_box()
                .await?
                .ok_or_else(|| ZendriverError::Navigation("element has no bounding box".into()))?;
            let cx = bbox.x + bbox.width / 2.0;
            let cy = bbox.y + bbox.height / 2.0;
            let input = self.inner.tab.input().clone();
            mouse::move_raw(&input, &self.inner.tab, cx, cy).await
        })
        .await
    }

    /// Move keyboard focus to this element by calling `el.focus()`.
    ///
    /// Gated by an actionability check (visible + enabled) so disabled
    /// controls + hidden elements surface a [`ZendriverError::NotActionable`]
    /// error rather than silently no-op on the page side. Reused by
    /// [`Element::type_text`] / [`Element::press`] — they focus first so
    /// keystrokes reach this element.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let input = tab.find().css("input[name=email]").one().await?;
    /// input.focus().await?;
    /// # Ok(()) }
    /// ```
    pub async fn focus(&self) -> Result<()> {
        self.with_refresh(|| async move {
            actionability::wait_actionable(
                self,
                ActionabilityCheck::TEXT_INPUT,
                DEFAULT_ACTIONABILITY_TIMEOUT,
            )
            .await?;
            let _ = self
                .call_on_main("function(){ this.focus(); }", json!([]))
                .await?;
            Ok(())
        })
        .await
    }

    /// Scroll this element into view, centered in its scroll container.
    ///
    /// Synchronous (`behavior: 'instant'`) so the post-scroll bbox is final
    /// by the time the next CDP call (e.g. `bounding_box`) runs — important
    /// because subsequent action steps assume the layout is settled.
    ///
    /// No actionability gate: this method IS the visibility prerequisite
    /// for the other actions; gating it on visibility would deadlock.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let footer = tab.find().css("footer").one().await?;
    /// footer.scroll_into_view().await?;
    /// # Ok(()) }
    /// ```
    pub async fn scroll_into_view(&self) -> Result<()> {
        self.with_refresh(|| async move {
            let _ = self
                .call_on_main(
                    "function(){ this.scrollIntoView({block:'center',behavior:'instant'}); }",
                    json!([]),
                )
                .await?;
            Ok(())
        })
        .await
    }

    /// Set this element's `value` directly + fire `input` and `change`
    /// events.
    ///
    /// Bypasses keydown/keyup (use [`Element::type_text`] for a real
    /// keystroke sequence) but dispatches the bubbled `input` + `change`
    /// events so React-style controlled inputs see the update through their
    /// onChange handlers.
    ///
    /// No actionability gate — `set_value` is the fast-path for tests +
    /// automation flows that don't care about visibility/enabledness. If
    /// you need the gate, focus the element first then call this.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let input = tab.find().css("input[name=q]").one().await?;
    /// input.set_value("rust async").await?;
    /// # Ok(()) }
    /// ```
    pub async fn set_value(&self, value: impl AsRef<str>) -> Result<()> {
        let value = value.as_ref().to_string();
        self.with_refresh(|| {
            let value = value.clone();
            async move {
                let _ = self
                    .call_on_main(
                        "function(el, v){ \
                            this.value = v; \
                            this.dispatchEvent(new Event('input', {bubbles: true})); \
                            this.dispatchEvent(new Event('change', {bubbles: true})); \
                        }",
                        json!([{ "value": value }]),
                    )
                    .await?;
                Ok(())
            }
        })
        .await
    }

    /// Clear this element's `value` by assigning `''` and firing a bubbled
    /// `input` event.
    ///
    /// Omits the `change` event + focus + Backspace sequence — for
    /// contenteditable / non-`<input>` clearing semantics, use
    /// [`Element::type_text`].
    ///
    /// No actionability gate — same rationale as [`Element::set_value`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let input = tab.find().css("input").one().await?;
    /// input.clear().await?;
    /// # Ok(()) }
    /// ```
    pub async fn clear(&self) -> Result<()> {
        self.with_refresh(|| async move {
            let _ = self
                .call_on_main(
                    "function(){ \
                        this.value = ''; \
                        this.dispatchEvent(new Event('input', {bubbles: true})); \
                    }",
                    json!([]),
                )
                .await?;
            Ok(())
        })
        .await
    }

    /// Attach files to this `<input type="file">` element via
    /// `DOM.setFileInputFiles`.
    ///
    /// Bypasses the OS file picker entirely — CDP wires the paths straight
    /// into the input's `FileList`, and the page sees a normal `change`
    /// event from the input.
    ///
    /// Scope is direct `<input type="file">` only; routing through a hidden
    /// input clicked by a label / button wrapper is the page's
    /// responsibility. Paths are passed as their lossy `to_string_lossy()`
    /// representation, matching CDP's UTF-8 string contract.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn ex() -> zendriver::Result<()> {
    /// # let browser = zendriver::Browser::builder().launch().await?;
    /// # let tab = browser.main_tab();
    /// let file_input = tab.find().css("input[type=file]").one().await?;
    /// file_input.upload_files(&["/tmp/photo.jpg"]).await?;
    /// # Ok(()) }
    /// ```
    pub async fn upload_files<P: AsRef<Path>>(&self, paths: &[P]) -> Result<()> {
        let files: Vec<String> = paths
            .iter()
            .map(|p| p.as_ref().to_string_lossy().into_owned())
            .collect();
        self.with_refresh(|| {
            let files = files.clone();
            async move {
                let backend_node_id = self.backend_node_id_cloned().await?;
                let _ = self
                    .inner
                    .tab
                    .call(
                        "DOM.setFileInputFiles",
                        json!({
                            "files": files,
                            "backendNodeId": backend_node_id,
                        }),
                    )
                    .await?;
                Ok(())
            }
        })
        .await
    }
}

#[cfg(test)]
#[allow(clippy::panic, clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::tab::Tab;
    use zendriver_transport::SessionHandle;
    use zendriver_transport::testing::MockConnection;

    #[tokio::test]
    async fn hover_dispatches_input_dispatchmouseevent_with_type_mousemoved() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        // `Tab::new_for_test` seeds an `InputController` from the native
        // profile (fast: 10 px/ms ⇒ 0.5 ms segment delay; zero jitter ⇒
        // stable Bezier output) with deterministic seed 42 — pinning the
        // RNG path in case a future profile tweak adds entropy.
        let tab = Tab::new_for_test(sess);
        let el = Element::from_jsret(tab.clone(), 99, "R1".to_string());

        let fut = tokio::spawn({
            let e = el.clone();
            async move { e.hover().await }
        });

        // Step 1: scroll_into_view → Runtime.callFunctionOn.
        let id = mock.expect_cmd("Runtime.callFunctionOn").await;
        let sent = mock.last_sent();
        assert!(
            sent["params"]["functionDeclaration"]
                .as_str()
                .unwrap()
                .contains("scrollIntoView")
        );
        mock.reply(id, json!({ "result": { "type": "undefined" } }))
            .await;

        // Step 2: actionability gate runs check_visible first.
        let id = mock.expect_cmd("Runtime.callFunctionOn").await;
        mock.reply(
            id,
            json!({ "result": { "value": true, "type": "boolean" } }),
        )
        .await;
        // check_stable (gate order: visible → enabled → stable → receives_pointer;
        // enabled is disabled for hover, so stable is next).
        let id = mock.expect_cmd("Runtime.callFunctionOn").await;
        mock.reply(
            id,
            json!({ "result": { "value": true, "type": "boolean" } }),
        )
        .await;
        // check_receives_pointer.
        let id = mock.expect_cmd("Runtime.callFunctionOn").await;
        mock.reply(
            id,
            json!({ "result": { "value": true, "type": "boolean" } }),
        )
        .await;

        // Step 3: bounding_box → DOM.getBoxModel.
        let id = mock.expect_cmd("DOM.getBoxModel").await;
        mock.reply(
            id,
            json!({
                "model": {
                    "content": [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "padding": [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "border":  [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "margin":  [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "width":  100,
                    "height": 50
                }
            }),
        )
        .await;

        // Step 4: mouse move — Bezier path emits N=9..=61
        // `Input.dispatchMouseEvent { type: mouseMoved }` calls. Drain
        // each one, asserting type=mouseMoved along the way; stop once
        // the future completes (no more dispatches arrive within the
        // window).
        let mut saw_mouse_moved = false;
        loop {
            let next = tokio::time::timeout(
                Duration::from_millis(500),
                mock.expect_cmd("Input.dispatchMouseEvent"),
            )
            .await;
            match next {
                Ok(id) => {
                    let sent = mock.last_sent();
                    let kind = sent["params"]["type"].as_str().unwrap_or("");
                    assert_eq!(
                        kind, "mouseMoved",
                        "hover should only emit mouseMoved events"
                    );
                    saw_mouse_moved = true;
                    mock.reply(id, json!({})).await;
                }
                Err(_) => break,
            }
        }

        let res = fut.await.unwrap();
        res.unwrap();
        assert!(
            saw_mouse_moved,
            "expected at least one Input.dispatchMouseEvent with type=mouseMoved"
        );
        conn.shutdown();
    }

    #[tokio::test]
    async fn click_dispatches_mousemoved_then_mousepressed_then_mousereleased() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        // `Tab::new_for_test` seeds the native input profile (fast, zero
        // jitter) with deterministic seed 42. Bezier path still emits N
        // mouseMoved frames, then exactly one mousePressed + one
        // mouseReleased — the per-tab `InputController` lives on `TabInner`
        // since P4 T0 (no `Browser::input()` dance any more).
        let tab = Tab::new_for_test(sess);
        let el = Element::from_jsret(tab.clone(), 99, "R1".to_string());

        let fut = tokio::spawn({
            let e = el.clone();
            async move { e.click().await }
        });

        // Step 1: scroll_into_view → Runtime.callFunctionOn.
        let id = mock.expect_cmd("Runtime.callFunctionOn").await;
        mock.reply(id, json!({ "result": { "type": "undefined" } }))
            .await;

        // Step 2: actionability gate (FULL = visible → enabled → stable →
        // receives_pointer); reply true to each.
        for _ in 0..4 {
            let id = mock.expect_cmd("Runtime.callFunctionOn").await;
            mock.reply(
                id,
                json!({ "result": { "value": true, "type": "boolean" } }),
            )
            .await;
        }

        // Step 3: bounding_box → DOM.getBoxModel.
        let id = mock.expect_cmd("DOM.getBoxModel").await;
        mock.reply(
            id,
            json!({
                "model": {
                    "content": [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "padding": [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "border":  [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "margin":  [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0],
                    "width":  100,
                    "height": 50
                }
            }),
        )
        .await;

        // Step 4: dispatch sequence. Bezier emits N mouseMoved frames, then
        // exactly one mousePressed + one mouseReleased. Walk all
        // `Input.dispatchMouseEvent` calls and assert ordering: every
        // mouseMoved precedes mousePressed, which precedes mouseReleased.
        let mut saw_pressed = false;
        let mut saw_released = false;
        let mut last_kind = String::new();
        loop {
            let next = tokio::time::timeout(
                Duration::from_millis(500),
                mock.expect_cmd("Input.dispatchMouseEvent"),
            )
            .await;
            match next {
                Ok(id) => {
                    let sent = mock.last_sent();
                    let kind = sent["params"]["type"].as_str().unwrap_or("").to_string();
                    match kind.as_str() {
                        "mouseMoved" => {
                            assert!(
                                !saw_pressed && !saw_released,
                                "mouseMoved arrived after mousePressed/Released"
                            );
                        }
                        "mousePressed" => {
                            assert!(!saw_pressed, "duplicate mousePressed");
                            assert!(!saw_released, "mousePressed after mouseReleased");
                            saw_pressed = true;
                        }
                        "mouseReleased" => {
                            assert!(saw_pressed, "mouseReleased before mousePressed");
                            assert!(!saw_released, "duplicate mouseReleased");
                            saw_released = true;
                        }
                        other => panic!("unexpected dispatch type: {other}"),
                    }
                    last_kind = kind;
                    mock.reply(id, json!({})).await;
                }
                Err(_) => break,
            }
        }

        let res = fut.await.unwrap();
        res.unwrap();
        assert!(saw_pressed, "expected a mousePressed dispatch");
        assert!(saw_released, "expected a mouseReleased dispatch");
        assert_eq!(
            last_kind, "mouseReleased",
            "final dispatch should be mouseReleased"
        );
        conn.shutdown();
    }

    #[tokio::test]
    async fn set_value_dispatches_call_function_on_with_value_argument() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);
        let el = Element::from_jsret(tab, 7, "R1".to_string());

        let fut = tokio::spawn({
            let e = el.clone();
            async move { e.set_value("hello world").await }
        });

        let id = mock.expect_cmd("Runtime.callFunctionOn").await;
        let sent = mock.last_sent();
        let decl = sent["params"]["functionDeclaration"].as_str().unwrap();
        // JS body fires both input + change events for React-style listeners.
        assert!(decl.contains("this.value = v"));
        assert!(decl.contains("'input'"));
        assert!(decl.contains("'change'"));
        // call_on_main prepends the element {objectId:...}; the user-supplied
        // value lands at arguments[1].
        let args = sent["params"]["arguments"].as_array().unwrap();
        assert_eq!(args.len(), 2);
        assert_eq!(args[0]["objectId"], "R1");
        assert_eq!(args[1]["value"], "hello world");
        mock.reply(id, json!({ "result": { "type": "undefined" } }))
            .await;

        fut.await.unwrap().unwrap();
        conn.shutdown();
    }

    #[tokio::test]
    async fn upload_files_dispatches_dom_set_file_input_files_with_paths() {
        let (mut mock, conn) = MockConnection::pair();
        let sess = SessionHandle::new(conn.clone(), "S1");
        let tab = Tab::new_for_test(sess);
        let el = Element::from_jsret(tab, 42, "R1".to_string());

        let paths: &[&std::path::Path] = &[
            std::path::Path::new("/tmp/a.txt"),
            std::path::Path::new("/tmp/b.pdf"),
        ];

        let fut = tokio::spawn({
            let e = el.clone();
            let paths: Vec<std::path::PathBuf> = paths.iter().map(|p| p.to_path_buf()).collect();
            async move { e.upload_files(&paths).await }
        });

        let id = mock.expect_cmd("DOM.setFileInputFiles").await;
        let sent = mock.last_sent();
        assert_eq!(sent["params"]["backendNodeId"], 42);
        let files = sent["params"]["files"].as_array().unwrap();
        assert_eq!(files.len(), 2);
        assert_eq!(files[0], "/tmp/a.txt");
        assert_eq!(files[1], "/tmp/b.pdf");
        mock.reply(id, json!({})).await;

        fut.await.unwrap().unwrap();
        conn.shutdown();
    }
}