chromewright 0.8.0

Browser automation MCP server via Chrome DevTools Protocol (CDP)
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
//! In-page script command model compiled from browser-kernel templates.
//!
//! Interaction, actionability, and selector-identity probes render once per command
//! and execute through the active CDP tab.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::OnceLock;

const BROWSER_KERNEL_JS: &str = include_str!("../tools/browser_kernel.js");
const ACTIONABILITY_PROBE_TEMPLATE_JS: &str = include_str!("../tools/actionability_probe.js");
const SELECTOR_IDENTITY_TEMPLATE_JS: &str = r#"
(() => {
  const config = __SELECTOR_IDENTITY_CONFIG__;

  __BROWSER_KERNEL__

  function countSelectorMatchesAcrossScopes(selector) {
    const visitedDocs = new Set();
    let count = 0;

    function searchRoot(root) {
      if (!root || typeof root.querySelectorAll !== 'function') {
        return;
      }

      let matches = [];
      try {
        matches = root.querySelectorAll(selector);
      } catch (error) {
        const normalized = normalizeSimpleIdSelector(selector);
        if (!normalized) {
          return;
        }

        try {
          matches = root.querySelectorAll(normalized);
        } catch (fallbackError) {
          return;
        }
      }

      count += matches.length;
      if (count > 1) {
        return;
      }

      const elements = root.querySelectorAll ? root.querySelectorAll('*') : [];
      for (const element of elements) {
        if (element.shadowRoot) {
          searchRoot(element.shadowRoot);
          if (count > 1) {
            return;
          }
        }

        if (element.tagName === 'IFRAME') {
          try {
            const frameDoc = element.contentDocument;
            if (!frameDoc || visitedDocs.has(frameDoc)) {
              continue;
            }

            visitedDocs.add(frameDoc);
            searchRoot(frameDoc);
            if (count > 1) {
              return;
            }
          } catch (error) {
            // Cross-origin frame; selector identity stops at the iframe boundary.
          }
        }
      }
    }

    visitedDocs.add(document);
    searchRoot(document);
    return count;
  }

  const matchCount = config.selector ? countSelectorMatchesAcrossScopes(config.selector) : 0;

  return JSON.stringify({
    present: matchCount > 0,
    unique: matchCount === 1
  });
})()
"#;
const CLICK_TEMPLATE_JS: &str = include_str!("../tools/click.js");
const INPUT_TEMPLATE_JS: &str = include_str!("../tools/input.js");
const HOVER_TEMPLATE_JS: &str = include_str!("../tools/hover.js");
const SELECT_TEMPLATE_JS: &str = include_str!("../tools/select.js");

static ACTIONABILITY_PROBE_SHELL: OnceLock<BrowserCommandTemplateShell> = OnceLock::new();
static SELECTOR_IDENTITY_SHELL: OnceLock<BrowserCommandTemplateShell> = OnceLock::new();
static CLICK_SHELL: OnceLock<BrowserCommandTemplateShell> = OnceLock::new();
static INPUT_SHELL: OnceLock<BrowserCommandTemplateShell> = OnceLock::new();
static HOVER_SHELL: OnceLock<BrowserCommandTemplateShell> = OnceLock::new();
static SELECT_SHELL: OnceLock<BrowserCommandTemplateShell> = OnceLock::new();

struct BrowserCommandTemplateShell {
    prefix: String,
    suffix: String,
}

impl BrowserCommandTemplateShell {
    fn compile(template: &'static str, config_placeholder: &'static str) -> Self {
        let expanded = template.replace("__BROWSER_KERNEL__", BROWSER_KERNEL_JS);
        let mut parts = expanded.split(config_placeholder);
        let prefix = parts
            .next()
            .expect("expanded browser-command template should have a prefix");
        let suffix = parts
            .next()
            .expect("browser-command template must contain exactly one config placeholder");
        assert!(
            parts.next().is_none(),
            "browser-command template must contain exactly one config placeholder"
        );

        Self {
            prefix: prefix.to_string(),
            suffix: suffix.to_string(),
        }
    }

