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
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
//! Interaction target resolution, actionability polling, and post-action handoff envelopes.
//!
//! Interaction tools fail closed on stale cursors ([`StaleCursorPolicy::DenyRebind`]) so
//! agents re-snapshot rather than act on an ambiguous selector rebound. After mutations,
//! handoffs refresh the DOM and classify target continuity (`same` / `rebound` / `detached` /
//! `unknown`).

use crate::browser::BrowserSession;
use crate::browser::commands::{
    BrowserCommand, BrowserCommandResult, SelectorIdentityProbeRequest, SelectorIdentityProbeResult,
};
pub use crate::contract::TargetStatus;
use crate::dom::{Cursor, DocumentMetadata, DomTree, NodeRef};
use crate::error::{BrowserError, Result};
use crate::tools::core::structured_tool_failure;
use crate::tools::{
    ResolvedTarget, StaleCursorPolicy, TargetEnvelope, TargetResolution, ToolContext, ToolResult,
    actionability::{
        ActionabilityDiagnostics, ActionabilityPredicate, ActionabilityProbeResult,
        ActionabilityRequest, probe_actionability,
    },
    browser_kernel::render_browser_kernel_script,
    duration_micros, resolve_target_with_cursor,
};
use std::sync::OnceLock;
use std::time::{Duration, Instant};

const SCROLL_TARGET_INTO_VIEW_TEMPLATE_JS: &str = include_str!("../scroll_target_into_view.js");
static SCROLL_TARGET_INTO_VIEW_SHELL: OnceLock<
    crate::tools::browser_kernel::BrowserKernelTemplateShell,
> = OnceLock::new();

/// Default actionability poll budget used by click/input and similar interactions.
pub(crate) const DEFAULT_ACTIONABILITY_TIMEOUT_MS: u64 = 5_000;
const ACTIONABILITY_POLL_INTERVAL_MS: u64 = 50;

/// Terminal state of an actionability poll loop.
pub(crate) enum ActionabilityWaitState {
    /// All requested predicates held true within the timeout.
    Ready,
    /// Budget exhausted; last probe is retained for structured failure diagnostics.
    TimedOut(ActionabilityProbeResult),
}

/// Post-action document envelope pieces: refreshed revision plus target continuity status.
///
/// Built after a mutating interaction so agents can decide whether to reuse handles or
/// re-snapshot. `target_after` may be omitted when the element is detached or ambiguous.
pub(crate) struct InteractionHandoff {
    /// Document metadata after DOM refresh (new revision when the page mutated).
    pub document: DocumentMetadata,
    /// Target envelope captured before the action.
    pub target_before: TargetEnvelope,
    /// Best-effort post-action target when still uniquely resolvable.
    pub target_after: Option<TargetEnvelope>,
    /// Continuity classification for the handle across the mutation.
    pub target_status: TargetStatus,
}

/// Resolve a click/input-style target, denying selector rebound on stale cursors.
///
/// Interaction tools fail closed on revision mismatch so agents re-snapshot rather than
/// acting on an ambiguous rebound.
pub(crate) fn resolve_interaction_target(
    tool: &str,
    selector: Option<String>,
    index: Option<usize>,
    node_ref: Option<NodeRef>,
    cursor: Option<Cursor>,
    context: &mut ToolContext,
) -> Result<TargetResolution> {
    let dom = Some(context.get_dom()?);
    resolve_target_with_cursor(
        tool,
        selector,
        index,
        node_ref,
        cursor,
        dom,
        StaleCursorPolicy::DenyRebind,
    )
}

