opencrabs 0.5.1

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Recommended: the 40MB prebuilt binary for macOS, Linux and Windows: https://github.com/adolfousier/opencrabs/releases
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
//! browser_act — Batched browser actions (multi_act) in ONE call.
//!
//! Accepts an ordered `actions` array (`click` / `fill` / `press` /
//! `select` / `wait`) and executes it against a STABLE view: every
//! selector is resolved up front in a single JS pass BEFORE anything
//! executes — a stale reference rejects the whole call instead of
//! half-running a sequence. Execution aborts on first failure and
//! reports the completed prefix. One screenshot at the end (the whole
//! point of batching: fewer round-trips, one page-change capture).

use super::manager::{BrowserManager, split_frame_selector};
use crate::brain::tools::error::Result;
use crate::brain::tools::r#trait::{
    Tool, ToolCapability, ToolExecutionContext, ToolHints, ToolResult,
};
use async_trait::async_trait;
use serde_json::Value;
use std::sync::Arc;

/// Hard cap on actions per call (#1188: "max-10 cap enforced").
pub(crate) const MAX_ACTIONS: usize = 10;
/// Per-`wait` cap — a single action must not eat the whole budget.
pub(crate) const MAX_WAIT_MS: u64 = 10_000;
/// Overall budget for the whole batch.
pub(crate) const BATCH_TIMEOUT_SECS: u64 = 120;

/// One parsed, validated action.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Act {
    Click { selector: String },
    Fill { selector: String, text: String },
    Press { key: String },
    Select { selector: String, value: String },
    Wait { ms: u64 },
}

impl Act {
    /// The selector this action targets, if any (drives pre-flight).
    pub(crate) fn selector(&self) -> Option<&str> {
        match self {
            Act::Click { selector } | Act::Fill { selector, .. } | Act::Select { selector, .. } => {
                Some(selector)
            }
            Act::Press { .. } | Act::Wait { .. } => None,
        }
    }

    /// Short human label for reporting ("click #submit", "wait 500ms").
    pub(crate) fn label(&self) -> String {
        match self {
            Act::Click { selector } => format!("click {selector}"),
            Act::Fill { selector, .. } => format!("fill {selector}"),
            Act::Press { key } => format!("press {key}"),
            Act::Select { selector, .. } => format!("select {selector}"),
            Act::Wait { ms } => format!("wait {ms}ms"),
        }
    }
}

/// Parse + validate the `actions` array. Pure — every rejection reason
/// is testable without a browser.
pub(crate) fn parse_actions(input: &Value) -> std::result::Result<Vec<Act>, String> {
    let raw = match input["actions"].as_array() {
        Some(a) if !a.is_empty() => a,
        _ => return Err("'actions' must be a non-empty array".into()),
    };
    if raw.len() > MAX_ACTIONS {
        return Err(format!(
            "Too many actions: {} (cap is {MAX_ACTIONS}). Split into multiple browser_act calls.",
            raw.len()
        ));
    }
    let mut out = Vec::with_capacity(raw.len());
    for (i, a) in raw.iter().enumerate() {
        let kind = a["type"].as_str().unwrap_or("");
        let act = match kind {
            "click" => Act::Click {
                selector: req_str(a, "selector", i, "click")?,
            },
            "fill" => Act::Fill {
                selector: req_str(a, "selector", i, "fill")?,
                text: req_str(a, "text", i, "fill")?,
            },
            "press" => Act::Press {
                key: req_str(a, "key", i, "press")?,
            },
            "select" => Act::Select {
                selector: req_str(a, "selector", i, "select")?,
                value: match a["value"].as_str() {
                    Some(v) => v.to_string(),
                    None => String::new(),
                },
            },
            "wait" => {
                let ms = a["ms"].as_u64().unwrap_or(0);
                if ms == 0 {
                    return Err(format!(
                        "action {}: 'wait' requires a positive \"ms\" (1-{MAX_WAIT_MS})",
                        i + 1
                    ));
                }
                if ms > MAX_WAIT_MS {
                    return Err(format!(
                        "action {}: wait of {ms}ms exceeds the per-action cap of {MAX_WAIT_MS}ms — \
                         split long waits into multiple actions",
                        i + 1
                    ));
                }
                Act::Wait { ms }
            }
            other => {
                return Err(format!(
                    "action {}: unknown type '{other}' (expected click/fill/press/select/wait)",
                    i + 1
                ));
            }
        };
        out.push(act);
    }
    Ok(out)
}

