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: say what each action changed, and stop loops
Lin (kwant bot)25e68ccd17b6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ef0f080f..f2b4fc9d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -57,6 +57,10 @@ 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 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 gone+ lines. If its last 3 steps changed nothing, or it asks for the same click a 3rd time in a row, it+ is told to stop and try something else. The page text bots read now keeps its line breaks.- **Bots click page controls by number, and never through a banner.** The page a bot reads listsits buttons, links and fields as numbered refs with their role (`[9] button "Add to cart" · SauceLabs Bike Light`), naming the product or row when several share a name. A bot clicks or types bydiff --git a/docs/bot-browser.md b/docs/bot-browser.mdindex 3fc6376c..5ea36af7 100644--- a/docs/bot-browser.md+++ b/docs/bot-browser.md@@ -25,7 +25,28 @@ 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 betweenthe payment check and the click renumbers it (one bot drives one browser, so rare).+## What changed, and the loop stop++Each `/act` (and `browser_act`) reads the page before and after the action+(`BrowserController::snapshot`: url, title, the rendered text in lines, scroll position, field fill+lengths and focus; field values never leave the page) and returns `changed`, one short line from+`progress::what_changed`: `Went to <url> ("<title>").`, or `Title is now "…". New: "…", "…" (+n+more). Gone: "…".`, or `Nothing on the page changed.` A page that hasn't changed yet is read once+more after 400 ms (a slow submit). A click always focuses what it hits, so for clicks a moved focus+alone is no change; for keys (Tab) it is.++`progress::Tracker` (one per browser, reset when an address is opened):+- 3 actions in a row that change nothing: the third returns `stalled: true` and `error` set to+ `STALL_STOP` (try something else, or tell the person). The count then starts over.+- The same click (same ref or label) or the same typing into the same place a 3rd time in a row on+ the same address is refused before it runs (`REPEAT_STOP`), until the bot does something else.+ Scrolls and keys don't count and don't break a run.++The page text in page states is now `document.body.innerText` (laid out in lines, hidden parts left+out) instead of the text of a detached copy, which ran lines together.+## 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`.+`tests/browser_refs_test.rs` and `tests/browser_progress_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`.diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex c94c7de6..f088828e 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -439,7 +439,7 @@ impl TurnInput {- `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. \+ 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. \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,@@ -455,7 +455,7 @@ impl TurnInput {- 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. \+ Every /act call returns the updated page (url, title, text, clickable) 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. \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 6cfcd99b..7c3b995f 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -793,6 +793,8 @@ pub struct BrowserController {/// The fixed viewport set for a windowless browser, restored after a bot's sized screenshot./// `None`: the page follows its real window.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>>,}/// Widest screenshot a bot gets, in pixels, and the narrowest width it may ask for.@@ -853,6 +855,7 @@ impl BrowserController {pointer_held: Arc::default(),cookie_jar: Arc::default(),viewport: Arc::default(),+ progress: Arc::default(),}}@@ -1160,6 +1163,7 @@ impl BrowserController {pub async fn navigate_unlocked(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {refuse_file_path(target_url)?;+ self.progress.lock().unwrap_or_else(|e| e.into_inner()).reset();let _ = self.collect_captured_credentials().await;let _ = self.send_cdp_command("Page.enable", json!({})).await;let res = self@@ -1269,6 +1273,38 @@ impl BrowserController {.ok_or_else(|| BrowserError::Protocol("Screenshot data missing".into()))}+ /// The page as one [`Snapshot`](super::progress::Snapshot) (url, title, the rendered text in+ /// lines, scroll and field state, and focus), in one read. Also updates the stored location.+ pub async fn snapshot(&self) -> Option<super::progress::Snapshot> {+ let expression = r#"+ (function() {+ // The rendered text, laid out in lines (hidden parts, scripts and styles left out)+ var text = document.body ? document.body.innerText.substring(0, 10000) : '';+ // Lengths and checks only: a field's value never leaves the page+ var fields = [];+ document.querySelectorAll('input,textarea,select').forEach(function (el) {+ fields.push((el.value || '').length + (el.checked ? 'c' : ''));+ });+ var a = document.activeElement;+ var focus = a ? a.tagName + '#' + (a.id || a.name || '') : '';+ return [location.href, document.title, text, Math.round(scrollX) + ',' + Math.round(scrollY) + '|' + fields.join(','), focus];+ })()+ "#;+ let res = self+ .send_cdp_command("Runtime.evaluate", json!({ "expression": expression, "returnByValue": true }))+ .await+ .ok()?;+ let v = res["result"]["value"].as_array()?;+ let s = |i: usize| v.get(i).and_then(Value::as_str).unwrap_or_default().to_string();+ let snap = super::progress::Snapshot { url: s(0), title: s(1), text: s(2), state: s(3), focus: s(4) };+ if snap.url.is_empty() {+ return None;+ }+ *self.current_url.lock().await = Some(snap.url.clone());+ *self.current_title.lock().await = Some(snap.title.clone());+ Some(snap)+ }+pub async fn extract_content(&self) -> Result<String, BrowserError> {let expression = r#"(function() {diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex 27e4ef9d..f0c0661c 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -3,6 +3,7 @@ pub mod browser;pub mod computer;pub mod credentials;pub mod manager;+pub mod progress;pub mod service;pub mod vault;diff --git a/src/sandbox/progress.rs b/src/sandbox/progress.rsnew file mode 100644index 00000000..b650744f--- /dev/null+++ b/src/sandbox/progress.rs@@ -0,0 +1,233 @@+//! Progress in a bot's browser: what an action changed on the page, and when the bot is going+//! round in circles. Pure, so the rules are tested as tables; `routes::act_sandbox_allowed` takes+//! a [`Snapshot`] before and after each action and keeps one [`Tracker`] per browser.++use super::ClickTarget;++/// What the page shows, for comparing before and after an action. `state` covers what the text+/// misses: scroll position and how much is in each field (lengths only, never values).+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct Snapshot {+ pub url: String,+ pub title: String,+ pub text: String,+ pub state: String,+ /// The focused element. A move is progress for a key (Tab), not for a click, which always+ /// focuses what it hits.+ pub focus: String,+}++/// Lines shown per side of a change, and the most characters per line.+const SHOWN_LINES: usize = 4;+const LINE_CHARS: usize = 80;++fn lines(text: &str) -> Vec<&str> {+ text.lines().map(str::trim).filter(|l| !l.is_empty()).collect()+}++fn quote(line: &str) -> String {+ let mut short: String = line.chars().take(LINE_CHARS).collect();+ if line.chars().count() > LINE_CHARS {+ short.push('…');+ }+ format!("\"{short}\"")+}++/// Lines of `a` that aren't in `b`, in page order, each once.+fn only_in<'a>(a: &[&'a str], b: &[&str]) -> Vec<&'a str> {+ let mut out: Vec<&str> = Vec::new();+ for line in a {+ if !b.contains(line) && !out.contains(line) {+ out.push(line);+ }+ }+ out+}++fn list(label: &str, found: &[&str]) -> Option<String> {+ if found.is_empty() {+ return None;+ }+ let shown: Vec<String> = found.iter().take(SHOWN_LINES).map(|l| quote(l)).collect();+ let more = found.len().saturating_sub(SHOWN_LINES);+ let more = if more > 0 { format!(" (+{more} more)") } else { String::new() };+ Some(format!("{label}: {}{more}.", shown.join(", ")))+}++/// A short "what changed" from `before` to `after`, or `None` when nothing did. `focus`: whether+/// the focus moving counts.+pub fn what_changed(before: &Snapshot, after: &Snapshot, focus: bool) -> Option<String> {+ let same_focus = !focus || before.focus == after.focus;+ if before.url == after.url && before.title == after.title && before.text == after.text && before.state == after.state && same_focus {+ return None;+ }+ if before.url != after.url {+ let title = if after.title.is_empty() { String::new() } else { format!(" ({})", quote(&after.title)) };+ return Some(format!("Went to {}{title}.", after.url));+ }+ let mut parts: Vec<String> = Vec::new();+ if before.title != after.title {+ parts.push(format!("Title is now {}.", quote(&after.title)));+ }+ let (old, new) = (lines(&before.text), lines(&after.text));+ parts.extend(list("New", &only_in(&new, &old)));+ parts.extend(list("Gone", &only_in(&old, &new)));+ if parts.is_empty() {+ if before.text != after.text {+ parts.push("The text moved around; no new lines.".into());+ } else if before.state != after.state {+ parts.push("No new text; the scroll position or a field changed.".into());+ } else {+ parts.push("The focus moved.".into());+ }+ }+ Some(parts.join(" "))+}++/// Which actions count as "the same action" for the loop stop: clicks on the same target and+/// typing the same text into the same place. Scrolls and keys (Tab, arrows) are left out: they+/// repeat on purpose.+pub fn action_key(action: &str, target: Option<&ClickTarget>, text: Option<&str>) -> Option<String> {+ let at = |t: Option<&ClickTarget>| match t {+ Some(ClickTarget::Ref(r)) => format!("ref {r}"),+ Some(ClickTarget::Text(l)) => format!("label {}", l.to_lowercase()),+ None => "focus".into(),+ };+ match action {+ "click" | "click_text" => Some(format!("click {}", at(target))),+ "type" => Some(format!("type {} into {}", text.unwrap_or_default(), at(target))),+ _ => None,+ }+}++/// How many times in a row before a bot is stopped.+pub const STALL_AFTER: u32 = 3;++pub const REPEAT_STOP: &str = "Not done: this is the 3rd time in a row you asked for exactly this action on this page. \+ Don't repeat it; try something else (another control, scroll, a different page), or tell the person what is in the way.";+pub const STALL_STOP: &str = "Stop: your last 3 actions changed nothing on this page. Don't repeat them; try something else \+ (another control, scroll, a different page), or tell the person what is in the way.";++/// One browser's recent actions.+#[derive(Debug, Default)]+pub struct Tracker {+ last: Option<(String, String)>,+ repeats: u32,+ unchanged: u32,+}++impl Tracker {+ /// A new page (the bot opened an address): start over.+ pub fn reset(&mut self) {+ *self = Tracker::default();+ }++ /// Before an action: `Some(REPEAT_STOP)` when it would be the same action a 3rd time in a row+ /// on `url`. It keeps refusing until the bot does something else.+ pub fn before(&mut self, url: &str, key: Option<&str>) -> Option<&'static str> {+ let key = key?;+ let same = self.last.as_ref().is_some_and(|(u, k)| u == url && k == key);+ if same && self.repeats + 1 >= STALL_AFTER {+ return Some(REPEAT_STOP);+ }+ self.repeats = if same { self.repeats + 1 } else { 1 };+ self.last = Some((url.to_string(), key.to_string()));+ None+ }++ /// After an action: `Some(STALL_STOP)` when it is the 3rd in a row that changed nothing.+ /// The count starts over after it is reported.+ pub fn after(&mut self, changed: bool) -> Option<&'static str> {+ if changed {+ self.unchanged = 0;+ return None;+ }+ self.unchanged += 1;+ if self.unchanged >= STALL_AFTER {+ self.unchanged = 0;+ return Some(STALL_STOP);+ }+ None+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn snap(url: &str, title: &str, text: &str, state: &str) -> Snapshot {+ Snapshot { url: url.into(), title: title.into(), text: text.into(), state: state.into(), focus: String::new() }+ }++ #[test]+ fn a_change_is_told_in_a_line() {+ let a = snap("https://s.test/", "Shop", "Backpack\nAdd to cart\nBike Light\nAdd to cart", "0");+ assert_eq!(what_changed(&a, &a, true), None);+ let b = snap("https://s.test/", "Shop", "Backpack\nRemove\nBike Light\nAdd to cart\n1", "0");+ assert_eq!(what_changed(&a, &b, true).unwrap(), "New: \"Remove\", \"1\".");+ let c = snap("https://s.test/", "Cart (1)", "Backpack", "0");+ assert_eq!(what_changed(&a, &c, true).unwrap(), "Title is now \"Cart (1)\". Gone: \"Add to cart\", \"Bike Light\".");+ let d = snap("https://s.test/cart", "Your cart", "anything", "0");+ assert_eq!(what_changed(&a, &d, true).unwrap(), "Went to https://s.test/cart (\"Your cart\").");+ let e = snap("https://s.test/", "Shop", "Bike Light\nAdd to cart\nBackpack\nAdd to cart", "0");+ assert_eq!(what_changed(&a, &e, true).unwrap(), "The text moved around; no new lines.");+ let f = snap("https://s.test/", "Shop", a.text.as_str(), "600");+ assert!(what_changed(&a, &f, true).unwrap().starts_with("No new text"));+ let g = Snapshot { focus: "BUTTON#".into(), ..a.clone() };+ assert!(what_changed(&a, &g, true).is_some(), "Tab moved the focus");+ assert_eq!(what_changed(&a, &g, false), None, "a click always focuses what it hits");+ }++ #[test]+ fn long_changes_are_cut_short() {+ let a = snap("u", "t", "", "");+ assert_eq!(what_changed(&a, &Snapshot { focus: "INPUT#q".into(), ..a.clone() }, true).unwrap(), "The focus moved.");+ let many: Vec<String> = (1..=7).map(|i| format!("line {i}")).collect();+ let b = snap("u", "t", &many.join("\n"), "");+ assert_eq!(what_changed(&a, &b, true).unwrap(), "New: \"line 1\", \"line 2\", \"line 3\", \"line 4\" (+3 more).");+ let long = "x".repeat(200);+ let c = snap("u", "t", &long, "");+ assert_eq!(what_changed(&a, &c, true).unwrap(), format!("New: \"{}…\".", "x".repeat(80)));+ }++ #[test]+ fn the_same_action_a_third_time_is_refused_until_the_bot_does_something_else() {+ let mut t = Tracker::default();+ let add = action_key("click", Some(&ClickTarget::Ref(9)), None);+ let add = add.as_deref();+ assert_eq!(t.before("u", add), None);+ assert_eq!(t.before("u", add), None);+ assert_eq!(t.before("u", add), Some(REPEAT_STOP));+ assert_eq!(t.before("u", add), Some(REPEAT_STOP), "still refused");+ assert_eq!(t.before("u", Some("click ref 3")), None);+ assert_eq!(t.before("u", add), None, "after something else it may again");+ // Scrolls and keys don't count and don't break a run+ assert_eq!(action_key("scroll", None, None), None);+ assert_eq!(action_key("key", None, None), None);+ assert_eq!(t.before("u", None), None);+ assert_eq!(t.before("u", add), None);+ assert_eq!(t.before("u", add), Some(REPEAT_STOP));+ // The same click on another page is another action+ assert_eq!(t.before("u2", add), None);+ // Typing different text is a different action; a label is matched without case+ assert_ne!(action_key("type", None, Some("a")), action_key("type", None, Some("b")));+ assert_eq!(+ action_key("click_text", Some(&ClickTarget::Text("Next".into())), None),+ action_key("click", Some(&ClickTarget::Text("next".into())), None)+ );+ t.reset();+ assert_eq!(t.before("u2", add), None);+ }++ #[test]+ fn three_actions_that_change_nothing_stop_the_bot() {+ let mut t = Tracker::default();+ assert_eq!(t.after(false), None);+ assert_eq!(t.after(false), None);+ assert_eq!(t.after(true), None, "a change starts over");+ assert_eq!(t.after(false), None);+ assert_eq!(t.after(false), None);+ assert_eq!(t.after(false), Some(STALL_STOP));+ assert_eq!(t.after(false), None, "counted afresh after it is told");+ }+}diff --git a/src/server/routes.rs b/src/server/routes.rsindex 81452eca..bd1e9d0b 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -4326,14 +4326,20 @@ 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 (url, title) = match ctrl.sync_location().await {- Some(loc) => loc,+ let snap = ctrl.snapshot().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 {+ let (url, title, text) = match snap {+ Some(s) => (s.url, s.title, s.text),None => (ctrl.current_url.lock().await.clone().unwrap_or_default(),ctrl.current_title.lock().await.clone().unwrap_or_default(),+ String::new(),),};- let text = ctrl.extract_content().await.unwrap_or_default();let clickable = ctrl.list_clickables(40).await;let mut page = json!({"url": url,@@ -4427,6 +4433,22 @@ pub async fn act_sandbox_allowed(let _permit = ctrl.control.try_read().map_err(|_| browser_request_failed(crate::sandbox::BrowserError::HumanControl))?;let text = payload.text.clone().unwrap_or_default();let clicks = crate::sandbox::ClickTarget::from_args(&json!({"ref": payload.ref_, "text": payload.text}));+ // The loop stop: the same action a 3rd time in a row on this page is refused+ use crate::sandbox::progress;+ let before = ctrl.snapshot().await;+ let target = match payload.action.as_str() {+ "type" => crate::sandbox::ClickTarget::from_args(&json!({"ref": payload.ref_})),+ _ => clicks.clone(),+ };+ let key = progress::action_key(&payload.action, target.as_ref(), payload.text.as_deref());+ 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;+ page["stalled"] = json!(true);+ page["error"] = json!(stop);+ return Ok(Json(page));+ }let result: Result<String, String> = match (payload.action.as_str(), clicks) {("click_text" | "click", Some(target)) => ctrl.click_target(&target)@@ -4470,11 +4492,32 @@ pub async fn act_sandbox_allowed()),};broadcast_sandbox_screenshot(&state, &team_id, &ctrl).await;- let mut page = sandbox_page_state(&ctrl).await;+ // What changed; a page that hasn't yet gets one more moment (a slow submit, an animation)+ let focus = !matches!(payload.action.as_str(), "click" | "click_text");+ let diff = |after: &Option<progress::Snapshot>| match (&before, after) {+ (Some(b), Some(a)) => progress::what_changed(b, a, focus),+ _ => Some("The page couldn't be read before or after.".to_string()),+ };+ let mut after = ctrl.snapshot().await;+ let mut changed = diff(&after);+ if changed.is_none() {+ tokio::time::sleep(std::time::Duration::from_millis(400)).await;+ after = ctrl.snapshot().await;+ 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;+ page["changed"] = json!(changed.as_deref().unwrap_or("Nothing on the page changed."));match result {Ok(done) => page["result"] = json!(done),Err(err) => page["error"] = json!(err),}+ if let Some(stop) = stall {+ page["stalled"] = json!(true);+ if page.get("error").is_none() {+ page["error"] = json!(stop);+ }+ }if let Some(url) = page["url"].as_str() {let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {team_id: team_id.clone(),diff --git a/tests/browser_progress_test.rs b/tests/browser_progress_test.rsnew file mode 100644index 00000000..37327bd8--- /dev/null+++ b/tests/browser_progress_test.rs@@ -0,0 +1,197 @@+//! What changed after each action in kwnt's own browser, and the loop stop, through a real+//! Chrome: each `/act` says what is new or gone (or that it went to another page), waits a moment+//! for a slow change, and stops a bot whose last 3 actions changed nothing or who asks for the+//! same action a 3rd time in a row. Opening an address starts over. 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, progress},+ server::{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 COUNTER_PAGE: &str = "<!doctype html><title>counter</title><p id=n>Count 0</p>\+<button onclick=\"var n=document.getElementById('n');n.textContent='Count '+(Number(n.textContent.slice(6))+1)\">Add</button>\+<button>Nothing</button><button>Also nothing</button>\+<button onclick=\"setTimeout(function(){document.getElementById('s').textContent='Slow done'},500)\">Slow</button><p id=s></p>\+<input name=q placeholder=Search><a href='/other'>Other page</a>";+const OTHER_PAGE: &str = "<!doctype html><title>other</title><p>Elsewhere</p>";++/// 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() {+ "/counter" => COUNTER_PAGE,+ _ => OTHER_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 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 act(e: &Env, body: Value) -> Value {+ let (status, page) = post_act(&e.app, &e.bot.id, body).await;+ assert_eq!(status, StatusCode::OK, "{page}");+ page+}++fn click(label: &str) -> Value {+ json!({"action": "click_text", "text": label})+}++#[tokio::test]+async fn each_action_says_what_changed_and_a_loop_is_stopped() {+ 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}/counter")).await;++ // New and gone lines+ let page = act(&e, click("Add")).await;+ assert_eq!(page["changed"], "New: \"Count 1\". Gone: \"Count 0\".", "{page}");+ assert!(page["error"].is_null());+ // A change that lands after the click returns still shows+ let page = act(&e, click("Slow")).await;+ 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: 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}");++ // Three actions in a row that change nothing: the third says stop+ let page = act(&e, click("Nothing")).await;+ assert_eq!(page["changed"], "Nothing on the page changed.");+ assert!(page["error"].is_null(), "{page}");+ act(&e, click("Also nothing")).await;+ let page = act(&e, json!({"action": "scroll", "delta_y": 600})).await;+ assert_eq!(page["error"], progress::STALL_STOP, "{page}");+ assert_eq!(page["stalled"], true);++ // The same click a third time in a row is refused before it runs, until something else+ act(&e, click("Add")).await;+ act(&e, click("Add")).await;+ let page = act(&e, click("Add")).await;+ assert_eq!(page["error"], progress::REPEAT_STOP, "{page}");+ assert!(page["text"].as_str().unwrap().contains("Count 3"), "not clicked: {page}");+ let page = act(&e, click("Add")).await;+ assert_eq!(page["error"], progress::REPEAT_STOP, "still refused");+ act(&e, json!({"action": "key", "key": "Tab"})).await;+ let page = act(&e, click("Add")).await;+ assert_eq!(page["error"], progress::REPEAT_STOP, "a key doesn't count as something else");+ act(&e, click("Nothing")).await;+ let page = act(&e, click("Add")).await;+ assert!(page["error"].is_null() && page["text"].as_str().unwrap().contains("Count 4"), "{page}");++ // Another page+ let page = act(&e, click("Other page")).await;+ assert_eq!(page["changed"], format!("Went to {base}/other (\"other\")."), "{page}");++ // Opening an address starts over+ open(&e, &format!("{base}/counter")).await;+ act(&e, click("Add")).await;+ act(&e, click("Add")).await;+ open(&e, &format!("{base}/counter")).await;+ let page = act(&e, click("Add")).await;+ assert!(page["error"].is_null(), "{page}");+}++/// A real demo shop: logging in says where it went, adding to the cart says what changed.+/// Needs the network.+#[tokio::test]+#[ignore]+async fn saucedemo_says_what_changed() {+ 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;+ act(&e, json!({"action": "click_text", "text": "Username"})).await;+ act(&e, json!({"action": "type", "text": "standard_user"})).await;+ act(&e, json!({"action": "click_text", "text": "Password"})).await;+ act(&e, json!({"action": "type", "text": "secret_sauce"})).await;+ let page = act(&e, click("Login")).await;+ assert_eq!(page["changed"], "Went to https://www.saucedemo.com/inventory.html (\"Swag Labs\").", "{page}");+ let page = act(&e, click("Add to cart")).await;+ let changed = page["changed"].as_str().unwrap();+ assert!(changed.contains("New: \"Remove\"") || changed.contains("\"1\""), "{changed}");+ eprintln!("{changed}");+}