    fn render(&self, config: &Value) -> String {
        let config_json = config.to_string();
        let mut rendered =
            String::with_capacity(self.prefix.len() + config_json.len() + self.suffix.len());
        rendered.push_str(&self.prefix);
        rendered.push_str(&config_json);
        rendered.push_str(&self.suffix);
        rendered
    }
}

fn render_command_script(
    shell_cache: &OnceLock<BrowserCommandTemplateShell>,
    template: &'static str,
    config_placeholder: &'static str,
    config: &Value,
) -> String {
    shell_cache
        .get_or_init(|| BrowserCommandTemplateShell::compile(template, config_placeholder))
        .render(config)
}

/// In-page command compiled from browser-kernel templates and executed via CDP evaluation.
///
/// Probes are idempotent reads used for waits and selector identity; interactions mutate the
/// page and always invalidate follow-up snapshot assumptions at the session layer.
#[derive(Debug, Clone)]
pub(crate) enum BrowserCommand {
    /// Read-only actionability predicates for a selector (present, visible, enabled, …).
    ActionabilityProbe(ActionabilityProbeRequest),
    /// Read-only check whether a selector matches zero, one, or many nodes across scopes.
    SelectorIdentityProbe(SelectorIdentityProbeRequest),
    /// Click, input, hover, or select mutation against a targeted element.
    Interaction(InteractionCommand),
}

impl BrowserCommand {
    /// Stable capability id used in metrics and [`BrowserError::BackendUnsupported`] payloads.
    pub(crate) fn capability(&self) -> &'static str {
        match self {
            Self::ActionabilityProbe(_) => "actionability_probe",
            Self::SelectorIdentityProbe(_) => "selector_identity_probe",
            Self::Interaction(command) => command.capability(),
        }
    }

    /// Stable operation id for this command (mirrors capability for probes; interaction name for mutations).
    pub(crate) fn operation(&self) -> &'static str {
        match self {
            Self::ActionabilityProbe(_) => "actionability_probe",
            Self::SelectorIdentityProbe(_) => "selector_identity_probe",
            Self::Interaction(command) => command.operation(),
        }
    }

    /// True for read-only probes; false for interactions that may mutate the page.
    ///
    /// Non-idempotent commands must not be auto-replayed during connection recovery.
    pub(crate) fn is_idempotent(&self) -> bool {
        match self {
            Self::ActionabilityProbe(_) | Self::SelectorIdentityProbe(_) => true,
            Self::Interaction(_) => false,
        }
    }

    /// Render the in-page JavaScript by injecting JSON config into the compiled browser-kernel template.
    pub(crate) fn render_script(&self) -> String {
        match self {
            Self::ActionabilityProbe(request) => {
                let config = serde_json::json!({
                    "selector": request.selector,
                    "target_index": request.target_index,
                    "predicates": request
                        .predicates
                        .iter()
                        .map(|predicate| predicate.key())
                        .collect::<Vec<_>>(),
                    "text": request.expected_text,
                    "value": request.expected_value,
                });
                render_command_script(
                    &ACTIONABILITY_PROBE_SHELL,
                    ACTIONABILITY_PROBE_TEMPLATE_JS,
                    "__ACTIONABILITY_CONFIG__",
                    &config,
                )
            }
            Self::SelectorIdentityProbe(request) => {
                let config = serde_json::json!({ "selector": request.selector });
                render_command_script(
                    &SELECTOR_IDENTITY_SHELL,
                    SELECTOR_IDENTITY_TEMPLATE_JS,
                    "__SELECTOR_IDENTITY_CONFIG__",
                    &config,
                )
            }
            Self::Interaction(command) => command.render_script(),
        }
    }
}

