chrome-agent 0.14.0

Browser automation for AI agents. Single binary, zero deps, CDP direct to Chrome.
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
//! Form controls, file inputs and drag, split out of `element.rs` to stay under the repo's
//! 1000-line file cap. Re-exported from `element` so callers keep one path.

use std::collections::HashMap;

use serde_json::json;

use crate::cdp::client::CdpClient;
use crate::cdp::types::{DispatchMouseEventParams, MouseButton, MouseEventType};
use crate::element_ref::ElementRef;

use std::time::Duration;

use super::element::{check_js_exception, click, resolve_uid, wait_for_stabilization, ElementError};

/// What a select did, and when it looked.
///
/// The read-back happens through the same observation window as fill and check
/// (`READ_BACK_MS`): a controlled component that snaps the selection back on a microtask
/// or `setTimeout(0)` is caught; a validator firing later is not, which is why the window
/// is reported rather than persistence asserted.
///
/// `actual` and `kept` are carried rather than recomputed by the caller from the fact that
/// this outcome exists at all. The refusal below is what makes them agree, and a
/// postcondition rebuilt out of control flow — "we did not return an error, so the page
/// kept it" — is no longer a measurement: it would keep claiming `value_kept` if the
/// refusal ever moved.
pub struct SelectOutcome {
    /// Text of the option we asked the element to hold.
    pub text: String,
    /// Text of the option it held when we looked, whatever that was.
    pub actual: Option<String>,
    /// Whether that was the same option — compared by index, not by text, so two options
    /// sharing a label cannot pass for each other.
    pub kept: bool,
    /// The `<select>` names a secret through `autocomplete` (`element::SECRET_FIELD`). The
    /// option text is then withheld from the report and from the message, exactly as a
    /// fill withholds a password.
    pub secret: bool,
    pub observed_after_ms: u64,
}

impl SelectOutcome {
    /// The option text for a message, or a marker when the element names a secret.
    ///
    /// The message reaches stdout, the agent transcript and any `--record` file, so
    /// redacting the report while quoting the text one field away would redact nothing.
    #[must_use]
    pub fn label(&self) -> &str {
        if self.secret { "(redacted)" } else { &self.text }
    }
}

/// How a `<select>`'s current selection is read.
///
/// One reader, two callers: `select`'s own read-back below, and `assert state --selected`.
/// An assertion that read the selection differently from the action that made it could
/// report a form as correctly filled while `select` had already refused it, or the reverse.
pub const SELECT_READ: &str = r"function (el) {
    if (el.tagName !== 'SELECT') throw new Error('Element is not a <select>');
    const i = el.selectedIndex;
    const o = (i >= 0 && el.options[i]) ? el.options[i] : null;
    return { index: i, text: o ? o.text : null, value: o ? o.value : null };
}";

/// Shared body: set the selection, dispatch `change`, then read it back after the
/// window — all bound to the same `el`, so a document change between round trips
/// cannot swap the node under us. Composed at run time rather than declared as a `const`
/// so the read-back goes through `SELECT_READ` instead of its own copy of it.
fn select_apply() -> String {
    format!(
        r"function (el, target, windowMs) {{
    if (el.tagName !== 'SELECT') throw new Error('Element is not a <select>');
    const opts = Array.from(el.options);
    let idx = opts.findIndex(o => o.value === target);
    if (idx === -1) idx = opts.findIndex(o => o.text.trim() === target);
    if (idx === -1) throw new Error('No option matching: ' + target);
    el.selectedIndex = idx;
    el.dispatchEvent(new Event('change', {{bubbles: true}}));
    return new Promise(resolve => setTimeout(() => {{
        const now = ({SELECT_READ})(el);
        resolve({{
            requested: opts[idx].text,
            kept: now.index === idx,
            actual: now.text,
            secret: !!{SECRET},
        }});
    }}, windowMs));
}}",
        SECRET = crate::element::SECRET_FIELD
    )
}

