Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions crates/tinycomputer-browser/src/surface/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,15 @@ impl BrowserSurface {
// subtree can be read beside sight, not two.
_ => return None,
}
// Shadow reads may refresh the browser's native refs, so map Sight
// controls only after the last such read, against the exact snapshot
// generation that will be used by the next action.
let snapshot = self
.block(self.browser.snapshot(&id, SnapshotRequest::default()))
.ok()?;
screen
.candidates
.retain_mut(|candidate| attach_unique_snapshot_ref(candidate, &snapshot.refs));
self.keep_denoised(sight::denoised(result));
Some(screen)
}
Expand Down Expand Up @@ -461,5 +470,34 @@ impl BrowserSurface {
}
}

/// Resolve every native ref against the final accessibility snapshot, since
/// an intervening shadow read may have reassigned its `eN` identifiers. Sight
/// selectors remain available for hosts that support them, but are replaced
/// by a native ref only when the snapshot has one exact role/name match.
fn attach_unique_snapshot_ref(
candidate: &mut tinycomputer_core::surface::Candidate,
refs: &[tinycomputer_bus::browser::ElementRef],
) -> bool {
candidate
.children
.retain_mut(|child| attach_unique_snapshot_ref(child, refs));
let Some(name) = candidate.name.as_deref().filter(|name| !name.is_empty()) else {
return sight::is_seen(&candidate.ref_id);
};
let mut matches = refs
.iter()
.filter(|item| item.role == candidate.role && item.name.as_str() == name);
let Some(found) = matches.next() else {
// Sight refs are selector-backed and remain governed by the host's
// existing policy. Native refs must never survive a missing match.
return sight::is_seen(&candidate.ref_id);
};
if matches.next().is_some() {
return sight::is_seen(&candidate.ref_id);
}
candidate.ref_id.clone_from(&found.id);
true
}

#[cfg(test)]
mod surface_tests;
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,28 @@ fn keys_are_spelled_the_way_agent_browser_reads_them() {
assert_eq!(browser_key(" + ", Platform::MacOs), "");
}

#[test]
fn a_tree_snapshot_ref_does_not_run_sight_only_tab_preparation() {
let Harness { fake, surface, .. } = harness("tree-ref-same-tab", page_fake());
let screen = surface.observe("shop", None, Depth::Full).unwrap();
let search = screen
.candidates
.iter()
.find(|candidate| candidate.name.as_deref() == Some("Search"))
.unwrap()
.clone();
assert!(search.ref_id.starts_with('e'));

let result = surface.execute(JevOperation::Click, Some(search), None);
assert!(result.ok, "{:?}", result.error);
assert!(fake.sent().iter().all(|command| {
command["action"] != "evaluate"
|| !command["script"]
.as_str()
.is_some_and(|script| script.contains("window.__tcOpen"))
}));
}