/// Poll actionability predicates until ready, optionally scrolling the target into view.
///
/// When receives-events / unobscured-center predicates need viewport locality and the
/// probe reports present-but-out-of-viewport, scrolls into view between poll ticks.
/// Records poll iterations and browser evaluations on [`ToolContext`]. Does not return a
/// soft failure on timeout—callers map [`ActionabilityWaitState::TimedOut`] themselves.
pub(crate) fn wait_for_actionability(
    context: &mut ToolContext,
    target: &ResolvedTarget,
    predicates: &[ActionabilityPredicate],
    timeout_ms: u64,
) -> Result<ActionabilityWaitState> {
    let start = Instant::now();
    let timeout = Duration::from_millis(timeout_ms);
    let requested_predicates = requested_actionability_predicates(predicates);

    loop {
        context.record_poll_iteration();
        context.record_browser_evaluation();
        let probe = probe_actionability(
            context.session,
            &ActionabilityRequest {
                selector: &target.selector,
                target_index: target.browser_command_target_index(),
                predicates: requested_predicates.as_slice(),
                expected_text: None,
                expected_value: None,
            },
        )?;

        if should_scroll_target_into_view(&probe, predicates) {
            scroll_target_into_view(context, target)?;
            std::thread::sleep(Duration::from_millis(ACTIONABILITY_POLL_INTERVAL_MS));
            continue;
        }

        if predicates
            .iter()
            .all(|predicate| probe.predicate(*predicate) == Some(true))
        {
            return Ok(ActionabilityWaitState::Ready);
        }

        if start.elapsed() >= timeout {
            return Ok(ActionabilityWaitState::TimedOut(probe));
        }

        std::thread::sleep(Duration::from_millis(ACTIONABILITY_POLL_INTERVAL_MS));
    }
}

/// Refresh the DOM after a mutation and classify target continuity (same / moved / detached).
pub(crate) fn build_interaction_handoff(
    context: &mut ToolContext,
    target_before: &ResolvedTarget,
) -> Result<InteractionHandoff> {
    let started = Instant::now();
    let target_before_envelope = target_before.to_target_envelope();
    let (current_document, actionable_matches) = {
        let dom = context.refresh_dom()?;
        (
            dom.document.clone(),
            actionable_targets_for_selector(dom, &target_before.selector),
        )
    };

    let (target_after, target_status) = determine_target_after(
        context,
        target_before,
        &current_document,
        actionable_matches,
    )?;
    context.record_handoff_rebuild_micros(duration_micros(started.elapsed()));

    Ok(InteractionHandoff {
        document: current_document,
        target_before: target_before_envelope,
        target_after,
        target_status,
    })
}

/// Structured failure from a timed-out or failed actionability probe, with recovery hints.
pub(crate) fn build_actionability_failure(
    tool: &str,
    session: &BrowserSession,
    target: &ResolvedTarget,
    probe: &ActionabilityProbeResult,
    predicates: &[ActionabilityPredicate],
    override_code: Option<&str>,
) -> Result<ToolResult> {
    let failed_predicates = failed_predicates(probe, predicates);
    let (default_code, error) = classify_actionability_failure(probe, predicates);
    build_interaction_failure(
        tool,
        session,
        target,
        override_code.unwrap_or(default_code).to_string(),
        error,
        failed_predicates,
        probe.diagnostics.clone(),
    )
}

/// Shared structured interaction failure (code, failed predicates, diagnostics, suggested tool).
pub(crate) fn build_interaction_failure(
    _tool: &str,
    session: &BrowserSession,
    target: &ResolvedTarget,
    code: String,
    error: String,
    failed_predicates: Vec<String>,
    diagnostics: Option<ActionabilityDiagnostics>,
) -> Result<ToolResult> {
    let current_document = session.document_metadata()?;
    let suggested_tool = if code == "target_detached" {
        "snapshot"
    } else {
        "inspect_node"
    };

    Ok(structured_tool_failure(
        code,
        error,
        Some(current_document),
        Some(target.to_target_envelope()),
        Some(serde_json::json!({
            "suggested_tool": suggested_tool,
        })),
        Some(serde_json::json!({
            "failed_predicates": failed_predicates,
            "diagnostics": diagnostics,
        })),
    ))
}

/// Parse a browser action result that may arrive as a JSON string or a structured value.
pub(crate) fn decode_action_result(
    value: Option<serde_json::Value>,
    fallback: serde_json::Value,
) -> Result<serde_json::Value> {
    if let Some(serde_json::Value::String(json_str)) = value {
        serde_json::from_str(&json_str).map_err(BrowserError::from)
    } else {
        Ok(value.unwrap_or(fallback))
    }
}