/// Discriminated result of a [`BrowserCommand`] after in-page script execution.
#[derive(Debug, Clone)]
pub(crate) enum BrowserCommandResult {
    /// Outcomes for present/visible/enabled and related wait predicates.
    ActionabilityProbe(ActionabilityProbeResult),
    /// Present + unique match counts for a CSS selector across resolvable scopes.
    SelectorIdentityProbe(SelectorIdentityProbeResult),
    /// Click/input/hover/select mutation result from browser-kernel scripts.
    Interaction(InteractionCommandResult),
}

/// In-page actionability probe: selector, optional index, and predicates to evaluate.
#[derive(Debug, Clone)]
pub(crate) struct ActionabilityProbeRequest {
    /// CSS selector resolved across light DOM, shadow roots, and same-origin frames.
    pub selector: String,
    /// Optional interactive-index disambiguation when multiple matches exist.
    pub target_index: Option<usize>,
    /// Predicates to evaluate; omitted fields in the result stay `None`.
    pub predicates: Vec<ActionabilityPredicate>,
    /// Expected substring for [`ActionabilityPredicate::TextContains`].
    pub expected_text: Option<String>,
    /// Expected form value for [`ActionabilityPredicate::ValueEquals`].
    pub expected_value: Option<String>,
}

/// Named actionability checks aligned with Playwright-style wait preconditions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum ActionabilityPredicate {
    /// At least one matching element exists in resolvable document scopes.
    Present,
    /// Element has a non-zero layout box and is not `visibility: hidden`.
    Visible,
    /// Element is not disabled for pointer/keyboard interaction.
    Enabled,
    /// Element accepts text input (contenteditable or form control).
    Editable,
    /// Layout geometry is stable across consecutive samples.
    Stable,
    /// Element can receive pointer events (not fully blocked by ancestors).
    ReceivesEvents,
    /// Any part of the element intersects the current viewport.
    InViewport,
    /// Center point hit-tests back to the element (not covered by overlay).
    UnobscuredCenter,
    /// Accessible or text content contains the expected substring.
    TextContains,
    /// Form control value equals the expected string.
    ValueEquals,
}

impl ActionabilityPredicate {
    /// Wire key embedded in the probe config JSON consumed by the in-page script.
    pub(crate) const fn key(self) -> &'static str {
        match self {
            ActionabilityPredicate::Present => "present",
            ActionabilityPredicate::Visible => "visible",
            ActionabilityPredicate::Enabled => "enabled",
            ActionabilityPredicate::Editable => "editable",
            ActionabilityPredicate::Stable => "stable",
            ActionabilityPredicate::ReceivesEvents => "receives_events",
            ActionabilityPredicate::InViewport => "in_viewport",
            ActionabilityPredicate::UnobscuredCenter => "unobscured_center",
            ActionabilityPredicate::TextContains => "text_contains",
            ActionabilityPredicate::ValueEquals => "value_equals",
        }
    }
}

/// Predicate outcomes from an actionability probe; optional fields track requested predicates only.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub(crate) struct ActionabilityProbeResult {
    /// Always populated: whether any match was found for the selector/index.
    pub present: bool,
    /// Layout visibility when that predicate was requested.
    pub visible: Option<bool>,
    /// Enabled state when that predicate was requested.
    pub enabled: Option<bool>,
    /// Editable state when that predicate was requested.
    pub editable: Option<bool>,
    /// Geometry stability when that predicate was requested.
    pub stable: Option<bool>,
    /// Pointer-event readiness when that predicate was requested.
    pub receives_events: Option<bool>,
    /// Viewport intersection when that predicate was requested.
    pub in_viewport: Option<bool>,
    /// Center hit-test when that predicate was requested.
    pub unobscured_center: Option<bool>,
    /// Text-contains match when that predicate was requested.
    pub text_contains: Option<bool>,
    /// Value-equals match when that predicate was requested.
    pub value_equals: Option<bool>,
    /// Nesting depth of the frame that resolved the target, when known.
    pub frame_depth: Option<usize>,
    /// Extra hit-test and text diagnostics for failed waits.
    pub diagnostics: Option<ActionabilityDiagnostics>,
}