/// Turn the read-back into the outcome, refusing when the page took the selection away.
///
/// Same policy as check: reporting "Selected" for a select the page has already snapped
/// back is the one answer an agent cannot recover from — it submits the form believing a
/// different option is chosen than what the page holds.
fn select_outcome(result: &serde_json::Value) -> Result<SelectOutcome, ElementError> {
    check_js_exception(result)?;
    let value = result.get("result").and_then(|r| r.get("value"));
    let kept = value.and_then(|v| v.get("kept")).and_then(serde_json::Value::as_bool).unwrap_or(false);
    let requested = value.and_then(|v| v.get("requested")).and_then(serde_json::Value::as_str).unwrap_or("");
    let secret = value.and_then(|v| v.get("secret")).and_then(serde_json::Value::as_bool).unwrap_or(false);
    let actual = value
        .and_then(|v| v.get("actual"))
        .and_then(serde_json::Value::as_str)
        .map(str::to_string);
    if !kept {
        // A secret element names neither option: this message reaches stdout and the
        // transcript, and "reverted to X" leaks X as surely as the success would.
        let (held, asked) = if secret {
            ("another option".to_string(), "the option asked for".to_string())
        } else {
            (
                actual.as_ref().map_or_else(|| "nothing".to_string(), |a| format!("\"{a}\"")),
                format!("\"{requested}\""),
            )
        };
        return Err(ElementError::Action(format!(
            "The page reverted the selection to {held} within {}ms; {asked} did not stick.",
            crate::element::READ_BACK_MS
        )));
    }
    Ok(SelectOutcome {
        text: requested.to_string(),
        actual,
        kept,
        secret,
        observed_after_ms: crate::element::READ_BACK_MS,
    })
}

pub async fn select_option(
    client: &CdpClient,
    uid_map: &HashMap<String, ElementRef>,
    uid: &str,
    value: &str,
) -> Result<SelectOutcome, ElementError> {
    let resolved = resolve_uid(client, uid_map, uid).await?;
    let apply = select_apply();
    let js = format!(
        "function(target, windowMs) {{ return ({apply})(this, target, windowMs); }}"
    );
    let result: serde_json::Value = client
        .call("Runtime.callFunctionOn", json!({
            "objectId": resolved.object_id,
            "functionDeclaration": js,
            "arguments": [{"value": value}, {"value": crate::element::READ_BACK_MS}],
            "returnByValue": true,
            "awaitPromise": true,
        }))
        .await
        .map_err(|e| ElementError::Action(format!("select_option failed: {e}")))?;

    select_outcome(&result)
}

/// Select a dropdown option by CSS selector.
pub async fn select_option_selector(
    client: &CdpClient,
    selector: &str,
    value: &str,
) -> Result<SelectOutcome, ElementError> {
    let sel_json = serde_json::to_string(selector).unwrap_or_default();
    let val_json = serde_json::to_string(value).unwrap_or_default();
    let js = format!(
        r"(() => {{
            const el = document.querySelector({sel_json});
            if (!el) throw new Error('No element matches selector: ' + {sel_json});
            return ({apply})(el, {val_json}, {window});
        }})()",
        apply = select_apply(),
        window = crate::element::READ_BACK_MS
    );
    let result: serde_json::Value = client
        .call(
            "Runtime.evaluate",
            json!({"expression": js, "returnByValue": true, "awaitPromise": true}),
        )
        .await
        .map_err(|e| ElementError::Action(format!("select_option_selector failed: {e}")))?;

    select_outcome(&result)
}

// ---------------------------------------------------------------------------
// Check / Uncheck
// ---------------------------------------------------------------------------

