fix(snapshot): stop selector-scoped snapshots duplicating and dropping elements (#2043)

* fix(snapshot): stop selector-scoped snapshots duplicating and dropping elements

A node is a root of a selector-scoped snapshot only when none of its AX ancestors are inside the matched subtree, so ignored wrappers no longer create extra roots. DOM.describeNode now pierces shadow roots, so shadow content under the matched element is collected.

Fixes #2018

Co-Authored-By: Naman Satish <naman.satish@gmail.com>

* test(snapshot): assert selector-scoped snapshots exclude content outside the selector

---------

Co-authored-by: Naman Satish <naman.satish@gmail.com>
This commit is contained in:
Railly Hugo
2026-10-03 03:28:26 -03:00
committed by GitHub
co-authored by Naman Satish
parent 39a74c70d7
commit 526157cfd4
2 changed files with 128 additions and 14 deletions
+108
View File
@@ -5696,6 +5696,61 @@ async fn e2e_snapshot_cursor_many_elements() {
assert_success(&resp);
}
/// Test that a selector-scoped snapshot of a web component includes the
/// content of its shadow root.
#[tokio::test]
#[ignore]
async fn e2e_snapshot_selector_includes_shadow_root() {
let mut state = DaemonState::new();
let resp = execute_command(
&json!({ "id": "1", "action": "launch", "headless": true }),
&mut state,
)
.await;
assert_success(&resp);
let html =
"data:text/html,<my-card><span>Slotted</span></my-card><button>Outside</button><script>\
customElements.define('my-card', class extends HTMLElement { constructor() { \
super(); this.attachShadow({ mode: 'open' }).innerHTML = \
'<button>Inside shadow</button><slot></slot>'; } });</script>";
let resp = execute_command(
&json!({ "id": "2", "action": "navigate", "url": html }),
&mut state,
)
.await;
assert_success(&resp);
let resp = execute_command(
&json!({ "id": "3", "action": "snapshot", "selector": "my-card" }),
&mut state,
)
.await;
assert_success(&resp);
let snapshot = get_data(&resp)["snapshot"].as_str().unwrap();
assert!(
snapshot.contains("button \"Inside shadow\""),
"Snapshot should contain the shadow root button: {}",
snapshot
);
assert!(
snapshot.contains("Slotted"),
"Snapshot should contain the slotted text: {}",
snapshot
);
assert!(
!snapshot.contains("Outside"),
"Snapshot should not contain content outside the selector: {}",
snapshot
);
let resp = execute_command(&json!({ "id": "99", "action": "close" }), &mut state).await;
assert_success(&resp);
}
/// Test that InlineTextBox nodes are filtered from snapshot output while preserving
/// the actual text content from parent elements.
#[tokio::test]
@@ -5754,6 +5809,59 @@ async fn e2e_snapshot_continuous_static_text() {
assert_success(&resp);
}
/// Test that a selector-scoped snapshot renders each element once when plain
/// wrapper elements (ignored in the AX tree) sit between the matched element
/// and its descendants.
#[tokio::test]
#[ignore]
async fn e2e_snapshot_selector_no_duplicates() {
let mut state = DaemonState::new();
let resp = execute_command(
&json!({ "id": "1", "action": "launch", "headless": true }),
&mut state,
)
.await;
assert_success(&resp);
let html = "data:text/html,<main><div><div><button>Save</button></div></div>\
<select><option>Small</option><option>Large</option></select></main>\
<footer><button>Outside</button></footer>";
let resp = execute_command(
&json!({ "id": "2", "action": "navigate", "url": html }),
&mut state,
)
.await;
assert_success(&resp);
let resp = execute_command(
&json!({ "id": "3", "action": "snapshot", "selector": "main" }),
&mut state,
)
.await;
assert_success(&resp);
let snapshot = get_data(&resp)["snapshot"].as_str().unwrap();
for name in ["button \"Save\"", "option \"Small\"", "option \"Large\""] {
assert_eq!(
snapshot.matches(name).count(),
1,
"{} should appear once: {}",
name,
snapshot
);
}
assert!(
!snapshot.contains("Outside"),
"Snapshot should not contain content outside the selector: {}",
snapshot
);
let resp = execute_command(&json!({ "id": "99", "action": "close" }), &mut state).await;
assert_success(&resp);
}
// ---------------------------------------------------------------------------
// Helper: tiny HTTP server that echoes request headers as JSON
// ---------------------------------------------------------------------------
+20 -14
View File
@@ -374,12 +374,13 @@ pub async fn take_snapshot(
.object_id
.ok_or_else(|| format!("Selector '{}' did not match any element", selector))?;
// Request the full DOM subtree (depth: -1) so we can collect all
// backendNodeIds that live under the matched element.
// Request the full DOM subtree (depth: -1), including shadow roots
// (pierce), so we can collect all backendNodeIds that live under
// the matched element.
let describe: Value = client
.send_command(
"DOM.describeNode",
Some(serde_json::json!({ "objectId": object_id, "depth": -1 })),
Some(serde_json::json!({ "objectId": object_id, "depth": -1, "pierce": true })),
Some(session_id),
)
.await?;
@@ -445,18 +446,23 @@ pub async fn take_snapshot(
.map(|n| n.backend_node_id.is_some_and(|bid| id_set.contains(&bid)))
.collect();
// An AX node is a "top-level" match if it is in the subtree but its
// parent (in the AX tree) is not.
let mut roots = Vec::new();
for (idx, node) in tree_nodes.iter().enumerate() {
if !in_subtree[idx] {
continue;
// An AX node is a "top-level" match if it is in the subtree but none
// of its ancestors (in the AX tree) are. Checking only the parent is
// not enough: ignored nodes lose their backendDOMNodeId in
// build_tree, so a wrapper <div> between two matched nodes would
// turn everything below it into an extra root and render it twice.
let has_ancestor_in_subtree = |mut idx: usize| {
while let Some(pidx) = tree_nodes[idx].parent_idx {
if in_subtree[pidx] {
return true;
}
idx = pidx;
}
let parent_in_subtree = node.parent_idx.is_some_and(|pidx| in_subtree[pidx]);
if !parent_in_subtree {
roots.push(idx);
}
}
false
};
let roots: Vec<usize> = (0..tree_nodes.len())
.filter(|&idx| in_subtree[idx] && !has_ancestor_in_subtree(idx))
.collect();
if roots.is_empty() {
return Err(format!(