fn req_str(a: &Value, field: &str, i: usize, kind: &str) -> std::result::Result<String, String> {
    match a[field].as_str() {
        Some(s) if !s.is_empty() => Ok(s.to_string()),
        _ => Err(format!(
            "action {}: '{kind}' requires a non-empty \"{field}\"",
            i + 1
        )),
    }
}

/// Completed-prefix failure report: "actions 1-2 OK; action 3 failed: …".
/// Pure — pinned by tests.
pub(crate) fn format_prefix_report(done: usize, failed: &Act, reason: &str) -> String {
    let label = failed.label();
    if done == 0 {
        format!("action 1 ({label}) failed: {reason}. No actions executed.")
    } else {
        format!(
            "actions 1-{done} OK; action {} ({label}) failed: {reason}. Later actions were NOT run — \
             the page state reflects the completed prefix only; re-inventory with browser_find \
             before retrying the remainder.",
            done + 1
        )
    }
}

/// Build the one-pass pre-flight JS: resolves EVERY selector (all three
/// shapes: CSS, `text=…`, `xpath=…`) and reports presence + visibility.
/// Injected as a JSON array so quoting is airtight; pure fn — shape is
/// pinned by tests.
pub(crate) fn build_pre_flight_js(selectors: &[String]) -> String {
    let arr = serde_json::to_string(selectors).unwrap_or_else(|_| "[]".into());
    format!(
        r#"(function(){{
  var sels = {arr};
  var results = [];
  for (var i = 0; i < sels.length; i++) {{
    var s = sels[i];
    var el = null;
    try {{
      if (s.indexOf("text=") === 0) {{
        var needle = s.slice(5).toLowerCase();
        var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
        var node;
        while ((node = walker.nextNode())) {{
          var t = (node.innerText || node.textContent || "").toLowerCase();
          if (t.indexOf(needle) !== -1) {{
            var r = node.getBoundingClientRect();
            if (r.width > 0 && r.height > 0) {{ el = node; break; }}
          }}
        }}
      }} else if (s.indexOf("xpath=") === 0) {{
        var it = document.evaluate(s.slice(6), document, null,
          XPathResult.FIRST_ORDERED_NODE_TYPE, null);
        var n = it.singleNodeValue;
        if (n) {{
          var r2 = n.getBoundingClientRect();
          if (r2.width > 0 && r2.height > 0) el = n;
        }}
      }} else {{
        var q = document.querySelector(s);
        if (q) {{
          var r3 = q.getBoundingClientRect();
          if (r3.width > 0 && r3.height > 0) el = q;
        }}
      }}
    }} catch (e) {{
      results.push({{i: i, ok: false, reason: "invalid selector: " + e.message}});
      continue;
    }}
    results.push({{i: i, ok: !!el, reason: el ? "" : "not found or not visible"}});
  }}
  return results;
}})()"#
    )
}

pub struct BrowserActTool {
    manager: Arc<BrowserManager>,
}

impl BrowserActTool {
    pub fn new(manager: Arc<BrowserManager>) -> Self {
        Self { manager }
    }
}

#[async_trait]
impl Tool for BrowserActTool {
    fn name(&self) -> &str {
        "browser_act"
    }

    fn description(&self) -> &str {
        "Execute a batch of browser actions in ONE call against the current page. \
         Actions run in order: click/fill/press/select/wait (max 10). Every selector is \
         resolved BEFORE anything executes — one stale reference rejects the whole call \
         with zero side effects. On mid-sequence failure the completed prefix is reported \
         and the rest is skipped. Takes ONE screenshot at the end. Use this instead of \
         chained browser_click/browser_type calls whenever the sequence is known: one \
         round-trip, one stable view, one screenshot."
    }