/// Classify a checkable and read its current state, as a JS expression taking `el`.
///
/// `el.checked` is the wrong reading twice over. Every `HTMLInputElement` exposes it, so a
/// text input answers `false` and a click on it reports success while meaning nothing. And a
/// `<div role="checkbox" aria-checked="true">` has no such property at all, so a truthiness
/// read calls a checked box unchecked and the click turns it OFF while reporting success.
pub const CHECKABLE_PROBE: &str = r"function (el) {
  const tag = el.tagName;
  const type = (el.type || '').toLowerCase();
  const role = (el.getAttribute('role') || '').toLowerCase();
  const ariaAttr = el.getAttribute('aria-checked');
  const native = tag === 'INPUT' && (type === 'checkbox' || type === 'radio');
  const aria = ariaAttr !== null ||
    ['checkbox', 'radio', 'switch', 'menuitemcheckbox', 'menuitemradio'].indexOf(role) >= 0;
  if (!native && !aria) {
    return { kind: 'none', tag: tag, type: type, role: role };
  }
  const state = native
    ? (el.indeterminate ? 'mixed' : (el.checked ? 'true' : 'false'))
    : (ariaAttr === null ? 'false' : ariaAttr.toLowerCase());
  return {
    kind: native ? 'native' : 'aria',
    radio: (native && type === 'radio') || role === 'radio' || role === 'menuitemradio',
    state: state
  };
}";

/// What the probe found: either the element can't be checked, or here is its state.
///
/// Visible to the crate because `assert state --checked` reads through this same
/// classification: the assertion and the action agree by construction, not by two
/// implementations that happen to match today.
pub struct Checkable {
    pub kind: String,
    pub radio: bool,
    pub state: String,
    pub tag: String,
    pub ty: String,
    pub role: String,
}

fn parse_probe(v: &serde_json::Value) -> Checkable {
    parse_probe_value(&v.get("result").and_then(|r| r.get("value")).cloned().unwrap_or_default())
}

/// `parse_probe` for a caller that already unwrapped the CDP envelope.
pub fn parse_probe_value(r: &serde_json::Value) -> Checkable {
    let s = |k: &str| r.get(k).and_then(serde_json::Value::as_str).unwrap_or_default().to_string();
    Checkable {
        kind: s("kind"),
        radio: r.get("radio").and_then(serde_json::Value::as_bool).unwrap_or(false),
        state: s("state"),
        tag: s("tag"),
        ty: s("type"),
        role: s("role"),
    }
}

/// Reject an element that cannot hold a checked state, or a radio asked to become unchecked.
///
/// `assert state --checked` calls it with `desired: true` so only the first refusal applies:
/// asking whether a `<div>` is checked is as unanswerable as asking to check it.
pub fn refuse_uncheckable(probe: &Checkable, desired: bool) -> Result<(), ElementError> {
    if probe.kind == "none" {
        let mut what = probe.tag.to_lowercase();
        if !probe.ty.is_empty() {
            what.push_str(&format!(" type={}", probe.ty));
        }
        if !probe.role.is_empty() {
            what.push_str(&format!(" role={}", probe.role));
        }
        return Err(ElementError::Action(format!(
            "<{what}> has no checked state. check/uncheck need an <input type=checkbox|radio> \
             or an element with role=checkbox|radio|switch and aria-checked."
        )));
    }
    if !desired && probe.radio {
        return Err(ElementError::Action(
            "A radio cannot be unchecked by clicking it. Select another radio in the group instead."
                .into(),
        ));
    }
    Ok(())
}

/// What a check/uncheck asked the element to hold, and what it held when read back.
///
/// `actual` is the state the probe reported after the window, carried rather than assumed
/// equal to `requested`: the refusal in `set_checked` is what makes the two agree, and a
/// postcondition rebuilt from control flow would keep claiming the write landed if that
/// refusal ever moved.
pub struct CheckReadBack {
    /// The state asked for, in the words the message uses: `checked` or `unchecked`.
    pub requested: &'static str,
    /// The state the element held when it was read back.
    pub actual: String,
    pub observed_after_ms: u64,
}

