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: "unchanged" re-reads and find-ranked controls on dense pages
Lin (kwant bot)cefc11435efd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3ea6dd6b..d540f59b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -57,6 +57,11 @@ 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 don't re-read a page that hasn't changed, and find controls on crowded pages.** When a bot+ reads its browser page again and nothing changed since its last look, it gets a one-line+ "unchanged" instead of the whole page. On a page with more than 40 controls, the bot can say what+ it looks for ("add to cart bike light") and the matching controls are listed first, by plain word+ matching with no extra model call; their numbers stay the same.- **Bots see what each browser step changed, and stop going round in circles.** After every click,key or typing, the bot gets one line saying what changed: the page it went to, or the new and gonelines. If its last 3 steps changed nothing, or it asks a 3rd time in a row for the same click thatdiff --git a/docs/bot-browser.md b/docs/bot-browser.mdindex 488c6355..91e17e72 100644--- a/docs/bot-browser.md+++ b/docs/bot-browser.md@@ -47,8 +47,27 @@ alone is no change; for keys (Tab) it is.The page text in page states is now `document.body.innerText` (laid out in lines, hidden parts leftout) instead of the text of a detached copy, which ran lines together.+## Cheaper reads++Every page state carries `hash` (`reads::page_hash`, FNV-1a over url, title, the text shown, every+control line and the `find` words). A read of a page that still reads the same as the reader's last+look returns only `{url, title, hash, blocked, unchanged: true, note}`:+- HTTP: `GET /page?since=<hash>`, with the hash of the bot's last page state (from `/page`,+ `/navigate` or `/act`). Without `since` the page is always sent whole.+- `browser_page`: the turn is the reader (`SelfScope::turn_id`). Every browser tool's answer counts+ as a look (`BrowserController::reads`, the last 32 readers), so a read right after an action that+ changed nothing is "unchanged". `full: true` sends it whole anyway; a new turn, or one without an+ id, always gets it whole.++Pages list at most 40 controls (`reads::pick_controls`). Without `find` they are the first 40 in+page order (topmost first). With `find` (`browser_page`, or `/page?find=`), the controls naming the+most of its words (3+ letters, a few filler words left out; plain word matching, no model call)+come first, ties in page order. Ref numbers are the page's own, so a control past the 40th still+clicks by its ref. `controls_note` says what was left out. Step answers (`/act`, `browser_act`)+list the first 40 in page order.+## Tests-`tests/browser_refs_test.rs` and `tests/browser_progress_test.rs` (real Chrome, skipped without one;+`tests/browser_refs_test.rs`, `tests/browser_progress_test.rs` and `tests/browser_reads_test.rs` (real Chrome, skipped without one;the `saucedemo_*` tests are ignored and need the network), `ref_tests` in `src/sandbox/browser.rs`-and the tests in `src/sandbox/progress.rs`.+and the tests in `src/sandbox/progress.rs` and `src/sandbox/reads.rs`.diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex f088828e..83a724e0 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`: read the page (url, title, text, clickable controls numbered like [3] button \"Add to cart\").\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_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 and what changed, so you rarely need a separate read. If it says nothing changed or tells you to stop, don't repeat the action: try something else. \@@ -450,7 +450,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\"): curl -sS '{api}/page'\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\- 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.rsindex 7c3b995f..7288ce9c 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -795,6 +795,8 @@ pub struct BrowserController {viewport: Arc<std::sync::Mutex<Option<(u32, u32)>>>,/// The bot's recent actions, for the loop stop (see [`super::progress::Tracker`]).pub progress: Arc<std::sync::Mutex<super::progress::Tracker>>,+ /// Which read each bot saw last, for "unchanged since your last read" (see [`super::reads`]).+ pub reads: Arc<std::sync::Mutex<super::reads::Reads>>,}/// Widest screenshot a bot gets, in pixels, and the narrowest width it may ask for.@@ -856,6 +858,7 @@ impl BrowserController {cookie_jar: Arc::default(),viewport: Arc::default(),progress: Arc::default(),+ reads: Arc::default(),}}diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex f0c0661c..a0d7218b 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -4,6 +4,7 @@ pub mod computer;pub mod credentials;pub mod manager;pub mod progress;+pub mod reads;pub mod service;pub mod vault;diff --git a/src/sandbox/reads.rs b/src/sandbox/reads.rsnew file mode 100644index 00000000..c75b1183--- /dev/null+++ b/src/sandbox/reads.rs@@ -0,0 +1,192 @@+//! Cheaper page reads for bots: a hash of what a read shows, so a read of an unchanged page can+//! answer "same as last time" instead of the whole page again, and a cap on the controls listed,+//! with the ones matching the bot's own words first (plain word matching, no model call).++/// The most controls one read lists.+pub const SHOWN_CONTROLS: usize = 40;+/// The most controls read from the page before picking (the hash covers all of them).+pub const READ_CONTROLS: usize = 400;+/// Bots remembered per browser for "unchanged since your last read".+pub const READERS_KEPT: usize = 32;++/// FNV-1a, 64 bits: stable across runs and builds, unlike `DefaultHasher`.+fn fnv1a(parts: &[&str]) -> u64 {+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;+ for part in parts {+ for b in part.bytes().chain(std::iter::once(0xff)) {+ h ^= u64::from(b);+ h = h.wrapping_mul(0x0000_0100_0000_01b3);+ }+ }+ h+}++/// 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.+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));+ format!("{:016x}", fnv1a(&parts))+}++/// The words of `find` worth matching: lowercase, 3+ letters, without a few filler words.+pub fn find_words(find: &str) -> Vec<String> {+ const FILLER: &[&str] = &["the", "and", "for", "with", "this", "that", "from", "into", "button", "link"];+ let mut words: Vec<String> = Vec::new();+ for w in find.split(|c: char| !c.is_alphanumeric()).map(str::to_lowercase) {+ if w.chars().count() >= 3 && !FILLER.contains(&w.as_str()) && !words.contains(&w) {+ words.push(w);+ }+ }+ words+}++/// 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+/// 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);+ let mut order: Vec<(usize, &String)> = lines.iter().map(|l| (0, l)).collect();+ let mut matched = 0;+ if !words.is_empty() {+ for (score, line) in order.iter_mut() {+ let low = line.to_lowercase();+ *score = words.iter().filter(|w| low.contains(w.as_str())).count();+ if *score > 0 {+ matched += 1;+ }+ }+ // Stable: equal scores keep page order+ order.sort_by_key(|(score, _)| std::cmp::Reverse(*score));+ }+ let shown: Vec<String> = order.iter().take(cap).map(|(_, l)| (*l).clone()).collect();+ let total = lines.len();+ let note = match (words.is_empty(), matched) {+ (false, 0) => Some(format!("No control matches \"{}\"; showing them in page order.", find.trim())),+ _ if total <= cap => None,+ (true, _) => Some(format!(+ "Showing the first {cap} of {total} controls. Read the page again with find (words for what you look for) to list the matching ones first."+ )),+ (false, m) => Some(format!(+ "Showing {cap} of {total} controls: the {} matching \"{}\" first.",+ m.min(cap),+ find.trim()+ )),+ };+ (shown, note)+}++/// Remembers which read each bot (`reader`) saw last, and answers whether a new read is the same.+#[derive(Debug, Default)]+pub struct Reads {+ seen: Vec<(String, String)>,+}++impl Reads {+ /// Whether `reader`'s last read had this `hash`.+ pub fn is_same(&self, reader: &str, hash: &str) -> bool {+ self.seen.iter().any(|(r, h)| r == reader && h == hash)+ }++ /// `reader` was just shown the read with this `hash`.+ pub fn saw(&mut self, reader: &str, hash: &str) {+ self.seen.retain(|(r, _)| r != reader);+ if self.seen.len() >= READERS_KEPT {+ self.seen.remove(0);+ }+ self.seen.push((reader.to_string(), hash.to_string()));+ }++ /// `reader` must get the whole page next time (it asked for it, or lost it).+ pub fn forget(&mut self, reader: &str) {+ self.seen.retain(|(r, _)| r != reader);+ }+}++/// What a read of an unchanged page says instead of the page.+pub const UNCHANGED_NOTE: &str = "Same as your last read of this page: nothing on it changed, so its text and the numbered \+ controls you were shown still hold. Read it with full=true if you need it again.";++#[cfg(test)]+mod tests {+ use super::*;++ fn lines(names: &[&str]) -> Vec<String> {+ names.iter().enumerate().map(|(i, n)| format!("[{}] button \"{n}\"", i + 1)).collect()+ }++ #[test]+ fn the_hash_changes_with_anything_a_read_shows() {+ let c = lines(&["Add to cart"]);+ let h = page_hash("u", "t", "text", &c, "");+ assert_eq!(h, page_hash("u", "t", "text", &c, ""), "stable");+ assert_eq!(h.len(), 16);+ assert_ne!(h, page_hash("u2", "t", "text", &c, ""));+ assert_ne!(h, page_hash("u", "t2", "text", &c, ""));+ assert_ne!(h, page_hash("u", "t", "text!", &c, ""));+ assert_ne!(h, page_hash("u", "t", "text", &lines(&["Remove"]), ""));+ assert_ne!(h, page_hash("u", "t", "text", &c, "cart"));+ // Parts don't run into each other+ assert_ne!(page_hash("ab", "c", "", &[], ""), page_hash("a", "bc", "", &[], ""));+ }++ #[test]+ fn find_keeps_the_words_that_mean_something() {+ assert_eq!(find_words("Add the Bike Light to cart"), vec!["add", "bike", "light", "cart"]);+ assert_eq!(find_words(" "), Vec::<String>::new());+ assert_eq!(find_words("checkout button, checkout"), vec!["checkout"]);+ }++ #[test]+ fn a_short_list_is_shown_whole_and_in_page_order() {+ let all = lines(&["Menu", "Add to cart", "Checkout"]);+ assert_eq!(pick_controls(&all, "", 40), (all.clone(), None));+ }++ #[test]+ fn a_long_list_is_cut_and_matching_controls_come_first() {+ let names: Vec<String> = (1..=60).map(|i| if i == 55 { "Bike Light".into() } else { format!("Item {i}") }).collect();+ let names: Vec<&str> = names.iter().map(String::as_str).collect();+ let all = lines(&names);+ let (shown, note) = pick_controls(&all, "", 40);+ assert_eq!(shown.len(), 40);+ assert_eq!(shown[0], "[1] button \"Item 1\"");+ assert!(note.unwrap().starts_with("Showing the first 40 of 60 controls."));++ let (shown, note) = pick_controls(&all, "bike light", 40);+ assert_eq!(shown[0], "[55] button \"Bike Light\"", "keeps its ref");+ assert_eq!(shown[1], "[1] button \"Item 1\"", "then page order");+ assert_eq!(note.unwrap(), "Showing 40 of 60 controls: the 1 matching \"bike light\" first.");++ // More words matched ranks higher+ let all = lines(&["Light", "Bike", "Bike Light"]);+ let (shown, note) = pick_controls(&all, "bike light", 40);+ assert_eq!(shown[0], "[3] button \"Bike Light\"");+ assert_eq!(&shown[1..], &all[..2]);+ assert_eq!(note, None);++ let (shown, note) = pick_controls(&all, "zebra", 2);+ assert_eq!(shown, all[..2]);+ assert_eq!(note.unwrap(), "No control matches \"zebra\"; showing them in page order.");+ }++ #[test]+ fn each_bot_is_told_unchanged_only_about_its_own_last_read() {+ let mut r = Reads::default();+ assert!(!r.is_same("a", "h1"));+ r.saw("a", "h1");+ assert!(r.is_same("a", "h1"));+ assert!(!r.is_same("b", "h1"), "another bot never saw it");+ r.saw("a", "h2");+ assert!(!r.is_same("a", "h1"));+ r.forget("a");+ assert!(!r.is_same("a", "h2"));+ for i in 0..READERS_KEPT + 5 {+ r.saw(&format!("bot{i}"), "h");+ }+ assert_eq!(r.seen.len(), READERS_KEPT);+ assert!(r.is_same(&format!("bot{}", READERS_KEPT + 4), "h"));+ assert!(!r.is_same("bot0", "h"));+ }+}diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 8be6aecf..d5e9abe9 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -519,8 +519,14 @@ 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.",- "inputSchema": {"type": "object", "properties": {}},+ "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.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "find": {"type": "string", "description": "Words for what you look for, e.g. \"bike light add to cart\": controls naming them are listed first."},+ "full": {"type": "boolean", "description": "true: send the whole page even if it didn't change since your last look."},+ },+ },}),json!({"name": BROWSER_SCREENSHOT,@@ -622,7 +628,10 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, natrue,);}- let (text, is_error) = run_browser_tool(state, target, name, args).await;+ // Each turn is its own reader: a new turn gets the whole page on its first read. A turn+ // without an id always gets the whole page+ let reader = scope.turn_id.clone().unwrap_or_default();+ let (text, is_error) = run_browser_tool(state, target, &reader, name, args).await;// A CAPTCHA wall: ask the person to solve it, then show the agent the page they leftif !is_error {if let Ok(page) = serde_json::from_str::<Value>(&text) {@@ -631,7 +640,7 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, naif super::human_steps::browser_is_held(state, target).await {return (note, false);}- let (after, _) = run_browser_tool(state, target, BROWSER_PAGE, &Value::Null).await;+ let (after, _) = run_browser_tool(state, target, &reader, BROWSER_PAGE, &json!({"full": true})).await;return (format!("{note}\n\nThe page now:\n{after}"), false);}}@@ -640,8 +649,14 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, na(text, is_error)}-async fn run_browser_tool(state: &AppState, target: &str, name: &str, args: &Value) -> (String, bool) {- use super::routes::{act_sandbox_allowed, get_sandbox_page, navigate_sandbox, InteractPayload, NavigatePayload};+/// `reader` names who reads (empty: nobody known), for `browser_page` to answer "unchanged" when+/// that reader's last page (from any browser tool) still reads the same.+async fn run_browser_tool(state: &AppState, target: &str, reader: &str, name: &str, args: &Value) -> (String, bool) {+ use super::routes::{act_sandbox_allowed, get_sandbox_page, navigate_sandbox, unchanged_read, InteractPayload, NavigatePayload, PageQuery};+ let ctrl = match reader {+ "" => None,+ _ => super::routes::get_or_create_browser_controller(state, target).await,+ };let state = State(state.clone());let target = Path(target.to_string());let result = match name {@@ -651,7 +666,10 @@ async fn run_browser_tool(state: &AppState, target: &str, name: &str, args: &Val};navigate_sandbox(state, target, Json(NavigatePayload { url: url.to_string() })).await}- BROWSER_PAGE => get_sandbox_page(state, target).await,+ BROWSER_PAGE => {+ let find = args["find"].as_str().map(str::to_string);+ get_sandbox_page(state, target, Query(PageQuery { find, since: None })).await+ }_ => {let Some(action) = args["action"].as_str() else {return ("action is required: click, type, key or scroll".into(), true);@@ -672,7 +690,15 @@ async fn run_browser_tool(state: &AppState, target: &str, name: &str, args: &Val}};match result {- Ok(Json(page)) => {+ Ok(Json(mut page)) => {+ if let (Some(ctrl), Some(hash)) = (ctrl, page["hash"].as_str().map(str::to_string)) {+ let mut reads = ctrl.reads.lock().unwrap_or_else(|e| e.into_inner());+ let same = name == BROWSER_PAGE && args["full"].as_bool() != Some(true) && reads.is_same(reader, &hash);+ reads.saw(reader, &hash);+ if same {+ page = unchanged_read(&page);+ }+ }let is_error = page.get("error").is_some();(page.to_string(), is_error)}diff --git a/src/server/routes.rs b/src/server/routes.rsindex bd1e9d0b..aabf1305 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -4327,11 +4327,19 @@ pub async fn interact_sandbox(/// Compact, text-only page state for agents (no base64 image to wade through).async fn sandbox_page_state(ctrl: &crate::sandbox::BrowserController) -> serde_json::Value {let snap = ctrl.snapshot().await;- page_state_from(ctrl, snap).await+ page_state_from(ctrl, snap, "").await}/// [`sandbox_page_state`] from a snapshot already read (`None`: the page couldn't be read).-async fn page_state_from(ctrl: &crate::sandbox::BrowserController, snap: Option<crate::sandbox::progress::Snapshot>) -> serde_json::Value {+/// `find`: the bot's words for what it looks for, to list the matching controls first on a page+/// with more than [`reads::SHOWN_CONTROLS`](crate::sandbox::reads::SHOWN_CONTROLS). `hash` says+/// what the read shows, for [`get_sandbox_page`]'s `since`.+async fn page_state_from(+ ctrl: &crate::sandbox::BrowserController,+ snap: Option<crate::sandbox::progress::Snapshot>,+ find: &str,+) -> serde_json::Value {+ use crate::sandbox::reads;let (url, title, text) = match snap {Some(s) => (s.url, s.title, s.text),None => (@@ -4340,14 +4348,21 @@ async fn page_state_from(ctrl: &crate::sandbox::BrowserController, snap: Option<String::new(),),};- let clickable = ctrl.list_clickables(40).await;+ let controls = ctrl.list_clickables(reads::READ_CONTROLS).await;+ let shown = truncate_chars(&text, 2000);+ let hash = reads::page_hash(&url, &title, shown, &controls, find.trim());+ let (clickable, controls_note) = reads::pick_controls(&controls, find, reads::SHOWN_CONTROLS);let mut page = json!({"url": url,"title": title,- "text": truncate_chars(&text, 2000),+ "text": shown,"clickable": clickable,"blocked": false,+ "hash": hash,});+ if let Some(note) = controls_note {+ page["controls_note"] = json!(note);+ }// A CAPTCHA widget on an otherwise normal page (TikTok's slider over the feed, a// reCAPTCHA on a form) counts too; its box tells the person's view where to looklet captcha = ctrl.probe_captcha().await.ok().flatten();@@ -4385,14 +4400,43 @@ async fn broadcast_sandbox_screenshot(state: &AppState, team_id: &str, ctrl: &cr}}+/// `GET /api/sandbox/:id/page` options. `find`: words for what the bot looks for (matching+/// controls listed first). `since`: the `hash` of the bot's last read; when the page still reads+/// the same, the answer is a short `unchanged` note instead of the page.+#[derive(Debug, Default, Deserialize)]+pub struct PageQuery {+ #[serde(default)]+ pub find: Option<String>,+ #[serde(default)]+ pub since: Option<String>,+}+pub async fn get_sandbox_page(State(state): State<AppState>,Path(team_id): Path<String>,+ Query(query): Query<PageQuery>,) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {let ctrl = get_or_create_browser_controller(&state, &team_id).await.ok_or_else(|| browser_unavailable(&state))?;- Ok(Json(sandbox_page_state(&ctrl).await))+ let snap = ctrl.snapshot().await;+ let page = page_state_from(&ctrl, snap, query.find.as_deref().unwrap_or_default()).await;+ if query.since.as_deref().is_some_and(|since| !since.is_empty() && page["hash"] == json!(since)) {+ return Ok(Json(unchanged_read(&page)));+ }+ Ok(Json(page))+}++/// What a read of a page that still reads the same returns instead of it.+pub fn unchanged_read(page: &serde_json::Value) -> serde_json::Value {+ json!({+ "url": page["url"],+ "title": page["title"],+ "hash": page["hash"],+ "blocked": page["blocked"],+ "unchanged": true,+ "note": crate::sandbox::reads::UNCHANGED_NOTE,+ })}/// Agent-facing action endpoint (`POST /api/sandbox/:id/act`, the shell bots' browser API):@@ -4444,7 +4488,7 @@ pub async fn act_sandbox_allowed(let here = before.as_ref().map(|b| b.url.clone()).unwrap_or_default();let repeat = ctrl.progress.lock().unwrap_or_else(|e| e.into_inner()).before(&here, key.as_deref());if let Some(stop) = repeat {- let mut page = page_state_from(&ctrl, before).await;+ let mut page = page_state_from(&ctrl, before, "").await;page["stalled"] = json!(true);page["error"] = json!(stop);return Ok(Json(page));@@ -4506,7 +4550,7 @@ pub async fn act_sandbox_allowed(changed = diff(&after);}let stall = ctrl.progress.lock().unwrap_or_else(|e| e.into_inner()).after(changed.is_some());- let mut page = page_state_from(&ctrl, after).await;+ let mut page = page_state_from(&ctrl, after, "").await;page["changed"] = json!(changed.as_deref().unwrap_or("Nothing on the page changed."));match result {Ok(done) => page["result"] = json!(done),diff --git a/tests/browser_reads_test.rs b/tests/browser_reads_test.rsnew file mode 100644index 00000000..a7f107fe--- /dev/null+++ b/tests/browser_reads_test.rs@@ -0,0 +1,220 @@+//! Cheaper page reads in kwnt's own browser, through a real Chrome: a read of a page that still+//! reads the same as the bot's last look answers "unchanged" instead of the page (`?since=` on+//! the HTTP API, per turn for `browser_page`), and a page with many controls lists 40, the ones+//! matching the bot's `find` words first, with their refs kept. Skipped when no Chrome is+//! installed.+#[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,+ server::{continuity::SelfScope, create_router, mcp_runtime, 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;++/// 60 products, one of them far down the page, and a counter.+fn shop_page() -> String {+ let mut page = String::from("<!doctype html><title>shop</title><p id=n>Cart 0</p>");+ for i in 1..=60 {+ let name = if i == 55 { "Bike Light".to_string() } else { format!("Item {i}") };+ page.push_str(&format!(+ "<div><h3>{name}</h3><button onclick=\"var n=document.getElementById('n');n.textContent='Cart '+(Number(n.textContent.slice(5))+1)\">Add {name}</button></div>"+ ));+ }+ page+}++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 _ = stream.read(&mut buf).await;+ let page = shop_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}/shop")+}++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 send(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Value) -> Value {+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ if let Some(token) = auth {+ req = req.header("authorization", format!("Bearer {token}"));+ }+ let body = if method == "GET" { Body::empty() } else { Body::from(body.to_string()) };+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ assert_eq!(status, StatusCode::OK, "{v}");+ v+}++async fn page(e: &Env, query: &str) -> Value {+ send(&e.app, "GET", &format!("/api/sandbox/{}/page{query}", e.bot.id), None, Value::Null).await+}++async fn act(e: &Env, body: Value) -> Value {+ send(&e.app, "POST", &format!("/api/sandbox/{}/act", e.bot.id), None, body).await+}++fn controls(page: &Value) -> Vec<String> {+ page["clickable"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect()+}++fn ref_of(line: &str) -> u64 {+ line[1..line.find(']').unwrap()].parse().unwrap()+}++/// Calls one of the turn's own browser tools; returns the page it answered.+async fn tool(e: &Env, token: &str, name: &str, args: Value) -> Value {+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});+ let v = send(&e.app, "POST", "/api/mcp/self", Some(token), rpc).await;+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or_default();+ serde_json::from_str(text).unwrap_or_else(|_| panic!("{v}"))+}++#[tokio::test]+async fn an_unchanged_page_is_not_sent_again_and_a_long_list_puts_matches_first() {+ 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 url = serve().await;+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");+ ctrl.navigate(&url).await.unwrap();++ // 60 controls: 40 listed in page order, and a note on how to see the others+ let first = page(&e, "").await;+ let hash = first["hash"].as_str().unwrap().to_string();+ let listed = controls(&first);+ assert_eq!(listed.len(), 40, "{first}");+ assert!(listed[0].contains("Add Item 1"), "{listed:?}");+ assert!(!first.to_string().contains("Bike Light\\\""), "far down the page");+ assert!(first["controls_note"].as_str().unwrap().starts_with("Showing the first 40 of 60 controls."), "{first}");++ // The same page again: only "unchanged"+ let again = page(&e, &format!("?since={hash}")).await;+ assert_eq!(again["unchanged"], true, "{again}");+ assert!(again.get("text").is_none() && again.get("clickable").is_none(), "{again}");+ assert_eq!(again["url"], first["url"]);+ // Without since, or with another hash: the whole page+ assert!(page(&e, "").await.get("text").is_some());+ assert!(page(&e, "?since=0000").await.get("text").is_some());++ // find lists the matching control first, under its own ref, which clicks it+ let found = page(&e, "?find=bike%20light").await;+ let bike = controls(&found)[0].clone();+ assert!(bike.contains("Add Bike Light"), "{found}");+ assert_eq!(found["controls_note"], "Showing 40 of 60 controls: the 1 matching \"bike light\" first.", "{found}");+ assert_ne!(found["hash"], first["hash"], "another read");+ let done = act(&e, json!({"action": "click", "ref": ref_of(&bike)})).await;+ assert_eq!(done["changed"], "New: \"Cart 1\". Gone: \"Cart 0\".", "{done}");++ // The page changed, so the old hash gets it whole+ let after = page(&e, &format!("?since={hash}")).await;+ assert!(after["text"].as_str().unwrap().contains("Cart 1"), "{after}");++ // browser_page in a turn: unchanged after the turn's own last look, whole for a new turn+ let scope = |turn: &str| SelfScope {+ kwant_id: e.bot.id.clone(),+ kwant_name: e.bot.name.clone(),+ sandbox_target: Some(e.bot.id.clone()),+ turn_id: Some(turn.to_string()),+ ..Default::default()+ };+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&e.state, &e.bot, None, None, Some(scope("t1"))).await.unwrap();+ let opened = tool(&e, &token, "browser_open", json!({"url": url})).await;+ assert!(opened["text"].as_str().unwrap().contains("Cart 0"), "{opened}");+ let read = tool(&e, &token, "browser_page", json!({})).await;+ assert_eq!(read["unchanged"], true, "the open already showed it: {read}");+ let read = tool(&e, &token, "browser_page", json!({"full": true})).await;+ assert!(read["text"].as_str().unwrap().contains("Cart 0"), "{read}");+ let found = tool(&e, &token, "browser_page", json!({"find": "bike"})).await;+ assert!(controls(&found)[0].contains("Add Bike Light"), "other words, another read: {found}");+ let acted = tool(&e, &token, "browser_act", json!({"action": "click", "ref": ref_of(&controls(&found)[0])})).await;+ assert!(acted["text"].as_str().unwrap().contains("Cart 1"), "{acted}");+ assert_eq!(tool(&e, &token, "browser_page", json!({})).await["unchanged"], true, "the act's answer showed it");++ let (_ctx2, other_turn) = mcp_runtime::prepare_turn_with_self(&e.state, &e.bot, None, None, Some(scope("t2"))).await.unwrap();+ let read = tool(&e, &other_turn, "browser_page", json!({})).await;+ assert!(read["text"].as_str().unwrap().contains("Cart 1"), "a new turn never saw it: {read}");+ assert_eq!(tool(&e, &other_turn, "browser_page", json!({})).await["unchanged"], true);+ mcp_runtime::finish_turn(&e.state, &token).await;+ mcp_runtime::finish_turn(&e.state, &other_turn).await;+}++/// The same on a real shop (network): the inventory read twice is "unchanged" the second time,+/// and find ("add to cart bike light") puts the Bike Light's Add to cart button first.+#[tokio::test]+#[ignore = "needs the network"]+async fn saucedemo_reads_are_cheaper() {+ 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 ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");+ ctrl.navigate("https://www.saucedemo.com/").await.unwrap();+ let login = page(&e, "").await;+ let field = |name: &str| ref_of(controls(&login).iter().find(|l| l.contains(name)).unwrap());+ act(&e, json!({"action": "type", "ref": field("Username"), "text": "standard_user"})).await;+ act(&e, json!({"action": "type", "ref": field("Password"), "text": "secret_sauce"})).await;+ let shop = act(&e, json!({"action": "click", "ref": field("Login")})).await;+ assert!(shop["url"].as_str().unwrap().contains("inventory"), "{shop}");++ let again = page(&e, &format!("?since={}", shop["hash"].as_str().unwrap())).await;+ assert_eq!(again["unchanged"], true, "{again}");+ let found = page(&e, "?find=add%20to%20cart%20bike%20light").await;+ let first = &controls(&found)[0];+ assert!(first.contains("Add to cart") && first.contains("Bike Light"), "{found}");+ eprintln!("first control for \"bike light\": {first}");+}diff --git a/tests/browser_tools_test.rs b/tests/browser_tools_test.rsindex 16ca15a8..fa38f17f 100644--- a/tests/browser_tools_test.rs+++ b/tests/browser_tools_test.rs@@ -220,7 +220,8 @@ async fn claude_turn_gets_browser_tools_that_drive_its_own_panel() {assert!(!ctrl.capture_screenshot().await.unwrap().is_empty());assert!(!state.browser_controllers.lock().await.contains_key(&other.id), "no other bot's browser touched");- let (text, is_error) = self_tool(&app, &token, "browser_page", json!({})).await;+ // full: the click's own answer may already show this page, and a plain re-read would say "unchanged"+ let (text, is_error) = self_tool(&app, &token, "browser_page", json!({"full": true})).await;assert!(!is_error && text.contains("button was pressed"), "{text}");let (text, is_error) = self_tool(&app, &token, "browser_act", json!({"action": "dance"})).await;assert!(is_error && text.contains("Unknown action"), "{text}");