    fn input_schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "actions": {
                    "type": "array",
                    "maxItems": 10,
                    "description": "Ordered actions. Each object has a \"type\" plus its fields: \
                        {\"type\":\"click\",\"selector\":\"\"} (CSS, text=Label, xpath=//…, or f2:N frame index), \
                        {\"type\":\"fill\",\"selector\":\"\",\"text\":\"\"} (replaces the value, framework-safe), \
                        {\"type\":\"press\",\"key\":\"Enter\"}, \
                        {\"type\":\"select\",\"selector\":\"\",\"value\":\"option value\"}, \
                        {\"type\":\"wait\",\"ms\":500} (max 10000).",
                }
            },
            "required": ["actions"]
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::Network]
    }

    fn hints(&self) -> ToolHints {
        ToolHints {
            read_only: false,
            destructive: true,
            idempotent: false,
            open_world: true,
        }
    }

    fn requires_approval(&self) -> bool {
        true
    }

    async fn execute(&self, input: Value, context: &ToolExecutionContext) -> Result<ToolResult> {
        let main_page = match self
            .manager
            .get_or_create_session_page(context.session_id)
            .await
        {
            Ok(p) => p,
            Err(e) => return Ok(ToolResult::error(format!("Browser error: {e}"))),
        };

        // Overall batch budget (#1188): pre-flight + execution must fit
        // inside BATCH_TIMEOUT_SECS. Wait actions are individually capped
        // at MAX_WAIT_MS, so the sum is bounded, but a hung CDP call or a
        // pathological sequence still gets cut off here.
        tokio::time::timeout(
            std::time::Duration::from_secs(BATCH_TIMEOUT_SECS),
            self.run_batch(&input, context, &main_page),
        )
        .await
        .unwrap_or_else(|_| {
            Ok(ToolResult::error(format!(
                "Batch exceeded the overall {BATCH_TIMEOUT_SECS}s budget (pre-flight + execution). \
                 Reduce waits or split into multiple browser_act calls."
            )))
        })
    }
} // impl Tool for BrowserActTool

impl BrowserActTool {
    async fn run_batch(
        &self,
        input: &Value,
        context: &ToolExecutionContext,
        main_page: &chromiumoxide::Page,
    ) -> Result<ToolResult> {
        let acts = match parse_actions(input) {
            Ok(a) => a,
            Err(e) => return Ok(ToolResult::error(e)),
        };

        // Resolve every action's page up front: frame-prefixed selectors
        // (`f2:14`) route to their OOPIF page, everything else to main.
        // A stale frame label rejects the whole call (consistent with
        // click/type routing).
        use std::collections::HashMap;
        let mut frame_pages: HashMap<String, chromiumoxide::Page> = HashMap::new();
        for act in &acts {
            let Some(sel) = act.selector() else { continue };
            let Some((label, _)) = split_frame_selector(sel) else {
                continue;
            };
            if let std::collections::hash_map::Entry::Vacant(slot) =
                frame_pages.entry(label.clone())
            {
                match self
                    .manager
                    .oopif_page_by_label(context.session_id, &label)
                    .await
                {
                    Ok(Some(p)) => {
                        slot.insert(p);
                    }
                    Ok(None) => {
                        return Ok(ToolResult::error(format!(
                            "Frame '{label}' not found. The frame may have navigated away — \
                             re-run `browser_find` to get a fresh inventory."
                        )));
                    }
                    Err(e) => {
                        return Ok(ToolResult::error(format!("Browser error: {e}")));
                    }
                }
            }
        }

        // ---- Pre-flight: one JS pass per page resolving ALL selectors ----
        // Group selector-having actions by their page (main or frame),
        // run the resolver, map failures back to action indices.
        let mut page_selectors: Vec<(Option<String>, Vec<usize>)> = Vec::new(); // (frame label, action idx)
        for (idx, act) in acts.iter().enumerate() {
            if let Some(sel) = act.selector() {
                let label = split_frame_selector(sel).map(|(l, _)| l);
                match page_selectors.iter_mut().find(|(l, _)| *l == label) {
                    Some((_, v)) => v.push(idx),
                    None => page_selectors.push((label, vec![idx])),
                }
            }
        }
        for (label, idxs) in &page_selectors {
            let page = match label {
                Some(l) => &frame_pages[l],
                None => main_page,
            };
            let selectors: Vec<String> = idxs
                .iter()
                .map(|&i| acts[i].selector().unwrap().to_string())
                .collect();
            let js = build_pre_flight_js(&selectors);
            let raw = match page.evaluate(js.as_str()).await {
                Ok(r) => r.value().cloned().unwrap_or(Value::Null),
                Err(e) => return Ok(ToolResult::error(format!("Pre-flight check failed: {e}"))),
            };
            if let Some(arr) = raw.as_array() {
                for entry in arr {
                    let local_i = entry["i"].as_u64().unwrap_or(0) as usize;
                    let ok = entry["ok"].as_bool().unwrap_or(false);
                    if !ok && local_i < idxs.len() {
                        let act_idx = idxs[local_i];
                        let reason = entry["reason"].as_str().unwrap_or("unresolved");
                        let sel = acts[act_idx].selector().unwrap_or("?");
                        return Ok(ToolResult::error(format!(
                            "Pre-flight rejected: action {} targets '{sel}' — {reason}. \
                             NOTHING executed. Re-run `browser_find` for a fresh inventory.",
                            act_idx + 1
                        )));
                    }
                }
            }
        }

        // ---- Execute in order; abort on first failure ----
        let mut done = 0usize;
        for act in &acts {
            let page_ref = match act.selector().and_then(split_frame_selector) {
                Some((label, _)) => &frame_pages[&label],
                None => main_page,
            };
            let outcome: std::result::Result<(), String> = match act {
                Act::Click { selector } => self.exec_click(page_ref, selector).await,
                Act::Fill { selector, text } => self.exec_fill(page_ref, selector, text).await,
                Act::Press { key } => page_ref
                    .press_key(key.as_str())
                    .await
                    .map(|_| ())
                    .map_err(|e| e.to_string()),
                Act::Select { selector, value } => {
                    self.exec_select(page_ref, selector, value).await
                }
                Act::Wait { ms } => {
                    tokio::time::sleep(std::time::Duration::from_millis(*ms)).await;
                    Ok(())
                }
            };
            match outcome {
                Ok(()) => done += 1,
                Err(e) => {
                    let report = format_prefix_report(done, act, &e);
                    self.manager
                        .reset_identical_screenshot_count(context.session_id)
                        .await;
                    let mut tr = ToolResult::error(super::events::append_line(
                        report,
                        self.manager.drain_recent_events(),
                    ));
                    self.manager
                        .attach_screenshot(context.session_id, &mut tr)
                        .await;
                    return Ok(tr);
                }
            }
        }

        // ---- Success: one screenshot, event line, summary ----
        self.manager
            .reset_identical_screenshot_count(context.session_id)
            .await;
        let summary = acts
            .iter()
            .map(|a| a.label())
            .collect::<Vec<_>>()
            .join(", ");
        let mut result = ToolResult::success(super::events::append_line(
            format!(
                "Executed {} action{} (one call): {summary}",
                acts.len(),
                if acts.len() == 1 { "" } else { "s" }
            ),
            self.manager.drain_recent_events(),
        ));
        self.manager
            .attach_screenshot(context.session_id, &mut result)
            .await;
        Ok(result)
    }
}

