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
Bot browser starts at most one kwant Chrome per profile
Lin (kwant bot)ee9e6bc3c596
diff --git a/src/sandbox/computer.rs b/src/sandbox/computer.rsindex 0cc2f684..e376263f 100644--- a/src/sandbox/computer.rs+++ b/src/sandbox/computer.rs@@ -230,10 +230,35 @@ pub async fn running_local_chrome(profile: &Path) -> Option<(String, bool)> {Some((endpoint, is_headless_user_agent(&agent)))}-/// Waits until the kwant Chrome on `profile` stops answering (it was asked to close).+/// The live process holding `profile`, from the `SingletonLock` link Chrome keeps in it+/// ("<host>-<pid>"). `None` when no Chrome holds it, or on Windows, which has no such link.+pub fn profile_owner(profile: &Path) -> Option<u32> {+ let target = std::fs::read_link(profile.join("SingletonLock")).ok()?;+ let pid: u32 = target.to_string_lossy().rsplit('-').next()?.parse().ok()?;+ pid_alive(pid).then_some(pid)+}++#[cfg(unix)]+fn pid_alive(pid: u32) -> bool {+ let Ok(pid) = i32::try_from(pid) else { return false };+ if pid <= 0 {+ return false;+ }+ // signal 0 only checks; EPERM means it exists under another user+ let found = unsafe { libc::kill(pid, 0) } == 0;+ found || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)+}++#[cfg(not(unix))]+fn pid_alive(_pid: u32) -> bool {+ false+}++/// Waits until the kwant Chrome on `profile` stops answering and its process lets go of the+/// profile (it was asked to close).pub async fn wait_local_chrome_gone(profile: &Path) -> Result<(), String> {for _ in 0..60 {- if running_local_chrome(profile).await.is_none() {+ if running_local_chrome(profile).await.is_none() && profile_owner(profile).is_none() {// Chrome drops its profile lock just after the port closestokio::time::sleep(Duration::from_millis(300)).await;return Ok(());@@ -243,9 +268,156 @@ pub async fn wait_local_chrome_gone(profile: &Path) -> Result<(), String> {Err("Chrome did not close within 15 seconds.".into())}-/// Launches the kwant Chrome on `profile` (detached, so it outlives a switch or a kwant restart)-/// and returns its CDP endpoint. The caller makes sure none is running on this profile.-pub async fn launch_local_chrome(profile: &Path, headless: bool) -> Result<String, String> {+/// How long [`ensure_chrome_with`] waits, and how often it looks.+#[derive(Clone, Copy)]+pub struct LaunchTiming {+ /// For a Chrome that holds the profile but does not answer yet (starting, or busy).+ pub owner: Duration,+ /// For the Chrome just started to open its debugging port.+ pub start: Duration,+ pub step: Duration,+}++impl Default for LaunchTiming {+ fn default() -> Self {+ Self { owner: Duration::from_secs(15), start: Duration::from_secs(20), step: Duration::from_millis(250) }+ }+}++type LaunchLocks = std::sync::Mutex<std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<()>>>>;++/// One launch at a time per profile in this process. Every caller (the Bot browser panel, its+/// stream, a bot's turn) goes through here, so they wait for the one Chrome instead of each+/// starting their own.+fn launch_lock(profile: &Path) -> std::sync::Arc<tokio::sync::Mutex<()>> {+ static LOCKS: std::sync::LazyLock<LaunchLocks> = std::sync::LazyLock::new(Default::default);+ LOCKS.lock().unwrap_or_else(|e| e.into_inner()).entry(profile.to_path_buf()).or_default().clone()+}++/// The Chrome found holding `profile` that did not answer within the owner wait, and when.+/// `set`: `Some(Some(pid))` records it, `Some(None)` clears it, `None` only reads.+fn unresponsive(profile: &Path, set: Option<Option<u32>>) -> Option<(u32, std::time::Instant)> {+ static STUCK: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<PathBuf, (u32, std::time::Instant)>>> =+ std::sync::LazyLock::new(Default::default);+ let mut stuck = STUCK.lock().unwrap_or_else(|e| e.into_inner());+ match set {+ Some(Some(pid)) => { stuck.insert(profile.to_path_buf(), (pid, std::time::Instant::now())); }+ Some(None) => { stuck.remove(profile); }+ None => {}+ }+ stuck.get(profile).copied()+}++/// The same across kwnt processes sharing a data folder: an advisory lock on a file next to the+/// profile, released when dropped (or when the process dies).+struct FileLock {+ _file: std::fs::File,+}++impl FileLock {+ async fn acquire(profile: &Path) -> Result<Self, String> {+ let path = profile.with_extension("launch.lock");+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;+ }+ let file = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&path)+ .map_err(|e| format!("Could not open {}: {e}", path.display()))?;+ #[cfg(unix)]+ {+ use std::os::unix::io::AsRawFd;+ for _ in 0..240 {+ if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {+ return Ok(Self { _file: file });+ }+ tokio::time::sleep(Duration::from_millis(250)).await;+ }+ Err("Another kwnt is still starting Chrome on this profile.".into())+ }+ #[cfg(not(unix))]+ Ok(Self { _file: file })+ }+}++/// The kwant Chrome on `profile`, started if none is: its CDP endpoint and whether it is+/// windowless. A running Chrome is reused whatever its form (the caller restarts it if it wants the+/// other one); `headless` only applies to a start.+pub async fn ensure_local_chrome(profile: &Path, headless: bool) -> Result<(String, bool), String> {+ ensure_chrome_with(+ profile,+ || running_local_chrome(profile),+ || launch_local_chrome(profile, headless),+ LaunchTiming::default(),+ )+ .await+}++/// [`ensure_local_chrome`] with the check and the start passed in, so tests can count starts.+///+/// Never starts a second Chrome on a profile a live Chrome holds: on macOS that second start hands+/// its arguments to the running one, which opens one more blank window each time. The stale+/// `DevToolsActivePort` is removed only once no process holds the profile, since removing a live+/// Chrome's port file left every later call unable to find it, so each one started another.+pub async fn ensure_chrome_with<'a, P, PF, S>(+ profile: &Path,+ probe: P,+ spawn: S,+ timing: LaunchTiming,+) -> Result<(String, bool), String>+where+ P: Fn() -> PF,+ PF: std::future::Future<Output = Option<(String, bool)>> + 'a,+ S: FnOnce() -> Result<(), String>,+{+ let lock = launch_lock(profile);+ let _in_process = lock.lock().await;+ let _across = FileLock::acquire(profile).await?;+ if let Some(found) = probe().await {+ unresponsive(profile, Some(None));+ return Ok(found);+ }+ if let Some(pid) = profile_owner(profile) {+ // callers queued behind one that already waited the full time for this Chrome look once+ // and give up, instead of each waiting again+ let known_stuck = unresponsive(profile, None).is_some_and(|(p, at)| p == pid && at.elapsed() < timing.owner);+ let deadline = tokio::time::Instant::now() + if known_stuck { Duration::ZERO } else { timing.owner };+ loop {+ if let Some(found) = probe().await {+ unresponsive(profile, Some(None));+ return Ok(found);+ }+ if profile_owner(profile).is_none() {+ break; // it closed: start a fresh one below+ }+ if tokio::time::Instant::now() >= deadline {+ if !known_stuck {+ unresponsive(profile, Some(Some(pid)));+ }+ return Err(format!(+ "kwant's Chrome (process {pid}) is open but not answering, so kwant did not start another. \+ Quit that Chrome (Cmd+Q on a Mac) and try again."+ ));+ }+ tokio::time::sleep(timing.step).await;+ }+ }+ // nothing holds the profile, so a port file left behind points at nothing+ let _ = std::fs::remove_file(profile.join("DevToolsActivePort"));+ spawn()?;+ let deadline = tokio::time::Instant::now() + timing.start;+ loop {+ if let Some(found) = probe().await {+ return Ok(found);+ }+ if tokio::time::Instant::now() >= deadline {+ return Err("Chrome started but did not open its debugging port in time.".into());+ }+ tokio::time::sleep(timing.step).await;+ }+}++/// Starts the kwant Chrome on `profile`, detached, so it outlives a switch or a kwant restart.+/// Only [`ensure_local_chrome`] calls this, once no Chrome holds the profile.+fn launch_local_chrome(profile: &Path, headless: bool) -> Result<(), String> {let chrome = local_chrome_path().ok_or_else(|| local_reason().unwrap_or_default())?;if !headless {if let Some(reason) = window_reason() {@@ -253,8 +425,6 @@ pub async fn launch_local_chrome(profile: &Path, headless: bool) -> Result<Strin}}std::fs::create_dir_all(profile).map_err(|e| e.to_string())?;- // a stale port file from a closed Chrome would point at nothing- let _ = std::fs::remove_file(profile.join("DevToolsActivePort"));let mut cmd = std::process::Command::new(&chrome);cmd.args(chrome_args(profile, headless)).stdin(std::process::Stdio::null())@@ -269,17 +439,12 @@ pub async fn launch_local_chrome(profile: &Path, headless: bool) -> Result<Strinlet mut child = cmd.spawn().map_err(|e| format!("Could not start {}: {e}", chrome.display()))?;+ tracing::info!(pid = child.id(), headless, profile = %profile.display(), "started kwant's local Chrome");// reap it when it exits; never kill itstd::thread::spawn(move || {let _ = child.wait();});- for _ in 0..80 {- if let Some((endpoint, _)) = running_local_chrome(profile).await {- return Ok(endpoint);- }- tokio::time::sleep(Duration::from_millis(250)).await;- }- Err("Chrome started but did not open its debugging port within 20 seconds.".into())+ Ok(())}#[cfg(test)]@@ -433,4 +598,151 @@ mod tests {std::fs::write(dir.path().join("DevToolsActivePort"), "0\n").unwrap();assert_eq!(read_devtools_port(dir.path()), None);}++ fn fast() -> LaunchTiming {+ LaunchTiming {+ owner: Duration::from_millis(400),+ start: Duration::from_secs(5),+ step: Duration::from_millis(20),+ }+ }++ /// A pid that is not running: a child that already exited and was reaped.+ fn dead_pid() -> u32 {+ let mut child = std::process::Command::new("true").spawn().unwrap();+ let pid = child.id();+ child.wait().unwrap();+ pid+ }++ #[cfg(unix)]+ fn hold_profile(profile: &Path, pid: u32) {+ std::os::unix::fs::symlink(format!("host-{pid}"), profile.join("SingletonLock")).unwrap();+ }++ #[cfg(unix)]+ #[test]+ fn profile_owner_reads_chromes_singleton_lock() {+ let dir = tempfile::tempdir().unwrap();+ assert_eq!(profile_owner(dir.path()), None);+ hold_profile(dir.path(), std::process::id());+ assert_eq!(profile_owner(dir.path()), Some(std::process::id()));+ std::fs::remove_file(dir.path().join("SingletonLock")).unwrap();+ hold_profile(dir.path(), dead_pid());+ assert_eq!(profile_owner(dir.path()), None);+ }++ /// The Bot browser button, its stream and a bot's turn all asking at once start one Chrome.+ #[tokio::test]+ async fn concurrent_launches_start_one_chrome() {+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};+ use std::sync::Arc;+ let dir = tempfile::tempdir().unwrap();+ let profile = dir.path().join("local-chrome");+ let spawns = Arc::new(AtomicUsize::new(0));+ let up = Arc::new(AtomicBool::new(false));+ let mut calls = Vec::new();+ for _ in 0..10 {+ let (profile, spawns, up) = (profile.clone(), spawns.clone(), up.clone());+ calls.push(tokio::spawn(async move {+ let probe = || {+ let up = up.clone();+ async move { up.load(SeqCst).then(|| ("http://127.0.0.1:9".to_string(), true)) }+ };+ let spawn = || {+ spawns.fetch_add(1, SeqCst);+ let up = up.clone();+ // Chrome takes a moment to open its port+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(150)).await;+ up.store(true, SeqCst);+ });+ Ok(())+ };+ ensure_chrome_with(&profile, probe, spawn, fast()).await+ }));+ }+ for call in calls {+ assert!(call.await.unwrap().is_ok());+ }+ assert_eq!(spawns.load(SeqCst), 1);+ }++ /// A live Chrome that holds the profile but does not answer (its port file stale or gone) is+ /// never started again, and its port file is left alone.+ #[cfg(unix)]+ #[tokio::test]+ async fn stale_port_file_with_live_chrome_does_not_start_another() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(dir.path().join("DevToolsActivePort"), "1\n/devtools/browser/x\n").unwrap();+ hold_profile(dir.path(), std::process::id());+ let mut spawned = false;+ let result = ensure_chrome_with(dir.path(), || async { None }, || { spawned = true; Ok(()) }, fast()).await;+ let error = result.unwrap_err();+ assert!(!spawned);+ assert!(error.contains("did not start another"), "{error}");+ assert!(dir.path().join("DevToolsActivePort").exists());+ }++ /// Clicks queued behind one that waited the full time for a stuck Chrome give up at once.+ #[cfg(unix)]+ #[tokio::test]+ async fn callers_behind_a_stuck_chrome_do_not_each_wait() {+ let dir = tempfile::tempdir().unwrap();+ hold_profile(dir.path(), std::process::id());+ let timing = LaunchTiming { owner: Duration::from_secs(2), ..fast() };+ let first = std::time::Instant::now();+ assert!(ensure_chrome_with(dir.path(), || async { None }, || Ok(()), timing).await.is_err());+ assert!(first.elapsed() >= Duration::from_secs(2));+ let again = std::time::Instant::now();+ let error = ensure_chrome_with(dir.path(), || async { None }, || Ok(()), timing).await.unwrap_err();+ assert!(again.elapsed() < Duration::from_millis(500), "{:?}", again.elapsed());+ assert!(error.contains("did not start another"), "{error}");+ // once it answers it is used, and forgotten as stuck+ let found = ensure_chrome_with(dir.path(), || async { Some(("u".to_string(), true)) }, || Ok(()), timing).await;+ assert_eq!(found.unwrap().0, "u");+ assert!(unresponsive(dir.path(), None).is_none());+ }++ /// The same live Chrome that answers once it has started is reused, not started again.+ #[cfg(unix)]+ #[tokio::test]+ async fn starting_chrome_is_waited_for() {+ use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};+ let dir = tempfile::tempdir().unwrap();+ hold_profile(dir.path(), std::process::id());+ let probes = AtomicUsize::new(0);+ let probe = || {+ let n = probes.fetch_add(1, SeqCst);+ async move { (n >= 3).then(|| ("http://127.0.0.1:9".to_string(), false)) }+ };+ let mut spawned = false;+ let found = ensure_chrome_with(dir.path(), probe, || { spawned = true; Ok(()) }, fast()).await.unwrap();+ assert!(!spawned);+ assert_eq!(found, ("http://127.0.0.1:9".to_string(), false));+ }++ /// A port file left by a Chrome that is gone is removed and one fresh Chrome starts.+ #[cfg(unix)]+ #[tokio::test]+ async fn stale_port_file_with_dead_chrome_starts_one() {+ let dir = tempfile::tempdir().unwrap();+ let port_file = dir.path().join("DevToolsActivePort");+ std::fs::write(&port_file, "1\n").unwrap();+ hold_profile(dir.path(), dead_pid());+ let up = std::sync::atomic::AtomicBool::new(false);+ let probe = || {+ let found = up.load(std::sync::atomic::Ordering::SeqCst);+ async move { found.then(|| ("http://127.0.0.1:9".to_string(), true)) }+ };+ let mut spawns = 0;+ let result = ensure_chrome_with(dir.path(), probe, || {+ assert!(!port_file.exists(), "the stale port file goes before the start");+ spawns += 1;+ up.store(true, std::sync::atomic::Ordering::SeqCst);+ Ok(())+ }, fast()).await;+ assert!(result.is_ok());+ assert_eq!(spawns, 1);+ }}diff --git a/src/sandbox/service.rs b/src/sandbox/service.rsindex 7363894a..517e5e60 100644--- a/src/sandbox/service.rs+++ b/src/sandbox/service.rs@@ -82,13 +82,21 @@ impl BrowserService {let live: Vec<(String, bool)> = live["targetInfos"].as_array().into_iter().flatten().filter_map(|t| Some((t["targetId"].as_str()?.to_string(), t["type"] == "page" && t["url"] == "about:blank"))).collect();- for session in state.sessions.values_mut() {+ // Reopen only the pages that showed a site. A blank page would be one more empty window+ // per bot that ever used the browser; its bot gets a new one when it next asks.+ let mut dropped = Vec::new();+ for (bot, session) in state.sessions.iter_mut() {if live.iter().any(|(id, _)| *id == session.target) { continue; }- let url = urls.get(&session.target).filter(|u| u.starts_with("http")).map_or("about:blank", |u| u.as_str());- if let Ok(target) = state.browser.send_cdp_command("Target.createTarget", json!({"url": url, "newWindow": true})).await {- if let Some(id) = target["targetId"].as_str() { session.target = id.to_string(); }+ let Some(url) = urls.get(&session.target).filter(|u| u.starts_with("http")) else {+ dropped.push(bot.clone());+ continue;+ };+ match state.browser.send_cdp_command("Target.createTarget", json!({"url": url, "newWindow": true})).await {+ Ok(target) => if let Some(id) = target["targetId"].as_str() { session.target = id.to_string(); },+ Err(_) => dropped.push(bot.clone()),}}+ for bot in dropped { state.sessions.remove(&bot); }// Chrome's own blank start window would sit on top of the bots' pages in the windowif visible && !state.sessions.is_empty() {for (id, _) in live.iter().filter(|(id, blank)| *blank && !state.sessions.values().any(|s| s.target == *id)) {@@ -104,14 +112,16 @@ impl BrowserService {async fn local_endpoint(&self) -> Result<String, BrowserError> {let profile = self.local_profile();let headless = !self.local_window();- if let Some((endpoint, running_headless)) = computer::running_local_chrome(&profile).await {- if running_headless == headless { return Ok(endpoint); }- // the other form is running on this profile: close it first- let _ = BrowserController::at_endpoint(&endpoint, None, true)- .send_cdp_command("Browser.close", json!({})).await;- computer::wait_local_chrome_gone(&profile).await.map_err(BrowserError::Http)?;- }- computer::launch_local_chrome(&profile, headless).await.map_err(BrowserError::Http)+ // at most one kwant Chrome per profile: reuse it, or wait for the one starting+ let (endpoint, running_headless) = computer::ensure_local_chrome(&profile, headless).await+ .map_err(BrowserError::Http)?;+ if running_headless == headless { return Ok(endpoint); }+ // the other form is running on this profile: close it first+ let _ = BrowserController::at_endpoint(&endpoint, None, true)+ .send_cdp_command("Browser.close", json!({})).await;+ computer::wait_local_chrome_gone(&profile).await.map_err(BrowserError::Http)?;+ let (endpoint, _) = computer::ensure_local_chrome(&profile, headless).await.map_err(BrowserError::Http)?;+ Ok(endpoint)}async fn save_sessions(&self, sessions: &HashMap<String, SessionTarget>) -> Result<(), BrowserError> {diff --git a/tests/local_chrome_test.rs b/tests/local_chrome_test.rsindex 02a85778..c0288aa6 100644--- a/tests/local_chrome_test.rs+++ b/tests/local_chrome_test.rs@@ -88,13 +88,16 @@ async fn local_chrome_runs_windowless_and_can_open_as_a_window() {assert!(service.local_window());let (_, headless) = computer::running_local_chrome(&profile).await.expect("chrome running");assert!(!headless, "the window form must be a real window");- // only the two bots' pages are open: Chrome's blank start window is not left on top+ // only the bot's real page is open: Chrome's blank start window is not left on top, and+ // the other bot's never-used blank page is not reopened as a window of its ownlet (endpoint, _) = computer::running_local_chrome(&profile).await.unwrap();let browser = kwnt::sandbox::BrowserController::at_endpoint(&endpoint, None, true);let targets = browser.send_cdp_command("Target.getTargets", serde_json::json!({})).await.unwrap();let pages: Vec<_> = targets["targetInfos"].as_array().unwrap().iter().filter(|t| t["type"] == "page").map(|t| t["url"].as_str().unwrap_or("").to_string()).collect();- assert_eq!(pages.len(), 2, "pages in the window form: {pages:?}");+ assert_eq!(pages, vec![url.clone()], "pages in the window form");+ // the other bot still gets a page when it asks for one+ service.session("other", tmp.path()).await.expect("other bot's page on demand");// the bot's page was reopened therelet ctrl = service.session("bot", tmp.path()).await.unwrap();ctrl.refresh_location().await.unwrap();