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: close idle DevTools connections instead of leaking them (#753) (#759)
Oleksandr Ivanchenko49738baaf382
diff --git a/docker/browser-entrypoint.sh b/docker/browser-entrypoint.shindex cc554f09..810fbcee 100644--- a/docker/browser-entrypoint.sh+++ b/docker/browser-entrypoint.sh@@ -28,7 +28,10 @@ if [ -n "${KWNT_BROWSER_PROXY:-}" ]; thenfichromium "$@" about:blank &chrome_pid=$!-socat TCP-LISTEN:9222,fork,reuseaddr TCP:127.0.0.1:9223 &+# max-children caps forked copies so a connection leak runs out of room loudly (ECONNREFUSED) well+# before it exhausts the container's processes/threads and takes Chromium down with it (#753). No+# timeout: a site guard or download connection sitting idle is normal, not stuck.+socat TCP-LISTEN:9222,fork,reuseaddr,max-children=64 TCP:127.0.0.1:9223 &proxy_pid=$!trap 'kill "$chrome_pid" "$proxy_pid" 2>/dev/null || true' EXIT INT TERMwait "$chrome_pid"diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex e4e509be..60a07d0a 100755--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -20,7 +20,10 @@ chromium \--enable-features=PasswordImport,AutofillServerCommunication \--disable-blink-features=AutomationControlled &-# Proxy incoming port 9222 from container network to local Chromium on 9223-socat TCP-LISTEN:9222,fork,reuseaddr TCP:127.0.0.1:9223 &+# Proxy incoming port 9222 from container network to local Chromium on 9223.+# max-children caps forked copies so a connection leak runs out of room loudly (ECONNREFUSED) well+# before it exhausts the container's processes/threads and takes Chromium down with it (#753). No+# timeout: a site guard or download connection sitting idle is normal, not stuck.+socat TCP-LISTEN:9222,fork,reuseaddr,max-children=64 TCP:127.0.0.1:9223 &exec sleep infinitydiff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex 12dd8ae5..cf555b60 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -1708,7 +1708,12 @@ impl BrowserController {if self.downloads.lock().unwrap_or_else(|e| e.into_inner()).is_some() {return;}- let center = super::browser_downloads::DownloadCenter::start(self.clone(), workspace, home, context_id, staging_root).await;+ // `run` only calls `get_ws_url()`, never touches `downloads` — give it a clone with that+ // field cut so the center isn't kept alive by its own background task (ctrl -> downloads+ // -> jobs Sender -> the Receiver `run` awaits forever), which would leak its connection.+ let mut ctrl = self.clone();+ ctrl.downloads = Arc::default();+ let center = super::browser_downloads::DownloadCenter::start(ctrl, workspace, home, context_id, staging_root).await;let mut guard = self.downloads.lock().unwrap_or_else(|e| e.into_inner());if guard.is_none() {*guard = Some(center);diff --git a/src/sandbox/service.rs b/src/sandbox/service.rsindex 09dcebca..87896635 100644--- a/src/sandbox/service.rs+++ b/src/sandbox/service.rs@@ -13,7 +13,7 @@ use tokio::{process::Command, sync::Mutex, time::{sleep, timeout}};/// 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.-pub const BROWSER_IMAGE: &str = "kwnt-browser:v4";+pub const BROWSER_IMAGE: &str = "kwnt-browser:v5";const BROWSER_DOCKERFILE: &str = include_str!("../../docker/browser.Dockerfile");const BROWSER_ENTRYPOINT: &str = include_str!("../../docker/browser-entrypoint.sh");@@ -753,6 +753,10 @@ impl BrowserService {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() {+ // Drop this page's own cached controller too (#753): otherwise its downloads/site+ // guard/popups connections to the browser outlive the page they were opened for,+ // even though `Target.closeTarget` below ends the page itself.+ state.controllers.remove(key);if let Some(session) = state.sessions.remove(key) {let _ = state.browser.send_cdp_command("Target.closeTarget", json!({"targetId": session.target})).await;self.save_sessions(&state.sessions).await?;@@ -761,6 +765,17 @@ impl BrowserService {Ok(())}+ /// Drops a page's cached controller without closing its page or context (#753): the next use+ /// reconnects lazily in [`Self::open_session`]. For a page that stays open but has been idle,+ /// freeing its DevTools connections (and the download/site-guard/popups tasks that hold them)+ /// without losing the session, its sign-ins, or its place in the page.+ pub async fn drop_connection(&self, key: &str) -> bool {+ match self.state.lock().await.as_mut() {+ Some(state) => state.controllers.remove(key).is_some(),+ None => false,+ }+ }+/// Where a bot's VM-browser cookies are kept between container restarts.pub fn cookie_jar(&self, id: &str) -> PathBuf {let name: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).take(120).collect();@@ -780,6 +795,10 @@ impl BrowserService {*lock = Some(self.connect().await?);}if let Some(state) = lock.as_mut() {+ // Its own and its job pages' cached controllers go with the context (#753): their+ // downloads/site-guard/popups tasks would otherwise outlive the disposed context.+ state.controllers.remove(id);+ state.controllers.retain(|k, _| !k.starts_with(&prefix));if let Some(session) = state.sessions.remove(id) {if session.context.is_empty() {// a local tab in the shared profile: close just that tab@@ -978,7 +997,7 @@ mod image_tests {use super::{BROWSER_DOCKERFILE, BROWSER_ENTRYPOINT, BROWSER_IMAGE};use sha2::{Digest, Sha256};- /// The browser files `kwnt-browser:v4` was built from. A change to them without a new+ /// The browser files `kwnt-browser:v5` was built from. A change to them without a new/// [`BROWSER_IMAGE`] would never reach a computer that already has the old tag.#[test]fn the_browser_image_tag_moves_with_its_files() {@@ -988,7 +1007,7 @@ mod image_tests {let hash: String = files.finalize().iter().take(8).map(|b| format!("{b:02x}")).collect();assert_eq!((BROWSER_IMAGE, hash.as_str()),- ("kwnt-browser:v4", "3de3efce1e8d41e4"),+ ("kwnt-browser:v5", "67a48c2dc2d62735"),"docker/browser files changed: bump BROWSER_IMAGE, then record the new hash here");}diff --git a/src/server/browser_pages.rs b/src/server/browser_pages.rsindex b1b42644..dc89b0b9 100644--- a/src/server/browser_pages.rs+++ b/src/server/browser_pages.rs@@ -20,6 +20,18 @@//! 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`]).+//!+//! Closing idle connections (#753). A page's controller keeps a DevTools connection open for as+//! long as it's cached: one for the page itself, plus a download/chooser connection and a+//! browser-level one each for its site guard and popup watcher. Freezing or blanking a page+//! doesn't touch any of these, and before this fix nothing ever did for a page that stayed open+//! (every team page, and a job page short of [`JOB_PAGE_IDLE`]) or even reliably for one that+//! was closed: on a long-running kwant they piled up until the browser ran out of the OS+//! resources (processes, threads) they each cost and every `browser_open` failed. A page idle+//! past [`CONN_IDLE_CLOSE`] now has its connections closed ([`close_idle_connections`]); its+//! 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`]).use super::continuity::SelfScope;use super::AppState;@@ -50,6 +62,12 @@ pub const PAGE_WAIT: Duration = Duration::from_secs(60);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);+/// VM mode: a page idle this long has its DevTools connections closed (#753): the download, site+/// guard and popups tasks that each hold one of their own, same as [`IDLE_FREEZE`] since a frozen+/// page has nothing left for them to watch. The page and its sign-ins stay; the next use+/// reconnects lazily. Never one that's watched, held for a person, or has a download or file+/// chooser in flight.+pub const CONN_IDLE_CLOSE: Duration = IDLE_FREEZE;/// 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`].@@ -243,10 +261,66 @@ pub async fn rest_idle(state: &AppState, freeze_after: Duration, blank_after: Du(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.+/// Whether a page's connections may be closed given whether it's [`restable`] and has a download+/// or file chooser in flight: closing mid-download would drop it, and a chooser the bot hasn't+/// answered yet would be lost.+pub fn connection_closable(restable: bool, downloading: bool, chooser_open: bool) -> bool {+ restable && !downloading && !chooser_open+}++/// Whether a page's connections may be closed now: see [`connection_closable`].+async fn connections_closable(state: &AppState, key: &str) -> bool {+ let restable = restable(state, key).await;+ if !restable {+ return false;+ }+ let ctrl = state.browser_controllers.lock().await.get(key).cloned();+ let Some(ctrl) = ctrl else { return true };+ let downloading = ctrl.peek_download_report().is_some_and(|r| r["status"] == "in_progress");+ connection_closable(restable, downloading, ctrl.open_chooser_report().is_some())+}++/// Closes one page's DevTools connections (its controller's download, site guard and popups+/// tasks) without closing the page itself or its context: the next use reconnects lazily and its+/// sign-ins stay (`persist_cookies` first, belt and suspenders for a VM container restart; the+/// browser's own cookie store for the page's context is untouched either way). Whether it was.+async fn close_connection(state: &AppState, key: &str) -> bool {+ let ctrl = state.browser_controllers.lock().await.remove(key);+ if let Some(ctrl) = &ctrl {+ ctrl.persist_cookies().await;+ }+ let dropped_cached = state.browser_service.drop_connection(key).await;+ ctrl.is_some() || dropped_cached+}++/// VM mode: closes the DevTools connections of pages idle past [`CONN_IDLE_CLOSE`] (job pages+/// not yet past [`JOB_PAGE_IDLE`], and team pages, which [`sweep_idle`] never closes at all).+/// Returns how many.+pub async fn close_idle_connections(state: &AppState, after: Duration) -> usize {+ if state.browser_service.mode() == crate::sandbox::computer::ComputerMode::Local {+ return 0;+ }+ let now = Instant::now();+ let mut closed = 0;+ for (key, at) in state.browser_service.open_pages().await {+ if now.duration_since(at) < after || !connections_closable(state, &key).await {+ continue;+ }+ if close_connection(state, &key).await {+ closed += 1;+ tracing::info!(page = %key, "browser: closed an idle page's connections");+ }+ }+ closed+}++/// The browser stopped answering a call for `keep`: frees memory and DevTools connections by+/// closing other idle job pages and blanking and disconnecting other idle team pages, least+/// recently used first, never `keep` nor a page used in the last minute, watched, held, mid-+/// download, or otherwise in use. A `BROWSER_BUSY` the resource-exhaustion fix (#753) couldn't+/// prevent is exactly this: too many of these connections open at once, so relief drops them too,+/// not just memory, before a retry gives up. Each step is bounded (the browser may be stalled),+/// and all of it by [`RELIEF_BUDGET`]. Returns how many pages were closed, blanked or disconnected.pub async fn relieve(state: &AppState, keep: &str) -> usize {if state.browser_service.mode() == crate::sandbox::computer::ComputerMode::Local {return 0;@@ -269,14 +343,18 @@ pub async fn relieve(state: &AppState, keep: &str) -> usize {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 {+ continue;+ }+ let blanked = state.browser_service.rest_of(&key) != Some(Rest::Blank) && rest_page(state, &key, Rest::Blank).await;+ let disconnected = connections_closable(state, &key).await && close_connection(state, &key).await;+ if blanked || disconnected {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");+ tracing::warn!(page = %keep, "browser: not answering; closed, blanked or disconnected {relieved} other idle pages to free resources");}relieved}@@ -355,6 +433,10 @@ pub fn spawn_sweeper(state: AppState, cancel: tokio_util::sync::CancellationTokeif frozen + blanked > 0 {tracing::info!("browser: froze {frozen} and blanked {blanked} idle pages");}+ let disconnected = close_idle_connections(&state, CONN_IDLE_CLOSE).await;+ if disconnected > 0 {+ tracing::info!("browser: closed {disconnected} idle pages' connections");+ }}});}@@ -484,6 +566,15 @@ mod tests {assert_eq!(rest(true, m(600), None), Some(Rest::Frozen), "a job page is never blanked (it is closed)");}+ #[test]+ fn a_pages_connections_never_close_mid_download_or_chooser_even_if_restable() {+ assert!(connection_closable(true, false, false));+ assert!(!connection_closable(false, false, false), "not restable (watched, held, or has a turn)");+ assert!(!connection_closable(true, true, false), "a download is in progress");+ assert!(!connection_closable(true, false, true), "a file chooser is open, unanswered");+ assert!(!connection_closable(true, true, true));+ }+#[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/tests/browser_pages_test.rs b/tests/browser_pages_test.rsindex 10f346d8..20b9c9ff 100644--- a/tests/browser_pages_test.rs+++ b/tests/browser_pages_test.rs@@ -150,6 +150,26 @@ async fn controller(state: &AppState, page: &str) -> BrowserController {state.browser_controllers.lock().await.get(page).cloned().unwrap_or_else(|| panic!("no controller for {page}"))}+/// How many TCP connections on this host are `ESTABLISHED` to local port `port` (either side):+/// a page's own DevTools connection, plus one each for its download, site guard and popups tasks,+/// all to the same container browser port (#753).+async fn established_connections(port: u16) -> usize {+ let hex_port = format!("{port:04X}");+ let mut n = 0;+ for path in ["/proc/net/tcp", "/proc/net/tcp6"] {+ let Ok(text) = tokio::fs::read_to_string(path).await else { continue };+ for line in text.lines().skip(1) {+ let cols: Vec<&str> = line.split_whitespace().collect();+ let (Some(local), Some(remote), Some(st)) = (cols.get(1), cols.get(2), cols.get(3)) else { continue };+ let ends_in_port = |addr: &str| addr.rsplit_once(':').is_some_and(|(_, p)| p.eq_ignore_ascii_case(&hex_port));+ if *st == "01" && (ends_in_port(local) || ends_in_port(remote)) {+ n += 1;+ }+ }+ }+ n+}+#[tokio::test]async fn a_sign_in_on_one_jobs_page_holds_only_that_page_and_the_teams_sign_ins_are_shared() {let tmp = tempdir().unwrap();@@ -449,6 +469,86 @@ 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");}+/// 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+/// time, forever. With the fix, closing a page drops its connections with it.+#[tokio::test]+async fn finished_jobs_dont_leave_their_browser_connections_behind() {+ let tmp = tempdir().unwrap();+ let Some((endpoint, _chrome)) = start_chrome(&tmp.path().join("chrome")).await else { return };+ let port: u16 = endpoint.rsplit(':').next().unwrap().parse().unwrap();+ let state = container_state(&tmp, endpoint).await;+ let team = first_bot(&state).await.id;+ let base = serve().await;++ get_or_create_browser_controller(&state, &team).await.expect("the team page opens");+ tokio::time::sleep(Duration::from_millis(200)).await;+ let before = established_connections(port).await;++ // Ten jobs, one after another, each opening its own page (its own DevTools connection, plus+ // a download and a popups connection started the same way a live job's would be) and then+ // closed the way a finished job's page is: never held, never watched.+ for i in 0..10 {+ let chat = format!("c{i}");+ let ctrl = open_page(&state, &team, &chat).await.expect("a job page opens");+ ctrl.navigate(&format!("{base}/plain")).await.unwrap();+ assert_eq!(title_becomes(&ctrl, "plain").await, "plain");+ browser_pages::close_page(&state, &job_page_key(&team, "k", &chat).unwrap()).await;+ }+ tokio::time::sleep(Duration::from_millis(300)).await;+ let after = established_connections(port).await;+ assert!(+ after <= before + 3,+ "ten finished jobs left the browser with {after} connections, started with {before}: \+ closing a page should drop its connections, not add to them forever"+ );+}++/// An idle page's connections close; one that's watched (a live view open on it) or held (a step+/// open for the person) never does, even past the same idle time.+#[tokio::test]+async fn an_idle_pages_connections_close_but_never_one_watched_or_held() {+ 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 team = first_bot(&state).await.id;+ let key = |c: &str| job_page_key(&team, "k", c).unwrap();+ open_page(&state, &team, "idle").await.unwrap();+ open_page(&state, &team, "held").await.unwrap();+ let watched = open_page(&state, &team, "watched").await.unwrap();+ hold(&state, &team, &key("held"), "t").await;+ let _watching = watched.watch();++ assert_eq!(browser_pages::close_idle_connections(&state, Duration::ZERO).await, 1);+ let cached = state.browser_controllers.lock().await;+ assert!(!cached.contains_key(&key("idle")), "the idle page's connections are gone");+ assert!(cached.contains_key(&key("held")), "a page held for the person keeps its connections");+ assert!(cached.contains_key(&key("watched")), "a watched page keeps its connections");+}++/// Closing a page's connections keeps the page itself, its place, and its sign-in; the next use+/// reconnects lazily to the very same page, not a fresh one.+#[tokio::test]+async fn closing_a_pages_connections_keeps_its_sign_in_and_reconnects_the_same_page() {+ 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 team = first_bot(&state).await.id;+ let key = job_page_key(&team, "k", "c").unwrap();+ let base = serve().await;+ let ctrl = open_page(&state, &team, "c").await.unwrap();+ ctrl.navigate(&format!("{base}/signin")).await.unwrap();+ assert_eq!(title_becomes(&ctrl, "sign in").await, "sign in");++ assert_eq!(browser_pages::close_idle_connections(&state, Duration::ZERO).await, 1);+ assert!(!state.browser_controllers.lock().await.contains_key(&key), "its connections are gone from the cache");++ let ctrl2 = open_page(&state, &team, "c").await.expect("its next use reconnects");+ assert_eq!(eval(&ctrl2, "document.cookie").await, json!("kwnt_session=signed-in"), "its sign-in survived");+ assert_eq!(eval(&ctrl2, "document.title").await, json!("sign in"), "the same page, not a fresh one");+}+#[tokio::test]async fn in_local_mode_a_job_page_is_a_window_of_the_same_chrome_with_its_sign_ins() {if computer::local_chrome_path().is_none() {