fn requested_actionability_predicates(
    predicates: &[ActionabilityPredicate],
) -> Vec<ActionabilityPredicate> {
    let mut requested = predicates.to_vec();
    if predicates_require_viewport_scroll(predicates)
        && !requested.contains(&ActionabilityPredicate::InViewport)
    {
        requested.push(ActionabilityPredicate::InViewport);
    }
    requested
}

fn predicates_require_viewport_scroll(predicates: &[ActionabilityPredicate]) -> bool {
    predicates.iter().any(|predicate| {
        matches!(
            predicate,
            ActionabilityPredicate::ReceivesEvents | ActionabilityPredicate::UnobscuredCenter
        )
    })
}

fn should_scroll_target_into_view(
    probe: &ActionabilityProbeResult,
    predicates: &[ActionabilityPredicate],
) -> bool {
    predicates_require_viewport_scroll(predicates)
        && probe.present
        && probe.visible != Some(false)
        && probe.in_viewport == Some(false)
}

fn scroll_target_into_view(context: &mut ToolContext, target: &ResolvedTarget) -> Result<()> {
    let config = serde_json::json!({
        "selector": target.selector,
        "target_index": target.browser_command_target_index(),
    });
    let scroll_js = build_scroll_target_into_view_js(&config);
    context.record_browser_evaluation();
    context
        .session
        .evaluate(&scroll_js, false)
        .map_err(|e| match e {
            BrowserError::EvaluationFailed(reason) => BrowserError::ToolExecutionFailed {
                tool: "interaction".to_string(),
                reason,
            },
            other => other,
        })?;
    Ok(())
}

fn failed_predicates(
    probe: &ActionabilityProbeResult,
    predicates: &[ActionabilityPredicate],
) -> Vec<String> {
    let mut failures = predicates
        .iter()
        .filter(|predicate| probe.predicate(**predicate) != Some(true))
        .map(|predicate| predicate.key().to_string())
        .collect::<Vec<_>>();

    if !probe.present && !failures.iter().any(|predicate| predicate == "present") {
        failures.insert(0, "present".to_string());
    }

    failures
}

fn classify_actionability_failure(
    probe: &ActionabilityProbeResult,
    predicates: &[ActionabilityPredicate],
) -> (&'static str, String) {
    if !probe.present {
        return ("target_detached", "Target is no longer present".to_string());
    }

    for predicate in predicates {
        match predicate {
            ActionabilityPredicate::Visible if probe.visible == Some(false) => {
                return ("target_not_visible", "Target is not visible".to_string());
            }
            ActionabilityPredicate::Enabled if probe.enabled == Some(false) => {
                return ("target_not_enabled", "Target is not enabled".to_string());
            }
            ActionabilityPredicate::Editable if probe.editable == Some(false) => {
                return ("target_not_editable", "Target is not editable".to_string());
            }
            ActionabilityPredicate::Stable if probe.stable == Some(false) => {
                return (
                    "target_not_stable",
                    "Target is not stable enough to interact with".to_string(),
                );
            }
            ActionabilityPredicate::ReceivesEvents if probe.receives_events == Some(false) => {
                return (
                    "target_obscured",
                    "Target is not receiving events".to_string(),
                );
            }
            ActionabilityPredicate::UnobscuredCenter if probe.unobscured_center == Some(false) => {
                return (
                    "target_obscured",
                    "Target is obscured at its interaction point".to_string(),
                );
            }
            _ => {}
        }
    }

    (
        "target_not_stable",
        "Target did not become ready within the bounded auto-wait window".to_string(),
    )
}

fn actionable_targets_for_selector(dom: &DomTree, selector: &str) -> Vec<Cursor> {
    dom.cursors_for_selector(selector)
}