/// Supplemental hit-test and content details attached to a failed or partial probe.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub(crate) struct ActionabilityDiagnostics {
    /// Computed `pointer-events` CSS value when collected.
    pub pointer_events: Option<String>,
    /// Element under the pointer at the target center, when hit-testing ran.
    pub hit_target: Option<ActionabilityElementSummary>,
    /// Length of accessible/text content when text predicates ran.
    pub text_length: Option<usize>,
    /// Whether the control currently has a non-empty value.
    pub has_value: Option<bool>,
}

/// Compact DOM identity summary used in actionability diagnostics.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub(crate) struct ActionabilityElementSummary {
    /// Lowercase HTML tag name.
    pub tag: String,
    /// Author `id` when present.
    pub id: Option<String>,
    /// Class tokens for the element.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub classes: Vec<String>,
}

impl ActionabilityProbeResult {
    /// Read one predicate outcome; `None` when that predicate was not requested by the probe.
    pub(crate) fn predicate(&self, predicate: ActionabilityPredicate) -> Option<bool> {
        match predicate {
            ActionabilityPredicate::Present => Some(self.present),
            ActionabilityPredicate::Visible => self.visible,
            ActionabilityPredicate::Enabled => self.enabled,
            ActionabilityPredicate::Editable => self.editable,
            ActionabilityPredicate::Stable => self.stable,
            ActionabilityPredicate::ReceivesEvents => self.receives_events,
            ActionabilityPredicate::InViewport => self.in_viewport,
            ActionabilityPredicate::UnobscuredCenter => self.unobscured_center,
            ActionabilityPredicate::TextContains => self.text_contains,
            ActionabilityPredicate::ValueEquals => self.value_equals,
        }
    }
}

/// Request to count selector matches across light DOM, shadow roots, and same-origin frames.
#[derive(Debug, Clone)]
pub(crate) struct SelectorIdentityProbeRequest {
    /// CSS selector whose match count is measured across resolvable scopes.
    pub selector: String,
}

/// Whether a selector is present and uniquely resolves to a single node.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub(crate) struct SelectorIdentityProbeResult {
    /// At least one match exists in a resolvable scope.
    pub present: bool,
    /// `true` only when exactly one match exists across resolvable scopes.
    pub unique: bool,
}

/// Mutation command that performs a user-facing interaction through browser-kernel scripts.
#[derive(Debug, Clone)]
pub(crate) enum InteractionCommand {
    /// Activate an element after resolution (click).
    Click(TargetedInteractionRequest),
    /// Type into a control, optionally clearing first.
    Input(InputInteractionRequest),
    /// Move the pointer over a target without activating it.
    Hover(TargetedInteractionRequest),
    /// Choose an option on a select control by value.
    Select(SelectInteractionRequest),
}

impl InteractionCommand {
    fn capability(&self) -> &'static str {
        match self {
            Self::Click(_) => "click",
            Self::Input(_) => "input",
            Self::Hover(_) => "hover",
            Self::Select(_) => "select",
        }
    }

    fn operation(&self) -> &'static str {
        self.capability()
    }

    fn render_script(&self) -> String {
        match self {
            Self::Click(request) => render_interaction_script(
                &CLICK_SHELL,
                CLICK_TEMPLATE_JS,
                "__CLICK_CONFIG__",
                &request.config(),
            ),
            Self::Input(request) => render_interaction_script(
                &INPUT_SHELL,
                INPUT_TEMPLATE_JS,
                "__INPUT_CONFIG__",
                &serde_json::json!({
                    "selector": request.target.selector,
                    "target_index": request.target.target_index,
                    "text": request.text,
                    "clear": request.clear,
                }),
            ),
            Self::Hover(request) => render_interaction_script(
                &HOVER_SHELL,
                HOVER_TEMPLATE_JS,
                "__HOVER_CONFIG__",
                &request.config(),
            ),
            Self::Select(request) => render_interaction_script(
                &SELECT_SHELL,
                SELECT_TEMPLATE_JS,
                "__SELECT_CONFIG__",
                &serde_json::json!({
                    "selector": request.target.selector,
                    "target_index": request.target.target_index,
                    "value": request.value,
                }),
            ),
        }
    }
}