impl BrowserActTool {
    /// Click honoring the three selector shapes. CSS goes through
    /// find_element (CDP-level trusted click); text=/xpath= use the
    /// in-page evaluator — same split as browser_click.
    async fn exec_click(
        &self,
        page: &chromiumoxide::Page,
        selector: &str,
    ) -> std::result::Result<(), String> {
        let selector = selector.to_string(); // own for the JS builds below
        if let Some(text) = selector.strip_prefix("text=") {
            let escaped = text.replace('\\', "\\\\").replace('"', "\\\"");
            let js = format!(
                r#"
                (() => {{
                    const needle = "{escaped}".toLowerCase();
                    const walker = document.createTreeWalker(
                        document.body, NodeFilter.SHOW_ELEMENT);
                    let node;
                    while ((node = walker.nextNode())) {{
                        const t = (node.innerText || node.textContent || "").toLowerCase();
                        if (!t.includes(needle)) continue;
                        const r = node.getBoundingClientRect();
                        if (r.width === 0 || r.height === 0) continue;
                        node.scrollIntoView({{block: "center"}});
                        node.click();
                        return "ok";
                    }}
                    return "not_found";
                }})()
                "#
            );
            let r = page
                .evaluate(js.as_str())
                .await
                .map_err(|e| format!("text-click eval failed: {e}"))?;
            let v = r.value().and_then(|v| v.as_str().map(String::from));
            if v.as_deref() == Some("ok") {
                let _ = page
                    .wait_for_network_almost_idle_with_timeout(std::time::Duration::from_secs(3))
                    .await;
                Ok(())
            } else {
                Err(format!(
                    "no visible element matched text '{text}' (present during pre-flight; \
                     the view changed)"
                ))
            }
        } else if let Some(xpath) = selector.strip_prefix("xpath=") {
            let escaped = xpath.replace('\\', "\\\\").replace('"', "\\\"");
            let js = format!(
                r#"
                (() => {{
                    const it = document.evaluate("{escaped}", document, null,
                        XPathResult.FIRST_ORDERED_NODE_TYPE, null);
                    const node = it.singleNodeValue;
                    if (!node) return "not_found";
                    const r = node.getBoundingClientRect();
                    if (r.width === 0 || r.height === 0) return "not_visible";
                    node.scrollIntoView({{block: "center"}});
                    node.click();
                    return "ok";
                }})()
                "#
            );
            let r = page
                .evaluate(js.as_str())
                .await
                .map_err(|e| format!("xpath-click eval failed: {e}"))?;
            let v = r.value().and_then(|v| v.as_str().map(String::from));
            if v.as_deref() == Some("ok") {
                let _ = page
                    .wait_for_network_almost_idle_with_timeout(std::time::Duration::from_secs(3))
                    .await;
                Ok(())
            } else {
                Err(format!("xpath '{xpath}' no longer resolves"))
            }
        } else {
            // Plain CSS — CDP-level click like browser_click.
            let element = page
                .find_element(&selector)
                .await
                .map_err(|e| format!("element '{selector}' not found: {e}"))?;
            element
                .click()
                .await
                .map_err(|e| format!("click failed: {e}"))?;
            let _ = page
                .wait_for_network_almost_idle_with_timeout(std::time::Duration::from_secs(3))
                .await;
            Ok(())
        }
    }