#[test]
fn secret_type_preflight_uses_gate_metadata_without_sending_text_to_the_page() {
#[derive(Default)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,92 @@

use serde_json::json;
use tinycomputer_bus::JevOperation;
use tinycomputer_core::surface::{Depth, Surface};
use tinycomputer_bus::browser::ElementRef;
use tinycomputer_core::surface::{Candidate, Depth, Surface};

use super::{Harness, harness, page_fake};
use crate::fake::{Fake, failure, ok};
use crate::surface::{Denoised, Perception};

#[test]
fn sight_targets_map_to_unique_current_native_refs_only() {
let mut unique = Candidate {
ref_id: "seen:1".to_owned(),
role: "button".to_owned(),
name: Some("Accept cookies".to_owned()),
..Candidate::default()
};
crate::surface::attach_unique_snapshot_ref(
&mut unique,
&[ElementRef {
id: "e1".to_owned(),
role: "button".to_owned(),
name: "Accept cookies".to_owned(),
}],
);
assert_eq!(unique.ref_id, "e1");

let mut duplicate = Candidate {
ref_id: "seen:2".to_owned(),
role: "button".to_owned(),
name: Some("Continue".to_owned()),
..Candidate::default()
};
crate::surface::attach_unique_snapshot_ref(
&mut duplicate,
&[
ElementRef {
id: "e2".to_owned(),
role: "button".to_owned(),
name: "Continue".to_owned(),
},
ElementRef {
id: "e3".to_owned(),
role: "button".to_owned(),
name: "Continue".to_owned(),
},
],
);
assert_eq!(duplicate.ref_id, "seen:2");

let mut stale_shadow_ref = Candidate {
ref_id: "e2".to_owned(),
role: "button".to_owned(),
name: Some("Allow Selection".to_owned()),
..Candidate::default()
};
assert!(!crate::surface::attach_unique_snapshot_ref(
&mut stale_shadow_ref,
&[ElementRef {
id: "e2".to_owned(),
role: "button".to_owned(),
name: "Different target".to_owned(),
}],
));

let mut ambiguous_shadow_ref = Candidate {
ref_id: "e3".to_owned(),
role: "button".to_owned(),
name: Some("Continue".to_owned()),
..Candidate::default()
};
assert!(!crate::surface::attach_unique_snapshot_ref(
&mut ambiguous_shadow_ref,
&[
ElementRef {
id: "e3".to_owned(),
role: "button".to_owned(),
name: "Continue".to_owned(),
},
ElementRef {
id: "e4".to_owned(),
role: "button".to_owned(),
name: "Continue".to_owned(),
},
],
));
}

/// A page read by sight: one field and one result link a card covers.
fn sighted_fake() -> Fake {
Fake::scripted(|command| match command["action"].as_str().unwrap() {
Expand All @@ -29,6 +109,13 @@ fn sighted_fake() -> Fake {
]
}})))
}
"snapshot" => Some(ok(&json!({
"snapshot": "- textbox \"To\" [ref=e1]\n- link [ref=e2]",
"refs": {
"e1": {"role": "textbox", "name": "To"},
"e2": {"role": "link", "name": ""}
}
}))),
"click" => Some(failure(
"Element is covered by <div.layer> at its click point, so the input would land on that element instead.",
)),
Expand All @@ -44,10 +131,10 @@ fn sighted_fake() -> Fake {
fn sight_reads_the_page_and_its_refs_reach_their_marks() {
let Harness { fake, surface, .. } = harness("sight", sighted_fake());
let screen = surface.observe("flights", None, Depth::Skeleton).unwrap();
assert!(!fake.actions().iter().any(|action| action == "snapshot"));
assert!(fake.actions().iter().any(|action| action == "snapshot"));
assert_eq!(screen.app, "flights");
let field = screen.candidates[0].clone();
assert_eq!(field.ref_id, "seen:1");
assert_eq!(field.ref_id, "e1");

let typed = surface.execute(
JevOperation::TypeText,
Expand All @@ -56,8 +143,8 @@ fn sight_reads_the_page_and_its_refs_reach_their_marks() {
);
assert!(typed.ok, "{:?}", typed.error);
let fill = fake.last("fill");
assert_eq!(fill["selector"], r#"[data-tc-seen="1"]"#, "{fill}");
assert_eq!(fake.last("focus")["selector"], r#"[data-tc-seen="1"]"#);
assert_eq!(fill["selector"], "@e1", "{fill}");
assert_eq!(fake.last("focus")["selector"], "@e1");

// An unnamed link a card covers is still clicked through its card: its
// mark names it exactly.
Expand All @@ -79,9 +166,17 @@ fn sight_reads_the_page_and_its_refs_reach_their_marks() {
"{script}"
);

surface.observe("", Some("seen:1"), Depth::Full).unwrap();
let scoped = fake.last("evaluate")["script"].as_str().unwrap().to_owned();
assert!(scoped.contains(r#"("[data-tc-seen=\"1\"]", {"#));
surface.observe("", Some("seen:2"), Depth::Full).unwrap();
let sent = fake.sent();
let scoped = sent
.iter()
.filter(|command| command["action"] == "evaluate")
.filter_map(|command| command["script"].as_str())
.find(|script| {
script.contains("__tinycomputerSeen") && script.contains("data-tc-seen=\\\"2\\\"")
})
.expect("the scoped Sight script uses the retained Sight ref");
assert!(scoped.contains(r#"("[data-tc-seen=\"2\"]", {"#), "{scoped}");
}

#[test]
Expand Down Expand Up @@ -162,6 +257,14 @@ fn shadowed_fake(shadows: serde_json::Value, subtree_fails: bool) -> Fake {
"e3": {"role": "button", "name": "Allow all"}
}
}))),
"snapshot" => Some(ok(&json!({
"snapshot": "- button \"Add To Cart\" [ref=e1]\n- button \"Allow Selection\" [ref=e2]\n- button \"Allow all\" [ref=e3]",
"refs": {
"e1": {"role": "button", "name": "Add To Cart"},
"e2": {"role": "button", "name": "Allow Selection"},
"e3": {"role": "button", "name": "Allow all"}
}
}))),
_ => None,
})
}
Expand All @@ -187,7 +290,7 @@ fn a_shadow_roots_controls_are_read_by_the_tree_beside_sight() {
assert_eq!(
names,
[
("seen:1", "Add To Cart"),
("e1", "Add To Cart"),
("e2", "Allow Selection"),
("e3", "Allow all")
]
Expand All @@ -208,7 +311,11 @@ fn a_shadow_roots_controls_are_read_by_the_tree_beside_sight() {
.iter()
.any(|line| line.contains("We value your privacy"))
);
let subtree = fake.last("snapshot");
let sent = fake.sent();
let subtree = sent
.iter()
.find(|command| command["action"] == "snapshot" && command.get("selector").is_some())
.unwrap();
assert_eq!(subtree["selector"], r#"[data-tc-seen="9"]"#, "{subtree}");

// A shadow root that draws no layer keeps the tree's own places.
Expand Down
5 changes: 5 additions & 0 deletions crates/tinycomputer-browser/src/surface/tabs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ impl BrowserSurface {
/// (`SAME_TAB_JS`). Best effort: a page that refuses the script, or an
/// element it cannot find, is pressed as it is.
pub(super) fn keep_in_tab(&self, reference: &str) {
// Sight refs are CSS marks. A tree ref such as `e3` addresses the
// browser's own snapshot and cannot be resolved by document.querySelector.
if !sight::is_seen(reference) {
return;
}
let selector = Value::String(sight::selector(reference));
let script = format!("{SAME_TAB_JS}(document.querySelector({selector}))");
if let Ok(id) = self.ensure_session() {
Expand Down
Loading