Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

0.9.3: each job gets its own browser page; a sign-in holds only its page (#531)

Oleksandr Ivanchenko7e7d63b715a9
diff --git a/src/db/human_steps.rs b/src/db/human_steps.rs
index 1567e5c7..58a13f7d 100644
--- a/src/db/human_steps.rs
+++ b/src/db/human_steps.rs
@@ -46,6 +46,11 @@ pub struct HumanStep {
pub message_id: Option<String>,
pub created_at: DateTime<Utc>,
pub closed_at: Option<DateTime<Utc>>,
+ /// The page of the bot browser the step holds: a job's own page
+ /// (`team#bot#chat`, see `server::browser_pages`) or the team page. `NULL` on steps saved
+ /// before pages existed, which held the team page ([`Self::page`]).
+ #[sqlx(default)]
+ pub page_key: Option<String>,
}
fn target_object<S: serde::Serializer>(target: &Option<String>, s: S) -> Result<S::Ok, S::Error> {
@@ -54,6 +59,12 @@ fn target_object<S: serde::Serializer>(target: &Option<String>, s: S) -> Result<
}
impl HumanStep {
+ /// The page this step holds: its own page key, else (a step saved before job pages) the
+ /// team page, which is the sandbox target itself.
+ pub fn page(&self) -> Option<&str> {
+ self.page_key.as_deref().or(self.sandbox_target.as_deref())
+ }
+
/// The chat id the step was asked in: channel, thread or the direct chat's kwant.
pub fn context_id(&self) -> String {
self.channel_id
@@ -137,6 +148,8 @@ pub struct HumanStepPlace {
pub thread_id: Option<String>,
pub turn_id: Option<String>,
pub sandbox_target: Option<String>,
+ /// The page it holds; `None` is the team page (`sandbox_target`).
+ pub page_key: Option<String>,
}
/// A new step (with `true`), or one already open that the ask gets back (with `false`): the
@@ -169,7 +182,8 @@ const CREATE_HUMAN_STEPS: &str = "CREATE TABLE IF NOT EXISTS human_steps (
status TEXT NOT NULL CHECK (status IN ('open', 'done', 'declined', 'cancelled', 'resolved_auto', 'timed_out')),
message_id TEXT,
created_at TIMESTAMP NOT NULL,
- closed_at TIMESTAMP
+ closed_at TIMESTAMP,
+ page_key TEXT
)";
impl Database {
@@ -192,6 +206,13 @@ impl Database {
sqlx::query("DROP TABLE human_steps_old").execute(&mut *tx).await?;
tx.commit().await?;
}
+ // 0.9.3: the page a step holds (additive; older rows keep NULL, the team page)
+ let has_page: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pragma_table_info('human_steps') WHERE name = 'page_key'")
+ .fetch_one(&self.pool)
+ .await?;
+ if has_page == 0 {
+ sqlx::query("ALTER TABLE human_steps ADD COLUMN page_key TEXT").execute(&self.pool).await?;
+ }
sqlx::query("CREATE INDEX IF NOT EXISTS human_steps_by_status ON human_steps (status, kwant_id)").execute(&self.pool).await?;
Ok(())
}
@@ -219,8 +240,8 @@ impl Database {
// Writes first so the transaction holds SQLite's write lock before it reads
let id = Uuid::new_v4().to_string();
let inserted = sqlx::query(&format!(
- "INSERT INTO human_steps (id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, kind, reason, url, sandbox_target, source, status, created_at, target)
- SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'open', ?12, ?14
+ "INSERT INTO human_steps (id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, kind, reason, url, sandbox_target, source, status, created_at, target, page_key)
+ SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'open', ?12, ?14, ?16
WHERE (SELECT COUNT(*) FROM human_steps WHERE kwant_id = ?2 AND status = 'open') < ?13
AND NOT EXISTS (SELECT 1 FROM human_steps WHERE status = 'open' AND ?6 IS NOT NULL AND turn_id = ?6)
AND NOT EXISTS (SELECT 1 FROM human_steps WHERE {})",
@@ -241,6 +262,7 @@ impl Database {
.bind(MAX_OPEN_PER_KWANT)
.bind(target)
.bind(&site)
+ .bind(&place.page_key)
.execute(&mut *tx)
.await?;
if inserted.rows_affected() == 0 {
@@ -322,10 +344,12 @@ impl Database {
.await?)
}
- /// Whether a step is open in this bot browser (it stays the person's until then).
- pub async fn human_step_open_in(&self, sandbox_target: &str) -> Result<bool, DbError> {
- let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM human_steps WHERE status = 'open' AND sandbox_target = ?")
- .bind(sandbox_target)
+ /// Whether a step is open on this browser page (it stays the person's until then): a job's
+ /// page key, or a sandbox target for its team page. A step saved before job pages (no
+ /// `page_key`) holds its team page.
+ pub async fn human_step_open_on(&self, page: &str) -> Result<bool, DbError> {
+ let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM human_steps WHERE status = 'open' AND COALESCE(page_key, sandbox_target) = ?")
+ .bind(page)
.fetch_one(&self.pool)
.await?;
Ok(n > 0)
@@ -385,7 +409,7 @@ mod tests {
let (s, new, _) = db.create_human_step_with_card(&place("t1"), "sign_in", "Log in", None, None, "bot", |_| None).await.unwrap();
assert!(new);
assert_eq!(s.context_id(), "k");
- assert!(db.human_step_open_in("k").await.unwrap());
+ assert!(db.human_step_open_on("k").await.unwrap());
let (again, new, _) = db.create_human_step_with_card(&place("t1"), "captcha", "Solve", None, None, "auto", |_| None).await.unwrap();
assert!(!new);
assert_eq!(again.id, s.id);
@@ -395,7 +419,7 @@ mod tests {
let closed = db.get_human_step(&s.id).await.unwrap().unwrap();
assert_eq!(closed.status, "done");
assert!(closed.closed_at.is_some());
- assert!(!db.human_step_open_in("k").await.unwrap());
+ assert!(!db.human_step_open_on("k").await.unwrap());
for i in 0..MAX_OPEN_PER_KWANT {
db.create_human_step_with_card(&place(&format!("t{}", i + 10)), "other", "Do it", None, None, "bot", |_| None).await.unwrap();
}
@@ -487,4 +511,45 @@ mod tests {
assert!(db.close_human_step(&s.id, "timed_out").await.unwrap());
assert!(serde_json::to_value(db.get_human_step(&s.id).await.unwrap().unwrap()).unwrap()["target"].is_null());
}
+
+ /// 0.9.3: a step holds only its own page; a step saved before pages (no page key, as an
+ /// older kwnt left it) holds its team page, and a table from before the column gains it.
+ #[tokio::test]
+ async fn a_step_holds_its_page_and_old_steps_hold_the_team_page() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ // a table as 0.9.2 left it: no page_key column, one open step on team "t"
+ sqlx::query("DROP TABLE human_steps").execute(&db.pool).await.unwrap();
+ sqlx::query(&CREATE_HUMAN_STEPS.replace(",\n page_key TEXT", "")).execute(&db.pool).await.unwrap();
+ sqlx::query("INSERT INTO human_steps (id, kwant_id, kind, reason, sandbox_target, source, status, created_at) VALUES ('old', 'k', 'sign_in', 'Log in', 't', 'bot', 'open', ?)")
+ .bind(Utc::now()).execute(&db.pool).await.unwrap();
+ // Migrate the way kwnt starts: reopen, so the one-connection migration pool runs it. Changing
+ // the table under this test's runtime pool would leave another pooled connection with a
+ // `SELECT *` column list from before (sqlx's index-out-of-bounds panic, then None).
+ db.pool.close().await;
+ let db = Database::init(tmp.path()).await.unwrap();
+ let old = db.get_human_step("old").await.unwrap().unwrap();
+ assert_eq!(old.page_key, None);
+ assert_eq!(old.page(), Some("t"), "an old step holds its team page");
+ assert!(db.human_step_open_on("t").await.unwrap());
+ assert!(!db.human_step_open_on("t#k#chat").await.unwrap(), "a job page is free while the team page is held");
+ assert!(db.close_human_step("old", "done").await.unwrap());
+ // a job's step holds that job's page only
+ let place = HumanStepPlace {
+ kwant_id: "k".into(),
+ thread_id: Some("chat".into()),
+ turn_id: Some("turn".into()),
+ sandbox_target: Some("t".into()),
+ page_key: Some("t#k#chat".into()),
+ ..Default::default()
+ };
+ let (s, _, _) = db.create_human_step_with_card(&place, "sign_in", "Log in", None, None, "bot", |_| None).await.unwrap();
+ assert_eq!(s.page(), Some("t#k#chat"));
+ assert!(db.human_step_open_on("t#k#chat").await.unwrap());
+ assert!(!db.human_step_open_on("t").await.unwrap(), "the team page stays free");
+ assert!(!db.human_step_open_on("t#k#other").await.unwrap());
+ // migrating again changes nothing
+ db.migrate_human_steps().await.unwrap();
+ assert_eq!(db.get_human_step(&s.id).await.unwrap().unwrap().page_key.as_deref(), Some("t#k#chat"));
+ }
}
diff --git a/src/sandbox/service.rs b/src/sandbox/service.rs
index 0fbbfa7b..51f15244 100644
--- a/src/sandbox/service.rs
+++ b/src/sandbox/service.rs
@@ -15,6 +15,26 @@ 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");
+/// Joins a job page's key: `team#bot#chat` (see [`job_page_key`]).
+pub const PAGE_SEP: char = '#';
+
+/// The key of a job's own page in its team's browser: one page per (sandbox target, bot, chat).
+/// `None` when a part is empty or holds [`PAGE_SEP`] (such a job uses the team page).
+pub fn job_page_key(team: &str, kwant: &str, chat: &str) -> Option<String> {
+ let ok = |p: &str| !p.is_empty() && !p.contains(PAGE_SEP);
+ (ok(team) && ok(kwant) && ok(chat)).then(|| format!("{team}{PAGE_SEP}{kwant}{PAGE_SEP}{chat}"))
+}
+
+/// The team (sandbox target) a page belongs to: the key itself for the team page.
+pub fn page_team(key: &str) -> &str {
+ key.split(PAGE_SEP).next().unwrap_or(key)
+}
+
+/// Whether this key names a job's own page rather than a team page.
+pub fn is_job_page(key: &str) -> bool {
+ key.contains(PAGE_SEP)
+}
+
#[derive(Clone, Serialize, Deserialize)]
struct SessionTarget {
context: String,
@@ -38,6 +58,10 @@ pub struct BrowserService {
last_use: std::sync::Mutex<Option<std::time::SystemTime>>,
/// Local mode without Chrome: the private browser kwnt downloads on first use (O5).
chrome_setup: std::sync::Arc<ChromeSetup>,
+ /// When each page (team or job page) was last used in this run: the job-page cap closes the
+ /// 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>>,
}
struct ServiceState {
@@ -54,6 +78,7 @@ impl BrowserService {
local_window: std::sync::atomic::AtomicBool::new(false), state: Mutex::new(None),
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(),
}
}
@@ -377,6 +402,18 @@ impl BrowserService {
}
pub async fn session(&self, id: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {
+ self.open(id, workspace).await
+ }
+
+ /// A job's own page ([`job_page_key`]): a new page in its team's browser context, so the
+ /// team's sign-ins and cookies are shared, opened in a window of its own in local mode. It
+ /// is kept across restarts like a team page. The team page is opened first if needed (its
+ /// context is the one shared).
+ pub async fn page_session(&self, key: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {
+ self.open(key, workspace).await
+ }
+
+ async fn open(&self, id: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {
let result = match self.ensure_private_browser().await {
Ok(()) => self.open_session(id, workspace).await,
Err(e) => Err(e),
@@ -409,7 +446,11 @@ impl BrowserService {
let existing = state.sessions.get(id).filter(|session| targets["targetInfos"].as_array()
.is_some_and(|targets| targets.iter().any(|target| target["targetId"] == session.target)));
let local = self.mode() == ComputerMode::Local;
- let fresh_context = existing.is_none() && !local;
+ let alive = |target: &str| targets["targetInfos"].as_array()
+ .is_some_and(|targets| targets.iter().any(|t| t["targetId"] == target));
+ let team = page_team(id);
+ let job = is_job_page(id);
+ let mut fresh_context = existing.is_none() && !local;
let session = if let Some(existing) = existing { existing.clone() } else if local {
// Local pages share the kwant profile's default context, so a sign-in in the window
// is kept. (`context` stays empty.) Each bot gets its own window, not a tab: Chrome
@@ -417,32 +458,36 @@ impl BrowserService {
let target = state.browser.send_cdp_command("Target.createTarget", json!({"url": "about:blank", "newWindow": true})).await?;
SessionTarget { context: String::new(), target: target["targetId"].as_str()
.ok_or_else(|| BrowserError::Protocol("Browser page missing".into()))?.to_string() }
- } else {
- // Do not dispose on detach: contexts survive a Kwnt server restart.
- let context = state.browser.send_cdp_command("Target.createBrowserContext", json!({"disposeOnDetach": false})).await?;
- let context = context["browserContextId"].as_str()
- .ok_or_else(|| BrowserError::Protocol("Browser context missing".into()))?.to_string();
- let target = state.browser.send_cdp_command("Target.createTarget", json!({
- "url": "about:blank", "browserContextId": context
- })).await;
- let target = match target {
- Ok(target) => target,
- Err(error) => {
- let _ = state.browser.send_cdp_command("Target.disposeBrowserContext", json!({"browserContextId": context})).await;
- return Err(error);
+ } else if job {
+ // A job page: a new page in the team's context (the team page's), never a context of
+ // its own, so a sign-in made on any page of the team holds on all of them. In a window
+ // of its own, as in local mode: a second tab would leave the page behind it unpainted,
+ // and its screenshots (so every navigation) would hang until the 15 s timeout.
+ let team_session = state.sessions.get(team).filter(|s| alive(&s.target)).cloned();
+ let context = match team_session {
+ Some(team_session) => { fresh_context = false; team_session.context }
+ None => {
+ let team_session = Self::new_context_page(&state.browser).await?;
+ state.sessions.insert(team.to_string(), team_session.clone());
+ team_session.context
}
};
+ let target = state.browser.send_cdp_command("Target.createTarget", json!({
+ "url": "about:blank", "browserContextId": context, "newWindow": true
+ })).await?;
SessionTarget { context, target: target["targetId"].as_str()
.ok_or_else(|| BrowserError::Protocol("Browser page missing".into()))?.to_string() }
+ } else {
+ Self::new_context_page(&state.browser).await?
};
state.sessions.insert(id.to_string(), session.clone());
self.save_sessions(&state.sessions).await?;
let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target), false);
if !local {
// The VM browser's profile is on tmpfs, so its contexts' cookies go when the
- // container restarts: keep them per bot in the data folder (local mode's on-disk
- // profile already keeps them).
- ctrl.set_cookie_jar(Some(self.cookie_jar(id)));
+ // container restarts: keep them per team in the data folder (local mode's on-disk
+ // profile already keeps them). A job page shares its team's context, so its jar.
+ ctrl.set_cookie_jar(Some(self.cookie_jar(team)));
if fresh_context {
let restored = ctrl.restore_cookies().await;
if restored > 0 { tracing::debug!("Restored {} browser cookies for {}", restored, id); }
@@ -456,6 +501,85 @@ impl BrowserService {
Ok(ctrl)
}
+ /// A new browser context (VM mode) with one blank page in it.
+ async fn new_context_page(browser: &BrowserController) -> Result<SessionTarget, BrowserError> {
+ {
+ // Do not dispose on detach: contexts survive a Kwnt server restart.
+ let context = browser.send_cdp_command("Target.createBrowserContext", json!({"disposeOnDetach": false})).await?;
+ let context = context["browserContextId"].as_str()
+ .ok_or_else(|| BrowserError::Protocol("Browser context missing".into()))?.to_string();
+ let target = browser.send_cdp_command("Target.createTarget", json!({
+ "url": "about:blank", "browserContextId": context
+ })).await;
+ let target = match target {
+ Ok(target) => target,
+ Err(error) => {
+ let _ = browser.send_cdp_command("Target.disposeBrowserContext", json!({"browserContextId": context})).await;
+ return Err(error);
+ }
+ };
+ Ok(SessionTarget { context, target: target["targetId"].as_str()
+ .ok_or_else(|| BrowserError::Protocol("Browser page missing".into()))?.to_string() })
+ }
+ }
+
+ /// 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());
+ }
+
+ /// Forgets a job page's use when it couldn't open (no room, or the browser failed), so it
+ /// isn't counted as one of its team's pages.
+ pub fn forget_page(&self, key: &str) {
+ if is_job_page(key) {
+ self.page_use.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
+ }
+ }
+
+ /// When a page was last used in this run, if it was.
+ pub fn page_used_at(&self, key: &str) -> Option<std::time::Instant> {
+ self.page_use.lock().unwrap_or_else(|e| e.into_inner()).get(key).copied()
+ }
+
+ /// The team's job pages that are open (or kept from an earlier run), each with when it was
+ /// last used, oldest first. A kept page this run hasn't used yet counts as used now.
+ pub async fn job_pages(&self, team: &str) -> Vec<(String, std::time::Instant)> {
+ let prefix = format!("{team}{PAGE_SEP}");
+ let mut keys: Vec<String> = match self.state.lock().await.as_ref() {
+ Some(state) => state.sessions.keys().filter(|k| k.starts_with(&prefix)).cloned().collect(),
+ None => Vec::new(),
+ };
+ let mut use_ = self.page_use.lock().unwrap_or_else(|e| e.into_inner());
+ keys.extend(use_.keys().filter(|k| k.starts_with(&prefix)).cloned());
+ keys.sort();
+ keys.dedup();
+ let now = std::time::Instant::now();
+ let mut pages: Vec<(String, std::time::Instant)> = keys.into_iter()
+ .map(|k| { let at = *use_.entry(k.clone()).or_insert(now); (k, at) }).collect();
+ pages.sort_by_key(|(_, at)| *at);
+ pages
+ }
+
+ /// Every page this run knows of (team and job pages), with when it was last used.
+ pub fn pages_in_use(&self) -> Vec<(String, std::time::Instant)> {
+ self.page_use.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|(k, at)| (k.clone(), *at)).collect()
+ }
+
+ /// Closes a job's page. Its team's context and sign-ins stay; the next call from that job
+ /// opens a new page.
+ 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);
+ let mut lock = self.state.lock().await;
+ if let Some(state) = lock.as_mut() {
+ 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?;
+ }
+ }
+ Ok(())
+ }
+
/// 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();
@@ -463,8 +587,12 @@ impl BrowserService {
}
pub async fn reset(&self, id: &str) -> Result<(), BrowserError> {
+ // a job page shares its team's context: resetting it only closes it
+ if is_job_page(id) { return self.close_page(id).await; }
// A reset is a clean slate, including the saved sign-ins
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));
let mut lock = self.state.lock().await;
if lock.is_none() && self.sessions_file().exists() {
*lock = Some(self.connect().await?);
@@ -478,6 +606,14 @@ impl BrowserService {
state.browser.send_cdp_command("Target.disposeBrowserContext", json!({"browserContextId": session.context})).await?;
}
}
+ // the team's job pages go with it (in the VM they were in the context just disposed)
+ let jobs: Vec<String> = state.sessions.keys().filter(|k| k.starts_with(&prefix)).cloned().collect();
+ for key in jobs {
+ 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?;
}
Ok(())
}
diff --git a/src/serve.rs b/src/serve.rs
index 593d77df..48a023ff 100644
--- a/src/serve.rs
+++ b/src/serve.rs
@@ -76,6 +76,8 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(
// browser containers left by this or another kwant: remove orphans, stop idle ones
let browser = state.browser_service.clone();
browser.clone().spawn_reaper(cancel.clone());
+ // each job's own browser page: closed once idle past its limit (never one a step holds)
+ crate::server::browser_pages::spawn_sweeper(state.clone(), cancel.clone());
// Claude's VM containers: remove ones a previous run left, then idle ones (Linux only)
if crate::sandbox::agent_vm::supported_os().is_ok() {
state.agent_vm.start_reaper();
diff --git a/src/server/browser_pages.rs b/src/server/browser_pages.rs
new file mode 100644
index 00000000..7f6c2e42
--- /dev/null
+++ b/src/server/browser_pages.rs
@@ -0,0 +1,295 @@
+//! One browser page per job (0.9.3). A team's bots shared one page, so a sign-in the person was
+//! asked to do on it (a held page) stopped every other job of the team. Now a bot turn in a chat
+//! gets its own page, keyed by (sandbox target, bot, chat): a new page in the team's existing
+//! browser context, so sign-ins and cookies are shared, while a hold for the person's step holds
+//! only the page it was asked on. The person's panel and calls that name no chat keep the team
+//! page, whose key is the sandbox target itself.
+//!
+//! Limits: at most [`MAX_JOB_PAGES_PER_TEAM`] job pages per team (the least recently used idle
+//! one is closed to make room) and a job page nobody used for [`JOB_PAGE_IDLE`] is closed. A
+//! page with an open step, one the person is driving, or one whose job (bot and chat) still has
+//! 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`].
+
+use super::continuity::SelfScope;
+use super::AppState;
+use axum::{extract::{Path, State}, Json};
+use serde_json::{json, Value};
+use std::{
+ collections::HashMap,
+ sync::{
+ atomic::{AtomicU64, Ordering},
+ Arc,
+ },
+ time::{Duration, Instant},
+};
+
+pub use crate::sandbox::service::{is_job_page, job_page_key, page_team, PAGE_SEP};
+
+/// 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).
+pub const JOB_PAGE_IDLE: Duration = Duration::from_secs(30 * 60);
+/// How often idle job pages are looked for.
+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);
+
+/// 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 {
+ format!(
+ "All {MAX_JOB_PAGES_PER_TEAM} of this team's browser pages are in use by other jobs. \
+ Try again in a minute; nothing is wrong with the browser."
+ )
+}
+
+/// Opening job pages: one lock per team, so making room and opening the page happen as one
+/// step, and how long a bot call waits for room.
+#[derive(Default)]
+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,
+}
+
+impl JobPages {
+ /// The lock held while a page of `team` is made room for and opened, or closed.
+ pub fn team_lock(&self, team: &str) -> Arc<tokio::sync::Mutex<()>> {
+ self.opening.lock().unwrap_or_else(|e| e.into_inner()).entry(team.to_string()).or_default().clone()
+ }
+
+ /// Tests: a shorter wait for room than [`PAGE_WAIT`].
+ pub fn set_wait(&self, wait: Duration) {
+ self.wait_ms.store((wait.as_millis() as u64).max(1), Ordering::Relaxed);
+ }
+
+ pub fn wait(&self) -> Duration {
+ match self.wait_ms.load(Ordering::Relaxed) {
+ 0 => PAGE_WAIT,
+ ms => Duration::from_millis(ms),
+ }
+ }
+}
+
+/// A job page's team, bot and chat; `None` for the team page.
+pub fn job_of(key: &str) -> Option<(&str, &str, &str)> {
+ let mut parts = key.splitn(3, PAGE_SEP);
+ match (parts.next(), parts.next(), parts.next()) {
+ (Some(team), Some(kwant), Some(chat)) => Some((team, kwant, chat)),
+ _ => None,
+ }
+}
+
+/// The page a turn's browser calls use: the job's own page when the turn runs in a chat
+/// ([`super::human_steps::chat_key`], the same chat the bot's browser address names), else the
+/// team page. `None` when the turn has no bot browser.
+pub fn scope_page(scope: &SelfScope) -> Option<String> {
+ let team = scope.sandbox_target.as_deref()?;
+ Some(
+ super::human_steps::chat_key(scope)
+ .and_then(|chat| job_page_key(team, &scope.kwant_id, &chat))
+ .unwrap_or_else(|| team.to_string()),
+ )
+}
+
+/// The page a call on the bot browser API uses: the chat route's job page, else (the plain route,
+/// or a bot route without a chat) the team page.
+pub fn call_page(team: &str, kwant: Option<&str>, chat: Option<&str>) -> String {
+ match (kwant, chat) {
+ (Some(kwant), Some(chat)) => job_page_key(team, kwant, chat).unwrap_or_else(|| team.to_string()),
+ _ => team.to_string(),
+ }
+}
+
+/// Whether a page may be closed now: no open step holds it, its job has no turn still running
+/// (a bot waiting minutes on a render between two calls comes back to its page, not a blank
+/// one), and nobody (the person, or a bot's action) is using it.
+async fn closable(state: &AppState, key: &str) -> bool {
+ if state.db.human_step_open_on(key).await.unwrap_or(true) {
+ return false;
+ }
+ if let Some((team, kwant, chat)) = job_of(key) {
+ if state.human_steps.has_turn_in(team, kwant, chat) {
+ return false;
+ }
+ }
+ match state.browser_controllers.lock().await.get(key) {
+ Some(ctrl) => ctrl.control.try_write().is_ok() && !ctrl.is_held_for_person(),
+ None => true,
+ }
+}
+
+/// 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);
+ if let Some(ctrl) = ctrl {
+ ctrl.persist_cookies().await;
+ }
+ if let Err(e) = state.browser_service.close_page(key).await {
+ tracing::debug!("couldn't close the job page {key}: {e}");
+ }
+ tracing::info!(page = %key, "closed a job's browser page");
+}
+
+/// Before a new job page opens in `team`: makes room under [`MAX_JOB_PAGES_PER_TEAM`] by closing
+/// the least recently used page that can be closed. `false` when every page is held or in use.
+/// The caller holds the team's [`JobPages::team_lock`] until the new page is open.
+pub async fn make_room(state: &AppState, team: &str, key: &str) -> bool {
+ let pages = state.browser_service.job_pages(team).await;
+ let open: Vec<_> = pages.into_iter().filter(|(k, _)| k != key).collect();
+ if open.len() < MAX_JOB_PAGES_PER_TEAM {
+ return true;
+ }
+ let mut to_close = open.len() + 1 - MAX_JOB_PAGES_PER_TEAM;
+ for (page, _) in open {
+ if to_close == 0 {
+ break;
+ }
+ if closable(state, &page).await {
+ close_page(state, &page).await;
+ to_close -= 1;
+ }
+ }
+ to_close == 0
+}
+
+/// 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();
+ let teams: std::collections::BTreeSet<String> = state
+ .browser_service
+ .pages_in_use()
+ .into_iter()
+ .filter(|(k, _)| is_job_page(k))
+ .map(|(k, _)| page_team(&k).to_string())
+ .collect();
+ let mut closed = 0;
+ for team in teams {
+ let lock = state.job_pages.team_lock(&team);
+ let _opening = lock.lock().await;
+ for (page, at) in state.browser_service.job_pages(&team).await {
+ if now.duration_since(at) >= idle && closable(state, &page).await {
+ close_page(state, &page).await;
+ closed += 1;
+ }
+ }
+ }
+ closed
+}
+
+/// Runs [`sweep_idle`] every [`SWEEP_EVERY`] until `cancel`.
+pub fn spawn_sweeper(state: AppState, cancel: tokio_util::sync::CancellationToken) {
+ tokio::spawn(async move {
+ loop {
+ tokio::select! {
+ _ = cancel.cancelled() => return,
+ _ = tokio::time::sleep(SWEEP_EVERY) => {}
+ }
+ let closed = sweep_idle(&state, JOB_PAGE_IDLE).await;
+ if closed > 0 {
+ tracing::info!("browser: closed {closed} idle job pages");
+ }
+ }
+ });
+}
+
+/// The page the team's live view shows: the page an open step holds (the person has something
+/// to do there), else the page used most recently, else the team page.
+pub async fn live_page(state: &AppState, team: &str) -> String {
+ if let Ok(steps) = state.db.list_human_steps(Some("open"), None, None).await {
+ if let Some(page) = steps.iter().filter(|s| s.sandbox_target.as_deref() == Some(team)).find_map(|s| s.page().map(str::to_string)) {
+ return page;
+ }
+ }
+ let prefix = format!("{team}{}", PAGE_SEP);
+ state
+ .browser_service
+ .pages_in_use()
+ .into_iter()
+ .filter(|(k, _)| k == team || k.starts_with(&prefix))
+ .max_by_key(|(_, at)| *at)
+ .map(|(k, _)| k)
+ .unwrap_or_else(|| team.to_string())
+}
+
+/// `GET /api/sandbox/:team_id/pages`: the team's pages for a tab strip, newest first. Each has
+/// its `page` key (pass it to the live view as `?page=`), the bot and chat of a job page, its
+/// address and title, whether a step holds it (`held`), and seconds since its last use. `live`
+/// is the page the live view shows by default.
+pub async fn list_pages(State(state): State<AppState>, Path(team_id): Path<String>) -> Json<Value> {
+ let team = page_team(&team_id).to_string();
+ let now = Instant::now();
+ let mut pages: Vec<(String, Option<Instant>)> = vec![(team.clone(), state.browser_service.page_used_at(&team))];
+ pages.extend(state.browser_service.job_pages(&team).await.into_iter().map(|(k, at)| (k, Some(at))));
+ pages.sort_by_key(|(_, at)| std::cmp::Reverse(*at));
+ let mut out = Vec::new();
+ for (key, at) in pages {
+ let ctrl = state.browser_controllers.lock().await.get(&key).cloned();
+ let (url, title) = match &ctrl {
+ Some(c) => (c.current_url.lock().await.clone(), c.current_title.lock().await.clone()),
+ None => (None, None),
+ };
+ let mut parts = key.splitn(3, PAGE_SEP).skip(1);
+ out.push(json!({
+ "page": key,
+ "team_id": team,
+ "kwant_id": parts.next(),
+ "chat_id": parts.next(),
+ "job": is_job_page(&key),
+ "url": url,
+ "title": title,
+ "held": state.db.human_step_open_on(&key).await.unwrap_or(false),
+ "idle_seconds": at.map(|at| now.duration_since(at).as_secs()),
+ }));
+ }
+ Json(json!({
+ "team_id": team,
+ "live": live_page(&state, &team).await,
+ "max_job_pages": MAX_JOB_PAGES_PER_TEAM,
+ "pages": out,
+ }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_job_page_is_keyed_by_team_bot_and_chat() {
+ assert_eq!(job_page_key("t", "k", "c").as_deref(), Some("t#k#c"));
+ assert_eq!(job_page_key("t", "k", ""), None);
+ assert_eq!(job_page_key("t", "k#x", "c"), None, "a part with the separator can't make a key");
+ assert_eq!(page_team("t#k#c"), "t");
+ assert_eq!(page_team("t"), "t");
+ assert!(is_job_page("t#k#c") && !is_job_page("t"));
+ assert_eq!(call_page("t", Some("k"), Some("c")), "t#k#c");
+ assert_eq!(call_page("t", Some("k"), None), "t", "a bot route without a chat keeps the team page");
+ assert_eq!(call_page("t", None, None), "t", "the person's panel keeps the team page");
+ }
+
+ #[test]
+ fn a_job_pages_parts_are_read_back_from_its_key() {
+ assert_eq!(job_of("t#k#c"), Some(("t", "k", "c")));
+ assert_eq!(job_of("t"), None);
+ assert!(pages_full_message().starts_with("All 4 of this team's browser pages are in use by other jobs."));
+ let pages = JobPages::default();
+ assert_eq!(pages.wait(), PAGE_WAIT);
+ pages.set_wait(Duration::from_millis(5));
+ assert_eq!(pages.wait(), Duration::from_millis(5));
+ assert!(Arc::ptr_eq(&pages.team_lock("t"), &pages.team_lock("t")));
+ assert!(!Arc::ptr_eq(&pages.team_lock("t"), &pages.team_lock("u")), "one lock per team");
+ }
+
+ #[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() };
+ let scope = SelfScope { kwant_id: "k".into(), origin: Some(origin), sandbox_target: Some("t".into()), ..Default::default() };
+ assert_eq!(scope_page(&scope).as_deref(), Some("t#k#th"));
+ let no_chat = SelfScope { kwant_id: "k".into(), sandbox_target: Some("t".into()), ..Default::default() };
+ assert_eq!(scope_page(&no_chat).as_deref(), Some("t"));
+ let no_browser = SelfScope { kwant_id: "k".into(), ..Default::default() };
+ assert_eq!(scope_page(&no_browser), None);
+ }
+}
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 8782554e..38b7128d 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -1190,12 +1190,31 @@ async fn focused_editable(cdp: &Cdp) -> bool {
.ok().and_then(|r| r["result"]["value"].as_bool()).unwrap_or(false)
}
-pub async fn upgrade(State(state): State<AppState>, Path(id): Path<String>, headers: HeaderMap, ws: WebSocketUpgrade) -> Result<Response, StatusCode> {
+/// `?page=`: which of the team's pages to show (a key from `GET /api/sandbox/:id/pages`).
+#[derive(Debug, Default, Deserialize)]
+pub struct StreamQuery {
+ #[serde(default)]
+ pub page: Option<String>,
+}
+
+pub async fn upgrade(
+ State(state): State<AppState>,
+ Path(id): Path<String>,
+ axum::extract::Query(query): axum::extract::Query<StreamQuery>,
+ headers: HeaderMap,
+ ws: WebSocketUpgrade,
+) -> Result<Response, StatusCode> {
// Prevent a third-party website from controlling an authenticated same-origin session.
let origin = headers.get("origin").and_then(|v| v.to_str().ok()).and_then(|s| reqwest::Url::parse(s).ok()).ok_or(StatusCode::FORBIDDEN)?;
let host = headers.get("host").and_then(|v| v.to_str().ok()).ok_or(StatusCode::FORBIDDEN)?;
let expected = reqwest::Url::parse(&format!("{}://{}", origin.scheme(), host)).map_err(|_| StatusCode::FORBIDDEN)?;
if !matches!(origin.scheme(), "http" | "https") || origin.origin() != expected.origin() { return Err(StatusCode::FORBIDDEN); }
+ // The page shown: the one asked for (a page of this team only), else the page an open step
+ // holds, else the page used last (0.9.3: each job has its own page)
+ let id = match query.page.filter(|p| super::browser_pages::page_team(p) == id) {
+ Some(page) => page,
+ 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;
if let Err(error) = result { tracing::debug!("Browser stream ended: {}", error); }
@@ -1288,7 +1307,8 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
let (jobs, jobs_rx) = mpsc::unbounded_channel::<Job>();
let worker = Worker { ctrl: ctrl.clone(), cdp: cdp.clone(), shared: shared.clone(), client: client_tx.clone(), swallowed: 0, open_select: None };
let worker = tokio::spawn(worker.run(jobs_rx));
- let mut rec = StageRecorder::new(state.clone(), id.clone(), shared.socket);
+ // Show it once records on the team's stage, whichever of its pages is shown
+ let mut rec = StageRecorder::new(state.clone(), super::browser_pages::page_team(&id).to_string(), shared.socket);
let pointer = Pointer::new(state.clone(), cdp.clone(), client_tx.clone());
let result = stream(&mut socket, &ctrl, &cdp, &mut events, &mut page, &shared, &client_tx, &mut client_rx, &jobs, &mut rec, &pointer).await;
// a recording live on this socket stops here (Show it once: `closed`), its steps kept, after
diff --git a/src/server/computer.rs b/src/server/computer.rs
index b2d25ceb..ff31e442 100644
--- a/src/server/computer.rs
+++ b/src/server/computer.rs
@@ -29,7 +29,7 @@ pub async fn apply_mode(state: &AppState) -> ComputerMode {
if state.browser_service.mode() != mode {
let mut controllers = state.browser_controllers.lock().await;
if state.browser_service.set_mode(mode).await {
- for team_id in controllers.drain().map(|(id, _)| id) {
+ for team_id in controllers.drain().map(|(id, _)| super::browser_pages::page_team(&id).to_string()).collect::<std::collections::BTreeSet<_>>() {
let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {
team_id,
container_name: "browser-service".into(),
@@ -206,7 +206,7 @@ pub async fn put_window(
format!("Could not restart Chrome: {error}"),
));
}
- for team_id in controllers.drain().map(|(id, _)| id) {
+ for team_id in controllers.drain().map(|(id, _)| super::browser_pages::page_team(&id).to_string()).collect::<std::collections::BTreeSet<_>>() {
let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {
team_id,
container_name: "browser-service".into(),
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index c026e307..87cb18f5 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -734,9 +734,11 @@ pub const BROWSER_CITE: &str = "browser_cite";
/// Same holds as the other browser tools: the person's sign-in/CAPTCHA step or their control.
pub(crate) async fn browser_screenshot_tool(state: &AppState, scope: &SelfScope, args: &Value) -> (Value, bool) {
let text = |t: &str| json!([{"type": "text", "text": t}]);
- let Some(target) = &scope.sandbox_target else {
+ // the turn's own page: its job page in a chat, else the team page
+ let Some(target) = super::browser_pages::scope_page(scope) else {
return (text(&format!("Unknown tool {BROWSER_SCREENSHOT}.")), true);
};
+ let target = &target;
if super::human_steps::browser_is_held(state, target).await {
return (
text("The browser is waiting on the person (a sign-in or CAPTCHA step). Stop browser actions until they finish it."),
@@ -755,8 +757,9 @@ 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 Some(ctrl) = super::routes::get_or_create_browser_controller(state, target).await else {
- return (text(&state.browser_service.unavailable_reason()), true);
+ let ctrl = match super::routes::open_page(state, target, state.job_pages.wait()).await {
+ Ok(ctrl) => ctrl,
+ Err(refusal) => return (text(&page_refusal_text(state, refusal)), true),
};
match ctrl.capture_for_agent(width).await {
Ok(shot) => {
@@ -826,9 +829,13 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, na
// Each turn is its own reader: a new turn gets the whole page on its first read. A turn
// without an id always gets the whole page
let reader = scope.turn_id.clone().unwrap_or_default();
- // This bot drives the browser now, so its site rules are the ones that hold
- if let Some(ctrl) = super::routes::get_or_create_browser_controller(state, target).await {
- ctrl.site_guard.set_driver(&scope.kwant_id);
+ // 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 {
+ Ok(ctrl) => ctrl.site_guard.set_driver(&scope.kwant_id),
+ Err(refusal @ super::routes::PageRefusal::PagesFull) => 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;
// A CAPTCHA wall: ask the person to solve it, then show the agent the page they left. Also
@@ -864,6 +871,14 @@ fn wall_check_helps(text: &str, page: Option<&Value>) -> bool {
!(text.starts_with("The user has taken control") || text.ends_with(" is required") || text.starts_with("action is required"))
}
+/// What a bot's browser tool says when its page couldn't be had.
+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::Unavailable => state.browser_service.unavailable_reason(),
+ }
+}
+
/// `reader` names who reads (empty: nobody known), for `browser_page` to answer "unchanged" when
/// that reader's last page (from any browser tool) still reads the same.
async fn run_browser_tool(state: &AppState, target: &str, reader: &str, name: &str, args: &Value) -> (String, bool) {
@@ -1290,8 +1305,10 @@ async fn call_tool(
}
}
}
- BROWSER_OPEN | BROWSER_PAGE | BROWSER_ACT | BROWSER_CITE => match &scope.sandbox_target {
- Some(target) => call_browser_tool(state, scope, target, name, args).await,
+ // on the turn's own page (its job page in a chat), so a page held for another job's
+ // sign-in doesn't stop this one
+ BROWSER_OPEN | BROWSER_PAGE | BROWSER_ACT | BROWSER_CITE => match super::browser_pages::scope_page(scope) {
+ Some(target) => call_browser_tool(state, scope, &target, name, args).await,
None => (format!("Unknown tool {name}."), true),
},
super::rerouting::HAND_BACK => super::rerouting::tool_call(state, scope, args).await,
diff --git a/src/server/human_steps.rs b/src/server/human_steps.rs
index 9e3f2d2a..221ea7a0 100644
--- a/src/server/human_steps.rs
+++ b/src/server/human_steps.rs
@@ -168,6 +168,12 @@ impl HumanStepHub {
}
}
+ /// Whether `kwant` has a turn running in `chat` ([`chat_key`]) on the bot browser `target`:
+ /// that job still uses its page, even between two browser calls.
+ pub fn has_turn_in(&self, target: &str, kwant: &str, chat: &str) -> bool {
+ self.newest_on(target, |s| s.kwant_id == kwant && chat_key(s).as_deref() == Some(chat)).is_some()
+ }
+
fn newest_on(&self, target: &str, pick: impl Fn(&SelfScope) -> bool) -> Option<SelfScope> {
let turns = self.turns.lock().unwrap_or_else(|e| e.into_inner());
turns.get(target)?.iter().rev().map(|(_, s)| s).find(|s| {
@@ -240,6 +246,8 @@ fn card_meta(s: &HumanStep) -> Value {
"reason": s.reason,
"url": s.url,
"sandbox_target": s.sandbox_target,
+ // the page to show for this step (`?page=` on the live view)
+ "page_key": s.page(),
"source": s.source,
"status": s.status,
"target": s.target.as_deref().and_then(|t| serde_json::from_str::<Value>(t).ok()),
@@ -283,7 +291,7 @@ async fn changed(state: &AppState, s: &HumanStep) {
let _ = state.event_sender.send(RuntimeEvent::HumanStepUpdated { step: serde_json::to_value(s).unwrap_or(Value::Null) });
}
-/// Holds the browser for the person, if it is running.
+/// Holds the browser page for the person, if it is running.
async fn hold_browser(state: &AppState, target: Option<&str>) {
let Some(target) = target else { return };
let ctrl = state.browser_controllers.lock().await.get(target).cloned();
@@ -294,10 +302,10 @@ async fn hold_browser(state: &AppState, target: Option<&str>) {
}
}
-/// Hands the browser back once no step is open in it any more.
+/// Hands the browser page back once no step is open on it any more.
async fn release_browser(state: &AppState, target: Option<&str>) {
let Some(target) = target else { return };
- if state.db.human_step_open_in(target).await.unwrap_or(false) {
+ if state.db.human_step_open_on(target).await.unwrap_or(false) {
return;
}
let ctrl = state.browser_controllers.lock().await.get(target).cloned();
@@ -316,7 +324,7 @@ async fn close(state: &AppState, id: &str, status: &'static str) -> Option<Human
return None;
}
let s = state.db.get_human_step(id).await.ok().flatten()?;
- release_browser(state, s.sandbox_target.as_deref()).await;
+ release_browser(state, s.page()).await;
if let Some(turn) = s.turn_id.as_deref().and_then(super::activity::TurnActivity::find) {
turn.settle(&s.id, if status == "cancelled" { "stopped" } else { status });
}
@@ -324,9 +332,10 @@ async fn close(state: &AppState, id: &str, status: &'static str) -> Option<Human
Some(s)
}
-/// Whether a human step holds this bot browser: bot actions wait until it closes.
-pub async fn browser_is_held(state: &AppState, target: &str) -> bool {
- state.db.human_step_open_in(target).await.unwrap_or(false)
+/// Whether a human step holds this browser page (a job's page, or the team page): bot actions
+/// on it wait until it closes. Other pages of the team are not held.
+pub async fn browser_is_held(state: &AppState, page: &str) -> bool {
+ state.db.human_step_open_on(page).await.unwrap_or(false)
}
// Agent tool
@@ -410,7 +419,8 @@ pub async fn raise(
target: Option<&CaptchaHit>,
source: &str,
) -> Result<Option<Outcome>, String> {
- raise_step(state, scope, kind, reason, url, target, source, true).await
+ let page = super::browser_pages::scope_page(scope);
+ raise_step(state, scope, page, kind, reason, url, target, source, true).await
}
/// [`raise`]; `wait: false` only asks (card, notification, held browser, CAPTCHA watcher) and
@@ -421,6 +431,7 @@ pub async fn raise(
async fn raise_step(
state: &AppState,
scope: &SelfScope,
+ page: Option<String>,
kind: &str,
reason: &str,
url: Option<&str>,
@@ -443,11 +454,13 @@ async fn raise_step(
thread_id: origin.thread_id.clone(),
turn_id: scope.turn_id.clone(),
sandbox_target: scope.sandbox_target.clone(),
+ // only a page of this turn's own bot browser
+ page_key: page.filter(|p| scope.sandbox_target.as_deref() == Some(super::browser_pages::page_team(p))),
};
// The browser is the person's before anyone can see the step: a bot action that lands between
// the two would otherwise run on a page the person was just asked to use (and a test reading
// the open step could find the browser not yet held, as CI did once on 3bfe50e)
- hold_browser(state, place.sandbox_target.as_deref()).await;
+ hold_browser(state, place.page_key.as_deref().or(place.sandbox_target.as_deref())).await;
// Like ask_user, the step, its card and the waiter appear together
let hub = &state.human_steps;
let target_json = target.and_then(|t| serde_json::to_string(t).ok());
@@ -478,7 +491,7 @@ async fn raise_step(
hub.take(&id);
}
// No step after all: hand the browser back unless another step still holds it
- release_browser(state, place.sandbox_target.as_deref()).await;
+ release_browser(state, place.page_key.as_deref().or(place.sandbox_target.as_deref())).await;
return Err(match e {
HumanStepError::Db => "Could not save the step.".into(),
e => e.to_string(),
@@ -516,7 +529,7 @@ async fn raise_step(
if is_new {
// Again, in case another step in this browser closed (and handed it back) just before
// this one was saved; a no-op when it is still held
- hold_browser(state, step.sandbox_target.as_deref()).await;
+ hold_browser(state, step.page()).await;
if step.kind == "captcha" && step.sandbox_target.is_some() {
// a CAPTCHA kwnt saw is on the page already; one the bot named must show up first
spawn_watch_captcha(state.clone(), step.id.clone(), source == "auto");
@@ -605,11 +618,11 @@ pub const ASKED_NOTE: &str = "A CAPTCHA / human check blocked the page, so kwnt
/// [`raise_for_bot_wall`] for a CAPTCHA no tool call can wait on: kwnt opened the page before
/// the bot's turn, or the bot met it through the shell browser API. The person gets the card and
/// the notification at once; the answer starts a new turn. `None` when there's no chat to ask in
-/// (the note for the bot otherwise).
-pub async fn ask_for_bot_wall(state: &AppState, scope: &SelfScope, page: &Value) -> Option<String> {
+/// (the note for the bot otherwise). `on`: the browser page that showed it, which the step holds.
+pub async fn ask_for_bot_wall(state: &AppState, scope: &SelfScope, on: &str, page: &Value) -> Option<String> {
scope.origin.as_ref()?;
let (reason, url, target) = wall_request(page);
- match raise_step(state, scope, "captcha", &reason, url.as_deref(), target.as_ref(), "auto", false).await {
+ match raise_step(state, scope, Some(on.to_string()), "captcha", &reason, url.as_deref(), target.as_ref(), "auto", false).await {
Ok(Some(outcome)) => Some(format!("A CAPTCHA blocked the page, so the person was asked to solve it. {}", outcome_text(Some(outcome), true))),
Ok(None) => Some(ASKED_NOTE.to_string()),
Err(e) => {
@@ -665,7 +678,7 @@ async fn watch_captcha(state: AppState, id: String, mut seen: bool) {
settle(&state, &id, Outcome::TimedOut).await;
return;
}
- let Some(target) = step.sandbox_target.as_deref() else { return };
+ let Some(target) = step.page() else { return };
let ctrl = state.browser_controllers.lock().await.get(target).cloned();
let Some(ctrl) = ctrl else { continue };
match wall_on_page(&ctrl).await {
@@ -924,6 +937,23 @@ mod tests {
assert_eq!(chat_key(&dm).as_deref(), Some("ann"));
}
+ /// A job (bot and chat) with a turn running keeps its page; the turn ending frees it.
+ #[test]
+ fn a_job_with_a_live_turn_is_known_until_the_turn_ends() {
+ let hub = Arc::new(HumanStepHub::default());
+ let a = hub.track_turn("team", turn_in("ann", "thread-a"));
+ assert!(hub.has_turn_in("team", "ann", "thread-a"));
+ assert!(!hub.has_turn_in("team", "ann", "thread-b"), "another chat of the same bot");
+ assert!(!hub.has_turn_in("team", "bob", "thread-a"), "another bot");
+ assert!(!hub.has_turn_in("other-team", "ann", "thread-a"), "another team's browser");
+ drop(a);
+ assert!(!hub.has_turn_in("team", "ann", "thread-a"));
+ let stopped = tokio_util::sync::CancellationToken::new();
+ stopped.cancel();
+ let _s = hub.track_turn("team", SelfScope { cancel: Some(stopped), ..turn_in("ann", "thread-a") });
+ assert!(!hub.has_turn_in("team", "ann", "thread-a"), "a stopped turn uses no page");
+ }
+
#[test]
fn the_agent_hears_each_outcome_plainly() {
assert!(outcome_text(Some(Outcome::Done), false).contains("Look at the page"));
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index bafa6924..030c01db 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -652,7 +652,8 @@ pub async fn prepare_turn_with_opts(
}
// Signed-in http servers get their (refreshed) access token as a secret header
super::mcp_oauth::authorize_servers(state, &mut servers).await;
- let browser = self_scope.as_ref().and_then(|s| s.sandbox_target.clone()).map(|t| (state.clone(), t));
+ // the payment check reads the page this turn's browser tools use (its job page in a chat)
+ let browser = self_scope.as_ref().and_then(super::browser_pages::scope_page).map(|t| (state.clone(), t));
let self_tools = self_scope.is_some() && !servers.iter().any(|s| s.name.eq_ignore_ascii_case(mcp::SELF_SERVER_NAME));
if self_tools {
servers.push(super::continuity::self_server(&local_base_url(state), &token));
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 9e987d54..0e4cc125 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -34,6 +34,7 @@ pub mod questions;
pub mod activity;
pub mod bot_status;
pub mod human_steps;
+pub mod browser_pages;
pub mod skills;
pub mod spaces;
pub mod asks;
@@ -124,6 +125,8 @@ pub struct AppState {
pub questions: Arc<questions::QuestionHub>,
/// `request_human_step` calls waiting for the person to sign in or solve a CAPTCHA.
pub human_steps: Arc<human_steps::HumanStepHub>,
+ /// Opening job pages: one lock per team and the wait for room (0.9.3).
+ pub job_pages: Arc<browser_pages::JobPages>,
/// "Sign in with Claude" for the Claude engine.
pub claude_login: Arc<engine_login::ClaudeLogin>,
/// "Sign in with ChatGPT" (Codex device code) for the Codex engine.
@@ -193,6 +196,7 @@ impl AppState {
scheduler_wake: Default::default(),
questions: Default::default(),
human_steps: Default::default(),
+ job_pages: Default::default(),
claude_login: Default::default(),
codex_login: Arc::new(engine_login::EngineLogin::system(crate::profiles::Engine::Codex)),
grok_login: Arc::new(engine_login::EngineLogin::system(crate::profiles::Engine::Grok)),
@@ -335,6 +339,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/sandbox/:team_id/navigate", post(routes::navigate_sandbox_api))
.route("/api/sandbox/:team_id/interact", post(routes::interact_sandbox))
.route("/api/sandbox/:team_id/stream", get(browser_stream::upgrade))
+ .route("/api/sandbox/:team_id/pages", get(browser_pages::list_pages))
.route("/api/sandbox/:team_id/page", get(routes::get_sandbox_page_api))
.route("/api/sandbox/:team_id/act", post(routes::act_sandbox_api))
.route("/api/sandbox/:team_id/cite", post(routes::cite_sandbox))
diff --git a/src/server/passwords.rs b/src/server/passwords.rs
index 83528e72..c4f9dec0 100644
--- a/src/server/passwords.rs
+++ b/src/server/passwords.rs
@@ -175,9 +175,23 @@ fn meta_json(m: &CredentialMeta) -> Value {
}
/// The browser controller already open for this target, if any; listing never starts a browser.
+/// With a page per job (0.9.3), the page holding a password waiting to be saved wins (the person
+/// signed in on a job's page), then the page the live view shows, then the team page.
async fn open_controller(state: &AppState, path_id: &str, owner: &str) -> Option<crate::sandbox::BrowserController> {
- let controllers = state.browser_controllers.lock().await;
- controllers.get(owner).or_else(|| controllers.get(path_id)).cloned()
+ let live = super::browser_pages::live_page(state, path_id).await;
+ let prefix = format!("{path_id}{}", super::browser_pages::PAGE_SEP);
+ let found: Vec<crate::sandbox::BrowserController> = {
+ let controllers = state.browser_controllers.lock().await;
+ [live.as_str(), owner, path_id].into_iter().filter_map(|k| controllers.get(k))
+ .chain(controllers.iter().filter(|(k, _)| k.starts_with(&prefix)).map(|(_, c)| c))
+ .cloned().collect()
+ };
+ for ctrl in &found {
+ if ctrl.pending().await.is_some() {
+ return Some(ctrl.clone());
+ }
+ }
+ found.into_iter().next()
}
pub async fn list(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
diff --git a/src/server/routes.rs b/src/server/routes.rs
index ed2403ef..09e7a286 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2782,7 +2782,10 @@ async fn run_kwant_turn_inner(
// A replay works in its own scratch browser and asks nobody
let _turn_on_browser = opts.rehearse.is_none().then(|| state.human_steps.track_turn(&sandbox_target, turn_scope.clone()));
- let active_ctrl = state.browser_controllers.lock().await.get(&sandbox_target).cloned();
+ // The turn's own page: its job page in this chat (0.9.3), so another job's sign-in held
+ // on the team browser doesn't stop it; the team page when the turn has no chat
+ let turn_page = super::browser_pages::scope_page(&turn_scope).unwrap_or_else(|| sandbox_target.clone());
+ let active_ctrl = state.browser_controllers.lock().await.get(&turn_page).cloned();
// The user may have browsed in the live viewer since the last turn; read the real location
let active_browser_url = if let Some(ref ctrl) = active_ctrl {
let _ = ctrl.sync_location().await;
@@ -2800,9 +2803,9 @@ async fn run_kwant_turn_inner(
"🌐 Navigating bot browser to {}...",
target_url
)));
- if let Some(ctrl) = get_or_create_browser_controller(state, &sandbox_target).await {
+ if let Some(ctrl) = get_or_create_browser_controller(state, &turn_page).await {
ctrl.site_guard.set_driver(&target_kwant.id);
- let navigated = match guard_bot_action(state, &ctrl, &sandbox_target).await {
+ let navigated = match guard_bot_action(state, &ctrl, &turn_page).await {
Ok(()) => ctrl.navigate(&target_url).await,
Err(e) => Err(e),
};
@@ -2828,7 +2831,7 @@ async fn run_kwant_turn_inner(
let wall = crate::sandbox::detect_bot_wall(&nav.url, &nav.title, &page_text).or(captcha.as_ref().map(|c| c.label()));
// The person is asked at once; the bot hears it was, instead of a block to report
let asked = match wall {
- Some(_) => super::human_steps::ask_for_bot_wall(state, &turn_scope, &json!({"url": nav.url, "captcha": captcha})).await,
+ Some(_) => super::human_steps::ask_for_bot_wall(state, &turn_scope, &turn_page, &json!({"url": nav.url, "captcha": captcha})).await,
None => None,
};
final_prompt = if let (Some(kind), Some(note)) = (wall, asked) {
@@ -5527,14 +5530,103 @@ pub fn detect_url_in_prompt(prompt: &str) -> Option<String> {
})
}
+/// The controller of one browser page: `team_id` is a page key, the team page (a sandbox target)
+/// or a job's own page ([`super::browser_pages`]). A new job page opens in its team's context,
+/// after room is made under the team's job-page cap; `None` at once when the browser is
+/// unavailable or every job page of the team is held or in use (see [`page_controller`] for a
+/// call that waits for room).
pub async fn get_or_create_browser_controller(
state: &AppState,
team_id: &str,
) -> Option<crate::sandbox::BrowserController> {
+ open_page(state, team_id, std::time::Duration::ZERO).await.ok()
+}
+
+/// Why a page couldn't be had.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PageRefusal {
+ /// The browser didn't start or answer.
+ Unavailable,
+ /// Every job page of the team is held or in use, and none freed up in time.
+ PagesFull,
+}
+
+/// The page's controller for a bot's browser call: like [`get_or_create_browser_controller`],
+/// but a job page that finds its team's pages all in use waits up to
+/// [`super::browser_pages::PAGE_WAIT`] for one to free up, then gets a clear 503 saying so
+/// (nothing is wrong with the browser) instead of "browser unavailable".
+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))
+}
+
+/// 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::PagesFull => (StatusCode::SERVICE_UNAVAILABLE, Json(json!({
+ "error": super::browser_pages::pages_full_message(),
+ "code": PAGES_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";
+
+/// 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
+/// tries again each second until `wait` has passed.
+pub async fn open_page(
+ state: &AppState,
+ key: &str,
+ wait: std::time::Duration,
+) -> Result<crate::sandbox::BrowserController, PageRefusal> {
// follow a mode switch made elsewhere (another kwnt process sharing the data dir)
super::computer::apply_mode(state).await;
// keeps the browser container from being stopped as idle while bots use it
state.browser_service.note_use();
+ 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);
+ }
+ // An open job page that answers needs no lock; any page is only ever opened under it
+ let existing = state.browser_controllers.lock().await.get(key).cloned();
+ if let Some(ctrl) = existing {
+ state.browser_service.touch_page(key);
+ if !ctrl.is_managed_session() || ctrl.refresh_location().await.is_ok() {
+ return Ok(ctrl);
+ }
+ }
+ let deadline = std::time::Instant::now() + wait;
+ loop {
+ let lock = state.job_pages.team_lock(&team);
+ let opening = lock.lock().await;
+ let open = state.browser_controllers.lock().await.contains_key(key);
+ if open || super::browser_pages::make_room(state, &team, key).await {
+ state.browser_service.touch_page(key);
+ let ctrl = controller_for(state, key, &team).await;
+ drop(opening);
+ return ctrl.ok_or(PageRefusal::Unavailable);
+ }
+ 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);
+ }
+ tokio::time::sleep((deadline - now).min(std::time::Duration::from_secs(1))).await;
+ }
+}
+
+/// 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> {
+ 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) {
@@ -5543,11 +5635,19 @@ pub async fn get_or_create_browser_controller(
driver = ctrl.site_guard.driver();
controllers.remove(team_id);
}
- let (_, workspace) = resolve_sandbox_target_info(state, team_id).await?;
- match state.browser_service.session(team_id, &workspace).await {
+ let Some((_, workspace)) = resolve_sandbox_target_info(state, &team).await else {
+ state.browser_service.forget_page(team_id);
+ return None;
+ };
+ let opened = if job {
+ state.browser_service.page_session(team_id, &workspace).await
+ } else {
+ state.browser_service.session(team_id, &workspace).await
+ };
+ match opened {
Ok(ctrl) => {
// Passwords belong to the team, channel or bot (by id), never to a folder
- if let Some((owner, _)) = super::passwords::password_owner(state, team_id).await {
+ if let Some((owner, _)) = super::passwords::password_owner(state, &team).await {
ctrl.attach_vault(state.credentials.clone(), &owner).await;
}
// The new page keeps the old one's driving bot, so its site rules still hold
@@ -5556,11 +5656,16 @@ pub async fn get_or_create_browser_controller(
}
controllers.insert(team_id.to_string(), ctrl.clone());
let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {
- team_id: team_id.to_string(), container_name: "browser-service".into(), is_running: true,
+ team_id: team, container_name: "browser-service".into(), is_running: true,
});
Some(ctrl)
}
- Err(error) => { tracing::warn!("Browser service unavailable: {}", error); None }
+ Err(error) => {
+ tracing::warn!("Browser service unavailable: {}", error);
+ // a job page that didn't open isn't one of the team's pages
+ if job { state.browser_service.forget_page(team_id); }
+ None
+ }
}
}
@@ -5576,7 +5681,11 @@ pub(crate) async fn guard_bot_action(
ctrl.site_guard.set_actor(Actor::Bot);
let driver = match ctrl.site_guard.driver() {
Some(driver) => Some(driver),
- None => state.db.get_kwant(team_id).await.ok().flatten().map(|k| k.id),
+ // a job's page is driven by its bot; the team page by the bot whose own browser it is
+ None => match team_id.split(super::browser_pages::PAGE_SEP).nth(1) {
+ Some(kwant) => Some(kwant.to_string()),
+ None => state.db.get_kwant(team_id).await.ok().flatten().map(|k| k.id),
+ },
};
let rules = match &driver {
Some(kwant) => state
@@ -5627,14 +5736,13 @@ pub async fn get_browser_screenshot(
State(state): State<AppState>,
Path(team_id): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- let ctrl = get_or_create_browser_controller(&state, &team_id).await
- .ok_or_else(|| browser_unavailable(&state))?;
+ let ctrl = page_controller(&state, &team_id).await?;
// The user may have navigated in the live viewer; keep url/title (and other viewers) in sync
let previous_url = ctrl.current_url.lock().await.clone();
if let Some((new_url, new_title)) = ctrl.sync_location().await {
if previous_url.as_deref() != Some(new_url.as_str()) {
let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {
- team_id: team_id.clone(),
+ team_id: super::browser_pages::page_team(&team_id).to_string(),
url: new_url,
title: new_title,
status_code: 200,
@@ -5669,6 +5777,11 @@ pub async fn restart_sandbox(
} else { None };
state.browser_service.reset(&team_id).await.map_err(|_| StatusCode::BAD_GATEWAY)?;
controllers.remove(&team_id);
+ // Restarting the team page closes its job pages too (0.9.3)
+ if !super::browser_pages::is_job_page(&team_id) {
+ let prefix = format!("{team_id}{}", super::browser_pages::PAGE_SEP);
+ controllers.retain(|k, _| !k.starts_with(&prefix));
+ }
}
let running = get_or_create_browser_controller(&state, &team_id).await.is_some();
let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {
@@ -5683,13 +5796,12 @@ pub async fn navigate_sandbox(
Path(team_id): Path<String>,
Json(payload): Json<NavigatePayload>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- let ctrl = get_or_create_browser_controller(&state, &team_id).await
- .ok_or_else(|| browser_unavailable(&state))?;
+ let ctrl = page_controller(&state, &team_id).await?;
guard_bot_action(&state, &ctrl, &team_id).await.map_err(browser_request_failed)?;
let nav = ctrl.navigate(&payload.url).await.map_err(browser_request_failed)?;
let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {
- team_id: team_id.clone(),
+ team_id: super::browser_pages::page_team(&team_id).to_string(),
url: nav.url.clone(),
title: nav.title.clone(),
status_code: nav.status_code,
@@ -5697,7 +5809,7 @@ pub async fn navigate_sandbox(
if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {
let _ = state.event_sender.send(RuntimeEvent::BrowserScreenshot {
- team_id: team_id.clone(),
+ team_id: super::browser_pages::page_team(&team_id).to_string(),
url: nav.url.clone(),
image_base64: b64,
timestamp: chrono::Utc::now().to_rfc3339(),
@@ -5707,7 +5819,7 @@ pub async fn navigate_sandbox(
// Return the real page so agents can't mistake a redirect/CAPTCHA for success
let mut page = sandbox_page_state(&ctrl).await;
page["status"] = json!(if page["blocked"].as_bool() == Some(true) { "blocked" } else { "navigated" });
- page["team_id"] = json!(team_id);
+ page["team_id"] = json!(super::browser_pages::page_team(&team_id));
page["requested_url"] = json!(payload.url);
page["status_code"] = json!(nav.status_code);
Ok(Json(page))
@@ -5745,7 +5857,7 @@ pub async fn interact_sandbox(
}))));
}
- let ctrl = get_or_create_browser_controller(&state, &team_id).await.ok_or_else(|| browser_unavailable(&state))?;
+ let ctrl = page_controller(&state, &team_id).await?;
let _permit = ctrl.control.try_read().map_err(|_| (StatusCode::CONFLICT, Json(json!({"error":"Browser is controlled by a person."}))))?;
// The person's own input: their navigation is never held to a bot's site rules
@@ -5773,7 +5885,7 @@ pub async fn interact_sandbox(
let current_url = ctrl.current_url.lock().await.clone().unwrap_or_default();
let _ = state.event_sender.send(RuntimeEvent::BrowserScreenshot {
- team_id: team_id.clone(),
+ team_id: super::browser_pages::page_team(&team_id).to_string(),
url: current_url.clone(),
image_base64: screenshot.clone(),
timestamp: chrono::Utc::now().to_rfc3339(),
@@ -5907,6 +6019,12 @@ impl BotCall {
fn caller(&self) -> super::human_steps::Caller<'_> {
super::human_steps::Caller { kwant: &self.kwant, chat: self.chat.as_deref() }
}
+
+ /// The page this call uses in `team`'s browser: the job's own page on the chat route, the
+ /// team page on the route without a chat.
+ fn page_in(team: &str) -> impl Fn(&BotCall) -> String + '_ {
+ move |by| super::browser_pages::call_page(team, Some(&by.kwant), by.chat.as_deref())
+ }
}
/// `POST /api/sandbox/:id/bot/:kwant_id/navigate`: the browser API a bot's prompt gave it before
@@ -5978,10 +6096,11 @@ pub async fn act_sandbox_bot_chat(
/// `POST /api/sandbox/:id/bot/:kwant_id/chat/:chat/cite`.
pub async fn cite_sandbox_bot_chat(
State(state): State<AppState>,
- Path((team_id, _kwant_id, _chat)): Path<(String, String, String)>,
+ Path((team_id, kwant_id, chat)): Path<(String, String, String)>,
payload: Json<CitePayload>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- cite_sandbox(State(state), Path(team_id), payload).await
+ let page = super::browser_pages::call_page(&team_id, Some(&kwant_id), Some(&chat));
+ cite_sandbox(State(state), Path(page), payload).await
}
/// `by`: the bot that made the call (its own route), `None` on the plain route.
@@ -5991,9 +6110,10 @@ async fn navigate_as(
by: Option<BotCall>,
payload: Json<NavigatePayload>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- refuse_while_held(&state, &team_id, by.is_some()).await?;
- let result = navigate_sandbox(State(state.clone()), Path(team_id.clone()), payload).await;
- ask_on_wall(&state, &team_id, by.as_ref().map(BotCall::caller), result).await
+ let page = by.as_ref().map_or_else(|| team_id.clone(), BotCall::page_in(&team_id));
+ refuse_while_held(&state, &page, by.is_some()).await?;
+ let result = navigate_sandbox(State(state.clone()), Path(page.clone()), payload).await;
+ ask_on_wall(&state, &team_id, &page, by.as_ref().map(BotCall::caller), result).await
}
async fn page_as(
@@ -6002,12 +6122,13 @@ async fn page_as(
by: Option<BotCall>,
query: Query<PageQuery>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- let result = get_sandbox_page(State(state.clone()), Path(team_id.clone()), query).await;
+ let page = by.as_ref().map_or_else(|| team_id.clone(), BotCall::page_in(&team_id));
+ let result = get_sandbox_page(State(state.clone()), Path(page.clone()), query).await;
// A page held for the person's step was already asked about
- if super::human_steps::browser_is_held(&state, &team_id).await {
+ if super::human_steps::browser_is_held(&state, &page).await {
return result;
}
- ask_on_wall(&state, &team_id, by.as_ref().map(BotCall::caller), result).await
+ ask_on_wall(&state, &team_id, &page, by.as_ref().map(BotCall::caller), result).await
}
async fn act_as(
@@ -6016,9 +6137,10 @@ async fn act_as(
by: Option<BotCall>,
payload: Json<InteractPayload>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- refuse_while_held(&state, &team_id, by.is_some()).await?;
- let result = act_sandbox(State(state.clone()), Path(team_id.clone()), payload).await;
- ask_on_wall(&state, &team_id, by.as_ref().map(BotCall::caller), result).await
+ let page = by.as_ref().map_or_else(|| team_id.clone(), BotCall::page_in(&team_id));
+ refuse_while_held(&state, &page, by.is_some()).await?;
+ let result = act_sandbox(State(state.clone()), Path(page.clone()), payload).await;
+ ask_on_wall(&state, &team_id, &page, by.as_ref().map(BotCall::caller), result).await
}
/// What a browser call is told while the browser is held for the person's step: a bot (its own
@@ -6027,7 +6149,8 @@ async fn act_as(
pub const HELD_FOR_BOT: &str = "The browser is waiting on the person (a sign-in or CAPTCHA step). Stop browser actions and end your turn; you get a new one when they finish.";
pub const HELD_FOR_PERSON: &str = "This browser is set aside for the step a bot asked you to do (a sign-in or human check). Take control in the browser panel to use it, or press Done or Decline on the card in the chat first.";
-/// A bot action on a browser the person was handed for a step waits until they finish it.
+/// A bot action on a browser page the person was handed for a step waits until they finish it.
+/// `team_id`: the page key (only that page is held; the team's other pages aren't).
async fn refuse_while_held(state: &AppState, team_id: &str, bot: bool) -> Result<(), (StatusCode, Json<serde_json::Value>)> {
if super::human_steps::browser_is_held(state, team_id).await {
return Err((StatusCode::CONFLICT, Json(json!({"error": if bot { HELD_FOR_BOT } else { HELD_FOR_PERSON }}))));
@@ -6042,6 +6165,7 @@ async fn refuse_while_held(state: &AppState, team_id: &str, bot: bool) -> Result
async fn ask_on_wall(
state: &AppState,
team_id: &str,
+ on: &str,
by: Option<super::human_steps::Caller<'_>>,
result: Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
@@ -6049,7 +6173,7 @@ async fn ask_on_wall(
match result {
Ok(Json(mut page)) => {
if page["blocked"] == json!(true) {
- if let Some(note) = super::human_steps::ask_for_bot_wall(state, &turn, &page).await {
+ if let Some(note) = super::human_steps::ask_for_bot_wall(state, &turn, on, &page).await {
page["notice"] = json!(note);
page["human_step"] = json!("asked");
}
@@ -6057,12 +6181,12 @@ async fn ask_on_wall(
Ok(Json(page))
}
Err((status, Json(mut body))) if status != StatusCode::CONFLICT && status != StatusCode::BAD_REQUEST => {
- let page = match state.browser_controllers.lock().await.get(team_id).cloned() {
+ let page = match state.browser_controllers.lock().await.get(on).cloned() {
Some(ctrl) => Some(sandbox_page_state(&ctrl).await),
None => None,
};
if let Some(page) = page.filter(|p| p["blocked"] == json!(true)) {
- if let Some(note) = super::human_steps::ask_for_bot_wall(state, &turn, &page).await {
+ if let Some(note) = super::human_steps::ask_for_bot_wall(state, &turn, on, &page).await {
body["notice"] = json!(note);
body["human_step"] = json!("asked");
}
@@ -6077,7 +6201,7 @@ async fn broadcast_sandbox_screenshot(state: &AppState, team_id: &str, ctrl: &cr
if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {
let url = ctrl.current_url.lock().await.clone().unwrap_or_default();
let _ = state.event_sender.send(RuntimeEvent::BrowserScreenshot {
- team_id: team_id.to_string(),
+ team_id: super::browser_pages::page_team(team_id).to_string(),
url,
image_base64: b64,
timestamp: chrono::Utc::now().to_rfc3339(),
@@ -6146,9 +6270,7 @@ pub async fn get_sandbox_page(
Path(team_id): Path<String>,
Query(query): Query<PageQuery>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- let ctrl = get_or_create_browser_controller(&state, &team_id)
- .await
- .ok_or_else(|| browser_unavailable(&state))?;
+ let ctrl = page_controller(&state, &team_id).await?;
let snap = ctrl.snapshot().await;
let mut page = page_state_from(&ctrl, snap, query.find.as_deref().unwrap_or_default()).await;
if query.wants_blocks() {
@@ -6181,9 +6303,7 @@ pub async fn cite_sandbox(
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
use crate::sandbox::cite;
let refuse = |msg: String| (StatusCode::UNPROCESSABLE_ENTITY, Json(json!({ "error": msg })));
- let ctrl = get_or_create_browser_controller(&state, &team_id)
- .await
- .ok_or_else(|| browser_unavailable(&state))?;
+ let ctrl = page_controller(&state, &team_id).await?;
let Some(frames) = ctrl.frame_texts().await else {
return Err(refuse("Couldn't read the page to check the quote. Open a page first.".into()));
};
@@ -6220,9 +6340,7 @@ pub async fn act_sandbox(
Path(team_id): Path<String>,
Json(payload): Json<InteractPayload>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- let ctrl = get_or_create_browser_controller(&state, &team_id)
- .await
- .ok_or_else(|| browser_unavailable(&state))?;
+ let ctrl = page_controller(&state, &team_id).await?;
let args = json!({"action": payload.action, "text": payload.text, "key": payload.key, "ref": payload.ref_});
if let Some(why) = super::continuity::browser_act_payment(&state, &team_id, &args).await {
let mut page = sandbox_page_state(&ctrl).await;
@@ -6242,9 +6360,7 @@ pub async fn act_sandbox_allowed(
Path(team_id): Path<String>,
Json(payload): Json<InteractPayload>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- let ctrl = get_or_create_browser_controller(&state, &team_id)
- .await
- .ok_or_else(|| browser_unavailable(&state))?;
+ let ctrl = page_controller(&state, &team_id).await?;
let _permit = ctrl.control.try_read().map_err(|_| browser_request_failed(crate::sandbox::BrowserError::HumanControl))?;
guard_bot_action(&state, &ctrl, &team_id).await.map_err(browser_request_failed)?;
let _ = ctrl.site_guard.take_refusal();
@@ -6357,7 +6473,7 @@ pub async fn act_sandbox_allowed(
}
if let Some(url) = page["url"].as_str() {
let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {
- team_id: team_id.clone(),
+ team_id: super::browser_pages::page_team(&team_id).to_string(),
url: url.to_string(),
title: page["title"].as_str().unwrap_or("").to_string(),
status_code: 200,
diff --git a/tests/browser_pages_test.rs b/tests/browser_pages_test.rs
new file mode 100644
index 00000000..10f346d8
--- /dev/null
+++ b/tests/browser_pages_test.rs
@@ -0,0 +1,473 @@
+//! One browser page per job (0.9.3). Two jobs of one team, each in its own chat, get their own
+//! pages in the team's browser: a sign-in the person is asked to do on one job's page holds only
+//! that page, while the other job opens and acts on another site; both pages share the team's
+//! sign-ins (cookies). A team keeps at most `MAX_JOB_PAGES_PER_TEAM` job pages (the least recently
+//! used idle one makes room, never one a step holds) and an idle page is closed, never a held one.
+//!
+//! The browser parts run a real windowless Chrome, as the team's container browser (an external
+//! DevTools endpoint, where a job page is a new page in the team's browser context) and in Local
+//! mode (a new window of the person's Chrome). Skipped when no Chrome is installed.
+
+#[path = "support/chrome_guard.rs"]
+mod chrome_guard;
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrome_guard::ChromeGuard;
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{human_steps::HumanStepPlace, models::Kwant, spaces::SpaceId, Database},
+ router::LayaRouter,
+ sandbox::{computer, BrowserController},
+ server::{
+ 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},
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::{path::Path, time::Duration};
+use tempfile::{tempdir, TempDir};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tower::ServiceExt;
+
+/// A sign-in page that sets the site's cookie, and another site's page with a button over all of
+/// it that sets its title when clicked.
+async fn serve() -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buf = [0u8; 4096];
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let req = String::from_utf8_lossy(&buf[..n]).to_string();
+ let (extra, page) = match req.split_whitespace().nth(1).unwrap_or("/") {
+ "/signin" => ("set-cookie: kwnt_session=signed-in; Max-Age=86400; Path=/\r\n", "<!doctype html><title>sign in</title>"),
+ "/other" => ("", "<!doctype html><title>other</title><body style=margin:0>\
+ <button onclick=\"document.title='clicked'\" style='position:fixed;inset:0'>Go</button></body>"),
+ _ => ("", "<!doctype html><title>plain</title>"),
+ };
+ let reply = format!("HTTP/1.1 200 OK\r\ncontent-type: text/html\r\n{extra}content-length: {}\r\nconnection: close\r\n\r\n{page}", page.len());
+ let _ = stream.write_all(reply.as_bytes()).await;
+ });
+ }
+ });
+ format!("http://127.0.0.1:{port}")
+}
+
+async fn start_chrome(profile: &Path) -> Option<(String, ChromeGuard)> {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return None;
+ }
+ let (endpoint, _) = computer::ensure_local_chrome(profile, true).await.expect("Chrome starts");
+ Some((endpoint, ChromeGuard(profile.to_path_buf())))
+}
+
+/// kwnt whose bot browser is the container browser at `endpoint`.
+async fn container_state(tmp: &TempDir, endpoint: String) -> AppState {
+ std::env::set_var("KWNT_COMPUTER_MODE", "vm");
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some(endpoint), ..Config::default() };
+ AppState::new(config.clone(), db, ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url))
+}
+
+async fn first_bot(state: &AppState) -> Kwant {
+ state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0)
+}
+
+/// A turn of `bot` in its thread `thread`, on the team browser `team`; returns its tool token.
+async fn turn_in_thread(state: &AppState, bot: &Kwant, turn_id: &str, thread: &str, team: &str) -> String {
+ let scope = SelfScope {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ origin: Some(TurnOrigin { thread_id: Some(thread.into()), ..Default::default() }),
+ cancel: Some(tokio_util::sync::CancellationToken::new()),
+ turn_id: Some(turn_id.into()),
+ sandbox_target: Some(team.into()),
+ ..Default::default()
+ };
+ mcp_runtime::prepare_turn_with_self(state, bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1
+}
+
+/// Calls a self tool in the background, as the CLI would while the turn waits.
+fn call(app: &Router, token: &str, name: &str, args: Value) -> tokio::task::JoinHandle<(String, bool)> {
+ let (app, token, name) = (app.clone(), token.to_string(), name.to_string());
+ tokio::spawn(async move {
+ let body = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});
+ let req = Request::builder()
+ .method("POST")
+ .uri("/api/mcp/self")
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {token}"))
+ .body(Body::from(body.to_string()))
+ .unwrap();
+ let resp = app.oneshot(req).await.unwrap();
+ let v: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap();
+ (v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(), v["result"]["isError"].as_bool().unwrap_or(false))
+ })
+}
+
+/// A request to kwnt's API; the status and the JSON answer.
+async fn request(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri);
+ if body.is_some() {
+ req = req.header("content-type", "application/json");
+ }
+ let body = body.map_or_else(Body::empty, |b| Body::from(b.to_string()));
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn eval(ctrl: &BrowserController, expression: &str) -> Value {
+ let v = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": expression, "returnByValue": true})).await.unwrap();
+ v["result"]["value"].clone()
+}
+
+/// The page's title, once it is `want` (or after 5 s).
+async fn title_becomes(ctrl: &BrowserController, want: &str) -> String {
+ let mut title = String::new();
+ for _ in 0..50 {
+ title = eval(ctrl, "document.title").await.as_str().unwrap_or_default().to_string();
+ if title == want {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ title
+}
+
+async fn controller(state: &AppState, page: &str) -> BrowserController {
+ state.browser_controllers.lock().await.get(page).cloned().unwrap_or_else(|| panic!("no controller for {page}"))
+}
+
+#[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();
+ 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 base = serve().await;
+ let bot = first_bot(&state).await;
+ let team = bot.id.clone();
+ let chat_a = state.db.create_thread(&bot.id, "TikTok", "chat", None, "user").await.unwrap().id;
+ let chat_b = state.db.create_thread(&bot.id, "Google Flow", "chat", None, "user").await.unwrap().id;
+ let page_a = job_page_key(&team, &bot.id, &chat_a).unwrap();
+ let page_b = job_page_key(&team, &bot.id, &chat_b).unwrap();
+
+ // Job A opens the sign-in page on its own page (the site sets its cookie) and asks the person
+ let token_a = turn_in_thread(&state, &bot, "turn-a", &chat_a, &team).await;
+ let (text, is_error) = call(&app, &token_a, "browser_open", json!({"url": format!("{base}/signin")})).await.unwrap();
+ assert!(!is_error, "{text}");
+ let ctrl_a = controller(&state, &page_a).await;
+ assert_eq!(title_becomes(&ctrl_a, "sign in").await, "sign in");
+ let waiting = call(&app, &token_a, "request_human_step", json!({"kind": "sign_in", "reason": "Sign in to the test site"}));
+ let mut step = None;
+ for _ in 0..100 {
+ step = state.db.list_human_steps(Some("open"), None, None).await.unwrap().pop();
+ if step.is_some() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ let step = step.expect("a step was raised");
+ assert_eq!(step.page(), Some(page_a.as_str()), "the step holds job A's page");
+ assert_eq!(step.sandbox_target.as_deref(), Some(team.as_str()));
+ let card = state.db.get_message(step.message_id.as_deref().unwrap()).await.unwrap().unwrap();
+ let meta: Value = serde_json::from_str(card.meta.as_deref().unwrap()).unwrap();
+ assert_eq!(meta["page_key"], json!(page_a), "the card points at the step's page");
+ assert!(!waiting.is_finished(), "job A waits for the person");
+ assert!(ctrl_a.is_held_for_person());
+
+ // Job A's own browser calls are told to stop while the person signs in
+ let a_route = format!("/api/sandbox/{team}/bot/{}/chat/{chat_a}", bot.id);
+ let (status, body) = request(&app, "POST", &format!("{a_route}/navigate"), Some(json!({"url": format!("{base}/plain")}))).await;
+ assert_eq!(status, StatusCode::CONFLICT);
+ assert_eq!(body["error"], HELD_FOR_BOT);
+
+ // Job B, same team, other chat: opens another site and acts on it meanwhile
+ let b_route = format!("/api/sandbox/{team}/bot/{}/chat/{chat_b}", bot.id);
+ let (status, body) = request(&app, "POST", &format!("{b_route}/navigate"), Some(json!({"url": format!("{base}/other")}))).await;
+ assert_eq!(status, StatusCode::OK, "job B isn't held by job A's sign-in: {body}");
+ let ctrl_b = controller(&state, &page_b).await;
+ assert_eq!(title_becomes(&ctrl_b, "other").await, "other");
+ let (status, body) = request(&app, "POST", &format!("{b_route}/act"), Some(json!({"action": "click", "text": "Go"}))).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(title_becomes(&ctrl_b, "clicked").await, "clicked", "job B's click landed on its own page");
+ assert_eq!(title_becomes(&ctrl_a, "sign in").await, "sign in", "job A's page is untouched");
+ assert!(!kwnt::server::human_steps::browser_is_held(&state, &team).await, "the team page isn't held either");
+ // Each page is shown, none is a background tab Chrome doesn't paint: the team page, opened
+ // first, still answers screenshots and navigations (they hung, 502, before job pages got
+ // windows of their own in VM mode)
+ let (status, body) = request(&app, "POST", &format!("/api/sandbox/{team}/navigate"), Some(json!({"url": format!("{base}/plain")}))).await;
+ assert_eq!(status, StatusCode::OK, "the team page answers: {body}");
+ let ctrl_team = controller(&state, &team).await;
+ for (page, ctrl) in [("team", &ctrl_team), ("A", &ctrl_a), ("B", &ctrl_b)] {
+ assert_eq!(eval(ctrl, "document.visibilityState").await, json!("visible"), "{page}'s page is painted");
+ }
+
+ // The live view and the tab strip show job A's page while the person has a step there
+ let (status, pages) = request(&app, "GET", &format!("/api/sandbox/{team}/pages"), None).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(pages["live"], json!(page_a), "{pages}");
+ assert_eq!(pages["max_job_pages"], json!(MAX_JOB_PAGES_PER_TEAM));
+ let listed: Vec<&Value> = pages["pages"].as_array().unwrap().iter().filter(|p| p["job"] == true).collect();
+ assert_eq!(listed.len(), 2, "{pages}");
+ let a = listed.iter().find(|p| p["page"] == json!(page_a)).unwrap();
+ assert_eq!((a["held"].clone(), a["kwant_id"].clone(), a["chat_id"].clone()), (json!(true), json!(bot.id), json!(chat_a)));
+ let b = listed.iter().find(|p| p["page"] == json!(page_b)).unwrap();
+ assert_eq!(b["held"], json!(false));
+ assert!(b["url"].as_str().unwrap().ends_with("/other"), "{b}");
+
+ // One browser context per team: job A's sign-in cookie is on job B's page too
+ request(&app, "POST", &format!("{b_route}/navigate"), Some(json!({"url": format!("{base}/plain")}))).await;
+ assert_eq!(title_becomes(&ctrl_b, "plain").await, "plain");
+ assert_eq!(eval(&ctrl_b, "document.cookie").await, json!("kwnt_session=signed-in"), "sign-ins are shared by the team's pages");
+
+ // The person presses Done: job A carries on on its own page
+ let (status, _) = request(&app, "POST", &format!("/api/human-steps/{}/done", step.id), None).await;
+ assert_eq!(status, StatusCode::OK);
+ let (text, is_error) = tokio::time::timeout(Duration::from_secs(20), waiting).await.expect("job A resumes").unwrap();
+ assert!(!is_error && text.contains("done"), "{text}");
+ assert!(!ctrl_a.is_held_for_person());
+ let (status, body) = request(&app, "POST", &format!("{a_route}/navigate"), Some(json!({"url": format!("{base}/plain")}))).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(title_becomes(&ctrl_a, "plain").await, "plain");
+ assert_eq!(title_becomes(&ctrl_b, "plain").await, "plain");
+}
+
+/// Opens a job page for chat `chat` of team `team`.
+async fn open_page(state: &AppState, team: &str, chat: &str) -> Option<BrowserController> {
+ get_or_create_browser_controller(state, &job_page_key(team, "k", chat).unwrap()).await
+}
+
+/// An open step on `page` (as a bot's sign-in there would leave it); its id.
+async fn hold(state: &AppState, team: &str, page: &str, turn: &str) -> String {
+ let place = HumanStepPlace {
+ kwant_id: "k".into(),
+ turn_id: Some(turn.into()),
+ sandbox_target: Some(team.into()),
+ page_key: Some(page.into()),
+ ..Default::default()
+ };
+ state.db.create_human_step_with_card(&place, "other", "a step", None, None, "bot", |_| None).await.unwrap().0.id
+}
+
+async fn open_pages(state: &AppState) -> Vec<String> {
+ let mut pages: Vec<String> = state.browser_controllers.lock().await.keys().filter(|k| browser_pages::is_job_page(k)).cloned().collect();
+ pages.sort();
+ pages
+}
+
+#[tokio::test]
+async fn a_team_keeps_at_most_four_job_pages_and_never_closes_a_held_one_to_make_room() {
+ 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;
+ assert_eq!(MAX_JOB_PAGES_PER_TEAM, 4);
+ let key = |c: &str| job_page_key(&team, "k", c).unwrap();
+ for chat in ["c0", "c1", "c2", "c3"] {
+ open_page(&state, &team, chat).await.expect("a job page opens");
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ // c0 is the oldest but the person has a step there
+ hold(&state, &team, &key("c0"), "t0").await;
+ open_page(&state, &team, "c4").await.expect("a fifth job opens a page");
+ assert_eq!(open_pages(&state).await, vec![key("c0"), key("c2"), key("c3"), key("c4")], "the oldest idle page made room");
+ assert_eq!(state.browser_service.job_pages(&team).await.len(), MAX_JOB_PAGES_PER_TEAM);
+
+ // Using a page again keeps it: c2 is used, so c3 is now the oldest idle one
+ open_page(&state, &team, "c2").await.unwrap();
+ open_page(&state, &team, "c5").await.unwrap();
+ assert_eq!(open_pages(&state).await, vec![key("c0"), key("c2"), key("c4"), key("c5")]);
+
+ // Every page held: no room, and none is closed
+ for (chat, turn) in [("c2", "t2"), ("c4", "t4"), ("c5", "t5")] {
+ hold(&state, &team, &key(chat), turn).await;
+ }
+ assert!(open_page(&state, &team, "c6").await.is_none(), "no page is closed while its step is open");
+ assert_eq!(open_pages(&state).await, vec![key("c0"), key("c2"), key("c4"), key("c5")]);
+ // The team page is never counted, and still opens
+ assert!(get_or_create_browser_controller(&state, &team).await.is_some());
+}
+
+#[tokio::test]
+async fn an_idle_job_page_is_closed_but_never_one_with_an_open_step() {
+ 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();
+ get_or_create_browser_controller(&state, &team).await.unwrap();
+ hold(&state, &team, &key("held"), "t").await;
+
+ assert_eq!(browser_pages::sweep_idle(&state, browser_pages::JOB_PAGE_IDLE).await, 0, "pages just used stay open");
+ assert_eq!(browser_pages::sweep_idle(&state, Duration::ZERO).await, 1);
+ assert_eq!(open_pages(&state).await, vec![key("held")], "the held page stays");
+ assert!(state.browser_controllers.lock().await.contains_key(&team), "the team page is never swept");
+ assert_eq!(state.browser_service.job_pages(&team).await.len(), 1);
+
+ // A closed job page opens again on its next use
+ open_page(&state, &team, "idle").await.expect("reopens");
+ assert_eq!(open_pages(&state).await, vec![key("held"), key("idle")]);
+}
+
+/// A turn of bot `k` running in chat `chat` on `team`'s browser, until the guard drops.
+fn running_turn(state: &AppState, team: &str, chat: &str) -> impl Drop {
+ let scope = SelfScope {
+ kwant_id: "k".into(),
+ origin: Some(TurnOrigin { thread_id: Some(chat.into()), ..Default::default() }),
+ sandbox_target: Some(team.into()),
+ ..Default::default()
+ };
+ state.human_steps.track_turn(team, scope)
+}
+
+/// A job waiting minutes between two browser calls (a render) is the least recently used page,
+/// but while its turn runs neither the cap nor the idle sweep closes it; once the turn ends both do.
+#[tokio::test]
+async fn a_page_whose_job_still_has_a_turn_running_is_never_closed() {
+ 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();
+
+ // The cap: "busy" is the oldest page, its turn still runs, so the next oldest makes room
+ let turn = running_turn(&state, &team, "busy");
+ for chat in ["busy", "c1", "c2", "c3"] {
+ open_page(&state, &team, chat).await.expect("a job page opens");
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ open_page(&state, &team, "c4").await.expect("a fifth job opens a page");
+ assert_eq!(open_pages(&state).await, vec![key("busy"), key("c2"), key("c3"), key("c4")], "the running job's page is kept");
+ // The turn ends: its page is now the oldest one that can close
+ drop(turn);
+ open_page(&state, &team, "c5").await.unwrap();
+ assert_eq!(open_pages(&state).await, vec![key("c2"), key("c3"), key("c4"), key("c5")], "closed by the cap once its turn ended");
+
+ // The idle sweep: a running job's page stays however long it was unused
+ let turn = running_turn(&state, &team, "busy");
+ open_page(&state, &team, "busy").await.unwrap();
+ assert_eq!(browser_pages::sweep_idle(&state, Duration::ZERO).await, 3, "the other jobs' idle pages close");
+ assert_eq!(open_pages(&state).await, vec![key("busy")]);
+ drop(turn);
+ assert_eq!(browser_pages::sweep_idle(&state, Duration::ZERO).await, 1, "closed once its turn ended");
+ assert!(open_pages(&state).await.is_empty());
+}
+
+/// Every job page held: a fifth job's bot call waits for a page to free up, gets one as soon as
+/// a step ends, and when none frees up in time is told plainly that the pages are in use (not
+/// that the browser is broken), through the HTTP route and the bot's browser tool alike.
+#[tokio::test]
+async fn a_job_that_finds_every_page_in_use_waits_for_one_then_is_told_plainly() {
+ 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 base = serve().await;
+ let bot = first_bot(&state).await;
+ let team = bot.id.clone();
+ let key = |c: &str| job_page_key(&team, "k", c).unwrap();
+ let mut steps = Vec::new();
+ for chat in ["c0", "c1", "c2", "c3"] {
+ open_page(&state, &team, chat).await.expect("a job page opens");
+ steps.push(hold(&state, &team, &key(chat), chat).await);
+ }
+ let navigate = format!("/api/sandbox/{}/navigate", key("c4").replace('#', "%23"));
+ let body = json!({"url": format!("{base}/plain")});
+
+ // No page frees up in time: a clear 503, after the wait
+ state.job_pages.set_wait(Duration::from_millis(1500));
+ let started = std::time::Instant::now();
+ let (status, v) = request(&app, "POST", &navigate, Some(body.clone())).await;
+ assert!(started.elapsed() >= Duration::from_millis(1400), "it waited for a page first");
+ assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
+ assert_eq!(v["code"], PAGES_FULL);
+ assert_eq!(v["error"], browser_pages::pages_full_message());
+ assert!(v["error"].as_str().unwrap().contains("nothing is wrong with the browser"));
+ assert_eq!(open_pages(&state).await.len(), MAX_JOB_PAGES_PER_TEAM, "nothing was closed");
+ assert!(state.browser_service.job_pages(&team).await.iter().all(|(k, _)| *k != key("c4")), "the refused page isn't counted");
+
+ // The bot's own browser tool says the same
+ let token = turn_in_thread(&state, &bot, "turn-9", "t9", &team).await;
+ let (text, is_error) = call(&app, &token, "browser_open", json!({"url": format!("{base}/plain")})).await.unwrap();
+ assert!(is_error);
+ assert_eq!(text, browser_pages::pages_full_message());
+
+ // A step ends while the call waits: the page that freed up makes room, and the call goes on
+ state.job_pages.set_wait(Duration::from_secs(20));
+ let waiting = {
+ let (app, navigate, body) = (app.clone(), navigate.clone(), body.clone());
+ tokio::spawn(async move { request(&app, "POST", &navigate, Some(body)).await })
+ };
+ tokio::time::sleep(Duration::from_millis(1200)).await;
+ assert!(!waiting.is_finished(), "still waiting while every page is held");
+ assert!(state.db.close_human_step(&steps[0], "done").await.unwrap());
+ let (status, v) = tokio::time::timeout(Duration::from_secs(10), waiting).await.expect("answers soon after").unwrap();
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(open_pages(&state).await, vec![key("c1"), key("c2"), key("c3"), key("c4")], "the freed page made room");
+}
+
+/// Six jobs opening pages at the same moment never leave more than four open: making room and
+/// opening are one step per team.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn jobs_opening_pages_at_once_never_pass_the_cap() {
+ let tmp = tempdir().unwrap();
+ let Some((endpoint, _chrome)) = start_chrome(&tmp.path().join("chrome")).await else { return };
+ let state = container_state(&tmp, endpoint.clone()).await;
+ let team = first_bot(&state).await.id;
+ get_or_create_browser_controller(&state, &team).await.expect("the team page opens");
+ let page_targets = || async {
+ let targets: Value = reqwest::get(format!("{endpoint}/json/list")).await.unwrap().json().await.unwrap();
+ targets.as_array().unwrap().iter().filter(|t| t["type"] == "page").count()
+ };
+ let before = page_targets().await;
+ let opens: Vec<_> = (0..6)
+ .map(|i| {
+ let (state, team) = (state.clone(), team.clone());
+ tokio::spawn(async move { open_page(&state, &team, &format!("j{i}")).await.is_some() })
+ })
+ .collect();
+ for open in opens {
+ assert!(open.await.unwrap(), "each job gets a page (an older idle one makes room)");
+ }
+ assert_eq!(open_pages(&state).await.len(), MAX_JOB_PAGES_PER_TEAM);
+ assert_eq!(state.browser_service.job_pages(&team).await.len(), MAX_JOB_PAGES_PER_TEAM);
+ assert_eq!(page_targets().await, before + MAX_JOB_PAGES_PER_TEAM, "four job pages in the browser, the others closed");
+}
+
+#[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() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ db.set_setting(computer::SETTING_KEY, "local").await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(config.clone(), db, ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ let _chrome = ChromeGuard(tmp.path().join("local-chrome"));
+ let base = serve().await;
+ let team = first_bot(&state).await.id;
+ let a = open_page(&state, &team, "a").await.expect("local Chrome job page");
+ let b = open_page(&state, &team, "b").await.expect("a second job page");
+ a.navigate(&format!("{base}/signin")).await.unwrap();
+ b.navigate(&format!("{base}/other")).await.unwrap();
+ assert_eq!(title_becomes(&a, "sign in").await, "sign in");
+ assert_eq!(title_becomes(&b, "other").await, "other", "each job has its own page");
+ assert_eq!(eval(&b, "document.cookie").await, json!("kwnt_session=signed-in"), "the same Chrome, so the same sign-ins");
+}
diff --git a/tests/browser_screenshot_test.rs b/tests/browser_screenshot_test.rs
index 81f8dd2f..d35cfb29 100644
--- a/tests/browser_screenshot_test.rs
+++ b/tests/browser_screenshot_test.rs
@@ -154,7 +154,9 @@ async fn a_bot_sees_the_page_as_a_jpeg_at_the_width_it_asks_for() {
let url = serve_page().await;
let opened = rpc(&app, &token, "tools/call", json!({"name": "browser_open", "arguments": {"url": url}})).await;
assert_eq!(opened["isError"], false, "{opened}");
- let ctrl = state.browser_controllers.lock().await.get(&bot.id).cloned().unwrap();
+ // The turn runs in the bot's DM, so its browser tools use that job's own page (0.9.3)
+ let page = kwnt::server::browser_pages::job_page_key(&bot.id, &bot.id, &bot.id).unwrap();
+ let ctrl = state.browser_controllers.lock().await.get(&page).cloned().expect("the job's page");
let panel_before = ctrl.last_screenshot.lock().await.clone();
// At its own size: the VM browser's 1280×800
diff --git a/tests/captcha_test.rs b/tests/captcha_test.rs
index e0315088..25332735 100644
--- a/tests/captcha_test.rs
+++ b/tests/captcha_test.rs
@@ -315,7 +315,7 @@ async fn a_bot_landing_on_a_slider_gets_a_step_with_its_box_that_closes_once_sol
let card = state.db.get_message(step.message_id.as_deref().unwrap()).await.unwrap().unwrap();
let meta: Value = serde_json::from_str(card.meta.as_deref().unwrap()).unwrap();
assert_eq!(meta["target"]["kind"], "tiktok");
- let ctrl = state.browser_controllers.lock().await.get(step.sandbox_target.as_deref().unwrap()).cloned().unwrap();
+ let ctrl = state.browser_controllers.lock().await.get(step.page().unwrap()).cloned().unwrap();
// raise() holds the browser before the step is saved, so this can't see the step first
assert!(ctrl.is_held_for_person());
assert!(!task.is_finished(), "the turn waits for the person");
diff --git a/tests/captcha_turn_test.rs b/tests/captcha_turn_test.rs
index 7ff64cc6..ff41434a 100644
--- a/tests/captcha_turn_test.rs
+++ b/tests/captcha_turn_test.rs
@@ -263,12 +263,18 @@ async fn a_captcha_met_through_the_shell_browser_api_asks_the_person() {
assert!(read("Ossi", "curl2").contains("waiting on the person"));
assert_asked(&env, &bot, &mut events).await;
- // The person's own panel (the plain route) is told where their step is, not told to end a turn
- let (s, v) = call(&env.app, "POST", &format!("/api/sandbox/{bot}/navigate"), Some(json!({"url": format!("{}px_wall.html", env.fixtures)}))).await;
+ // The person's own panel (the plain route) on the step's page is told where their step is,
+ // not told to end a turn
+ let page = kwnt::server::browser_pages::job_page_key(&bot, &bot, &bot).unwrap();
+ let held = format!("/api/sandbox/{}/navigate", page.replace('#', "%23"));
+ let (s, v) = call(&env.app, "POST", &held, Some(json!({"url": format!("{}px_wall.html", env.fixtures)}))).await;
assert_eq!(s, StatusCode::CONFLICT, "{v}");
let error = v["error"].as_str().unwrap();
assert_eq!(error, kwnt::server::routes::HELD_FOR_PERSON);
assert!(error.contains("Take control") && !error.contains("end your turn"), "{error}");
+ // Only that page is held (0.9.3): the team page is free
+ let (s, v) = call(&env.app, "POST", &format!("/api/sandbox/{bot}/navigate"), Some(json!({"url": format!("{}px_wall.html", env.fixtures)}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
}
/// Two bots of one team share its browser and run at once (Rigel's N3, Oleks's "mixing
diff --git a/tests/human_step_test.rs b/tests/human_step_test.rs
index ae54a21c..1d0d8d41 100644
--- a/tests/human_step_test.rs
+++ b/tests/human_step_test.rs
@@ -53,8 +53,8 @@ async fn done_resumes_the_waiting_turn() {
assert_eq!((meta["kind"].as_str(), meta["human_step_id"].as_str(), meta["status"].as_str()), (Some("human_step"), Some(id.as_str()), Some("open")));
assert!(!card.text.contains("pw") && !card.text.contains("token"));
- // The bot's browser is the person's while the step is open
- if let Some(target) = s["sandbox_target"].as_str() {
+ // The bot's browser page (the job's own, 0.9.3) is the person's while the step is open
+ if let Some(target) = s["page_key"].as_str().or(s["sandbox_target"].as_str()) {
assert!(kwnt::server::human_steps::browser_is_held(&env.state, target).await);
}
@@ -64,7 +64,7 @@ async fn done_resumes_the_waiting_turn() {
let reply = wait_reply(&env, &env.a, "answer h1").await;
assert!(reply.text.contains("TOOL[The person says the step is done"), "{}", reply.text);
assert_eq!(step(&env, &id).await["step"]["status"], "done");
- if let Some(target) = s["sandbox_target"].as_str() {
+ if let Some(target) = s["page_key"].as_str().or(s["sandbox_target"].as_str()) {
assert!(!kwnt::server::human_steps::browser_is_held(&env.state, target).await, "handed back");
}
let card = messages(&env, &env.a).await.into_iter().find(|m| m.id == card.id).unwrap();