/// Idempotent check/uncheck: query current state, click only if different.
/// What a check/uncheck did, and when it looked.
///
/// The message alone could not say whether a read-back had happened: "Already checked" is a
/// pre-action observation, "Checked" is a post-action one, and only the second has a window.
pub struct CheckOutcome {
    pub message: String,
    /// `None` when the element already held the desired state: nothing was dispatched, so
    /// there was no post-action moment and no read-back of a write of ours to report.
    pub read_back: Option<CheckReadBack>,
    /// How the click that changed the state was delivered. `NotProbed` when none was needed
    /// (the state already held); `JsDispatch` on the selector path, which drives the change
    /// with `el.click()` inside a single evaluation and so performs no hit test at all.
    pub delivery: crate::verdict::Delivery,
}

/// The probe's state token in the words the messages use.
///
/// An agent reading `value.actual` should not have to know the probe answers `"true"`, and
/// an `aria-checked` holding something else entirely passes through unchanged rather than
/// being flattened into one of the three we know.
fn state_word(state: &str) -> String {
    match state {
        "true" => "checked".to_string(),
        "false" => "unchecked".to_string(),
        "mixed" => "indeterminate".to_string(),
        other => other.to_string(),
    }
}

impl CheckOutcome {
    const fn already(message: String) -> Self {
        Self { message, read_back: None, delivery: crate::verdict::Delivery::NotProbed }
    }
    fn acted(
        message: String,
        delivery: crate::verdict::Delivery,
        desired: bool,
        held: &str,
    ) -> Self {
        Self {
            message,
            read_back: Some(CheckReadBack {
                requested: if desired { "checked" } else { "unchecked" },
                actual: state_word(held),
                observed_after_ms: crate::element::READ_BACK_MS,
            }),
            delivery,
        }
    }
}

pub async fn set_checked(
    client: &CdpClient,
    uid_map: &HashMap<String, ElementRef>,
    uid: &str,
    desired: bool,
    on_intercept: crate::hit_test::OnIntercept,
) -> Result<CheckOutcome, ElementError> {
    let resolved = resolve_uid(client, uid_map, uid).await?;
    let probe_fn = format!("function() {{ return ({CHECKABLE_PROBE})(this); }}");

    let read_state = |object_id: String, decl: String| async move {
        client
            .call::<_, serde_json::Value>("Runtime.callFunctionOn", json!({
                "objectId": object_id,
                "functionDeclaration": decl,
                "returnByValue": true,
            }))
            .await
            .map_err(|e| ElementError::Action(format!("read checked state failed: {e}")))
            .and_then(|v| {
                // A throwing probe used to yield an empty kind, sail past the refusal and
                // click the element anyway — blaming the page for our own read failure
                // while mutating it unasked.
                check_js_exception(&v)?;
                Ok(v)
            })
    };

    let before = parse_probe(&read_state(resolved.object_id.clone(), probe_fn.clone()).await?);
    refuse_uncheckable(&before, desired)?;

    let want = if desired { "true" } else { "false" };
    let asked_for = if desired { "checked" } else { "unchecked" };
    if before.state == want {
        return Ok(CheckOutcome::already(format!("Already {asked_for} uid={uid}")));
    }

    let dispatched = click(client, uid_map, uid, on_intercept).await?;
    // A state change asks for a click that arrives. When the aim point never settled nothing
    // was sent, so the read-back below would blame the page for a click we never made — and
    // "is still unchecked after the click" is the sentence that sends an agent hunting an
    // overlay that does not exist.
    if let Some(refused) = dispatched.refusal_message("check", &format!("uid={uid}")) {
        return Err(ElementError::NotInteractable(refused));
    }

    // Read it back: a click is a request, not a result. A handler can reject or revert it,
    // and reporting "Checked" for a box that is still off is the one answer an agent cannot
    // recover from. Waited explicitly, not by accident: this path used to observe whatever
    // a CDP round trip happened to cost, which is neither the selector path's window nor
    // any window at all.
    tokio::time::sleep(std::time::Duration::from_millis(crate::element::READ_BACK_MS)).await;
    let after = parse_probe(&read_state(resolved.object_id, probe_fn).await?);
    if after.state != want {
        let received = dispatched.receiver.as_ref().map_or_else(
            || "the page did not accept the change".to_string(),
            |hit| {
                format!(
                    "the click was received by {}, which covers it",
                    hit.id.as_deref().map_or_else(|| hit.tag.to_lowercase(), |id| format!("#{id}"))
                )
            },
        );
        return Err(ElementError::Action(format!(
            "uid={uid} is still {} after the click; {received}.",
            state_word(&after.state)
        )));
    }
    Ok(CheckOutcome::acted(
        format!("{} uid={uid}", if desired { "Checked" } else { "Unchecked" }),
        dispatched.delivery,
        desired,
        &after.state,
    ))
}

