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.

fix(sandbox): fix channel browser targeting, conversation history in CLI drivers, and relative URL navigation

Oleksandr Ivanchenko63888aeb6fe4
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 46b2a210..4b45ff34 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -279,6 +279,8 @@ export const App: React.FC = () => {
!teamId ||
currentTid === teamId ||
teamId === 'default' ||
+ teamId === selectedIdRef.current ||
+ teamId === streamingContextIdRef.current ||
(k && (k.id === teamId || k.name.toLowerCase() === teamId.toLowerCase())) ||
(t && (t.id === teamId || t.name.toLowerCase() === teamId.toLowerCase()));
if (isMatch) {
@@ -300,6 +302,8 @@ export const App: React.FC = () => {
!teamId ||
currentTid === teamId ||
teamId === 'default' ||
+ teamId === selectedIdRef.current ||
+ teamId === streamingContextIdRef.current ||
(k && (k.id === teamId || k.name.toLowerCase() === teamId.toLowerCase())) ||
(t && (t.id === teamId || t.name.toLowerCase() === teamId.toLowerCase()));
if (isMatch) {
@@ -321,6 +325,8 @@ export const App: React.FC = () => {
!teamId ||
currentTid === teamId ||
teamId === 'default' ||
+ teamId === selectedIdRef.current ||
+ teamId === streamingContextIdRef.current ||
(k && (k.id === teamId || k.name.toLowerCase() === teamId.toLowerCase())) ||
(t && (t.id === teamId || t.name.toLowerCase() === teamId.toLowerCase()));
if (isMatch) {
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 97aa41ac..6635f902 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -52,6 +52,33 @@ pub fn find_cli_binary(name: &str) -> Option<String> {
None
}
+pub fn build_cli_prompt(input: &TurnInput) -> String {
+ if input.history.is_empty() {
+ return input.prompt.clone();
+ }
+
+ let mut parts = Vec::new();
+ parts.push("### Conversation History:".to_string());
+ let recent = if input.history.len() > 10 {
+ &input.history[input.history.len() - 10..]
+ } else {
+ &input.history[..]
+ };
+
+ for msg in recent {
+ let role = match msg.sender_role.as_str() {
+ "user" => "User",
+ "kwant" => "Assistant",
+ "system" => "System",
+ _ => &msg.sender_role,
+ };
+ parts.push(format!("{}: {}", role, msg.text));
+ }
+
+ parts.push(format!("\n### Current User Request:\n{}", input.prompt));
+ parts.join("\n")
+}
+
#[derive(Clone, Debug, Default)]
pub struct CliDriver {
pub cli_binary: Option<String>,
@@ -117,6 +144,7 @@ impl Driver for CliDriver {
.await;
let system_prompt = input.format_system_prompt();
+ let effective_prompt = build_cli_prompt(&input);
// Prevent CLI tools from spawning desktop browser windows on host
cmd.env("BROWSER", "none");
@@ -130,7 +158,7 @@ impl Driver for CliDriver {
"low" => "low",
_ => "medium",
};
- let full_prompt = format!("[System Context: {}]\n\n{}", system_prompt, input.prompt);
+ let full_prompt = format!("[System Context: {}]\n\n{}", system_prompt, effective_prompt);
cmd.arg("exec")
.arg("--ephemeral")
.arg("--skip-git-repo-check")
@@ -145,12 +173,12 @@ impl Driver for CliDriver {
}
"grok" => {
cmd.arg("--rules").arg(&system_prompt);
- cmd.arg("-p").arg(&input.prompt);
+ cmd.arg("-p").arg(&effective_prompt);
}
_ => {
// claude default
cmd.arg("--append-system-prompt").arg(&system_prompt);
- cmd.arg("-p").arg(&input.prompt);
+ cmd.arg("-p").arg(&effective_prompt);
}
}
@@ -226,3 +254,99 @@ impl Driver for CliDriver {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::db::models::{Kwant, Message};
+
+ #[test]
+ fn test_build_cli_prompt_with_history() {
+ let kwant = Kwant {
+ id: "k1".into(),
+ name: "Architect".into(),
+ title: "Lead".into(),
+ persona_prompt: "p".into(),
+ avatar_sprite: "s".into(),
+ driver_type: "cli".into(),
+ preferred_model: "grok".into(),
+ temperature: 0.7,
+ max_tokens: 1000,
+ level: 1,
+ turns_completed: 0,
+ created_at: None,
+ };
+ let input = TurnInput {
+ thread_id: "t1".into(),
+ kwant,
+ prompt: "open some playlist page".into(),
+ history: vec![
+ Message {
+ id: "m1".into(),
+ channel_id: Some("c1".into()),
+ direct_kwant_id: None,
+ sender_role: "user".into(),
+ sender_id: "Player".into(),
+ text: "open booktun.ing".into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 10,
+ created_at: None,
+ },
+ Message {
+ id: "m2".into(),
+ channel_id: Some("c1".into()),
+ direct_kwant_id: None,
+ sender_role: "kwant".into(),
+ sender_id: "Architect".into(),
+ text: "I opened booktun.ing for you.".into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 20,
+ created_at: None,
+ },
+ ],
+ model_override: None,
+ effort_level: None,
+ team_context: None,
+ workspace_dir: None,
+ };
+
+ let result = build_cli_prompt(&input);
+ assert!(result.contains("### Conversation History:"));
+ assert!(result.contains("User: open booktun.ing"));
+ assert!(result.contains("Assistant: I opened booktun.ing for you."));
+ assert!(result.contains("### Current User Request:\nopen some playlist page"));
+ }
+
+ #[test]
+ fn test_build_cli_prompt_without_history() {
+ let kwant = Kwant {
+ id: "k1".into(),
+ name: "Architect".into(),
+ title: "Lead".into(),
+ persona_prompt: "p".into(),
+ avatar_sprite: "s".into(),
+ driver_type: "cli".into(),
+ preferred_model: "grok".into(),
+ temperature: 0.7,
+ max_tokens: 1000,
+ level: 1,
+ turns_completed: 0,
+ created_at: None,
+ };
+ let input = TurnInput {
+ thread_id: "t1".into(),
+ kwant,
+ prompt: "hello world".into(),
+ history: vec![],
+ model_override: None,
+ effort_level: None,
+ team_context: None,
+ workspace_dir: None,
+ };
+
+ let result = build_cli_prompt(&input);
+ assert_eq!(result, "hello world");
+ }
+}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 21889bd0..a2086bff 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -262,11 +262,20 @@ fn execute_single_turn(
let sandbox_target = team_keys
.as_ref()
.map(|(id, _)| id.clone())
+ .or_else(|| channel_id.clone())
.or_else(|| kwant_id.clone())
.unwrap_or_else(|| target_kwant.id.clone());
+ let active_browser_url = if let Some(ctrl) = state.browser_controllers.lock().await.get(&sandbox_target) {
+ ctrl.current_url.lock().await.clone()
+ } else {
+ None
+ };
+
let mut final_prompt = prompt.clone();
- if let Some(target_url) = detect_url_in_prompt(&prompt) {
+ let target_url_opt = detect_url_with_context(&prompt, active_browser_url.as_deref());
+
+ if let Some(target_url) = target_url_opt {
let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(
"🌐 Navigating Sandbox VM in-container browser to {}...",
target_url
@@ -299,6 +308,13 @@ fn execute_single_turn(
);
}
}
+ } 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") {
+ final_prompt = format!(
+ "{}\n\n[Active Sandbox Browser State: The right-panel Sandbox VM browser is currently viewing: {}. Maintain context on this website. Do not suggest or switch to other services like YouTube unless explicitly requested.]",
+ prompt, curr_url
+ );
+ }
}
let driver = resolve_driver_for_model(&target_model, configured_key, endpoint);
@@ -340,6 +356,31 @@ fn execute_single_turn(
if cancelled {
let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta("⏹️ Cancelled by user".into()));
} else if let Ok(Ok(output)) = driver_task.await {
+ // Post-turn sync: If bot response outputs a URL, sync navigation so the user sees it in Sandbox VM
+ if let Some(bot_url) = extract_url_from_text(&output.text) {
+ if let Some(ctrl) = get_or_create_browser_controller(&state, &sandbox_target).await {
+ let curr = ctrl.current_url.lock().await.clone().unwrap_or_default();
+ if curr != bot_url && !bot_url.contains("localhost") && !bot_url.contains("127.0.0.1") {
+ if let Ok(nav) = ctrl.navigate(&bot_url).await {
+ let _ = event_broadcast.send(RuntimeEvent::BrowserNavigated {
+ team_id: sandbox_target.clone(),
+ url: bot_url.clone(),
+ title: nav.title.clone(),
+ status_code: nav.status_code,
+ });
+ if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {
+ let _ = event_broadcast.send(RuntimeEvent::BrowserScreenshot {
+ team_id: sandbox_target.clone(),
+ url: bot_url.clone(),
+ image_base64: b64,
+ timestamp: chrono::Utc::now().to_rfc3339(),
+ });
+ }
+ }
+ }
+ }
+ }
+
let asst_msg = NewMessage {
channel_id: channel_id.clone(),
direct_kwant_id: kwant_id.clone(),
@@ -1162,7 +1203,7 @@ pub struct NavigatePayload {
pub url: String,
}
-async fn resolve_sandbox_target_info(state: &AppState, target_id: &str) -> Option<(String, PathBuf)> {
+pub async fn resolve_sandbox_target_info(state: &AppState, target_id: &str) -> Option<(String, PathBuf)> {
if let Ok(Some(team)) = state.db.get_team(target_id).await {
let ws = team
.workspace_path
@@ -1171,6 +1212,10 @@ async fn resolve_sandbox_target_info(state: &AppState, target_id: &str) -> Optio
.map(PathBuf::from)
.unwrap_or_else(|| state.config.data_dir.join("workspaces").join(&team.name));
Some((team.name, ws))
+ } else if let Ok(Some(channel)) = state.db.get_channel(target_id).await {
+ let safe_cname = channel.name.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "-");
+ let ws = state.config.data_dir.join("workspaces").join(format!("chan-{}", safe_cname));
+ Some((format!("chan-{}", safe_cname), ws))
} else if let Ok(Some(kwant)) = state.db.get_kwant(target_id).await {
let safe_kname = kwant.name.to_lowercase().replace(|c: char| !c.is_alphanumeric(), "-");
Some((format!("bot-{}", safe_kname), state.config.data_dir.join("workspaces").join(format!("bot-{}", safe_kname))))
@@ -1187,35 +1232,112 @@ async fn resolve_sandbox_target_info(state: &AppState, target_id: &str) -> Optio
}
}
-pub fn detect_url_in_prompt(prompt: &str) -> Option<String> {
+const EXCLUDED_EXTENSIONS: &[&str] = &[
+ "rs", "ts", "tsx", "js", "jsx", "json", "toml", "yaml", "yml", "md",
+ "txt", "log", "lock", "png", "jpg", "jpeg", "gif", "svg", "css", "html",
+ "sh", "py", "go", "c", "cpp", "h", "java", "kt", "rb", "php", "sql",
+];
+
+pub fn extract_url_from_text(text: &str) -> Option<String> {
+ for word in text.split_whitespace() {
+ let clean = word.trim_matches(|c: char| {
+ !c.is_alphanumeric() && c != '.' && c != '/' && c != ':' && c != '-' && c != '_' && c != '?' && c != '=' && c != '&' && c != '#'
+ });
+ if clean.starts_with("http://") || clean.starts_with("https://") {
+ return Some(clean.to_string());
+ }
+ if !clean.contains('@') && clean.contains('.') && !clean.starts_with('.') && !clean.ends_with('.') {
+ let host_part = clean.split('/').next().unwrap_or("");
+ let parts: Vec<&str> = host_part.split('.').collect();
+ if parts.len() >= 2 {
+ let tld = parts.last().unwrap_or(&"");
+ let tld_lower = tld.to_lowercase();
+ if tld.len() >= 2
+ && tld.len() <= 12
+ && tld.chars().all(|c| c.is_ascii_alphabetic())
+ && !EXCLUDED_EXTENSIONS.contains(&tld_lower.as_str())
+ {
+ let valid_labels = parts.iter().all(|label| {
+ !label.is_empty()
+ && !label.starts_with('-')
+ && !label.ends_with('-')
+ && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
+ });
+ if valid_labels {
+ return Some(format!("https://{}", clean));
+ }
+ }
+ }
+ }
+ }
+ None
+}
+
+pub fn detect_url_with_context(prompt: &str, current_url: Option<&str>) -> Option<String> {
let lower = prompt.to_lowercase();
let is_browser_request = lower.contains("browser")
|| lower.contains("open ")
|| lower.contains("navigate")
|| lower.contains("go to ")
|| lower.contains("browse ")
+ || lower.contains("visit ")
|| lower.contains("search for ")
+ || lower.contains("look up ")
|| lower.contains("http://")
|| lower.contains("https://");
+ if let Some(direct_url) = extract_url_from_text(prompt) {
+ if is_browser_request || prompt.split_whitespace().count() <= 3 {
+ return Some(direct_url);
+ }
+ }
+
if !is_browser_request {
return None;
}
- for word in prompt.split_whitespace() {
- let clean = word.trim_matches(|c: char| !c.is_alphanumeric() && c != '.' && c != '/' && c != ':' && c != '-' && c != '_');
- if clean.starts_with("http://") || clean.starts_with("https://") {
- return Some(clean.to_string());
- }
- if (clean.contains(".com") || clean.contains(".org") || clean.contains(".net") || clean.contains(".de") || clean.contains(".io") || clean.contains(".ai") || clean.contains(".co"))
- && !clean.contains('@')
- {
- return Some(format!("https://{}", clean));
+ // Relative navigation if active current_url exists
+ if let Some(curr) = current_url {
+ let curr = curr.trim();
+ if (curr.starts_with("http://") || curr.starts_with("https://")) && !curr.contains("about:blank") && !curr.contains("example.com") {
+ let origin = if let Some(idx) = curr[8..].find('/') {
+ &curr[..8 + idx]
+ } else {
+ curr
+ };
+
+ for word in prompt.split_whitespace() {
+ let clean = word.trim_matches(|c: char| !c.is_alphanumeric() && c != '/');
+ if clean.starts_with('/') && clean.len() > 1 {
+ return Some(format!("{}{}", origin, clean));
+ }
+ }
+
+ if lower.contains("playlist") {
+ return Some(format!("{}/playlists", origin));
+ } else if lower.contains("explore") {
+ return Some(format!("{}/explore", origin));
+ } else if lower.contains("search") && !lower.contains("google") {
+ return Some(format!("{}/search", origin));
+ } else if lower.contains("login") || lower.contains("sign in") {
+ return Some(format!("{}/login", origin));
+ } else if lower.contains("settings") {
+ return Some(format!("{}/settings", origin));
+ } else if lower.contains("about") {
+ return Some(format!("{}/about", origin));
+ } else if lower.contains("home") {
+ return Some(origin.to_string());
+ }
}
}
+
None
}
+pub fn detect_url_in_prompt(prompt: &str) -> Option<String> {
+ detect_url_with_context(prompt, None)
+}
+
pub async fn get_or_create_browser_controller(
state: &AppState,
team_id: &str,
diff --git a/tests/server_test.rs b/tests/server_test.rs
index e208d246..ff829602 100644
--- a/tests/server_test.rs
+++ b/tests/server_test.rs
@@ -549,5 +549,66 @@ async fn test_sandbox_interactive_control_endpoint() {
assert_eq!(resp.status(), StatusCode::OK);
}
+#[tokio::test]
+async fn test_url_extraction_and_relative_navigation() {
+ use kwnt::server::routes::{detect_url_in_prompt, detect_url_with_context, extract_url_from_text};
+
+ // 1. Modern TLD (.ing) extraction
+ let url = extract_url_from_text("please open booktun.ing for me");
+ assert_eq!(url, Some("https://booktun.ing".to_string()));
+
+ // 2. Code extensions must not be treated as URLs
+ assert_eq!(extract_url_from_text("read src/main.rs"), None);
+ assert_eq!(extract_url_from_text("check file.json"), None);
+
+ // 3. Direct URL in prompt detection
+ assert_eq!(
+ detect_url_in_prompt("open booktun.ing"),
+ Some("https://booktun.ing".to_string())
+ );
+
+ // 4. Relative navigation with active browser context
+ let rel_playlist = detect_url_with_context(
+ "open some playlist page",
+ Some("https://booktun.ing"),
+ );
+ assert_eq!(rel_playlist, Some("https://booktun.ing/playlists".to_string()));
+
+ let rel_path = detect_url_with_context(
+ "navigate to /explore",
+ Some("https://booktun.ing"),
+ );
+ assert_eq!(rel_path, Some("https://booktun.ing/explore".to_string()));
+
+ // 5. Explicit navigation to another site overrides active browser context
+ let override_url = detect_url_with_context(
+ "open youtube.com",
+ Some("https://booktun.ing"),
+ );
+ assert_eq!(override_url, Some("https://youtube.com".to_string()));
+}
+
+#[tokio::test]
+async fn test_channel_sandbox_target_resolution() {
+ use kwnt::server::routes::resolve_sandbox_target_info;
+
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config::default();
+ let tools = ToolRunner::new(tmp.path().join("workspace"));
+ let broker = PermissionBroker::new();
+ let router = LayaRouter::new(config.laya_url.clone());
+ let state = AppState::new(config, db.clone(), tools, broker, router);
+
+ let channels = db.list_channels().await.unwrap();
+ let general_channel = channels.iter().find(|c| c.name == "general").expect("Seeded general channel");
+
+ let resolved = resolve_sandbox_target_info(&state, &general_channel.id).await;
+ assert!(resolved.is_some());
+ let (target_name, ws_path) = resolved.unwrap();
+ assert_eq!(target_name, "chan-general");
+ assert!(ws_path.to_string_lossy().ends_with("workspaces/chan-general"));
+}
+