Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Browser: numbered refs for page controls, hit-tested before each click
Lin (kwant bot)4f494b5e8e69
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bfe444a3..ef0f080f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -57,6 +57,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).the notification toggles. This is step 4 of Automation Discovery.### Changed+- **Bots click page controls by number, and never through a banner.** The page a bot reads lists+ its buttons, links and fields as numbered refs with their role (`[9] button "Add to cart" · Sauce+ Labs Bike Light`), naming the product or row when several share a name. A bot clicks or types by+ ref, so the click hits exactly that control (scrolled into view, also inside frames). If it has+ gone, been hidden or renamed, or a cookie banner or dialog covers it, nothing is clicked and the bot+ gets a fresh list with the reason. Clicking by label still works.- **Browser checkouts ask before paying, also behind a plain "Continue".** Before a bot clicks orpresses Enter or Space in its browser, kwant reads the page: the button the click would really hit, cardnumber or CVC fields, a payment provider's card frame (Stripe, Braintree, Adyen, …) and forms thatdiff --git a/docs/bot-browser.md b/docs/bot-browser.mdnew file mode 100644index 00000000..3fc6376c--- /dev/null+++ b/docs/bot-browser.md@@ -0,0 +1,31 @@+# How bots use their browser++Bots drive the browser in their side panel through `browser_open`, `browser_page` and `browser_act`+(kwnt's own tools) or the shell API (`/api/sandbox/:id/{navigate,page,act}`). Both return the same+compact page state: `url`, `title`, `text`, `clickable`. Payments are covered in+[payments.md](payments.md); the person's live view uses `/interact`, which bots can't call.++## Clicking by ref++`BrowserController::list_clickables` (every page state the bot gets: `/page`, `/act`, `browser_*`)+numbers the controls it lists, topmost first: `[ref] role "name"`, plus ` · context` when several+controls share a name (the first line of the largest block around it holding no other control of+that name, e.g. the product card). Listing keeps the elements in the page+(`window[Symbol.for('kwnt.refs')]`), so the refs a bot was last shown are the ones that resolve.++`browser_act` / `/act` take `{"action": "click", "ref": 9}` (also `type` with a ref, which clicks that+field first). A whole copied line as `text` (`[9] button "Add to cart" · …`) counts as that ref; a bare+`[1]` stays a label (footnote links). Before clicking, `REF_JS` checks the element is still in the+page, shown, still has the same label, and is the topmost element at its center after scrolling it+into view (and the frame it sits in is topmost too). Then kwant clicks there with real mouse events.+Otherwise nothing is clicked and the error says why (`gone`, `hidden`, `now reads "…"`, `covered by div+"Cookie banner"`, `no list of refs yet` after a reload); the page state returned with it is a fresh+list. The payment floor judges the element the ref points to.++Limits: the page can read or change the list like anything else on it; another page read between+the payment check and the click renumbers it (one bot drives one browser, so rare).++## Tests++`tests/browser_refs_test.rs` (real Chrome, skipped without one; `saucedemo_by_refs` is ignored and+needs the network) and `ref_tests` in `src/sandbox/browser.rs`.diff --git a/docs/live-activity.md b/docs/live-activity.mdindex ec50edfe..f233c010 100644--- a/docs/live-activity.md+++ b/docs/live-activity.md@@ -135,7 +135,7 @@ While a step is open in a bot browser:The person can use the live view freely.**Bots never see typed passwords.** The agent's browser tools are `browser_open`, `browser_page`-and `browser_act` (click by text, type, key, scroll); there is no script tool. Page reads use+and `browser_act` (click by ref or text, type, key, scroll); there is no script tool. Page reads use`innerText` and element labels, which never include the value of an input (only submit and buttonlabels), and all three tools are refused while the step is open. This covers kwnt's own browsertools; a CLI engine's own built-in browser or shell is outside it.diff --git a/docs/payments.md b/docs/payments.mdindex 1f512d58..ee7eb308 100644--- a/docs/payments.md+++ b/docs/payments.md@@ -65,7 +65,8 @@ every MCP tool, through claude's permission prompt and the MCP gateway), inBefore the click or key, kwnt also reads the page itself (`BrowserController::payment_signals`,rules in `payment_floor::page_reason`), so the bot's own words never decide:-- The element the click would really hit (the same match `click_text` makes) has a pay-type+- The element the click would really hit (the control a `ref` points to, or the same match+ `click_text` makes) has a pay-typelabel: the bot wrote "order", the button is "Place order".- A button on a page with card fields: a card number or CVC field (`autocomplete="cc-number"`,`cc-csc`, `cc-exp`, or a name/id/placeholder like `cardnumber`, `cvc`, `cvv`), in open shadowdiff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex a53a5135..c94c7de6 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -436,11 +436,11 @@ impl TurnInput {Your browser session is displayed live in the user's right panel; the user can browse in it too.\n\Never open a host desktop browser (no `open <url>`, `xdg-open`, etc.) and don't use the shell or curl for it. Use ONLY your `{tools}` tools:\n\- `browser_open` (url): open a page.\n\- - `browser_page`: read the page (url, title, text, clickable labels).\n\- - `browser_act` (action click_text + text, type + text, key + key, scroll + delta_y): click a button/link/field by its visible label, type into the focused field, press a key, scroll.\n\+ - `browser_page`: read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\").\n\+ - `browser_act` (action click + ref, type + text (+ ref), key + key, scroll + delta_y): click a control by its number from the clickable list, type into that field (or the focused one), press a key, scroll. If a ref is gone or covered, nothing is clicked and you get a fresh list.\n\- `browser_screenshot` (optional width, e.g. 390 phone / 1280 desktop): see the page as a picture, for layout, colours and spacing.\n\Every call returns the updated page, so you rarely need a separate read. \- The current page state and its clickable labels are usually already in the request; act on them directly.\n\+ The current page state and its clickable list are usually already in the request; act on them directly.\n\{control_rules}",tools = crate::mcp::SELF_SERVER_NAME,),@@ -450,13 +450,13 @@ impl TurnInput {Browser API: {api}\n\Never open a host desktop browser (no `open <url>`, `xdg-open`, etc.). Use ONLY these commands (the full API, do not search for more):\n\- Open a page: curl -sS -X POST '{api}/navigate' -H 'Content-Type: application/json' -d '{{\"url\":\"<url>\"}}'\n\- - Read the page (url, title, text, clickable labels): curl -sS '{api}/page'\n\- - Click a button/link/field by its visible label: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"click_text\",\"text\":\"<label>\"}}'\n\- - Type into the focused field: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"type\",\"text\":\"<text>\"}}'\n\+ - Read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\"): curl -sS '{api}/page'\n\+ - Click a control by its number from the clickable list: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"click\",\"ref\":3}}' (if it is gone or covered, nothing is clicked and you get a fresh list)\n\+ - Type into a field by its number (leave out ref for the focused field): curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"type\",\"ref\":5,\"text\":\"<text>\"}}'\n\- Press a key: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"key\",\"key\":\"Enter\"}}'\n\- Scroll: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"scroll\",\"delta_y\":600}}'\n\Every /act call returns the updated page (url, title, text, clickable), so you rarely need a separate read. \- The current page state and its clickable labels are usually already in the request; act on them directly.\n\+ The current page state and its clickable list are usually already in the request; act on them directly.\n\{control_rules}",api = api,),diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex 7ae696cb..6cfcd99b 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -44,17 +44,50 @@ const CLICKABLES_JS: &str = r#"function (needle, probe) {var SEL = 'button,a[href],[role=button],[role=link],[role=menuitem],[role=tab],[role=checkbox],[role=option],input,textarea,select,summary,label,[onclick]';var items = [];function clean(s) { return (s || '').replace(/\s+/g, ' ').trim().slice(0, 80); }- function labelOf(el) {+ // A control's role for the ref list: what it is, in one word+ function roleOf(el) {+ var role = (el.getAttribute('role') || '').toLowerCase();+ if (role) return role;+ var tag = el.tagName, t = (el.type || '').toLowerCase();+ if (tag === 'A') return 'link';+ if (tag === 'SELECT') return 'select';+ if (tag === 'LABEL') return 'label';+ if (tag === 'INPUT' && (t === 'checkbox' || t === 'radio')) return t;+ if (tag === 'TEXTAREA' || (tag === 'INPUT' && ['submit', 'button', 'image', 'reset'].indexOf(t) < 0)) return 'field';+ return 'button';+ }+ function nameOf(el) {var tag = el.tagName;if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') {var t = (el.type || '').toLowerCase();if (t === 'submit' || t === 'button') return clean(el.value);if (t === 'hidden') return '';- var name = clean(el.getAttribute('aria-label') || el.placeholder || el.name || el.id);- return name ? name + ' (' + (t === 'checkbox' || t === 'radio' ? t : 'field') + ')' : '';+ return clean(el.getAttribute('aria-label') || el.placeholder || el.name || el.id);}return clean(el.innerText || el.getAttribute('aria-label') || el.title || el.value);}+ function labelOf(el) {+ var name = nameOf(el), tag = el.tagName, t = (el.type || '').toLowerCase();+ if (!name || !(tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') || t === 'submit' || t === 'button') return name;+ return name + ' (' + (t === 'checkbox' || t === 'radio' ? t : 'field') + ')';+ }+ // The text that tells a repeated control apart (the product a repeated "Add to cart" belongs+ // to): the first line of the largest block around it that holds no other control of that name+ function contextOf(el, name, twins) {+ var block = null;+ for (var a = el.parentElement, depth = 0; a && depth < 10; a = a.parentElement, depth++) {+ var shared = false;+ for (var t = 0; t < twins.length; t++) if (twins[t] !== el && a.contains(twins[t])) { shared = true; break; }+ if (shared) break;+ block = a;+ }+ var lines = block ? (block.innerText || '').split('\n') : [];+ for (var i = 0; i < lines.length; i++) {+ var line = clean(lines[i]).slice(0, 50);+ if (line && line !== name) return line;+ }+ return '';+ }function walk(root, ox, oy) {var all;try { all = root.querySelectorAll('*'); } catch (e) { return; }@@ -80,7 +113,7 @@ const CLICKABLES_JS: &str = r#"function (needle, probe) {var hit = root.elementFromPoint ? root.elementFromPoint(lx, ly) : null;onTop = !hit || hit === el || el.contains(hit) || hit.contains(el);}- items.push({ label: label, x: Math.round(x), y: Math.round(y), inView: inView, onTop: onTop, el: el });+ items.push({ label: label, name: nameOf(el), role: roleOf(el), x: Math.round(x), y: Math.round(y), inView: inView, onTop: onTop, el: el });}}walk(document, 0, 0);@@ -106,14 +139,87 @@ const CLICKABLES_JS: &str = r#"function (needle, probe) {}}}+ if (!needle) {+ // A listing numbers the controls (ref = position + 1) and keeps their elements in the page,+ // so the next `act` by ref hits exactly this element or says it is gone+ var twins = {};+ for (var k = 0; k < items.length; k++) (twins[items[k].name] = twins[items[k].name] || []).push(items[k].el);+ var reg = window[Symbol.for('kwnt.refs')];+ if (!reg) {+ reg = { gen: 0 };+ try { Object.defineProperty(window, Symbol.for('kwnt.refs'), { value: reg }); } catch (e) {}+ }+ reg.gen += 1;+ reg.items = items.map(function (i) { return { el: i.el, label: i.label }; });+ reg.labelOf = labelOf;+ return { gen: reg.gen, items: items.map(function (i, k) {+ return { ref: k + 1, label: i.label, name: i.name, role: i.role, onTop: i.onTop,+ context: twins[i.name].length > 1 ? contextOf(i.el, i.name, twins[i.name]) : '' };+ }) };+ }return { items: items.map(function (i) { return { label: i.label, onTop: i.onTop }; }), match: match };}"#;+/// Finds control `ref` from the last listing (see [`CLICKABLES_JS`]). With `probe`, returns+/// `{el, label}` (or null) and touches nothing. Otherwise checks it can still be clicked: still+/// in the page, shown, the same label, and on top at its center after scrolling it into view+/// (so a cookie banner or modal over it is reported, not clicked through). Returns+/// `{ok: true, x, y, label}` in top-page pixels, or `{ok: false, why}`.+const REF_JS: &str = r#"function (ref, probe) {+ function clean(s) { return (s || '').replace(/\s+/g, ' ').trim().slice(0, 80); }+ var reg = window[Symbol.for('kwnt.refs')];+ var item = reg && reg.items && reg.items[ref - 1];+ if (probe) return item ? { el: item.el, label: item.label } : null;+ if (!item) return { ok: false, why: reg ? 'there is no ref ' + ref + ' in the last list' : 'this page has no list of refs yet (it changed or reloaded)' };+ var el = item.el;+ if (!el.isConnected) return { ok: false, why: 'it is no longer on the page' };+ var label = reg.labelOf ? reg.labelOf(el) : item.label;+ if (label !== item.label) return { ok: false, why: 'it now reads "' + label + '", not "' + item.label + '"' };+ function shown() {+ var r = el.getBoundingClientRect();+ if (r.width < 2 || r.height < 2) return null;+ var cs = getComputedStyle(el);+ if (cs.visibility === 'hidden' || cs.display === 'none' || Number(cs.opacity) === 0) return null;+ return r;+ }+ var r = shown();+ if (!r) return { ok: false, why: 'it is hidden now' };+ var win = el.ownerDocument.defaultView;+ if (r.top < 0 || r.left < 0 || r.bottom > win.innerHeight || r.right > win.innerWidth) {+ el.scrollIntoView({ block: 'center', inline: 'center' });+ r = shown();+ if (!r) return { ok: false, why: 'it is hidden now' };+ }+ var lx = r.left + r.width / 2, ly = r.top + r.height / 2;+ // The top-page point: add the offsets of the (same-origin) frames it sits in+ var x = lx, y = ly, frames = [];+ for (var w = win; w !== w.top && w.frameElement; w = w.parent) {+ var fr = w.frameElement.getBoundingClientRect();+ x += fr.left; y += fr.top;+ frames.push(w.frameElement);+ }+ if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) return { ok: false, why: 'it is outside the window' };+ function covers(hit, target) { return !hit || hit === target || target.contains(hit) || hit.contains(target); }+ function what(hit) {+ var t = clean(hit.innerText || hit.getAttribute('aria-label') || '').slice(0, 40);+ return hit.tagName.toLowerCase() + (t ? ' "' + t + '"' : '');+ }+ var root = el.getRootNode();+ var hit = root.elementFromPoint ? root.elementFromPoint(lx, ly) : null;+ if (!covers(hit, el)) return { ok: false, why: 'it is covered by ' + what(hit) };+ if (frames.length) {+ var top = document.elementFromPoint(x, y), outer = frames[frames.length - 1];+ if (!covers(top, outer)) return { ok: false, why: 'it is covered by ' + what(top) };+ }+ return { ok: true, x: Math.round(x), y: Math.round(y), label: item.label };+}"#;+/// What the payment floor needs from the page before a `browser_act` (see/// `payment_floor::PageSignals`): the element a click on `needle` would hit (the same match as/// `click_text`) or, with no needle, the focused element; visible card fields; and frames by host.const PAYMENT_SIGNALS_JS: &str = r#"function (needle) {var CLICK = __CLICKABLES__;+ var REF = __REF__;var CARD = /card.?num|cardnumber|cc.?num|credit.?card|card.?cvc|\bcvc2?\b|\bcvv2?\b/i;function isCard(el) {if (!el || el.tagName !== 'INPUT') return false;@@ -170,7 +276,7 @@ const PAYMENT_SIGNALS_JS: &str = r#"function (needle) {}var target = null;if (needle) {- var m = CLICK(needle, true);+ var m = typeof needle === 'number' ? REF(needle, true) : CLICK(needle, true);if (m) target = describe(m.el, m.label);} else {var a = document.activeElement;@@ -205,6 +311,50 @@ pub enum BrowserError {/// A file path (or file:// address) handed to the browser; see [`refuse_file_path`].#[error("{0}")]NotWebAddress(String),+ /// A ref from the control list that can't be clicked any more (gone, hidden, covered).+ #[error("{0}")]+ StaleRef(String),+}++/// What a click aims at: a label to match, or a numbered ref from the last control list.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ClickTarget {+ Text(String),+ Ref(u32),+}++impl ClickTarget {+ /// From `browser_act`/`/act` arguments: `ref` (a number, or digits) wins; a text that starts+ /// with a listed ref (`[3] button "Add to cart"`, copied whole from the list) is that ref.+ pub fn from_args(args: &Value) -> Option<ClickTarget> {+ let r = &args["ref"];+ let num = r.as_u64().or_else(|| r.as_str().and_then(|t| t.trim().trim_start_matches('[').trim_end_matches(']').parse().ok()));+ if let Some(n) = num.and_then(|n| u32::try_from(n).ok()).filter(|n| *n > 0) {+ return Some(ClickTarget::Ref(n));+ }+ let text = args["text"].as_str().map(str::trim).filter(|t| !t.is_empty())?;+ // Only a whole copied line: a bare "[1]" is a footnote link's label (Wikipedia)+ if let Some((n, rest)) = text.strip_prefix('[').and_then(|t| t.split_once(']')) {+ if let Some(n) = n.trim().parse::<u32>().ok().filter(|n| *n > 0 && rest.contains('"')) {+ return Some(ClickTarget::Ref(n));+ }+ }+ Some(ClickTarget::Text(text.to_string()))+ }+}++/// One line of the control list: `[3] button "Add to cart" · Sauce Labs Backpack`. The context+/// (nearby text) is only there when several controls share a name.+pub fn ref_line(item: &Value) -> Option<String> {+ let r = item["ref"].as_u64()?;+ let name = item["name"].as_str().filter(|n| !n.is_empty()).or(item["label"].as_str())?;+ let role = item["role"].as_str().filter(|r| !r.is_empty()).unwrap_or("button");+ let mut line = format!("[{r}] {role} \"{name}\"");+ if let Some(ctx) = item["context"].as_str().filter(|c| !c.is_empty()) {+ line.push_str(" · ");+ line.push_str(ctx);+ }+ Some(line)}/// Refuses an address that is a file on the computer before it reaches Chrome, so it is never@@ -1292,9 +1442,13 @@ impl BrowserController {/// What the page shows for the payment floor before `action` (see [`PAYMENT_SIGNALS_JS`]):/// for a click the element `needle` would hit, for a key the focused element. Reads only.- pub async fn payment_signals(&self, needle: Option<&str>) -> Result<Value, BrowserError> {- let needle = serde_json::to_string(&needle).map_err(|e| BrowserError::Protocol(e.to_string()))?;- let script = PAYMENT_SIGNALS_JS.replace("__CLICKABLES__", CLICKABLES_JS);+ pub async fn payment_signals(&self, target: Option<&ClickTarget>) -> Result<Value, BrowserError> {+ let needle = match target {+ Some(ClickTarget::Text(t)) => json!(t),+ Some(ClickTarget::Ref(n)) => json!(n),+ None => Value::Null,+ };+ let script = PAYMENT_SIGNALS_JS.replace("__CLICKABLES__", CLICKABLES_JS).replace("__REF__", REF_JS);let res = self.send_cdp_command("Runtime.evaluate",@@ -1307,7 +1461,9 @@ impl BrowserController {Ok(res["result"]["value"].clone())}- /// Labels of visible interactive elements, topmost (e.g. modal buttons) first.+ /// The page's controls as numbered refs (see [`ref_line`]), topmost (e.g. modal buttons)+ /// first. Listing also re-indexes the page, so the refs a bot was last shown are the ones+ /// [`Self::click_ref`] resolves.pub async fn list_clickables(&self, limit: usize) -> Vec<String> {let expression = format!("({})(null)", CLICKABLES_JS);let Ok(res) = self@@ -1319,20 +1475,47 @@ impl BrowserController {else {return Vec::new();};- let mut labels: Vec<String> = Vec::new();- if let Some(items) = res["result"]["value"]["items"].as_array() {- for item in items {- if let Some(label) = item["label"].as_str() {- if !labels.iter().any(|l| l == label) {- labels.push(label.to_string());- }- }- if labels.len() >= limit {- break;- }- }+ res["result"]["value"]["items"]+ .as_array()+ .map(|items| items.iter().filter_map(ref_line).take(limit).collect())+ .unwrap_or_default()+ }++ /// Clicks control `r` from the last list with a real mouse click at its center, after+ /// checking it is still in the page, shown, unchanged and not covered (see [`REF_JS`]).+ /// Otherwise clicks nothing and says why ([`BrowserError::StaleRef`]); the page state the+ /// caller returns next re-lists the controls.+ pub async fn click_ref(&self, r: u32) -> Result<String, BrowserError> {+ let res = self+ .send_cdp_command(+ "Runtime.evaluate",+ json!({ "expression": format!("({REF_JS})({r}, false)"), "returnByValue": true }),+ )+ .await?;+ if let Some(err) = res.get("exceptionDetails") {+ return Err(BrowserError::Protocol(format!("ref check failed: {}", err["text"])));+ }+ let v = &res["result"]["value"];+ if v["ok"].as_bool() != Some(true) {+ let why = v["why"].as_str().unwrap_or("it can't be found");+ return Err(BrowserError::StaleRef(format!(+ "Didn't click ref {r}: {why}. The clickable list was read again just now; pick from the new list."+ )));+ }+ let (x, y) = (v["x"].as_i64().unwrap_or(0), v["y"].as_i64().unwrap_or(0));+ self.interact_click(x, y).await?;+ tokio::time::sleep(Duration::from_millis(250)).await;+ let _ = self.sync_location().await;+ let _ = self.capture_screenshot().await;+ Ok(v["label"].as_str().unwrap_or_default().to_string())+ }++ /// Clicks `target`: a ref with [`Self::click_ref`], a label with [`Self::click_text`].+ pub async fn click_target(&self, target: &ClickTarget) -> Result<String, BrowserError> {+ match target {+ ClickTarget::Ref(r) => self.click_ref(*r).await,+ ClickTarget::Text(t) => self.click_text(t).await,}- labels}/// Clicks the visible element whose label best matches `text` (exact > prefix > contains,@@ -1499,3 +1682,34 @@ mod agent_shot_tests {assert_eq!(agent_shot_viewport(Some(9000), (1280, 800), 1.0), Some((1280, 800, false)));}}++#[cfg(test)]+mod ref_tests {+ use super::{ref_line, ClickTarget};+ use serde_json::json;++ #[test]+ fn a_click_aims_at_a_ref_or_a_label() {+ let t = |a| ClickTarget::from_args(&a);+ assert_eq!(t(json!({"ref": 3})), Some(ClickTarget::Ref(3)));+ assert_eq!(t(json!({"ref": "7"})), Some(ClickTarget::Ref(7)));+ assert_eq!(t(json!({"ref": "[7]", "text": "Login"})), Some(ClickTarget::Ref(7)), "ref wins over text");+ assert_eq!(t(json!({"text": "[4] button \"Add to cart\" · Backpack"})), Some(ClickTarget::Ref(4)), "a whole copied line");+ assert_eq!(t(json!({"text": "[1]"})), Some(ClickTarget::Text("[1]".into())), "a footnote link stays a label");+ assert_eq!(t(json!({"text": " Login "})), Some(ClickTarget::Text("Login".into())));+ assert_eq!(t(json!({"ref": 0, "text": "Login"})), Some(ClickTarget::Text("Login".into())));+ assert_eq!(t(json!({"ref": -2})), None);+ assert_eq!(t(json!({"ref": null, "text": " "})), None);+ }++ #[test]+ fn a_ref_line_names_role_and_context_only_when_needed() {+ let line = |v| ref_line(&v);+ assert_eq!(line(json!({"ref": 3, "role": "button", "name": "Add to cart", "context": "Sauce Labs Backpack"})).as_deref(),+ Some("[3] button \"Add to cart\" · Sauce Labs Backpack"));+ assert_eq!(line(json!({"ref": 1, "role": "field", "name": "Username", "label": "Username (field)", "context": ""})).as_deref(),+ Some("[1] field \"Username\""));+ assert_eq!(line(json!({"ref": 2, "label": "Menu"})).as_deref(), Some("[2] button \"Menu\""));+ assert_eq!(line(json!({"label": "No ref"})), None);+ }+}diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex 1c287df5..27e4ef9d 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -6,7 +6,7 @@ pub mod manager;pub mod service;pub mod vault;-pub use browser::{detect_bot_wall, refuse_file_path, BrowserController, BrowserError, NavigationResult, PendingCapture};+pub use browser::{detect_bot_wall, ref_line, refuse_file_path, BrowserController, ClickTarget, BrowserError, NavigationResult, PendingCapture};pub use credentials::{Credential, CredentialMeta, CredentialStore, EncryptedFileStore};pub use manager::{ActiveSandbox, SandboxError, SandboxManager, ShellOutput};diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 46b05e0a..8be6aecf 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -435,11 +435,11 @@ pub async fn browser_act_payment(state: &AppState, target: &str, args: &Value) -let ctrl = ctrl?;let action = args["action"].as_str().unwrap_or("");let needle = match action {- "click_text" | "click" => Some(args["text"].as_str().map(str::trim).filter(|t| !t.is_empty())?),+ "click_text" | "click" => Some(crate::sandbox::ClickTarget::from_args(args)?),"key" => None,_ => return None,};- let page = match ctrl.payment_signals(needle).await {+ let page = match ctrl.payment_signals(needle.as_ref()).await {Ok(page) => page,Err(e) => {tracing::warn!(error = %e, "payment floor could not read the page");@@ -510,7 +510,7 @@ fn browser_tools() -> Vec<Value> {vec![json!({"name": BROWSER_OPEN,- "description": "Open a web page in your browser, the one shown live in the user's side panel. Returns the page you landed on (url, title, text, clickable labels); trust it over the url you asked for.",+ "description": "Open a web page in your browser, the one shown live in the user's side panel. Returns the page you landed on (url, title, text, clickable controls, numbered for browser_act); trust it over the url you asked for.","inputSchema": {"type": "object","properties": {"url": {"type": "string", "description": "The address to open, e.g. https://www.google.com/maps"}},@@ -519,7 +519,7 @@ fn browser_tools() -> Vec<Value> {}),json!({"name": BROWSER_PAGE,- "description": "Read the page your browser shows now: url, title, visible text and clickable labels.",+ "description": "Read the page your browser shows now: url, title, visible text and clickable controls, numbered for browser_act.","inputSchema": {"type": "object", "properties": {}},}),json!({@@ -539,12 +539,13 @@ fn browser_tools() -> Vec<Value> {}),json!({"name": BROWSER_ACT,- "description": "Do one thing on the current page and get the page back. click_text clicks a button, link or field by its visible label; type types into the focused field; key presses a key (Enter, Tab, Escape, ArrowDown…); scroll scrolls by delta_y pixels (negative is up).",+ "description": "Do one thing on the current page and get the page back. click clicks a control by its ref, the number in the page's clickable list ([3] button \"Add to cart\"), or by its visible label in text; if the ref is gone, hidden or covered nothing is clicked and you get a fresh list. type types into the field with that ref, or the focused field; key presses a key (Enter, Tab, Escape, ArrowDown…); scroll scrolls by delta_y pixels (negative is up).","inputSchema": {"type": "object","properties": {- "action": {"type": "string", "enum": ["click_text", "type", "key", "scroll"]},- "text": {"type": "string", "description": "click_text: the label to click; type: the text to type"},+ "action": {"type": "string", "enum": ["click", "click_text", "type", "key", "scroll"]},+ "ref": {"type": "integer", "description": "click or type: the control's number from the clickable list"},+ "text": {"type": "string", "description": "click: a visible label, when there's no ref; type: the text to type"},"key": {"type": "string", "description": "key: the key to press"},"delta_y": {"type": "number", "description": "scroll: pixels to scroll, default 600"},},@@ -653,7 +654,7 @@ async fn run_browser_tool(state: &AppState, target: &str, name: &str, args: &ValBROWSER_PAGE => get_sandbox_page(state, target).await,_ => {let Some(action) = args["action"].as_str() else {- return ("action is required: click_text, type, key or scroll".into(), true);+ return ("action is required: click, type, key or scroll".into(), true);};let payload = InteractPayload {action: action.to_string(),@@ -664,6 +665,7 @@ async fn run_browser_tool(state: &AppState, target: &str, name: &str, args: &Valcode: None,delta_x: None,delta_y: args["delta_y"].as_f64(),+ ref_: Some(args["ref"].clone()).filter(|r| !r.is_null()),};// SelfToolsApprover already gave a payment its card (browser_act_payment)act_sandbox_allowed(state, target, Json(payload)).awaitdiff --git a/src/server/routes.rs b/src/server/routes.rsindex 12100cae..81452eca 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -4263,6 +4263,9 @@ pub struct InteractPayload {pub code: Option<String>,pub delta_x: Option<f64>,pub delta_y: Option<f64>,+ /// click (or type): a numbered ref from the page's clickable list instead of a label+ #[serde(default, rename = "ref")]+ pub ref_: Option<serde_json::Value>,}pub async fn interact_sandbox(@@ -4399,7 +4402,7 @@ pub async fn act_sandbox(let ctrl = get_or_create_browser_controller(&state, &team_id).await.ok_or_else(|| browser_unavailable(&state))?;- let args = json!({"action": payload.action, "text": payload.text, "key": payload.key});+ let args = json!({"action": payload.action, "text": payload.text, "key": payload.key, "ref": payload.ref_});if let Some(why) = super::continuity::browser_act_payment(&state, &team_id, &args).await {let mut page = sandbox_page_state(&ctrl).await;page["payment"] = json!(why);@@ -4423,31 +4426,46 @@ pub async fn act_sandbox_allowed(.ok_or_else(|| browser_unavailable(&state))?;let _permit = ctrl.control.try_read().map_err(|_| browser_request_failed(crate::sandbox::BrowserError::HumanControl))?;let text = payload.text.clone().unwrap_or_default();- let result: Result<String, String> = match payload.action.as_str() {- "click_text" | "click" if !text.is_empty() => ctrl- .click_text(&text)+ let clicks = crate::sandbox::ClickTarget::from_args(&json!({"ref": payload.ref_, "text": payload.text}));+ let result: Result<String, String> = match (payload.action.as_str(), clicks) {+ ("click_text" | "click", Some(target)) => ctrl+ .click_target(&target).await.map(|label| format!("clicked \"{}\"", label)).map_err(|e| e.to_string()),- "type" => ctrl- .interact_type(&text)- .await- .map(|_| format!("typed {} chars", text.chars().count()))- .map_err(|e| e.to_string()),- "key" => {+ // type with a ref: click that field first, then type into it+ ("type", _) => {+ let focus = match crate::sandbox::ClickTarget::from_args(&json!({"ref": payload.ref_})) {+ Some(field) => ctrl.click_target(&field).await.map(Some),+ None => Ok(None),+ };+ match focus {+ Ok(field) => ctrl+ .interact_type(&text)+ .await+ .map(|_| match field {+ Some(f) => format!("typed {} chars into \"{f}\"", text.chars().count()),+ None => format!("typed {} chars", text.chars().count()),+ })+ .map_err(|e| e.to_string()),+ Err(e) => Err(e.to_string()),+ }+ }+ ("key", _) => {let key = payload.key.clone().unwrap_or_else(|| "Enter".into());ctrl.interact_key(&key, payload.code.as_deref()).await.map(|_| format!("pressed {}", key)).map_err(|e| e.to_string())}- "scroll" => ctrl+ ("scroll", _) => ctrl.interact_scroll(640, 400, 0.0, payload.delta_y.unwrap_or(600.0)).await.map(|_| "scrolled".to_string()).map_err(|e| e.to_string()),- other => Err(format!(- "Unknown action \"{}\". Use click_text (with text), type (with text), key (with key) or scroll (with delta_y).",+ ("click_text" | "click", None) => Err("click needs ref (a number from the clickable list) or text (a label).".to_string()),+ (other, _) => Err(format!(+ "Unknown action \"{}\". Use click (with ref or text), type (with text), key (with key) or scroll (with delta_y).",other)),};diff --git a/tests/browser_refs_test.rs b/tests/browser_refs_test.rsnew file mode 100644index 00000000..58e419db--- /dev/null+++ b/tests/browser_refs_test.rs@@ -0,0 +1,247 @@+//! Numbered refs in kwnt's own browser, through a real Chrome: the clickable list numbers each+//! control with its role (and nearby text when names repeat), a click by ref hits exactly that+//! control (scrolled into view, inside a frame), and a ref that is gone, hidden, renamed or+//! covered clicks nothing and says why, with a fresh list. Payments are judged on the element+//! the ref points to. Skipped when no Chrome is installed. `saucedemo_by_refs` (ignored, needs+//! the network) shops a real demo store by refs.+#[path = "support/chrome_guard.rs"]+mod chrome_guard;+use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use chrome_guard::ChromeGuard;+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{models::Kwant, spaces::SpaceId, Database},+ router::LayaRouter,+ sandbox::{computer, BrowserError},+ server::{continuity::browser_act_payment, create_router, routes::get_or_create_browser_controller, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tower::ServiceExt;++const SHOP_PAGE: &str = "<!doctype html><title>shop</title>\+<div class=item><h3>Backpack</h3><p>$29.99</p><button onclick=\"document.title='added backpack'\">Add to cart</button></div>\+<div class=item><h3>Bike Light</h3><p>$9.99</p><button id=light onclick=\"document.title='added light'\">Add to cart</button></div>\+<button onclick=\"document.getElementById('banner').style.display='block'\">Show banner</button>\+<input name=user placeholder=Username>\+<div style='height:2500px'></div><a href='#bottom' onclick=\"document.title='bottom'\">Far away</a>\+<iframe srcdoc=\"<button onclick='parent.document.title="framed"'>In frame</button>\" style='width:300px;height:60px'></iframe>\+<div id=banner style='display:none;position:fixed;inset:0;background:#fff'>Cookie banner</div>";+const CARD_PAGE: &str = "<!doctype html><title>card</title><form onsubmit=\"return false\">\+<input autocomplete=cc-number placeholder='Card number'><button type=submit>Continue</button></form>";+const PLAIN_PAGE: &str = "<!doctype html><title>plain</title><button>Continue</button>";++/// A small HTTP server for the pages above on 127.0.0.1, so the test needs no network.+async fn serve() -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ tokio::spawn(async move {+ while let Ok((mut stream, _)) = listener.accept().await {+ tokio::spawn(async move {+ let mut buf = [0u8; 4096];+ let n = stream.read(&mut buf).await.unwrap_or(0);+ let req = String::from_utf8_lossy(&buf[..n]).to_string();+ let path = req.split_whitespace().nth(1).unwrap_or("/").to_string();+ let page = match path.as_str() {+ "/shop" => SHOP_PAGE,+ "/card" => CARD_PAGE,+ _ => PLAIN_PAGE,+ };+ let reply = format!(+ "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{page}",+ page.len()+ );+ let _ = stream.write_all(reply.as_bytes()).await;+ });+ }+ });+ format!("http://127.0.0.1:{port}")+}++struct Env {+ app: Router,+ state: AppState,+ bot: Kwant,+ tmp: TempDir,+}++/// kwnt in Local mode, so the bot's browser is a real Chrome on this machine.+async fn setup() -> Env {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ db.set_setting(computer::SETTING_KEY, "local").await.unwrap();+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();+ Env { app: create_router(state.clone()), state, bot, tmp }+}++async fn open(e: &Env, url: &str) -> kwnt::sandbox::BrowserController {+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");+ ctrl.navigate(url).await.unwrap();+ ctrl+}+++async fn pay(e: &Env, args: Value) -> Option<String> {+ browser_act_payment(&e.state, &e.bot.id, &args).await+}+async fn post_act(app: &Router, bot: &str, body: Value) -> (StatusCode, Value) {+ let req = Request::builder()+ .method("POST")+ .uri(format!("/api/sandbox/{bot}/act"))+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap();+ let resp = app.clone().oneshot(req).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++async fn get_page(app: &Router, bot: &str) -> Value {+ let req = Request::builder().uri(format!("/api/sandbox/{bot}/page")).body(Body::empty()).unwrap();+ let resp = app.clone().oneshot(req).await.unwrap();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ serde_json::from_slice(&bytes).unwrap()+}++/// The ref of the first listed control whose line contains `needle`.+fn ref_of(page: &Value, needle: &str) -> u64 {+ let lines = page["clickable"].as_array().expect("a clickable list");+ let line = lines.iter().filter_map(Value::as_str).find(|l| l.contains(needle)).unwrap_or_else(|| panic!("{needle} in {page}"));+ line[1..line.find(']').unwrap()].parse().unwrap()+}++async fn eval(ctrl: &kwnt::sandbox::BrowserController, js: &str) {+ ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": js})).await.unwrap();+}++#[tokio::test]+async fn a_click_by_ref_hits_that_control_or_nothing() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));+ let base = serve().await;+ let ctrl = open(&e, &format!("{base}/shop")).await;++ // Role, name, and the product when two buttons share a name+ let page = get_page(&e.app, &e.bot.id).await;+ let list = page["clickable"].to_string();+ assert!(list.contains(r#"button \"Add to cart\" · Backpack"#), "{list}");+ assert!(list.contains(r#"button \"Add to cart\" · Bike Light"#), "{list}");+ assert!(list.contains(r#"field \"Username\""#), "{list}");+ assert!(list.contains(r#"button \"Show banner\"""#), "names that don't repeat carry no context: {list}");++ // The second "Add to cart", which a label can't tell apart+ let light = ref_of(&page, "· Bike Light");+ let (status, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": light})).await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(page["title"], "added light", "{page}");+ assert!(page["result"].as_str().unwrap().contains("Add to cart"), "{page}");++ // A copied line works as text too; a control far below is scrolled into view first+ let line = page["clickable"].as_array().unwrap().iter().filter_map(Value::as_str).find(|l| l.contains("Far away")).unwrap().to_string();+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click_text", "text": line})).await;+ assert_eq!(page["title"], "bottom", "{page}");++ // Inside a same-origin frame: the click lands at the frame's offset+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, "In frame")})).await;+ assert_eq!(page["title"], "framed", "{page}");++ // Type into a field by its ref+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "type", "ref": ref_of(&page, "Username"), "text": "standard_user"})).await;+ assert!(page["result"].as_str().unwrap().contains("Username"), "{page}");+ eval(&ctrl, "document.title = document.querySelector('[name=user]').value").await;+ assert_eq!(ctrl.sync_location().await.unwrap().1, "standard_user");++ // Covered: a banner over the page; nothing is clicked, the answer says so and lists again+ open(&e, &format!("{base}/shop")).await;+ let page = get_page(&e.app, &e.bot.id).await;+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, "Show banner")})).await;+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, "· Backpack")})).await;+ assert_eq!(page["title"], "shop", "{page}");+ let err = page["error"].as_str().expect("an error");+ assert!(err.contains("covered by div \"Cookie banner\"") && err.contains("pick from the new list"), "{err}");+ assert!(page["clickable"].as_array().is_some_and(|l| !l.is_empty()));++ // Gone, hidden, renamed, unknown: each says why and clicks nothing+ open(&e, &format!("{base}/shop")).await;+ let page = get_page(&e.app, &e.bot.id).await;+ let light = ref_of(&page, "· Bike Light") as u32;+ eval(&ctrl, "document.getElementById('light').textContent = 'Remove'").await;+ let err = ctrl.click_ref(light).await.unwrap_err();+ assert!(matches!(err, BrowserError::StaleRef(_)) && err.to_string().contains("now reads \"Remove\""), "{err}");+ eval(&ctrl, "document.getElementById('light').textContent = 'Add to cart'; document.getElementById('light').style.display = 'none'").await;+ assert!(ctrl.click_ref(light).await.unwrap_err().to_string().contains("hidden"));+ eval(&ctrl, "document.getElementById('light').remove()").await;+ assert!(ctrl.click_ref(light).await.unwrap_err().to_string().contains("no longer on the page"));+ assert!(ctrl.click_ref(999).await.unwrap_err().to_string().contains("no ref 999"));+ assert_eq!(ctrl.sync_location().await.unwrap().1, "shop");+ // A reload forgets the list+ open(&e, &format!("{base}/shop")).await;+ assert!(ctrl.click_ref(1).await.unwrap_err().to_string().contains("no list of refs yet"));+}++#[tokio::test]+async fn a_payment_is_judged_on_the_element_a_ref_points_to() {+ if computer::local_chrome_path().is_none() {+ eprintln!("skipped: no Chrome or Chromium installed");+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));+ let base = serve().await;++ open(&e, &format!("{base}/card")).await;+ let page = get_page(&e.app, &e.bot.id).await;+ let why = pay(&e, json!({"action": "click", "ref": ref_of(&page, "Continue")})).await.expect("Continue on a card form");+ assert!(why.contains("card fields"), "{why}");+ // The shell API refuses it and clicks nothing+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, "Continue")})).await;+ assert!(page["payment"].is_string(), "{page}");++ open(&e, &format!("{base}/plain")).await;+ let page = get_page(&e.app, &e.bot.id).await;+ assert_eq!(pay(&e, json!({"action": "click", "ref": ref_of(&page, "Continue")})).await, None);+}++/// A real demo shop by refs: add the second product of several identical "Add to cart"+/// buttons. Needs the network.+#[tokio::test]+#[ignore]+async fn saucedemo_by_refs() {+ if computer::local_chrome_path().is_none() {+ return;+ }+ let e = setup().await;+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));+ open(&e, "https://www.saucedemo.com/").await;+ let page = get_page(&e.app, &e.bot.id).await;+ post_act(&e.app, &e.bot.id, json!({"action": "type", "ref": ref_of(&page, "Username"), "text": "standard_user"})).await;+ post_act(&e.app, &e.bot.id, json!({"action": "type", "ref": ref_of(&page, "Password"), "text": "secret_sauce"})).await;+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, "Login")})).await;+ assert!(page["url"].as_str().unwrap().contains("inventory"), "{page}");+ let list = page["clickable"].to_string();+ assert!(list.contains("Add to cart"), "{list}");+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, "· Sauce Labs Bike Light")})).await;+ assert!(page["error"].is_null(), "{page}");+ assert!(page["clickable"].to_string().contains("Remove"), "{page}");+ eprintln!("{}", page["clickable"]);+}