1use crate::session::BrowserSession;
5use adk_core::{Result, Tool, ToolContext, ToolEffect};
6use async_trait::async_trait;
7use serde_json::{Value, json};
8use std::sync::Arc;
9
10const DEFAULT_LIMIT: u64 = 200;
12const MAX_LIMIT: u64 = 500;
14
15const ELEMENTS_SCRIPT: &str = r#"
18const LIMIT = __LIMIT__;
19const QUERY = 'a[href], button, input:not([type=hidden]), select, textarea, summary, label[for], '
20 + '[role=button], [role=link], [role=checkbox], [role=radio], [role=tab], [role=menuitem], '
21 + '[role=option], [role=switch], [role=textbox], [role=combobox], [role=searchbox], '
22 + '[contenteditable=""], [contenteditable=true], [onclick], [tabindex]:not([tabindex="-1"])';
23const unique = (sel) => { try { return document.querySelectorAll(sel).length === 1; } catch (e) { return false; } };
24const quote = (v) => '"' + v.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
25function selectorFor(el) {
26 if (el.id && unique('#' + CSS.escape(el.id))) return '#' + CSS.escape(el.id);
27 const tag = el.tagName.toLowerCase();
28 for (const attr of ['data-testid', 'data-test', 'data-qa', 'name', 'aria-label']) {
29 const v = el.getAttribute(attr);
30 if (v) { const s = tag + '[' + attr + '=' + quote(v) + ']'; if (unique(s)) return s; }
31 }
32 const parts = [];
33 let node = el;
34 while (node && node.nodeType === 1 && node !== document.documentElement) {
35 if (node !== el && node.id && unique('#' + CSS.escape(node.id))) { parts.unshift('#' + CSS.escape(node.id)); break; }
36 let i = 1, sib = node;
37 while ((sib = sib.previousElementSibling)) if (sib.tagName === node.tagName) i++;
38 parts.unshift(node.tagName.toLowerCase() + ':nth-of-type(' + i + ')');
39 node = node.parentElement;
40 }
41 if (!parts.length || !parts[0].startsWith('#')) parts.unshift('html');
42 return parts.join(' > ');
43}
44function roleOf(el) {
45 const role = el.getAttribute('role');
46 if (role) return role;
47 const tag = el.tagName.toLowerCase();
48 if (tag === 'a') return 'link';
49 if (tag === 'select') return 'combobox';
50 if (tag === 'textarea') return 'textbox';
51 if (tag === 'input') {
52 const type = (el.getAttribute('type') || 'text').toLowerCase();
53 if (['button', 'submit', 'reset', 'image'].includes(type)) return 'button';
54 if (['checkbox', 'radio', 'range'].includes(type)) return type === 'range' ? 'slider' : type;
55 return type === 'search' ? 'searchbox' : 'textbox';
56 }
57 return tag;
58}
59function nameOf(el) {
60 const clip = (t) => (t || '').replace(/\s+/g, ' ').trim().slice(0, 80);
61 const label = el.getAttribute('aria-label');
62 if (label) return clip(label);
63 const by = el.getAttribute('aria-labelledby');
64 if (by) { const t = by.split(/\s+/).map((id) => document.getElementById(id)).filter(Boolean).map((n) => n.textContent).join(' '); if (clip(t)) return clip(t); }
65 if (el.labels && el.labels.length) return clip(Array.from(el.labels).map((l) => l.textContent).join(' '));
66 const tag = el.tagName.toLowerCase();
67 if (tag === 'input' && ['button', 'submit', 'reset'].includes((el.type || '').toLowerCase())) return clip(el.value);
68 const text = clip(el.innerText || el.textContent);
69 if (text) return text;
70 return clip(el.getAttribute('alt') || el.getAttribute('title') || el.getAttribute('placeholder') || '');
71}
72const vw = window.innerWidth, vh = window.innerHeight;
73const round = (v) => Math.round(v * 100) / 100;
74const seen = new Set();
75const elements = [];
76let truncated = false;
77for (const el of document.querySelectorAll(QUERY)) {
78 if (seen.has(el)) continue;
79 seen.add(el);
80 if (el.disabled) continue;
81 const r = el.getBoundingClientRect();
82 if (r.width < 1 || r.height < 1 || r.right <= 0 || r.bottom <= 0 || r.left >= vw || r.top >= vh) continue;
83 const style = getComputedStyle(el);
84 if (style.visibility === 'hidden' || style.display === 'none' || Number(style.opacity) === 0) continue;
85 if (elements.length >= LIMIT) { truncated = true; break; }
86 elements.push({
87 index: elements.length + 1,
88 selector: selectorFor(el),
89 role: roleOf(el),
90 name: nameOf(el),
91 tag: el.tagName.toLowerCase(),
92 rect: { x: round(r.left), y: round(r.top), width: round(r.width), height: round(r.height) },
93 });
94}
95return {
96 url: location.href,
97 devicePixelRatio: window.devicePixelRatio || 1,
98 viewport: { width: vw, height: vh },
99 elements,
100 truncated,
101};
102"#;
103
104pub struct ElementsTool {
121 browser: Arc<BrowserSession>,
122}
123
124impl ElementsTool {
125 pub fn new(browser: Arc<BrowserSession>) -> Self {
127 Self { browser }
128 }
129}
130
131#[async_trait]
132impl Tool for ElementsTool {
133 fn name(&self) -> &str {
134 "browser_elements"
135 }
136
137 fn description(&self) -> &str {
138 "List the visible interactive elements in the viewport: links, buttons, inputs and \
139 controls, each with its rectangle in CSS pixels, its role and name, and a CSS selector \
140 that matches only it. Draw them as numbered marks on a screenshot with vision_annotate \
141 (units css, this answer's devicePixelRatio) and click the chosen element with \
142 browser_click and its selector."
143 }
144
145 fn parameters_schema(&self) -> Option<Value> {
146 Some(json!({
147 "type": "object",
148 "properties": {
149 "limit": {
150 "type": "integer",
151 "minimum": 1,
152 "maximum": MAX_LIMIT,
153 "description": format!("Most elements to return, in document order (default {DEFAULT_LIMIT}).")
154 }
155 }
156 }))
157 }
158
159 fn response_schema(&self) -> Option<Value> {
160 Some(json!({
161 "type": "object",
162 "properties": {
163 "url": { "type": "string" },
164 "devicePixelRatio": { "type": "number" },
165 "viewport": {
166 "type": "object",
167 "properties": { "width": { "type": "number" }, "height": { "type": "number" } }
168 },
169 "elements": {
170 "type": "array",
171 "items": {
172 "type": "object",
173 "properties": {
174 "index": { "type": "integer" },
175 "selector": { "type": "string" },
176 "role": { "type": "string" },
177 "name": { "type": "string" },
178 "tag": { "type": "string" },
179 "rect": {
180 "type": "object",
181 "properties": {
182 "x": { "type": "number" }, "y": { "type": "number" },
183 "width": { "type": "number" }, "height": { "type": "number" }
184 }
185 }
186 }
187 }
188 },
189 "truncated": { "type": "boolean" }
190 }
191 }))
192 }
193
194 fn is_read_only(&self) -> bool {
195 true
196 }
197
198 fn is_concurrency_safe(&self) -> bool {
199 true
200 }
201
202 fn effect(&self) -> ToolEffect {
203 ToolEffect::ReadOnly
204 }
205
206 async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
207 let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(DEFAULT_LIMIT);
208 let limit = limit.clamp(1, MAX_LIMIT);
209 let body = ELEMENTS_SCRIPT.replace("__LIMIT__", &limit.to_string());
210 let answer =
211 self.browser.execute_script(&crate::viewport::script("elements", &body)).await?;
212 if !answer.get("elements").is_some_and(Value::is_array) {
213 return Err(adk_core::AdkError::tool(
214 "Error: the page did not return its elements; reload it and call \
215 browser_elements again",
216 ));
217 }
218 Ok(answer)
219 }
220}