Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Close review gaps: redaction, atomic hire cap, browser cleanup, image v2
Lin (kwant bot)2e68bb07de8b
diff --git a/README.md b/README.mdindex ce29fbb7..f46f2ac1 100644--- a/README.md+++ b/README.md@@ -70,7 +70,7 @@ make run # builds the web app (frontend/dist), then runs `cargo run --Open **http://127.0.0.1:8799**. If no account works yet, kwant shows a **Get ready** banner with an **Add an account** button. A fresh install starts with three bots in `#general`: Architect, TechLead and DevOps. Make more with **New bot**, from a ready-made persona or blank.-The binary embeds `frontend/dist`, so `cargo run -- serve` on its own only works after the first `make run` (or `make frontend`).+The binary embeds `frontend/dist`, so on a fresh clone `cargo build`, `cargo test` and `cargo run -- serve` fail to compile until you've run `make run` or `make frontend` once.**The first start takes a few minutes:** kwant installs its Laya router and downloads its model (about 420 MB) in the background. Bots answer meanwhile, picked by keyword. To skip Laya, run `cargo run -- serve --no-laya`.diff --git a/docs/browser-service.md b/docs/browser-service.mdindex 86420479..5ab5a0d5 100644--- a/docs/browser-service.md+++ b/docs/browser-service.md@@ -39,12 +39,12 @@ Local mode gives up isolation: commands run with your user's access to your file## VM mode on a Mac or Linux VPS-Install Docker and start Kwnt normally. The first browser request builds the embedded browser image and starts a private container. Neither a desktop session nor a display server is required on the VPS. Subsequent requests reuse Chromium. The managed debugging port binds only to 127.0.0.1.+Install Docker and start Kwnt normally. The first browser request builds the embedded browser image and starts a private container. Neither a desktop session nor a display server is required on the VPS. Subsequent requests reuse Chromium. When an update ships a new browser image tag, the first browser request builds it and replaces kwant's browser container, so the bots' open pages close once. The managed debugging port binds only to 127.0.0.1.Prebuild images to avoid first-use latency:```bash-docker build -t kwnt-browser:v1 -f docker/browser.Dockerfile docker+docker build -t kwnt-browser:v2 -f docker/browser.Dockerfile dockerdocker build -t kwnt-executor:v1 -f docker/executor.Dockerfile docker./target/release/kwnt serve --host 127.0.0.1 --port 8799```diff --git a/site-src/docs-browser.html b/site-src/docs-browser.htmlindex 66aaf09c..e334117b 100644--- a/site-src/docs-browser.html+++ b/site-src/docs-browser.html@@ -31,7 +31,7 @@ nav: browser<h2 id="vm">VM mode with Docker</h2><p>Install Docker and start kwant. The first browser request builds the browser image from a recipe embedded in the binary and starts a private container, so a VPS with only the binary works too. No desktop or display server is needed. Prebuild the images to skip the first-use wait:</p>-<pre><code>docker build -t kwnt-browser:v1 -f docker/browser.Dockerfile docker+<pre><code>docker build -t kwnt-browser:v2 -f docker/browser.Dockerfile dockerdocker build -t kwnt-executor:v1 -f docker/executor.Dockerfile docker</code></pre><p>The browser shares a 1.5 GiB memory limit across all bots, rather than one Chromium per bot. Browser contexts keep cookies and local storage apart. They aren't OS isolation between users who don't trust each other.</p>diff --git a/site/docs/browser.html b/site/docs/browser.htmlindex 784245ac..2fbe51be 100644--- a/site/docs/browser.html+++ b/site/docs/browser.html@@ -75,7 +75,7 @@<h2 id="vm">VM mode with Docker</h2><p>Install Docker and start kwant. The first browser request builds the browser image from a recipe embedded in the binary and starts a private container, so a VPS with only the binary works too. No desktop or display server is needed. Prebuild the images to skip the first-use wait:</p>-<pre><code>docker build -t kwnt-browser:v1 -f docker/browser.Dockerfile docker+<pre><code>docker build -t kwnt-browser:v2 -f docker/browser.Dockerfile dockerdocker build -t kwnt-executor:v1 -f docker/executor.Dockerfile docker</code></pre><p>The browser shares a 1.5 GiB memory limit across all bots, rather than one Chromium per bot. Browser contexts keep cookies and local storage apart. They aren't OS isolation between users who don't trust each other.</p>diff --git a/src/drivers/activity.rs b/src/drivers/activity.rsindex e2bd9104..45ccffe1 100644--- a/src/drivers/activity.rs+++ b/src/drivers/activity.rs@@ -298,7 +298,8 @@ pub fn redact(text: &str, secrets: &[String]) -> String {}/// Replaces home folders in text shown to other people and bots with `~`: this computer's home-/// and anything shaped like `/home/<name>` or `/Users/<name>`, so a username doesn't leak.+/// and anything shaped like `/home/<name>`, `/Users/<name>` or `C:\Users\<name>`, so a username+/// doesn't leak.pub fn hide_home_paths(text: &str) -> String {let mut text = text.to_string();// A home elsewhere (`/root`, `/var/lib/kwant`); only whole folders, so `/rooted` stays@@ -309,8 +310,13 @@ pub fn hide_home_paths(text: &str) -> String {}let mut out = String::with_capacity(text.len());let mut rest = text.as_str();- while let Some((at, len)) = ["/home/", "/Users/"].iter().filter_map(|p| rest.find(p).map(|i| (i, p.len()))).min() {- let name_len = rest[at + len..].find(|c: char| c == '/' || c.is_whitespace() || "\"'`)]>:,;".contains(c)).unwrap_or(rest.len() - at - len);+ loop {+ let unix = ["/home/", "/Users/"].iter().filter_map(|p| rest.find(p).map(|i| (i, p.len()))).min();+ let Some((at, len)) = [unix, windows_users_folder(rest)].into_iter().flatten().min() else {+ break;+ };+ let quote = rest[..at].chars().next_back().filter(|c| "\"'`".contains(*c));+ let name_len = home_name_len(&rest[at + len..], quote);// `/home/` on its own (or inside a longer word like `/x/home/`) isn't someone's homelet starts_path = at == 0 || !rest[..at].ends_with(|c: char| c.is_alphanumeric() || "_-.".contains(c));if name_len == 0 || !starts_path {@@ -326,6 +332,61 @@ pub fn hide_home_paths(text: &str) -> String {out}+/// The length of the user name at the start of `s`, just after a home's `Users/`. A name with+/// spaces (`Oleks Smith`, up to three words) counts only when the path goes on after it or the+/// quote it opened with closes, so `/home/ann and more` stays `~ and more`.+fn home_name_len(s: &str, quote: Option<char>) -> usize {+ let word_end = |s: &str| s.find(|c: char| c == '/' || c == '\\' || c.is_whitespace() || "\"'`)]>:,;".contains(c)).unwrap_or(s.len());+ let first = word_end(s);+ let mut len = first;+ for _ in 0..2 {+ if first == 0 || !s[len..].starts_with(' ') {+ break;+ }+ let word = word_end(&s[len + 1..]);+ if word == 0 {+ break;+ }+ len += 1 + word;+ let next = s[len..].chars().next();+ if matches!(next, Some('/' | '\\')) || (next.is_some() && next == quote) {+ return len;+ }+ }+ first+}++/// Where the first Windows users folder (`C:\Users\`, `c:/users/`, or JSON-escaped+/// `C:\\Users\\`) starts in `text`, and its length up to the user name.+fn windows_users_folder(text: &str) -> Option<(usize, usize)> {+ let b = text.as_bytes();+ let separators = |mut j: usize| {+ while j < b.len() && (b[j] == b'\\' || b[j] == b'/') {+ j += 1;+ }+ j+ };+ let mut from = 0;+ while let Some(off) = text[from..].find(':') {+ let colon = from + off;+ from = colon + 1;+ // A drive letter on its own: `C:`, not the end of a word like `http:`+ if colon == 0 || !b[colon - 1].is_ascii_alphabetic() || (colon >= 2 && (b[colon - 2].is_ascii_alphanumeric() || b[colon - 2] == b'_')) {+ continue;+ }+ let users = separators(colon + 1);+ if users == colon + 1 || !b[users..].get(..5).is_some_and(|w| w.eq_ignore_ascii_case(b"users")) {+ continue;+ }+ let name = separators(users + 5);+ if name == users + 5 {+ continue;+ }+ return Some((colon - 1, name - (colon - 1)));+ }+ None+}+fn arg<'a>(args: &'a Value, keys: &[&str]) -> Option<&'a str> {keys.iter().find_map(|k| args.get(*k).and_then(Value::as_str)).filter(|s| !s.trim().is_empty())}@@ -543,8 +604,18 @@ mod tests {fn home_folders_are_hidden() {assert_eq!(hide_home_paths("open /home/oleks/.kwnt/data.db failed; see /Users/Oleks Smith/x and /home/ann"),- "open ~/.kwnt/data.db failed; see ~ Smith/x and ~"+ "open ~/.kwnt/data.db failed; see ~/x and ~");+ // A name with spaces, whole, when the path goes on or its quotes close+ assert_eq!(hide_home_paths("at /Users/Ann Marie Lee/Library/x"), "at ~/Library/x");+ assert_eq!(hide_home_paths("open '/Users/Oleks Smith' failed"), "open '~' failed");+ assert_eq!(hide_home_paths("/home/ann and then /tmp/x"), "~ and then /tmp/x", "a sentence after a name isn't the name");+ // Windows homes, either slash, any case, and escaped in JSON+ assert_eq!(hide_home_paths(r"C:\Users\Oleks Smith\AppData\kwnt.log"), r"~\AppData\kwnt.log");+ assert_eq!(hide_home_paths("d:/users/oleks/x and C:/Users/ann"), "~/x and ~");+ assert_eq!(hide_home_paths(r#"{"path":"C:\\Users\\oleks\\x"}"#), r#"{"path":"~\\x"}"#);+ // Not a Windows home: another folder, or a URL scheme+ assert_eq!(hide_home_paths(r"C:\Program Files\kwnt and note:\Users\x"), r"C:\Program Files\kwnt and note:\Users\x");// Not a home: a bare `/home/`, or `home` inside another pathassert_eq!(hide_home_paths("/home/ and /srv/home/app"), "/home/ and /srv/home/app");assert_eq!(hide_home_paths("no paths here"), "no paths here");diff --git a/src/sandbox/service.rs b/src/sandbox/service.rsindex 0c937be9..301a0fe7 100644--- a/src/sandbox/service.rs+++ b/src/sandbox/service.rs@@ -7,6 +7,13 @@ use serde_json::json;use std::{collections::HashMap, path::{Path, PathBuf}, time::Duration};use tokio::{process::Command, sync::Mutex, time::{sleep, timeout}};+/// The VM browser's image. Bump it whenever `docker/browser.Dockerfile` or+/// `docker/browser-entrypoint.sh` change: kwant builds an image only when its tag is missing, and+/// replaces a browser container made from another tag, so the bump is what ships the change.+pub const BROWSER_IMAGE: &str = "kwnt-browser:v2";+const BROWSER_DOCKERFILE: &str = include_str!("../../docker/browser.Dockerfile");+const BROWSER_ENTRYPOINT: &str = include_str!("../../docker/browser-entrypoint.sh");+#[derive(Clone, Serialize, Deserialize)]struct SessionTarget {context: String,@@ -184,29 +191,30 @@ impl BrowserService {}async fn managed_endpoint(&self) -> Result<String, BrowserError> {- // A deterministic installation name avoids collisions between local Kwnt instances.- use std::hash::{Hash, Hasher};- let mut hash = std::collections::hash_map::DefaultHasher::new();- self.root.hash(&mut hash);- let name = format!("kwnt-browser-{:016x}", hash.finish());- if !matches!(Self::docker(&["inspect", "--format", "{{.State.Running}}", &name], 5).await.as_deref(), Ok("true")) {- if Self::docker(&["inspect", "--format", "{{.Id}}", &name], 5).await.is_ok() {+ let name = managed_container_name(&self.root);+ let image = Self::docker(&["inspect", "--format", "{{.Config.Image}}", &name], 5).await.ok();+ // A container made from an older image keeps that image's browser: make a new one+ if image.as_deref().is_some_and(|i| i != BROWSER_IMAGE) {+ Self::docker(&["rm", "-f", &name], 30).await?;+ }+ if image.as_deref() == Some(BROWSER_IMAGE) {+ if !matches!(Self::docker(&["inspect", "--format", "{{.State.Running}}", &name], 5).await.as_deref(), Ok("true")) {Self::docker(&["start", &name], 30).await?;- } else {- if Self::docker(&["image", "inspect", "kwnt-browser:v1"], 5).await.is_err() {- let build = self.root.join("browser-image");- tokio::fs::create_dir_all(&build).await.map_err(|e| BrowserError::Http(e.to_string()))?;- tokio::fs::write(build.join("Dockerfile"), include_str!("../../docker/browser.Dockerfile")).await- .map_err(|e| BrowserError::Http(e.to_string()))?;- tokio::fs::write(build.join("browser-entrypoint.sh"), include_str!("../../docker/browser-entrypoint.sh")).await- .map_err(|e| BrowserError::Http(e.to_string()))?;- Self::docker(&["build", "-t", "kwnt-browser:v1", &build.to_string_lossy()], 600).await?;- }- Self::docker(&["run", "-d", "--name", &name, "--restart", "unless-stopped",- "--init", "--cap-drop=ALL", "--security-opt=no-new-privileges", "--memory=1536m",- "--cpus=2", "--pids-limit=512", "--read-only", "--tmpfs", "/tmp:rw,nosuid,size=512m",- "-p", "127.0.0.1::9222", "kwnt-browser:v1"], 30).await?;}+ } else {+ if Self::docker(&["image", "inspect", BROWSER_IMAGE], 5).await.is_err() {+ let build = self.root.join("browser-image");+ tokio::fs::create_dir_all(&build).await.map_err(|e| BrowserError::Http(e.to_string()))?;+ tokio::fs::write(build.join("Dockerfile"), BROWSER_DOCKERFILE).await+ .map_err(|e| BrowserError::Http(e.to_string()))?;+ tokio::fs::write(build.join("browser-entrypoint.sh"), BROWSER_ENTRYPOINT).await+ .map_err(|e| BrowserError::Http(e.to_string()))?;+ Self::docker(&["build", "-t", BROWSER_IMAGE, &build.to_string_lossy()], 600).await?;+ }+ Self::docker(&["run", "-d", "--name", &name, "--restart", "unless-stopped",+ "--init", "--cap-drop=ALL", "--security-opt=no-new-privileges", "--memory=1536m",+ "--cpus=2", "--pids-limit=512", "--read-only", "--tmpfs", "/tmp:rw,nosuid,size=512m",+ "-p", "127.0.0.1::9222", BROWSER_IMAGE], 30).await?;}let binding = Self::docker(&["port", &name, "9222/tcp"], 5).await?;let port = binding.lines().next().and_then(|line| line.rsplit(':').next())@@ -334,3 +342,33 @@ impl BrowserService {Ok(())}}++/// The VM browser container of the kwant whose data folder is `root`: one name per installation+/// avoids collisions between local kwant instances.+pub fn managed_container_name(root: &Path) -> String {+ use std::hash::{Hash, Hasher};+ let mut hash = std::collections::hash_map::DefaultHasher::new();+ root.hash(&mut hash);+ format!("kwnt-browser-{:016x}", hash.finish())+}++#[cfg(test)]+mod image_tests {+ use super::{BROWSER_DOCKERFILE, BROWSER_ENTRYPOINT, BROWSER_IMAGE};+ use sha2::{Digest, Sha256};++ /// The browser files `kwnt-browser:v2` was built from. A change to them without a new+ /// [`BROWSER_IMAGE`] would never reach a computer that already has the old tag.+ #[test]+ fn the_browser_image_tag_moves_with_its_files() {+ let mut files = Sha256::new();+ files.update(BROWSER_DOCKERFILE);+ files.update(BROWSER_ENTRYPOINT);+ let hash: String = files.finalize().iter().take(8).map(|b| format!("{b:02x}")).collect();+ assert_eq!(+ (BROWSER_IMAGE, hash.as_str()),+ ("kwnt-browser:v2", "52d86739629ce24f"),+ "docker/browser files changed: bump BROWSER_IMAGE, then record the new hash here"+ );+ }+}diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rsindex d43bd21e..4b7d6c73 100644--- a/src/server/bot_actions.rs+++ b/src/server/bot_actions.rs@@ -1127,6 +1127,7 @@ impl Ctx<'_> {// requested_by_person is only this bot's word, so it shares the daily cap on bots made// without a card; past it, the person confirms the bot themselveslet cap = crate::db::hires::AUTO_HIRES_PER_DAY;+ let _cap = super::hires::AUTO_HIRE_CAP.lock().await;if self.state.db.auto_hires_today(&self.space).await.unwrap_or(i64::MAX) >= cap {return fail(format!("Nothing was created: {cap} bots were already made without a card in the last 24 hours. \diff --git a/src/server/hires.rs b/src/server/hires.rsindex 73fa31b5..672dc7c0 100644--- a/src/server/hires.rs+++ b/src/server/hires.rs@@ -471,6 +471,7 @@ async fn propose(state: &AppState, scope: &SelfScope, space: &SpaceId, args: &Vanote = Some("A team proposal always asks you, even with \"always accept\".".to_string());}} else if policy == "auto" && denied.is_none() {+ let _cap = AUTO_HIRE_CAP.lock().await;let used = state.db.auto_hires_today(space).await.unwrap_or(i64::MAX);if used < AUTO_HIRES_PER_DAY {return match accept(state, &hire, true).await {@@ -631,6 +632,10 @@ pub(super) async fn undone(state: &AppState, id: &str) {refresh(state, id, None).await;}+/// Held from counting today's automatic hires until the new one is recorded, by automatic+/// accepts and `bot_create`, so two at once can't both see room under [`AUTO_HIRES_PER_DAY`].+pub(super) static AUTO_HIRE_CAP: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());+/// Creates the bot for a pending proposal: same path as `bot_create`, plus its tools and team,/// logged as a `bot_hire` action for Undo. Puts the proposal back to pending on failure.async fn accept(state: &AppState, h: &Hire, auto: bool) -> Result<Hire, (StatusCode, String)> {diff --git a/src/server/routes.rs b/src/server/routes.rsindex 3b05a3ad..91eded23 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3760,6 +3760,10 @@ mod tests {assert!(text.ends_with('…') && text.len() < 700, "{} bytes", text.len());// A short error is kept wholeassert!(!turn_failed_text("Lin", "the turn ended without a reply", &activity).ends_with('…'));+ // Whole user names, with spaces and on Windows+ let text = turn_failed_text("Lin", r"no config at /Users/Oleks Smith/.kwnt or C:\Users\Oleks Smith\.kwnt", &activity);+ assert!(!text.contains("Oleks") && !text.contains("Smith"), "{text}");+ assert!(text.ends_with(r"no config at ~/.kwnt or ~\.kwnt"), "{text}");}#[test]diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rsindex d7affb79..e2acb69e 100644--- a/tests/browser_stream_test.rs+++ b/tests/browser_stream_test.rs@@ -153,10 +153,11 @@ async fn stream_input_control_lease_and_origin_protection() {/// Opt in after building docker/browser.Dockerfile. Uses disposable data and a local HTML page.#[tokio::test]-#[ignore = "requires Docker and the kwnt-browser:v1 image"]+#[ignore = "requires Docker and the kwnt-browser:v2 image"]async fn live_chromium_stream_and_isolated_sessions() {let _ = tracing_subscriber::fmt().with_max_level(tracing::Level::WARN).try_init();let tmp = tempfile::tempdir().unwrap();+ let _container = Container(kwnt::sandbox::service::managed_container_name(tmp.path()));let config = Config { data_dir: tmp.path().into(), ..Config::default() };let db = Database::init(tmp.path()).await.unwrap();let bots = db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();@@ -209,3 +210,41 @@ async fn live_chromium_stream_and_isolated_sessions() {state.browser_service.reset(&bots[1].id).await.unwrap();task.abort();}++/// Removes a test's browser container when the test ends: kwant starts it with+/// `--restart unless-stopped` and never removes it, so each disposable data folder would leave+/// one running.+struct Container(String);++impl Drop for Container {+ fn drop(&mut self) {+ let _ = std::process::Command::new("docker").args(["rm", "-f", &self.0]).output();+ }+}++/// Opt in after building docker/browser.Dockerfile as kwnt-browser:v2, with kwnt-browser:v1 kept:+/// a browser container made from an older image is replaced, so an image change reaches it.+#[tokio::test]+#[ignore = "requires Docker and the kwnt-browser:v1 and :v2 images"]+async fn a_browser_container_from_an_older_image_is_replaced() {+ let tmp = tempfile::tempdir().unwrap();+ let name = kwnt::sandbox::service::managed_container_name(tmp.path());+ let _container = Container(name.clone());+ let made = std::process::Command::new("docker")+ .args(["run", "-d", "--name", &name, "--init", "-p", "127.0.0.1::9222", "kwnt-browser:v1"])+ .output()+ .unwrap();+ assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));+ let image = || {+ let out = std::process::Command::new("docker").args(["inspect", "--format", "{{.Config.Image}}", &name]).output().unwrap();+ String::from_utf8_lossy(&out.stdout).trim().to_string()+ };+ assert_eq!(image(), "kwnt-browser:v1");++ let service = BrowserService::new(tmp.path().into(), None);+ service.set_mode(kwnt::sandbox::computer::ComputerMode::Vm).await;+ let ctrl = service.session("bot", tmp.path()).await.expect("a browser from the new image");+ assert_eq!(image(), kwnt::sandbox::service::BROWSER_IMAGE);+ let agent = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": "navigator.userAgent", "returnByValue": true})).await.unwrap();+ assert!(agent.to_string().contains("Chrome/") && !agent.to_string().contains("Headless"), "{agent}");+}diff --git a/tests/browser_tools_test.rs b/tests/browser_tools_test.rsindex fcc10591..226c9912 100644--- a/tests/browser_tools_test.rs+++ b/tests/browser_tools_test.rs@@ -4,6 +4,9 @@//! only the turn's own sandbox. The browser part runs a real windowless Chrome in Local mode and//! is skipped when none is installed.+#[path = "support/chrome_guard.rs"]+mod chrome_guard;+use chrome_guard::ChromeGuard;use axum::{body::{to_bytes, Body},http::{Request, StatusCode},@@ -113,6 +116,7 @@ async fn claude_turn_gets_browser_tools_that_drive_its_own_panel() {std::env::remove_var("WAYLAND_DISPLAY");std::env::set_var("KWNT_COMPUTER_MODE", "local");let (app, state, _tmp) = setup().await;+ let _chrome = ChromeGuard(state.config.data_dir.join("local-chrome"));let kwants = state.db.list_kwants(&SpaceId::default_space()).await.unwrap();let (bot, other) = (&kwants[0], &kwants[1]);let scope = |sandbox: Option<&str>| SelfScope {diff --git a/tests/hires_test.rs b/tests/hires_test.rsindex 8f698a00..77acbb0a 100644--- a/tests/hires_test.rs+++ b/tests/hires_test.rs@@ -595,3 +595,44 @@ async fn bot_create_counts_against_the_daily_auto_hire_cap() {assert!(text.contains("Nothing is created"), "{text}");assert_eq!(latest(&e).await["status"], "pending");}++/// Counting the day's automatic hires and making the bot are one step: bots creating bots at+/// the same moment, and "always accept" hiring alongside them, still stop at the daily cap.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn simultaneous_hires_cannot_pass_the_daily_cap() {+ let e = setup().await;+ let (_, _) = call(&e.app, "PUT", "/api/spaces/spc_default/hire-policy", None, Some(json!({"policy": "auto"}))).await;+ let roles = [+ ("Taxman", "Tax advisor"),+ ("Coach", "Fitness coach"),+ ("Gardener", "Garden designer"),+ ("Painter", "Portrait painter"),+ ("Baker", "Bread recipe planner"),+ ("Pilot", "Flight route planner"),+ ];+ let mut tokens = Vec::new();+ for i in 0..roles.len() {+ tokens.push(turn(&e, &format!("t-race{i}")).await);+ }+ let calls = roles.iter().zip(&tokens).enumerate().map(|(i, ((name, role), token))| {+ let e = &e;+ async move {+ if i % 2 == 0 {+ let args = json!({"name": name, "title": role, "instructions": format!("You are {name}."), "requested_by_person": true});+ tool(e, token, "bot_create", args).await;+ } else {+ tool(e, token, "propose_hire", specialist(name, role)).await;+ }+ }+ });+ futures::future::join_all(calls).await;+ let mut made = Vec::new();+ for (name, _) in roles {+ if bot_named(&e, "spc_default", name).await.is_some() {+ made.push(name);+ }+ }+ assert_eq!(made.len(), 3, "only 3 bots a day without the person: {made:?}");+ let (_, p) = call(&e.app, "GET", "/api/spaces/spc_default/hire-policy", None, None).await;+ assert_eq!(p["auto_hires_last_24h"], 3, "{p}");+}diff --git a/tests/local_chrome_test.rs b/tests/local_chrome_test.rsindex 3beb5ca3..de210bdb 100644--- a/tests/local_chrome_test.rs+++ b/tests/local_chrome_test.rs@@ -1,6 +1,9 @@//! Local mode against a real Chrome/Chromium: it runs without a window, pages render and take//! input at the viewer's 1280x800 size, and the window switch reopens the same page in a real//! window and back. Skipped when no Chrome is installed; the window part needs Xvfb on Linux.+#[path = "support/chrome_guard.rs"]+mod chrome_guard;+use chrome_guard::ChromeGuard;use kwnt::sandbox::{computer::{self, ComputerMode},service::BrowserService,@@ -62,6 +65,7 @@ async fn local_chrome_runs_windowless_and_can_open_as_a_window() {}let tmp = tempfile::tempdir().unwrap();let profile = tmp.path().join("local-chrome");+ let _chrome = ChromeGuard(profile.clone());let service = BrowserService::new(tmp.path().to_path_buf(), None);service.set_mode(ComputerMode::Local).await;let url = serve_page().await;diff --git a/tests/local_chrome_upgrade_test.rs b/tests/local_chrome_upgrade_test.rsindex 671b433b..4ba4e449 100644--- a/tests/local_chrome_upgrade_test.rs+++ b/tests/local_chrome_upgrade_test.rs@@ -1,6 +1,9 @@//! Upgrading kwant with its windowless Chrome still running: that Chrome was started without//! kwant's user agent and tells sites it is "HeadlessChrome", so kwant restarts it once, and never//! again after. Skipped when no Chrome is installed.+#[path = "support/chrome_guard.rs"]+mod chrome_guard;+use chrome_guard::ChromeGuard;use kwnt::sandbox::{computer::{self, ComputerMode},service::BrowserService,@@ -23,6 +26,7 @@ async fn an_older_kwants_headless_chrome_is_restarted_once() {let tmp = tempfile::tempdir().unwrap();let profile = tmp.path().join("local-chrome");std::fs::create_dir_all(&profile).unwrap();+ let _chrome = ChromeGuard(profile.clone());// what an older kwant left running: windowless, its own user agent, no launch recordlet mut old = std::process::Command::new(&chrome)diff --git a/tests/support/chrome_guard.rs b/tests/support/chrome_guard.rsnew file mode 100644index 00000000..f094cfac--- /dev/null+++ b/tests/support/chrome_guard.rs@@ -0,0 +1,19 @@+//! Stops the Chrome a test started on its profile when the test ends, also when an assert fails+//! first: a test's own cleanup at its end never runs then, and the Chrome, detached from the test,+//! would keep running with nothing to close it.++use std::path::PathBuf;++pub struct ChromeGuard(pub PathBuf);++impl Drop for ChromeGuard {+ fn drop(&mut self) {+ // Nothing when the test closed its Chrome itself+ if let Some(pid) = kwnt::sandbox::computer::profile_owner(&self.0) {+ // SAFETY: kill(2) with a pid that profile_owner just saw as this profile's Chrome+ unsafe {+ libc::kill(pid as libc::pid_t, libc::SIGKILL);+ }+ }+ }+}