    /// Framework-safe fill — the native-setter dance from browser_type.
    async fn exec_fill(
        &self,
        page: &chromiumoxide::Page,
        selector: &str,
        text: &str,
    ) -> std::result::Result<(), String> {
        let sel_js = serde_json::to_string(selector).unwrap_or_else(|_| "null".into());
        let val_js = serde_json::to_string(text).unwrap_or_else(|_| "\"\"".into());
        let js = format!(
            r#"(function(){{
  var sel = {sel_js};
  var val = {val_js};
  var el = sel ? document.querySelector(sel) : document.activeElement;
  if (!el) return "no_element";
  var editable = el.isContentEditable;
  if (el.value === undefined && !editable) return "not_input";
  try {{ el.focus(); }} catch (e) {{}}
  if (editable) {{
    el.textContent = val;
    el.dispatchEvent(new InputEvent("input", {{bubbles:true}}));
    el.dispatchEvent(new Event("change", {{bubbles:true}}));
    return "ok";
  }}
  var proto = el.tagName === "TEXTAREA"
    ? window.HTMLTextAreaElement.prototype
    : window.HTMLInputElement.prototype;
  var desc = Object.getOwnPropertyDescriptor(proto, "value");
  if (desc && desc.set) {{ desc.set.call(el, val); }} else {{ el.value = val; }}
  el.dispatchEvent(new Event("input", {{bubbles:true}}));
  el.dispatchEvent(new Event("change", {{bubbles:true}}));
  return "ok";
}})()"#
        );
        let r = page
            .evaluate(js.as_str())
            .await
            .map_err(|e| format!("fill eval failed: {e}"))?;
        let v = r.value().and_then(|v| v.as_str().map(String::from));
        match v.as_deref() {
            Some("ok") => Ok(()),
            Some("no_element") => Err(format!(
                "fill target '{selector}' disappeared (was present during pre-flight)"
            )),
            Some("not_input") => Err(format!("fill target '{selector}' is not an input")),
            _ => Err(format!("fill failed on '{selector}'")),
        }
    }

    /// Fresh `<select>` handling: set value + dispatch change.
    async fn exec_select(
        &self,
        page: &chromiumoxide::Page,
        selector: &str,
        value: &str,
    ) -> std::result::Result<(), String> {
        let sel_js = serde_json::to_string(selector).unwrap_or_else(|_| "null".into());
        let val_js = serde_json::to_string(value).unwrap_or_else(|_| "\"\"".into());
        let js = format!(
            r#"(function(){{
  var el = document.querySelector({sel_js});
  if (!el) return "no_element";
  if (el.tagName !== "SELECT") return "not_select";
  var val = {val_js};
  var opt = Array.prototype.find.call(el.options, function(o) {{
    return o.value === val || o.text === val;
  }});
  if (!opt) return "no_option";
  el.value = opt.value;
  el.dispatchEvent(new Event("input", {{bubbles:true}}));
  el.dispatchEvent(new Event("change", {{bubbles:true}}));
  return "ok";
}})()"#
        );
        let r = page
            .evaluate(js.as_str())
            .await
            .map_err(|e| format!("select eval failed: {e}"))?;
        let v = r.value().and_then(|v| v.as_str().map(String::from));
        match v.as_deref() {
            Some("ok") => Ok(()),
            Some("no_element") => Err(format!(
                "select target '{selector}' disappeared (was present during pre-flight)"
            )),
            Some("not_select") => Err(format!("select target '{selector}' is not a <select>")),
            Some("no_option") => Err(format!("no option matching '{value}' in '{selector}'")),
            _ => Err(format!("select failed on '{selector}'")),
        }
    }
}