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
Add local/vm computer mode with runtime switching
Lin (kwant bot)9355c9ade288
diff --git a/docs/browser-service.md b/docs/browser-service.mdindex 2a8b8ed4..10f9e0e3 100644--- a/docs/browser-service.md+++ b/docs/browser-service.md@@ -6,7 +6,32 @@ Clicks, text, keys, and scroll events are acknowledged independently of frames.Take Control obtains an exclusive server-side lease. Bot navigation and selector actions return a conflict while the person holds it; other viewers cannot acquire it. Returning control, closing the pane, or disconnecting releases the lease. The connection has heartbeat and slow-client timeouts. This pauses browser actions, not the entire agent conversation or host CLI process.-## Local Mac or Linux VPS+## Computer mode: local or VM++Kwnt runs bots' browser and shell commands in one of two places, chosen in **Settings → Computer** or with the browser panel's mode toggle:++- **Local computer** (`local`, the default on macOS): Kwnt opens your installed Chrome or Chromium in a visible window with its own profile, `<data dir>/local-chrome`. It never uses your everyday Chrome profile. Each bot gets its own tab. Sign-ins made in that window are kept in the kwant profile and shared by its tabs. The debugging port is chosen by Chrome and listens on 127.0.0.1 only. Shell commands run on your computer in the bot's working folder, and **every command asks for your approval first**. "Always allow" applies to that one command; it is not remembered. Docker is not needed.+- **VM (isolated)** (`vm`, the default everywhere else, including a VPS): the Docker browser and execution containers described below.++Switching takes effect at once, without a restart. Kwnt disconnects from the old browser without closing it: the local Chrome window and the VM container both keep running, and switching back reuses them. Each mode keeps its own saved pages (`browser-sessions-local.json` and `browser-sessions.json`). If the local window was closed, the next browser action opens it again. Kwnt does not close the window when it stops, either.++Precedence: a choice saved in Settings wins; otherwise `KWNT_COMPUTER_MODE=local|vm`; otherwise the platform default. `KWNT_CHROME_PATH` names the browser binary local mode launches. Without it, Kwnt looks for Google Chrome, Chromium or Chrome Canary in `/Applications` and `~/Applications` on macOS, then for `google-chrome`, `google-chrome-stable`, `chromium`, `chromium-browser` or `chrome` on `PATH`.++A mode that cannot run here is refused with the reason: local needs a Chrome binary and a display (always present on macOS; `DISPLAY` or `WAYLAND_DISPLAY` on Linux). VM needs Docker, or a `KWNT_BROWSER_CDP_URL` for the browser.++API (same authentication as the other settings routes):++```text+GET /api/settings/computer+→ {"mode":"local"|"vm","available":{"local":bool,"vm":bool},"reasons":{"local":string|null,"vm":string|null}}++PUT /api/settings/computer {"mode":"local"|"vm"}+→ the same shape after switching; 400 {"error":"<reason>"} for an unknown or unavailable mode+```++Local mode gives up isolation: commands run with your user's access to your files, and the debugging port can be reached by other programs on the same computer while the kwant window is open. Use VM mode for untrusted work.++## VM mode on a Mac or Linux VPSInstall 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.diff --git a/src/sandbox/computer.rs b/src/sandbox/computer.rsnew file mode 100644index 00000000..1396ba87--- /dev/null+++ b/src/sandbox/computer.rs@@ -0,0 +1,381 @@+//! Where bots do computer work: the person's own computer ("local": their installed Chrome with a+//! kwant-only profile, and host shell commands that each need approval) or isolated containers+//! ("vm": the Docker browser and executor). Local is the default on macOS, vm everywhere else.+use serde::{Deserialize, Serialize};+use std::path::{Path, PathBuf};+use std::time::Duration;++/// Settings row holding the person's explicit choice.+pub const SETTING_KEY: &str = "computer_mode";+/// Overrides the platform default (not an explicit saved choice).+pub const MODE_ENV: &str = "KWNT_COMPUTER_MODE";+/// Path to the Chrome/Chromium binary local mode launches, instead of searching for one.+pub const CHROME_PATH_ENV: &str = "KWNT_CHROME_PATH";++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum ComputerMode {+ Local,+ Vm,+}++impl ComputerMode {+ pub fn parse(value: &str) -> Option<Self> {+ match value.trim().to_ascii_lowercase().as_str() {+ "local" => Some(Self::Local),+ "vm" => Some(Self::Vm),+ _ => None,+ }+ }++ pub fn as_str(self) -> &'static str {+ match self {+ Self::Local => "local",+ Self::Vm => "vm",+ }+ }+}++/// The mode used when the person has not chosen one: a valid env value, else local on macOS+/// (`os` is `std::env::consts::OS`) and vm elsewhere.+pub fn default_mode(os: &str, env: Option<&str>) -> ComputerMode {+ env.and_then(ComputerMode::parse)+ .unwrap_or(if os == "macos" {+ ComputerMode::Local+ } else {+ ComputerMode::Vm+ })+}++/// A valid saved choice wins over the env/platform default.+pub fn effective_mode(saved: Option<&str>, os: &str, env: Option<&str>) -> ComputerMode {+ saved+ .and_then(ComputerMode::parse)+ .unwrap_or_else(|| default_mode(os, env))+}++/// [`effective_mode`] for this process's OS and environment.+pub fn current_mode(saved: Option<&str>) -> ComputerMode {+ effective_mode(+ saved,+ std::env::consts::OS,+ std::env::var(MODE_ENV).ok().as_deref(),+ )+}++const MAC_CHROME_APPS: [&str; 3] = [+ "Google Chrome.app/Contents/MacOS/Google Chrome",+ "Chromium.app/Contents/MacOS/Chromium",+ "Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",+];+const CHROME_COMMANDS: [&str; 5] = [+ "google-chrome",+ "google-chrome-stable",+ "chromium",+ "chromium-browser",+ "chrome",+];++/// Finds the browser local mode launches: the override if it names a file, else the macOS app+/// bundles (in `/Applications` and `~/Applications`), else a Chrome/Chromium command on `path`.+pub fn find_chrome(+ override_path: Option<&str>,+ os: &str,+ home: Option<&Path>,+ path: Option<&str>,+) -> Option<PathBuf> {+ if let Some(p) = override_path.filter(|p| !p.trim().is_empty()) {+ return Path::new(p).is_file().then(|| PathBuf::from(p));+ }+ if os == "macos" {+ let roots = [+ Some(PathBuf::from("/Applications")),+ home.map(|h| h.join("Applications")),+ ];+ for root in roots.iter().flatten() {+ for app in MAC_CHROME_APPS {+ let candidate = root.join(app);+ if candidate.is_file() {+ return Some(candidate);+ }+ }+ }+ }+ let path = path?;+ std::env::split_paths(path).find_map(|dir| {+ CHROME_COMMANDS+ .iter()+ .map(|name| dir.join(name))+ .find(|candidate| candidate.is_file())+ })+}++/// Whether a window can be shown: always on macOS and Windows, on Linux only with an X11 or+/// Wayland display.+pub fn has_display(os: &str, display: Option<&str>, wayland: Option<&str>) -> bool {+ match os {+ "linux" | "freebsd" | "openbsd" | "netbsd" => {+ display.is_some_and(|d| !d.is_empty()) || wayland.is_some_and(|d| !d.is_empty())+ }+ _ => true,+ }+}++/// Why local mode cannot run here, or `None` if it can.+pub fn local_unavailable_reason(chrome: Option<&Path>, display: bool) -> Option<String> {+ if chrome.is_none() {+ return Some(format!(+ "No Chrome or Chromium was found. Install Google Chrome, or set {CHROME_PATH_ENV} to its path."+ ));+ }+ if !display {+ return Some(+ "This computer has no screen to show a browser window on (no display).".into(),+ );+ }+ None+}++/// Why vm mode cannot run here, or `None` if it can. A configured browser service URL is enough+/// for the browser even without Docker.+pub fn vm_unavailable_reason(docker: bool, browser_url_configured: bool) -> Option<String> {+ (!docker && !browser_url_configured).then(|| {+ "Docker is not installed or not running. Install and start Docker (Docker Desktop on a Mac) to use the VM."+ .into()+ })+}++/// The local Chrome this process would launch, from the real environment.+pub fn local_chrome_path() -> Option<PathBuf> {+ let home = std::env::var_os("HOME").map(PathBuf::from);+ find_chrome(+ std::env::var(CHROME_PATH_ENV).ok().as_deref(),+ std::env::consts::OS,+ home.as_deref(),+ std::env::var("PATH").ok().as_deref(),+ )+}++/// [`local_unavailable_reason`] for this process's environment.+pub fn local_reason() -> Option<String> {+ let os = std::env::consts::OS;+ let display = has_display(+ os,+ std::env::var("DISPLAY").ok().as_deref(),+ std::env::var("WAYLAND_DISPLAY").ok().as_deref(),+ );+ local_unavailable_reason(local_chrome_path().as_deref(), display)+}++/// Reads the debugging port Chrome writes to `DevToolsActivePort` in its profile folder.+pub fn read_devtools_port(profile: &Path) -> Option<u16> {+ let text = std::fs::read_to_string(profile.join("DevToolsActivePort")).ok()?;+ text.lines().next()?.trim().parse().ok().filter(|&p| p > 0)+}++/// Chrome's command line for local mode: a headed window with its own profile, never the+/// person's everyday one, and a debugging port Chrome picks itself (it listens on 127.0.0.1).+pub fn chrome_args(profile: &Path) -> Vec<String> {+ vec![+ format!("--user-data-dir={}", profile.display()),+ "--remote-debugging-port=0".into(),+ "--remote-debugging-address=127.0.0.1".into(),+ "--no-first-run".into(),+ "--no-default-browser-check".into(),+ "about:blank".into(),+ ]+}++async fn answers(endpoint: &str) -> bool {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(2))+ .build()+ .unwrap_or_default();+ client+ .get(format!("{endpoint}/json/version"))+ .send()+ .await+ .is_ok_and(|r| r.status().is_success())+}++/// Returns the CDP endpoint of the kwant Chrome window, reusing it while it runs and launching+/// it (detached, so it outlives a switch or a kwant restart) when it does not.+pub async fn ensure_local_chrome(profile: &Path) -> Result<String, String> {+ if let Some(port) = read_devtools_port(profile) {+ let endpoint = format!("http://127.0.0.1:{port}");+ if answers(&endpoint).await {+ return Ok(endpoint);+ }+ }+ let chrome = local_chrome_path().ok_or_else(|| local_reason().unwrap_or_default())?;+ std::fs::create_dir_all(profile).map_err(|e| e.to_string())?;+ // a stale port file from a closed window would point at nothing+ let _ = std::fs::remove_file(profile.join("DevToolsActivePort"));+ let mut cmd = std::process::Command::new(&chrome);+ cmd.args(chrome_args(profile))+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null());+ #[cfg(unix)]+ {+ // its own process group, so Ctrl+C on kwnt does not close the person's window+ use std::os::unix::process::CommandExt;+ cmd.process_group(0);+ }+ let mut child = cmd+ .spawn()+ .map_err(|e| format!("Could not start {}: {e}", chrome.display()))?;+ // reap it when it exits; never kill it+ std::thread::spawn(move || {+ let _ = child.wait();+ });+ for _ in 0..80 {+ if let Some(port) = read_devtools_port(profile) {+ let endpoint = format!("http://127.0.0.1:{port}");+ if answers(&endpoint).await {+ return Ok(endpoint);+ }+ }+ tokio::time::sleep(Duration::from_millis(250)).await;+ }+ Err("Chrome started but did not open its debugging port within 20 seconds.".into())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn default_is_local_on_macos_and_vm_elsewhere() {+ assert_eq!(default_mode("macos", None), ComputerMode::Local);+ assert_eq!(default_mode("linux", None), ComputerMode::Vm);+ assert_eq!(default_mode("windows", None), ComputerMode::Vm);+ }++ #[test]+ fn env_overrides_default_and_saved_overrides_env() {+ assert_eq!(default_mode("linux", Some("local")), ComputerMode::Local);+ assert_eq!(default_mode("macos", Some(" VM ")), ComputerMode::Vm);+ // a bad env value is ignored+ assert_eq!(default_mode("macos", Some("docker")), ComputerMode::Local);+ assert_eq!(+ effective_mode(Some("vm"), "macos", Some("local")),+ ComputerMode::Vm+ );+ assert_eq!(+ effective_mode(Some("local"), "linux", Some("vm")),+ ComputerMode::Local+ );+ assert_eq!(+ effective_mode(None, "linux", Some("local")),+ ComputerMode::Local+ );+ // a bad saved value falls back to the default+ assert_eq!(+ effective_mode(Some("??"), "macos", None),+ ComputerMode::Local+ );+ }++ #[test]+ fn mode_round_trips_as_lowercase_json() {+ assert_eq!(+ serde_json::to_string(&ComputerMode::Local).unwrap(),+ "\"local\""+ );+ assert_eq!(+ serde_json::from_str::<ComputerMode>("\"vm\"").unwrap(),+ ComputerMode::Vm+ );+ assert!(serde_json::from_str::<ComputerMode>("\"VM\"").is_err());+ assert_eq!(ComputerMode::parse("Local"), Some(ComputerMode::Local));+ assert_eq!(ComputerMode::parse(""), None);+ }++ #[test]+ fn chrome_is_found_by_override_or_on_path() {+ let dir = tempfile::tempdir().unwrap();+ let bin = dir.path().join("chromium");+ std::fs::write(&bin, "").unwrap();+ let path = dir.path().to_string_lossy().to_string();+ assert_eq!(+ find_chrome(None, "linux", None, Some(&path)),+ Some(bin.clone())+ );+ let custom = dir.path().join("my-chrome");+ std::fs::write(&custom, "").unwrap();+ assert_eq!(+ find_chrome(Some(custom.to_str().unwrap()), "linux", None, Some(&path)),+ Some(custom)+ );+ // an override naming nothing finds nothing, rather than silently using another browser+ assert_eq!(+ find_chrome(Some("/nope/chrome"), "linux", None, Some(&path)),+ None+ );+ let empty = tempfile::tempdir().unwrap();+ assert_eq!(+ find_chrome(None, "linux", None, Some(&empty.path().to_string_lossy())),+ None+ );+ assert_eq!(find_chrome(None, "linux", None, None), None);+ }++ #[test]+ fn chrome_is_found_in_mac_user_applications() {+ let home = tempfile::tempdir().unwrap();+ let app = home.path().join("Applications/Chromium.app/Contents/MacOS");+ std::fs::create_dir_all(&app).unwrap();+ std::fs::write(app.join("Chromium"), "").unwrap();+ let found = find_chrome(None, "macos", Some(home.path()), None);+ // /Applications on the test machine could hold a real Chrome first+ assert!(found.is_some());+ assert_eq!(find_chrome(None, "linux", Some(home.path()), None), None);+ }++ #[test]+ fn availability_reasons() {+ assert!(has_display("macos", None, None));+ assert!(!has_display("linux", None, None));+ assert!(!has_display("linux", Some(""), None));+ assert!(has_display("linux", Some(":0"), None));+ assert!(has_display("linux", None, Some("wayland-0")));++ let chrome = Path::new("/usr/bin/chromium");+ assert_eq!(local_unavailable_reason(Some(chrome), true), None);+ assert!(local_unavailable_reason(None, true)+ .unwrap()+ .contains(CHROME_PATH_ENV));+ assert!(local_unavailable_reason(Some(chrome), false)+ .unwrap()+ .contains("display"));++ assert_eq!(vm_unavailable_reason(true, false), None);+ assert_eq!(vm_unavailable_reason(false, true), None);+ assert!(vm_unavailable_reason(false, false)+ .unwrap()+ .contains("Docker"));+ }++ #[test]+ fn chrome_uses_its_own_profile_and_a_loopback_port() {+ let args = chrome_args(Path::new("/data/local-chrome"));+ assert!(args.contains(&"--user-data-dir=/data/local-chrome".to_string()));+ assert!(args.contains(&"--remote-debugging-port=0".to_string()));+ assert!(args.contains(&"--remote-debugging-address=127.0.0.1".to_string()));+ }++ #[test]+ fn devtools_port_file() {+ let dir = tempfile::tempdir().unwrap();+ assert_eq!(read_devtools_port(dir.path()), None);+ std::fs::write(+ dir.path().join("DevToolsActivePort"),+ "41234\n/devtools/browser/x\n",+ )+ .unwrap();+ assert_eq!(read_devtools_port(dir.path()), Some(41234));+ std::fs::write(dir.path().join("DevToolsActivePort"), "0\n").unwrap();+ assert_eq!(read_devtools_port(dir.path()), None);+ }+}diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex 38563646..32c9aaef 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -1,4 +1,5 @@pub mod browser;+pub mod computer;pub mod manager;pub mod service;diff --git a/src/sandbox/service.rs b/src/sandbox/service.rsindex e1ae3f0a..154ebdd1 100644--- a/src/sandbox/service.rs+++ b/src/sandbox/service.rs@@ -1,6 +1,7 @@//! One browser service per installation; isolated CDP contexts per bot/team.//! The private CDP endpoint is used only by the server, never by the web client.use super::browser::{BrowserController, BrowserError};+use super::computer::{self, ComputerMode};use serde::{Deserialize, Serialize};use serde_json::json;use std::{collections::HashMap, path::{Path, PathBuf}, time::Duration};@@ -15,6 +16,8 @@ struct SessionTarget {pub struct BrowserService {root: PathBuf,endpoint: Option<String>,+ /// Local Chrome or the vm browser; changing it drops the connection (see [`Self::set_mode`]).+ mode: std::sync::RwLock<ComputerMode>,// Serialize startup and session creation, including simultaneous status/frame requests.state: Mutex<Option<ServiceState>>,}@@ -27,7 +30,35 @@ struct ServiceState {impl BrowserService {pub fn new(root: PathBuf, endpoint: Option<String>) -> Self {- Self { root, endpoint, state: Mutex::new(None) }+ let mode = computer::current_mode(None);+ Self { root, endpoint, mode: std::sync::RwLock::new(mode), state: Mutex::new(None) }+ }++ pub fn mode(&self) -> ComputerMode {+ *self.mode.read().unwrap_or_else(|e| e.into_inner())+ }++ /// Whether a browser service URL (`KWNT_BROWSER_CDP_URL`) is configured for vm mode.+ pub fn has_endpoint(&self) -> bool { self.endpoint.is_some() }++ /// Switches where the browser runs. The current connection is dropped, not the browser:+ /// the local Chrome window and the vm container both keep running. Returns whether the+ /// mode changed.+ pub async fn set_mode(&self, mode: ComputerMode) -> bool {+ let mut lock = self.state.lock().await;+ let mut current = self.mode.write().unwrap_or_else(|e| e.into_inner());+ if *current == mode { return false; }+ *current = mode;+ *lock = None;+ true+ }++ /// Each mode keeps its own saved pages, since they live in different browsers.+ fn sessions_file(&self) -> PathBuf {+ self.root.join(match self.mode() {+ ComputerMode::Vm => "browser-sessions.json",+ ComputerMode::Local => "browser-sessions-local.json",+ })}async fn docker(args: &[&str], seconds: u64) -> Result<String, BrowserError> {@@ -73,12 +104,15 @@ impl BrowserService {}async fn connect(&self) -> Result<ServiceState, BrowserError> {+ let local = self.mode() == ComputerMode::Local;let endpoint = match &self.endpoint {+ _ if local => computer::ensure_local_chrome(&self.root.join("local-chrome")).await+ .map_err(BrowserError::Http)?,Some(endpoint) => endpoint.trim_end_matches('/').to_string(),None => self.managed_endpoint().await?,};let browser = BrowserController::at_endpoint(&endpoint, None, None, true);- if self.endpoint.is_some() {+ if self.endpoint.is_some() || local {browser.send_cdp_command("Browser.getVersion", json!({})).await?;} else { timeout(Duration::from_secs(30), async {loop {@@ -86,7 +120,7 @@ impl BrowserService {sleep(Duration::from_millis(250)).await;}}).await.map_err(|_| BrowserError::Timeout)?; }- let sessions = tokio::fs::read(self.root.join("browser-sessions.json")).await.ok()+ let sessions = tokio::fs::read(self.sessions_file()).await.ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default();Ok(ServiceState { browser, endpoint, sessions })}@@ -94,14 +128,28 @@ impl BrowserService {pub async fn session(&self, id: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {let mut lock = self.state.lock().await;if lock.is_none() { *lock = Some(self.connect().await?); }+ let mut targets = lock.as_ref().unwrap().browser.send_cdp_command("Target.getTargets", json!({})).await;+ if targets.is_err() && self.mode() == ComputerMode::Local {+ // the person closed the Chrome window: open it again in this same call+ *lock = None;+ *lock = Some(self.connect().await?);+ targets = lock.as_ref().unwrap().browser.send_cdp_command("Target.getTargets", json!({})).await;+ }let state = lock.as_mut().unwrap();- let targets = match state.browser.send_cdp_command("Target.getTargets", json!({})).await {+ let targets = match targets {Ok(targets) => targets,Err(error) => { *lock = None; return Err(error); }};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 session = if let Some(existing) = existing { existing.clone() } else {+ let local = self.mode() == ComputerMode::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; each bot still gets its own tab. (`context` stays empty.)+ let target = state.browser.send_cdp_command("Target.createTarget", json!({"url": "about:blank"})).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()@@ -121,26 +169,34 @@ impl BrowserService {};state.sessions.insert(id.to_string(), session.clone());tokio::fs::create_dir_all(&self.root).await.map_err(|e| BrowserError::Http(e.to_string()))?;- let file = self.root.join("browser-sessions.json");+ let file = self.sessions_file();tokio::fs::write(file.with_extension("tmp"), serde_json::to_vec(&state.sessions).unwrap()).await.map_err(|e| BrowserError::Http(e.to_string()))?;tokio::fs::rename(file.with_extension("tmp"), file).await.map_err(|e| BrowserError::Http(e.to_string()))?;let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target), Some(workspace.to_path_buf()), false);- ctrl.send_cdp_command("Emulation.setDeviceMetricsOverride", json!({- "width": 1280, "height": 800, "deviceScaleFactor": 1, "mobile": false- })).await?;+ // A real window keeps its own size; only the headless vm browser gets a fixed viewport.+ if !local {+ ctrl.send_cdp_command("Emulation.setDeviceMetricsOverride", json!({+ "width": 1280, "height": 800, "deviceScaleFactor": 1, "mobile": false+ })).await?;+ }ctrl.refresh_location().await?;Ok(ctrl)}pub async fn reset(&self, id: &str) -> Result<(), BrowserError> {let mut lock = self.state.lock().await;- if lock.is_none() && self.root.join("browser-sessions.json").exists() {+ if lock.is_none() && self.sessions_file().exists() {*lock = Some(self.connect().await?);}if let Some(state) = lock.as_mut() {if let Some(session) = state.sessions.remove(id) {- state.browser.send_cdp_command("Target.disposeBrowserContext", json!({"browserContextId": session.context})).await?;+ if session.context.is_empty() {+ // a local tab in the shared profile: close just that tab+ let _ = state.browser.send_cdp_command("Target.closeTarget", json!({"targetId": session.target})).await;+ } else {+ state.browser.send_cdp_command("Target.disposeBrowserContext", json!({"browserContextId": session.context})).await?;+ }}}Ok(())diff --git a/src/server/computer.rs b/src/server/computer.rsnew file mode 100644index 00000000..b83f93e9--- /dev/null+++ b/src/server/computer.rs@@ -0,0 +1,154 @@+//! Settings → Computer: whether bots use this computer (its Chrome and shell) or the isolated+//! vm containers, and the approval every local shell command needs.+use super::AppState;+use crate::broker::{ApprovalDecision, ApprovalRequest};+use crate::db::models::NewApproval;+use crate::drivers::events::RuntimeEvent;+use crate::sandbox::computer::{self, ComputerMode};+use axum::{extract::State, http::StatusCode, Json};+use serde::Deserialize;+use serde_json::{json, Value};+use std::path::Path;++/// The mode in force: the saved choice, else `KWNT_COMPUTER_MODE`, else the platform default.+pub async fn current_mode(state: &AppState) -> ComputerMode {+ let saved = state+ .db+ .get_setting(computer::SETTING_KEY)+ .await+ .ok()+ .flatten();+ computer::current_mode(saved.as_deref())+}++/// Points the browser service at the mode in force. On a change the old browser is+/// disconnected (never closed) and the next browser call opens a page in the new one.+pub async fn apply_mode(state: &AppState) -> ComputerMode {+ let mode = current_mode(state).await;+ 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) {+ let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {+ team_id,+ container_name: "browser-service".into(),+ is_running: false,+ });+ }+ }+ }+ mode+}++async fn view(state: &AppState) -> Value {+ let mode = current_mode(state).await;+ let local = computer::local_reason();+ let vm = computer::vm_unavailable_reason(+ state.sandbox_manager.is_docker_available().await,+ state.browser_service.has_endpoint(),+ );+ json!({+ "mode": mode,+ "available": {"local": local.is_none(), "vm": vm.is_none()},+ "reasons": {"local": local, "vm": vm},+ })+}++/// `GET /api/settings/computer`+pub async fn get_computer(State(state): State<AppState>) -> Json<Value> {+ Json(view(&state).await)+}++#[derive(Deserialize)]+pub struct ComputerPayload {+ pub mode: ComputerMode,+}++/// `PUT /api/settings/computer` with `{"mode":"local"|"vm"}`: saves the choice and switches at+/// once. 400 for an unknown mode or one this computer cannot run (with the reason).+pub async fn put_computer(+ State(state): State<AppState>,+ payload: Result<Json<ComputerPayload>, axum::extract::rejection::JsonRejection>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ let bad = |m: String| (StatusCode::BAD_REQUEST, Json(json!({ "error": m })));+ let Json(ComputerPayload { mode }) =+ payload.map_err(|_| bad("mode must be \"local\" or \"vm\"".into()))?;+ let current = view(&state).await;+ if current["available"][mode.as_str()] != json!(true) {+ let reason = current["reasons"][mode.as_str()]+ .as_str()+ .unwrap_or("unavailable");+ return Err(bad(reason.to_string()));+ }+ state+ .db+ .set_setting(computer::SETTING_KEY, mode.as_str())+ .await+ .map_err(|e| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({ "error": e.to_string() })),+ )+ })?;+ apply_mode(&state).await;+ Ok(Json(view(&state).await))+}++/// Asks the person before a shell command runs on their own computer. Every command asks:+/// "always allow" is honoured for this one command only, never remembered.+pub async fn approve_local_shell(+ state: &AppState,+ target_id: &str,+ command: &str,+ cwd: &Path,+) -> bool {+ let details = json!({+ "source": "local_shell",+ "tool": "execute_shell",+ "arguments": {"command": command, "cwd": cwd.to_string_lossy()},+ "kwant_id": target_id,+ });+ let ticket = match state+ .db+ .save_approval(&NewApproval {+ turn_id: String::new(),+ kwant_id: target_id.to_string(),+ tool_name: "execute_shell".into(),+ parameters: details.clone(),+ })+ .await+ {+ Ok(a) => a.id,+ Err(e) => {+ tracing::warn!(error = %e, "could not store local shell approval; denying");+ return false;+ }+ };+ let rx = state+ .broker+ .request_approval(ApprovalRequest {+ id: ticket.clone(),+ kwant_id: target_id.to_string(),+ tool_name: "execute_shell".into(),+ details: details.clone(),+ })+ .await;+ let _ = state.event_sender.send(RuntimeEvent::ApprovalRequired {+ id: ticket.clone(),+ tool_name: "execute_shell".into(),+ details,+ });+ match tokio::time::timeout(super::mcp_runtime::APPROVAL_TIMEOUT, rx).await {+ Ok(Ok(ApprovalDecision::AllowOnce | ApprovalDecision::AlwaysAllowSession)) => true,+ Ok(_) => false,+ Err(_) => {+ if state.broker.cancel(&ticket).await {+ let _ = state.db.update_approval_status(&ticket, "expired").await;+ let _ = state+ .event_sender+ .send(RuntimeEvent::ApprovalWithdrawn { id: ticket });+ }+ false+ }+ }+}diff --git a/src/server/mod.rs b/src/server/mod.rsindex f7384585..de12b8bd 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -16,6 +16,7 @@ pub mod attachments;pub mod questions;pub mod skills;pub mod away;+pub mod computer;use crate::broker::PermissionBroker;use crate::config::Config;@@ -134,6 +135,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/chat/cancel", post(routes::cancel_chat)).route("/api/approvals/:id/resolve", post(routes::resolve_approval)).route("/api/settings", get(routes::get_settings).post(routes::save_settings))+ .route("/api/settings/computer", get(computer::get_computer).put(computer::put_computer)).route("/api/system/directories", get(routes::list_system_directories)).route("/api/system/select-folder", post(routes::select_folder)).route("/api/sandbox/:team_id/status", get(routes::get_sandbox_status))diff --git a/src/server/routes.rs b/src/server/routes.rsindex 14eecf2a..fd0f550c 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -2310,6 +2310,8 @@ pub async fn get_or_create_browser_controller(state: &AppState,team_id: &str,) -> Option<crate::sandbox::BrowserController> {+ // follow a mode switch made elsewhere (another kwnt process sharing the data dir)+ super::computer::apply_mode(state).await;let mut controllers = state.browser_controllers.lock().await;if let Some(ctrl) = controllers.get(team_id) {if !ctrl.is_managed_session() || ctrl.refresh_location().await.is_ok() { return Some(ctrl.clone()); }@@ -2644,6 +2646,25 @@ pub async fn execute_tool(if let Some(tid) = team_id { get_or_create_browser_controller(state, tid).await } else { None }} else { None };+ if tool_name == "execute_shell"+ && super::computer::apply_mode(state).await == crate::sandbox::computer::ComputerMode::Local+ {+ // Local mode: the command runs on this computer, so the person approves each one first.+ let workspace = match team_id {+ Some(tid) => resolve_sandbox_target_info(state, tid).await.map(|(_, ws)| ws),+ None => None,+ }+ .unwrap_or_else(|| state.tools.workspace_dir.clone());+ tokio::fs::create_dir_all(&workspace).await?;+ let command = args["command"].as_str()+ .ok_or_else(|| crate::tools::ToolError::InvalidArgs("Missing 'command' argument".into()))?;+ if !super::computer::approve_local_shell(state, team_id.unwrap_or("default"), command, &workspace).await {+ return Err(crate::tools::ToolError::Execution(+ "The person did not approve this command, so it was not run.".into(),+ ));+ }+ return crate::tools::shell::execute_shell(&workspace, args).await;+ }if tool_name == "execute_shell" {if let Some(tid) = team_id {if let Some((name, workspace)) = resolve_sandbox_target_info(state, tid).await {diff --git a/tests/computer_mode_test.rs b/tests/computer_mode_test.rsnew file mode 100644index 00000000..b57ad697--- /dev/null+++ b/tests/computer_mode_test.rs@@ -0,0 +1,190 @@+//! Settings → Computer API and local-mode shell approval. One test function, because it changes+//! process environment (Chrome path, display, KWNT_COMPUTER_MODE) step by step.+use axum::{+ body::Body,+ http::{Request, StatusCode},+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::Database,+ drivers::events::RuntimeEvent,+ router::LayaRouter,+ sandbox::computer::ComputerMode,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use tempfile::tempdir;+use tower::ServiceExt;++async fn call(app: &axum::Router, method: &str, body: Option<Value>) -> (StatusCode, Value) {+ let req = Request::builder()+ .method(method)+ .uri("/api/settings/computer")+ .header("content-type", "application/json")+ .body(body.map_or_else(Body::empty, |b| Body::from(b.to_string())))+ .unwrap();+ let resp = app.clone().oneshot(req).await.unwrap();+ let status = resp.status();+ let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20)+ .await+ .unwrap();+ (+ status,+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),+ )+}++async fn next_approval(rx: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>) -> (String, Value) {+ loop {+ let event = tokio::time::timeout(std::time::Duration::from_secs(10), rx.recv())+ .await+ .expect("approval card")+ .unwrap();+ if let RuntimeEvent::ApprovalRequired {+ id,+ tool_name,+ details,+ } = event+ {+ assert_eq!(tool_name, "execute_shell");+ return (id, details);+ }+ }+}++async fn resolve(app: &axum::Router, id: &str, decision: &str) {+ let req = Request::builder()+ .method("POST")+ .uri(format!("/api/approvals/{id}/resolve"))+ .header("content-type", "application/json")+ .body(Body::from(json!({ "decision": decision }).to_string()))+ .unwrap();+ assert_eq!(+ app.clone().oneshot(req).await.unwrap().status(),+ StatusCode::OK+ );+}++#[tokio::test]+async fn computer_mode_api_and_local_shell_approval() {+ let tmp = tempdir().unwrap();+ let fake_chrome = tmp.path().join("fake-chrome");+ std::fs::write(&fake_chrome, "").unwrap();+ std::env::remove_var("KWNT_COMPUTER_MODE");+ std::env::set_var("KWNT_CHROME_PATH", tmp.path().join("missing-chrome"));++ let db = Database::init(tmp.path()).await.unwrap();+ // a configured browser URL makes vm available without Docker on the test machine+ let config = Config {+ data_dir: tmp.path().to_path_buf(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let tools = ToolRunner::new(tmp.path().join("workspace"));+ let router = LayaRouter::new(config.laya_url.clone());+ let state = AppState::new(config, db.clone(), tools, PermissionBroker::new(), router);+ let app = create_router(state.clone());++ // GET: the contract shape; no Chrome → local unavailable with a reason+ let (status, view) = call(&app, "GET", None).await;+ assert_eq!(status, StatusCode::OK);+ let expected_default = if cfg!(target_os = "macos") {+ "local"+ } else {+ "vm"+ };+ assert_eq!(view["mode"], expected_default);+ assert_eq!(view["available"], json!({"local": false, "vm": true}));+ assert!(view["reasons"]["local"]+ .as_str()+ .unwrap()+ .contains("KWNT_CHROME_PATH"));+ assert_eq!(view["reasons"]["vm"], Value::Null);++ // PUT: bad bodies and unavailable modes are 400 and save nothing+ for body in [+ json!({"mode": "docker"}),+ json!({"mode": "VM"}),+ json!({}),+ json!("vm"),+ ] {+ let (status, err) = call(&app, "PUT", Some(body.clone())).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");+ assert!(err["error"].is_string(), "{body}");+ }+ let (status, err) = call(&app, "PUT", Some(json!({"mode": "local"}))).await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert!(err["error"].as_str().unwrap().contains("Chrome"));+ assert_eq!(db.get_setting("computer_mode").await.unwrap(), None);++ // env default applies while nothing is saved+ std::env::set_var("KWNT_COMPUTER_MODE", "local");+ assert_eq!(call(&app, "GET", None).await.1["mode"], "local");++ // a saved choice wins over the env default+ let (status, view) = call(&app, "PUT", Some(json!({"mode": "vm"}))).await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(view["mode"], "vm");+ assert_eq!(+ db.get_setting("computer_mode").await.unwrap().as_deref(),+ Some("vm")+ );+ assert_eq!(call(&app, "GET", None).await.1["mode"], "vm");+ assert_eq!(state.browser_service.mode(), ComputerMode::Vm);++ // with a Chrome and a display, local becomes available and switching works at runtime+ std::env::set_var("KWNT_CHROME_PATH", &fake_chrome);+ std::env::set_var("DISPLAY", ":99");+ let (status, view) = call(&app, "PUT", Some(json!({"mode": "local"}))).await;+ assert_eq!(status, StatusCode::OK, "{view}");+ assert_eq!(view["mode"], "local");+ assert_eq!(view["available"]["local"], true);+ assert_eq!(state.browser_service.mode(), ComputerMode::Local);++ // local shell: every command needs approval; a denied one does not run+ let mut rx = state.event_sender.subscribe();+ let marker = tmp.path().join("workspace").join("ran.txt");+ let run = |cmd: &'static str| {+ let state = state.clone();+ tokio::spawn(async move {+ kwnt::server::routes::execute_tool(+ &state,+ None,+ "execute_shell",+ &json!({ "command": cmd }),+ )+ .await+ })+ };+ let denied = run("touch ran.txt");+ let (id, details) = next_approval(&mut rx).await;+ assert_eq!(details["source"], "local_shell");+ assert_eq!(details["arguments"]["command"], "touch ran.txt");+ resolve(&app, &id, "deny").await;+ assert!(denied.await.unwrap().is_err());+ assert!(!marker.exists(), "a denied command must not run");++ // "always allow" runs this command only; the next one asks again+ let allowed = run("touch ran.txt && echo local-ok");+ let (id, _) = next_approval(&mut rx).await;+ resolve(&app, &id, "always_allow").await;+ let out = allowed.await.unwrap().unwrap();+ assert!(out["stdout"].as_str().unwrap().contains("local-ok"));+ assert!(marker.exists());+ let again = run("echo again");+ let (id, _) = next_approval(&mut rx).await;+ resolve(&app, &id, "allow_once").await;+ assert!(again.await.unwrap().is_ok());++ // switching back to vm takes effect without a restart+ let (status, view) = call(&app, "PUT", Some(json!({"mode": "vm"}))).await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(view["mode"], "vm");+ assert_eq!(state.browser_service.mode(), ComputerMode::Vm);++ std::env::remove_var("KWNT_COMPUTER_MODE");+ std::env::remove_var("KWNT_CHROME_PATH");+ std::env::remove_var("DISPLAY");+}