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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Browser panel: page_title on bot browser open steps (server half) (#588)
Oleksandr Ivanchenko468cae0bdda3
diff --git a/docs/live-activity.md b/docs/live-activity.mdindex 85ce78f0..b3dfe235 100644--- a/docs/live-activity.md+++ b/docs/live-activity.md@@ -50,6 +50,7 @@ turn's list (keyed by `turn_id`); append it if it's new.| `ref_id` | optional. For `approval` it is the approval ticket, and for `human_step` it is the human-step id. Use it to link to the card || `started_at`, `ended_at` | RFC 3339 with milliseconds. `ended_at` is missing while the step is open || `duration_ms` | set once the step ends |+| `page_title` | optional (0.9.8). On a `tool` step whose tool opens a page in the bot's browser (`browser_open`, `browser_navigate`, `navigate`, `open_url`, under any `mcp__<server>__` prefix), once it ends `ok`: the title of the page it landed on, redacted, ≤160 chars. Missing when the page had no title, and on replies saved before 0.9.8 |**Thinking text streams live** as the existing `ThinkingDelta` event (`data` is a string chunk,scoped to the turn). The `activity` step of kind `thinking` only marks start (`running`) and enddiff --git a/src/drivers/activity.rs b/src/drivers/activity.rsindex ef2c7a8a..9cbb7a73 100644--- a/src/drivers/activity.rs+++ b/src/drivers/activity.rs@@ -53,6 +53,11 @@ pub struct Step {pub ended_at: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub duration_ms: Option<u64>,+ /// The title of the page a bot browser open/navigate step landed on (see [`opens_page`]),+ /// redacted and cut to [`MAX_TITLE`], once the step ends. Missing for every other step, and+ /// on replies saved before 0.9.8.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub page_title: Option<String>,#[serde(skip)]clock: Option<Instant>,}@@ -128,6 +133,7 @@ impl ActivityLog {started_at: now(),ended_at: None,duration_ms: None,+ page_title: None,clock: Some(Instant::now()),});Some(self.steps.len() - 1)@@ -198,6 +204,13 @@ impl ActivityLog {if let Some(Some(why)) = failed {self.steps[i].detail = Some(cut(&self.redact(why), MAX_DETAIL));}+ if failed.is_none() && self.steps[i].tool.as_deref().is_some_and(opens_page) {+ self.steps[i].page_title = result["title"]+ .as_str()+ .map(str::trim)+ .filter(|t| !t.is_empty())+ .map(|t| cut(&self.redact(t), MAX_TITLE));+ }changed.push(self.end(i, if failed.is_some() { "failed" } else { "ok" }));}}@@ -497,6 +510,40 @@ const TOKEN_PREFIXES: [&str; 12] = [/// Masks secrets in text shown to people: the exact `secrets`, then credentials written as/// `key=value`, `Bearer …`, URL passwords and provider-looking tokens.+/// Own names (after any `mcp__<server>__` prefix) of the bot browser tools that open or move to a+/// page: kwnt's `browser_open` and `browser_navigate`, and the `navigate` / `open_url` of browser+/// tool servers. The same list the chat's page trail counts (`frontend/src/browserPages.ts`).+/// WebFetch isn't one: it never touches the bot's browser.+pub const PAGE_OPEN_TOOLS: [&str; 4] = ["browser_open", "browser_navigate", "navigate", "open_url"];++/// Whether a tool (`browser_open`, `mcp__kwnt__browser_open`, …) opens a page in the bot's browser.+pub fn opens_page(tool: &str) -> bool {+ PAGE_OPEN_TOOLS.contains(&tool.rsplit("__").next().unwrap_or(tool))+}++/// The page title in the text a page-opening browser tool answered with: the `title` of the page+/// JSON it returns (kwnt's `browser_open`), or of the page after a note ("…\n\nThe page now:\n{…}").+/// Drivers put it on the finished tool call's result as `title`, for [`Step::page_title`].+pub fn page_title_in(text: &str) -> Option<String> {+ let text = text.trim();+ let page = serde_json::from_str::<Value>(text).ok().or_else(|| {+ let at = text.rfind("\n{")?;+ serde_json::from_str::<Value>(&text[at + 1..]).ok()+ })?;+ page["title"].as_str().map(str::trim).filter(|t| !t.is_empty()).map(str::to_string)+}++/// The finished tool call's result with the page title on it (`title`), when the tool opens a+/// page and its answer (`text`) names one. Other results pass as they are.+pub fn with_page_title(mut result: Value, tool: &str, text: &str) -> Value {+ if opens_page(tool) && failed_reason(&result).is_none() {+ if let (Some(title), Some(obj)) = (page_title_in(text), result.as_object_mut()) {+ obj.insert("title".into(), Value::String(title));+ }+ }+ result+}+/// A finished tool call's result: `None` when it went fine, `Some(why)` when its step is/// `failed` (error, failed, denied or cancelled), with the reason it gave, trimmed, if any. The/// one rule for "a tool failed", shared with the chat's failure line (`server::tool_failures`).@@ -957,4 +1004,82 @@ mod tests {assert_eq!(redact(text, &[]), want);}}++ fn opened(id: &str, result: Value) -> RuntimeEvent {+ RuntimeEvent::ToolCallCompleted { id: id.into(), result }+ }++ /// 0.9.8 browser panel: a bot browser open/navigate step keeps the title of the page it+ /// landed on, under any MCP prefix, so a saved reply's page trail shows titles after a reload.+ #[test]+ fn a_browser_open_step_keeps_the_page_title() {+ for tool in ["browser_open", "mcp__kwnt__browser_open", "mcp__kwnt_tools__browser_open", "browser_navigate", "mcp__playwright__navigate", "open_url"] {+ let mut log = ActivityLog::default();+ log.observe(&pending("b", tool, json!({"url": "http://roastco.example.com/"})));+ assert!(log.steps()[0].page_title.is_none(), "no title while it runs");+ let ended = log.observe(&opened("b", json!({"status": "ok", "title": " RoastCo · Shop "})));+ assert_eq!(ended[0].page_title.as_deref(), Some("RoastCo · Shop"), "{tool}");+ assert_eq!(log.to_json()["steps"][0]["page_title"], "RoastCo · Shop", "{tool}: saved on the reply");+ }+ }++ #[test]+ fn other_steps_get_no_page_title() {+ let mut log = ActivityLog::default();+ // WebFetch never touches the bot's browser; a GitHub issue's title isn't a page+ for (id, tool) in [("1", "WebFetch"), ("2", "mcp__github__create_issue"), ("3", "mcp__kwnt__browser_page"), ("4", "Bash")] {+ log.observe(&pending(id, tool, json!({"url": "https://example.com"})));+ let ended = log.observe(&opened(id, json!({"status": "ok", "title": "Some title"})));+ assert_eq!(ended[0].page_title, None, "{tool}");+ }+ // An open that failed, or a page with no title (or a blank one), has none either+ for (id, result) in [+ ("5", json!({"status": "error", "error": "net::ERR_NAME_NOT_RESOLVED", "title": "x"})),+ ("6", json!({"status": "ok"})),+ ("7", json!({"status": "ok", "title": " "})),+ ("8", json!({"status": "ok", "title": 42})),+ ] {+ log.observe(&pending(id, "mcp__kwnt__browser_open", json!({"url": "https://example.com"})));+ assert_eq!(log.observe(&opened(id, result))[0].page_title, None, "step {id}");+ }+ // Old rows and other steps carry no `page_title` key at all+ let saved = log.to_json();+ assert!(saved["steps"].as_array().unwrap().iter().all(|s| s.get("page_title").is_none()), "{saved}");+ }++ #[test]+ fn a_page_title_is_redacted_and_cut() {+ let mut log = ActivityLog::with_secrets(vec!["hunter2-mcp-value".into()]);+ log.observe(&pending("b", "mcp__kwnt__browser_open", json!({"url": "https://example.com"})));+ let title = "Reset for hunter2-mcp-value with ghp_abcdefghijklmnopqrstuvwxyz0123";+ let ended = log.observe(&opened("b", json!({"status": "ok", "title": title})));+ let shown = ended[0].page_title.clone().unwrap();+ assert!(!shown.contains("hunter2-mcp-value") && !shown.contains("ghp_abc"), "{shown}");+ assert!(shown.starts_with("Reset for "), "{shown}");++ log.observe(&pending("c", "browser_navigate", json!({"url": "https://example.com"})));+ let ended = log.observe(&opened("c", json!({"status": "ok", "title": "é".repeat(MAX_TITLE + 40)})));+ let cut = ended[0].page_title.clone().unwrap();+ assert_eq!(cut.chars().count(), MAX_TITLE);+ assert!(cut.ends_with('…'));+ }++ /// The drivers find the title in the page JSON `browser_open` answers with.+ #[test]+ fn drivers_read_the_title_from_the_page_the_tool_answered_with() {+ let page = json!({"url": "http://roastco.example.com/", "title": "RoastCo · Shop", "text": "Prices"}).to_string();+ assert_eq!(page_title_in(&page).as_deref(), Some("RoastCo · Shop"));+ // A CAPTCHA note, then the page the person left+ let noted = format!("Solved by the person.\n\nThe page now:\n{page}");+ assert_eq!(page_title_in(¬ed).as_deref(), Some("RoastCo · Shop"));+ for text in ["", "Browser error (HTTP 502).", r#"{"title": ""}"#, r#"{"url": "x"}"#, "[1,2]", "{\"title\": \"cut off"] {+ assert_eq!(page_title_in(text), None, "{text:?}");+ }+ let ok = with_page_title(json!({"status": "ok"}), "mcp__kwnt__browser_open", &page);+ assert_eq!(ok, json!({"status": "ok", "title": "RoastCo · Shop"}));+ // Not a page-opening tool, or the call failed: the result passes as it is+ assert_eq!(with_page_title(json!({"status": "ok"}), "WebFetch", &page), json!({"status": "ok"}));+ let failed = json!({"status": "error", "error": "x"});+ assert_eq!(with_page_title(failed.clone(), "browser_open", &page), failed);+ }}diff --git a/src/drivers/api.rs b/src/drivers/api.rsindex f6e74439..a70753e5 100644--- a/src/drivers/api.rs+++ b/src/drivers/api.rs@@ -1200,10 +1200,14 @@ impl ApiDriver {let _ = event_tx.send(RuntimeEvent::ToolCallCompleted {id: id.to_string(),- result: json!({- "status": outcome.status,- "content": crate::mcp::truncate_text(&outcome.text, crate::mcp::RECORD_RESULT_MAX_CHARS),- }),+ result: super::activity::with_page_title(+ json!({+ "status": outcome.status,+ "content": crate::mcp::truncate_text(&outcome.text, crate::mcp::RECORD_RESULT_MAX_CHARS),+ }),+ name,+ &outcome.text,+ ),}).await;messages.push(json!({"role": "tool", "tool_call_id": id, "content": outcome.text}));diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex ce702e5f..cc3ef168 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -1089,6 +1089,9 @@ struct ClaudeStream {running: std::collections::HashSet<String>,/// Tool calls already reported, so a repeated message isn't reported twice.seen: std::collections::HashSet<String>,+ /// Running tool calls that open a page in the bot's browser, by `tool_use` id: their tool+ /// name, so the page title in their answer reaches the activity step (`page_title`).+ page_opens: std::collections::HashMap<String, String>,result_line: Option<String>,/// Output that isn't JSON (an older claude without `stream-json`).plain: String,@@ -1208,6 +1211,9 @@ impl ClaudeStream {_ => b["input"].clone(),};let name = b["name"].as_str().unwrap_or("tool").to_string();+ if super::activity::opens_page(&name) {+ self.page_opens.insert(id.to_string(), name.clone());+ }events.push(RuntimeEvent::ToolCallPending { id: id.to_string(), name, args });}}@@ -1222,6 +1228,10 @@ impl ClaudeStream {} else {serde_json::json!({ "status": "ok" })};+ let result = match self.page_opens.remove(id) {+ Some(name) => super::activity::with_page_title(result, &name, &tool_result_text(&b["content"])),+ None => result,+ };events.push(RuntimeEvent::ToolCallCompleted { id: id.to_string(), result });}}@@ -2257,6 +2267,32 @@ endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\n}}+ /// 0.9.8 browser panel: a `browser_open` that went fine carries the page's title to its+ /// activity step; other tools don't, and a failed open doesn't.+ #[test]+ fn claude_stream_passes_the_opened_pages_title_on() {+ let t0 = Instant::now();+ let mut s = ClaudeStream::default();+ let page = serde_json::json!({"url": "http://roastco.example.com/", "title": "RoastCo · Shop", "status": "navigated"}).to_string();+ let call = |id: &str, name: &str| {+ serde_json::json!({"type":"assistant","message":{"content":[{"type":"tool_use","id":id,"name":name,"input":{"url":"http://roastco.example.com/"}}]}}).to_string()+ };+ let answer = |id: &str, is_error: bool| {+ serde_json::json!({"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":id,"is_error":is_error,"content":[{"type":"text","text":page}]}]}}).to_string()+ };+ let result_of = |events: Vec<RuntimeEvent>| match events.as_slice() {+ [RuntimeEvent::ToolCallCompleted { result, .. }] => result.clone(),+ other => panic!("{other:?}"),+ };+ s.line(&call("o", "mcp__kwnt_tools__browser_open"), t0);+ assert_eq!(result_of(s.line(&answer("o", false), t0)), serde_json::json!({"status": "ok", "title": "RoastCo · Shop"}));+ s.line(&call("f", "WebFetch"), t0);+ assert_eq!(result_of(s.line(&answer("f", false), t0)), serde_json::json!({"status": "ok"}));+ s.line(&call("e", "mcp__kwnt_tools__browser_open"), t0);+ assert!(result_of(s.line(&answer("e", true), t0)).get("title").is_none());+ assert!(s.page_opens.is_empty(), "nothing left over once the calls end");+ }+#[test]fn claude_stream_progress_is_sent_at_most_once_a_second() {let t0 = Instant::now();diff --git a/src/drivers/codex_json.rs b/src/drivers/codex_json.rsindex 16ebc02a..faf1ff3f 100644--- a/src/drivers/codex_json.rs+++ b/src/drivers/codex_json.rs@@ -42,6 +42,14 @@ fn as_tool(item: &Value) -> Option<(String, Value)> {})}+/// The text an `mcp_tool_call` item's tool answered with (its `result.content` text parts).+fn mcp_result_text(item: &Value) -> String {+ match item["result"]["content"].as_array() {+ Some(parts) => parts.iter().filter_map(|p| p["text"].as_str()).collect::<Vec<_>>().join("\n"),+ None => String::new(),+ }+}+/// How a finished item went: `ok`, or `error` with why.fn outcome(item: &Value) -> Value {let status = item["status"].as_str().unwrap_or_default();@@ -116,9 +124,14 @@ impl CodexStream {self.had_effects |= item["type"] != "todo_list";// a file change is often only reported once it's doneif !self.running.remove(&id) {- events.push(RuntimeEvent::ToolCallPending { id: id.clone(), name, args });+ events.push(RuntimeEvent::ToolCallPending { id: id.clone(), name: name.clone(), args });}- events.push(RuntimeEvent::ToolCallCompleted { id, result: outcome(item) });+ let result = if super::activity::opens_page(&name) {+ super::activity::with_page_title(outcome(item), &name, &mcp_result_text(item))+ } else {+ outcome(item)+ };+ events.push(RuntimeEvent::ToolCallCompleted { id, result });}}}@@ -171,6 +184,27 @@ mod tests {/// codex with no sign-in: retries, a fallback notice, then the error that ends the turn.const SIGNED_OUT: &str = include_str!("fixtures/codex_exec_json_401.jsonl");+ /// 0.9.8 browser panel: kwnt's `browser_open` run through codex carries the page title on.+ #[test]+ fn codex_json_passes_the_opened_pages_title_on() {+ let page = json!({"url": "http://roastco.example.com/", "title": "RoastCo · Shop"}).to_string();+ let item = |id: &str, tool: &str| {+ json!({"type":"item.completed","item":{"id":id,"type":"mcp_tool_call","server":"kwnt_tools","tool":tool,"arguments":{"url":"http://roastco.example.com/"},+ "result":{"content":[{"type":"text","text":page}],"structured_content":null},"error":null,"status":"completed"}})+ .to_string()+ };+ let mut s = CodexStream::default();+ let titles: Vec<Option<String>> = [item("a", "browser_open"), item("b", "browser_page")]+ .iter()+ .flat_map(|l| s.line(l))+ .filter_map(|e| match e {+ RuntimeEvent::ToolCallCompleted { result, .. } => Some(result["title"].as_str().map(str::to_string)),+ _ => None,+ })+ .collect();+ assert_eq!(titles, [Some("RoastCo · Shop".to_string()), None]);+ }+#[test]fn codex_json_reports_reasoning_and_each_tool_run() {let (s, kinds) = run(WORKING);diff --git a/src/server/activity.rs b/src/server/activity.rsindex cecea3dd..24d18e6e 100644--- a/src/server/activity.rs+++ b/src/server/activity.rs@@ -222,6 +222,30 @@ mod tests {assert_eq!(with_activity(None, Some(json!({"steps": []}))).unwrap()["activity"]["steps"], json!([]));}+ /// 0.9.8 browser panel: the page title of a bot browser open goes out live, is listed on+ /// `GET /api/turns` and is kept on the saved reply; a reply saved before it reads as it did.+ #[test]+ fn a_browser_steps_page_title_streams_and_is_saved() {+ let (tx, mut rx) = broadcast::channel(16);+ let tag = TurnTag { turn_id: "turn-page-title".into(), kwant_id: "k".into(), context_id: "c".into(), thread_id: None };+ let turn = TurnActivity::start(tx, tag);+ turn.observe(&RuntimeEvent::ToolCallPending { id: "1".into(), name: "mcp__kwnt_tools__browser_open".into(), args: json!({"url": "http://roastco.example.com/"}) });+ turn.observe(&RuntimeEvent::ToolCallCompleted { id: "1".into(), result: json!({"status": "ok", "title": "RoastCo · Shop"}) });+ let wire: Vec<Value> = std::iter::from_fn(|| rx.try_recv().ok()).map(|e| e.to_wire()).collect();+ assert_eq!(wire.last().unwrap()["data"]["step"]["page_title"], "RoastCo · Shop");+ let saved = turn.finish().unwrap();+ let meta = with_activity(Some(json!({"model": "m"})), Some(saved)).unwrap();+ // what the reply's meta holds in the DB and what /api sends back after a reload+ let reloaded: Value = serde_json::from_str(&meta.to_string()).unwrap();+ assert_eq!(reloaded["activity"]["steps"][0]["page_title"], "RoastCo · Shop");+ assert_eq!(reloaded["activity"]["steps"][0]["detail"], "http://roastco.example.com/");+ drop(turn);+ // An old row, saved before the field existed, still reads the same+ let old = json!({"activity": {"steps": [{"id": "s1", "kind": "tool", "status": "ok", "title": "Opening example.com", "tool": "browser_open", "started_at": "2026-11-01T10:00:00.000Z"}]}});+ assert_eq!(with_activity(Some(old.clone()), None), Some(old.clone()));+ assert!(old["activity"]["steps"][0].get("page_title").is_none());+ }+/// Ticket 4: a page that loads mid-turn gets the open step from `GET /api/turns`.#[test]fn listed_turn_carries_its_steps_so_far() {