Skip to main content

agentmux_mcp/tools/
browser_sessions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Browser` actions `list` and `show`: the browser panes an agent holds, and turning a background session into a
5//! pane the person sees (docs/specs/SPEC_BACKGROUND_BROWSER_SESSIONS_2026_11_28.md §6).
6
7use agentmux_common::browser_control_types::{UiBrowserHideRequest, UiBrowserListRequest, UiBrowserShowRequest};
8use agentmux_common::shown_url::shown_url;
9
10use super::*;
11
12/// A pane's line in `list`.
13fn line(p: &Value) -> String {
14    let get = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or("");
15    let kind = match (p.get("background").and_then(Value::as_bool), p.get("floating").and_then(Value::as_bool)) {
16        (Some(true), _) => "background session",
17        (_, Some(true)) => "floating pane",
18        _ => "pane in a tab",
19    };
20    let title = if get("title").is_empty() { String::new() } else { format!(" {:?}", get("title")) };
21    format!("- {:?}: {kind}, at {:?}{title}", get("pane"), shown_url(get("url")))
22}
23
24/// The answer to `list`: every browser pane the caller opened, and how many background sessions it holds of its most.
25fn list_text(data: &Value) -> String {
26    let panes = data.get("panes").and_then(Value::as_array).cloned().unwrap_or_default();
27    if panes.is_empty() {
28        return "You have no browser panes open.".to_string();
29    }
30    let (held, most) = (data.get("background").and_then(Value::as_u64).unwrap_or(0), data.get("background_limit").and_then(Value::as_u64).unwrap_or(0));
31    let lines = panes.iter().map(line).collect::<Vec<_>>().join("\n");
32    format!("Your browser panes ({held} of your {most} background sessions in use):\n{lines}")
33}
34
35pub(super) async fn run_list(_arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
36    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
37    require_agent_env(local_url, auth_key, block_id)?;
38    let auth = sign_ui_automation_auth()?;
39    let url = format!("{}/api/v1/ui/browser/list", local_url.trim_end_matches('/'));
40    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&UiBrowserListRequest { auth }).send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
41    if !resp.status().is_success() {
42        let status = resp.status();
43        let text = resp.text().await.unwrap_or_default();
44        anyhow::bail!("Browser list failed: HTTP {status} — {text}");
45    }
46    let body: Value = resp.json().await.map_err(|e| anyhow::anyhow!("Browser list: bad response: {e}"))?;
47    Ok(list_text(body.get("data").unwrap_or(&Value::Null)))
48}
49
50pub(super) async fn run_show(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
51    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
52    require_agent_env(local_url, auth_key, block_id)?;
53    let auth = sign_ui_automation_auth()?;
54    let pane = pane_arg(arguments).ok_or_else(|| anyhow::anyhow!("Browser show needs pane: the id of a background session (Browser list names them)"))?;
55    cx.post("/api/v1/ui/browser/show", &UiBrowserShowRequest { auth, pane: pane.clone() }, "Browser show").await?;
56    Ok(format!(
57        "{pane:?} is a floating pane the person sees now, on the right of their screen. It counts as one of your floating panes: \
58         Pane move, resize, place and dock work on it."
59    ))
60}
61
62pub(super) async fn run_hide(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
63    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
64    require_agent_env(local_url, auth_key, block_id)?;
65    let auth = sign_ui_automation_auth()?;
66    let pane = pane_arg(arguments).ok_or_else(|| anyhow::anyhow!("Browser hide needs pane: the id of a floating browser pane you opened (Browser list names them)"))?;
67    cx.post("/api/v1/ui/browser/hide", &UiBrowserHideRequest { auth, pane: pane.clone() }, "Browser hide").await?;
68    Ok(format!("{pane:?} is a background session again: no screen shows it, and it counts against your two (and the machine's six). Browser show brings it back."))
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74    use serde_json::json;
75
76    #[test]
77    fn the_list_names_each_pane_and_how_many_sessions_are_in_use() {
78        let data = json!({
79            "panes": [
80                { "pane": "b1", "url": "https://example.com/a", "title": "A", "floating": false, "background": false },
81                { "pane": "b2", "url": "https://example.com/b", "title": "", "floating": true, "background": true },
82            ],
83            "background": 1,
84            "background_limit": 2,
85        });
86        let text = list_text(&data);
87        assert!(text.contains("1 of your 2 background sessions"), "{text}");
88        assert!(text.contains("\"b1\": pane in a tab") && text.contains("\"b2\": background session"), "{text}");
89        assert!(text.contains("\"A\""), "{text}");
90        assert_eq!(list_text(&json!({ "panes": [] })), "You have no browser panes open.");
91    }
92}