/// Idempotent check/uncheck by CSS selector.
pub async fn set_checked_selector(
    client: &CdpClient,
    selector: &str,
    desired: bool,
) -> Result<CheckOutcome, ElementError> {
    let sel_json = serde_json::to_string(selector).unwrap_or_default();
    let want = if desired { "true" } else { "false" };
    // One evaluation does probe, click and read-back, so all three bind the same node even
    // if the document changes under us between round trips.
    let js = format!(
        r"(() => {{
            const el = document.querySelector({sel_json});
            if (!el) throw new Error('No element matches selector: ' + {sel_json});
            const probe = ({CHECKABLE_PROBE});
            const before = probe(el);
            if (before.kind === 'none') return before;
            if ('{want}' === 'false' && before.radio) return {{ kind: 'radio_locked' }};
            if (before.state === '{want}') return {{ kind: before.kind, state: 'already' }};
            el.click();
            // Read back after the window: a handler that reverts the change in a promise
            // or a timeout is invisible to a synchronous read.
            return new Promise(resolve => setTimeout(() => {{
                const after = probe(el);
                resolve({{
                    kind: before.kind,
                    state: after.state === '{want}' ? 'ok' : after.state,
                    // The reading itself, beside the verdict on it: the response reports what
                    // the element held, not that control flow reached the success branch.
                    held: after.state,
                }});
            }}, {window}));
        }})()",
        window = crate::element::READ_BACK_MS
    );
    let result: serde_json::Value = client
        .call(
            "Runtime.evaluate",
            json!({"expression": js, "returnByValue": true, "awaitPromise": true}),
        )
        .await
        .map_err(|e| ElementError::Action(format!("set_checked_selector failed: {e}")))?;

    check_js_exception(&result)?;
    let probe = parse_probe(&result);
    if probe.kind == "radio_locked" {
        return Err(ElementError::Action(
            "A radio cannot be unchecked by clicking it. Select another radio in the group instead."
                .into(),
        ));
    }
    refuse_uncheckable(&probe, desired)?;

    let held = result
        .get("result")
        .and_then(|r| r.get("value"))
        .and_then(|v| v.get("held"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default();
    let asked_for = if desired { "checked" } else { "unchecked" };
    match probe.state.as_str() {
        "already" => Ok(CheckOutcome::already(format!(
            "Already {asked_for} selector '{selector}'"
        ))),
        "ok" => Ok(CheckOutcome::acted(
            format!("{} selector '{selector}'", if desired { "Checked" } else { "Unchecked" }),
            // `el.click()`, inside the same evaluation as the probe and the read-back: no hit
            // test happened and none could have, so interception is inapplicable here rather
            // than undetected.
            crate::verdict::Delivery::JsDispatch,
            desired,
            held,
        )),
        // `state_word`, not the probe's own token: the same reading is reported as
        // `value.actual` on the success path, and one state must not have two spellings.
        other => Err(ElementError::Action(format!(
            "selector '{selector}' is still {} after the click; the page did not accept the change.",
            state_word(other)
        ))),
    }
}

// ---------------------------------------------------------------------------
// File upload
// ---------------------------------------------------------------------------

/// Validate every upload path exists before invoking CDP; returns the first
/// missing path as `ElementError::Action`. Shared by both upload entry points.
pub fn validate_upload_paths(files: &[String]) -> Result<(), ElementError> {
    for f in files {
        if !std::path::Path::new(f).exists() {
            return Err(ElementError::Action(format!("File not found: {f}")));
        }
    }
    Ok(())
}

/// Set files on a file input using `DOM.setFileInputFiles`.
pub async fn set_file_input(
    client: &CdpClient,
    uid_map: &HashMap<String, ElementRef>,
    uid: &str,
    files: &[String],
) -> Result<(), ElementError> {
    validate_upload_paths(files)?;
    let resolved = resolve_uid(client, uid_map, uid).await?;
    let nav_events = client.events();
    client
        .send("DOM.setFileInputFiles", json!({
            "files": files,
            "backendNodeId": resolved.backend_node_id,
        }))
        .await
        .map_err(|e| ElementError::Action(format!("setFileInputFiles failed: {e}")))?;
    wait_for_stabilization(client, nav_events).await;
    Ok(())
}

/// Set files on a file input identified by CSS selector.
pub async fn set_file_input_selector(
    client: &CdpClient,
    selector: &str,
    files: &[String],
) -> Result<(), ElementError> {
    validate_upload_paths(files)?;
    let sel_json = serde_json::to_string(selector).unwrap_or_default();
    let node: serde_json::Value = client
        .call("Runtime.evaluate", json!({
            "expression": format!("(() => {{ const el = document.querySelector({sel_json}); if (!el) throw new Error('No element matches selector: ' + {sel_json}); return true; }})()"),
            "returnByValue": true,
        }))
        .await
        .map_err(|e| ElementError::Action(format!("set_file_input_selector resolve failed: {e}")))?;
    check_js_exception(&node)?;

    let doc: serde_json::Value = client
        .call("DOM.getDocument", json!({"depth": 0}))
        .await
        .map_err(|e| ElementError::Action(format!("DOM.getDocument failed: {e}")))?;
    let root_node_id = doc.get("root")
        .and_then(|r| r.get("nodeId"))
        .and_then(serde_json::Value::as_i64)
        .ok_or_else(|| ElementError::Action("Could not get root nodeId".into()))?;

    let qs_result: serde_json::Value = client
        .call("DOM.querySelector", json!({"nodeId": root_node_id, "selector": selector}))
        .await
        .map_err(|e| ElementError::Action(format!("DOM.querySelector failed: {e}")))?;
    let node_id = qs_result.get("nodeId")
        .and_then(serde_json::Value::as_i64)
        .ok_or_else(|| ElementError::Action(format!("No element matches selector: {selector}")))?;

    let nav_events = client.events();
    client
        .send("DOM.setFileInputFiles", json!({
            "files": files,
            "nodeId": node_id,
        }))
        .await
        .map_err(|e| ElementError::Action(format!("setFileInputFiles failed: {e}")))?;
    wait_for_stabilization(client, nav_events).await;
    Ok(())
}

// ---------------------------------------------------------------------------
// Drag
// ---------------------------------------------------------------------------

/// Linear-interpolate the mouse-move points for a drag from `(x1,y1)` to
/// `(x2,y2)` over `steps` segments (last point lands on the destination).
/// Extracted so `drag` and its regression test exercise the *same* math.
pub fn drag_interpolation_points(x1: f64, y1: f64, x2: f64, y2: f64, steps: u32) -> Vec<(f64, f64)> {
    (1..=steps)
        .map(|i| {
            let t = f64::from(i) / f64::from(steps);
            ((x2 - x1).mul_add(t, x1), (y2 - y1).mul_add(t, y1))
        })
        .collect()
}

/// Drag from one element to another.
pub async fn drag(
    client: &CdpClient,
    uid_map: &HashMap<String, ElementRef>,
    from_uid: &str,
    to_uid: &str,
) -> Result<(), ElementError> {
    let from = resolve_uid(client, uid_map, from_uid).await?;
    let to = resolve_uid(client, uid_map, to_uid).await?;

    let (x1, y1) = from.center.ok_or_else(|| {
        ElementError::NotInteractable(format!("Element uid={from_uid} has no visible box model."))
    })?;
    let (x2, y2) = to.center.ok_or_else(|| {
        ElementError::NotInteractable(format!("Element uid={to_uid} has no visible box model."))
    })?;

    let mouse = |et, x, y, btn: Option<MouseButton>, btns, cc| {
        DispatchMouseEventParams {
            event_type: et, x, y,
            button: btn, buttons: btns, click_count: cc,
            modifiers: None, timestamp: None, delta_x: None, delta_y: None,
            pointer_type: Some("mouse".into()),
        }
    };

    // See `CdpClient::ensure_foreground`: a drag is five pointer events, and each one of them
    // pays the background-tab timer.
    client.ensure_foreground().await;
    let nav_events = client.events();
    client.send_input("Input.dispatchMouseEvent",
        mouse(MouseEventType::MouseMoved, x1, y1, None, None, None))
        .await.map_err(|e| ElementError::Action(format!("drag move failed: {e}")))?;

    client.send_input("Input.dispatchMouseEvent",
        mouse(MouseEventType::MousePressed, x1, y1, Some(MouseButton::Left), Some(1), Some(1)))
        .await.map_err(|e| ElementError::Action(format!("drag press failed: {e}")))?;

    for (x, y) in drag_interpolation_points(x1, y1, x2, y2, 5) {
        client.send_input("Input.dispatchMouseEvent",
            mouse(MouseEventType::MouseMoved, x, y, Some(MouseButton::Left), Some(1), None))
            .await.map_err(|e| ElementError::Action(format!("drag step failed: {e}")))?;
        tokio::time::sleep(Duration::from_millis(16)).await;
    }

    client.send_input("Input.dispatchMouseEvent",
        mouse(MouseEventType::MouseReleased, x2, y2, Some(MouseButton::Left), Some(0), Some(1)))
        .await.map_err(|e| ElementError::Action(format!("drag release failed: {e}")))?;

    wait_for_stabilization(client, nav_events).await;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn drag_interpolation_5_steps() {
        // Exercises the real fn `drag` calls (not a re-implementation of the math).
        let points = drag_interpolation_points(100.0, 100.0, 200.0, 300.0, 5);
        assert_eq!(points.len(), 5);
        assert!((points[0].0 - 120.0).abs() < 0.01);
        assert!((points[0].1 - 140.0).abs() < 0.01);
        // Last point lands exactly on the destination.
        assert!((points[4].0 - 200.0).abs() < 0.01);
        assert!((points[4].1 - 300.0).abs() < 0.01);
    }

    #[test]
    fn upload_validation_rejects_missing_and_accepts_existing() {
        // Missing path → error through the real upload validation code path.
        let missing = vec!["/nonexistent/file.txt".to_string()];
        let err = validate_upload_paths(&missing).unwrap_err();
        assert!(matches!(err, ElementError::Action(_)));
        assert!(err.to_string().contains("File not found: /nonexistent/file.txt"));
        // An existing path (this test binary) passes validation.
        let exe = std::env::current_exe().unwrap().to_string_lossy().into_owned();
        assert!(validate_upload_paths(&[exe]).is_ok());
    }

    // A10f: a receiver subscribed BEFORE the action still observes navigation
    // events that fired before we start waiting — the fast-load race the fix closes.
}