fn render_interaction_script(
    shell_cache: &OnceLock<BrowserCommandTemplateShell>,
    template: &'static str,
    config_placeholder: &'static str,
    config: &Value,
) -> String {
    render_command_script(shell_cache, template, config_placeholder, config)
}

/// Selector plus optional interactive index shared by click, hover, input, and select.
#[derive(Debug, Clone)]
pub(crate) struct TargetedInteractionRequest {
    /// CSS selector resolved across light DOM, shadow roots, and same-origin frames.
    pub selector: String,
    /// Disambiguates among multiple matches when the interactive index is known.
    pub target_index: Option<usize>,
}

impl TargetedInteractionRequest {
    fn config(&self) -> Value {
        serde_json::json!({
            "selector": self.selector,
            "target_index": self.target_index,
        })
    }
}

/// Text input interaction, optionally clearing the control before typing.
#[derive(Debug, Clone)]
pub(crate) struct InputInteractionRequest {
    /// Selector/index target for the control.
    pub target: TargetedInteractionRequest,
    /// Text to insert into the control.
    pub text: String,
    /// When true, clear existing value before inserting `text`.
    pub clear: bool,
}

/// Select an option by value on a `<select>` or equivalent control.
#[derive(Debug, Clone)]
pub(crate) struct SelectInteractionRequest {
    /// Selector/index target for the select control.
    pub target: TargetedInteractionRequest,
    /// Option value to select.
    pub value: String,
}

/// Outcome of a mutating interaction command after browser-kernel execution.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) enum InteractionCommandResult {
    /// Click activation outcome.
    Click(ActionCommandResult),
    /// Input/typing outcome with optional post-value.
    Input(InputCommandResult),
    /// Hover outcome with optional hit element identity.
    Hover(HoverCommandResult),
    /// Select outcome with chosen value/label.
    Select(SelectCommandResult),
}

/// Generic success/error payload shared by click-style actions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct ActionCommandResult {
    /// Whether the in-page script completed the action successfully.
    pub success: bool,
    /// Stable machine code when the script reports a known failure mode.
    #[serde(default)]
    pub code: Option<String>,
    /// Human-readable failure detail from the browser-kernel script.
    #[serde(default)]
    pub error: Option<String>,
}

/// Input interaction result including the control value after typing when available.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct InputCommandResult {
    /// Whether typing completed successfully.
    pub success: bool,
    /// Stable machine code when the script reports a known failure mode.
    #[serde(default)]
    pub code: Option<String>,
    /// Human-readable failure detail from the browser-kernel script.
    #[serde(default)]
    pub error: Option<String>,
    /// Control value observed after the input script completes.
    #[serde(default)]
    pub value: Option<String>,
}

/// Hover result with optional DOM identity of the element under the pointer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct HoverCommandResult {
    /// Whether the hover completed successfully.
    pub success: bool,
    /// Stable machine code when the script reports a known failure mode.
    #[serde(default)]
    pub code: Option<String>,
    /// Human-readable failure detail from the browser-kernel script.
    #[serde(default)]
    pub error: Option<String>,
    /// Tag name of the element under the pointer after hover, when reported.
    #[serde(default, rename = "tagName")]
    pub tag_name: Option<String>,
    /// Element `id` under the pointer, when reported.
    #[serde(default)]
    pub id: Option<String>,
    /// Element `className` under the pointer, when reported.
    #[serde(default, rename = "className")]
    pub class_name: Option<String>,
}

