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.

Open sandbox browser in a live, shared full-page viewer

Oleksandr Ivanchenko9f6d05223d5c
diff --git a/frontend/src/components/SandboxViewer.tsx b/frontend/src/components/SandboxViewer.tsx
new file mode 100644
index 00000000..c872d4f9
--- /dev/null
+++ b/frontend/src/components/SandboxViewer.tsx
@@ -0,0 +1,293 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { Globe, Loader2, RefreshCw, Share2, MousePointerClick } from 'lucide-react';
+
+// Must match the sandbox Chromium --window-size (docker/entrypoint.sh)
+const VIEWPORT_W = 1280;
+const VIEWPORT_H = 800;
+const POLL_MS = 2000;
+const SPECIAL_KEYS = ['Enter', 'Backspace', 'Tab', 'Escape', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Delete', 'Home', 'End', 'PageUp', 'PageDown'];
+
+type InteractPayload = {
+ action: 'click' | 'type' | 'key' | 'scroll';
+ x?: number;
+ y?: number;
+ text?: string;
+ key?: string;
+ code?: string;
+ delta_x?: number;
+ delta_y?: number;
+};
+
+/** Full-page live view of a sandbox's Chromium. Everything happens in the same
+ * browser the agents use, so they see the resulting page on their next turn. */
+export const SandboxViewer: React.FC<{ teamId: string }> = ({ teamId }) => {
+ const [screenshot, setScreenshot] = useState<string | null>(null);
+ const [url, setUrl] = useState('');
+ const [title, setTitle] = useState('');
+ const [inputUrl, setInputUrl] = useState('');
+ const [isBusy, setIsBusy] = useState(false);
+ const [isFocused, setIsFocused] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const imageRef = useRef<HTMLImageElement>(null);
+ const viewportRef = useRef<HTMLDivElement>(null);
+ const busyRef = useRef(false);
+ const urlInputFocusedRef = useRef(false);
+ const lastWheelRef = useRef(0);
+ const api = `/api/sandbox/${encodeURIComponent(teamId)}`;
+
+ const applyUrl = useCallback((next?: string) => {
+ if (!next || next === 'about:blank') return;
+ setUrl(next);
+ if (!urlInputFocusedRef.current) setInputUrl(next);
+ }, []);
+
+ const refresh = useCallback(async () => {
+ if (busyRef.current) return;
+ try {
+ const res = await fetch(`${api}/screenshot`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ if (data.image_base64) setScreenshot(data.image_base64);
+ applyUrl(data.url);
+ if (data.title) setTitle(data.title);
+ setError(null);
+ } catch (err) {
+ setError('Sandbox browser is not reachable. Is the sandbox running?');
+ }
+ }, [api, applyUrl]);
+
+ const run = useCallback(
+ async (fn: () => Promise<void>) => {
+ busyRef.current = true;
+ setIsBusy(true);
+ try {
+ await fn();
+ } catch (err) {
+ console.error('Sandbox viewer action failed:', err);
+ } finally {
+ busyRef.current = false;
+ setIsBusy(false);
+ }
+ },
+ []
+ );
+
+ const interact = useCallback(
+ (payload: InteractPayload) =>
+ run(async () => {
+ const res = await fetch(`${api}/interact`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ if (!res.ok) return;
+ const data = await res.json();
+ if (data.screenshot) setScreenshot(data.screenshot);
+ applyUrl(data.url);
+ }),
+ [api, run, applyUrl]
+ );
+
+ const navigate = useCallback(
+ (target: string) =>
+ run(async () => {
+ let next = target.trim();
+ if (!next) return;
+ if (!/^[a-z]+:\/\//i.test(next)) next = `https://${next}`;
+ const res = await fetch(`${api}/navigate`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ url: next }),
+ });
+ if (res.ok) {
+ const data = await res.json();
+ applyUrl(data.url);
+ if (data.title) setTitle(data.title);
+ }
+ }).then(refresh),
+ [api, run, applyUrl, refresh]
+ );
+
+ // Initial load + polling so page changes (loads, animations, bot actions) show up
+ useEffect(() => {
+ refresh();
+ const timer = window.setInterval(() => {
+ if (document.visibilityState === 'visible') refresh();
+ }, POLL_MS);
+ return () => window.clearInterval(timer);
+ }, [refresh]);
+
+ // Live updates when the bot (or the in-app pane) drives the same browser
+ useEffect(() => {
+ const sse = new EventSource('/api/events');
+ sse.onmessage = (e) => {
+ try {
+ const event = JSON.parse(e.data);
+ if (event.data?.team_id !== teamId) return;
+ if (event.type === 'browser_screenshot' || event.type === 'BrowserScreenshot') {
+ if (event.data.image_base64) setScreenshot(event.data.image_base64);
+ applyUrl(event.data.url);
+ } else if (event.type === 'browser_navigated' || event.type === 'BrowserNavigated') {
+ applyUrl(event.data.url);
+ if (event.data.title) setTitle(event.data.title);
+ }
+ } catch {
+ // ignore malformed events
+ }
+ };
+ return () => sse.close();
+ }, [teamId, applyUrl]);
+
+ useEffect(() => {
+ document.title = `${title || url || 'Sandbox browser'} · kwnt sandbox`;
+ }, [title, url]);
+
+ const toViewport = (clientX: number, clientY: number) => {
+ const img = imageRef.current;
+ const rect = img?.getBoundingClientRect();
+ if (!img || !rect || rect.width === 0) return null;
+ // Account for object-contain letterboxing
+ const ratio = (img.naturalWidth || VIEWPORT_W) / (img.naturalHeight || VIEWPORT_H);
+ let w = rect.width;
+ let h = rect.width / ratio;
+ if (h > rect.height) {
+ h = rect.height;
+ w = rect.height * ratio;
+ }
+ const x = clientX - rect.left - (rect.width - w) / 2;
+ const y = clientY - rect.top - (rect.height - h) / 2;
+ if (x < 0 || y < 0 || x > w || y > h) return null;
+ return {
+ x: Math.round((x / w) * VIEWPORT_W),
+ y: Math.round((y / h) * VIEWPORT_H),
+ };
+ };
+
+ const handleClick = (e: React.MouseEvent) => {
+ viewportRef.current?.focus();
+ const p = toViewport(e.clientX, e.clientY);
+ if (p) interact({ action: 'click', ...p });
+ };
+
+ const handleWheel = (e: React.WheelEvent) => {
+ const now = Date.now();
+ if (now - lastWheelRef.current < 120) return;
+ lastWheelRef.current = now;
+ const p = toViewport(e.clientX, e.clientY) || { x: VIEWPORT_W / 2, y: VIEWPORT_H / 2 };
+ interact({ action: 'scroll', ...p, delta_x: e.deltaX, delta_y: e.deltaY });
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent) => {
+ if (e.metaKey || e.ctrlKey || e.altKey) return; // let browser shortcuts (incl. paste) through
+ if (SPECIAL_KEYS.includes(e.key)) {
+ e.preventDefault();
+ interact({ action: 'key', key: e.key, code: e.code });
+ } else if (e.key.length === 1) {
+ e.preventDefault();
+ interact({ action: 'type', text: e.key });
+ }
+ };
+
+ const handlePaste = (e: React.ClipboardEvent) => {
+ const text = e.clipboardData.getData('text');
+ if (text) {
+ e.preventDefault();
+ interact({ action: 'type', text });
+ }
+ };
+
+ return (
+ <div className="h-screen w-screen flex flex-col bg-zinc-950 text-zinc-200">
+ <header className="flex items-center gap-3 px-4 py-2.5 border-b border-zinc-800 bg-zinc-900/60">
+ <div className="flex items-center gap-2 flex-shrink-0">
+ <span className={`w-2.5 h-2.5 rounded-full ${error ? 'bg-zinc-500' : 'bg-emerald-400 animate-pulse'}`} />
+ <span className="text-sm font-semibold">Sandbox browser</span>
+ </div>
+
+ <form
+ className="flex-1 flex items-center gap-2 px-3 py-1.5 rounded-lg bg-zinc-950 border border-zinc-800 focus-within:border-sky-500/50 min-w-0"
+ onSubmit={(e) => {
+ e.preventDefault();
+ navigate(inputUrl);
+ }}
+ >
+ <Globe size={14} className="text-zinc-500 flex-shrink-0" />
+ <input
+ value={inputUrl}
+ onChange={(e) => setInputUrl(e.target.value)}
+ onFocus={() => (urlInputFocusedRef.current = true)}
+ onBlur={() => {
+ urlInputFocusedRef.current = false;
+ setInputUrl(url);
+ }}
+ placeholder="Enter a URL to open in the sandbox"
+ className="flex-1 bg-transparent outline-none text-sm font-mono min-w-0"
+ />
+ {isBusy && <Loader2 size={14} className="animate-spin text-sky-400 flex-shrink-0" />}
+ </form>
+
+ <button
+ type="button"
+ onClick={() => (url ? navigate(url) : refresh())}
+ title="Reload page"
+ className="p-2 rounded-md text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 cursor-pointer"
+ >
+ <RefreshCw size={14} />
+ </button>
+
+ <div
+ className="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium text-emerald-300 bg-emerald-500/10 border border-emerald-500/30 flex-shrink-0"
+ title="This is the same browser your agents use. They will see the current page on their next reply."
+ >
+ <Share2 size={12} />
+ <span>Shared with your agents</span>
+ </div>
+ </header>
+
+ <div className="px-4 py-1.5 text-[11px] text-zinc-500 border-b border-zinc-900 flex items-center gap-2">
+ <MousePointerClick size={12} className={isFocused ? 'text-sky-400' : ''} />
+ <span>
+ {isFocused
+ ? 'Controlling the sandbox: clicks, scrolling, typing and paste go to the page.'
+ : 'Click the page to take control. Your agents will see wherever you leave this browser.'}
+ </span>
+ {title && <span className="ml-auto truncate text-zinc-400">{title}</span>}
+ </div>
+
+ <main className="flex-1 min-h-0 flex items-center justify-center p-4 overflow-hidden">
+ {error && !screenshot ? (
+ <div className="text-sm text-zinc-400">{error}</div>
+ ) : (
+ <div
+ ref={viewportRef}
+ tabIndex={0}
+ onClick={handleClick}
+ onWheel={handleWheel}
+ onKeyDown={handleKeyDown}
+ onPaste={handlePaste}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ className={`relative max-w-full max-h-full outline-none rounded-lg overflow-hidden border shadow-2xl cursor-pointer ${
+ isFocused ? 'border-sky-500/60 shadow-sky-500/10' : 'border-zinc-800'
+ }`}
+ style={{ aspectRatio: `${VIEWPORT_W} / ${VIEWPORT_H}`, width: `min(100%, calc((100vh - 7rem) * ${VIEWPORT_W / VIEWPORT_H}))` }}
+ >
+ {screenshot ? (
+ <img
+ ref={imageRef}
+ src={`data:image/jpeg;base64,${screenshot}`}
+ alt={title || 'Sandbox browser'}
+ draggable={false}
+ className="w-full h-full object-contain select-none bg-white"
+ />
+ ) : (
+ <div className="w-full h-full flex items-center justify-center text-zinc-500 text-sm gap-2">
+ <Loader2 size={16} className="animate-spin" /> Connecting to sandbox…
+ </div>
+ )}
+ </div>
+ )}
+ </main>
+ </div>
+ );
+};
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index c1fbc37f..ef8abd50 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -512,13 +512,13 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
</button>
)}
- {activeUrl && activeUrl !== 'about:blank' && (
+ {teamId && teamId !== 'default' && (
<a
- href={activeUrl}
+ href={`/sandbox/${encodeURIComponent(teamId)}`}
target="_blank"
- rel="noopener noreferrer"
+ rel="noopener"
className="text-zinc-400 hover:text-sky-400 p-0.5 flex-shrink-0"
- title="Open in new window"
+ title="Open the live sandbox browser in a new tab (shared with your agents)"
>
<ExternalLink size={12} />
</a>
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 8699ad90..21e77e6c 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -1,10 +1,13 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from './App';
+import { SandboxViewer } from './components/SandboxViewer';
import './styles/modern.css';
+const sandboxMatch = window.location.pathname.match(/^\/sandbox\/([^/]+)\/?$/);
+
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
- <App />
+ {sandboxMatch ? <SandboxViewer teamId={decodeURIComponent(sandboxMatch[1])} /> : <App />}
</React.StrictMode>,
);
diff --git a/src/main.rs b/src/main.rs
index 540b674d..06f17951 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -17,6 +17,10 @@ pub struct Cli {
#[arg(short, long, help = "Path to config file")]
pub config: Option<PathBuf>,
+
+ /// Path to the Kwants data directory. Available on every subcommand.
+ #[arg(long, global = true)]
+ pub data_dir: Option<PathBuf>,
}
#[derive(Subcommand, Debug)]
@@ -29,12 +33,21 @@ pub enum Commands {
#[arg(short, long, help = "Server port to listen on")]
port: Option<u16>,
- #[arg(long, help = "Path to Kwants data directory")]
- data_dir: Option<PathBuf>,
-
#[arg(long, help = "Laya router service URL")]
laya_url: Option<String>,
},
+
+ /// Print the resolved config and whether local data files exist
+ Status,
+
+ /// List kwants stored in the local database
+ Agents,
+
+ /// List teams stored in the local database
+ Teams,
+
+ /// List channels stored in the local database
+ Channels,
}
#[tokio::main]
@@ -47,11 +60,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
None => Config::load()?,
};
+ if let Some(data_dir) = cli.data_dir {
+ config.data_dir = data_dir;
+ }
+
match cli.command {
Some(Commands::Serve {
host,
port,
- data_dir,
laya_url,
}) => {
if let Some(h) = host {
@@ -60,9 +76,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
if let Some(p) = port {
config.port = p;
}
- if let Some(d) = data_dir {
- config.data_dir = d;
- }
if let Some(l) = laya_url {
config.laya_url = l;
}
@@ -92,6 +105,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
axum::serve(listener, app).await?;
}
+ Some(Commands::Status) => print_status(&config),
+ Some(Commands::Agents) => print_agents(&config).await?,
+ Some(Commands::Teams) => print_teams(&config).await?,
+ Some(Commands::Channels) => print_channels(&config).await?,
None => {
println!("⚡ Kwants: Multi-Agent AI Platform in Rust");
println!("Run `kwnt serve` to start the server, or `kwnt --help` for options.");
@@ -100,3 +117,84 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
+
+fn print_status(config: &Config) {
+ let config_path = config.data_dir.join("config.toml");
+ let db_path = config.data_dir.join("kwnt.db");
+ let db_label = if db_path.exists() {
+ let bytes = std::fs::metadata(&db_path).map(|m| m.len()).unwrap_or(0);
+ format!("{} ({bytes} bytes)", db_path.display())
+ } else {
+ "not created yet".to_string()
+ };
+ let config_label = if config_path.exists() {
+ config_path.display().to_string()
+ } else {
+ format!("{} (absent)", config_path.display())
+ };
+
+ println!("Kwants");
+ println!(" host {}", config.host);
+ println!(" port {}", config.port);
+ println!(" data dir {}", config.data_dir.display());
+ println!(" config {config_label}");
+ println!(" database {db_label}");
+ println!(" laya {}", config.laya_url);
+ println!(" fallback {}", config.default_fallback_model);
+}
+
+async fn print_agents(config: &Config) -> Result<(), Box<dyn std::error::Error>> {
+ let db = Database::init(&config.data_dir).await?;
+ let kwants = db.list_kwants().await?;
+ println!(
+ "{:<16} {:<32} {:<8} {}",
+ "NAME", "TITLE", "DRIVER", "MODEL"
+ );
+ if kwants.is_empty() {
+ println!("(no kwants)");
+ return Ok(());
+ }
+ for kwant in kwants {
+ println!(
+ "{:<16} {:<32} {:<8} {}",
+ kwant.name, kwant.title, kwant.driver_type, kwant.preferred_model
+ );
+ }
+ Ok(())
+}
+
+async fn print_teams(config: &Config) -> Result<(), Box<dyn std::error::Error>> {
+ let db = Database::init(&config.data_dir).await?;
+ let teams = db.list_teams().await?;
+ println!("{:<24} {:<8} {}", "TEAM", "MEMBERS", "WORKSPACE");
+ if teams.is_empty() {
+ println!("(no teams)");
+ return Ok(());
+ }
+ for team in teams {
+ let members = serde_json::from_str::<Vec<String>>(&team.member_kwants)
+ .map(|ids| ids.len())
+ .unwrap_or(0);
+ let workspace = team.workspace_path.unwrap_or_else(|| "-".to_string());
+ println!("{:<24} {:<8} {workspace}", team.name, members);
+ }
+ Ok(())
+}
+
+async fn print_channels(config: &Config) -> Result<(), Box<dyn std::error::Error>> {
+ let db = Database::init(&config.data_dir).await?;
+ let channels = db.list_channels().await?;
+ println!("{:<24} {:<10} {}", "CHANNEL", "ROUTING", "DESCRIPTION");
+ if channels.is_empty() {
+ println!("(no channels)");
+ return Ok(());
+ }
+ for channel in channels {
+ let description = channel.description.unwrap_or_else(|| "-".to_string());
+ println!(
+ "{:<24} {:<10} {description}",
+ channel.name, channel.routing_mode
+ );
+ }
+ Ok(())
+}
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index ed0afecc..52f247bc 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -560,6 +560,27 @@ impl BrowserController {
Ok(())
}
+ /// Re-reads the page's real URL and title, since user clicks/keys can navigate
+ /// without going through `navigate()`.
+ pub async fn sync_location(&self) -> Option<(String, String)> {
+ let res = self
+ .send_cdp_command(
+ "Runtime.evaluate",
+ json!({ "expression": "[location.href, document.title]", "returnByValue": true }),
+ )
+ .await
+ .ok()?;
+ let vals = res["result"]["value"].as_array()?;
+ let url = vals.first()?.as_str()?.to_string();
+ let title = vals.get(1).and_then(|v| v.as_str()).unwrap_or("").to_string();
+ if url.is_empty() {
+ return None;
+ }
+ *self.current_url.lock().await = Some(url.clone());
+ *self.current_title.lock().await = Some(title.clone());
+ Some((url, title))
+ }
+
pub async fn interact_click(&self, x: i64, y: i64) -> Result<String, BrowserError> {
self.send_cdp_command(
"Input.dispatchMouseEvent",
@@ -587,6 +608,7 @@ impl BrowserController {
tokio::time::sleep(Duration::from_millis(150)).await;
let _ = self.collect_and_save_captured_credentials().await;
+ let _ = self.sync_location().await;
self.capture_screenshot().await
}
@@ -599,6 +621,7 @@ impl BrowserController {
tokio::time::sleep(Duration::from_millis(150)).await;
let _ = self.collect_and_save_captured_credentials().await;
+ let _ = self.sync_location().await;
self.capture_screenshot().await
}
@@ -623,6 +646,7 @@ impl BrowserController {
tokio::time::sleep(Duration::from_millis(150)).await;
let _ = self.collect_and_save_captured_credentials().await;
+ let _ = self.sync_location().await;
self.capture_screenshot().await
}
@@ -640,6 +664,7 @@ impl BrowserController {
.await?;
tokio::time::sleep(Duration::from_millis(150)).await;
+ let _ = self.sync_location().await;
self.capture_screenshot().await
}
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index aa50b665..4a642f61 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -204,6 +204,18 @@ async fn get_configured_endpoint(db: &crate::db::Database, target_model: &str) -
}
}
+/// Truncates to at most `max` bytes without splitting a UTF-8 character.
+fn truncate_chars(text: &str, max: usize) -> &str {
+ if text.len() <= max {
+ return text;
+ }
+ let mut end = max;
+ while !text.is_char_boundary(end) {
+ end -= 1;
+ }
+ &text[..end]
+}
+
fn routing_candidates(members: &[Kwant]) -> Vec<RoutingCandidate> {
members
.iter()
@@ -277,7 +289,10 @@ fn execute_single_turn(
.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) {
+ let active_ctrl = state.browser_controllers.lock().await.get(&sandbox_target).cloned();
+ // The user may have browsed in the live viewer since the last turn; read the real location
+ let active_browser_url = if let Some(ref ctrl) = active_ctrl {
+ let _ = ctrl.sync_location().await;
ctrl.current_url.lock().await.clone()
} else {
None
@@ -294,11 +309,7 @@ fn execute_single_turn(
if let Some(ctrl) = get_or_create_browser_controller(&state, &sandbox_target).await {
if let Ok(nav) = ctrl.navigate(&target_url).await {
let page_text = ctrl.extract_content().await.unwrap_or_default();
- let preview = if page_text.len() > 3000 {
- &page_text[..3000]
- } else {
- &page_text
- };
+ let preview = truncate_chars(&page_text, 3000);
let _ = event_broadcast.send(RuntimeEvent::BrowserNavigated {
team_id: sandbox_target.clone(),
url: target_url.clone(),
@@ -321,9 +332,16 @@ 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") {
+ let (title, page_text) = match active_ctrl {
+ Some(ref ctrl) => (
+ ctrl.current_title.lock().await.clone().unwrap_or_default(),
+ ctrl.extract_content().await.unwrap_or_default(),
+ ),
+ None => (String::new(), String::new()),
+ };
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
+ "{}\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)
);
}
}
@@ -740,11 +758,7 @@ pub async fn send_chat(
if let Some(ctrl) = get_or_create_browser_controller(&state_clone, &team_clone.id).await {
if let Ok(nav) = ctrl.navigate(&target_url).await {
let page_text = ctrl.extract_content().await.unwrap_or_default();
- let preview = if page_text.len() > 3000 {
- &page_text[..3000]
- } else {
- &page_text
- };
+ let preview = truncate_chars(&page_text, 3000);
let _ = event_broadcast.send(RuntimeEvent::BrowserNavigated {
team_id: team_clone.id.clone(),
url: target_url.clone(),
@@ -1497,7 +1511,18 @@ pub async fn get_browser_screenshot(
let controller = get_or_create_browser_controller(&state, &team_id).await;
let placeholder = crate::tools::sandbox::PLACEHOLDER_PNG;
- let (b64, url) = if let Some(ctrl) = controller {
+ let (b64, url, title) = if let Some(ctrl) = controller {
+ let previous_url = ctrl.current_url.lock().await.clone();
+ if let Some((new_url, new_title)) = ctrl.sync_location().await {
+ if previous_url.as_deref() != Some(new_url.as_str()) {
+ let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {
+ team_id: team_id.clone(),
+ url: new_url,
+ title: new_title,
+ status_code: 200,
+ });
+ }
+ }
let shot = match ctrl.capture_screenshot().await {
Ok(img) => img,
Err(_) => {
@@ -1506,9 +1531,10 @@ pub async fn get_browser_screenshot(
}
};
let curr_url = ctrl.current_url.lock().await.clone().unwrap_or_default();
- (shot, curr_url)
+ let curr_title = ctrl.current_title.lock().await.clone().unwrap_or_default();
+ (shot, curr_url, curr_title)
} else {
- (placeholder.to_string(), String::new())
+ (placeholder.to_string(), String::new(), String::new())
};
let timestamp = chrono::Utc::now().to_rfc3339();
@@ -1516,6 +1542,7 @@ pub async fn get_browser_screenshot(
Ok(Json(json!({
"team_id": team_id,
"url": url,
+ "title": title,
"image_base64": b64,
"screenshot": b64,
"format": "jpeg",