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.

Bot browser as kwnt_tools MCP tools: browser_open, browser_page, browser_act

Lin (kwant bot)593baf91c21b
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index 892d2ba2..a8945913 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -586,7 +586,14 @@ impl Driver for ApiDriver {
// If target is a real live API endpoint with API key or local Ollama, call HTTP streaming
if api_key.is_some() || is_ollama(target_model) || custom {
- let system_prompt = input.format_system_prompt();
+ // An API turn has no shell: the browser is reachable only through the tools, which the
+ // Anthropic Messages format doesn't get
+ let browser = if input.has_self_tools() && !url.ends_with("/v1/messages") {
+ super::BrowserAccess::Tools
+ } else {
+ super::BrowserAccess::Unavailable
+ };
+ let system_prompt = input.format_system_prompt_with(browser);
let mut messages = vec![json!({"role": "system", "content": system_prompt})];
for msg in &input.history {
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index bb51440f..faf63076 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -85,8 +85,32 @@ pub fn current_date_block(now: chrono::DateTime<chrono::FixedOffset>) -> String
)
}
+/// How a turn's agent reaches its bot browser, which decides what the prompt tells it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BrowserAccess {
+ /// kwnt's own `browser_*` MCP tools are attached.
+ Tools,
+ /// No MCP this turn: the agent's shell calls the browser API with curl.
+ Shell,
+ /// Neither (an API turn without tools): there is no way to the browser.
+ Unavailable,
+}
+
impl TurnInput {
+ /// Whether kwnt's own tools server (which carries the `browser_*` tools) is attached.
+ pub fn has_self_tools(&self) -> bool {
+ self.mcp
+ .as_ref()
+ .is_some_and(|c| c.servers.iter().any(|s| s.name == crate::mcp::SELF_SERVER_NAME))
+ }
+
+ /// The prompt for a CLI turn: browser tools when attached, else curl through the shell.
pub fn format_system_prompt(&self) -> String {
+ let access = if self.has_self_tools() { BrowserAccess::Tools } else { BrowserAccess::Shell };
+ self.format_system_prompt_with(access)
+ }
+
+ pub fn format_system_prompt_with(&self, browser: BrowserAccess) -> String {
let mut base = format!(
"{}\n\nYou are {}, {}.",
self.kwant.persona_prompt, self.kwant.name, self.kwant.title
@@ -127,25 +151,47 @@ impl TurnInput {
let api = self.browser_api_url.clone().unwrap_or_else(|| {
format!("http://127.0.0.1:{}/api/sandbox/{}", crate::config::DEFAULT_PORT, sandbox_target)
});
+ let control_rules = "A 409 / \"taken control\" answer means the user is using the browser: stop browser actions and wait for the user to hand it back. Never bypass the control API or connect to CDP directly.\n\
+ Report browser errors honestly. Never claim a page opened unless navigation succeeded, and only describe content that appears in the returned page text. If a response has \"blocked\": true (CAPTCHA / bot check), follow its \"notice\" instead of claiming results.";
+ let browser_block = match browser {
+ BrowserAccess::Tools => format!(
+ "\n\n[Bot Browser]\n\
+ Your browser session is displayed live in the user's right panel; the user can browse in it too.\n\
+ Never open a host desktop browser (no `open <url>`, `xdg-open`, etc.) and don't use the shell or curl for it. Use ONLY your `{tools}` tools:\n\
+ - `browser_open` (url): open a page.\n\
+ - `browser_page`: read the page (url, title, text, clickable labels).\n\
+ - `browser_act` (action click_text + text, type + text, key + key, scroll + delta_y): click a button/link/field by its visible label, type into the focused field, press a key, scroll.\n\
+ Every call returns the updated page, so you rarely need a separate read. \
+ The current page state and its clickable labels are usually already in the request; act on them directly.\n\
+ {control_rules}",
+ tools = crate::mcp::SELF_SERVER_NAME,
+ ),
+ BrowserAccess::Shell => format!(
+ "\n\n[Bot Browser]\n\
+ Your browser session is displayed live in the user's right panel; the user can browse in it too. Shell execution uses a separate container.\n\
+ Browser API: {api}\n\
+ Never open a host desktop browser (no `open <url>`, `xdg-open`, etc.). Use ONLY these commands (the full API, do not search for more):\n\
+ - Open a page: curl -sS -X POST '{api}/navigate' -H 'Content-Type: application/json' -d '{{\"url\":\"<url>\"}}'\n\
+ - Read the page (url, title, text, clickable labels): curl -sS '{api}/page'\n\
+ - Click a button/link/field by its visible label: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"click_text\",\"text\":\"<label>\"}}'\n\
+ - Type into the focused field: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"type\",\"text\":\"<text>\"}}'\n\
+ - Press a key: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"key\",\"key\":\"Enter\"}}'\n\
+ - Scroll: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"scroll\",\"delta_y\":600}}'\n\
+ Every /act call returns the updated page (url, title, text, clickable), so you rarely need a separate read. \
+ The current page state and its clickable labels are usually already in the request; act on them directly.\n\
+ {control_rules}",
+ api = api,
+ ),
+ BrowserAccess::Unavailable => "\n\n[Bot Browser]\n\
+ You have no way to use the browser in the user's side panel this turn. If the user asks you to browse, say so plainly and \
+ suggest they open the page themselves (Take Control in the panel); never claim you opened or read a page."
+ .to_string(),
+ };
let sandbox_rules = format!(
- "\n\n[Bot Browser]\n\
- Your browser session is displayed live in the user's right panel; the user can browse in it too. Shell execution uses a separate container.\n\
- Browser API: {api}\n\
- Never open a host desktop browser (no `open <url>`, `xdg-open`, etc.). Use ONLY these commands (the full API, do not search for more):\n\
- - Open a page: curl -sS -X POST '{api}/navigate' -H 'Content-Type: application/json' -d '{{\"url\":\"<url>\"}}'\n\
- - Read the page (url, title, text, clickable labels): curl -sS '{api}/page'\n\
- - Click a button/link/field by its visible label: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"click_text\",\"text\":\"<label>\"}}'\n\
- - Type into the focused field: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"type\",\"text\":\"<text>\"}}'\n\
- - Press a key: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"key\",\"key\":\"Enter\"}}'\n\
- - Scroll: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"scroll\",\"delta_y\":600}}'\n\
- Every /act call returns the updated page (url, title, text, clickable), so you rarely need a separate read. \
- The current page state and its clickable labels are usually already in the request; act on them directly.\n\
- A 409 means the user has taken control: stop browser actions and wait for the user to return control. Never bypass the control API or connect to CDP directly.\n\
- Report API errors honestly. Never claim a page opened unless navigation succeeded, and only describe content that appears in the returned page text. If a response has \"blocked\": true (CAPTCHA / bot check), follow its \"notice\" instead of claiming results.\n\n\
+ "{browser_block}\n\n\
[Speed]\n\
The user is waiting in a live chat. Respond as fast as possible: answer directly when you can, use the fewest tool calls (usually one), \
do not explore the filesystem, read source code or plan multi-step investigations to figure out how the browser works, and keep replies short.",
- api = api,
);
let teammates_block = if self.teammates.is_empty() {
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 4030f374..6e33592d 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -158,6 +158,9 @@ pub struct SelfScope {
pub turn_id: Option<String>,
/// The turn's workspace (team chats): `share_file` may share files from inside it.
pub workspace: Option<std::path::PathBuf>,
+ /// The bot browser shown in this turn's side panel (team, channel or kwant id). The
+ /// `browser_*` tools are offered only when it is set and only ever drive this one.
+ pub sandbox_target: Option<String>,
}
/// Where a turn runs, for the delegation tools: results go back to this chat.
@@ -210,6 +213,9 @@ fn tool_list(scope: &SelfScope) -> Value {
let mut tools = memory_tools();
if let Some(list) = tools.as_array_mut() {
list.extend(super::skills::tools());
+ if scope.sandbox_target.is_some() {
+ list.extend(browser_tools());
+ }
if scope.origin.is_some() {
list.extend(delegation_tools());
list.extend(super::attachments::tools());
@@ -221,6 +227,92 @@ fn tool_list(scope: &SelfScope) -> Value {
tools
}
+/// The bot browser as MCP tools, so engines whose shell can't reach kwnt (claude's permission
+/// prompt refuses Bash, codex's sandbox has no network) still drive it.
+fn browser_tools() -> Vec<Value> {
+ vec![
+ json!({
+ "name": BROWSER_OPEN,
+ "description": "Open a web page in your browser, the one shown live in the user's side panel. Returns the page you landed on (url, title, text, clickable labels); trust it over the url you asked for.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"url": {"type": "string", "description": "The address to open, e.g. https://www.google.com/maps"}},
+ "required": ["url"],
+ },
+ }),
+ json!({
+ "name": BROWSER_PAGE,
+ "description": "Read the page your browser shows now: url, title, visible text and clickable labels.",
+ "inputSchema": {"type": "object", "properties": {}},
+ }),
+ json!({
+ "name": BROWSER_ACT,
+ "description": "Do one thing on the current page and get the page back. click_text clicks a button, link or field by its visible label; type types into the focused field; key presses a key (Enter, Tab, Escape, ArrowDown…); scroll scrolls by delta_y pixels (negative is up).",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "action": {"type": "string", "enum": ["click_text", "type", "key", "scroll"]},
+ "text": {"type": "string", "description": "click_text: the label to click; type: the text to type"},
+ "key": {"type": "string", "description": "key: the key to press"},
+ "delta_y": {"type": "number", "description": "scroll: pixels to scroll, default 600"},
+ },
+ "required": ["action"],
+ },
+ }),
+ ]
+}
+
+pub const BROWSER_OPEN: &str = "browser_open";
+pub const BROWSER_PAGE: &str = "browser_page";
+pub const BROWSER_ACT: &str = "browser_act";
+
+/// Runs one `browser_*` tool on the turn's own sandbox through the same handlers as the HTTP
+/// browser API, so control (409), CAPTCHA notices and panel updates behave the same.
+async fn call_browser_tool(state: &AppState, target: &str, name: &str, args: &Value) -> (String, bool) {
+ use super::routes::{act_sandbox, get_sandbox_page, navigate_sandbox, InteractPayload, NavigatePayload};
+ let state = State(state.clone());
+ let target = Path(target.to_string());
+ let result = match name {
+ BROWSER_OPEN => {
+ let Some(url) = args["url"].as_str().map(str::trim).filter(|u| !u.is_empty()) else {
+ return ("url is required".into(), true);
+ };
+ navigate_sandbox(state, target, Json(NavigatePayload { url: url.to_string() })).await
+ }
+ BROWSER_PAGE => get_sandbox_page(state, target).await,
+ _ => {
+ let Some(action) = args["action"].as_str() else {
+ return ("action is required: click_text, type, key or scroll".into(), true);
+ };
+ let payload = InteractPayload {
+ action: action.to_string(),
+ x: None,
+ y: None,
+ text: args["text"].as_str().map(str::to_string),
+ key: args["key"].as_str().map(str::to_string),
+ code: None,
+ delta_x: None,
+ delta_y: args["delta_y"].as_f64(),
+ };
+ act_sandbox(state, target, Json(payload)).await
+ }
+ };
+ match result {
+ Ok(Json(page)) => {
+ let is_error = page.get("error").is_some();
+ (page.to_string(), is_error)
+ }
+ Err((StatusCode::CONFLICT, _)) => (
+ "The user has taken control of the browser. Stop browser actions and wait until they hand it back.".into(),
+ true,
+ ),
+ Err((status, Json(body))) => (
+ body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("Browser error (HTTP {}).", status.as_u16())),
+ true,
+ ),
+ }
+}
+
fn delegation_tools() -> Vec<Value> {
vec![
json!({
@@ -481,6 +573,10 @@ async fn call_tool(
Err(_) => ("database error".into(), true),
}
}
+ BROWSER_OPEN | BROWSER_PAGE | BROWSER_ACT => match &scope.sandbox_target {
+ Some(target) => call_browser_tool(state, target, name, args).await,
+ None => (format!("Unknown tool {name}."), true),
+ },
"skill_propose" => super::skills::tool_propose(state, scope, args).await,
"skill_get" => super::skills::tool_get(state, scope, args).await,
"ask_user" => super::questions::tool_ask(state, scope, args).await,
diff --git a/src/server/routes.rs b/src/server/routes.rs
index e5c2a786..2b7977bf 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1313,6 +1313,7 @@ async fn run_kwant_turn_inner(
cancel: Some(cancel_token.clone()),
turn_id: Some(tag.turn_id.clone()),
workspace: scope.workspace_dir.clone(),
+ sandbox_target: Some(sandbox_target.clone()),
}
});
let mcp_turn = super::mcp_runtime::prepare_turn_with_self(
diff --git a/tests/browser_tools_test.rs b/tests/browser_tools_test.rs
new file mode 100644
index 00000000..3a58bafd
--- /dev/null
+++ b/tests/browser_tools_test.rs
@@ -0,0 +1,222 @@
+//! The bot browser as kwnt's own MCP tools (`browser_open`, `browser_page`, `browser_act`).
+//! Claude's permission prompt refuses Bash, so the old curl instructions never reached the
+//! browser; these tools go through the self server, which needs no approval card, and drive
+//! only the turn's own sandbox. The browser part runs a real windowless Chrome in Local mode and
+//! is skipped when none is installed.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{spaces::SpaceId, Database},
+ drivers::{BrowserAccess, TurnInput},
+ mcp::{PERMISSION_TOOL, SELF_SERVER_NAME},
+ router::LayaRouter,
+ sandbox::computer,
+ server::{continuity::SelfScope, create_router, mcp_runtime, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::time::Duration;
+use tempfile::{tempdir, TempDir};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tower::ServiceExt;
+
+const PAGE: &str = "<!doctype html><title>Test page</title><body>\
+<p>Hello from the test page</p>\
+<button onclick=\"document.title='Clicked!';document.body.insertAdjacentHTML('beforeend','<p>button was pressed</p>')\">Press me</button>";
+
+async fn serve_page() -> 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; 2048];
+ let _ = stream.read(&mut buf).await;
+ let reply = format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-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 setup() -> (Router, AppState, TempDir) {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).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()),
+ );
+ (create_router(state.clone()), state, tmp)
+}
+
+async fn post(app: &Router, uri: &str, auth: Option<&str>, body: Value) -> (StatusCode, Value) {
+ let mut req = Request::builder().method("POST").uri(uri).header("content-type", "application/json");
+ if let Some(token) = auth {
+ req = req.header("authorization", format!("Bearer {token}"));
+ }
+ let resp = app.clone().oneshot(req.body(Body::from(body.to_string())).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))
+}
+
+fn rpc(method: &str, params: Value) -> Value {
+ json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
+}
+
+/// Calls one self tool; returns its text and whether it is an error.
+async fn self_tool(app: &Router, token: &str, name: &str, args: Value) -> (String, bool) {
+ let (status, v) = post(app, "/api/mcp/self", Some(token), rpc("tools/call", json!({"name": name, "arguments": args}))).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ (
+ v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(),
+ v["result"]["isError"].as_bool().unwrap_or(false),
+ )
+}
+
+async fn tool_names(app: &Router, token: &str) -> Vec<String> {
+ let (_, v) = post(app, "/api/mcp/self", Some(token), rpc("tools/list", json!({}))).await;
+ v["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
+}
+
+/// What claude's `--permission-prompt-tool` asks kwnt before running a tool.
+async fn claude_asks(app: &Router, token: &str, tool_name: &str) -> String {
+ let (status, v) = post(
+ app,
+ &format!("/api/mcp/permission/{token}"),
+ None,
+ rpc("tools/call", json!({"name": PERMISSION_TOOL, "arguments": {"tool_name": tool_name, "input": {"url": "x"}, "tool_use_id": "u1"}})),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ let decision: Value = serde_json::from_str(v["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
+ decision["behavior"].as_str().unwrap().to_string()
+}
+
+#[tokio::test]
+async fn claude_turn_gets_browser_tools_that_drive_its_own_panel() {
+ std::env::remove_var("DISPLAY");
+ std::env::remove_var("WAYLAND_DISPLAY");
+ std::env::set_var("KWNT_COMPUTER_MODE", "local");
+ let (app, state, _tmp) = setup().await;
+ let kwants = state.db.list_kwants(&SpaceId::default_space()).await.unwrap();
+ let (bot, other) = (&kwants[0], &kwants[1]);
+ let scope = |sandbox: Option<&str>| SelfScope {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ sandbox_target: sandbox.map(str::to_string),
+ ..Default::default()
+ };
+
+ // A turn with its sandbox: the browser tools are listed next to the memory tools
+ let (ctx, token) = mcp_runtime::prepare_turn_with_self(&state, bot, None, None, Some(scope(Some(&bot.id))))
+ .await
+ .unwrap();
+ let names = tool_names(&app, &token).await;
+ for tool in ["browser_open", "browser_page", "browser_act", "memory_add"] {
+ assert!(names.iter().any(|n| n == tool), "{tool} missing from {names:?}");
+ }
+ // Without a sandbox (e.g. a turn that shows no panel) they aren't offered or callable
+ let (_, bare) = mcp_runtime::prepare_turn_with_self(&state, bot, None, None, Some(scope(None))).await.unwrap();
+ assert!(!tool_names(&app, &bare).await.iter().any(|n| n.starts_with("browser_")));
+ let (text, is_error) = self_tool(&app, &bare, "browser_open", json!({"url": "http://127.0.0.1:1/"})).await;
+ assert!(is_error && text.contains("Unknown tool"), "{text}");
+
+ // claude asks before every tool: Bash stays refused, the browser tools pass with no card
+ assert_eq!(claude_asks(&app, &token, "Bash").await, "deny");
+ assert_eq!(claude_asks(&app, &token, &format!("mcp__{SELF_SERVER_NAME}__browser_open")).await, "allow");
+ assert_eq!(claude_asks(&app, &token, &format!("mcp__{SELF_SERVER_NAME}__browser_act")).await, "allow");
+ assert!(state.broker.pending_ids().await.is_empty(), "no approval card for the bot's own browser");
+
+ // The prompt tells a tools turn to use them, not curl through a shell it doesn't have
+ let input = TurnInput {
+ thread_id: "t".into(),
+ kwant: bot.clone(),
+ prompt: "open the page".into(),
+ history: vec![],
+ model_override: None,
+ model: None,
+ effort_level: None,
+ team_context: None,
+ workspace_dir: None,
+ browser_api_url: Some("http://127.0.0.1:7878/api/sandbox/x".into()),
+ sandbox_id: Some(bot.id.clone()),
+ teammates: vec![],
+ continuity: String::new(),
+ mcp: Some(ctx.clone()),
+ };
+ let prompt = input.format_system_prompt();
+ assert!(prompt.contains("browser_open") && !prompt.contains("curl -sS"), "{prompt}");
+ let shell = TurnInput { mcp: None, ..input.clone() }.format_system_prompt();
+ assert!(shell.contains("curl -sS -X POST 'http://127.0.0.1:7878/api/sandbox/x/navigate'"));
+ let none = input.format_system_prompt_with(BrowserAccess::Unavailable);
+ assert!(!none.contains("curl -sS") && !none.contains("browser_open") && none.contains("no way to use the browser"));
+
+ if computer::local_chrome_path().is_none() {
+ eprintln!("browser part skipped: no Chrome or Chromium installed");
+ mcp_runtime::finish_turn(&state, &token).await;
+ return;
+ }
+ let url = serve_page().await;
+ let (text, is_error) = self_tool(&app, &token, "browser_open", json!({"url": url})).await;
+ assert!(!is_error, "{text}");
+ let page: Value = serde_json::from_str(&text).unwrap();
+ assert_eq!(page["status"], "navigated", "{page}");
+ assert_eq!(page["title"], "Test page");
+ assert!(page["text"].as_str().unwrap().contains("Hello from the test page"));
+ assert!(page["clickable"].to_string().contains("Press me"), "{page}");
+
+ let (text, is_error) = self_tool(&app, &token, "browser_act", json!({"action": "click_text", "text": "Press me"})).await;
+ assert!(!is_error, "{text}");
+ let page: Value = serde_json::from_str(&text).unwrap();
+ assert!(page["result"].as_str().unwrap().contains("Press me"), "{page}");
+ assert!(page["text"].as_str().unwrap().contains("button was pressed"), "{page}");
+
+ // It drove the bot's own panel: the same controller the side panel's screenshots come from
+ let ctrl = state.browser_controllers.lock().await.get(&bot.id).cloned().expect("bot's browser");
+ let mut title = String::new();
+ for _ in 0..30 {
+ title = ctrl.sync_location().await.map(|(_, t)| t).unwrap_or_default();
+ if title == "Clicked!" {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ assert_eq!(title, "Clicked!");
+ assert!(!ctrl.capture_screenshot().await.unwrap().is_empty());
+ assert!(!state.browser_controllers.lock().await.contains_key(&other.id), "no other bot's browser touched");
+
+ let (text, is_error) = self_tool(&app, &token, "browser_page", json!({})).await;
+ assert!(!is_error && text.contains("button was pressed"), "{text}");
+ let (text, is_error) = self_tool(&app, &token, "browser_act", json!({"action": "dance"})).await;
+ assert!(is_error && text.contains("Unknown action"), "{text}");
+
+ // Take Control: the bot is told to stop, and nothing is clicked
+ {
+ let _held = ctrl.control.clone().try_write_owned().unwrap();
+ let (text, is_error) = self_tool(&app, &token, "browser_act", json!({"action": "click_text", "text": "Press me"})).await;
+ assert!(is_error && text.contains("taken control"), "{text}");
+ }
+
+ // The turn's token ends with the turn
+ mcp_runtime::finish_turn(&state, &token).await;
+ let (status, _) = post(&app, "/api/mcp/self", Some(&token), rpc("tools/list", json!({}))).await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ drop(ctrl);
+ state.browser_service.set_mode(computer::ComputerMode::Vm).await;
+ let _ = computer::wait_local_chrome_gone(&state.config.data_dir.join("local-chrome")).await;
+}
diff --git a/tests/spaces_isolation_test.rs b/tests/spaces_isolation_test.rs
index 97d94210..64be7c21 100644
--- a/tests/spaces_isolation_test.rs
+++ b/tests/spaces_isolation_test.rs
@@ -325,6 +325,7 @@ async fn delegation_without_a_member_list_stays_in_the_leads_space() {
cancel: None,
turn_id: None,
workspace: None,
+ sandbox_target: None,
};
let (text, is_error) = delegation::tool_delegate(&env.state, &scope, &json!({"to": "Remy", "task": "help"})).await;
assert!(is_error, "{text}");
@@ -499,6 +500,7 @@ async fn the_search_tool_only_finds_messages_in_the_agents_space() {
cancel: None,
turn_id: None,
workspace: None,
+ sandbox_target: None,
},
);
let resp = env