Skip to content

The headless browser for AI agents and web scraping

fix(mcp): return bounded actionable snapshots

SGavrl3c56f59d1f29
diff --git a/crates/obscura-browser/src/accessibility.rs b/crates/obscura-browser/src/accessibility.rs
new file mode 100644
index 00000000..d1793f5c
--- /dev/null
+++ b/crates/obscura-browser/src/accessibility.rs
@@ -0,0 +1,955 @@
+//! Shared accessibility names, visibility and control state for CDP and automation tools.
+
+use std::collections::{HashMap, HashSet};
+
+use obscura_dom::{DomTree, NodeData, NodeId};
+use obscura_js::runtime::AccessibilityStyle;
+use serde_json::{json, Value};
+
+/// Build a CDP AXValue for a role type.
+fn ax_value_role(role: &str) -> Value {
+ json!({"type": "role", "value": role})
+}
+
+/// Build a CDP AXValue for a string type.
+fn ax_value_string(s: &str) -> Value {
+ json!({"type": "string", "value": s})
+}
+
+/// Build a CDP AXValue for a boolean type.
+fn ax_value_boolean(b: bool) -> Value {
+ json!({"type": "boolean", "value": b})
+}
+
+/// Build a CDP AXValue for an integer type.
+fn ax_value_integer(i: u32) -> Value {
+ json!({"type": "integer", "value": i})
+}
+
+/// Walk the full DOM tree and produce CDP Accessibility AXNode array.
+#[cfg(test)]
+fn build_ax_nodes(dom: &DomTree) -> Vec<Value> {
+ build_ax_nodes_with_styles(dom, &HashMap::new())
+}
+
+/// Build the visible AX tree using optional computed styles from the renderer.
+pub fn build_ax_nodes_with_styles(
+ dom: &DomTree,
+ styles: &HashMap<NodeId, AccessibilityStyle>,
+) -> Vec<Value> {
+ let mut nodes: Vec<Value> = Vec::new();
+ let mut id_counter: u32 = 0;
+ // Map DOM NodeId → AX string id, populated only for nodes actually in the AX tree
+ let mut dom_to_ax: std::collections::HashMap<u32, String> = std::collections::HashMap::new();
+
+ let document = dom.document();
+
+ // Collect all DOM nodes in tree order (root + descendants)
+ let mut all_dom_ids: Vec<NodeId> = vec![document];
+ all_dom_ids.extend(dom.descendants(document));
+ let context = AccessibilityContext::new(dom, &all_dom_ids, styles);
+
+ // First pass: assign AX IDs only to nodes that will produce an AX node
+ let mut eligible: Vec<NodeId> = Vec::new();
+ for dom_id in &all_dom_ids {
+ // Quick check without full build_ax_node (just role check to avoid borrow issues)
+ if let Some(node) = dom.get_node(*dom_id) {
+ let role = map_role(&node.data);
+ if !role.is_empty() && !context.is_hidden(*dom_id) {
+ id_counter += 1;
+ dom_to_ax.insert(dom_id.raw(), id_counter.to_string());
+ eligible.push(*dom_id);
+ }
+ }
+ }
+
+ // Second pass: build AXNode for eligible nodes
+ for dom_id in &eligible {
+ if let Some(ax) = build_ax_node(dom, *dom_id, &dom_to_ax, &context) {
+ nodes.push(ax);
+ }
+ }
+
+ let mut children: HashMap<String, Vec<Value>> = HashMap::new();
+ for node in &nodes {
+ if let Some(parent) = node["parentId"].as_str() {
+ children
+ .entry(parent.to_string())
+ .or_default()
+ .push(node["nodeId"].clone());
+ }
+ }
+ for node in &mut nodes {
+ if let Some(ids) = children.remove(node["nodeId"].as_str().unwrap()) {
+ node["childIds"] = json!(ids);
+ }
+ }
+ nodes
+}
+
+fn build_ax_node(
+ dom: &DomTree,
+ node_id: NodeId,
+ dom_to_ax: &std::collections::HashMap<u32, String>,
+ context: &AccessibilityContext,
+) -> Option<Value> {
+ let ax_id = dom_to_ax.get(&node_id.raw())?.clone();
+ let mut ax_node = context.describe_node(dom, node_id)?;
+
+ // Resolve parentId — walk DOM ancestors until we find one in the AX tree
+ let parent_id: Option<String> = {
+ let mut current = node_id;
+ let mut result = None;
+ loop {
+ let next_parent = dom.with_node(current, |n| n.parent).flatten();
+ match next_parent {
+ Some(pid) => {
+ if let Some(ax_pid) = dom_to_ax.get(&pid.raw()) {
+ result = Some(ax_pid.clone());
+ break;
+ }
+ current = pid;
+ }
+ None => break,
+ }
+ }
+ result
+ };
+
+ ax_node["nodeId"] = json!(ax_id);
+ ax_node["ignored"] = json!(false);
+ if let Some(ref pid) = parent_id {
+ ax_node.as_object_mut().unwrap().insert("parentId".into(), json!(pid));
+ }
+ Some(ax_node)
+}
+
+/// Map HTML element tag to ARIA role value.
+fn map_role(data: &NodeData) -> &'static str {
+ match data {
+ NodeData::Document => "RootWebArea",
+ NodeData::Element { name, attrs, .. } => {
+ let tag = name.local.as_ref();
+
+ // Check explicit role attribute first
+ if let Some(role_attr) = attrs.iter().find(|a| a.name.local.as_ref() == "role") {
+ return match role_attr.value.as_str() {
+ "button" => "button",
+ "link" => "link",
+ "heading" => "heading",
+ "textbox" | "searchbox" => "textbox",
+ "checkbox" => "checkbox",
+ "radio" => "radio",
+ "listbox" => "listbox",
+ "combobox" => "combobox",
+ "list" => "list",
+ "listitem" => "listitem",
+ "navigation" => "navigation",
+ "banner" => "banner",
+ "main" => "main",
+ "complementary" => "complementary",
+ "contentinfo" => "contentinfo",
+ "form" => "form",
+ "table" => "table",
+ "row" => "row",
+ "cell" | "gridcell" => "cell",
+ "img" => "image",
+ "dialog" => "dialog",
+ "alert" => "alert",
+ "tab" => "tab",
+ "tablist" => "tablist",
+ "tabpanel" => "tabpanel",
+ "menu" => "menu",
+ "menuitem" => "menuitem",
+ "toolbar" => "toolbar",
+ "separator" => "separator",
+ "presentation" | "none" => {
+ // presentation/none roles get the role but content is still in tree
+ "presentation"
+ }
+ _ => "generic",
+ };
+ }
+
+ match tag {
+ "a" => {
+ if attrs.iter().any(|a| a.name.local.as_ref() == "href") {
+ "link"
+ } else {
+ "generic"
+ }
+ }
+ "button" | "summary" => "button",
+ "input" => {
+ let type_attr = attrs
+ .iter()
+ .find(|a| a.name.local.as_ref() == "type")
+ .map(|a| a.value.as_str())
+ .unwrap_or("text");
+ match type_attr {
+ "submit" | "reset" | "button" | "image" => "button",
+ "checkbox" => "checkbox",
+ "radio" => "radio",
+ "range" => "slider",
+ "number" => "spinbutton",
+ "search" => "searchbox",
+ _ => "textbox",
+ }
+ }
+ "textarea" => "textbox",
+ "select" => {
+ if attrs.iter().any(|a| {
+ a.name.local.as_ref() == "multiple"
+ || a.name.local.as_ref() == "size"
+ }) {
+ "listbox"
+ } else {
+ "combobox"
+ }
+ }
+ "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => "heading",
+ "img" | "svg" => "image",
+ "ul" | "ol" | "menu" => "list",
+ "li" => "listitem",
+ "table" => "table",
+ "tr" => "row",
+ "td" | "th" => "cell",
+ "nav" => "navigation",
+ "header" => "banner",
+ "main" => "main",
+ "footer" => "contentinfo",
+ "form" => "form",
+ "dialog" => "dialog",
+ "hr" => "separator",
+ "label" => "LabelText",
+ "article" => "article",
+ "aside" => "complementary",
+ "section" => "region",
+ "figure" => "figure",
+ "figcaption" => "StaticText",
+ "p" | "div" | "span" | "pre" | "blockquote" | "code"
+ | "em" | "strong" | "b" | "i" | "u" | "s" | "small"
+ | "sub" | "sup" | "mark" | "del" | "ins" => "generic",
+ "iframe" => "Iframe",
+ _ => "generic",
+ }
+ }
+ NodeData::Text { .. } => "StaticText",
+ NodeData::Doctype { .. } | NodeData::Comment { .. } | NodeData::ProcessingInstruction { .. } => {
+ ""
+ }
+ }
+}
+
+#[derive(Clone, Copy, Default)]
+struct Visibility {
+ subtree_hidden: bool,
+ visibility_hidden: bool,
+}
+
+/// Names and visibility for one unchanged document, without AX node serialization.
+pub struct AccessibilityContext {
+ visibility: HashMap<NodeId, Visibility>,
+ elements_by_id: HashMap<String, NodeId>,
+ labels: HashMap<NodeId, Vec<NodeId>>,
+}
+
+impl AccessibilityContext {
+ pub fn for_document(dom: &DomTree, styles: &HashMap<NodeId, AccessibilityStyle>) -> Self {
+ let mut ids = vec![dom.document()];
+ ids.extend(dom.descendants(dom.document()));
+ Self::new(dom, &ids, styles)
+ }
+
+ /// Describe only the requested visible node; CDP adds tree links separately.
+ pub fn describe_node(&self, dom: &DomTree, id: NodeId) -> Option<Value> {
+ if self.is_hidden(id) { return None; }
+ let node = dom.get_node(id)?;
+ let role = map_role(&node.data);
+ if role.is_empty() { return None; }
+ let mut result = json!({"backendDOMNodeId":id.raw(),"role":ax_value_role(role)});
+ if let Some(name) = compute_name(dom, &node, self) { result["name"] = ax_value_string(&name); }
+ if let Some(value) = compute_value(dom, &node) { result["value"] = ax_value_string(&value); }
+ let properties = compute_properties(dom, &node);
+ if !properties.is_empty() { result["properties"] = json!(properties); }
+ Some(result)
+ }
+
+ fn new(dom: &DomTree, ids: &[NodeId], styles: &HashMap<NodeId, AccessibilityStyle>) -> Self {
+ let mut context = Self {
+ visibility: HashMap::new(),
+ elements_by_id: HashMap::new(),
+ labels: HashMap::new(),
+ };
+ for id in ids {
+ let Some(node) = dom.get_node(*id) else {
+ continue;
+ };
+ let parent = node
+ .parent
+ .and_then(|id| context.visibility.get(&id))
+ .copied()
+ .unwrap_or_default();
+ let style = styles.get(id).copied().unwrap_or_default();
+ let hidden = node.get_attribute("hidden").is_some()
+ || node
+ .get_attribute("aria-hidden")
+ .is_some_and(|value| value.eq_ignore_ascii_case("true"))
+ || matches!(
+ tag(&node),
+ "head" | "script" | "style" | "template" | "noscript"
+ )
+ || (tag(&node) == "input" && input_type(&node) == "hidden");
+ context.visibility.insert(
+ *id,
+ Visibility {
+ subtree_hidden: parent.subtree_hidden || hidden || style.display_none,
+ visibility_hidden: style.visibility_hidden.unwrap_or(parent.visibility_hidden),
+ },
+ );
+ if let Some(value) = node.get_attribute("id").filter(|value| !value.is_empty()) {
+ context
+ .elements_by_id
+ .entry(value.to_string())
+ .or_insert(*id);
+ }
+ }
+ for id in ids {
+ let Some(node) = dom.get_node(*id) else {
+ continue;
+ };
+ if tag(&node) != "label" {
+ continue;
+ }
+ let control = if let Some(target) = node.get_attribute("for") {
+ context
+ .elements_by_id
+ .get(target)
+ .copied()
+ .filter(|id| dom.get_node(*id).is_some_and(|node| is_labelable(&node)))
+ } else {
+ dom.descendants(*id)
+ .into_iter()
+ .find(|id| dom.get_node(*id).is_some_and(|node| is_labelable(&node)))
+ };
+ if let Some(control) = control {
+ context.labels.entry(control).or_default().push(*id);
+ }
+ }
+ context
+ }
+
+ pub fn is_hidden(&self, id: NodeId) -> bool {
+ self.visibility
+ .get(&id)
+ .is_some_and(|state| state.subtree_hidden || state.visibility_hidden)
+ }
+}
+
+fn tag(node: &obscura_dom::Node) -> &str {
+ node.as_element()
+ .map(|name| name.local.as_ref())
+ .unwrap_or("")
+}
+
+fn input_type(node: &obscura_dom::Node) -> String {
+ node.get_attribute("type")
+ .unwrap_or("text")
+ .to_ascii_lowercase()
+}
+
+fn is_labelable(node: &obscura_dom::Node) -> bool {
+ matches!(
+ tag(node),
+ "button" | "meter" | "output" | "progress" | "select" | "textarea"
+ ) || (tag(node) == "input" && input_type(node) != "hidden")
+}
+
+fn is_nested_control(node: &obscura_dom::Node) -> bool {
+ matches!(
+ tag(node),
+ "input" | "textarea" | "select" | "button" | "summary" | "iframe"
+ ) || contenteditable_keyword(node) == Some(true)
+ || matches!(
+ map_role(&node.data),
+ "button"
+ | "textbox"
+ | "searchbox"
+ | "checkbox"
+ | "radio"
+ | "listbox"
+ | "combobox"
+ | "slider"
+ | "spinbutton"
+ | "menuitem"
+ | "tab"
+ )
+}
+
+fn flat_string(value: &str) -> String {
+ value.split_whitespace().collect::<Vec<_>>().join(" ")
+}
+
+fn nonempty(value: &str) -> Option<String> {
+ let value = flat_string(value);
+ (!value.is_empty()).then_some(value)
+}
+
+fn text_alternative(node: &obscura_dom::Node) -> Option<String> {
+ if let Some(label) = node.get_attribute("aria-label").and_then(nonempty) {
+ return Some(label);
+ }
+ if tag(node) == "img" || (tag(node) == "input" && input_type(node) == "image") {
+ return node.get_attribute("alt").map(flat_string);
+ }
+ if tag(node) == "input" {
+ match input_type(node).as_str() {
+ "button" => return node.get_attribute("value").and_then(nonempty),
+ "submit" => {
+ return Some(
+ node.get_attribute("value")
+ .map(flat_string)
+ .unwrap_or_else(|| "Submit".into()),
+ )
+ }
+ "reset" => {
+ return Some(
+ node.get_attribute("value")
+ .map(flat_string)
+ .unwrap_or_else(|| "Reset".into()),
+ )
+ }
+ _ => {}
+ }
+ }
+ None
+}
+
+fn content_name(
+ dom: &DomTree,
+ root: NodeId,
+ context: &AccessibilityContext,
+ include_hidden: bool,
+) -> String {
+ let mut text = String::new();
+ let mut pending = vec![(root, false)];
+ while let Some((id, end_block)) = pending.pop() {
+ if end_block {
+ text.push(' ');
+ continue;
+ }
+ let Some(node) = dom.get_node(id) else {
+ continue;
+ };
+ if !include_hidden
+ && context
+ .visibility
+ .get(&id)
+ .is_some_and(|state| state.subtree_hidden)
+ {
+ continue;
+ }
+ if matches!(tag(&node), "script" | "style" | "template" | "noscript") {
+ continue;
+ }
+ if id != root && is_nested_control(&node) {
+ continue;
+ }
+ let hidden = !include_hidden && context.is_hidden(id);
+ if let NodeData::Text { contents } = &node.data {
+ if !hidden {
+ text.push_str(contents);
+ }
+ continue;
+ }
+ if !hidden {
+ if let Some(alternative) = text_alternative(&node) {
+ text.push(' ');
+ text.push_str(&alternative);
+ text.push(' ');
+ continue;
+ }
+ }
+ let block = matches!(
+ tag(&node),
+ "br" | "p" | "div" | "li" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
+ );
+ if block {
+ text.push(' ');
+ pending.push((id, true));
+ }
+ pending.extend(dom.children(id).into_iter().rev().map(|id| (id, false)));
+ }
+ flat_string(&text)
+}
+
+/// Compute the accessible name for a node.
+fn compute_name(dom: &DomTree, node: &obscura_dom::Node, context: &AccessibilityContext) -> Option<String> {
+ if let NodeData::Text { contents } = &node.data {
+ return nonempty(contents);
+ }
+ if let Some(labelledby) = node.get_attribute("aria-labelledby") {
+ let mut seen = HashSet::new();
+ let references: Vec<_> = labelledby
+ .split_whitespace()
+ .filter_map(|id| context.elements_by_id.get(id).copied())
+ .filter(|id| seen.insert(*id))
+ .collect();
+ if !references.is_empty() {
+ let parts: Vec<_> = references
+ .into_iter()
+ .map(|id| {
+ if let Some(alternative) =
+ dom.get_node(id).and_then(|node| text_alternative(&node))
+ {
+ return alternative;
+ }
+ let text = content_name(dom, id, context, context.is_hidden(id));
+ if !text.is_empty() {
+ return text;
+ }
+ dom.get_node(id)
+ .and_then(|node| node.get_attribute("title").and_then(nonempty))
+ .unwrap_or_default()
+ })
+ .collect();
+ return Some(flat_string(&parts.join(" ")));
+ }
+ }
+ if let Some(label) = node.get_attribute("aria-label").and_then(nonempty) {
+ return Some(label);
+ }
+ if let Some(labels) = context.labels.get(&node.id) {
+ let parts: Vec<_> = labels
+ .iter()
+ .map(|id| content_name(dom, *id, context, context.is_hidden(*id)))
+ .collect();
+ if let Some(name) = nonempty(&parts.join(" ")) {
+ return Some(name);
+ }
+ }
+ if let Some(alternative) = text_alternative(node) {
+ return Some(alternative);
+ }
+ if matches!(
+ map_role(&node.data),
+ "button"
+ | "link"
+ | "heading"
+ | "checkbox"
+ | "radio"
+ | "menuitem"
+ | "tab"
+ | "cell"
+ | "row"
+ | "LabelText"
+ | "StaticText"
+ ) {
+ if let Some(name) = nonempty(&content_name(dom, node.id, context, false)) {
+ return Some(name);
+ }
+ }
+ if let Some(title) = node.get_attribute("title").and_then(nonempty) {
+ return Some(title);
+ }
+ if matches!(tag(node), "input" | "textarea") {
+ return node.get_attribute("placeholder").and_then(nonempty);
+ }
+ None
+}
+
+/// Compute the accessible value for a node (e.g., current input value).
+fn compute_value(dom: &DomTree, node: &obscura_dom::Node) -> Option<String> {
+ if let NodeData::Element { name, attrs, .. } = &node.data {
+ let tag = name.local.as_ref();
+ if tag == "input" || tag == "textarea" || tag == "select" {
+ if tag == "input" && input_type(node) == "password" {
+ return None;
+ }
+ if let Some(value) = dom.form_control_state(node.id).and_then(|state| state.value) {
+ return Some(value);
+ }
+ return attrs
+ .iter()
+ .find(|a| a.name.local.as_ref() == "value")
+ .map(|a| a.value.clone());
+ }
+
+ if is_content_editing_host(dom, node) {
+ return Some(dom.text_content(node.id));
+ }
+ }
+ None
+}
+
+fn contenteditable_keyword(node: &obscura_dom::Node) -> Option<bool> {
+ let NodeData::Element { attrs, .. } = &node.data else {
+ return None;
+ };
+ let value = &attrs
+ .iter()
+ .find(|attr| attr.name.local.as_ref() == "contenteditable")?
+ .value;
+
+ if value.is_empty()
+ || value.eq_ignore_ascii_case("true")
+ || value.eq_ignore_ascii_case("plaintext-only")
+ {
+ Some(true)
+ } else if value.eq_ignore_ascii_case("false") {
+ Some(false)
+ } else {
+ None
+ }
+}
+
+fn is_effectively_contenteditable(dom: &DomTree, node_id: NodeId) -> bool {
+ let mut current = Some(node_id);
+ while let Some(id) = current {
+ let Some(node) = dom.get_node(id) else {
+ return false;
+ };
+ if let Some(editable) = contenteditable_keyword(&node) {
+ return editable;
+ }
+ current = node.parent;
+ }
+ false
+}
+
+fn is_content_editing_host(dom: &DomTree, node: &obscura_dom::Node) -> bool {
+ is_effectively_contenteditable(dom, node.id)
+ && node
+ .parent
+ .is_none_or(|parent| !is_effectively_contenteditable(dom, parent))
+}
+
+/// Compute accessibility properties for a node.
+fn compute_properties(dom: &DomTree, node: &obscura_dom::Node) -> Vec<Value> {
+ if let NodeData::Element { name, attrs, .. } = &node.data {
+ let tag = name.local.as_ref();
+ let mut props = Vec::new();
+
+ // focusable
+ let focusable = matches!(
+ tag,
+ "a" | "button" | "input" | "select" | "textarea" | "details" | "summary"
+ ) || attrs.iter().any(|a| {
+ let an = a.name.local.as_ref();
+ an == "tabindex" || an == "contenteditable"
+ });
+ if focusable {
+ props.push(json!({"name": "focusable", "value": ax_value_boolean(true)}));
+ }
+
+ // editable
+ if tag == "input" || tag == "textarea"
+ || attrs
+ .iter()
+ .any(|a| a.name.local.as_ref() == "contenteditable" && a.value != "false")
+ {
+ props.push(json!({"name": "editable", "value": ax_value_boolean(true)}));
+ }
+
+ if tag == "input" && matches!(input_type(node).as_str(), "checkbox" | "radio") {
+ let checked = if input_type(node) == "checkbox" && dom.form_control_indeterminate(node.id) {
+ json!("mixed")
+ } else {
+ json!(dom.form_control_checked(node.id).unwrap_or_else(|| node.get_attribute("checked").is_some()))
+ };
+ props.push(json!({"name":"checked","value":{"type":"tristate","value":checked}}));
+ } else if let Some(checked) = node.get_attribute("aria-checked") {
+ let value = match checked {
+ "true" => Some(json!(true)),
+ "false" => Some(json!(false)),
+ "mixed" if map_role(&node.data) == "checkbox" => Some(json!("mixed")),
+ _ => None,
+ };
+ if let Some(value) = value {
+ props.push(json!({"name":"checked","value":{"type":"tristate","value":value}}));
+ }
+ }
+
+ // disabled
+ if node.get_attribute("disabled").is_some() {
+ props.push(json!({"name": "disabled", "value": ax_value_boolean(true)}));
+ } else if let Some(value) = node.get_attribute("aria-disabled").filter(|value| matches!(*value, "true" | "false")) {
+ props.push(json!({"name":"disabled","value":ax_value_boolean(value == "true")}));
+ }
+ for (property, attribute) in [("expanded", "aria-expanded"), ("selected", "aria-selected"), ("pressed", "aria-pressed")] {
+ if let Some(value) = node.get_attribute(attribute).filter(|value| matches!(*value, "true" | "false")) {
+ props.push(json!({"name":property,"value":ax_value_boolean(value == "true")}));
+ }
+ }
+
+ // level for headings
+ if let Some(level) = tag.strip_prefix('h').and_then(|s| s.parse::<u32>().ok()) {
+ if level >= 1 && level <= 6 {
+ props.push(json!({"name": "level", "value": ax_value_integer(level)}));
+ }
+ }
+
+ // required
+ if node.get_attribute("required").is_some() {
+ props.push(json!({"name": "required", "value": ax_value_boolean(true)}));
+ } else if let Some(value) = node.get_attribute("aria-required").filter(|value| matches!(*value, "true" | "false")) {
+ props.push(json!({"name":"required","value":ax_value_boolean(value == "true")}));
+ }
+
+ // multiline for textarea
+ if tag == "textarea" {
+ props.push(json!({"name": "multiline", "value": ax_value_boolean(true)}));
+ }
+
+ props
+ } else {
+ Vec::new()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use obscura_dom::parse_html;
+
+ #[test]
+ fn live_control_state_overrides_initial_attributes() {
+ let dom = parse_html("<input id=c type=checkbox checked><input id=f value=old><input id=p type=password value=secret>");
+ let checkbox = dom.get_element_by_id("c").unwrap();
+ dom.update_form_control_state(checkbox, |state| state.checked = Some(false));
+ dom.update_form_control_state(dom.get_element_by_id("f").unwrap(), |state| state.value = Some("fresh".into()));
+ let nodes = build_ax_nodes(&dom);
+ let node = ax_node_for(&nodes, checkbox);
+ let checked = node["properties"].as_array().unwrap().iter().find(|property| property["name"] == "checked").unwrap();
+ assert_eq!(checked["value"]["value"], json!(false));
+ assert_ax_value(&nodes, &dom, "f", Some("fresh"));
+ assert_ax_value(&nodes, &dom, "p", None);
+ dom.update_form_control_state(checkbox, |state| state.indeterminate = true);
+ let nodes = build_ax_nodes(&dom);
+ let mixed = ax_node_for(&nodes, checkbox)["properties"].as_array().unwrap().iter()
+ .find(|property| property["name"] == "checked").unwrap();
+ assert_eq!(mixed["value"]["value"], json!("mixed"));
+ }
+
+ #[test]
+ fn aria_control_states_preserve_false_and_mixed_values() {
+ let dom = parse_html("<div id=tab role=tab aria-selected=true></div><div id=field role=textbox aria-required=false></div><button id=exp aria-expanded=false aria-pressed=true aria-disabled=false></button><div id=mixed role=checkbox aria-checked=mixed></div>");
+ let nodes = build_ax_nodes(&dom);
+ for (id, name, expected) in [("tab", "selected", json!(true)), ("field", "required", json!(false)), ("exp", "expanded", json!(false)), ("exp", "pressed", json!(true)), ("exp", "disabled", json!(false)), ("mixed", "checked", json!("mixed"))] {
+ let node = ax_node_for(&nodes, dom.get_element_by_id(id).unwrap());
+ let property = node["properties"].as_array().unwrap().iter().find(|property| property["name"] == name)
+ .unwrap_or_else(|| panic!("missing {name} for #{id}"));
+ assert_eq!(property["value"]["value"], expected, "#{id}: {name}");
+ }
+ }
+
+ fn ax_node_for<'a>(nodes: &'a [Value], backend_node_id: NodeId) -> &'a Value {
+ nodes
+ .iter()
+ .find(|node| node["backendDOMNodeId"] == backend_node_id.raw())
+ .expect("element is present in the AX tree")
+ }
+
+ fn assert_ax_value(nodes: &[Value], dom: &DomTree, id: &str, expected: Option<&str>) {
+ let node = ax_node_for(nodes, dom.get_element_by_id(id).unwrap());
+ assert_eq!(
+ node.get("value").and_then(|value| value["value"].as_str()),
+ expected,
+ "unexpected AX value for #{id}"
+ );
+ }
+
+ fn assert_name(dom: &DomTree, id: &str, expected: Option<&str>) {
+ let nodes = build_ax_nodes(dom);
+ let node = ax_node_for(&nodes, dom.get_element_by_id(id).unwrap());
+ assert_eq!(
+ node.get("name").and_then(|name| name["value"].as_str()),
+ expected,
+ "#{id}"
+ );
+ }
+
+ #[test]
+ fn names_from_content_preserve_inline_words_and_normalize_whitespace() {
+ let dom = parse_html(
+ r#"<button id="button" title="tooltip"> Save <b>changes</b> now </button>
+ <a id="link" href="/">Read <span>the <em>docs</em></span></a>
+ <h2 id="heading">Access<b>ibility</b> test</h2>
+ <div id="generic">Do not duplicate all descendant text</div>"#,
+ );
+ assert_name(&dom, "button", Some("Save changes now"));
+ assert_name(&dom, "link", Some("Read the docs"));
+ assert_name(&dom, "heading", Some("Accessibility test"));
+ assert_name(&dom, "generic", None);
+ }
+
+ #[test]
+ fn html_labels_follow_control_association_and_document_order() {
+ let dom = parse_html(
+ r#"<label for="email"> Work <b>email</b> </label>
+ <input id="email" placeholder="fallback"><label for="email">address</label>
+ <label>Accept <span>terms</span><input id="accept" type="checkbox"></label>
+ <label for="email">Elsewhere<input id="wrong"></label>
+ <label>First<input id="first"><input id="second"></label>
+ <label for="missing">No association<input id="missing-for"></label>"#,
+ );
+ assert_name(&dom, "email", Some("Work email address Elsewhere"));
+ assert_name(&dom, "accept", Some("Accept terms"));
+ assert_name(&dom, "wrong", None);
+ assert_name(&dom, "first", Some("First"));
+ assert_name(&dom, "second", None);
+ assert_name(&dom, "missing-for", None);
+ }
+
+ #[test]
+ fn aria_labelledby_precedes_aria_label_and_native_names() {
+ let dom = parse_html(
+ r#"<span id="one">First</span><span id="two">Second</span>
+ <label for="target">Native</label>
+ <button id="target" aria-labelledby="two missing one two" aria-label="ARIA">Content</button>
+ <button id="invalid" aria-labelledby="missing" aria-label=" ARIA fallback ">Content</button>
+ <button id="blank" aria-label=" ">Content</button>
+ <span id="empty"></span><button id="empty-ref" aria-labelledby="empty" aria-label="fallback">Content</button>
+ <button id="self" aria-labelledby="self one" aria-label="Self">Content</button>
+ <span id="cycle-a" aria-labelledby="cycle-b">A</span><span id="cycle-b" aria-labelledby="cycle-a">B</span>
+ <button id="cycle" aria-labelledby="cycle-a">Content</button>"#,
+ );
+ assert_name(&dom, "target", Some("Second First"));
+ assert_name(&dom, "invalid", Some("ARIA fallback"));
+ assert_name(&dom, "blank", Some("Content"));
+ assert_name(&dom, "empty-ref", Some(""));
+ assert_name(&dom, "self", Some("Self First"));
+ assert_name(&dom, "cycle", Some("A"));
+ }
+
+ #[test]
+ fn hidden_references_name_controls_without_exposing_hidden_nodes() {
+ let dom = parse_html(
+ r#"<span id="hidden" hidden>Hidden <span hidden>reference</span></span>
+ <span id="visible">Visible <span hidden>noise</span></span>
+ <button id="referenced" aria-labelledby="hidden visible">Content</button>
+ <label hidden for="native">Hidden native</label><input id="native">
+ <button id="content">Shown<span aria-hidden="true"> noise</span><script>noise</script></button>"#,
+ );
+ assert_name(&dom, "referenced", Some("Hidden reference Visible"));
+ assert_name(&dom, "native", Some("Hidden native"));
+ assert_name(&dom, "content", Some("Shown"));
+ let nodes = build_ax_nodes(&dom);
+ let hidden = dom.get_element_by_id("hidden").unwrap();
+ assert!(!nodes
+ .iter()
+ .any(|node| node["backendDOMNodeId"] == hidden.raw()));
+ }
+
+ #[test]
+ fn aria_references_preserve_link_text() {
+ let dom = parse_html(
+ r#"<span id="label">Read <a href="/terms">terms</a><a href="/secret" hidden> secret</a></span>
+ <button id="native-link" aria-labelledby="label" aria-label="Fallback">Continue</button>
+ <span id="role-label">Review <span role="link">privacy</span></span>
+ <button id="role-link" aria-labelledby="role-label">Continue</button>
+ <span id="hidden-label" hidden>Read <a href="/terms" hidden>hidden terms</a></span>
+ <button id="hidden-link" aria-labelledby="hidden-label">Continue</button>"#,
+ );
+ assert_name(&dom, "native-link", Some("Read terms"));
+ assert_name(&dom, "role-link", Some("Review privacy"));
+ assert_name(&dom, "hidden-link", Some("Read hidden terms"));
+ }
+
+ #[test]
+ fn native_labels_preserve_link_text() {
+ let dom = parse_html(
+ r#"<label for="explicit">Read <a href="/terms">terms</a> and <span role="link">privacy</span></label>
+ <input id="explicit">
+ <label>Accept <a href="/terms">terms</a> and <span role="link">privacy</span><input id="implicit" type="checkbox"></label>
+ <label for="hidden" hidden>Read <a href="/terms" hidden>hidden terms</a></label><input id="hidden">"#,
+ );
+ assert_name(&dom, "explicit", Some("Read terms and privacy"));
+ assert_name(&dom, "implicit", Some("Accept terms and privacy"));
+ assert_name(&dom, "hidden", Some("Read hidden terms"));
+ }
+
+ #[test]
+ fn nested_buttons_remain_excluded_from_content_names() {
+ let dom = parse_html(
+ r#"<button id="outer">Outer</button><button id="inner" role="link">Nested action</button>"#,
+ );
+ let outer = dom.get_element_by_id("outer").unwrap();
+ let inner = dom.get_element_by_id("inner").unwrap();
+ dom.append_child(outer, inner);
+ assert_eq!(dom.get_node(inner).unwrap().parent, Some(outer));
+ assert_name(&dom, "outer", Some("Outer"));
+ assert_name(&dom, "inner", Some("Nested action"));
+ }
+
+ #[test]
+ fn nested_controls_do_not_pollute_labels_or_content_names() {
+ let dom = parse_html(
+ r#"<label for="field">Account <a href="/">Help</a><select><option>Noise</option></select><textarea>Noise</textarea><span role="textbox">Noise</span><span contenteditable="true">Noise</span><a href="/" role="button">Noise</a><button role="link">Noise</button></label>
+ <input id="field"><div role="button" id="button">Open <span role="button">Nested action</span><img alt="folder"></div>"#,
+ );
+ assert_name(&dom, "field", Some("Account Help"));
+ assert_name(&dom, "button", Some("Open folder"));
+ }
+
+ #[test]
+ fn html_and_aria_hidden_subtrees_are_absent() {
+ let dom = parse_html(
+ r#"<div hidden="false"><button id="html">Hidden</button></div>
+ <div aria-hidden="TrUe"><button id="aria" aria-hidden="false">Hidden</button></div>
+ <input id="input" type="hidden"><button id="visible" aria-hidden="false">Visible</button>"#,
+ );
+ let nodes = build_ax_nodes(&dom);
+ for id in ["html", "aria", "input"] {
+ let id = dom.get_element_by_id(id).unwrap();
+ assert!(!nodes
+ .iter()
+ .any(|node| node["backendDOMNodeId"] == id.raw()));
+ }
+ assert_name(&dom, "visible", Some("Visible"));
+ }
+
+ #[test]
+ fn native_alternatives_and_aria_override_content() {
+ let dom = parse_html(
+ r#"<button id="aria" aria-label="Named">Content</button>
+ <button id="image"><img alt="Download"></button>
+ <img id="decorative" alt="" title="Not a name">
+ <input id="submit" type="submit" value="Send">
+ <input id="password" type="password" value="secret" placeholder="Password">
+ <label for="select">Choice</label><select id="select"><option>Not the name</option></select>"#,
+ );
+ assert_name(&dom, "aria", Some("Named"));
+ assert_name(&dom, "image", Some("Download"));
+ assert_name(&dom, "decorative", Some(""));
+ assert_name(&dom, "submit", Some("Send"));
+ assert_name(&dom, "password", Some("Password"));
+ assert_name(&dom, "select", Some("Choice"));
+ }
+
+ #[test]
+ fn content_editing_hosts_expose_ax_values_without_duplicating_descendants() {
+ let dom = parse_html(
+ r#"<div id="true" contenteditable="TrUe">true</div>
+ <div id="empty-keyword" contenteditable>empty keyword</div>
+ <div id="plaintext" contenteditable="PlAiNtExT-OnLy">plaintext</div>
+ <div id="empty-host" contenteditable></div>
+ <div id="host" contenteditable="true">host<span id="inherited"> inherited</span><span id="invalid" contenteditable="bogus"> invalid</span><span id="nested-explicit" contenteditable="plaintext-only"> nested</span></div>
+ <div id="disabled" contenteditable="FaLsE">disabled<span id="invalid-disabled" contenteditable="bogus"> inherited off</span><span id="reenabled" contenteditable="TRUE">reenabled<span id="reenabled-child"> child</span></span></div>"#,
+ );
+ let nodes = build_ax_nodes(&dom);
+
+ assert_ax_value(&nodes, &dom, "true", Some("true"));
+ assert_ax_value(&nodes, &dom, "empty-keyword", Some("empty keyword"));
+ assert_ax_value(&nodes, &dom, "plaintext", Some("plaintext"));
+ assert_ax_value(&nodes, &dom, "empty-host", Some(""));
+ assert_ax_value(&nodes, &dom, "host", Some("host inherited invalid nested"));
+ assert_ax_value(&nodes, &dom, "inherited", None);
+ assert_ax_value(&nodes, &dom, "invalid", None);
+ assert_ax_value(&nodes, &dom, "nested-explicit", None);
+ assert_ax_value(&nodes, &dom, "disabled", None);
+ assert_ax_value(&nodes, &dom, "invalid-disabled", None);
+ assert_ax_value(&nodes, &dom, "reenabled", Some("reenabled child"));
+ assert_ax_value(&nodes, &dom, "reenabled-child", None);
+ }
+}
diff --git a/crates/obscura-browser/src/lib.rs b/crates/obscura-browser/src/lib.rs
index 4494d1fe..5bbd252e 100644
--- a/crates/obscura-browser/src/lib.rs
+++ b/crates/obscura-browser/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod accessibility;
pub mod context;
mod fork_virtual_url;
mod idle_deadline;
diff --git a/crates/obscura-cdp/src/domains/accessibility.rs b/crates/obscura-cdp/src/domains/accessibility.rs
index 807382c0..1105411d 100644
--- a/crates/obscura-cdp/src/domains/accessibility.rs
+++ b/crates/obscura-cdp/src/domains/accessibility.rs
@@ -1,31 +1,11 @@
-use std::collections::{HashMap, HashSet};
+#[cfg(not(feature = "render"))]
+use std::collections::HashMap;
-use obscura_dom::{DomTree, NodeData, NodeId};
-use obscura_js::runtime::AccessibilityStyle;
+use obscura_browser::accessibility::build_ax_nodes_with_styles;
use serde_json::{json, Value};
use crate::dispatch::CdpContext;
-/// Build a CDP AXValue for a role type.
-fn ax_value_role(role: &str) -> Value {
- json!({"type": "role", "value": role})
-}
-
-/// Build a CDP AXValue for a string type.
-fn ax_value_string(s: &str) -> Value {
- json!({"type": "string", "value": s})
-}
-
-/// Build a CDP AXValue for a boolean type.
-fn ax_value_boolean(b: bool) -> Value {
- json!({"type": "boolean", "value": b})
-}
-
-/// Build a CDP AXValue for an integer type.
-fn ax_value_integer(i: u32) -> Value {
- json!({"type": "integer", "value": i})
-}
-
pub async fn handle(
method: &str,
_params: &Value,
@@ -35,904 +15,14 @@ pub async fn handle(
match method {
"enable" => Ok(json!({})),
"getFullAXTree" => {
- let page = ctx
- .get_session_page(session_id)
- .ok_or("No page")?;
+ let page = ctx.get_session_page(session_id).ok_or("No page")?;
#[cfg(feature = "render")]
- let styles = page
- .js
- .as_ref()
- .map(|js| js.accessibility_styles())
- .unwrap_or_default();
+ let styles = page.js.as_ref().map(|js| js.accessibility_styles()).unwrap_or_default();
#[cfg(not(feature = "render"))]
let styles = HashMap::new();
- let nodes = page
- .with_dom(|dom| build_ax_nodes_with_styles(dom, &styles))
- .unwrap_or_default();
- Ok(json!({ "nodes": nodes }))
+ let nodes = page.with_dom(|dom| build_ax_nodes_with_styles(dom, &styles)).unwrap_or_default();
+ Ok(json!({"nodes": nodes}))
}
_ => Ok(json!({})),
}
}
-
-/// Walk the full DOM tree and produce CDP Accessibility AXNode array.
-#[cfg(test)]
-fn build_ax_nodes(dom: &DomTree) -> Vec<Value> {
- build_ax_nodes_with_styles(dom, &HashMap::new())
-}
-
-fn build_ax_nodes_with_styles(
- dom: &DomTree,
- styles: &HashMap<NodeId, AccessibilityStyle>,
-) -> Vec<Value> {
- let mut nodes: Vec<Value> = Vec::new();
- let mut id_counter: u32 = 0;
- // Map DOM NodeId → AX string id, populated only for nodes actually in the AX tree
- let mut dom_to_ax: std::collections::HashMap<u32, String> = std::collections::HashMap::new();
-
- let document = dom.document();
-
- // Collect all DOM nodes in tree order (root + descendants)
- let mut all_dom_ids: Vec<NodeId> = vec![document];
- all_dom_ids.extend(dom.descendants(document));
- let context = NameContext::new(dom, &all_dom_ids, styles);
-
- // First pass: assign AX IDs only to nodes that will produce an AX node
- let mut eligible: Vec<NodeId> = Vec::new();
- for dom_id in &all_dom_ids {
- // Quick check without full build_ax_node (just role check to avoid borrow issues)
- if let Some(node) = dom.get_node(*dom_id) {
- let role = map_role(&node.data);
- if !role.is_empty() && !context.is_hidden(*dom_id) {
- id_counter += 1;
- dom_to_ax.insert(dom_id.raw(), id_counter.to_string());
- eligible.push(*dom_id);
- }
- }
- }
-
- // Second pass: build AXNode for eligible nodes
- for dom_id in &eligible {
- if let Some(ax) = build_ax_node(dom, *dom_id, &dom_to_ax, &context) {
- nodes.push(ax);
- }
- }
-
- let mut children: HashMap<String, Vec<Value>> = HashMap::new();
- for node in &nodes {
- if let Some(parent) = node["parentId"].as_str() {
- children
- .entry(parent.to_string())
- .or_default()
- .push(node["nodeId"].clone());
- }
- }
- for node in &mut nodes {
- if let Some(ids) = children.remove(node["nodeId"].as_str().unwrap()) {
- node["childIds"] = json!(ids);
- }
- }
- nodes
-}
-
-fn build_ax_node(
- dom: &DomTree,
- node_id: NodeId,
- dom_to_ax: &std::collections::HashMap<u32, String>,
- context: &NameContext,
-) -> Option<Value> {
- let node = dom.get_node(node_id)?;
- let ax_id = dom_to_ax.get(&node_id.raw())?.clone();
-
- let role = map_role(&node.data);
- // Skip non-relevant nodes (Document, Doctype, Comment, PI)
- if role.is_empty() {
- return None;
- }
-
- let name = compute_name(dom, &node, context);
- let value = compute_value(dom, &node);
- let properties = compute_properties(dom, &node);
-
- // Resolve parentId — walk DOM ancestors until we find one in the AX tree
- let parent_id: Option<String> = {
- let mut current = node_id;
- let mut result = None;
- loop {
- let next_parent = dom.with_node(current, |n| n.parent).flatten();
- match next_parent {
- Some(pid) => {
- if let Some(ax_pid) = dom_to_ax.get(&pid.raw()) {
- result = Some(ax_pid.clone());
- break;
- }
- current = pid;
- }
- None => break,
- }
- }
- result
- };
-
- // Build node with only non-empty optional fields (per CDP spec, optional fields should be omitted when empty)
- let mut ax_node = json!({
- "nodeId": ax_id,
- "ignored": false,
- "role": ax_value_role(role),
- });
-
- if let Some(ref pid) = parent_id {
- ax_node.as_object_mut().unwrap().insert("parentId".into(), json!(pid));
- }
- if let Some(ref n) = name {
- ax_node.as_object_mut().unwrap().insert("name".into(), json!(ax_value_string(n)));
- }
- if let Some(ref v) = value {
- ax_node.as_object_mut().unwrap().insert("value".into(), json!(ax_value_string(v)));
- }
- if !properties.is_empty() {
- ax_node.as_object_mut().unwrap().insert("properties".into(), json!(properties));
- }
- ax_node.as_object_mut().unwrap().insert("backendDOMNodeId".into(), json!(node_id.raw()));
-
- Some(ax_node)
-}
-
-/// Map HTML element tag to ARIA role value.
-fn map_role(data: &NodeData) -> &'static str {
- match data {
- NodeData::Document => "RootWebArea",
- NodeData::Element { name, attrs, .. } => {
- let tag = name.local.as_ref();
-
- // Check explicit role attribute first
- if let Some(role_attr) = attrs.iter().find(|a| a.name.local.as_ref() == "role") {
- return match role_attr.value.as_str() {
- "button" => "button",
- "link" => "link",
- "heading" => "heading",
- "textbox" | "searchbox" => "textbox",
- "checkbox" => "checkbox",
- "radio" => "radio",
- "listbox" => "listbox",
- "combobox" => "combobox",
- "list" => "list",
- "listitem" => "listitem",
- "navigation" => "navigation",
- "banner" => "banner",
- "main" => "main",
- "complementary" => "complementary",
- "contentinfo" => "contentinfo",
- "form" => "form",
- "table" => "table",
- "row" => "row",
- "cell" | "gridcell" => "cell",
- "img" => "image",
- "dialog" => "dialog",
- "alert" => "alert",
- "tab" => "tab",
- "tablist" => "tablist",
- "tabpanel" => "tabpanel",
- "menu" => "menu",
- "menuitem" => "menuitem",
- "toolbar" => "toolbar",
- "separator" => "separator",
- "presentation" | "none" => {
- // presentation/none roles get the role but content is still in tree
- "presentation"
- }
- _ => "generic",
- };
- }
-
- match tag {
- "a" => {
- if attrs.iter().any(|a| a.name.local.as_ref() == "href") {
- "link"
- } else {
- "generic"
- }
- }
- "button" | "summary" => "button",
- "input" => {
- let type_attr = attrs
- .iter()
- .find(|a| a.name.local.as_ref() == "type")
- .map(|a| a.value.as_str())
- .unwrap_or("text");
- match type_attr {
- "submit" | "reset" | "button" | "image" => "button",
- "checkbox" => "checkbox",
- "radio" => "radio",
- "range" => "slider",
- "number" => "spinbutton",
- "search" => "searchbox",
- _ => "textbox",
- }
- }
- "textarea" => "textbox",
- "select" => {
- if attrs.iter().any(|a| {
- a.name.local.as_ref() == "multiple"
- || a.name.local.as_ref() == "size"
- }) {
- "listbox"
- } else {
- "combobox"
- }
- }
- "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => "heading",
- "img" | "svg" => "image",
- "ul" | "ol" | "menu" => "list",
- "li" => "listitem",
- "table" => "table",
- "tr" => "row",
- "td" | "th" => "cell",
- "nav" => "navigation",
- "header" => "banner",
- "main" => "main",
- "footer" => "contentinfo",
- "form" => "form",
- "dialog" => "dialog",
- "hr" => "separator",
- "label" => "LabelText",
- "article" => "article",
- "aside" => "complementary",
- "section" => "region",
- "figure" => "figure",
- "figcaption" => "StaticText",
- "p" | "div" | "span" | "pre" | "blockquote" | "code"
- | "em" | "strong" | "b" | "i" | "u" | "s" | "small"
- | "sub" | "sup" | "mark" | "del" | "ins" => "generic",
- "iframe" => "Iframe",
- _ => "generic",
- }
- }
- NodeData::Text { .. } => "StaticText",
- NodeData::Doctype { .. } | NodeData::Comment { .. } | NodeData::ProcessingInstruction { .. } => {
- ""
- }
- }
-}
-
-#[derive(Clone, Copy, Default)]
-struct Visibility {
- subtree_hidden: bool,
- visibility_hidden: bool,
-}
-
-struct NameContext {
- visibility: HashMap<NodeId, Visibility>,
- elements_by_id: HashMap<String, NodeId>,
- labels: HashMap<NodeId, Vec<NodeId>>,
-}
-
-impl NameContext {
- fn new(dom: &DomTree, ids: &[NodeId], styles: &HashMap<NodeId, AccessibilityStyle>) -> Self {
- let mut context = Self {
- visibility: HashMap::new(),
- elements_by_id: HashMap::new(),
- labels: HashMap::new(),
- };
- for id in ids {
- let Some(node) = dom.get_node(*id) else {
- continue;
- };
- let parent = node
- .parent
- .and_then(|id| context.visibility.get(&id))
- .copied()
- .unwrap_or_default();
- let style = styles.get(id).copied().unwrap_or_default();
- let hidden = node.get_attribute("hidden").is_some()
- || node
- .get_attribute("aria-hidden")
- .is_some_and(|value| value.eq_ignore_ascii_case("true"))
- || matches!(
- tag(&node),
- "head" | "script" | "style" | "template" | "noscript"
- )
- || (tag(&node) == "input" && input_type(&node) == "hidden");
- context.visibility.insert(
- *id,
- Visibility {
- subtree_hidden: parent.subtree_hidden || hidden || style.display_none,
- visibility_hidden: style.visibility_hidden.unwrap_or(parent.visibility_hidden),
- },
- );
- if let Some(value) = node.get_attribute("id").filter(|value| !value.is_empty()) {
- context
- .elements_by_id
- .entry(value.to_string())
- .or_insert(*id);
- }
- }
- for id in ids {
- let Some(node) = dom.get_node(*id) else {
- continue;
- };
- if tag(&node) != "label" {
- continue;
- }
- let control = if let Some(target) = node.get_attribute("for") {
- context
- .elements_by_id
- .get(target)
- .copied()
- .filter(|id| dom.get_node(*id).is_some_and(|node| is_labelable(&node)))
- } else {
- dom.descendants(*id)
- .into_iter()
- .find(|id| dom.get_node(*id).is_some_and(|node| is_labelable(&node)))
- };
- if let Some(control) = control {
- context.labels.entry(control).or_default().push(*id);
- }
- }
- context
- }
-
- fn is_hidden(&self, id: NodeId) -> bool {
- self.visibility
- .get(&id)
- .is_some_and(|state| state.subtree_hidden || state.visibility_hidden)
- }
-}
-
-fn tag(node: &obscura_dom::Node) -> &str {
- node.as_element()
- .map(|name| name.local.as_ref())
- .unwrap_or("")
-}
-
-fn input_type(node: &obscura_dom::Node) -> String {
- node.get_attribute("type")
- .unwrap_or("text")
- .to_ascii_lowercase()
-}
-
-fn is_labelable(node: &obscura_dom::Node) -> bool {
- matches!(
- tag(node),
- "button" | "meter" | "output" | "progress" | "select" | "textarea"
- ) || (tag(node) == "input" && input_type(node) != "hidden")
-}
-
-fn is_nested_control(node: &obscura_dom::Node) -> bool {
- matches!(
- tag(node),
- "input" | "textarea" | "select" | "button" | "summary" | "iframe"
- ) || contenteditable_keyword(node) == Some(true)
- || matches!(
- map_role(&node.data),
- "button"
- | "textbox"
- | "searchbox"
- | "checkbox"
- | "radio"
- | "listbox"
- | "combobox"
- | "slider"
- | "spinbutton"
- | "menuitem"
- | "tab"
- )
-}
-
-fn flat_string(value: &str) -> String {
- value.split_whitespace().collect::<Vec<_>>().join(" ")
-}
-
-fn nonempty(value: &str) -> Option<String> {
- let value = flat_string(value);
- (!value.is_empty()).then_some(value)
-}
-
-fn text_alternative(node: &obscura_dom::Node) -> Option<String> {
- if let Some(label) = node.get_attribute("aria-label").and_then(nonempty) {
- return Some(label);
- }
- if tag(node) == "img" || (tag(node) == "input" && input_type(node) == "image") {
- return node.get_attribute("alt").map(flat_string);
- }
- if tag(node) == "input" {
- match input_type(node).as_str() {
- "button" => return node.get_attribute("value").and_then(nonempty),
- "submit" => {
- return Some(
- node.get_attribute("value")
- .map(flat_string)
- .unwrap_or_else(|| "Submit".into()),
- )
- }
- "reset" => {
- return Some(
- node.get_attribute("value")
- .map(flat_string)
- .unwrap_or_else(|| "Reset".into()),
- )
- }
- _ => {}
- }
- }
- None
-}
-
-fn content_name(
- dom: &DomTree,
- root: NodeId,
- context: &NameContext,
- include_hidden: bool,
-) -> String {
- let mut text = String::new();
- let mut pending = vec![(root, false)];
- while let Some((id, end_block)) = pending.pop() {
- if end_block {
- text.push(' ');
- continue;
- }
- let Some(node) = dom.get_node(id) else {
- continue;
- };
- if !include_hidden
- && context
- .visibility
- .get(&id)
- .is_some_and(|state| state.subtree_hidden)
- {
- continue;
- }
- if matches!(tag(&node), "script" | "style" | "template" | "noscript") {
- continue;
- }
- if id != root && is_nested_control(&node) {
- continue;
- }
- let hidden = !include_hidden && context.is_hidden(id);
- if let NodeData::Text { contents } = &node.data {
- if !hidden {
- text.push_str(contents);
- }
- continue;
- }
- if !hidden {
- if let Some(alternative) = text_alternative(&node) {
- text.push(' ');
- text.push_str(&alternative);
- text.push(' ');
- continue;
- }
- }
- let block = matches!(
- tag(&node),
- "br" | "p" | "div" | "li" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
- );
- if block {
- text.push(' ');
- pending.push((id, true));
- }
- pending.extend(dom.children(id).into_iter().rev().map(|id| (id, false)));
- }
- flat_string(&text)
-}
-
-/// Compute the accessible name for a node.
-fn compute_name(dom: &DomTree, node: &obscura_dom::Node, context: &NameContext) -> Option<String> {
- if let NodeData::Text { contents } = &node.data {
- return nonempty(contents);
- }
- if let Some(labelledby) = node.get_attribute("aria-labelledby") {
- let mut seen = HashSet::new();
- let references: Vec<_> = labelledby
- .split_whitespace()
- .filter_map(|id| context.elements_by_id.get(id).copied())
- .filter(|id| seen.insert(*id))
- .collect();
- if !references.is_empty() {
- let parts: Vec<_> = references
- .into_iter()
- .map(|id| {
- if let Some(alternative) =
- dom.get_node(id).and_then(|node| text_alternative(&node))
- {
- return alternative;
- }
- let text = content_name(dom, id, context, context.is_hidden(id));
- if !text.is_empty() {
- return text;
- }
- dom.get_node(id)
- .and_then(|node| node.get_attribute("title").and_then(nonempty))
- .unwrap_or_default()
- })
- .collect();
- return Some(flat_string(&parts.join(" ")));
- }
- }
- if let Some(label) = node.get_attribute("aria-label").and_then(nonempty) {
- return Some(label);
- }
- if let Some(labels) = context.labels.get(&node.id) {
- let parts: Vec<_> = labels
- .iter()
- .map(|id| content_name(dom, *id, context, context.is_hidden(*id)))
- .collect();
- if let Some(name) = nonempty(&parts.join(" ")) {
- return Some(name);
- }
- }
- if let Some(alternative) = text_alternative(node) {
- return Some(alternative);
- }
- if matches!(
- map_role(&node.data),
- "button"
- | "link"
- | "heading"
- | "checkbox"
- | "radio"
- | "menuitem"
- | "tab"
- | "cell"
- | "row"
- | "LabelText"
- | "StaticText"
- ) {
- if let Some(name) = nonempty(&content_name(dom, node.id, context, false)) {
- return Some(name);
- }
- }
- if let Some(title) = node.get_attribute("title").and_then(nonempty) {
- return Some(title);
- }
- if matches!(tag(node), "input" | "textarea") {
- return node.get_attribute("placeholder").and_then(nonempty);
- }
- None
-}
-
-/// Compute the accessible value for a node (e.g., current input value).
-fn compute_value(dom: &DomTree, node: &obscura_dom::Node) -> Option<String> {
- if let NodeData::Element { name, attrs, .. } = &node.data {
- let tag = name.local.as_ref();
- // For native form controls, return the value attribute.
- if tag == "input" || tag == "textarea" || tag == "select" {
- return attrs
- .iter()
- .find(|a| a.name.local.as_ref() == "value")
- .map(|a| a.value.clone());
- }
-
- if is_content_editing_host(dom, node) {
- return Some(dom.text_content(node.id));
- }
- }
- None
-}
-
-fn contenteditable_keyword(node: &obscura_dom::Node) -> Option<bool> {
- let NodeData::Element { attrs, .. } = &node.data else {
- return None;
- };
- let value = &attrs
- .iter()
- .find(|attr| attr.name.local.as_ref() == "contenteditable")?
- .value;
-
- if value.is_empty()
- || value.eq_ignore_ascii_case("true")
- || value.eq_ignore_ascii_case("plaintext-only")
- {
- Some(true)
- } else if value.eq_ignore_ascii_case("false") {
- Some(false)
- } else {
- None
- }
-}
-
-fn is_effectively_contenteditable(dom: &DomTree, node_id: NodeId) -> bool {
- let mut current = Some(node_id);
- while let Some(id) = current {
- let Some(node) = dom.get_node(id) else {
- return false;
- };
- if let Some(editable) = contenteditable_keyword(&node) {
- return editable;
- }
- current = node.parent;
- }
- false
-}
-
-fn is_content_editing_host(dom: &DomTree, node: &obscura_dom::Node) -> bool {
- is_effectively_contenteditable(dom, node.id)
- && node
- .parent
- .is_none_or(|parent| !is_effectively_contenteditable(dom, parent))
-}
-
-/// Compute accessibility properties for a node.
-fn compute_properties(_dom: &DomTree, node: &obscura_dom::Node) -> Vec<Value> {
- if let NodeData::Element { name, attrs, .. } = &node.data {
- let tag = name.local.as_ref();
- let mut props = Vec::new();
-
- // focusable
- let focusable = matches!(
- tag,
- "a" | "button" | "input" | "select" | "textarea" | "details" | "summary"
- ) || attrs.iter().any(|a| {
- let an = a.name.local.as_ref();
- an == "tabindex" || an == "contenteditable"
- });
- if focusable {
- props.push(json!({"name": "focusable", "value": ax_value_boolean(true)}));
- }
-
- // editable
- if tag == "input" || tag == "textarea"
- || attrs
- .iter()
- .any(|a| a.name.local.as_ref() == "contenteditable" && a.value != "false")
- {
- props.push(json!({"name": "editable", "value": ax_value_boolean(true)}));
- }
-
- // checked for checkboxes/radios
- if attrs
- .iter()
- .any(|a| a.name.local.as_ref() == "checked")
- {
- props.push(json!({"name": "checked", "value": ax_value_boolean(true)}));
- }
-
- // disabled
- if attrs
- .iter()
- .any(|a| a.name.local.as_ref() == "disabled")
- {
- props.push(json!({"name": "disabled", "value": ax_value_boolean(true)}));
- }
-
- // level for headings
- if let Some(level) = tag.strip_prefix('h').and_then(|s| s.parse::<u32>().ok()) {
- if level >= 1 && level <= 6 {
- props.push(json!({"name": "level", "value": ax_value_integer(level)}));
- }
- }
-
- // required
- if attrs
- .iter()
- .any(|a| a.name.local.as_ref() == "required" || a.name.local.as_ref() == "aria-required")
- {
- props.push(json!({"name": "required", "value": ax_value_boolean(true)}));
- }
-
- // multiline for textarea
- if tag == "textarea" {
- props.push(json!({"name": "multiline", "value": ax_value_boolean(true)}));
- }
-
- props
- } else {
- Vec::new()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use obscura_dom::parse_html;
-
- fn ax_node_for<'a>(nodes: &'a [Value], backend_node_id: NodeId) -> &'a Value {
- nodes
- .iter()
- .find(|node| node["backendDOMNodeId"] == backend_node_id.raw())
- .expect("element is present in the AX tree")
- }
-
- fn assert_ax_value(nodes: &[Value], dom: &DomTree, id: &str, expected: Option<&str>) {
- let node = ax_node_for(nodes, dom.get_element_by_id(id).unwrap());
- assert_eq!(
- node.get("value").and_then(|value| value["value"].as_str()),
- expected,
- "unexpected AX value for #{id}"
- );
- }
-
- fn assert_name(dom: &DomTree, id: &str, expected: Option<&str>) {
- let nodes = build_ax_nodes(dom);
- let node = ax_node_for(&nodes, dom.get_element_by_id(id).unwrap());
- assert_eq!(
- node.get("name").and_then(|name| name["value"].as_str()),
- expected,
- "#{id}"
- );
- }
-
- #[test]
- fn names_from_content_preserve_inline_words_and_normalize_whitespace() {
- let dom = parse_html(
- r#"<button id="button" title="tooltip"> Save <b>changes</b> now </button>
- <a id="link" href="/">Read <span>the <em>docs</em></span></a>
- <h2 id="heading">Access<b>ibility</b> test</h2>
- <div id="generic">Do not duplicate all descendant text</div>"#,
- );
- assert_name(&dom, "button", Some("Save changes now"));
- assert_name(&dom, "link", Some("Read the docs"));
- assert_name(&dom, "heading", Some("Accessibility test"));
- assert_name(&dom, "generic", None);
- }
-
- #[test]
- fn html_labels_follow_control_association_and_document_order() {
- let dom = parse_html(
- r#"<label for="email"> Work <b>email</b> </label>
- <input id="email" placeholder="fallback"><label for="email">address</label>
- <label>Accept <span>terms</span><input id="accept" type="checkbox"></label>
- <label for="email">Elsewhere<input id="wrong"></label>
- <label>First<input id="first"><input id="second"></label>
- <label for="missing">No association<input id="missing-for"></label>"#,
- );
- assert_name(&dom, "email", Some("Work email address Elsewhere"));
- assert_name(&dom, "accept", Some("Accept terms"));
- assert_name(&dom, "wrong", None);
- assert_name(&dom, "first", Some("First"));
- assert_name(&dom, "second", None);
- assert_name(&dom, "missing-for", None);
- }
-
- #[test]
- fn aria_labelledby_precedes_aria_label_and_native_names() {
- let dom = parse_html(
- r#"<span id="one">First</span><span id="two">Second</span>
- <label for="target">Native</label>
- <button id="target" aria-labelledby="two missing one two" aria-label="ARIA">Content</button>
- <button id="invalid" aria-labelledby="missing" aria-label=" ARIA fallback ">Content</button>
- <button id="blank" aria-label=" ">Content</button>
- <span id="empty"></span><button id="empty-ref" aria-labelledby="empty" aria-label="fallback">Content</button>
- <button id="self" aria-labelledby="self one" aria-label="Self">Content</button>
- <span id="cycle-a" aria-labelledby="cycle-b">A</span><span id="cycle-b" aria-labelledby="cycle-a">B</span>
- <button id="cycle" aria-labelledby="cycle-a">Content</button>"#,
- );
- assert_name(&dom, "target", Some("Second First"));
- assert_name(&dom, "invalid", Some("ARIA fallback"));
- assert_name(&dom, "blank", Some("Content"));
- assert_name(&dom, "empty-ref", Some(""));
- assert_name(&dom, "self", Some("Self First"));
- assert_name(&dom, "cycle", Some("A"));
- }
-
- #[test]
- fn hidden_references_name_controls_without_exposing_hidden_nodes() {
- let dom = parse_html(
- r#"<span id="hidden" hidden>Hidden <span hidden>reference</span></span>
- <span id="visible">Visible <span hidden>noise</span></span>
- <button id="referenced" aria-labelledby="hidden visible">Content</button>
- <label hidden for="native">Hidden native</label><input id="native">
- <button id="content">Shown<span aria-hidden="true"> noise</span><script>noise</script></button>"#,
- );
- assert_name(&dom, "referenced", Some("Hidden reference Visible"));
- assert_name(&dom, "native", Some("Hidden native"));
- assert_name(&dom, "content", Some("Shown"));
- let nodes = build_ax_nodes(&dom);
- let hidden = dom.get_element_by_id("hidden").unwrap();
- assert!(!nodes
- .iter()
- .any(|node| node["backendDOMNodeId"] == hidden.raw()));
- }
-
- #[test]
- fn aria_references_preserve_link_text() {
- let dom = parse_html(
- r#"<span id="label">Read <a href="/terms">terms</a><a href="/secret" hidden> secret</a></span>
- <button id="native-link" aria-labelledby="label" aria-label="Fallback">Continue</button>
- <span id="role-label">Review <span role="link">privacy</span></span>
- <button id="role-link" aria-labelledby="role-label">Continue</button>
- <span id="hidden-label" hidden>Read <a href="/terms" hidden>hidden terms</a></span>
- <button id="hidden-link" aria-labelledby="hidden-label">Continue</button>"#,
- );
- assert_name(&dom, "native-link", Some("Read terms"));
- assert_name(&dom, "role-link", Some("Review privacy"));
- assert_name(&dom, "hidden-link", Some("Read hidden terms"));
- }
-
- #[test]
- fn native_labels_preserve_link_text() {
- let dom = parse_html(
- r#"<label for="explicit">Read <a href="/terms">terms</a> and <span role="link">privacy</span></label>
- <input id="explicit">
- <label>Accept <a href="/terms">terms</a> and <span role="link">privacy</span><input id="implicit" type="checkbox"></label>
- <label for="hidden" hidden>Read <a href="/terms" hidden>hidden terms</a></label><input id="hidden">"#,
- );
- assert_name(&dom, "explicit", Some("Read terms and privacy"));
- assert_name(&dom, "implicit", Some("Accept terms and privacy"));
- assert_name(&dom, "hidden", Some("Read hidden terms"));
- }
-
- #[test]
- fn nested_buttons_remain_excluded_from_content_names() {
- let dom = parse_html(
- r#"<button id="outer">Outer</button><button id="inner" role="link">Nested action</button>"#,
- );
- let outer = dom.get_element_by_id("outer").unwrap();
- let inner = dom.get_element_by_id("inner").unwrap();
- dom.append_child(outer, inner);
- assert_eq!(dom.get_node(inner).unwrap().parent, Some(outer));
- assert_name(&dom, "outer", Some("Outer"));
- assert_name(&dom, "inner", Some("Nested action"));
- }
-
- #[test]
- fn nested_controls_do_not_pollute_labels_or_content_names() {
- let dom = parse_html(
- r#"<label for="field">Account <a href="/">Help</a><select><option>Noise</option></select><textarea>Noise</textarea><span role="textbox">Noise</span><span contenteditable="true">Noise</span><a href="/" role="button">Noise</a><button role="link">Noise</button></label>
- <input id="field"><div role="button" id="button">Open <span role="button">Nested action</span><img alt="folder"></div>"#,
- );
- assert_name(&dom, "field", Some("Account Help"));
- assert_name(&dom, "button", Some("Open folder"));
- }
-
- #[test]
- fn html_and_aria_hidden_subtrees_are_absent() {
- let dom = parse_html(
- r#"<div hidden="false"><button id="html">Hidden</button></div>
- <div aria-hidden="TrUe"><button id="aria" aria-hidden="false">Hidden</button></div>
- <input id="input" type="hidden"><button id="visible" aria-hidden="false">Visible</button>"#,
- );
- let nodes = build_ax_nodes(&dom);
- for id in ["html", "aria", "input"] {
- let id = dom.get_element_by_id(id).unwrap();
- assert!(!nodes
- .iter()
- .any(|node| node["backendDOMNodeId"] == id.raw()));
- }
- assert_name(&dom, "visible", Some("Visible"));
- }
-
- #[test]
- fn native_alternatives_and_aria_override_content() {
- let dom = parse_html(
- r#"<button id="aria" aria-label="Named">Content</button>
- <button id="image"><img alt="Download"></button>
- <img id="decorative" alt="" title="Not a name">
- <input id="submit" type="submit" value="Send">
- <input id="password" type="password" value="secret" placeholder="Password">
- <label for="select">Choice</label><select id="select"><option>Not the name</option></select>"#,
- );
- assert_name(&dom, "aria", Some("Named"));
- assert_name(&dom, "image", Some("Download"));
- assert_name(&dom, "decorative", Some(""));
- assert_name(&dom, "submit", Some("Send"));
- assert_name(&dom, "password", Some("Password"));
- assert_name(&dom, "select", Some("Choice"));
- }
-
- #[test]
- fn content_editing_hosts_expose_ax_values_without_duplicating_descendants() {
- let dom = parse_html(
- r#"<div id="true" contenteditable="TrUe">true</div>
- <div id="empty-keyword" contenteditable>empty keyword</div>
- <div id="plaintext" contenteditable="PlAiNtExT-OnLy">plaintext</div>
- <div id="empty-host" contenteditable></div>
- <div id="host" contenteditable="true">host<span id="inherited"> inherited</span><span id="invalid" contenteditable="bogus"> invalid</span><span id="nested-explicit" contenteditable="plaintext-only"> nested</span></div>
- <div id="disabled" contenteditable="FaLsE">disabled<span id="invalid-disabled" contenteditable="bogus"> inherited off</span><span id="reenabled" contenteditable="TRUE">reenabled<span id="reenabled-child"> child</span></span></div>"#,
- );
- let nodes = build_ax_nodes(&dom);
-
- assert_ax_value(&nodes, &dom, "true", Some("true"));
- assert_ax_value(&nodes, &dom, "empty-keyword", Some("empty keyword"));
- assert_ax_value(&nodes, &dom, "plaintext", Some("plaintext"));
- assert_ax_value(&nodes, &dom, "empty-host", Some(""));
- assert_ax_value(&nodes, &dom, "host", Some("host inherited invalid nested"));
- assert_ax_value(&nodes, &dom, "inherited", None);
- assert_ax_value(&nodes, &dom, "invalid", None);
- assert_ax_value(&nodes, &dom, "nested-explicit", None);
- assert_ax_value(&nodes, &dom, "disabled", None);
- assert_ax_value(&nodes, &dom, "invalid-disabled", None);
- assert_ax_value(&nodes, &dom, "reenabled", Some("reenabled child"));
- assert_ax_value(&nodes, &dom, "reenabled-child", None);
- }
-}
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 02cfa985..e273ccb8 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -4173,6 +4173,17 @@ impl ObscuraJsRuntime {
pub fn accessibility_styles(&self) -> HashMap<NodeId, AccessibilityStyle> {
let mut state = self.state.borrow_mut();
crate::ops::sample_live_document_animations(&mut state);
+ if state.animation_timeline.waapi_nodes().is_empty() {
+ if let Some(styles) = state.dom.as_ref().and_then(|dom| {
+ obscura_render::dom::accessibility_styles_without_layout(
+ dom, state.viewport, state.render_media, &state.stylesheet_cache,
+ )
+ }) {
+ return styles.into_iter().map(|(id, (display_none, visibility_hidden))| {
+ (id, AccessibilityStyle { display_none, visibility_hidden })
+ }).collect();
+ }
+ }
let Some(prepared) = crate::ops::ensure_prepared_render(&mut state) else {
return HashMap::new();
};
@@ -4713,6 +4724,18 @@ mod tests {
rt
}
+ #[cfg(feature = "render")]
+ #[test]
+ fn static_accessibility_visibility_does_not_allocate_geometry() {
+ let rt = setup_runtime("<!doctype html><style>.gone{display:none}.hidden{visibility:hidden}.shown{visibility:visible}</style><div class=gone id=gone>hidden</div><div class=hidden id=hidden><span class=shown id=shown>visible</span></div>");
+ let styles = rt.accessibility_styles();
+ let ids = rt.with_dom(|dom| ["gone", "hidden", "shown"].map(|id| dom.get_element_by_id(id).unwrap())).unwrap();
+ assert!(styles[&ids[0]].display_none);
+ assert_eq!(styles[&ids[1]].visibility_hidden, Some(true));
+ assert_eq!(styles[&ids[2]].visibility_hidden, Some(false));
+ assert!(rt.state.borrow().prepared_render.is_none(), "a static visibility read must not retain layout/text geometry for an entire document");
+ }
+
#[test]
fn document_content_type_retains_url_fallback_without_response_metadata() {
let mut rt = ObscuraJsRuntime::new();
diff --git a/crates/obscura-mcp/src/lib.rs b/crates/obscura-mcp/src/lib.rs
index f5c02a6c..5d4f03ea 100644
--- a/crates/obscura-mcp/src/lib.rs
+++ b/crates/obscura-mcp/src/lib.rs
@@ -372,11 +372,11 @@ fn handle_tools_list(id: Value) -> RpcResponse {
},
{
"name": "browser_snapshot",
- "description": "Get the current page content as text (title, URL, and readable body text)",
+ "description": "Get URL, title, actionable element references, control states, and visible body text",
"inputSchema": {
"type": "object",
"properties": {
- "max_chars": { "type": "number", "minimum": 0, "description": "Truncate readable body text to this many characters (default: 4000)" }
+ "max_chars": { "type": "number", "minimum": 0, "description": "Character budget shared by whole control descriptions and visible body text (default: 4000); URL and title are separately capped at 256 characters each" }
},
"additionalProperties": false
}
@@ -1037,28 +1037,35 @@ fn tool_snapshot(args: &Value, state: &mut BrowserState) -> Result<String, Strin
.unwrap_or(DEFAULT_TEXT_LIMIT);
rebuild_interactive_refs(state)?;
let page = state.page_mut();
- let url = page.url_string();
- let title = page.title.clone();
-
+ let url = truncate(&page.url_string(), 256);
+ let title = truncate(&page.title, 256);
+ if max_chars == 0 { return Ok(format!("URL: {url}\nTitle: {title}")); }
+ let context = accessibility_context(page);
let body_text = page.with_dom(|dom| {
if let Ok(Some(body)) = dom.query_selector("body") {
- extract_text(dom, body)
+ extract_text(dom, body, context.as_ref())
} else {
String::new()
}
}).unwrap_or_default();
- let refs_summary = if state.interactive_refs.is_empty() {
- String::new()
- } else {
- format!(
- "\n\n{} interactive element(s) registered. Call browser_interactive_elements to list, or pass `ref` to browser_click/browser_fill/browser_type.",
- state.interactive_refs.len(),
- )
- };
-
- let body = truncate(body_text.trim(), max_chars);
- Ok(format!("URL: {url}\nTitle: {title}\n\n{body}{refs_summary}"))
+ let lines = context.as_ref().map(|context| interactive_lines(state, context, usize::MAX)).unwrap_or_default();
+ let mut content = String::new();
+ let mut remaining = max_chars;
+ let mut shown = 0;
+ for line in &lines {
+ let cost = line.chars().count() + 1;
+ if cost > remaining { break; }
+ content.push_str(line);
+ content.push('\n');
+ remaining -= cost;
+ shown += 1;
+ }
+ if shown < lines.len() {
+ content.push_str(&format!("...({} controls omitted; use browser_interactive_elements)\n", lines.len() - shown));
+ }
+ content.push_str(&truncate(body_text.trim(), remaining));
+ Ok(format!("URL: {url}\nTitle: {title}\n\n{content}"))
}
async fn tool_click(args: &Value, state: &mut BrowserState) -> Result<String, String> {
@@ -1408,45 +1415,51 @@ fn tool_links(args: &Value, state: &mut BrowserState) -> Result<String, String>
fn tool_interactive_elements(args: &Value, state: &mut BrowserState) -> Result<String, String> {
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(100) as usize;
rebuild_interactive_refs(state)?;
- if state.interactive_refs.is_empty() {
+ let context = accessibility_context(state.page_mut());
+ let lines = context.as_ref().map(|context| interactive_lines(state, context, limit)).unwrap_or_default();
+ if lines.is_empty() {
return Ok("No interactive elements on this page.".to_string());
}
- let page = state.page_mut();
- let js = format!(r#"(function(){{
- var els = document.querySelectorAll('[data-obscura-ref]');
- var out = [];
- for (var i = 0; i < els.length && out.length < {limit}; i++) {{
- var e = els[i];
- var label = (e.innerText || e.textContent || e.getAttribute('aria-label') || e.getAttribute('placeholder') || e.getAttribute('value') || e.getAttribute('name') || '').trim().replace(/\s+/g, ' ').slice(0, 80);
- var role = e.getAttribute('role') || '';
- var typeAttr = e.getAttribute('type') || '';
- out.push({{
- ref: e.getAttribute('data-obscura-ref'),
- tag: e.tagName.toLowerCase(),
- type: typeAttr,
- role: role,
- name: e.getAttribute('name') || '',
- label: label,
- }});
- }}
- return out;
- }})()"#);
- let val = evaluate_tool_script(page, &js)?;
- let arr = val.as_array().cloned().unwrap_or_default();
- let lines: Vec<String> = arr.into_iter().map(|item| {
- let r = item.get("ref").and_then(|v| v.as_str()).unwrap_or("?");
- let tag = item.get("tag").and_then(|v| v.as_str()).unwrap_or("?");
- let ty = item.get("type").and_then(|v| v.as_str()).unwrap_or("");
- let label = item.get("label").and_then(|v| v.as_str()).unwrap_or("");
- let name = item.get("name").and_then(|v| v.as_str()).unwrap_or("");
- let role = item.get("role").and_then(|v| v.as_str()).unwrap_or("");
- let kind = if !ty.is_empty() { format!("{tag}[{ty}]") } else if !role.is_empty() { format!("{tag}[role={role}]") } else { tag.to_string() };
- let detail = if !name.is_empty() { format!(" name={name:?}") } else { String::new() };
- format!("ref={r:<5} {kind:<22} {label:?}{detail}")
- }).collect();
Ok(lines.join("\n"))
}
+fn accessibility_context(page: &Page) -> Option<obscura_browser::accessibility::AccessibilityContext> {
+ #[cfg(feature = "render")]
+ let styles = page.js.as_ref().map(|js| js.accessibility_styles()).unwrap_or_default();
+ #[cfg(not(feature = "render"))]
+ let styles = HashMap::new();
+ page.with_dom(|dom| obscura_browser::accessibility::AccessibilityContext::for_document(dom, &styles))
+}
+
+fn interactive_lines(state: &BrowserState, context: &obscura_browser::accessibility::AccessibilityContext, limit: usize) -> Vec<String> {
+ let Some(page) = state.active_tab.as_ref().and_then(|id| state.tabs.get(id)) else { return Vec::new(); };
+ let refs: HashMap<_, _> = state.interactive_refs.iter().map(|(reference, id)| (id.raw(), reference.as_str())).collect();
+ page.with_dom(|dom| dom.descendants(dom.document()).into_iter().filter_map(|id| {
+ let reference = refs.get(&id.raw())?;
+ let ax = context.describe_node(dom, id)?;
+ let node = dom.get_node(id)?;
+ let tag = node.as_element()?.local.as_ref();
+ let preview = |value: &str| value.chars().take(80).collect::<String>();
+ let label = ax["name"]["value"].as_str().map(str::to_owned)
+ .unwrap_or_else(|| extract_text(dom, id, Some(context)).trim().to_string());
+ let label = preview(&label);
+ let role = ax["role"]["value"].as_str().unwrap_or("generic");
+ let mut line = format!("ref={reference} {tag} {label:?} role={role}");
+ if let Some(kind) = node.get_attribute("type") { line.push_str(&format!(" type={:?}", preview(kind))); }
+ if let Some(name) = node.get_attribute("name") { line.push_str(&format!(" name={:?}", preview(name))); }
+ if let Some(value) = ax["value"]["value"].as_str() { line.push_str(&format!(" value={:?}", preview(value))); }
+ if let Some(properties) = ax["properties"].as_array() {
+ for property in properties {
+ let name = property["name"].as_str().unwrap_or("");
+ if matches!(name, "checked" | "disabled" | "required" | "expanded" | "selected" | "pressed") {
+ line.push_str(&format!(" {name}={}", property["value"]["value"]));
+ }
+ }
+ }
+ Some(line)
+ }).take(limit).collect()).unwrap_or_default()
+}
+
/// Rebuild the ref table: walk the DOM, find every interactable, assign
/// a stable `data-obscura-ref="eN"` attribute, remember the nid for later
/// validation. Called on every snapshot / interactive-elements call so the
@@ -1999,7 +2012,7 @@ fn append_text_segment(result: &mut String, pending_space: &mut bool, contents:
*pending_space = contents.chars().next_back().is_some_and(is_html_whitespace);
}
-fn extract_text(dom: &obscura_dom::DomTree, node_id: obscura_dom::NodeId) -> String {
+fn extract_text(dom: &obscura_dom::DomTree, node_id: obscura_dom::NodeId, context: Option<&obscura_browser::accessibility::AccessibilityContext>) -> String {
use obscura_dom::NodeData;
enum Work {
@@ -2036,11 +2049,13 @@ fn extract_text(dom: &obscura_dom::DomTree, node_id: obscura_dom::NodeId) -> Str
match &node.data {
NodeData::Text { contents } => {
- append_text_segment(&mut result, &mut pending_space, contents);
+ if context.is_none_or(|context| !context.is_hidden(id)) {
+ append_text_segment(&mut result, &mut pending_space, contents);
+ }
}
NodeData::Element { name, .. } => {
let tag = name.local.as_ref();
- if matches!(tag, "script" | "style" | "noscript") {
+ if matches!(tag, "script" | "style" | "noscript" | "template") {
continue;
}
@@ -2087,7 +2102,7 @@ fn tool_search(args: &Value, state: &mut BrowserState) -> Result<String, String>
let page = state.page_mut();
let body = page.with_dom(|dom| {
dom.query_selector("body").ok().flatten()
- .map(|b| extract_text(dom, b))
+ .map(|b| extract_text(dom, b, None))
.unwrap_or_default()
}).unwrap_or_default();
@@ -2283,6 +2298,82 @@ fn tool_set_storage_state(args: &Value, state: &mut BrowserState) -> Result<Stri
mod tests {
use super::*;
+ #[tokio::test(flavor = "current_thread")]
+ async fn snapshot_references_are_actionable_without_an_extra_listing() {
+ let mut state = BrowserState::new(None, None, false);
+ state.page_mut().navigate("data:text/html,<label for=q>Work email</label><input id=q><button aria-label='Save account' onclick='window.saved=true'>Unhelpful text</button>").await.unwrap();
+ let snapshot = tool_snapshot(&json!({}), &mut state).unwrap();
+ let action = snapshot.lines().find(|line| line.starts_with("ref=") && line.contains("Save account"))
+ .expect("snapshot must include an accessible name and usable reference");
+ let reference = action.split_whitespace().next().unwrap().strip_prefix("ref=").unwrap();
+ let reference = reference.to_string();
+ assert!(snapshot.lines().any(|line| line.starts_with("ref=") && line.contains("Work email")), "associated labels must name fields: {snapshot}");
+ tool_click(&json!({"ref":reference}), &mut state).await.unwrap();
+ assert_eq!(state.page_mut().evaluate("window.saved"), json!(true));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn snapshot_exposes_live_states_without_password_values() {
+ let mut state = BrowserState::new(None, None, false);
+ state.page_mut().navigate("data:text/html,<input id=c type=checkbox checked aria-label=Consent><input id=f value=old aria-label=Account><input id=p type=password aria-label=Password><button disabled>Blocked</button><div role=tab aria-selected=true>Overview</div><button aria-expanded=false>Details</button>").await.unwrap();
+ state.page_mut().evaluate("(function(){document.getElementById('c').checked=false;document.getElementById('f').value='fresh';document.getElementById('p').value='private-password';return true;})()");
+ let snapshot = tool_snapshot(&json!({}), &mut state).unwrap();
+ for (label, detail) in [("Consent", "checked=false"), ("Account", "value=\"fresh\""), ("Blocked", "disabled=true"), ("Overview", "selected=true"), ("Details", "expanded=false")] {
+ assert!(snapshot.lines().any(|line| line.starts_with("ref=") && line.contains(label) && line.contains(detail)), "missing {label} {detail}: {snapshot}");
+ }
+ assert!(!snapshot.contains("private-password"), "automatic snapshots must not echo password values");
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn snapshot_budget_bounds_metadata_and_never_splits_a_reference() {
+ let mut state = BrowserState::new(None, None, false);
+ let html = format!("<title>{}</title><button>Continue</button><p>{}</p>", "界".repeat(1000), "Body ".repeat(2000));
+ state.page_mut().navigate(&format!("data:text/html,{html}")).await.unwrap();
+ let snapshot = tool_snapshot(&json!({"max_chars":96}), &mut state).unwrap();
+ assert!(snapshot.chars().count() < 900, "metadata must not bypass the content budget: {} characters", snapshot.chars().count());
+ for line in snapshot.lines().filter(|line| line.starts_with("ref=")) {
+ let reference = line.split_whitespace().next().unwrap().strip_prefix("ref=").unwrap();
+ assert!(state.interactive_refs.contains_key(reference), "a truncated ref must never be advertised");
+ assert!(line.contains("Continue"), "whole descriptions must fit or be omitted");
+ }
+ assert!(snapshot.contains("truncated") || snapshot.contains("omitted"), "omission must be explicit");
+ let empty = tool_snapshot(&json!({"max_chars":0}), &mut state).unwrap();
+ assert!(!empty.lines().any(|line| line.starts_with("ref=")));
+ assert!(empty.chars().count() < 800);
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn snapshot_omits_hidden_content_and_controls() {
+ let mut state = BrowserState::new(None, None, false);
+ state.page_mut().navigate("data:text/html,<p>Visible</p><div hidden><button>Hidden action</button><p>Hidden body</p></div><div aria-hidden=true>Private panel</div>").await.unwrap();
+ let snapshot = tool_snapshot(&json!({}), &mut state).unwrap();
+ let content = snapshot.split_once("\n\n").unwrap().1;
+ for hidden in ["Hidden action", "Hidden body", "Private panel"] {
+ assert!(!content.contains(hidden), "hidden content must not be exposed as visible context: {content}");
+ }
+ assert!(content.contains("Visible"));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn snapshots_preserve_generic_interactive_text_and_hidden_referenced_names() {
+ let mut state = BrowserState::new(None, None, false);
+ state.page_mut().navigate("data:text/html,<div tabindex=0 onclick='window.opened=true'>Open <b>folder</b></div><span id=label hidden>Accessible details</span><button aria-labelledby=label>Other text</button>").await.unwrap();
+ let snapshot = tool_snapshot(&json!({}), &mut state).unwrap();
+ assert!(snapshot.lines().any(|line| line.starts_with("ref=") && line.contains("Open folder")), "unlabelled generic controls must keep their visible text: {snapshot}");
+ assert!(snapshot.lines().any(|line| line.starts_with("ref=") && line.contains("Accessible details")), "hidden referenced text still supplies the visible control's name: {snapshot}");
+ }
+
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn snapshots_apply_css_visibility_without_hiding_visible_overrides() {
+ let mut state = BrowserState::new(None, None, false);
+ state.page_mut().navigate("data:text/html,<style>.gone{display:none}.invisible{visibility:hidden}.shown{visibility:visible}</style><div class=gone><button>CSS hidden action</button></div><div class=invisible>Hidden text<button class=shown>Visible override</button></div>").await.unwrap();
+ let snapshot = tool_snapshot(&json!({}), &mut state).unwrap();
+ let content = snapshot.split_once("\n\n").unwrap().1;
+ assert!(!content.contains("CSS hidden action") && !content.contains("Hidden text"), "{content}");
+ assert!(content.lines().any(|line| line.starts_with("ref=") && line.contains("Visible override")), "a visible descendant must remain actionable: {content}");
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn tool_serialization_deadline_recovers_the_page() {
// A missing production watchdog must fail this nextest process, not hang CI.
diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rs
index 7f0f21c5..8dbb68cc 100644
--- a/crates/obscura-render/src/dom.rs
+++ b/crates/obscura-render/src/dom.rs
@@ -4575,26 +4575,36 @@ impl NonGeometricStyleCache {
) -> Option<Self> {
let sources = document_stylesheet_sources(tree, viewport, media_type);
let sheet = cache.get(&sources, viewport, media_type)?;
+ Some(Self::from_sheet(tree, viewport, sheet))
+ }
+
+ fn from_sheet(tree: &DomTree, viewport: (f32, f32), sheet: std::sync::Arc<crate::css::Stylesheet>) -> Self {
let quirks = !tree.children(tree.document()).iter().any(|node| {
tree.borrow_node(*node).is_some_and(|node| {
matches!(node.data, obscura_dom::tree::NodeData::Doctype { .. })
})
});
- Some(Self {
+ Self {
has_container_queries: sheet.has_container_queries(), sheet, viewport, quirks,
styles: HashMap::new(), custom_properties: HashMap::new(), ancestors: HashMap::new(),
path: Vec::new(),
- })
+ }
}
pub fn resolve(
&mut self, tree: &DomTree, id: NodeId, property: &str,
) -> Option<HashMap<&'static str, String>> {
+ self.resolve_style(tree, id, property).map(crate::paint::non_geometric_computed_style)
+ }
+
+ fn resolve_style(
+ &mut self, tree: &DomTree, id: NodeId, property: &str,
+ ) -> Option<&crate::LayoutStyle> {
if !Self::supports(property) || !tree.is_connected(id) {
return None;
}
if self.ancestors.contains_key(&id) {
- return Some(crate::paint::non_geometric_computed_style(self.styles.get(&id)?));
+ return self.styles.get(&id);
}
let mut path = tree.ancestors(id);
path.reverse();
@@ -4690,10 +4700,39 @@ impl NonGeometricStyleCache {
}
self.ancestors.insert(node, (cell_padding, dark, ancestor_display_none, parent_is_item_container));
}
- Some(crate::paint::non_geometric_computed_style(self.styles.get(&id)?))
+ self.styles.get(&id)
}
}
+/// Read display/visibility without retaining geometry or styles for completed branches.
+/// Unsupported cascade dependencies leave the full renderer as the authority.
+#[cfg(feature = "paint")]
+pub fn accessibility_styles_without_layout(
+ tree: &DomTree,
+ viewport: (f32, f32),
+ media_type: crate::CssMediaType,
+ cache: &crate::css::StylesheetCache,
+) -> Option<HashMap<NodeId, (bool, Option<bool>)>> {
+ let sources = document_stylesheet_sources(tree, viewport, media_type);
+ // This document-wide read checks every animation owner before returning.
+ // Keep ordinary CSSOM cold-read behavior and retained-layout keys unchanged.
+ let sheet = cache.get(&sources, viewport, media_type).unwrap_or_else(|| std::sync::Arc::new(
+ crate::css::Stylesheet::parse_for_viewport_and_media(tree, &sources, viewport, media_type),
+ ));
+ let mut cascade = NonGeometricStyleCache::from_sheet(tree, viewport, sheet);
+ let mut result = HashMap::new();
+ for id in tree.descendants(tree.document()) {
+ if !tree.with_node(id, |node| node.is_element()).unwrap_or(false) { continue; }
+ let style = cascade.resolve_style(tree, id, "visibility")?;
+ if style.animation_name.is_some() { return None; }
+ result.insert(id, (style.display == crate::Display::None, style.visibility_hidden));
+ let path = &cascade.path;
+ cascade.styles.retain(|id, _| path.contains(id));
+ cascade.ancestors.retain(|id, _| path.contains(id));
+ }
+ Some(result)
+}
+
fn document_stylesheet_sources(
tree: &DomTree,
viewport: (f32, f32),
@@ -15547,6 +15586,33 @@ mod tests {
use obscura_dom::tree::ShadowRootMode;
use obscura_dom::tree_sink::parse_html;
+ #[cfg(feature = "paint")]
+ #[test]
+ fn accessibility_style_reads_preserve_visibility_and_the_retained_cache_key() {
+ let tree = parse_html("<!doctype html><style>body{--conceal:hidden}.hidden{visibility:var(--conceal)}.shown{visibility:visible}.gone{display:none}</style><div class=hidden id=hidden><span class=shown id=shown>shown</span></div><div class=gone id=gone>gone</div>");
+ let sheets = crate::StylesheetCache::default();
+ let styles = accessibility_styles_without_layout(&tree, (400.0,200.0), crate::CssMediaType::Screen, &sheets).unwrap();
+ assert_eq!(styles[&tree.get_element_by_id("hidden").unwrap()].1, Some(true));
+ assert_eq!(styles[&tree.get_element_by_id("shown").unwrap()].1, Some(false));
+ assert!(styles[&tree.get_element_by_id("gone").unwrap()].0);
+ assert_eq!(sheets.retained_source_bytes(), 0, "a read must not bless an unrelated retained layout with a new stylesheet key");
+ }
+
+ #[cfg(feature = "paint")]
+ #[test]
+ fn accessibility_styles_decline_animations_containers_and_shadow_dependencies() {
+ for source in [
+ "<!doctype html><style>@keyframes move{to{transform:translateX(1px)}}#x{animation:move 1s infinite}</style><p id=x>animated</p>",
+ "<!doctype html><style>.c{container-type:inline-size}@container(min-width:1px){#x{visibility:hidden}}</style><div class=c><p id=x>query</p></div>",
+ ] {
+ let tree = parse_html(source);
+ assert!(accessibility_styles_without_layout(&tree, (400.0,200.0), crate::CssMediaType::Screen, &crate::StylesheetCache::default()).is_none(), "unsupported dependencies must use full preparation: {source}");
+ }
+ let tree = parse_html("<!doctype html><div id=host></div><section id=source><style>:host{display:none}</style></section>");
+ attach_programmatic_shadow(&tree, tree.get_element_by_id("host").unwrap(), tree.get_element_by_id("source").unwrap());
+ assert!(accessibility_styles_without_layout(&tree, (400.0,200.0), crate::CssMediaType::Screen, &crate::StylesheetCache::default()).is_none());
+ }
+
fn attach_programmatic_shadow(tree: &DomTree, host: NodeId, source: NodeId) -> NodeId {
let root = tree
.attach_shadow_root(host, ShadowRootMode::Open)
diff --git a/docs/Use-the-MCP-server.md b/docs/Use-the-MCP-server.md
index 6eb4cb8e..3da184ee 100644
--- a/docs/Use-the-MCP-server.md
+++ b/docs/Use-the-MCP-server.md
@@ -66,10 +66,22 @@ Navigation and lifecycle:
Read the page:
-- `browser_snapshot`: current URL, title, readable body text, and interactive
- element references. Optional `max_chars` limits the returned text.
+- `browser_snapshot`: current URL, title, actionable element references, control
+ states, and visible body text. References can be passed directly to interaction
+ tools without a separate listing call. Names use the same native accessibility
+ logic as CDP, including associated labels and ARIA name precedence.
+ `max_chars` defaults to 4000 and is shared by whole control descriptions first,
+ then body text. Omission markers are added outside that budget. URL and title
+ are separately capped at 256 characters each; `max_chars: 0` returns only that
+ metadata. Descriptions preview at most 80 characters per name or value and
+ do not include password control values.
- `browser_markdown`, `browser_links`, `browser_extract`: page as markdown, link list, or structured content.
- `browser_interactive_elements`, `browser_detect_forms`: actionable elements and form fields.
+
+Snapshots and interactive-element listings exclude HTML/ARIA-hidden content;
+render builds also apply computed CSS visibility. Hidden text explicitly
+referenced by a visible control can still supply its accessible name. These are
+compact browsing context, not a claim of complete accessibility conformance.
- `browser_get_attribute`, `browser_count`, `browser_search`: read an attribute, count matches, find text.
Interact: