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
31b browser-pid-headroom: keep the browser's pages under its process limit (#910)
Oleksandr Ivanchenkof3667258faad
diff --git a/src/sandbox/service.rs b/src/sandbox/service.rsindex d2b59c9d..bf706014 100644--- a/src/sandbox/service.rs+++ b/src/sandbox/service.rs@@ -10,6 +10,11 @@ use serde_json::json;use std::{collections::HashMap, path::{Path, PathBuf}, time::Duration};use tokio::{process::Command, sync::Mutex, time::{sleep, timeout}};+/// The `--pids-limit` of kwant's own browser container ([`managed_run_args`]): processes and+/// threads together. Chrome and its DevTools proxy can't fork past it, so the browser's pages are+/// kept under a budget derived from it (31b, [`crate::server::browser_pages::PAGE_PID_BUDGET`]).+pub const BROWSER_PIDS_LIMIT: u64 = 512;+/// The VM browser's image. Bump it whenever `docker/browser.Dockerfile` or/// `docker/browser-entrypoint.sh` change: kwant builds an image only when its tag is missing, and/// replaces a browser container made from another tag, so the bump is what ships the change.@@ -616,6 +621,29 @@ impl BrowserService {pages}+ /// [`Self::open_pages`] whose page is still there in the browser (31b): after the container+ /// restarts, pages kept from before stay listed until reused or closed, and must not count+ /// toward the browser's process budget. Every open page when the browser can't be asked.+ pub async fn live_pages(&self) -> Vec<(String, std::time::Instant)> {+ let alive: Option<std::collections::HashSet<String>> = {+ let lock = self.state.lock().await;+ let Some(state) = lock.as_ref() else { return Vec::new() };+ match state.browser.send_cdp_command("Target.getTargets", json!({})).await {+ Ok(targets) => {+ let live: std::collections::HashSet<&str> = targets["targetInfos"].as_array().into_iter().flatten()+ .filter_map(|t| t["targetId"].as_str()).collect();+ Some(state.sessions.iter().filter(|(_, s)| live.contains(s.target.as_str())).map(|(k, _)| k.clone()).collect())+ }+ Err(_) => None,+ }+ };+ let pages = self.open_pages().await;+ match alive {+ Some(alive) => pages.into_iter().filter(|(k, _)| alive.contains(k)).collect(),+ None => 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);diff --git a/src/server/browser_pages.rs b/src/server/browser_pages.rsindex b824e3fc..97acd387 100644--- a/src/server/browser_pages.rs+++ b/src/server/browser_pages.rs@@ -32,6 +32,19 @@//! sign-ins and place in the page stay, and its next use reconnects lazily//! ([`crate::sandbox::service::BrowserService::open_session`]). Never a page that's watched, held//! for a person, or mid-download or -chooser ([`connections_closable`]).+//!+//! The browser's process budget (31b). kwant's browser container can't fork past+//! [`BROWSER_PIDS_LIMIT`] processes and threads, and every open page holds a share of them (its+//! renderer, its context's network and storage, and one DevTools proxy process per connection).+//! Measured on kwnt-browser:v5: about 116 idle, 30-54 for a team page (its new context) and 13-32+//! for a job page, so three busy teams' 15 pages sat at about 444 and 17 at 496. Past the limit+//! Chrome can't start a page's processes and the browser fails in ways that look unrelated (a+//! download that never ends, `net::ERR_EMPTY_RESPONSE`, BROWSER_BUSY). So before a new job page+//! opens, the pages of every team are kept under [`PAGE_PID_BUDGET`] ([`pids_with`]): the least+//! recently used idle job page of any team is closed to make room, and when none can close the+//! job is told plainly that the browser is full ([`browser_full_message`]). Freezing or blanking+//! a page frees none of its processes (blanking briefly adds one), so only closing makes room. A+//! team page is never refused or closed; it counts, so job pages give way to it.use super::continuity::SelfScope;use super::AppState;@@ -49,6 +62,48 @@ use std::{pub use crate::sandbox::service::{is_job_page, job_page_key, page_team, PAGE_SEP};+pub use crate::sandbox::service::BROWSER_PIDS_LIMIT;+/// The idle browser's own processes and threads, with no page open (measured 105-116).+pub const BROWSER_IDLE_PIDS: u64 = 120;+/// Kept free for what isn't a page: downloads copied out with `docker exec`, a live view's+/// connection, a blanked page's short-lived renderer (+11 measured).+pub const PIDS_HEADROOM: u64 = 64;+/// A team page: the first page of a team's browser context (measured 30-54 with its connections).+pub const TEAM_PAGE_PIDS: u64 = 40;+/// A job page: one more page in its team's context (measured 13-32 with its connections, about 19+/// on average).+pub const JOB_PAGE_PIDS: u64 = 20;+/// What every open page of the browser together may hold: room for three teams' pages and ten job+/// pages, or two teams with all eight of theirs.+pub const PAGE_PID_BUDGET: u64 = BROWSER_PIDS_LIMIT - BROWSER_IDLE_PIDS - PIDS_HEADROOM;++/// What one open page holds of the budget.+pub fn page_pids(key: &str) -> u64 {+ if is_job_page(key) {+ JOB_PAGE_PIDS+ } else {+ TEAM_PAGE_PIDS+ }+}++/// What the browser's pages would hold with `key` open beside the `open` ones: a job page whose+/// team has no page open yet opens its team's page (the context) too.+pub fn pids_with(open: &[String], key: &str) -> u64 {+ let others: u64 = open.iter().filter(|k| *k != key).map(|k| page_pids(k)).sum();+ let team = page_team(key);+ let team_too = is_job_page(key) && !open.iter().any(|k| k == team);+ others + page_pids(key) + if team_too { TEAM_PAGE_PIDS } else { 0 }+}++/// What a job is told when the browser holds as many pages as it can run (its process budget)+/// and every one is held or in use.+pub fn browser_full_message() -> String {+ "The browser is full: it has as many pages open as it can run, and every one is in use by a \+ job or waiting for a person. Try again in a minute, or finish a job that has a page open; \+ nothing is wrong with the browser."+ .to_string()+}+/// Most job pages one team keeps open at once.pub const MAX_JOB_PAGES_PER_TEAM: usize = 4;/// A job page unused this long is closed (unless a step holds it).@@ -108,6 +163,11 @@ pub struct JobPages {wait_ms: AtomicU64,/// Tests only: the retry window in ms (0 = [`RETRY_WINDOW`]).retry_ms: AtomicU64,+ /// Tests only: the page budget (0 = [`PAGE_PID_BUDGET`]).+ budget: AtomicU64,+ /// Held, after a team's lock, while room is made in the whole browser and a page opened, so+ /// two teams opening at once never pass [`PAGE_PID_BUDGET`] together.+ room: Arc<tokio::sync::Mutex<()>>,}impl JobPages {@@ -139,6 +199,23 @@ impl JobPages {ms => Duration::from_millis(ms),}}++ /// Tests: a smaller page budget than [`PAGE_PID_BUDGET`].+ pub fn set_page_budget(&self, pids: u64) {+ self.budget.store(pids.max(1), Ordering::Relaxed);+ }++ pub fn page_budget(&self) -> u64 {+ match self.budget.load(Ordering::Relaxed) {+ 0 => PAGE_PID_BUDGET,+ pids => pids,+ }+ }++ /// The lock held while room is made in the whole browser (see [`JobPages::room`]).+ pub fn room_lock(&self) -> Arc<tokio::sync::Mutex<()>> {+ self.room.clone()+ }}/// A job page's team, bot and chat; `None` for the team page.@@ -393,6 +470,50 @@ pub async fn make_room(state: &AppState, team: &str, key: &str) -> bool {to_close == 0}+/// 31b: before a new job page `key` opens: keeps every team's open pages under the browser's+/// process budget ([`JobPages::page_budget`], [`pids_with`]) by closing the least recently used+/// job pages of any team that can be closed ([`closable`]). Never a team page or `key`; another+/// team's page only when its team's lock is free (a page that team is opening or closing is left+/// to it). `false` when the budget can't be met. Local mode (the person's own Chrome) has no such+/// limit. The caller holds its team's [`JobPages::team_lock`] and then [`JobPages::room_lock`]+/// until the new page is open.+pub async fn make_browser_room(state: &AppState, key: &str) -> bool {+ if state.browser_service.mode() == crate::sandbox::computer::ComputerMode::Local {+ return true;+ }+ let budget = state.job_pages.page_budget();+ let pages = state.browser_service.live_pages().await;+ let mut open: Vec<String> = pages.iter().map(|(k, _)| k.clone()).collect();+ if pids_with(&open, key) <= budget {+ return true;+ }+ let team = page_team(key);+ for (page, _) in pages {+ if page == key || !is_job_page(&page) {+ continue;+ }+ let other_team = (page_team(&page) != team).then(|| state.job_pages.team_lock(page_team(&page)));+ let _other_team_lock = match &other_team {+ Some(lock) => match lock.try_lock() {+ Ok(guard) => Some(guard),+ Err(_) => continue,+ },+ None => None,+ };+ if !closable(state, &page).await {+ continue;+ }+ close_page(state, &page).await;+ open.retain(|k| *k != page);+ tracing::info!(page = %page, for_page = %key, "browser: closed the least recently used idle job page to stay under the browser's process limit");+ if pids_with(&open, key) <= budget {+ return true;+ }+ }+ tracing::warn!(page = %key, "the browser is at its page budget and every job page is held or in use");+ false+}+/// Closes job pages unused for `idle` that no step holds and nobody is using. Returns how many.pub async fn sweep_idle(state: &AppState, idle: Duration) -> usize {let now = Instant::now();@@ -587,6 +708,60 @@ mod tests {assert!(!connection_closable(true, true, true));}+ /// 31b: how many pages fit the budget for a number of teams, each team filling its pages in+ /// turn (at most four job pages each).+ fn pages_that_fit(teams: usize) -> usize {+ let mut open: Vec<String> = Vec::new();+ let mut jobs = vec![0; teams];+ 'fill: loop {+ let mut added = false;+ for (t, n) in jobs.iter_mut().enumerate() {+ let team = format!("t{t}");+ let key = if open.contains(&team) {+ if *n == MAX_JOB_PAGES_PER_TEAM {+ continue;+ }+ *n += 1;+ job_page_key(&team, "k", &format!("c{n}")).unwrap()+ } else {+ team+ };+ if pids_with(&open, &key) > PAGE_PID_BUDGET {+ break 'fill;+ }+ open.push(key);+ added = true;+ }+ if !added {+ break;+ }+ }+ open.len()+ }++ #[test]+ fn the_browsers_pages_stay_under_its_process_limit_with_room_for_normal_use() {+ assert_eq!(BROWSER_PIDS_LIMIT, 512);+ let args = crate::sandbox::service::managed_run_args("n", std::path::Path::new("/tmp"), None);+ assert!(args.contains(&format!("--pids-limit={BROWSER_PIDS_LIMIT}")), "the budget follows the container's real limit");+ assert_eq!(PAGE_PID_BUDGET, 328);+ // one or two teams never meet it; three busy teams keep 13 of their 15 pages+ assert_eq!(pages_that_fit(1), 1 + MAX_JOB_PAGES_PER_TEAM);+ assert_eq!(pages_that_fit(2), 2 * (1 + MAX_JOB_PAGES_PER_TEAM));+ assert_eq!(pages_that_fit(3), 13);+ assert!((4..=6).all(|teams| pages_that_fit(teams) >= 8), "never under the ~8 pages normal use needs");+ // a job page of a team with no page yet opens its team's page too; the page itself counts once+ assert_eq!(pids_with(&[], "t#k#c"), TEAM_PAGE_PIDS + JOB_PAGE_PIDS);+ assert_eq!(pids_with(&["t".into()], "t#k#c"), TEAM_PAGE_PIDS + JOB_PAGE_PIDS);+ assert_eq!(pids_with(&["t".into(), "t#k#c".into()], "t#k#c"), TEAM_PAGE_PIDS + JOB_PAGE_PIDS);+ assert_eq!(pids_with(&["u".into()], "t"), 2 * TEAM_PAGE_PIDS);+ assert!(browser_full_message().contains("nothing is wrong with the browser"));+ let pages = JobPages::default();+ assert_eq!(pages.page_budget(), PAGE_PID_BUDGET);+ pages.set_page_budget(60);+ assert_eq!(pages.page_budget(), 60);+ }+#[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 28a7e24e..4a9e714a 100644--- a/src/server/browser_stream.rs+++ b/src/server/browser_stream.rs@@ -1368,6 +1368,7 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String, bots_page: bolet error = match refusal {PageRefusal::Busy => crate::sandbox::service::BROWSER_RECONNECTING.to_string(),PageRefusal::PagesFull => super::browser_pages::pages_full_message(),+ PageRefusal::BrowserFull => super::browser_pages::browser_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;diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex fb497c1e..97b85a95 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -889,7 +889,7 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, na}match opened {Ok(ctrl) => ctrl.site_guard.set_driver(&scope.kwant_id),- Err(refusal @ (super::routes::PageRefusal::PagesFull | super::routes::PageRefusal::Busy)) => {+ Err(refusal @ (super::routes::PageRefusal::PagesFull | super::routes::PageRefusal::BrowserFull | super::routes::PageRefusal::Busy)) => {return (page_refusal_text(state, refusal), true)}Err(super::routes::PageRefusal::Unavailable) => {}@@ -933,6 +933,7 @@ fn wall_check_helps(text: &str, page: Option<&Value>) -> bool {fn page_refusal_text(state: &AppState, refusal: super::routes::PageRefusal) -> String {match refusal {super::routes::PageRefusal::PagesFull => super::browser_pages::pages_full_message(),+ super::routes::PageRefusal::BrowserFull => super::browser_pages::browser_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 e03424a9..4a7d09ec 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -6149,6 +6149,9 @@ pub enum PageRefusal {PagesFull,/// VM mode: the browser is there but didn't answer in time (overloaded). Temporary.Busy,+ /// The browser holds as many pages as its process limit allows and every one is held or in+ /// use (31b, [`super::browser_pages::PAGE_PID_BUDGET`]).+ BrowserFull,}/// The page's controller for a bot's browser call: like [`get_or_create_browser_controller`],@@ -6208,11 +6211,18 @@ pub(crate) fn page_refused(state: &AppState, refusal: PageRefusal) -> (StatusCod"code": PAGES_FULL,"is_running": true,}))),+ PageRefusal::BrowserFull => (StatusCode::SERVICE_UNAVAILABLE, Json(json!({+ "error": super::browser_pages::browser_full_message(),+ "code": BROWSER_FULL,+ "is_running": true,+ }))),}}/// The `code` of a call refused because every job page of the team is in use.pub const PAGES_FULL: &str = "PAGES_FULL";+/// The `code` of a call refused because the browser is full (31b).+pub const BROWSER_FULL: &str = "BROWSER_FULL";/// Opens (or returns) a page's controller. A job page that isn't open yet is made room for and/// opened under its team's lock, so two jobs opening at once never pass the cap; with no room it@@ -6243,18 +6253,36 @@ pub async fn open_page(loop {let lock = state.job_pages.team_lock(&team);let opening = lock.lock().await;+ // 31b: then the whole browser's, so two teams opening at once never pass its process+ // budget together (always after a team's lock; other teams' locks are only tried)+ let room_lock = state.job_pages.room_lock();+ let room = room_lock.lock().await;let open = state.browser_controllers.lock().await.contains_key(key);- if open || super::browser_pages::make_room(state, &team, key).await {+ let refusal = if open {+ None+ } else if !super::browser_pages::make_room(state, &team, key).await {+ Some(PageRefusal::PagesFull)+ } else if !super::browser_pages::make_browser_room(state, key).await {+ Some(PageRefusal::BrowserFull)+ } else {+ None+ };+ let Some(refusal) = refusal else {state.browser_service.touch_page(key);let ctrl = controller_for(state, key, &team).await;+ drop(room);drop(opening);return ctrl.map_err(refusal_for);- }+ };+ drop(room);drop(opening);let now = std::time::Instant::now();if now >= deadline {- tracing::warn!(page = %key, "every job page of this team is held or in use; no room for another");- return Err(PageRefusal::PagesFull);+ match refusal {+ PageRefusal::BrowserFull => tracing::warn!(page = %key, "the browser is full: every page is held or in use; no room for another"),+ _ => tracing::warn!(page = %key, "every job page of this team is held or in use; no room for another"),+ }+ return Err(refusal);}tokio::time::sleep((deadline - now).min(std::time::Duration::from_secs(1))).await;}diff --git a/tests/browser_pages_test.rs b/tests/browser_pages_test.rsindex f2d5ac99..2d6763f8 100644--- a/tests/browser_pages_test.rs+++ b/tests/browser_pages_test.rs@@ -29,7 +29,7 @@ use kwnt::{browser_pages::{self, job_page_key, MAX_JOB_PAGES_PER_TEAM},continuity::{SelfScope, TurnOrigin},create_router, mcp_runtime,- routes::{get_or_create_browser_controller, HELD_FOR_BOT, PAGES_FULL},+ routes::{get_or_create_browser_controller, PageRefusal, BROWSER_FULL, HELD_FOR_BOT, PAGES_FULL},AppState,},tools::ToolRunner,@@ -472,6 +472,65 @@ async fn jobs_opening_pages_at_once_never_pass_the_cap() {assert_eq!(page_targets().await, before + MAX_JOB_PAGES_PER_TEAM, "four job pages in the browser, the others closed");}+/// 31b: the browser's pages, across every team, stay under the container's process budget. A job+/// opening a page that would pass it first closes the least recently used idle job page of any+/// team (never a team page, a held one, or one in use); when nothing can close, the job is told+/// plainly the browser is full, through the HTTP route and the bot's browser tool alike, instead+/// of Chrome failing to start the page's processes.+#[tokio::test]+async fn a_page_past_the_browsers_process_budget_closes_the_oldest_idle_job_page_of_any_team() {+ let tmp = tempdir().unwrap();+ let Some((endpoint, _chrome)) = start_chrome(&tmp.path().join("chrome")).await else { return };+ let state = container_state(&tmp, endpoint).await;+ let app = create_router(state.clone());+ let bot = first_bot(&state).await;+ // two teams: each bot is a sandbox target with its own browser context+ let b = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(1).id;+ let a = bot.id.clone();+ assert_ne!(a, b);+ let key = |team: &str, c: &str| job_page_key(team, "k", c).unwrap();+ // room for two teams' pages and two job pages+ state.job_pages.set_page_budget(2 * browser_pages::TEAM_PAGE_PIDS + 2 * browser_pages::JOB_PAGE_PIDS);+ open_page(&state, &a, "a1").await.expect("a job page opens, with its team's page");+ tokio::time::sleep(Duration::from_millis(20)).await;+ open_page(&state, &b, "b1").await.expect("another team's job page opens");+ tokio::time::sleep(Duration::from_millis(20)).await;+ let mut both = vec![key(&a, "a1"), key(&b, "b1")];+ both.sort();+ assert_eq!(open_pages(&state).await, both);++ // A third job page would pass the budget: the oldest idle job page closes, though it's+ // another team's, and well under that team's own cap of four+ open_page(&state, &b, "b2").await.expect("a third job page opens");+ assert_eq!(open_pages(&state).await, vec![key(&b, "b1"), key(&b, "b2")], "team a's idle page made room");+ // A job page's team page is the browser service's (its context), not a kwant controller:+ // check it where the budget counts it, as a live page in the browser+ let team_pages_kept = || async {+ let live: Vec<String> = state.browser_service.live_pages().await.into_iter().map(|(k, _)| k).collect();+ live.contains(&a) && live.contains(&b)+ };+ assert!(team_pages_kept().await, "team pages are never closed to make room");++ // Every job page held: nothing closes, and the job is told the browser is full+ hold(&state, &b, &key(&b, "b1"), "t1").await;+ hold(&state, &b, &key(&b, "b2"), "t2").await;+ let refused = kwnt::server::routes::open_page(&state, &key(&a, "a2"), Duration::from_millis(300)).await;+ assert_eq!(refused.err(), Some(PageRefusal::BrowserFull));+ state.job_pages.set_wait(Duration::from_millis(300));+ let navigate = format!("/api/sandbox/{}/navigate", key(&a, "a3").replace('#', "%23"));+ let (status, v) = request(&app, "POST", &navigate, Some(json!({"url": "about:blank"}))).await;+ assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(v["code"], BROWSER_FULL);+ assert_eq!(v["error"], browser_pages::browser_full_message());+ let token = turn_in_thread(&state, &bot, "turn-9", "t9", &a).await;+ let (text, is_error) = call(&app, &token, "browser_open", json!({"url": "about:blank"})).await.unwrap();+ assert!(is_error);+ assert_eq!(text, browser_pages::browser_full_message());+ assert_eq!(open_pages(&state).await, vec![key(&b, "b1"), key(&b, "b2")], "nothing was closed");+ assert!(team_pages_kept().await, "nor a team page");+ assert!(state.browser_service.job_pages(&a).await.is_empty(), "the refused pages aren't counted");+}+/// The repro for #753: before the fix, closing a job page never dropped its controller from/// [`kwnt::sandbox::service::BrowserService`]'s own cache, so its DevTools, download and popups/// connections to the container browser outlived the page and piled up, one finished job at a