Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Browser: mark controls that just appeared with *

Lin (kwant bot)8d1a8e9f04e1
diff --git a/docs/bot-browser.md b/docs/bot-browser.md
index 3a076360..3a43a8f2 100644
--- a/docs/bot-browser.md
+++ b/docs/bot-browser.md
@@ -22,6 +22,18 @@ Otherwise nothing is clicked and the error says why (`gone`, `hidden`, `now read
"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.
+### New controls
+
+A control that wasn't in the page's previous list starts with `*`: `*[12] option "Large"`. Identity
+is the element itself (the kept refs), not its label, so a renamed button isn't new and a second
+"Add to cart" that just appeared is. The first list of a page marks nothing, nor does the first list
+after a reload, a navigation, or an address change other than its `#fragment` (the registry keeps
+the address it was made for). Every list compares against the one before it, whoever asked for it,
+so a read right after an action's answer marks nothing. With `find`, new controls come first among
+equally matching ones; without it, page order stays. The mark doesn't count towards `hash`, so a
+re-read of an unchanged page is still `unchanged`. A copied `*[12] …` line works as a ref.
+(Idea from browser-use's `_assign_interactive_indices_and_mark_new_nodes`.)
+
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).
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index b8afb7ee..94ce1c02 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -436,7 +436,7 @@ 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` (optional find): read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\"). It says \"unchanged\" if nothing changed since you last saw it; on a page with many controls, find (words for what you look for) lists the matching ones first.\n\
+ - `browser_page` (optional find): read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\"; *[12] marks one that just appeared, e.g. an opened menu's options). It says \"unchanged\" if nothing changed since you last saw it; on a page with many controls, find (words for what you look for) lists the matching ones first.\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\
- `browser_cite` (text: the exact words from the page, or block: an id from `browser_page` with blocks): checks the quote is on the page word for word and once, and returns {{quote, url, link}}; the link opens the page with the quote highlighted. When you answer facts you read on the web, back each with its cite link. If a quote is refused, quote the page exactly or quote more; never quote from memory.\n\
@@ -451,7 +451,7 @@ 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 controls numbered like [3] button \"Add to cart\", and a hash): curl -sS '{api}/page'. Add ?since=<hash of your last read> to get only \"unchanged\" when nothing changed, and &find=<words> on a page with many controls to list the matching ones first.\n\
+ - Read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\"; *[12] marks one that just appeared, and a hash): curl -sS '{api}/page'. Add ?since=<hash of your last read> to get only \"unchanged\" when nothing changed, and &find=<words> on a page with many controls to list the matching ones first.\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\
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 7b7b7591..aa3c9e07 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -149,11 +149,18 @@ const CLICKABLES_JS: &str = r#"function (needle, probe) {
reg = { gen: 0 };
try { Object.defineProperty(window, Symbol.for('kwnt.refs'), { value: reg }); } catch (e) {}
}
+ // A control is new when its element wasn't in this page's previous list (a dropdown's
+ // options, a dialog's buttons). The first list of a page, and one after the address changed
+ // (other than its #fragment), marks nothing
+ var here = location.href.split('#')[0];
+ var before = reg.items && reg.href === here ? new Set(reg.items.map(function (i) { return i.el; })) : null;
reg.gen += 1;
+ reg.href = here;
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,
+ new: !!before && !before.has(i.el),
context: twins[i.name].length > 1 ? contextOf(i.el, i.name, twins[i.name]) : '' };
}) };
}
@@ -328,13 +335,13 @@ impl ClickTarget {
/// 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()));
+ let num = r.as_u64().or_else(|| r.as_str().and_then(|t| unmarked(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, rest)) = unmarked(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));
}
@@ -344,12 +351,14 @@ impl ClickTarget {
}
/// 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.
+/// (nearby text) is only there when several controls share a name. A control that wasn't in the
+/// page's previous list starts with [`NEW_MARK`]: `*[12] option "Large"`.
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}\"");
+ let mark = if item["new"].as_bool() == Some(true) { NEW_MARK } else { "" };
+ let mut line = format!("{mark}[{r}] {role} \"{name}\"");
if let Some(ctx) = item["context"].as_str().filter(|c| !c.is_empty()) {
line.push_str(" · ");
line.push_str(ctx);
@@ -357,6 +366,14 @@ pub fn ref_line(item: &Value) -> Option<String> {
Some(line)
}
+/// Marks a control line as new since the page's previous list (see [`ref_line`]).
+pub const NEW_MARK: &str = "*";
+
+/// `line` without its [`NEW_MARK`], to compare lines across reads.
+pub fn unmarked(line: &str) -> &str {
+ line.strip_prefix(NEW_MARK).unwrap_or(line)
+}
+
/// Refuses an address that is a file on the computer before it reaches Chrome, so it is never
/// read as a page on the site already open. file:// is refused in every mode: in Local mode it
/// would show the bot any file on the person's computer, past the folders and approvals its
@@ -1774,6 +1791,8 @@ mod ref_tests {
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": "*[5] option \"Large\""})), Some(ClickTarget::Ref(5)), "a copied new line");
+ assert_eq!(t(json!({"ref": "*5"})), Some(ClickTarget::Ref(5)));
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())));
@@ -1790,5 +1809,7 @@ mod ref_tests {
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);
+ assert_eq!(line(json!({"ref": 12, "role": "option", "name": "Large", "new": true})).as_deref(), Some("*[12] option \"Large\""));
+ assert_eq!(line(json!({"ref": 12, "role": "option", "name": "Large", "new": false})).as_deref(), Some("[12] option \"Large\""));
}
}
diff --git a/src/sandbox/reads.rs b/src/sandbox/reads.rs
index c75b1183..35dece10 100644
--- a/src/sandbox/reads.rs
+++ b/src/sandbox/reads.rs
@@ -23,9 +23,11 @@ fn fnv1a(parts: &[&str]) -> u64 {
/// What a read shows, as a short hex string: the address, title, text, every control (not only
/// the ones listed) and the `find` words that picked them.
+/// A control's "new" mark doesn't count: it says what changed since the list before, so a re-read
+/// of an unchanged page drops it and still reads the same.
pub fn page_hash(url: &str, title: &str, text: &str, controls: &[String], find: &str) -> String {
let mut parts = vec![url, title, text, find];
- parts.extend(controls.iter().map(String::as_str));
+ parts.extend(controls.iter().map(|c| super::browser::unmarked(c)));
format!("{:016x}", fnv1a(&parts))
}
@@ -43,7 +45,8 @@ pub fn find_words(find: &str) -> Vec<String> {
/// Picks at most `cap` of the page's control lines. Without `find` words they keep page order
/// (topmost first). With them, the lines naming the most of those words come first, ties in page
-/// order. Ref numbers are part of each line, so they stay what the page gave them. The note says
+/// order, except that controls new since the page's last list (marked `*`) come first among equal
+/// scores. Ref numbers are part of each line, so they stay what the page gave them. The note says
/// what was left out, for the bot to ask again with other words.
pub fn pick_controls(lines: &[String], find: &str, cap: usize) -> (Vec<String>, Option<String>) {
let words = find_words(find);
@@ -57,8 +60,8 @@ pub fn pick_controls(lines: &[String], find: &str, cap: usize) -> (Vec<String>,
matched += 1;
}
}
- // Stable: equal scores keep page order
- order.sort_by_key(|(score, _)| std::cmp::Reverse(*score));
+ // Stable: equal scores keep page order, new controls first
+ order.sort_by_key(|(score, line)| (std::cmp::Reverse(*score), !line.starts_with(super::browser::NEW_MARK)));
}
let shown: Vec<String> = order.iter().take(cap).map(|(_, l)| (*l).clone()).collect();
let total = lines.len();
@@ -171,6 +174,24 @@ mod tests {
assert_eq!(note.unwrap(), "No control matches \"zebra\"; showing them in page order.");
}
+ #[test]
+ fn new_controls_come_first_among_equal_matches_and_dont_change_the_hash() {
+ let all = vec![
+ "[1] option \"Small\"".to_string(),
+ "[2] button \"Size\"".to_string(),
+ "*[3] option \"Medium\"".to_string(),
+ "*[4] option \"Large size\"".to_string(),
+ ];
+ // "size" matches 2 and 4 once each: the new one first; then 3 (new) before 1
+ let (shown, _) = pick_controls(&all, "size", 40);
+ assert_eq!(shown, vec![all[3].clone(), all[1].clone(), all[2].clone(), all[0].clone()]);
+ // Without find, page order as before
+ assert_eq!(pick_controls(&all, "", 40).0, all);
+ // The same page read again (nothing new any more) hashes the same
+ let plain: Vec<String> = all.iter().map(|l| l.trim_start_matches('*').to_string()).collect();
+ assert_eq!(page_hash("u", "t", "x", &all, ""), page_hash("u", "t", "x", &plain, ""));
+ }
+
#[test]
fn each_bot_is_told_unchanged_only_about_its_own_last_read() {
let mut r = Reads::default();
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 5cfa8c7c..753837ef 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -551,7 +551,7 @@ fn browser_tools() -> Vec<Value> {
}),
json!({
"name": BROWSER_PAGE,
- "description": "Read the page your browser shows now: url, title, visible text and clickable controls, numbered for browser_act. If nothing changed since your last look at it (a read or an action's answer), it says so instead of sending the page again. On a page with many controls only 40 are listed: give find to list the ones you look for first.",
+ "description": "Read the page your browser shows now: url, title, visible text and clickable controls, numbered for browser_act (a leading * marks one that appeared since your last look). If nothing changed since your last look at it (a read or an action's answer), it says so instead of sending the page again. On a page with many controls only 40 are listed: give find to list the ones you look for first.",
"inputSchema": {
"type": "object",
"properties": {
@@ -589,7 +589,7 @@ fn browser_tools() -> Vec<Value> {
}),
json!({
"name": BROWSER_ACT,
- "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).",
+ "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; a line starting with * (*[12] option \"Large\") is a control that appeared since your last look, e.g. the options a click opened; 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": {
diff --git a/tests/browser_progress_test.rs b/tests/browser_progress_test.rs
index f784d375..38c2c94c 100644
--- a/tests/browser_progress_test.rs
+++ b/tests/browser_progress_test.rs
@@ -132,6 +132,7 @@ async fn each_action_says_what_changed_and_a_loop_is_stopped() {
assert_eq!(page["changed"], "New: \"Slow done\".", "{page}");
// Typing changes no text, but it is a change
let search = page["clickable"].as_array().unwrap().iter().filter_map(Value::as_str).find(|l| l.contains("Search")).unwrap();
+ let search = search.trim_start_matches('*');
let search: u32 = search[1..search.find(']').unwrap()].parse().unwrap();
let page = act(&e, json!({"action": "type", "ref": search, "text": "boots"})).await;
assert!(page["changed"].as_str().unwrap().starts_with("No new text"), "{page}");
diff --git a/tests/browser_reads_test.rs b/tests/browser_reads_test.rs
index a7f107fe..b1e94c0e 100644
--- a/tests/browser_reads_test.rs
+++ b/tests/browser_reads_test.rs
@@ -108,6 +108,7 @@ fn controls(page: &Value) -> Vec<String> {
}
fn ref_of(line: &str) -> u64 {
+ let line = line.trim_start_matches('*');
line[1..line.find(']').unwrap()].parse().unwrap()
}
diff --git a/tests/browser_refs_test.rs b/tests/browser_refs_test.rs
index 58e419db..8d3a96be 100644
--- a/tests/browser_refs_test.rs
+++ b/tests/browser_refs_test.rs
@@ -36,6 +36,11 @@ const SHOP_PAGE: &str = "<!doctype html><title>shop</title>\
<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 MENU_PAGE: &str = "<!doctype html><title>menu</title>\
+<button onclick=\"var m=document.getElementById('menu');m.innerHTML='<button role=option>Small</button><button role=option>Large</button>'\">Size</button>\
+<button onclick=\"document.getElementById('dlg').showModal()\">Open dialog</button>\
+<a href='#bottom' onclick=\"document.getElementById('menu').insertAdjacentHTML('beforeend','<button>Extra</button>')\">Jump</a><div id=menu></div>\
+<dialog id=dlg><p>Sure?</p><button>Confirm</button><button onclick=\"this.closest('dialog').close()\">Cancel</button></dialog>";
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.
@@ -52,6 +57,7 @@ async fn serve() -> String {
let page = match path.as_str() {
"/shop" => SHOP_PAGE,
"/card" => CARD_PAGE,
+ "/menu" => MENU_PAGE,
_ => PLAIN_PAGE,
};
let reply = format!(
@@ -123,6 +129,7 @@ async fn get_page(app: &Router, bot: &str) -> Value {
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}"));
+ let line = line.trim_start_matches('*');
line[1..line.find(']').unwrap()].parse().unwrap()
}
@@ -245,3 +252,67 @@ async fn saucedemo_by_refs() {
assert!(page["clickable"].to_string().contains("Remove"), "{page}");
eprintln!("{}", page["clickable"]);
}
+
+fn lines(page: &Value) -> Vec<String> {
+ page["clickable"].as_array().expect("a clickable list").iter().filter_map(Value::as_str).map(str::to_string).collect()
+}
+fn marked(page: &Value) -> Vec<String> {
+ lines(page).into_iter().filter(|l| l.starts_with('*')).collect()
+}
+
+#[tokio::test]
+async fn controls_that_just_appeared_are_marked_new_and_nothing_else() {
+ 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}/menu")).await;
+
+ // The first read of a page marks nothing
+ let page = get_page(&e.app, &e.bot.id).await;
+ assert!(marked(&page).is_empty(), "{page}");
+
+ // Opening the dropdown marks exactly its options
+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, "Size")})).await;
+ let new = marked(&page);
+ assert_eq!(new.len(), 2, "{page}");
+ assert!(new[0].contains(r#"option "Small""#) && new[1].contains(r#"option "Large""#), "{new:?}");
+ assert!(lines(&page).iter().any(|l| l.contains(r#"button "Size""#) && !l.starts_with('*')), "{page}");
+ // A copied new line clicks as its ref
+ let large = lines(&page).into_iter().find(|l| l.contains("Large")).unwrap();
+ let (status, _) = post_act(&e.app, &e.bot.id, json!({"action": "click_text", "text": large})).await;
+ assert_eq!(status, StatusCode::OK);
+
+ // A re-read with no change marks nothing, and with since it is still "unchanged"
+ let page = get_page(&e.app, &e.bot.id).await;
+ assert!(marked(&page).is_empty(), "{page}");
+ let again = get_page(&e.app, &e.bot.id).await;
+ assert_eq!(page["hash"], again["hash"]);
+
+ // A dialog: only its buttons are new; with find, new ones come first among equal matches
+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click", "ref": ref_of(&page, "Open dialog")})).await;
+ let new = marked(&page);
+ assert!(new.iter().any(|l| l.contains("Confirm")) && new.iter().any(|l| l.contains("Cancel")), "{page}");
+ assert!(new.iter().all(|l| l.contains("Confirm") || l.contains("Cancel")), "{new:?}");
+
+ // Swapping the dropdown's options for new elements with the same names marks them again
+ eval(&ctrl, "document.getElementById('dlg').close(); var m=document.getElementById('menu'); m.innerHTML=m.innerHTML").await;
+ let req = Request::builder().uri(format!("/api/sandbox/{}/page?find=large", e.bot.id)).body(Body::empty()).unwrap();
+ let resp = e.app.clone().oneshot(req).await.unwrap();
+ let page: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap();
+ let all = lines(&page);
+ assert!(all[0].starts_with('*') && all[0].contains("Large"), "{all:?}");
+
+ // A #fragment change keeps the list (what the click added is still new); a reload forgets it
+ 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, "Jump")})).await;
+ assert!(page["url"].as_str().unwrap().ends_with("#bottom"), "{page}");
+ let new = marked(&page);
+ assert!(new.len() == 1 && new[0].contains(r#"button "Extra""#), "{page}");
+ open(&e, &format!("{base}/menu")).await;
+ let page = get_page(&e.app, &e.bot.id).await;
+ assert!(marked(&page).is_empty(), "a reload marks nothing: {page}");
+}