/// Select interaction result with the chosen option value and visible label.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct SelectCommandResult {
    /// Whether the option was selected successfully.
    pub success: bool,
    /// Stable machine code when the script reports a known failure mode.
    #[serde(default)]
    pub code: Option<String>,
    /// Human-readable failure detail from the browser-kernel script.
    #[serde(default)]
    pub error: Option<String>,
    /// Option `value` after selection, when reported.
    #[serde(default, rename = "selectedValue")]
    pub selected_value: Option<String>,
    /// Visible option label after selection, when reported.
    #[serde(default, rename = "selectedText")]
    pub selected_text: Option<String>,
}

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

    #[test]
    fn actionability_command_renders_existing_probe_template() {
        let script = BrowserCommand::ActionabilityProbe(ActionabilityProbeRequest {
            selector: "#save".to_string(),
            target_index: Some(1),
            predicates: vec![
                ActionabilityPredicate::Present,
                ActionabilityPredicate::Visible,
            ],
            expected_text: None,
            expected_value: None,
        })
        .render_script();

        assert!(script.contains("function resolveTargetMatch(config, options)"));
        assert!(script.contains("\"selector\":\"#save\""));
        assert!(script.contains("\"target_index\":1"));
        assert!(script.contains("\"predicates\":[\"present\",\"visible\"]"));
    }

    #[test]
    fn selector_identity_command_renders_cross_scope_probe() {
        let script = BrowserCommand::SelectorIdentityProbe(SelectorIdentityProbeRequest {
            selector: "#save".to_string(),
        })
        .render_script();

        assert!(script.contains("function countSelectorMatchesAcrossScopes(selector)"));
        assert!(script.contains("normalizeSimpleIdSelector(selector)"));
        assert!(script.contains("\"selector\":\"#save\""));
    }

    #[test]
    fn interaction_commands_render_existing_templates() {
        let target = TargetedInteractionRequest {
            selector: "#save".to_string(),
            target_index: Some(1),
        };
        let click =
            BrowserCommand::Interaction(InteractionCommand::Click(target.clone())).render_script();
        let input =
            BrowserCommand::Interaction(InteractionCommand::Input(InputInteractionRequest {
                target: target.clone(),
                text: "hello".to_string(),
                clear: true,
            }))
            .render_script();
        let hover =
            BrowserCommand::Interaction(InteractionCommand::Hover(target.clone())).render_script();
        let select =
            BrowserCommand::Interaction(InteractionCommand::Select(SelectInteractionRequest {
                target,
                value: "choice".to_string(),
            }))
            .render_script();

        assert!(click.contains("const element = resolveTargetElement(config);"));
        assert!(click.contains("searchActionableIndex(config.target_index)"));
        assert!(input.contains("\"text\":\"hello\""));
        assert!(input.contains("\"clear\":true"));
        assert!(hover.contains("const element = resolveTargetElement(config);"));
        assert!(select.contains("\"value\":\"choice\""));
    }

    #[test]
    fn probes_are_idempotent_but_interactions_are_not() {
        let target = TargetedInteractionRequest {
            selector: "#save".to_string(),
            target_index: Some(1),
        };

        assert!(
            BrowserCommand::ActionabilityProbe(ActionabilityProbeRequest {
                selector: "#save".to_string(),
                target_index: Some(1),
                predicates: vec![ActionabilityPredicate::Present],
                expected_text: None,
                expected_value: None,
            })
            .is_idempotent()
        );
        assert!(
            BrowserCommand::SelectorIdentityProbe(SelectorIdentityProbeRequest {
                selector: "#save".to_string(),
            })
            .is_idempotent()
        );

        for interaction in [
            InteractionCommand::Click(target.clone()),
            InteractionCommand::Input(InputInteractionRequest {
                target: target.clone(),
                text: "hi".to_string(),
                clear: false,
            }),
            InteractionCommand::Hover(target.clone()),
            InteractionCommand::Select(SelectInteractionRequest {
                target: target.clone(),
                value: "choice".to_string(),
            }),
        ] {
            assert!(
                !BrowserCommand::Interaction(interaction).is_idempotent(),
                "interaction commands must be non-idempotent"
            );
        }
    }
}