fn determine_target_after(
    context: &mut ToolContext,
    target_before: &ResolvedTarget,
    current_document: &DocumentMetadata,
    actionable_matches: Vec<Cursor>,
) -> Result<(Option<TargetEnvelope>, TargetStatus)> {
    if actionable_matches.len() > 1 {
        return Ok((None, TargetStatus::Unknown));
    }

    if let Some(cursor) = actionable_matches.into_iter().next() {
        let after_target = target_envelope_from_cursor(cursor);
        let status = classify_target_status(target_before, current_document, &after_target);
        return Ok((Some(after_target), status));
    }

    let identity = probe_selector_identity(context, &target_before.selector)?;
    if !identity.present {
        return Ok((None, TargetStatus::Detached));
    }

    if !identity.unique {
        return Ok((None, TargetStatus::Unknown));
    }

    let after_target = selector_target_envelope(&target_before.selector);
    let status = classify_target_status(target_before, current_document, &after_target);
    Ok((Some(after_target), status))
}

fn target_envelope_from_cursor(cursor: Cursor) -> TargetEnvelope {
    TargetEnvelope {
        method: "cursor".to_string(),
        resolution_status: "exact".to_string(),
        recovered_from: None,
        selector: Some(cursor.selector.clone()),
        index: Some(cursor.index),
        node_ref: Some(cursor.node_ref.clone()),
        cursor: Some(cursor),
    }
}

fn selector_target_envelope(selector: &str) -> TargetEnvelope {
    TargetEnvelope {
        method: "css".to_string(),
        resolution_status: "exact".to_string(),
        recovered_from: None,
        cursor: None,
        node_ref: None,
        selector: Some(selector.to_string()),
        index: None,
    }
}

fn classify_target_status(
    target_before: &ResolvedTarget,
    current_document: &DocumentMetadata,
    after_target: &TargetEnvelope,
) -> TargetStatus {
    let before_node_ref = target_before
        .cursor
        .as_ref()
        .map(|cursor| &cursor.node_ref)
        .or(target_before.node_ref.as_ref());

    let Some(before_node_ref) = before_node_ref else {
        return TargetStatus::Unknown;
    };

    if before_node_ref.document_id != current_document.document_id {
        return TargetStatus::Unknown;
    }

    if before_node_ref.revision == current_document.revision {
        return match after_target.node_ref.as_ref() {
            Some(after_node_ref) if after_node_ref == before_node_ref => TargetStatus::Same,
            Some(_) => TargetStatus::Unknown,
            None => TargetStatus::Same,
        };
    }

    TargetStatus::Rebound
}

fn probe_selector_identity(
    context: &mut ToolContext,
    selector: &str,
) -> Result<SelectorIdentityProbeResult> {
    context.record_browser_evaluation();
    let result = context
        .session
        .execute_command(BrowserCommand::SelectorIdentityProbe(
            SelectorIdentityProbeRequest {
                selector: selector.to_string(),
            },
        ))
        .map_err(|e| match e {
            BrowserError::EvaluationFailed(reason) => BrowserError::ToolExecutionFailed {
                tool: "interaction".to_string(),
                reason,
            },
            other => other,
        })?;

    let BrowserCommandResult::SelectorIdentityProbe(result) = result else {
        return Err(BrowserError::ToolExecutionFailed {
            tool: "interaction".to_string(),
            reason: "Browser command returned an unexpected result for selector identity"
                .to_string(),
        });
    };

    Ok(result)
}

