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
0.9.5: VM browser recovers instead of reporting unavailable (#544)
Oleksandr Ivanchenkoc1a0e7fefe50
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex 78db326e..083d297b 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -2,7 +2,7 @@ use futures::{SinkExt, StreamExt};use super::credentials::CredentialStore;use serde::{Deserialize, Serialize};use serde_json::{json, Value};-use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};use std::sync::Arc;use std::time::Duration;use thiserror::Error;@@ -50,10 +50,78 @@ async fn guard_app_links(ws: &mut WsStream, msg_id: &AtomicU64) {}pub(crate) async fn connect_cdp(url: &str) -> Result<WsStream, BrowserError> {- let (ws, _) = connect_async(cdp_ws_request(url)?).await.map_err(|e| BrowserError::Ws(e.to_string()))?;+ // A browser starved of memory can accept the TCP connection and never finish the upgrade:+ // that is a timeout (busy, try again), not a dead browser.+ let (ws, _) = timeout(CDP_CONNECT_TIMEOUT, connect_async(cdp_ws_request(url)?)).await+ .map_err(|_| BrowserError::Timeout)?+ .map_err(|e| BrowserError::Ws(e.to_string()))?;Ok(ws)}+/// One command on `ws` before it is handed out (waking a page), with a short deadline.+async fn raw_call(ws: &mut WsStream, msg_id: &AtomicU64, method: &str, params: Value) -> Result<Value, BrowserError> {+ let id = msg_id.fetch_add(1, Ordering::SeqCst);+ let request = json!({"id": id, "method": method, "params": params});+ ws.send(Message::Text(request.to_string())).await.map_err(|e| BrowserError::Ws(e.to_string()))?;+ timeout(Duration::from_secs(5), await_reply(ws, id)).await.map_err(|_| BrowserError::Timeout)?.and_then(|r| r)+}++/// How long opening a DevTools WebSocket may take.+const CDP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);++/// A DevTools `/json` request that failed: [`BrowserError::Timeout`] when it timed out, so a busy+/// browser is told apart from one that isn't there; otherwise the error with its causes ("error+/// sending request" alone doesn't say the connection was refused).+fn http_error(error: reqwest::Error) -> BrowserError {+ if error.is_timeout() {+ return BrowserError::Timeout;+ }+ let mut text = error.to_string();+ let mut source = std::error::Error::source(&error);+ while let Some(cause) = source {+ text.push_str(": ");+ text.push_str(&cause.to_string());+ source = cause.source();+ }+ BrowserError::Http(text)+}++/// Why the browser couldn't be used, as far as what to do next goes.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Outage {+ /// It is there but didn't answer in time (overloaded, out of memory, mid-restart): retry soon.+ Busy,+ /// Nothing listens at its address, the name doesn't resolve, or Docker isn't running.+ Unreachable,+ /// Anything else (Chrome refused a command, a person holds the page, ...).+ Other,+}++/// Classifies a failed browser call (see [`Outage`]). Only a refused connection, a failed name+/// lookup or a Docker failure is [`Outage::Unreachable`]; a timeout or a dropped connection is+/// [`Outage::Busy`].+pub fn outage(error: &BrowserError) -> Outage {+ const UNREACHABLE: [&str; 9] = [+ "connection refused", "dns error", "failed to lookup address", "name or service not known",+ "no such host", "network is unreachable", "no route to host", "cannot connect to the docker daemon",+ "docker:",+ ];+ match error {+ BrowserError::Timeout => Outage::Busy,+ BrowserError::Http(text) | BrowserError::Ws(text) | BrowserError::Protocol(text) => {+ let text = text.to_ascii_lowercase();+ if UNREACHABLE.iter().any(|u| text.contains(u)) {+ Outage::Unreachable+ } else if matches!(error, BrowserError::Protocol(_)) && !text.contains("connection closed before response") {+ Outage::Other+ } else {+ Outage::Busy+ }+ }+ _ => Outage::Other,+ }+}+/// Reads `ws` until the reply to command `id`. The outer `Err` means the connection broke (closed/// or a socket error); the inner one is Chrome's own error reply on a healthy connection.async fn await_reply(ws: &mut WsStream, id: u64) -> Result<Result<Value, BrowserError>, BrowserError> {@@ -1153,6 +1221,29 @@ pub struct BrowserController {/// [`super::popups::Popups::generation`] when `ws_conn` was opened: a newer one means the/// page in front changed and the next command reconnects to it.ws_generation: Arc<AtomicU64>,+ /// The page may be frozen (see [`Self::freeze`]): the next command wakes it first.+ needs_wake: Arc<AtomicBool>,+ /// How many live views show this page now: a watched page is never frozen.+ watchers: Arc<AtomicUsize>,+}++/// Stops media in a page that is put to rest, so a feed or video doesn't keep decoding. Media it+/// muted is unmuted when the page wakes ([`UNMUTE_SCRIPT`]); nothing resumes playing by itself.+const REST_MEDIA_SCRIPT: &str = r#"(() => { let n = 0;+ for (const m of document.querySelectorAll('video, audio')) {+ if (!m.paused) { m.pause(); n++; }+ if (!m.muted) { m.muted = true; m.dataset.kwntMuted = '1'; }+ }+ return n; })()"#;+const UNMUTE_SCRIPT: &str = r#"(() => { for (const m of document.querySelectorAll('[data-kwnt-muted]')) { m.muted = false; delete m.dataset.kwntMuted; } })()"#;++/// Counts one live view of a page while it lives (see [`BrowserController::watch`]).+pub struct WatchGuard(Arc<AtomicUsize>);++impl Drop for WatchGuard {+ fn drop(&mut self) {+ self.0.fetch_sub(1, Ordering::SeqCst);+ }}/// Widest screenshot a bot gets, in pixels, and the narrowest width it may ask for.@@ -1220,9 +1311,87 @@ impl BrowserController {site_guard: Arc::default(),popups: Arc::default(),ws_generation: Arc::default(),+ needs_wake: Arc::default(),+ watchers: Arc::default(),}}+ /// Puts an idle page to rest: pauses its media, then freezes it (Chrome stops its timers,+ /// animation frames and network tasks; the page keeps its state and still answers DevTools).+ /// The next command through this controller, or any controller of the page made later,+ /// wakes it first (see [`Self::wake_before_use`]).+ pub async fn freeze(&self) -> Result<(), BrowserError> {+ self.send_cdp_command("Runtime.evaluate", json!({"expression": REST_MEDIA_SCRIPT, "returnByValue": true})).await?;+ // marked and frozen under the connection's lock, so no command slips in between and+ // finds the page frozen but unmarked+ let mut guard = self.ws_conn.lock().await;+ self.ensure_connected(&mut guard).await?;+ self.needs_wake.store(true, Ordering::SeqCst);+ let frozen = raw_call(guard.as_mut().unwrap(), &self.msg_id, "Page.setWebLifecycleState", json!({"state": "frozen"})).await;+ if frozen.is_err() { *guard = None; }+ frozen.map(|_| ())+ }++ /// Sends the page to about:blank (a team page idle for hours: its site's memory is freed; the+ /// team's cookies are kept in its jar first).+ pub async fn blank(&self) -> Result<(), BrowserError> {+ self.persist_cookies().await;+ self.send_cdp_command("Page.navigate", json!({"url": "about:blank"})).await?;+ *self.current_url.lock().await = Some("about:blank".into());+ *self.current_title.lock().await = Some(String::new());+ Ok(())+ }++ /// Whether the page may be frozen, so its next command wakes it.+ pub fn needs_wake(&self) -> bool { self.needs_wake.load(Ordering::SeqCst) }++ /// Marks the page as possibly frozen, by an earlier controller or an earlier run of kwant:+ /// its next command wakes it.+ pub fn wake_before_use(&self) { self.needs_wake.store(true, Ordering::SeqCst); }++ /// Wakes the page now if it may be frozen (the live view, which talks to the page on its own+ /// connection, calls this first).+ pub async fn wake(&self) -> Result<(), BrowserError> {+ if self.needs_wake() {+ self.send_cdp_command("Runtime.evaluate", json!({"expression": "1", "returnByValue": true})).await?;+ }+ Ok(())+ }++ /// Counts a live view of this page until the guard drops: a watched page is never frozen.+ pub fn watch(&self) -> WatchGuard {+ self.watchers.fetch_add(1, Ordering::SeqCst);+ WatchGuard(self.watchers.clone())+ }++ /// How many live views show this page now.+ pub fn watchers(&self) -> usize { self.watchers.load(Ordering::SeqCst) }++ /// On `ws`, the page's own connection: makes the page active again and shows its window+ /// once more. Chrome keeps a page that was frozen "hidden" after it is made active (its+ /// screencast sends no frames and `requestAnimationFrame` never runs); minimizing its window+ /// and restoring it makes it visible again (checked on kwnt-browser's Chrome 156).+ async fn wake_page(&self, ws: &mut WsStream) -> Result<(), BrowserError> {+ let id = &self.msg_id;+ // Chrome refusing the method (an error reply, which await_reply gives as the error's+ // JSON) leaves nothing frozen to wake; a page that doesn't answer, or a dead socket, fails+ match raw_call(ws, id, "Page.setWebLifecycleState", json!({"state": "active"})).await {+ Err(BrowserError::Protocol(reply)) if reply.starts_with('{') => {}+ Err(error) => return Err(error),+ Ok(_) => {}+ }+ if let Ok(window) = raw_call(ws, id, "Browser.getWindowForTarget", json!({})).await {+ if let Some(window) = window["windowId"].as_i64() {+ for state in ["minimized", "normal"] {+ let bounds = json!({"windowId": window, "bounds": {"windowState": state}});+ let _ = raw_call(ws, id, "Browser.setWindowBounds", bounds).await;+ }+ }+ }+ let _ = raw_call(ws, id, "Runtime.evaluate", json!({"expression": UNMUTE_SCRIPT})).await;+ Ok(())+ }+/// Sets the fixed viewport of a windowless browser, and remembers it so a sized screenshot/// can put it back.pub async fn set_viewport(&self, width: u32, height: u32) -> Result<(), BrowserError> {@@ -1333,7 +1502,15 @@ impl BrowserController {// 1. Try /json/list to get active Page targetlet list_url = format!("{}/json/list", self.endpoint);if !self.browser_level {- if let Ok(resp) = client.get(&list_url).header(reqwest::header::HOST, "localhost").send().await {+ let listed = client.get(&list_url).header(reqwest::header::HOST, "localhost").send().await;+ // a page's own list request that timed out or was refused is the browser's state, not a+ // sign its page is gone+ if let Err(e) = &listed {+ if self.target_id.is_some() || e.is_timeout() {+ return Err(http_error(listed.err().unwrap()));+ }+ }+ if let Ok(resp) = listed {if let Ok(targets) = resp.json::<Vec<Value>>().await {let pages: Vec<&Value> = targets.iter().filter(|t| t["type"] == "page").collect();let chain = self.popups.chain();@@ -1374,9 +1551,9 @@ impl BrowserController {.header(reqwest::header::HOST, "localhost").send().await- .map_err(|e| BrowserError::Http(e.to_string()))?;+ .map_err(http_error)?;- let json: Value = resp.json().await.map_err(|e| BrowserError::Http(e.to_string()))?;+ let json: Value = resp.json().await.map_err(http_error)?;let advertised = json["webSocketDebuggerUrl"].as_str().ok_or_else(|| BrowserError::Protocol("Missing webSocketDebuggerUrl".into()))?;@@ -1394,8 +1571,8 @@ impl BrowserController {.header(reqwest::header::HOST, "localhost").send().await- .map_err(|e| BrowserError::Http(e.to_string()))?;- resp.json().await.map_err(|e| BrowserError::Http(e.to_string()))+ .map_err(http_error)?;+ resp.json().await.map_err(http_error)}/// Starts following the popups the bot's page opens, unless that is already running.@@ -1506,6 +1683,16 @@ impl BrowserController {) -> Result<Value, BrowserError> {let mut guard = self.ws_conn.lock().await;self.ensure_connected(&mut guard).await?;+ if !self.browser_level && self.needs_wake.load(Ordering::SeqCst) {+ match self.wake_page(guard.as_mut().unwrap()).await {+ Ok(()) => self.needs_wake.store(false, Ordering::SeqCst),+ Err(e) => {+ // stays marked, so the next command tries again on a new connection+ *guard = None;+ return Err(e);+ }+ }+ }let id = self.msg_id.fetch_add(1, Ordering::SeqCst);let request = json!({@@ -2456,3 +2643,38 @@ mod view_claim_tests {assert_eq!(claims.release(2), ViewRelease::Restore);}}++#[cfg(test)]+mod outage_tests {+ use super::{outage, BrowserError, Outage};++ #[test]+ fn a_browser_that_does_not_answer_in_time_is_busy() {+ assert_eq!(outage(&BrowserError::Timeout), Outage::Busy);+ // a socket that broke mid-answer, or a /json request that failed some other way+ assert_eq!(outage(&BrowserError::Ws("Connection reset without closing handshake".into())), Outage::Busy);+ assert_eq!(outage(&BrowserError::Http("error sending request: connection closed before message completed".into())), Outage::Busy);+ // Chrome dropped the page's socket before it answered+ assert_eq!(outage(&BrowserError::Protocol("Connection closed before response".into())), Outage::Busy);+ }++ #[test]+ fn nothing_at_the_address_is_unreachable() {+ for text in [+ "error sending request for url (http://127.0.0.1:9/json/version): client error (Connect): tcp connect error: Connection refused (os error 111)",+ "error sending request: dns error: failed to lookup address information: Name or service not known",+ "IO error: Connection refused (os error 111)",+ ] {+ assert_eq!(outage(&BrowserError::Http(text.into())), Outage::Unreachable, "{text}");+ assert_eq!(outage(&BrowserError::Ws(text.into())), Outage::Unreachable, "{text}");+ }+ assert_eq!(outage(&BrowserError::Protocol("docker: Cannot connect to the Docker daemon".into())), Outage::Unreachable);+ }++ #[test]+ fn everything_else_is_neither() {+ assert_eq!(outage(&BrowserError::Protocol("{\"code\":-32000,\"message\":\"No target with given id\"}".into())), Outage::Other);+ assert_eq!(outage(&BrowserError::HumanControl), Outage::Other);+ assert_eq!(outage(&BrowserError::Navigation("net::ERR_NAME_NOT_RESOLVED".into())), Outage::Other);+ }+}diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex f4c96d5a..6e52fc8b 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -16,7 +16,7 @@ pub mod service;pub mod site_guard;pub mod vault;-pub use browser::{detect_bot_wall, ref_line, refuse_file_path, web_address, BrowserController, ClickTarget, BrowserError, NavigationResult, PendingCapture};+pub use browser::{detect_bot_wall, outage, ref_line, refuse_file_path, web_address, BrowserController, ClickTarget, BrowserError, NavigationResult, Outage, PendingCapture};pub use credentials::{Credential, CredentialMeta, CredentialStore, EncryptedFileStore};pub use manager::{ActiveSandbox, SandboxError, SandboxManager, ShellOutput};diff --git a/src/sandbox/service.rs b/src/sandbox/service.rsindex 51f15244..bf94169f 100644--- a/src/sandbox/service.rs+++ b/src/sandbox/service.rs@@ -1,6 +1,6 @@//! One browser service per installation; isolated CDP contexts per bot/team.//! The private CDP endpoint is used only by the server, never by the web client.-use super::browser::{BrowserController, BrowserError};+use super::browser::{outage, BrowserController, BrowserError, Outage};use super::chrome_download::{self, ChromeSetup};use super::computer::{self, ComputerMode};use serde::{Deserialize, Serialize};@@ -15,6 +15,31 @@ pub const BROWSER_IMAGE: &str = "kwnt-browser:v2";const BROWSER_DOCKERFILE: &str = include_str!("../../docker/browser.Dockerfile");const BROWSER_ENTRYPOINT: &str = include_str!("../../docker/browser-entrypoint.sh");+/// What a bot (and the panel) is told when the VM browser didn't answer in time, even after+/// retrying for about [`crate::server::browser_pages::RETRY_WINDOW`]: it is there but overloaded.+/// It says the problem is temporary and what to do, so a bot retries the step instead of+/// ending its work (0.9.4 follow-through, 0.9.5 no-silent-stops key on it). Calls that fail+/// this way also carry `"code": "BROWSER_BUSY"` and `"retryable": true`.+pub const BROWSER_BUSY: &str = "The browser isn't responding right now (it is overloaded, not gone). \+This is temporary: retry the same step in a minute.";+/// The `code` of a call that failed because the browser is busy (see [`BROWSER_BUSY`]).+pub const BROWSER_BUSY_CODE: &str = "BROWSER_BUSY";+/// What the live view shows while it reconnects to a browser that is busy.+pub const BROWSER_RECONNECTING: &str = "The browser isn't responding. Reconnecting…";+/// How long the status check waits for the browser's answer before calling it busy.+const PING_WAIT: Duration = Duration::from_secs(5);+/// What the live view shows when nothing answers at the browser's address.+pub const BROWSER_UNREACHABLE_VIEW: &str = "Browser service unavailable. Check Docker or KWNT_BROWSER_CDP_URL.";++/// How a page was put to rest by the idle sweep (see `browser_pages::rest_idle`).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Rest {+ /// Media paused and the page frozen; it wakes before its next use.+ Frozen,+ /// A team page idle for hours, sent to about:blank (its cookies stay in the jar).+ Blank,+}+/// Joins a job page's key: `team#bot#chat` (see [`job_page_key`]).pub const PAGE_SEP: char = '#';@@ -62,6 +87,10 @@ pub struct BrowserService {/// least recently used one, the idle sweep the ones past their limit, and the live view/// shows the newest. A page kept from an earlier run counts from when this run first saw it.page_use: std::sync::Mutex<HashMap<String, std::time::Instant>>,+ /// Why the last [`Self::session`] failed, as far as what to do next goes (VM mode).+ last_outage: std::sync::Mutex<Option<Outage>>,+ /// Pages the idle sweep put to rest, until they are used again (see [`Self::touch_page`]).+ rested: std::sync::Mutex<HashMap<String, Rest>>,}struct ServiceState {@@ -79,6 +108,8 @@ impl BrowserService {last_error: std::sync::Mutex::new(None), last_use: std::sync::Mutex::new(None),chrome_setup: std::sync::Arc::new(ChromeSetup::system()),page_use: Default::default(),+ last_outage: Default::default(),+ rested: Default::default(),}}@@ -236,9 +267,10 @@ impl BrowserService {let out = timeout(Duration::from_secs(seconds), Command::new("docker").args(args).kill_on_drop(true).output()).await.map_err(|_| BrowserError::Timeout)?- .map_err(|e| BrowserError::Http(e.to_string()))?;+ .map_err(|e| BrowserError::Http(format!("docker: {e}")))?;+ // "docker:" marks it as Docker's failure, not the browser's (see [`outage`])if !out.status.success() {- return Err(BrowserError::Protocol(String::from_utf8_lossy(&out.stderr).trim().to_string()));+ return Err(BrowserError::Protocol(format!("docker: {}", String::from_utf8_lossy(&out.stderr).trim())));}Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())}@@ -389,8 +421,13 @@ impl BrowserService {/// What to tell the person when the browser could not be reached. In local mode that is the/// reason kwant's Chrome did not start, not Docker, which local mode does not use.+ /// In VM mode a browser that is there but didn't answer gets [`BROWSER_BUSY`]; the Docker+ /// advice is kept for one that can't be reached at all.pub fn unavailable_reason(&self) -> String {if self.mode() != ComputerMode::Local {+ if self.last_outage() == Some(Outage::Busy) {+ return BROWSER_BUSY.into();+ }return "Sandbox browser is unavailable. Check that Docker is running, then restart the browser.".into();}let last = self.last_error.lock().unwrap_or_else(|e| e.into_inner()).clone();@@ -423,9 +460,87 @@ impl BrowserService {BrowserError::Http(reason) => reason.clone(),other => other.to_string(),});+ *self.last_outage.lock().unwrap_or_else(|e| e.into_inner()) = result.as_ref().err().map(outage);result}+ /// How the last attempt to open a page failed, if it did (see [`Outage`]).+ pub fn last_outage(&self) -> Option<Outage> {+ *self.last_outage.lock().unwrap_or_else(|e| e.into_inner())+ }++ /// Whether the browser answers, without opening a page: connects first if needed (in VM mode+ /// that starts its container, as before). The panel's status uses it.+ /// A browser that takes longer than [`PING_WAIT`] is reported busy, so a status poll never+ /// waits out a whole command timeout.+ pub async fn ping(&self) -> Result<(), BrowserError> {+ // starting the container (Docker mode) isn't cut short; only the browser's answer is+ self.ensure_private_browser().await?;+ let result = match timeout(PING_WAIT, async {+ let mut lock = self.state.lock().await;+ if lock.is_none() { *lock = Some(self.connect().await?); }+ let result = lock.as_ref().unwrap().browser.send_cdp_command("Browser.getVersion", json!({})).await;+ if result.is_err() { *lock = None; }+ result.map(|_| ())+ }).await {+ Ok(result) => result,+ Err(_) => Err(BrowserError::Timeout),+ };+ if let Err(error) = &result {+ *self.last_outage.lock().unwrap_or_else(|e| e.into_inner()) = Some(outage(error));+ }+ result+ }++ /// Whether this page (team or job page) is open, or kept from an earlier run, as far as+ /// this kwant knows. Opens nothing.+ pub async fn has_page(&self, key: &str) -> bool {+ if let Some(state) = self.state.lock().await.as_ref() {+ return state.sessions.contains_key(key);+ }+ tokio::fs::read(self.sessions_file()).await.ok()+ .and_then(|bytes| serde_json::from_slice::<HashMap<String, SessionTarget>>(&bytes).ok())+ .is_some_and(|sessions| sessions.contains_key(key))+ }++ /// VM mode: a controller for a page that is already open, never creating one (the idle sweep+ /// rests pages no bot has a controller for this run). `None` when it isn't open, the browser+ /// isn't connected, or in local mode.+ pub async fn existing_page(&self, key: &str) -> Option<BrowserController> {+ if self.mode() == ComputerMode::Local { return None; }+ let lock = self.state.lock().await;+ let state = lock.as_ref()?;+ let session = state.sessions.get(key)?;+ let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target.clone()), false);+ ctrl.set_cookie_jar(Some(self.cookie_jar(page_team(key))));+ ctrl.wake_before_use();+ Some(ctrl)+ }++ /// Every open page (team and job pages) with when it was last used. A page kept from an+ /// earlier run that this run hasn't used counts from when it was first seen here.+ pub async fn open_pages(&self) -> Vec<(String, std::time::Instant)> {+ let keys: Vec<String> = match self.state.lock().await.as_ref() {+ Some(state) => state.sessions.keys().cloned().collect(),+ None => return Vec::new(),+ };+ let now = std::time::Instant::now();+ let mut use_ = self.page_use.lock().unwrap_or_else(|e| e.into_inner());+ let mut pages: Vec<_> = keys.into_iter().map(|k| { let at = *use_.entry(k.clone()).or_insert(now); (k, at) }).collect();+ pages.sort_by_key(|(_, at)| *at);+ pages+ }++ /// Records that the idle sweep put a page to rest.+ pub fn mark_rested(&self, key: &str, rest: Rest) {+ self.rested.lock().unwrap_or_else(|e| e.into_inner()).insert(key.to_string(), rest);+ }++ /// How the page was put to rest, if it was and hasn't been used since.+ pub fn rest_of(&self, key: &str) -> Option<Rest> {+ self.rested.lock().unwrap_or_else(|e| e.into_inner()).get(key).copied()+ }+async fn open_session(&self, id: &str, _workspace: &Path) -> Result<BrowserController, BrowserError> {let mut lock = self.state.lock().await;if lock.is_none() { *lock = Some(self.connect().await?); }@@ -493,6 +608,9 @@ impl BrowserService {if restored > 0 { tracing::debug!("Restored {} browser cookies for {}", restored, id); }}}+ // The page may have been frozen by the idle sweep through another controller, or by an+ // earlier run of kwant: wake it before anything else is sent (a no-op for an awake page)+ if !local { ctrl.wake_before_use(); }// A real window keeps its own size; a windowless browser gets the viewer's fixed viewport.if !local || !self.local_window() {ctrl.set_viewport(1280, 800).await?;@@ -526,6 +644,8 @@ impl BrowserService {/// Records that a page was used now (see `page_use`).pub fn touch_page(&self, key: &str) {self.page_use.lock().unwrap_or_else(|e| e.into_inner()).insert(key.to_string(), std::time::Instant::now());+ // its controller wakes it before the first command+ self.rested.lock().unwrap_or_else(|e| e.into_inner()).remove(key);}/// Forgets a job page's use when it couldn't open (no room, or the browser failed), so it@@ -570,6 +690,7 @@ impl BrowserService {pub async fn close_page(&self, key: &str) -> Result<(), BrowserError> {if !is_job_page(key) { return Ok(()); }self.page_use.lock().unwrap_or_else(|e| e.into_inner()).remove(key);+ self.rested.lock().unwrap_or_else(|e| e.into_inner()).remove(key);let mut lock = self.state.lock().await;if let Some(state) = lock.as_mut() {if let Some(session) = state.sessions.remove(key) {@@ -593,6 +714,7 @@ impl BrowserService {let _ = std::fs::remove_file(self.cookie_jar(id));let prefix = format!("{id}{PAGE_SEP}");self.page_use.lock().unwrap_or_else(|e| e.into_inner()).retain(|k, _| !k.starts_with(&prefix));+ self.rested.lock().unwrap_or_else(|e| e.into_inner()).retain(|k, _| k != id && !k.starts_with(&prefix));let mut lock = self.state.lock().await;if lock.is_none() && self.sessions_file().exists() {*lock = Some(self.connect().await?);@@ -762,3 +884,22 @@ mod image_tests {);}}++#[cfg(test)]+mod outage_reason_tests {+ use super::{BrowserService, ComputerMode, Outage, BROWSER_BUSY};++ #[test]+ fn a_busy_browser_says_retry_and_never_blames_docker() {+ let tmp = tempfile::tempdir().unwrap();+ let service = BrowserService::new(tmp.path().into(), Some("http://127.0.0.1:9".into()));+ // The VM browser, whatever this computer's default is (Windows defaults to local Chrome).+ *service.mode.write().unwrap() = ComputerMode::Vm;+ assert!(service.unavailable_reason().contains("Docker"), "no answer yet: the old text");+ *service.last_outage.lock().unwrap() = Some(Outage::Busy);+ assert_eq!(service.unavailable_reason(), BROWSER_BUSY);+ assert!(!BROWSER_BUSY.contains("Docker"));+ *service.last_outage.lock().unwrap() = Some(Outage::Unreachable);+ assert!(service.unavailable_reason().contains("Docker"));+ }+}diff --git a/src/server/browser_pages.rs b/src/server/browser_pages.rsindex 7f6c2e42..b1b42644 100644--- a/src/server/browser_pages.rs+++ b/src/server/browser_pages.rs@@ -11,9 +11,19 @@//! a turn running is never closed. Room is made and a page opened under one lock per team//! ([`JobPages::team_lock`]), so jobs opening at once never pass the cap. A bot tool that finds//! no room waits up to [`PAGE_WAIT`] for a page to free up, then gets [`pages_full_message`].+//!+//! Resting and recovery (0.9.5). In VM mode a page no bot has used and nobody has watched for+//! [`IDLE_FREEZE`] is put to rest: its media paused and the page frozen, so a feed left+//! autoplaying doesn't burn the browser's CPU and memory; a team page idle for [`IDLE_BLANK`] is+//! sent to about:blank (its cookies stay in the jar). A rested page wakes before its next+//! action, screenshot or live view. When the browser stops answering, a bot's call retries with+//! backoff for up to [`RETRY_WINDOW`], first freeing memory by closing or blanking other idle+//! pages ([`relieve`]), never the page the bot is using; if it still can't, the bot is told the+//! problem is temporary ([`crate::sandbox::service::BROWSER_BUSY`]).use super::continuity::SelfScope;use super::AppState;+use crate::sandbox::service::Rest;use axum::{extract::{Path, State}, Json};use serde_json::{json, Value};use std::{@@ -36,6 +46,32 @@ pub const SWEEP_EVERY: Duration = Duration::from_secs(60);/// How long a bot's browser call waits for one of its team's pages to free up before it is/// told every page is in use.pub const PAGE_WAIT: Duration = Duration::from_secs(60);+/// VM mode: a page no bot used and nobody watched for this long is frozen (media paused).+pub const IDLE_FREEZE: Duration = Duration::from_secs(10 * 60);+/// VM mode: a team page idle this long is sent to about:blank.+pub const IDLE_BLANK: Duration = Duration::from_secs(2 * 60 * 60);+/// How long a bot's browser call keeps retrying a browser that doesn't answer (VM mode).+pub const RETRY_WINDOW: Duration = Duration::from_secs(45);+/// The first wait between retries; each next one doubles, up to [`RETRY_MAX_DELAY`].+pub const RETRY_FIRST_DELAY: Duration = Duration::from_secs(1);+pub const RETRY_MAX_DELAY: Duration = Duration::from_secs(8);+/// Freeing memory for a stalled browser leaves alone a page used this recently.+const RELIEF_IDLE: Duration = Duration::from_secs(60);+/// Longest one rest or relief step on one page may take (the browser may be stalled).+const REST_STEP: Duration = Duration::from_secs(5);+/// Longest all of one [`relieve`] may take.+const RELIEF_BUDGET: Duration = Duration::from_secs(15);++/// The wait before retry number `attempt` (0-based): 1, 2, 4, 8, 8, ... seconds.+pub fn retry_delay(attempt: u32) -> Duration {+ RETRY_FIRST_DELAY.saturating_mul(1u32 << attempt.min(16)).min(RETRY_MAX_DELAY)+}++/// Whether to try once more after waiting `delay`, `elapsed` into a retry `window`: only while+/// the next attempt still starts inside it.+pub fn keep_retrying(elapsed: Duration, delay: Duration, window: Duration) -> bool {+ elapsed + delay < window+}/// What a job is told when every job page of its team is in use and none freed up in time.pub fn pages_full_message() -> String {@@ -52,6 +88,8 @@ pub struct JobPages {opening: std::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,/// Tests only: the wait for room in ms (0 = [`PAGE_WAIT`]).wait_ms: AtomicU64,+ /// Tests only: the retry window in ms (0 = [`RETRY_WINDOW`]).+ retry_ms: AtomicU64,}impl JobPages {@@ -71,6 +109,18 @@ impl JobPages {ms => Duration::from_millis(ms),}}++ /// Tests: a shorter retry window than [`RETRY_WINDOW`].+ pub fn set_retry_window(&self, window: Duration) {+ self.retry_ms.store((window.as_millis() as u64).max(1), Ordering::Relaxed);+ }++ pub fn retry_window(&self) -> Duration {+ match self.retry_ms.load(Ordering::Relaxed) {+ 0 => RETRY_WINDOW,+ ms => Duration::from_millis(ms),+ }+ }}/// A job page's team, bot and chat; `None` for the team page.@@ -121,6 +171,116 @@ async fn closable(state: &AppState, key: &str) -> bool {}}+/// Whether a page may be put to rest now: [`closable`], and no live view shows it.+async fn restable(state: &AppState, key: &str) -> bool {+ let watched = state.browser_controllers.lock().await.get(key).is_some_and(|c| c.watchers() > 0);+ !watched && closable(state, key).await+}++/// Puts one page to rest (see [`Rest`]) through its controller, or one made for the open page+/// when no bot has used it this run. Bounded by [`REST_STEP`]. Whether it was.+async fn rest_page(state: &AppState, key: &str, rest: Rest) -> bool {+ let ctrl = state.browser_controllers.lock().await.get(key).cloned();+ let ctrl = match ctrl {+ Some(ctrl) => ctrl,+ None => match state.browser_service.existing_page(key).await {+ Some(ctrl) => ctrl,+ None => return false,+ },+ };+ let done = match rest {+ Rest::Frozen => tokio::time::timeout(REST_STEP, ctrl.freeze()).await,+ Rest::Blank => tokio::time::timeout(REST_STEP, ctrl.blank()).await,+ };+ match done {+ Ok(Ok(())) => {+ state.browser_service.mark_rested(key, rest);+ true+ }+ Ok(Err(e)) => {+ tracing::debug!(page = %key, "couldn't put an idle page to rest: {e}");+ false+ }+ Err(_) => {+ tracing::debug!(page = %key, "putting an idle page to rest timed out");+ false+ }+ }+}++/// What the idle sweep does with a page idle for `idle` that was last put to rest as `rested`:+/// nothing before `freeze_after`; a team page past `blank_after` is blanked; any other is+/// frozen. `None` when it already is.+pub fn rest_for(job: bool, idle: Duration, rested: Option<Rest>, freeze_after: Duration, blank_after: Duration) -> Option<Rest> {+ if idle < freeze_after || rested == Some(Rest::Blank) {+ return None;+ }+ let want = if !job && idle >= blank_after { Rest::Blank } else { Rest::Frozen };+ (rested != Some(want)).then_some(want)+}++/// VM mode: puts to rest the pages idle past `freeze_after` (see [`rest_for`]) that no step+/// holds, no turn of their job is running in, and nobody is using or watching. Returns how many+/// were (frozen, blanked).+pub async fn rest_idle(state: &AppState, freeze_after: Duration, blank_after: Duration) -> (usize, usize) {+ if state.browser_service.mode() == crate::sandbox::computer::ComputerMode::Local {+ return (0, 0);+ }+ let now = Instant::now();+ let (mut frozen, mut blanked) = (0, 0);+ for (key, at) in state.browser_service.open_pages().await {+ let rested = state.browser_service.rest_of(&key);+ let Some(rest) = rest_for(is_job_page(&key), now.duration_since(at), rested, freeze_after, blank_after) else { continue };+ if !restable(state, &key).await || !rest_page(state, &key, rest).await {+ continue;+ }+ tracing::info!(page = %key, ?rest, "browser: put an idle page to rest");+ match rest {+ Rest::Frozen => frozen += 1,+ Rest::Blank => blanked += 1,+ }+ }+ (frozen, blanked)+}++/// The browser stopped answering a call for `keep`: frees memory by closing other idle job pages+/// and blanking other idle team pages, least recently used first, never `keep` nor a page used+/// in the last minute, watched, held or in use. Each step is bounded (the browser may be+/// stalled), and all of it by [`RELIEF_BUDGET`]. Returns how many pages were closed or blanked.+pub async fn relieve(state: &AppState, keep: &str) -> usize {+ if state.browser_service.mode() == crate::sandbox::computer::ComputerMode::Local {+ return 0;+ }+ let mut relieved = 0;+ let work = async {+ let now = Instant::now();+ let pages = match tokio::time::timeout(REST_STEP, state.browser_service.open_pages()).await {+ Ok(pages) => pages,+ Err(_) => return,+ };+ for (key, at) in pages {+ if key == keep || now.duration_since(at) < RELIEF_IDLE || !restable(state, &key).await {+ continue;+ }+ if is_job_page(&key) {+ // a page being opened or closed for its team is left to that+ let lock = state.job_pages.team_lock(page_team(&key));+ let Ok(_opening) = lock.try_lock() else { continue };+ if tokio::time::timeout(REST_STEP, close_page(state, &key)).await.is_ok() {+ relieved += 1;+ }+ } else if state.browser_service.rest_of(&key) != Some(Rest::Blank) && rest_page(state, &key, Rest::Blank).await {+ relieved += 1;+ }+ }+ };+ let _ = tokio::time::timeout(RELIEF_BUDGET, work).await;+ if relieved > 0 {+ tracing::warn!(page = %keep, "browser: not answering; closed or blanked {relieved} other idle pages to free memory");+ }+ relieved+}+/// Closes a job page: its controller first (cookies kept), then the page.pub async fn close_page(state: &AppState, key: &str) {let ctrl = state.browser_controllers.lock().await.remove(key);@@ -179,7 +339,7 @@ pub async fn sweep_idle(state: &AppState, idle: Duration) -> usize {closed}-/// Runs [`sweep_idle`] every [`SWEEP_EVERY`] until `cancel`.+/// Runs [`sweep_idle`] and [`rest_idle`] every [`SWEEP_EVERY`] until `cancel`.pub fn spawn_sweeper(state: AppState, cancel: tokio_util::sync::CancellationToken) {tokio::spawn(async move {loop {@@ -191,6 +351,10 @@ pub fn spawn_sweeper(state: AppState, cancel: tokio_util::sync::CancellationTokeif closed > 0 {tracing::info!("browser: closed {closed} idle job pages");}+ let (frozen, blanked) = rest_idle(&state, IDLE_FREEZE, IDLE_BLANK).await;+ if frozen + blanked > 0 {+ tracing::info!("browser: froze {frozen} and blanked {blanked} idle pages");+ }}});}@@ -282,6 +446,44 @@ mod tests {assert!(!Arc::ptr_eq(&pages.team_lock("t"), &pages.team_lock("u")), "one lock per team");}+ #[test]+ fn retries_back_off_from_one_second_to_eight_inside_the_window() {+ let delays: Vec<u64> = (0..6).map(|n| retry_delay(n).as_secs()).collect();+ assert_eq!(delays, [1, 2, 4, 8, 8, 8]);+ assert_eq!(retry_delay(40), RETRY_MAX_DELAY, "no overflow on a long outage");+ let s = Duration::from_secs;+ assert!(keep_retrying(s(0), s(1), RETRY_WINDOW));+ assert!(keep_retrying(s(36), s(8), RETRY_WINDOW));+ assert!(!keep_retrying(s(37), s(8), RETRY_WINDOW), "the next try would start after the window");+ assert!(!keep_retrying(s(45), s(1), RETRY_WINDOW));+ // the waits alone fill the window in 1+2+4+8+8+8+8 = 39 s: about 7 tries when each fails fast+ let mut elapsed = Duration::ZERO;+ let mut tries = 1;+ while keep_retrying(elapsed, retry_delay(tries - 1), RETRY_WINDOW) {+ elapsed += retry_delay(tries - 1);+ tries += 1;+ }+ assert_eq!((tries, elapsed.as_secs()), (8, 39));+ let pages = JobPages::default();+ assert_eq!(pages.retry_window(), RETRY_WINDOW);+ pages.set_retry_window(Duration::from_millis(5));+ assert_eq!(pages.retry_window(), Duration::from_millis(5));+ }++ #[test]+ fn idle_pages_are_frozen_after_ten_minutes_and_team_pages_blanked_after_hours() {+ let m = |n: u64| Duration::from_secs(n * 60);+ let rest = |job, idle, rested| rest_for(job, idle, rested, IDLE_FREEZE, IDLE_BLANK);+ assert_eq!(rest(false, m(9), None), None, "used within ten minutes");+ assert_eq!(rest(false, m(10), None), Some(Rest::Frozen));+ assert_eq!(rest(true, m(10), None), Some(Rest::Frozen));+ assert_eq!(rest(false, m(30), Some(Rest::Frozen)), None, "already frozen");+ assert_eq!(rest(false, m(120), Some(Rest::Frozen)), Some(Rest::Blank));+ assert_eq!(rest(false, m(120), None), Some(Rest::Blank));+ assert_eq!(rest(false, m(600), Some(Rest::Blank)), None, "already blank");+ assert_eq!(rest(true, m(600), None), Some(Rest::Frozen), "a job page is never blanked (it is closed)");+ }+#[test]fn a_turn_in_a_chat_uses_its_own_page_and_one_without_the_team_page() {let origin = super::super::continuity::TurnOrigin { thread_id: Some("th".into()), ..Default::default() };diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rsindex 38b7128d..41c94fd2 100644--- a/src/server/browser_stream.rs+++ b/src/server/browser_stream.rs@@ -7,7 +7,7 @@//! wait behind a bot's command.use super::browser_input::{self as bi, KeyEvent, KeyKind, MouseButton, RateLimit};use super::point;-use super::{routes::get_or_create_browser_controller, AppState};+use super::{routes::PageRefusal, AppState};use super::show_once::{capture as recorder, stage::{Act, StageRecorder}};use crate::sandbox::app_links::{self, AppLinkWatch, Verdict};use crate::sandbox::browser::{web_address, BrowserController, BrowserError, HeldPointer, PersonLease, ViewClaim, ViewRelease, FOCUSED_EDITABLE_JS, MOUSE_BUTTON_BITS};@@ -1216,8 +1216,10 @@ pub async fn upgrade(None => super::browser_pages::live_page(&state, &id).await,};Ok(ws.max_message_size(32 * 1024).on_upgrade(move |socket| async move {- let result = serve(socket, state, id).await;+ let result = serve(socket, state.clone(), id.clone()).await;if let Err(error) = result { tracing::debug!("Browser stream ended: {}", error); }+ // the page's idle time counts from when the person stopped watching it+ if state.browser_service.page_used_at(&id).is_some() { state.browser_service.touch_page(&id); }}))}@@ -1278,13 +1280,24 @@ async fn back_from_closed_page(ctrl: &BrowserController, cdp: &Cdp, page: &mut P}async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(), BrowserError> {- let ctrl = match get_or_create_browser_controller(&state, &id).await {- Some(ctrl) => ctrl,- None => {- let _ = socket.send(Message::Text(json!({"type":"error","error":"Browser service unavailable. Check Docker or KWNT_BROWSER_CDP_URL."}).to_string())).await;+ let ctrl = match super::routes::open_page(&state, &id, Duration::ZERO).await {+ Ok(ctrl) => ctrl,+ Err(refusal) => {+ // The view closes after this, and the app reconnects with backoff: a busy browser+ // says so and is tried again; the Docker advice is only for one that isn't there+ let error = match refusal {+ PageRefusal::Busy => crate::sandbox::service::BROWSER_RECONNECTING.to_string(),+ PageRefusal::PagesFull => super::browser_pages::pages_full_message(),+ PageRefusal::Unavailable => crate::sandbox::service::BROWSER_UNREACHABLE_VIEW.to_string(),+ };+ let _ = socket.send(Message::Text(json!({"type":"error","error":error}).to_string())).await;return Ok(());}};+ // a watched page is never put to rest; one put to rest before is woken for the view, which+ // talks to it on a connection of its own+ let _watching = ctrl.watch();+ let _woken = ctrl.wake().await;// subscribed first, so a popup opening while this connects is still followedlet changes = ctrl.page_changes();let ws_url = ctrl.get_ws_url().await?;diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 02033453..643f3df4 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -758,7 +758,7 @@ pub(crate) async fn browser_screenshot_tool(state: &AppState, scope: &SelfScope,Value::Bool(b) => *b,_ => return (text("share must be true or false"), true),};- let ctrl = match super::routes::open_page(state, target, state.job_pages.wait()).await {+ let ctrl = match super::routes::open_page_steady(state, target, state.job_pages.wait()).await {Ok(ctrl) => ctrl,Err(refusal) => return (text(&page_refusal_text(state, refusal)), true),};@@ -833,9 +833,13 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, na// This bot drives the browser now, so its site rules are the ones that hold. Its job page// opens here (waiting for room when its team's pages are all in use), so the tool below// finds it open- match super::routes::open_page(state, target, state.job_pages.wait()).await {+ // A browser that doesn't answer is retried here for up to a minute (VM mode), so the tool+ // below doesn't wait all over again+ match super::routes::open_page_steady(state, target, state.job_pages.wait()).await {Ok(ctrl) => ctrl.site_guard.set_driver(&scope.kwant_id),- Err(refusal @ super::routes::PageRefusal::PagesFull) => return (page_refusal_text(state, refusal), true),+ Err(refusal @ (super::routes::PageRefusal::PagesFull | super::routes::PageRefusal::Busy)) => {+ return (page_refusal_text(state, refusal), true)+ }Err(super::routes::PageRefusal::Unavailable) => {}}let (text, is_error) = run_browser_tool(state, target, &reader, name, args).await;@@ -877,6 +881,7 @@ fn page_refusal_text(state: &AppState, refusal: super::routes::PageRefusal) -> Smatch refusal {super::routes::PageRefusal::PagesFull => super::browser_pages::pages_full_message(),super::routes::PageRefusal::Unavailable => state.browser_service.unavailable_reason(),+ super::routes::PageRefusal::Busy => crate::sandbox::service::BROWSER_BUSY.to_string(),}}diff --git a/src/server/routes.rs b/src/server/routes.rsindex 7044959b..938104a3 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -5582,6 +5582,8 @@ pub enum PageRefusal {Unavailable,/// Every job page of the team is held or in use, and none freed up in time.PagesFull,+ /// VM mode: the browser is there but didn't answer in time (overloaded). Temporary.+ Busy,}/// The page's controller for a bot's browser call: like [`get_or_create_browser_controller`],@@ -5592,13 +5594,50 @@ pub async fn page_controller(state: &AppState,key: &str,) -> Result<crate::sandbox::BrowserController, (StatusCode, Json<serde_json::Value>)> {- open_page(state, key, state.job_pages.wait()).await.map_err(|refusal| page_refused(state, refusal))+ open_page_steady(state, key, state.job_pages.wait()).await.map_err(|refusal| page_refused(state, refusal))+}++/// [`open_page`] for a bot's call: in VM mode a browser that doesn't answer in time+/// ([`PageRefusal::Busy`]) is tried again with backoff ([`super::browser_pages::retry_delay`])+/// for up to [`super::browser_pages::RETRY_WINDOW`], after freeing memory once by closing or+/// blanking other idle pages ([`super::browser_pages::relieve`]). A browser that can't be+/// reached at all fails at once.+pub async fn open_page_steady(+ state: &AppState,+ key: &str,+ wait: std::time::Duration,+) -> Result<crate::sandbox::BrowserController, PageRefusal> {+ let started = std::time::Instant::now();+ let window = state.job_pages.retry_window();+ let mut attempt = 0;+ loop {+ let refusal = match open_page(state, key, wait).await {+ Ok(ctrl) => {+ if attempt > 0 {+ tracing::info!(page = %key, attempt, "the browser answered again");+ }+ return Ok(ctrl);+ }+ Err(refusal) => refusal,+ };+ let delay = super::browser_pages::retry_delay(attempt);+ if refusal != PageRefusal::Busy || !super::browser_pages::keep_retrying(started.elapsed(), delay, window) {+ return Err(refusal);+ }+ if attempt == 0 {+ super::browser_pages::relieve(state, key).await;+ }+ tracing::warn!(page = %key, attempt, "the browser isn't answering; trying again in {}s", delay.as_secs());+ tokio::time::sleep(delay).await;+ attempt += 1;+ }}/// The answer to a call whose page couldn't be had.pub(crate) fn page_refused(state: &AppState, refusal: PageRefusal) -> (StatusCode, Json<serde_json::Value>) {match refusal {PageRefusal::Unavailable => browser_unavailable(state),+ PageRefusal::Busy => browser_busy(),PageRefusal::PagesFull => (StatusCode::SERVICE_UNAVAILABLE, Json(json!({"error": super::browser_pages::pages_full_message(),"code": PAGES_FULL,@@ -5625,7 +5664,7 @@ pub async fn open_page(let team = super::browser_pages::page_team(key).to_string();if !super::browser_pages::is_job_page(key) {state.browser_service.touch_page(key);- return controller_for(state, key, &team).await.ok_or(PageRefusal::Unavailable);+ return controller_for(state, key, &team).await.map_err(refusal_for);}// An open job page that answers needs no lock; any page is only ever opened under itlet existing = state.browser_controllers.lock().await.get(key).cloned();@@ -5644,7 +5683,7 @@ pub async fn open_page(state.browser_service.touch_page(key);let ctrl = controller_for(state, key, &team).await;drop(opening);- return ctrl.ok_or(PageRefusal::Unavailable);+ return ctrl.map_err(refusal_for);}drop(opening);let now = std::time::Instant::now();@@ -5656,21 +5695,39 @@ pub async fn open_page(}}+/// Why a page's controller couldn't be had: [`PageRefusal::Busy`] for a VM browser that is+/// there but didn't answer in time, else [`PageRefusal::Unavailable`].+fn refusal_for(error: crate::sandbox::BrowserError) -> PageRefusal {+ match crate::sandbox::outage(&error) {+ crate::sandbox::Outage::Busy => PageRefusal::Busy,+ _ => PageRefusal::Unavailable,+ }+}+/// The page's controller, opening the page when it isn't open (or no longer answers).-async fn controller_for(state: &AppState, team_id: &str, team: &str) -> Option<crate::sandbox::BrowserController> {+async fn controller_for(+ state: &AppState,+ team_id: &str,+ team: &str,+) -> Result<crate::sandbox::BrowserController, crate::sandbox::BrowserError> {let team = team.to_string();let job = super::browser_pages::is_job_page(team_id);let mut controllers = state.browser_controllers.lock().await;let mut driver = None;if let Some(ctrl) = controllers.get(team_id) {- if !ctrl.is_managed_session() || ctrl.refresh_location().await.is_ok() { return Some(ctrl.clone()); }- if ctrl.control.try_write().is_err() { return None; }+ let checked = if ctrl.is_managed_session() { ctrl.refresh_location().await } else { Ok(()) };+ let error = match checked {+ Ok(()) => return Ok(ctrl.clone()),+ Err(error) => error,+ };+ // a bot is mid-step on it: the page is in use, not gone+ if ctrl.control.try_write().is_err() { return Err(error); }driver = ctrl.site_guard.driver();controllers.remove(team_id);}let Some((_, workspace)) = resolve_sandbox_target_info(state, &team).await else {state.browser_service.forget_page(team_id);- return None;+ return Err(crate::sandbox::BrowserError::Protocol(format!("no sandbox target {team}")));};let opened = if job {state.browser_service.page_session(team_id, &workspace).await@@ -5691,13 +5748,13 @@ async fn controller_for(state: &AppState, team_id: &str, team: &str) -> Option<clet _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {team_id: team, container_name: "browser-service".into(), is_running: true,});- Some(ctrl)+ Ok(ctrl)}Err(error) => {tracing::warn!("Browser service unavailable: {}", error);// a job page that didn't open isn't one of the team's pagesif job { state.browser_service.forget_page(team_id); }- None+ Err(error)}}}@@ -5732,13 +5789,40 @@ pub(crate) async fn guard_bot_action(ctrl.apply_site_rules(rules).await}+/// `GET /api/sandbox/:team_id/status`: whether the browser answers, read without opening,+/// using or waking a page (0.9.5: it used to open one for any key it was given, and the+/// panel's reads kept idle pages in use). `page_open` says whether this key's page is open.pub async fn get_sandbox_status(State(state): State<AppState>, Path(team_id): Path<String>,) -> Result<Json<serde_json::Value>, StatusCode> {- let running = get_or_create_browser_controller(&state, &team_id).await.is_some();+ let team = super::browser_pages::page_team(&team_id).to_string();+ // a key that names no sandbox target never reaches the browser+ let known = resolve_sandbox_target_info(&state, &team).await.is_some();+ let health = if known { Some(state.browser_service.ping().await) } else { None };+ let running = matches!(health, Some(Ok(())));+ let busy = matches!(&health, Some(Err(e)) if crate::sandbox::outage(e) == crate::sandbox::Outage::Busy);+ let page_open = known && state.browser_service.has_page(&team_id).await;let execution = state.sandbox_manager.get_sandbox(&team_id).await;- Ok(Json(json!({"team_id":team_id,"is_running":running,"container_name":"browser-service",- "execution_running":execution.is_some_and(|s| s.is_running)})))+ // a busy browser is still there (overloaded, not gone): running, but not answering+ let mut body = json!({"team_id":team_id,"is_running":running || busy,"responding":running,+ "container_name":"browser-service","page_open":page_open,+ "execution_running":execution.is_some_and(|s| s.is_running)});+ if busy {+ body["error"] = json!(crate::sandbox::service::BROWSER_BUSY);+ body["code"] = json!(crate::sandbox::service::BROWSER_BUSY_CODE);+ body["retryable"] = json!(true);+ }+ Ok(Json(body))+}++/// A call refused because the VM browser didn't answer in time: temporary, retry the step.+fn browser_busy() -> (StatusCode, Json<serde_json::Value>) {+ (StatusCode::SERVICE_UNAVAILABLE, Json(json!({+ "error": crate::sandbox::service::BROWSER_BUSY,+ "code": crate::sandbox::service::BROWSER_BUSY_CODE,+ "retryable": true,+ "is_running": true,+ })))}fn browser_unavailable(state: &AppState) -> (StatusCode, Json<serde_json::Value>) {@@ -5760,6 +5844,9 @@ fn browser_request_failed(error: crate::sandbox::BrowserError) -> (StatusCode, J})));}tracing::warn!("Sandbox browser request failed: {}", error);+ if crate::sandbox::outage(&error) == crate::sandbox::Outage::Busy {+ return browser_busy();+ }(StatusCode::BAD_GATEWAY, Json(json!({"error": "The sandbox browser did not respond. Restart the browser and try again."})))diff --git a/tests/browser_recovery_test.rs b/tests/browser_recovery_test.rsnew file mode 100644index 00000000..57fe44c2--- /dev/null+++ b/tests/browser_recovery_test.rs@@ -0,0 +1,305 @@+//! 0.9.5 browser recovery: a VM browser that stops answering for a while (overloaded, out of+//! memory) is waited for, not given up on; a browser that isn't there is reported at once; and+//! the panel's status never opens a page.+use axum::{extract::{Path, State, WebSocketUpgrade, ws::Message}, routing::get, Json, Router};+use futures::StreamExt;+use kwnt::{broker::PermissionBroker, config::Config, db::Database, router::LayaRouter, server::{create_router, AppState}, tools::ToolRunner};+use kwnt::sandbox::service::{BROWSER_BUSY, BROWSER_BUSY_CODE};+use serde_json::{json, Value};+use std::{sync::{atomic::{AtomicUsize, Ordering}, Arc}, time::{Duration, Instant}};+use tokio::{net::TcpListener, sync::Mutex};++/// A DevTools endpoint that can stop answering for a while, the way an overloaded Chrome does:+/// its `/json` requests hang and its sockets take commands without replying.+#[derive(Clone, Default)]+struct Mock {+ port: u16,+ targets: Arc<Mutex<Vec<Value>>>,+ commands: Arc<Mutex<Vec<Value>>>,+ contexts: Arc<AtomicUsize>,+ stall_until: Arc<std::sync::Mutex<Option<Instant>>>,+}++impl Mock {+ fn stalled(&self) -> bool { self.stall_until.lock().unwrap().is_some_and(|until| Instant::now() < until) }+ fn stall_for(&self, d: Duration) { *self.stall_until.lock().unwrap() = Some(Instant::now() + d); }+ /// Holds a `/json` answer (or a socket opening) while stalled: longer than any client waits.+ async fn hang_while_stalled(&self) { if self.stalled() { tokio::time::sleep(Duration::from_secs(60)).await; } }+ async fn methods(&self) -> Vec<String> {+ self.commands.lock().await.iter().map(|c| c["method"].as_str().unwrap_or_default().to_string()).collect()+ }+}++async fn cdp(State(mock): State<Mock>, Path(_id): Path<String>, ws: WebSocketUpgrade) -> axum::response::Response {+ mock.hang_while_stalled().await;+ ws.on_upgrade(move |mut socket| async move {+ while let Some(Ok(Message::Text(text))) = socket.next().await {+ let cmd: Value = serde_json::from_str(&text).unwrap();+ mock.commands.lock().await.push(cmd.clone());+ // an overloaded browser reads the command and never gets round to answering it+ if mock.stalled() { continue; }+ let result = match cmd["method"].as_str().unwrap() {+ "Target.createBrowserContext" => json!({"browserContextId": format!("context-{}", mock.contexts.fetch_add(1, Ordering::SeqCst))}),+ "Target.createTarget" => {+ let id = format!("page-{}", mock.contexts.load(Ordering::SeqCst));+ mock.targets.lock().await.push(json!({"targetId": id, "browserContextId": cmd["params"]["browserContextId"]}));+ json!({"targetId": id})+ }+ "Target.getTargets" => json!({"targetInfos": mock.targets.lock().await.clone()}),+ "Browser.getVersion" => json!({"product": "HeadlessChrome/156"}),+ "Runtime.evaluate" => json!({"result": {"value": {"url": "https://example.com/", "title": "Example"}}}),+ "Page.captureScreenshot" => json!({"data": "aGVsbG8="}),+ _ => json!({}),+ };+ if socket.send(Message::Text(json!({"id": cmd["id"], "result": result}).to_string())).await.is_err() { break; }+ }+ })+}++async fn mock() -> (Mock, tokio::task::JoinHandle<()>) {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let mock = Mock { port: listener.local_addr().unwrap().port(), ..Mock::default() };+ let app = Router::new()+ .route("/json/version", get(|State(m): State<Mock>| async move {+ m.hang_while_stalled().await;+ Json(json!({"webSocketDebuggerUrl": "ws://browser:9223/devtools/browser/root"}))+ }))+ .route("/json/list", get(|State(m): State<Mock>| async move {+ m.hang_while_stalled().await;+ Json(m.targets.lock().await.iter().map(|t| json!({"type": "page", "id": t["targetId"],+ "webSocketDebuggerUrl": format!("ws://browser:9223/devtools/page/{}", t["targetId"].as_str().unwrap())})).collect::<Vec<_>>())+ }))+ .route("/devtools/browser/:id", get(cdp))+ .route("/devtools/page/:id", get(cdp))+ .with_state(mock.clone());+ let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); });+ (mock, task)+}++/// A kwnt server whose VM browser is at `endpoint`, and the id of its first team.+async fn server(endpoint: String, tmp: &tempfile::TempDir) -> (AppState, String, u16, tokio::task::JoinHandle<()>) {+ let config = Config { data_dir: tmp.path().into(), browser_cdp_url: Some(endpoint), ..Config::default() };+ let db = Database::init(tmp.path()).await.unwrap();+ let id = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[0].id.clone();+ let state = AppState::new(config.clone(), db, ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url));+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let app = create_router(state.clone());+ let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); });+ (state, id, port, task)+}++async fn api_get(port: u16, path: &str) -> (reqwest::StatusCode, Value) {+ let response = reqwest::get(format!("http://127.0.0.1:{port}{path}")).await.unwrap();+ let status = response.status();+ (status, response.json().await.unwrap_or(Value::Null))+}++#[tokio::test]+async fn a_browser_that_stalls_for_ten_seconds_is_waited_for() {+ let (mock, cdp_task) = mock().await;+ let tmp = tempfile::tempdir().unwrap();+ let (_state, id, port, app_task) = server(format!("http://127.0.0.1:{}", mock.port), &tmp).await;++ // the bot's page is open and works+ let (status, body) = api_get(port, &format!("/api/sandbox/{id}/screenshot")).await;+ assert_eq!(status, 200, "{body}");++ // then the browser stops answering for 10 s (the Nov 12 incident: Target.getTargets and the+ // page's own commands time out); the bot's next step waits it out instead of failing+ mock.stall_for(Duration::from_secs(10));+ let started = Instant::now();+ let (status, body) = api_get(port, &format!("/api/sandbox/{id}/screenshot")).await;+ let waited = started.elapsed();+ assert_eq!(status, 200, "a 10 s stall must not fail the step: {body}");+ assert_eq!(body["screenshot"], "aGVsbG8=");+ assert!(waited >= Duration::from_secs(9), "the answer came after the stall, not before ({waited:?})");+ assert!(waited < Duration::from_secs(45), "inside the retry window ({waited:?})");+ assert_eq!(mock.contexts.load(Ordering::SeqCst), 1, "the same page is used again, not a new one");++ app_task.abort();+ cdp_task.abort();+}++#[tokio::test]+async fn a_browser_that_stays_stalled_is_reported_busy_and_retryable() {+ let (mock, cdp_task) = mock().await;+ let tmp = tempfile::tempdir().unwrap();+ let (state, id, port, app_task) = server(format!("http://127.0.0.1:{}", mock.port), &tmp).await;+ state.job_pages.set_retry_window(Duration::from_secs(4));+ mock.stall_for(Duration::from_secs(120));++ let (status, body) = api_get(port, &format!("/api/sandbox/{id}/screenshot")).await;+ assert_eq!(status, 503);+ assert_eq!(body["error"], BROWSER_BUSY, "temporary, retry in a minute; never the Docker text");+ assert_eq!(body["code"], BROWSER_BUSY_CODE);+ assert_eq!(body["retryable"], true);+ assert!(!body["error"].as_str().unwrap().contains("Docker"));++ // status says the same, quickly, and opens nothing+ let started = Instant::now();+ let (status, body) = api_get(port, &format!("/api/sandbox/{id}/status")).await;+ assert_eq!(status, 200);+ assert_eq!(body["is_running"], true, "overloaded, not gone");+ assert_eq!(body["responding"], false);+ assert_eq!(body["code"], BROWSER_BUSY_CODE);+ assert_eq!(body["retryable"], true);+ assert!(started.elapsed() < Duration::from_secs(8), "status doesn't wait out a whole command timeout");+ assert!(!mock.methods().await.iter().any(|m| m == "Target.createTarget"));++ app_task.abort();+ cdp_task.abort();+}++#[tokio::test]+async fn a_browser_that_is_not_there_gets_the_docker_text_at_once() {+ // a port nothing listens on: connection refused+ let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap().port();+ let tmp = tempfile::tempdir().unwrap();+ let (_state, id, port, app_task) = server(format!("http://127.0.0.1:{closed}"), &tmp).await;++ let started = Instant::now();+ let (status, body) = api_get(port, &format!("/api/sandbox/{id}/screenshot")).await;+ assert_eq!(status, 503);+ let error = body["error"].as_str().unwrap();+ assert_ne!(error, BROWSER_BUSY);+ assert!(body.get("code").is_none() && body.get("retryable").is_none(), "{body}");+ assert!(started.elapsed() < Duration::from_secs(5), "a refused connection isn't retried for 45 s");++ app_task.abort();+}++#[tokio::test]+async fn status_reports_health_without_opening_a_page() {+ let (mock, cdp_task) = mock().await;+ let tmp = tempfile::tempdir().unwrap();+ let (state, id, port, app_task) = server(format!("http://127.0.0.1:{}", mock.port), &tmp).await;++ for _ in 0..3 {+ let (status, body) = api_get(port, &format!("/api/sandbox/{id}/status")).await;+ assert_eq!(status, 200);+ assert_eq!(body["is_running"], true, "{body}");+ assert_eq!(body["responding"], true);+ assert_eq!(body["page_open"], false);+ }+ // a key that names no team never reaches the browser at all+ let before = mock.commands.lock().await.len();+ let (_, body) = api_get(port, "/api/sandbox/no-such-team/status").await;+ assert_eq!(body["is_running"], false);+ assert_eq!(mock.commands.lock().await.len(), before);++ let methods = mock.methods().await;+ assert!(!methods.iter().any(|m| m == "Target.createTarget" || m == "Target.createBrowserContext"), "{methods:?}");+ assert!(state.browser_controllers.lock().await.is_empty());++ // once the bot opened its page, status says so, still without touching it+ let (status, _) = api_get(port, &format!("/api/sandbox/{id}/screenshot")).await;+ assert_eq!(status, 200);+ let targets = mock.targets.lock().await.len();+ mock.commands.lock().await.clear();+ let (_, body) = api_get(port, &format!("/api/sandbox/{id}/status")).await;+ assert_eq!(body["page_open"], true);+ assert_eq!(mock.targets.lock().await.len(), targets);+ let methods = mock.methods().await;+ assert!(methods.iter().all(|m| m == "Browser.getVersion"), "status only asks the browser for its version: {methods:?}");++ app_task.abort();+ cdp_task.abort();+}++/// A page that keeps the browser busy the way an autoplaying feed does: a canvas animation+/// played as a video, plus a counter that ticks every 100 ms while the page runs.+const AUTOPLAY_PAGE: &str = "<title>autoplay</title><canvas id=c width=1280 height=720></canvas><video id=v autoplay muted playsinline></video><script>\+window.__ticks=0;setInterval(()=>window.__ticks++,100);\+const c=document.getElementById('c'),x=c.getContext('2d');\+(function draw(t){for(let i=0;i<400;i++){x.fillStyle='hsl('+((t/5+i)%360)+',80%,50%)';x.fillRect(Math.random()*1280,Math.random()*720,40,40);}requestAnimationFrame(draw);})(0);\+const v=document.getElementById('v');v.srcObject=c.captureStream(60);v.play();</script>";++/// What a bot drives: a page with a field it types into.+const DRIVEN_PAGE: &str = "<title>driven</title><input id=q><p id=out></p>";++/// A `data:` address for `html` (`%` and `#` escaped: `%360` would otherwise read as `%36`).+fn data_url(html: &str) -> String {+ format!("data:text/html,{}", html.replace('%', "%25").replace('#', "%23"))+}++async fn eval(ctrl: &kwnt::sandbox::BrowserController, expression: &str) -> Value {+ let reply = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": expression, "returnByValue": true})).await.unwrap();+ reply["result"]["value"].clone()+}++/// The real run (0.9.5 brief, "Real"): the repo's browser image under a small memory cap, one+/// autoplaying page and one driven page. Opt-in: `KWNT_REAL_CDP=http://127.0.0.1:<port>` of a+/// kwnt-browser container started for this run (never a shared one).+#[tokio::test]+#[ignore]+async fn real_capped_browser_keeps_the_driven_page_working() {+ let Ok(endpoint) = std::env::var("KWNT_REAL_CDP") else { return };+ let tmp = tempfile::tempdir().unwrap();+ let (state, id, _port, app_task) = server(endpoint, &tmp).await;+ let steady = |key: String| { let state = state.clone(); async move {+ kwnt::server::routes::open_page_steady(&state, &key, Duration::ZERO).await.unwrap_or_else(|_| panic!("open {key}"))+ }};++ // the team page autoplays, then is left alone+ let feed = steady(id.clone()).await;+ feed.send_cdp_command("Page.navigate", json!({"url": data_url(AUTOPLAY_PAGE)})).await.unwrap();+ tokio::time::sleep(Duration::from_secs(2)).await;+ assert_eq!(eval(&feed, "document.getElementById('v').paused").await, false, "the feed plays");+ tokio::time::sleep(Duration::from_secs(4)).await;+ let ticks_before = eval(&feed, "window.__ticks").await.as_i64().unwrap();+ println!("REAL feed playing, ticks={ticks_before}");++ // a bot's job page is driven; the sweep (2 s idle instead of 10 min) rests the feed only+ let job = format!("{id}#bot-1#chat-1");+ let driven = steady(job.clone()).await;+ driven.send_cdp_command("Page.navigate", json!({"url": data_url(DRIVEN_PAGE)})).await.unwrap();+ tokio::time::sleep(Duration::from_secs(3)).await;+ let _ = steady(job.clone()).await; // the bot's next step: just used+ let (frozen, blanked) = kwnt::server::browser_pages::rest_idle(&state, Duration::from_secs(2), Duration::from_secs(3600)).await;+ println!("REAL sweep froze={frozen} blanked={blanked}");+ assert_eq!((frozen, blanked), (1, 0), "the idle feed is frozen, the driven page isn't");++ // the driven page keeps working, step after step, while the feed rests+ let mut slowest = Duration::ZERO;+ let started = Instant::now();+ let mut steps = 0;+ while started.elapsed() < Duration::from_secs(15) {+ let step = Instant::now();+ let ctrl = steady(job.clone()).await;+ eval(&ctrl, &format!("document.getElementById('q').value='step {steps}';document.getElementById('out').textContent=document.getElementById('q').value")).await;+ let shot = ctrl.capture_screenshot().await.expect("the driven page answers");+ assert!(!shot.is_empty());+ slowest = slowest.max(step.elapsed());+ steps += 1;+ }+ assert_eq!(eval(&driven, "document.getElementById('out').textContent").await, json!(format!("step {}", steps - 1)));+ println!("REAL driven page: {steps} steps in 15 s, slowest {} ms", slowest.as_millis());+ assert!(slowest < Duration::from_secs(5), "every step answered promptly");++ // the feed didn't run while frozen, and wakes on its next use, muted video paused+ let ticks_after = eval(&feed, "window.__ticks").await.as_i64().unwrap();+ println!("REAL feed ticks while frozen: {} (it would be ~{} running)", ticks_after - ticks_before, 15 * 10 + 30);+ assert!(ticks_after - ticks_before < 60, "timers stopped while frozen");+ assert_eq!(eval(&feed, "document.visibilityState").await, json!("visible"), "woken pages paint again");+ assert_eq!(eval(&feed, "document.getElementById('v').paused").await, true, "the rested feed stays paused");+ let ticking = eval(&feed, "window.__ticks").await.as_i64().unwrap();+ tokio::time::sleep(Duration::from_secs(1)).await;+ assert!(eval(&feed, "window.__ticks").await.as_i64().unwrap() > ticking + 5, "timers run again after waking");+ assert!(!feed.capture_screenshot().await.unwrap().is_empty());+ // and it still navigates+ feed.send_cdp_command("Page.navigate", json!({"url": data_url(DRIVEN_PAGE)})).await.unwrap();+ tokio::time::sleep(Duration::from_secs(1)).await;+ assert_eq!(eval(&feed, "document.title").await, json!("driven"), "a woken page navigates");+ println!("REAL feed woke: visible, ticking, screenshot ok, navigated");++ // status says the browser is healthy, without creating a page+ let pages = state.browser_service.open_pages().await.len();+ let (_, body) = api_get(_port, &format!("/api/sandbox/{id}/status")).await;+ assert_eq!(body["responding"], true);+ assert_eq!(state.browser_service.open_pages().await.len(), pages);+ println!("REAL status: {body}");++ kwnt::server::browser_pages::close_page(&state, &job).await;+ app_task.abort();+}