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.

Speed up bot replies and make Laya's routing visible

Oleksandr Ivanchenko7adc4650516b
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 4ca6b823..02b274c7 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -31,6 +31,7 @@ export const App: React.FC = () => {
const messagesCacheRef = useRef<Record<string, ChatMessage[]>>({});
const [discussionState, setDiscussionState] = useState<DiscussionState>({ inProgress: false });
const [routingState, setRoutingState] = useState<RoutingState | null>(null);
+ const routingStartedAtRef = useRef<number>(0);
const discussionInProgressRef = useRef(false);
const kwantsRef = useRef<Kwant[]>(kwants);
kwantsRef.current = kwants;
@@ -153,6 +154,7 @@ export const App: React.FC = () => {
const ctx = event.data?.context_id;
const targetId = streamingContextIdRef.current;
if (ctx && targetId && ctx !== targetId) break;
+ routingStartedAtRef.current = Date.now();
setRoutingState({
phase: 'deciding',
contextId: ctx || targetId || undefined,
@@ -168,7 +170,10 @@ export const App: React.FC = () => {
const targetId = streamingContextIdRef.current;
if (ctx && targetId && ctx !== targetId) break;
const name: string = event.data?.kwant_name;
- setRoutingState((prev) => ({
+ const startedAt = routingStartedAtRef.current;
+ const applyDecision = () => {
+ if (routingStartedAtRef.current !== startedAt) return;
+ setRoutingState((prev) => (startedAt && !prev) ? prev : ({
phase: 'decided',
contextId: ctx || targetId || undefined,
candidates: prev?.candidates || [],
@@ -183,6 +188,11 @@ export const App: React.FC = () => {
streamingSpeakerNameRef.current = name;
}
playSfx('blip');
+ };
+ // Keep Laya's "deciding" visible briefly so instant heuristic routing doesn't just flash.
+ const remaining = 700 - (Date.now() - startedAt);
+ if (startedAt && remaining > 0) setTimeout(applyDecision, remaining);
+ else applyDecision();
break;
}
case 'ApprovalRequired':
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 6635f902..89c004ef 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -7,7 +7,25 @@ use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::sync::mpsc;
+static CLI_BINARY_CACHE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, Option<String>>>> =
+ std::sync::OnceLock::new();
+
+/// Cached lookup: resolving binaries spawns `which`, and this runs on every chat turn.
pub fn find_cli_binary(name: &str) -> Option<String> {
+ let cache = CLI_BINARY_CACHE.get_or_init(Default::default);
+ if let Some(hit) = cache.lock().ok().and_then(|c| c.get(name).cloned()) {
+ if hit.as_deref().map_or(true, |p| Path::new(p).exists()) {
+ return hit;
+ }
+ }
+ let found = find_cli_binary_uncached(name);
+ if let Ok(mut c) = cache.lock() {
+ c.insert(name.to_string(), found.clone());
+ }
+ found
+}
+
+fn find_cli_binary_uncached(name: &str) -> Option<String> {
// 1. Try standard which command
if let Ok(output) = std::process::Command::new("which").arg(name).output() {
if output.status.success() {
@@ -172,11 +190,27 @@ impl Driver for CliDriver {
codex_out_file = Some(out_file);
}
"grok" => {
+ let grok_effort = match effort {
+ "high" => "high",
+ "low" => "low",
+ _ => "medium",
+ };
+ // Without an explicit effort grok uses the user's default (often xhigh), which is far too slow for chat
+ cmd.arg("--reasoning-effort").arg(grok_effort);
+ cmd.arg("--no-plan").arg("--no-subagents");
cmd.arg("--rules").arg(&system_prompt);
cmd.arg("-p").arg(&effective_prompt);
}
_ => {
// claude default
+ let claude_effort = match effort {
+ "high" => "high",
+ "low" => "low",
+ _ => "medium",
+ };
+ cmd.arg("--effort").arg(claude_effort);
+ // Skip starting the user's personal MCP servers on every chat turn
+ cmd.arg("--strict-mcp-config");
cmd.arg("--append-system-prompt").arg(&system_prompt);
cmd.arg("-p").arg(&effective_prompt);
}
@@ -310,6 +344,7 @@ mod tests {
effort_level: None,
team_context: None,
workspace_dir: None,
+ sandbox_id: None,
};
let result = build_cli_prompt(&input);
@@ -344,6 +379,7 @@ mod tests {
effort_level: None,
team_context: None,
workspace_dir: None,
+ sandbox_id: None,
};
let result = build_cli_prompt(&input);
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index c2b3060e..44870641 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -43,6 +43,20 @@ pub struct TurnInput {
pub effort_level: Option<String>,
pub team_context: Option<TeamContext>,
pub workspace_dir: Option<std::path::PathBuf>,
+ /// Sandbox whose browser is shown to the user for this conversation (team, channel or kwant).
+ #[serde(default)]
+ pub sandbox_id: Option<String>,
+}
+
+static API_PORT: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
+
+/// Records the port the HTTP server listens on, so agents get working sandbox API URLs.
+pub fn set_api_port(port: u16) {
+ let _ = API_PORT.set(port);
+}
+
+fn api_port() -> u16 {
+ *API_PORT.get().unwrap_or(&8899)
}
impl TurnInput {
@@ -72,24 +86,32 @@ impl TurnInput {
};
let sandbox_target = self
- .team_context
- .as_ref()
- .map(|t| t.id.clone())
+ .sandbox_id
+ .clone()
+ .or_else(|| self.team_context.as_ref().map(|t| t.id.clone()))
.unwrap_or_else(|| self.kwant.id.clone());
+ let api = format!("http://127.0.0.1:{}/api/sandbox/{}", api_port(), sandbox_target);
let sandbox_rules = format!(
"\n\n[Virtual Machine Sandbox & Right-Panel In-Container Browser]\n\
- You have an isolated Sandbox Virtual Machine with a headless Chromium browser displayed live in the user's right-side UI panel.\n\
- Sandbox ID: {}\n\
- Control API Endpoint: http://127.0.0.1:8899/api/sandbox/{}\n\
+ You have an isolated Sandbox Virtual Machine with a headless Chromium browser displayed live in the user's right-side UI panel. The user can browse in it too.\n\
+ Sandbox ID: {sandbox}\n\
CRITICAL BROWSING INSTRUCTIONS:\n\
1. NEVER execute host desktop commands (e.g. `open <url>`, `start <url>`, `xdg-open`) or attempt to launch browser windows on the user's desktop!\n\
- 2. The user wants and expects all web browsing to appear inside the right-side Sandbox VM panel in Kwants.\n\
- 3. To navigate the in-container browser to any webpage or search engine, execute:\n\
- curl -s -X POST http://127.0.0.1:8899/api/sandbox/{}/navigate -H \"Content-Type: application/json\" -d '{{\"url\":\"<url>\"}}'\n\
- 4. This will instantly render the page in the user's right-side split pane and return the page title and status code.\n\
- 5. To view or extract text from the active page: curl -s http://127.0.0.1:8899/api/sandbox/{}/screenshot",
- sandbox_target, sandbox_target, sandbox_target, sandbox_target
+ 2. All web browsing must happen inside the right-side Sandbox browser, using ONLY these commands (the full API, do not search for more):\n\
+ - Open a page: curl -s -X POST {api}/navigate -H 'Content-Type: application/json' -d '{{\"url\":\"<url>\"}}'\n\
+ - Read the page (url, title, text, clickable labels): curl -s {api}/page\n\
+ - Click a button/link/field by its visible label: curl -s -X POST {api}/act -H 'Content-Type: application/json' -d '{{\"action\":\"click_text\",\"text\":\"<label>\"}}'\n\
+ - Type into the focused field: curl -s -X POST {api}/act -H 'Content-Type: application/json' -d '{{\"action\":\"type\",\"text\":\"<text>\"}}'\n\
+ - Press a key: curl -s -X POST {api}/act -H 'Content-Type: application/json' -d '{{\"action\":\"key\",\"key\":\"Enter\"}}'\n\
+ - Scroll: curl -s -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.\n\
+ 3. The current page state and its clickable labels are usually already in the request. Act on them directly.\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.",
+ sandbox = sandbox_target,
+ api = api,
);
format!("{}{}{}", base, team_block, sandbox_rules)
@@ -116,7 +138,12 @@ pub async fn detect_available_models(db: &crate::db::Database) -> Vec<ModelDescr
available.push(ModelDescriptor {
id: "claude".into(),
display_name: "Claude 3.5 Sonnet".into(),
- capability_desc: "deep architecture, multi-file refactoring, long complex analysis".into(),
+ capability_desc: if claude_key.is_none() {
+ "fastest local replies (~3s): everyday questions, quick answers, plus deep architecture and complex analysis"
+ } else {
+ "deep architecture, multi-file refactoring, long complex analysis"
+ }
+ .into(),
is_cli: claude_key.is_none() && claude_cli.is_some(),
});
}
@@ -129,7 +156,12 @@ pub async fn detect_available_models(db: &crate::db::Database) -> Vec<ModelDescr
available.push(ModelDescriptor {
id: "grok".into(),
display_name: "xAI Grok-2".into(),
- capability_desc: "fast technical reasoning, witty banter, quick coding solutions".into(),
+ capability_desc: if grok_key.is_none() {
+ "witty banter and technical reasoning; slow local CLI (10s+ per reply), avoid for quick questions"
+ } else {
+ "fast technical reasoning, witty banter, quick coding solutions"
+ }
+ .into(),
is_cli: grok_key.is_none() && grok_cli.is_some(),
});
}
diff --git a/src/main.rs b/src/main.rs
index 06f17951..123305a5 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -84,6 +84,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let tools = ToolRunner::new(config.data_dir.join("workspace"));
let broker = PermissionBroker::new();
let router = LayaRouter::new(config.laya_url.clone());
+ kwnt::drivers::set_api_port(config.port);
let state = AppState::new(config.clone(), db, tools, broker, router);
let app = create_router(state);
diff --git a/src/router/fallback.rs b/src/router/fallback.rs
index f55494ae..c8e5dfcf 100644
--- a/src/router/fallback.rs
+++ b/src/router/fallback.rs
@@ -111,11 +111,11 @@ pub fn heuristic_fallback_with_models(
}
}
- // 4. Default fast & general
- let selected = if is_available("grok") {
- "grok"
- } else if is_available("claude") {
+ // 4. Default fast & general — ordered by measured CLI latency (claude ~3s, codex ~7s, grok 10s+)
+ let selected = if is_available("claude") {
"claude"
+ } else if is_available("grok") {
+ "grok"
} else if is_available("codex") {
"codex"
} else if !available_models.is_empty() {
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 52f247bc..649d30b7 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -14,6 +14,77 @@ use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
+/// `function(needle)` evaluated in the page. Collects visible interactive elements (incl. open
+/// shadow roots and same-origin iframes), topmost first. With a needle, picks the best label match
+/// and either returns its viewport center (when nothing covers it) or clicks it directly.
+const CLICKABLES_JS: &str = r#"function (needle) {
+ var SEL = 'button,a[href],[role=button],[role=link],[role=menuitem],[role=tab],[role=checkbox],[role=option],input,textarea,select,summary,label,[onclick]';
+ var items = [];
+ function clean(s) { return (s || '').replace(/\s+/g, ' ').trim().slice(0, 80); }
+ function labelOf(el) {
+ var tag = el.tagName;
+ if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') {
+ var t = (el.type || '').toLowerCase();
+ if (t === 'submit' || t === 'button') return clean(el.value);
+ if (t === 'hidden') return '';
+ var name = clean(el.getAttribute('aria-label') || el.placeholder || el.name || el.id);
+ return name ? name + ' (' + (t === 'checkbox' || t === 'radio' ? t : 'field') + ')' : '';
+ }
+ return clean(el.innerText || el.getAttribute('aria-label') || el.title || el.value);
+ }
+ function walk(root, ox, oy) {
+ var all;
+ try { all = root.querySelectorAll('*'); } catch (e) { return; }
+ for (var i = 0; i < all.length; i++) {
+ var el = all[i];
+ if (el.shadowRoot) walk(el.shadowRoot, ox, oy);
+ if (el.tagName === 'IFRAME') {
+ try { var d = el.contentDocument; if (d) { var fr = el.getBoundingClientRect(); walk(d, ox + fr.left, oy + fr.top); } } catch (e) {}
+ continue;
+ }
+ if (!el.matches(SEL)) continue;
+ var r = el.getBoundingClientRect();
+ if (r.width < 2 || r.height < 2) continue;
+ var cs = getComputedStyle(el);
+ if (cs.visibility === 'hidden' || cs.display === 'none' || Number(cs.opacity) === 0) continue;
+ var label = labelOf(el);
+ if (!label) continue;
+ var lx = r.left + r.width / 2, ly = r.top + r.height / 2;
+ var x = ox + lx, y = oy + ly;
+ var inView = x >= 0 && y >= 0 && x <= innerWidth && y <= innerHeight;
+ var onTop = false;
+ if (inView) {
+ var hit = root.elementFromPoint ? root.elementFromPoint(lx, ly) : null;
+ onTop = !hit || hit === el || el.contains(hit) || hit.contains(el);
+ }
+ items.push({ label: label, x: Math.round(x), y: Math.round(y), inView: inView, onTop: onTop, el: el });
+ }
+ }
+ walk(document, 0, 0);
+ items.sort(function (a, b) { return (b.onTop - a.onTop) || (b.inView - a.inView); });
+ var match = null;
+ if (needle) {
+ var n = clean(needle).toLowerCase(), best = 0;
+ for (var j = 0; j < items.length; j++) {
+ var l = items[j].label.toLowerCase();
+ var s = l === n ? 3 : l.indexOf(n) === 0 ? 2 : l.indexOf(n) >= 0 ? 1 : 0;
+ if (s > best) { best = s; match = items[j]; }
+ }
+ if (match) {
+ var m = match.el;
+ if (!match.onTop) {
+ m.scrollIntoView({ block: 'center' });
+ if (typeof m.focus === 'function') m.focus();
+ m.click();
+ match = { label: match.label, clicked: true };
+ } else {
+ match = { label: match.label, x: match.x, y: match.y, clicked: false };
+ }
+ }
+ }
+ return { items: items.map(function (i) { return { label: i.label, onTop: i.onTop }; }), match: match };
+}"#;
+
#[derive(Error, Debug)]
pub enum BrowserError {
#[error("HTTP error connecting to CDP: {0}")]
@@ -581,6 +652,73 @@ impl BrowserController {
Some((url, title))
}
+ /// Labels of visible interactive elements, topmost (e.g. modal buttons) first.
+ pub async fn list_clickables(&self, limit: usize) -> Vec<String> {
+ let expression = format!("({})(null)", CLICKABLES_JS);
+ let Ok(res) = self
+ .send_cdp_command(
+ "Runtime.evaluate",
+ json!({ "expression": expression, "returnByValue": true }),
+ )
+ .await
+ else {
+ return Vec::new();
+ };
+ let mut labels: Vec<String> = Vec::new();
+ if let Some(items) = res["result"]["value"]["items"].as_array() {
+ for item in items {
+ if let Some(label) = item["label"].as_str() {
+ if !labels.iter().any(|l| l == label) {
+ labels.push(label.to_string());
+ }
+ }
+ if labels.len() >= limit {
+ break;
+ }
+ }
+ }
+ labels
+ }
+
+ /// Clicks the visible element whose label best matches `text` (exact > prefix > contains,
+ /// topmost first). Returns the clicked label, or an error listing the available ones.
+ pub async fn click_text(&self, text: &str) -> Result<String, BrowserError> {
+ let needle = serde_json::to_string(text).map_err(|e| BrowserError::Protocol(e.to_string()))?;
+ let expression = format!("({})({})", CLICKABLES_JS, needle);
+ let res = self
+ .send_cdp_command(
+ "Runtime.evaluate",
+ json!({ "expression": expression, "returnByValue": true }),
+ )
+ .await?;
+ let value = &res["result"]["value"];
+ let Some(label) = value["match"]["label"].as_str().map(str::to_string) else {
+ let options: Vec<&str> = value["items"]
+ .as_array()
+ .map(|a| a.iter().filter_map(|i| i["label"].as_str()).take(25).collect())
+ .unwrap_or_default();
+ return Err(BrowserError::Protocol(format!(
+ "No clickable element matching \"{}\". Visible options: {}",
+ text,
+ options.join(" | ")
+ )));
+ };
+ if value["match"]["clicked"].as_bool() == Some(true) {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ let _ = self.sync_location().await;
+ let _ = self.capture_screenshot().await;
+ } else {
+ let x = value["match"]["x"].as_i64().unwrap_or(0);
+ let y = value["match"]["y"].as_i64().unwrap_or(0);
+ self.interact_click(x, y).await?;
+ // Give navigations/animations triggered by the click a moment to settle
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ let _ = self.sync_location().await;
+ let _ = self.capture_screenshot().await;
+ }
+ Ok(label)
+ }
+
pub async fn interact_click(&self, x: i64, y: i64) -> Result<String, BrowserError> {
self.send_cdp_command(
"Input.dispatchMouseEvent",
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 262aed67..f0fa5e4a 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -86,6 +86,8 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/sandbox/:team_id/restart", post(routes::restart_sandbox))
.route("/api/sandbox/:team_id/navigate", post(routes::navigate_sandbox))
.route("/api/sandbox/:team_id/interact", post(routes::interact_sandbox))
+ .route("/api/sandbox/:team_id/page", get(routes::get_sandbox_page))
+ .route("/api/sandbox/:team_id/act", post(routes::act_sandbox))
.route("/api/sandbox/:team_id/passwords", get(routes::get_saved_passwords).post(routes::save_password))
.route("/api/sandbox/:team_id/passwords/:id", delete(routes::delete_password))
.route("/api/events", get(sse::sse_handler))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 4a642f61..37a19548 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -324,24 +324,26 @@ fn execute_single_turn(
timestamp: chrono::Utc::now().to_rfc3339(),
});
}
+ let clickable = ctrl.list_clickables(30).await;
final_prompt = format!(
- "{}\n\n[Sandbox Browser State: Successfully navigated the right-panel Sandbox VM browser to {}. Title: \"{}\".\nPage Content Preview:\n{}\n\nUse this page content to answer the user's request. NEVER attempt to open a desktop browser window.]",
- prompt, target_url, nav.title, preview
+ "{}\n\n[Sandbox Browser State: Successfully navigated the right-panel Sandbox VM browser to {}. Title: \"{}\".\nClickable (topmost first): {}\nPage Content Preview:\n{}\n\nUse this page content to answer the user's request. NEVER attempt to open a desktop browser window.]",
+ prompt, target_url, nav.title, clickable.join(" | "), preview
);
}
}
} else if let Some(ref curr_url) = active_browser_url {
if !curr_url.is_empty() && !curr_url.contains("about:blank") && !curr_url.contains("example.com") {
- let (title, page_text) = match active_ctrl {
+ let (title, page_text, clickable) = match active_ctrl {
Some(ref ctrl) => (
ctrl.current_title.lock().await.clone().unwrap_or_default(),
ctrl.extract_content().await.unwrap_or_default(),
+ ctrl.list_clickables(30).await,
),
- None => (String::new(), String::new()),
+ None => (String::new(), String::new(), Vec::new()),
};
final_prompt = format!(
- "{}\n\n[Active Sandbox Browser State: The right-panel Sandbox VM browser (shared live with the user, who may have clicked or typed in it) is currently viewing: {}. Title: \"{}\".\nPage Content Preview:\n{}\n\nMaintain context on this website. Do not suggest or switch to other services like YouTube unless explicitly requested.]",
- prompt, curr_url, title, truncate_chars(&page_text, 3000)
+ "{}\n\n[Active Sandbox Browser State: The right-panel Sandbox VM browser (shared live with the user, who may have clicked or typed in it) is currently viewing: {}. Title: \"{}\".\nClickable (topmost first, e.g. dialog buttons): {}\nPage Content Preview:\n{}\n\nMaintain context on this website. Do not suggest or switch to other services like YouTube unless explicitly requested.]",
+ prompt, curr_url, title, clickable.join(" | "), truncate_chars(&page_text, 3000)
);
}
}
@@ -356,6 +358,7 @@ fn execute_single_turn(
effort_level: Some(effort_level),
team_context,
workspace_dir,
+ sandbox_id: Some(sandbox_target.clone()),
};
let (driver_tx, mut driver_rx) = mpsc::channel(32);
@@ -825,6 +828,7 @@ pub async fn send_chat(
repo_url: team_clone.repo_url.clone(),
}),
workspace_dir: workspace_dir_clone.clone(),
+ sandbox_id: Some(team_clone.id.clone()),
};
let (driver_tx, mut driver_rx) = mpsc::channel(32);
@@ -1741,6 +1745,103 @@ pub async fn interact_sandbox(
})))
}
+/// Compact, text-only page state for agents (no base64 image to wade through).
+async fn sandbox_page_state(ctrl: &crate::sandbox::browser::BrowserController) -> serde_json::Value {
+ let (url, title) = match ctrl.sync_location().await {
+ Some(loc) => loc,
+ None => (
+ ctrl.current_url.lock().await.clone().unwrap_or_default(),
+ ctrl.current_title.lock().await.clone().unwrap_or_default(),
+ ),
+ };
+ let text = ctrl.extract_content().await.unwrap_or_default();
+ let clickable = ctrl.list_clickables(40).await;
+ json!({
+ "url": url,
+ "title": title,
+ "text": truncate_chars(&text, 2000),
+ "clickable": clickable,
+ })
+}
+
+async fn broadcast_sandbox_screenshot(state: &AppState, team_id: &str, ctrl: &crate::sandbox::browser::BrowserController) {
+ 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(),
+ url,
+ image_base64: b64,
+ timestamp: chrono::Utc::now().to_rfc3339(),
+ });
+ }
+}
+
+pub async fn get_sandbox_page(
+ State(state): State<AppState>,
+ Path(team_id): Path<String>,
+) -> Result<Json<serde_json::Value>, StatusCode> {
+ let ctrl = get_or_create_browser_controller(&state, &team_id)
+ .await
+ .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
+ Ok(Json(sandbox_page_state(&ctrl).await))
+}
+
+/// Agent-facing action endpoint: performs one action and returns the resulting page state,
+/// so an agent can act and answer without extra round-trips.
+pub async fn act_sandbox(
+ State(state): State<AppState>,
+ Path(team_id): Path<String>,
+ Json(payload): Json<InteractPayload>,
+) -> Result<Json<serde_json::Value>, StatusCode> {
+ let ctrl = get_or_create_browser_controller(&state, &team_id)
+ .await
+ .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
+ let text = payload.text.clone().unwrap_or_default();
+ let result: Result<String, String> = match payload.action.as_str() {
+ "click_text" | "click" if !text.is_empty() => ctrl
+ .click_text(&text)
+ .await
+ .map(|label| format!("clicked \"{}\"", label))
+ .map_err(|e| e.to_string()),
+ "type" => ctrl
+ .interact_type(&text)
+ .await
+ .map(|_| format!("typed {} chars", text.chars().count()))
+ .map_err(|e| e.to_string()),
+ "key" => {
+ let key = payload.key.clone().unwrap_or_else(|| "Enter".into());
+ ctrl.interact_key(&key, payload.code.as_deref())
+ .await
+ .map(|_| format!("pressed {}", key))
+ .map_err(|e| e.to_string())
+ }
+ "scroll" => ctrl
+ .interact_scroll(640, 400, 0.0, payload.delta_y.unwrap_or(600.0))
+ .await
+ .map(|_| "scrolled".to_string())
+ .map_err(|e| e.to_string()),
+ other => Err(format!(
+ "Unknown action \"{}\". Use click_text (with text), type (with text), key (with key) or scroll (with delta_y).",
+ other
+ )),
+ };
+ broadcast_sandbox_screenshot(&state, &team_id, &ctrl).await;
+ let mut page = sandbox_page_state(&ctrl).await;
+ match result {
+ Ok(done) => page["result"] = json!(done),
+ Err(err) => page["error"] = json!(err),
+ }
+ if let Some(url) = page["url"].as_str() {
+ let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {
+ team_id: team_id.clone(),
+ url: url.to_string(),
+ title: page["title"].as_str().unwrap_or("").to_string(),
+ status_code: 200,
+ });
+ }
+ Ok(Json(page))
+}
+
pub async fn execute_tool(
state: &AppState,
team_id: Option<&str>,
diff --git a/tests/driver_test.rs b/tests/driver_test.rs
index f2a22c31..839c2a29 100644
--- a/tests/driver_test.rs
+++ b/tests/driver_test.rs
@@ -85,6 +85,7 @@ async fn test_mock_driver_streaming() {
effort_level: None,
team_context: None,
workspace_dir: None,
+ sandbox_id: None,
};
let handle = tokio::spawn(async move {
@@ -139,6 +140,7 @@ fn test_turn_input_format_system_prompt_with_and_without_team_context() {
effort_level: None,
team_context: None,
workspace_dir: None,
+ sandbox_id: None,
};
let solo_prompt = input_solo.format_system_prompt();
@@ -162,6 +164,7 @@ fn test_turn_input_format_system_prompt_with_and_without_team_context() {
repo_url: None,
}),
workspace_dir: None,
+ sandbox_id: None,
};
let team_prompt = input_team.format_system_prompt();
@@ -186,6 +189,7 @@ fn test_turn_input_format_system_prompt_with_and_without_team_context() {
repo_url: Some("https://github.com/org/app".into()),
}),
workspace_dir: Some(std::path::PathBuf::from("/Users/dev/app")),
+ sandbox_id: None,
};
let ws_prompt = input_workspace.format_system_prompt();