fn build_scroll_target_into_view_js(config: &serde_json::Value) -> String {
    render_browser_kernel_script(
        &SCROLL_TARGET_INTO_VIEW_SHELL,
        SCROLL_TARGET_INTO_VIEW_TEMPLATE_JS,
        "__SCROLL_TARGET_CONFIG__",
        config,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::browser::BrowserSession;
    use crate::browser::backend::{ScriptEvaluation, SessionBackend, TabDescriptor};
    use crate::dom::{AriaChild, AriaNode, DocumentMetadata, DomTree};
    use crate::tools::core::{TargetRecoveredFrom, encode_selector_rebound_method};
    use serde_json::Value;
    use std::time::Duration;

    struct StaticInteractionBackend {
        value: Value,
    }

    impl SessionBackend for StaticInteractionBackend {
        fn navigate(&self, _url: &str) -> Result<()> {
            unreachable!("navigate is not used in this test")
        }

        fn wait_for_navigation(&self) -> Result<()> {
            unreachable!("wait_for_navigation is not used in this test")
        }

        fn wait_for_document_ready_with_timeout(&self, _timeout: Duration) -> Result<()> {
            unreachable!("wait_for_document_ready_with_timeout is not used in this test")
        }

        fn document_metadata(&self) -> Result<DocumentMetadata> {
            Ok(DocumentMetadata {
                document_id: "doc-1".to_string(),
                revision: "rev-2".to_string(),
                ..DocumentMetadata::default()
            })
        }

        fn extract_dom(&self) -> Result<DomTree> {
            unreachable!("extract_dom is not used in this test")
        }

        fn extract_dom_with_prefix(&self, _prefix: &str) -> Result<DomTree> {
            unreachable!("extract_dom_with_prefix is not used in this test")
        }

        fn evaluate(&self, _script: &str, _await_promise: bool) -> Result<ScriptEvaluation> {
            unreachable!("selector identity tests use browser commands, not raw evaluate")
        }

        fn execute_command(&self, command: BrowserCommand) -> Result<BrowserCommandResult> {
            match command {
                BrowserCommand::SelectorIdentityProbe(_) => {
                    serde_json::from_value::<SelectorIdentityProbeResult>(self.value.clone())
                        .map(BrowserCommandResult::SelectorIdentityProbe)
                        .map_err(|error| {
                            BrowserError::EvaluationFailed(format!(
                                "Failed to decode selector identity probe result: {error}"
                            ))
                        })
                }
                _ => unreachable!("only selector identity commands are used in this test"),
            }
        }

        fn capture_screenshot(&self, _full_page: bool) -> Result<Vec<u8>> {
            unreachable!("capture_screenshot is not used in this test")
        }

        fn press_key(&self, _key: &str) -> Result<()> {
            unreachable!("press_key is not used in this test")
        }

        fn list_tabs(&self) -> Result<Vec<TabDescriptor>> {
            Ok(vec![TabDescriptor {
                id: "tab-1".to_string(),
                title: "Test Tab".to_string(),
                url: "about:blank".to_string(),
            }])
        }

        fn active_tab(&self) -> Result<TabDescriptor> {
            Ok(TabDescriptor {
                id: "tab-1".to_string(),
                title: "Test Tab".to_string(),
                url: "about:blank".to_string(),
            })
        }

        fn open_tab(&self, _url: &str) -> Result<TabDescriptor> {
            Ok(TabDescriptor {
                id: "tab-1".to_string(),
                title: "Test Tab".to_string(),
                url: "about:blank".to_string(),
            })
        }

        fn activate_tab(&self, _tab_id: &str) -> Result<()> {
            unreachable!("activate_tab is not used in this test")
        }

        fn close_tab(&self, _tab_id: &str, _with_unload: bool) -> Result<()> {
            unreachable!("close_tab is not used in this test")
        }

        fn close(&self) -> Result<()> {
            unreachable!("close is not used in this test")
        }
    }

    fn sample_dom() -> DomTree {
        let root = AriaNode::fragment().with_child(AriaChild::Node(Box::new(
            AriaNode::new("button", "Save")
                .with_index(0)
                .with_box(true, Some("pointer".to_string())),
        )));
        let mut dom = DomTree::new(root);
        dom.document.document_id = "doc-1".to_string();
        dom.document.revision = "rev-2".to_string();
        dom.replace_selectors(vec!["#save".to_string()]);
        dom
    }

    #[test]
    fn test_resolve_interaction_target_rejects_stale_cursor_for_action_tools() {
        let dom = sample_dom();
        let mut stale_cursor = dom.cursor_for_index(0).expect("cursor should exist");
        stale_cursor.node_ref.revision = "rev-1".to_string();

        for tool in ["click", "input", "select", "hover", "wait"] {
            let session =
                BrowserSession::with_test_backend(StaticInteractionBackend { value: Value::Null });
            let mut context = ToolContext::with_dom(&session, dom.clone());
            let result = resolve_interaction_target(
                tool,
                None,
                None,
                None,
                Some(stale_cursor.clone()),
                &mut context,
            )
            .expect("stale cursor should become a structured tool failure");

            match result {
                TargetResolution::Failure(failure) => {
                    let data = failure
                        .data
                        .expect("stale cursor failure should include structured data");
                    assert_eq!(data["code"].as_str(), Some("stale_node_ref"));
                    assert_eq!(
                        data["details"]["resolution"]["recovered_from"].as_str(),
                        Some("cursor")
                    );
                    assert_eq!(
                        data["details"]["resolution"]["selector_rebound_attempted"].as_bool(),
                        Some(false)
                    );
                    assert_eq!(
                        data["recovery"]["suggested_tool"].as_str(),
                        Some("snapshot")
                    );
                    assert_eq!(
                        data["recovery"]["suggested_selector"].as_str(),
                        Some("#save")
                    );
                }
                TargetResolution::Resolved(target) => {
                    panic!("{tool} unexpectedly resolved stale cursor target: {target:?}")
                }
            }
        }
    }

    #[test]
    fn test_probe_selector_identity_rejects_invalid_present_payload() {
        let session = BrowserSession::with_test_backend(StaticInteractionBackend {
            value: serde_json::json!({
                "present": "yes",
                "unique": true,
            }),
        });
        let mut context = ToolContext::new(&session);

        let error = probe_selector_identity(&mut context, "#fake-target")
            .expect_err("invalid target_exists payload should fail");

        match error {
            BrowserError::ToolExecutionFailed { tool, reason } => {
                assert_eq!(tool, "interaction");
                assert!(reason.contains("Failed to decode selector identity probe result"));
                assert!(reason.contains("invalid type: string"));
                assert!(reason.contains("expected a boolean"));
            }
            other => panic!("unexpected target_exists error: {other:?}"),
        }
    }

    #[test]
    fn test_probe_selector_identity_rejects_invalid_unique_payload() {
        let session = BrowserSession::with_test_backend(StaticInteractionBackend {
            value: serde_json::json!({
                "present": true,
                "unique": "yes",
            }),
        });
        let mut context = ToolContext::new(&session);

        let error = probe_selector_identity(&mut context, "#fake-target")
            .expect_err("invalid unique payload should fail");

        match error {
            BrowserError::ToolExecutionFailed { tool, reason } => {
                assert_eq!(tool, "interaction");
                assert!(reason.contains("Failed to decode selector identity probe result"));
                assert!(reason.contains("invalid type: string"));
                assert!(reason.contains("expected a boolean"));
            }
            other => panic!("unexpected target_exists error: {other:?}"),
        }
    }

    #[test]
    fn test_determine_target_after_reuses_unique_selector_for_non_actionable_rebound() {
        let session = BrowserSession::with_test_backend(StaticInteractionBackend {
            value: serde_json::json!({
                "present": true,
                "unique": true,
            }),
        });
        let mut context = ToolContext::new(&session);
        let target_before = resolved_target(
            "#save",
            Some(NodeRef {
                document_id: "doc-1".to_string(),
                revision: "rev-1".to_string(),
                index: 3,
            }),
        );
        let current_document = DocumentMetadata {
            document_id: "doc-1".to_string(),
            revision: "rev-2".to_string(),
            ..DocumentMetadata::default()
        };

        let (target_after, status) =
            determine_target_after(&mut context, &target_before, &current_document, Vec::new())
                .expect("selector identity probe should succeed");

        assert_eq!(status, TargetStatus::Rebound);
        let target_after = target_after.expect("unique selector should yield target_after");
        assert_eq!(target_after.method, "css");
        assert_eq!(target_after.selector.as_deref(), Some("#save"));
        assert_eq!(target_after.resolution_status, "exact");
        assert_eq!(target_after.recovered_from, None);
        assert!(target_after.cursor.is_none());
        assert!(target_after.node_ref.is_none());
        assert!(target_after.index.is_none());
    }

    #[test]
    fn test_determine_target_after_marks_ambiguous_non_actionable_selector_unknown() {
        let session = BrowserSession::with_test_backend(StaticInteractionBackend {
            value: serde_json::json!({
                "present": true,
                "unique": false,
            }),
        });
        let mut context = ToolContext::new(&session);
        let target_before = resolved_target(
            "#save",
            Some(NodeRef {
                document_id: "doc-1".to_string(),
                revision: "rev-1".to_string(),
                index: 3,
            }),
        );
        let current_document = DocumentMetadata {
            document_id: "doc-1".to_string(),
            revision: "rev-2".to_string(),
            ..DocumentMetadata::default()
        };

        let (target_after, status) =
            determine_target_after(&mut context, &target_before, &current_document, Vec::new())
                .expect("selector identity probe should succeed");

        assert_eq!(status, TargetStatus::Unknown);
        assert!(target_after.is_none());
    }

    #[test]
    fn test_determine_target_after_marks_same_revision_cursor_mismatch_unknown() {
        let session =
            BrowserSession::with_test_backend(StaticInteractionBackend { value: Value::Null });
        let mut context = ToolContext::new(&session);
        let target_before = resolved_target(
            "#save",
            Some(NodeRef {
                document_id: "doc-1".to_string(),
                revision: "rev-1".to_string(),
                index: 1,
            }),
        );
        let current_document = DocumentMetadata {
            document_id: "doc-1".to_string(),
            revision: "rev-1".to_string(),
            ..DocumentMetadata::default()
        };
        let actionable_matches = vec![Cursor {
            node_ref: NodeRef {
                document_id: "doc-1".to_string(),
                revision: "rev-1".to_string(),
                index: 4,
            },
            selector: "#save".to_string(),
            index: 4,
            role: "button".to_string(),
            name: "Save".to_string(),
        }];

        let (target_after, status) = determine_target_after(
            &mut context,
            &target_before,
            &current_document,
            actionable_matches,
        )
        .expect("actionable match should classify");

        assert_eq!(status, TargetStatus::Unknown);
        assert_eq!(
            target_after
                .and_then(|target| target.node_ref)
                .map(|node| node.index),
            Some(4)
        );
    }

    #[test]
    fn test_build_interaction_failure_keeps_rebound_target_before_metadata() {
        let session =
            BrowserSession::with_test_backend(StaticInteractionBackend { value: Value::Null });
        let target = resolved_target_with_method(
            encode_selector_rebound_method("cursor", TargetRecoveredFrom::Cursor),
            "#save",
            Some(NodeRef {
                document_id: "doc-1".to_string(),
                revision: "rev-1".to_string(),
                index: 3,
            }),
        );

        let failure = build_interaction_failure(
            "click",
            &session,
            &target,
            "target_not_visible".to_string(),
            "Target is not visible".to_string(),
            vec!["visible".to_string()],
            None,
        )
        .expect("interaction failure should build");

        assert!(!failure.success);
        let data = failure.data.expect("failure data should be present");
        assert_eq!(
            data["target"]["resolution_status"].as_str(),
            Some("selector_rebound")
        );
        assert_eq!(data["target"]["recovered_from"].as_str(), Some("cursor"));
        assert_eq!(data["target"]["selector"].as_str(), Some("#save"));
        assert_eq!(
            data["details"]["failed_predicates"][0].as_str(),
            Some("visible")
        );
        assert_eq!(
            data["recovery"]["suggested_tool"].as_str(),
            Some("inspect_node")
        );
    }

    fn resolved_target(selector: &str, node_ref: Option<NodeRef>) -> ResolvedTarget {
        resolved_target_with_method("css".to_string(), selector, node_ref)
    }

    fn resolved_target_with_method(
        method: String,
        selector: &str,
        node_ref: Option<NodeRef>,
    ) -> ResolvedTarget {
        let cursor = node_ref.clone().map(|node_ref| Cursor {
            index: node_ref.index,
            node_ref,
            selector: selector.to_string(),
            role: "button".to_string(),
            name: "Save".to_string(),
        });

        ResolvedTarget {
            method,
            selector: selector.to_string(),
            index: None,
            node_ref,
            cursor,
        }
    }
}