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.

feat(sandbox): implement in-container CDP browser automation engine

Oleksandr Ivanchenko2f7bc1875a7a
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
new file mode 100644
index 00000000..b568dc87
--- /dev/null
+++ b/src/sandbox/browser.rs
@@ -0,0 +1,222 @@
+use futures::{SinkExt, StreamExt};
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+use thiserror::Error;
+use tokio::sync::Mutex;
+use tokio::time::timeout;
+use tokio_tungstenite::connect_async;
+use tokio_tungstenite::tungstenite::Message;
+
+#[derive(Error, Debug)]
+pub enum BrowserError {
+ #[error("HTTP error connecting to CDP: {0}")]
+ Http(String),
+ #[error("WebSocket connection to browser failed: {0}")]
+ Ws(String),
+ #[error("Protocol error: {0}")]
+ Protocol(String),
+ #[error("Operation timed out")]
+ Timeout,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct NavigationResult {
+ pub url: String,
+ pub title: String,
+ pub status_code: u16,
+}
+
+#[derive(Clone)]
+pub struct BrowserController {
+ pub cdp_port: u16,
+ pub current_url: Arc<Mutex<Option<String>>>,
+ pub current_title: Arc<Mutex<Option<String>>>,
+ pub last_screenshot: Arc<Mutex<Option<String>>>,
+ msg_id: Arc<AtomicU64>,
+}
+
+impl BrowserController {
+ pub fn new(cdp_port: u16) -> Self {
+ Self {
+ cdp_port,
+ current_url: Arc::new(Mutex::new(None)),
+ current_title: Arc::new(Mutex::new(None)),
+ last_screenshot: Arc::new(Mutex::new(None)),
+ msg_id: Arc::new(AtomicU64::new(1)),
+ }
+ }
+
+ async fn get_ws_url(&self) -> Result<String, BrowserError> {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(3))
+ .build()
+ .map_err(|e| BrowserError::Http(e.to_string()))?;
+
+ let url = format!("http://127.0.0.1:{}/json/version", self.cdp_port);
+ let resp = client
+ .get(&url)
+ .send()
+ .await
+ .map_err(|e| BrowserError::Http(e.to_string()))?;
+
+ let json: Value = resp.json().await.map_err(|e| BrowserError::Http(e.to_string()))?;
+ json["webSocketDebuggerUrl"]
+ .as_str()
+ .map(|s| s.to_string())
+ .ok_or_else(|| BrowserError::Protocol("Missing webSocketDebuggerUrl".into()))
+ }
+
+ async fn send_cdp_command(
+ &self,
+ method: &str,
+ params: Value,
+ ) -> Result<Value, BrowserError> {
+ let ws_url = self.get_ws_url().await?;
+ let (mut ws, _) = connect_async(&ws_url)
+ .await
+ .map_err(|e| BrowserError::Ws(e.to_string()))?;
+
+ let id = self.msg_id.fetch_add(1, Ordering::SeqCst);
+ let request = json!({
+ "id": id,
+ "method": method,
+ "params": params
+ });
+
+ ws.send(Message::Text(request.to_string().into()))
+ .await
+ .map_err(|e| BrowserError::Ws(e.to_string()))?;
+
+ let deadline = Duration::from_secs(15);
+ timeout(deadline, async {
+ while let Some(msg) = ws.next().await {
+ if let Ok(msg) = msg {
+ let txt = match msg {
+ Message::Text(t) => t.to_string(),
+ _ => continue,
+ };
+ if let Ok(parsed) = serde_json::from_str::<Value>(&txt) {
+ if parsed.get("id").and_then(|v| v.as_u64()) == Some(id) {
+ if let Some(err) = parsed.get("error") {
+ return Err(BrowserError::Protocol(err.to_string()));
+ }
+ return Ok(parsed.get("result").cloned().unwrap_or(Value::Null));
+ }
+ }
+ }
+ }
+ Err(BrowserError::Protocol("Connection closed before response".into()))
+ })
+ .await
+ .map_err(|_| BrowserError::Timeout)?
+ }
+
+ pub async fn navigate(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {
+ let _ = self.send_cdp_command("Page.enable", json!({})).await;
+ let _res = self
+ .send_cdp_command("Page.navigate", json!({ "url": target_url }))
+ .await?;
+
+ // Extract title
+ let eval_res = self
+ .send_cdp_command(
+ "Runtime.evaluate",
+ json!({ "expression": "document.title", "returnByValue": true }),
+ )
+ .await
+ .ok();
+
+ let title = eval_res
+ .as_ref()
+ .and_then(|r| r["result"]["value"].as_str())
+ .unwrap_or(target_url)
+ .to_string();
+
+ *self.current_url.lock().await = Some(target_url.to_string());
+ *self.current_title.lock().await = Some(title.clone());
+
+ // Automatically capture fresh screenshot on navigation
+ let _ = self.capture_screenshot().await;
+
+ Ok(NavigationResult {
+ url: target_url.to_string(),
+ title,
+ status_code: 200,
+ })
+ }
+
+ pub async fn capture_screenshot(&self) -> Result<String, BrowserError> {
+ let res = self
+ .send_cdp_command(
+ "Page.captureScreenshot",
+ json!({ "format": "jpeg", "quality": 75 }),
+ )
+ .await?;
+
+ let b64 = res["data"]
+ .as_str()
+ .ok_or_else(|| BrowserError::Protocol("Screenshot data missing".into()))?
+ .to_string();
+
+ *self.last_screenshot.lock().await = Some(b64.clone());
+ Ok(b64)
+ }
+
+ pub async fn extract_content(&self) -> Result<String, BrowserError> {
+ let expression = r#"
+ (function() {
+ var clone = document.body.cloneNode(true);
+ var scripts = clone.getElementsByTagName('script');
+ while(scripts.length > 0) { scripts[0].parentNode.removeChild(scripts[0]); }
+ var styles = clone.getElementsByTagName('style');
+ while(styles.length > 0) { styles[0].parentNode.removeChild(styles[0]); }
+ return clone.innerText.substring(0, 10000);
+ })()
+ "#;
+ let res = self
+ .send_cdp_command(
+ "Runtime.evaluate",
+ json!({ "expression": expression, "returnByValue": true }),
+ )
+ .await?;
+
+ let text = res["result"]["value"].as_str().unwrap_or("").to_string();
+ Ok(text)
+ }
+
+ pub async fn click(&self, selector: &str) -> Result<(), BrowserError> {
+ let expression = format!(
+ "var el = document.querySelector('{}'); if (el) {{ el.click(); true; }} else {{ false; }}",
+ selector.replace('\'', "\\'")
+ );
+ let _ = self
+ .send_cdp_command(
+ "Runtime.evaluate",
+ json!({ "expression": expression, "returnByValue": true }),
+ )
+ .await?;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ let _ = self.capture_screenshot().await;
+ Ok(())
+ }
+
+ pub async fn type_text(&self, selector: &str, text: &str) -> Result<(), BrowserError> {
+ let expression = format!(
+ "var el = document.querySelector('{}'); if (el) {{ el.value = '{}'; el.dispatchEvent(new Event('input', {{ bubbles: true }})); true; }} else {{ false; }}",
+ selector.replace('\'', "\\'"),
+ text.replace('\'', "\\'")
+ );
+ let _ = self
+ .send_cdp_command(
+ "Runtime.evaluate",
+ json!({ "expression": expression, "returnByValue": true }),
+ )
+ .await?;
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ let _ = self.capture_screenshot().await;
+ Ok(())
+ }
+}
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index d0749c19..a44c800c 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -1,3 +1,6 @@
+pub mod browser;
pub mod manager;
+pub use browser::{BrowserController, BrowserError, NavigationResult};
pub use manager::{ActiveSandbox, SandboxError, SandboxManager, ShellOutput};
+
diff --git a/tests/browser_test.rs b/tests/browser_test.rs
new file mode 100644
index 00000000..45373013
--- /dev/null
+++ b/tests/browser_test.rs
@@ -0,0 +1,244 @@
+use futures::{SinkExt, StreamExt};
+use kwnt::sandbox::browser::{BrowserController, BrowserError, NavigationResult};
+use serde_json::{json, Value};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+use tokio_tungstenite::accept_async;
+
+#[test]
+fn test_browser_controller_serialization_and_helpers() {
+ let nav = NavigationResult {
+ url: "https://example.com".into(),
+ title: "Example Domain".into(),
+ status_code: 200,
+ };
+
+ let json = serde_json::to_string(&nav).unwrap();
+ assert!(json.contains("Example Domain"));
+
+ let deserialized: NavigationResult = serde_json::from_str(&json).unwrap();
+ assert_eq!(deserialized.url, "https://example.com");
+ assert_eq!(deserialized.title, "Example Domain");
+ assert_eq!(deserialized.status_code, 200);
+
+ let controller = BrowserController::new(19222);
+ assert_eq!(controller.cdp_port, 19222);
+}
+
+#[tokio::test]
+async fn test_browser_controller_connection_failure() {
+ // Port 65530 is unlikely to be listening, should fail with Http error
+ let controller = BrowserController::new(65530);
+ let res = controller.navigate("https://example.com").await;
+ assert!(res.is_err());
+ match res.unwrap_err() {
+ BrowserError::Http(_) => {}
+ other => panic!("Expected BrowserError::Http, got {:?}", other),
+ }
+}
+
+#[tokio::test]
+async fn test_mock_cdp_controller_lifecycle() {
+ let http_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let http_port = http_listener.local_addr().unwrap().port();
+
+ let ws_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let ws_port = ws_listener.local_addr().unwrap().port();
+
+ // Spawn HTTP listener for /json/version
+ let http_handle = tokio::spawn(async move {
+ while let Ok((mut stream, _)) = http_listener.accept().await {
+ let mut buf = vec![0u8; 1024];
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let req = String::from_utf8_lossy(&buf[..n]);
+
+ if req.contains("/json/version") {
+ let ws_url = format!("ws://127.0.0.1:{}/devtools/page/test", ws_port);
+ let body = json!({
+ "Browser": "Chrome/120.0.0.0",
+ "webSocketDebuggerUrl": ws_url
+ })
+ .to_string();
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ body.len(),
+ body
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ let _ = stream.flush().await;
+ }
+ }
+ });
+
+ // Spawn WebSocket listener for CDP commands
+ let ws_handle = tokio::spawn(async move {
+ while let Ok((stream, _)) = ws_listener.accept().await {
+ tokio::spawn(async move {
+ if let Ok(mut ws) = accept_async(stream).await {
+ while let Some(Ok(msg)) = ws.next().await {
+ if let tokio_tungstenite::tungstenite::Message::Text(txt) = msg {
+ let parsed: Value = serde_json::from_str(&txt).unwrap();
+ let id = parsed["id"].as_u64().unwrap();
+ let method = parsed["method"].as_str().unwrap();
+
+ let result_val = match method {
+ "Page.enable" => json!({}),
+ "Page.navigate" => json!({ "frameId": "F1", "loaderId": "L1" }),
+ "Page.captureScreenshot" => json!({ "data": "dGVzdC1zY3JlZW5zaG90" }),
+ "Runtime.evaluate" => {
+ let expr = parsed["params"]["expression"].as_str().unwrap();
+ if expr == "document.title" {
+ json!({ "result": { "type": "string", "value": "Kwants Sandbox Test" } })
+ } else if expr.contains("clone.innerText") {
+ json!({ "result": { "type": "string", "value": "Extracted DOM Content" } })
+ } else if expr.contains("el.click()") {
+ json!({ "result": { "type": "boolean", "value": true } })
+ } else if expr.contains("el.value =") {
+ json!({ "result": { "type": "boolean", "value": true } })
+ } else {
+ json!({ "result": { "type": "undefined" } })
+ }
+ }
+ _ => json!({}),
+ };
+
+ let resp = json!({
+ "id": id,
+ "result": result_val
+ });
+
+ let _ = ws
+ .send(tokio_tungstenite::tungstenite::Message::Text(
+ resp.to_string().into(),
+ ))
+ .await;
+ }
+ }
+ }
+ });
+ }
+ });
+
+ let controller = BrowserController::new(http_port);
+
+ // Test navigate
+ let nav_res = controller.navigate("https://kwants.internal/app").await.unwrap();
+ assert_eq!(nav_res.url, "https://kwants.internal/app");
+ assert_eq!(nav_res.title, "Kwants Sandbox Test");
+ assert_eq!(nav_res.status_code, 200);
+
+ // Verify internal state updated
+ assert_eq!(controller.current_url.lock().await.as_deref(), Some("https://kwants.internal/app"));
+ assert_eq!(controller.current_title.lock().await.as_deref(), Some("Kwants Sandbox Test"));
+ assert_eq!(controller.last_screenshot.lock().await.as_deref(), Some("dGVzdC1zY3JlZW5zaG90"));
+
+ // Test capture_screenshot directly
+ let shot = controller.capture_screenshot().await.unwrap();
+ assert_eq!(shot, "dGVzdC1zY3JlZW5zaG90");
+
+ // Test extract_content
+ let text = controller.extract_content().await.unwrap();
+ assert_eq!(text, "Extracted DOM Content");
+
+ // Test click
+ controller.click("#submit-button").await.unwrap();
+
+ // Test type_text
+ controller.type_text("input[name=query]", "hello world").await.unwrap();
+
+ http_handle.abort();
+ ws_handle.abort();
+}
+
+#[tokio::test]
+async fn test_mock_cdp_missing_ws_url() {
+ let http_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let http_port = http_listener.local_addr().unwrap().port();
+
+ let http_handle = tokio::spawn(async move {
+ while let Ok((mut stream, _)) = http_listener.accept().await {
+ let mut buf = vec![0u8; 1024];
+ let _ = stream.read(&mut buf).await;
+ let body = json!({ "Browser": "Chrome/120.0.0.0" }).to_string();
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ body.len(),
+ body
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ let _ = stream.flush().await;
+ }
+ });
+
+ let controller = BrowserController::new(http_port);
+ let res = controller.navigate("https://kwants.internal").await;
+ match res {
+ Err(BrowserError::Protocol(msg)) => assert!(msg.contains("Missing webSocketDebuggerUrl")),
+ other => panic!("Expected BrowserError::Protocol, got {:?}", other),
+ }
+
+ http_handle.abort();
+}
+
+#[tokio::test]
+async fn test_mock_cdp_protocol_error_response() {
+ let http_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let http_port = http_listener.local_addr().unwrap().port();
+
+ let ws_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let ws_port = ws_listener.local_addr().unwrap().port();
+
+ let http_handle = tokio::spawn(async move {
+ while let Ok((mut stream, _)) = http_listener.accept().await {
+ let mut buf = vec![0u8; 1024];
+ let _ = stream.read(&mut buf).await;
+ let ws_url = format!("ws://127.0.0.1:{}/devtools/page/test", ws_port);
+ let body = json!({
+ "Browser": "Chrome/120.0.0.0",
+ "webSocketDebuggerUrl": ws_url
+ })
+ .to_string();
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ body.len(),
+ body
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ let _ = stream.flush().await;
+ }
+ });
+
+ let ws_handle = tokio::spawn(async move {
+ while let Ok((stream, _)) = ws_listener.accept().await {
+ tokio::spawn(async move {
+ if let Ok(mut ws) = accept_async(stream).await {
+ while let Some(Ok(msg)) = ws.next().await {
+ if let tokio_tungstenite::tungstenite::Message::Text(txt) = msg {
+ let parsed: Value = serde_json::from_str(&txt).unwrap();
+ let id = parsed["id"].as_u64().unwrap();
+ let resp = json!({
+ "id": id,
+ "error": { "code": -32000, "message": "Failed to take screenshot" }
+ });
+ let _ = ws
+ .send(tokio_tungstenite::tungstenite::Message::Text(
+ resp.to_string().into(),
+ ))
+ .await;
+ }
+ }
+ }
+ });
+ }
+ });
+
+ let controller = BrowserController::new(http_port);
+ let res = controller.capture_screenshot().await;
+ match res {
+ Err(BrowserError::Protocol(msg)) => assert!(msg.contains("Failed to take screenshot")),
+ other => panic!("Expected BrowserError::Protocol, got {:?}", other),
+ }
+
+ http_handle.abort();
+ ws_handle.abort();
+}