Skip to main content

agentmux_srv/server/
browser_close_route.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! `POST /api/v1/ui/browser/close`: backs Browser's `close`. An agent closes a browser tab it drives, when
4//! its job is done. The tab goes through the same check every other agent browser call does
5//! (`target_block_id`: it must still be the agent's, not taken over, paused or another agent's), then the
6//! shared close path, where the user has a few seconds to keep it. Only that tab closes: the pane's other
7//! tabs, the person's or another agent's, stay, and the pane goes with it only when it was the last tab.
8
9use axum::extract::State;
10use axum::http::StatusCode;
11use axum::response::IntoResponse;
12use axum::Json;
13
14use crate::server::ui_handlers::{err_response, target_block_id};
15use crate::server::AppState;
16
17pub(crate) async fn handle_ui_browser_close(
18    State(state): State<AppState>,
19    caller: Option<axum::Extension<crate::server::caller::Caller>>,
20    Json(req): Json<agentmux_common::api_types::UiBrowserCloseRequest>,
21) -> impl IntoResponse {
22    // Without a pane, the check would resolve to the caller's own, and closing that ends the caller.
23    let Some(pane) = req.pane.as_deref().map(str::trim).filter(|p| !p.is_empty()) else {
24        return err_response(StatusCode::BAD_REQUEST, "Browser close needs pane: the id Browser open gave you".to_string());
25    };
26    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, Some(pane)) {
27        Ok(b) => b,
28        Err((StatusCode::FORBIDDEN, e)) => {
29            return err_response(StatusCode::FORBIDDEN, format!("{e}. Browser close closes only tabs you opened with Browser open; for this one, ask the user to close it"));
30        }
31        Err((code, e)) => return err_response(code, e),
32    };
33    let reason = "the agent is done with its browser tab";
34    let (code, body) = crate::server::app_api::pane::close_pane_as(&state, &req.auth.agent_id, &block_id, Some(reason), "Browser close").await;
35    (code, Json(body)).into_response()
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use crate::server::tests::test_state;
42    use agentmux_common::api_types::{UiAutomationAuth, UiBrowserCloseRequest};
43    use agentmux_common::ipc::{Command, Event};
44
45    async fn apply(state: &AppState, cmd: Command) -> Vec<Event> {
46        let evs = crate::server::service::dispatch_to_reducer(state, cmd).await;
47        for ev in &evs {
48            crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).unwrap();
49        }
50        evs
51    }
52
53    /// Two blocks in one new tab: `(tab, first, second)`.
54    async fn two_blocks(state: &AppState) -> (String, String, String) {
55        let ws = apply(state, Command::CreateWorkspace { name: "w".into() }).await;
56        let ws = ws.iter().find_map(|e| if let Event::WorkspaceCreated { workspace_id, .. } = e { Some(workspace_id.clone()) } else { None }).unwrap();
57        let tab = apply(state, Command::CreateTab { workspace_id: ws, name: "t".into() }).await;
58        let tab = tab.iter().find_map(|e| if let Event::TabCreated { tab_id, .. } = e { Some(tab_id.clone()) } else { None }).unwrap();
59        let mut ids = Vec::new();
60        for _ in 0..2 {
61            let evs = apply(state, Command::CreateBlock { tab_id: tab.clone(), meta: serde_json::json!({ "view": "term" }) }).await;
62            ids.push(evs.iter().find_map(|e| if let Event::BlockCreated { block_id, .. } = e { Some(block_id.clone()) } else { None }).unwrap());
63        }
64        (tab, ids.remove(0), ids.remove(0))
65    }
66
67    fn auth(state: &AppState, agent_id: &str) -> UiAutomationAuth {
68        let key = state.mstore.agent_jekt_key_ensure(agent_id).unwrap();
69        let ts_secs = agentmux_common::time::now_secs();
70        let sig = agentmux_common::jekt_sign::sign_jekt(&key, "ui-automation-identity", agent_id, "__srv__", ts_secs, "");
71        UiAutomationAuth { agent_id: agent_id.to_string(), ts_secs, sig }
72    }
73
74    async fn status_of(state: &AppState, req: UiBrowserCloseRequest) -> StatusCode {
75        handle_ui_browser_close(State(state.clone()), None, Json(req)).await.into_response().status()
76    }
77
78    #[tokio::test]
79    async fn close_needs_a_pane_and_only_closes_a_browser_pane_the_agent_drives() {
80        let state = test_state();
81        let (tab, own, other) = two_blocks(&state).await;
82        let agent = format!("close-browser-{}", uuid::Uuid::new_v4());
83        state.reactive_handler.register_agent(&agent, &own, Some(&tab)).unwrap();
84        let ask = |pane: Option<&str>| UiBrowserCloseRequest { auth: auth(&state, &agent), pane: pane.map(str::to_string) };
85
86        assert_eq!(status_of(&state, ask(None)).await, StatusCode::BAD_REQUEST, "no pane would mean the caller's own");
87        assert_eq!(status_of(&state, ask(Some("  "))).await, StatusCode::BAD_REQUEST);
88        // The agent's own pane, and a pane that is no browser pane it opened, are refused, not scheduled.
89        for pane in [own.as_str(), other.as_str(), "no-such-pane"] {
90            let code = status_of(&state, ask(Some(pane))).await;
91            assert!(code == StatusCode::FORBIDDEN || code == StatusCode::NOT_FOUND, "{pane}: {code}");
92        }
93        let s = state.srv_state.lock().await;
94        assert!(s.blocks.contains_key(&own) && s.blocks.contains_key(&other), "nothing was closed");
95    }
96
97    /// A browser block in `tab`, opened by `owner` (recorded as Browser open does).
98    async fn browser_block(state: &AppState, tab: &str, owner: &str) -> String {
99        let meta = serde_json::json!({ "view": "browser", crate::server::browser_owner::OWNER_META_KEY: owner });
100        let evs = apply(state, Command::CreateBlock { tab_id: tab.to_string(), meta }).await;
101        let id = evs.iter().find_map(|e| if let Event::BlockCreated { block_id, .. } = e { Some(block_id.clone()) } else { None }).unwrap();
102        crate::server::browser_owner::record(&id, owner);
103        id
104    }
105
106    /// One pane holding `stack` as tabs, the first showing.
107    async fn stack_in_one_pane(state: &AppState, tab: &str, stack: &[&str]) {
108        let tree = agentmux_common::LayoutNode {
109            id: "leaf".into(),
110            data: Some(agentmux_common::LayoutNodeData {
111                block_id: stack[0].to_string(),
112                block_stack: stack.iter().map(|b| b.to_string()).collect(),
113                active_block_id: stack[0].to_string(),
114                ..Default::default()
115            }),
116            ..Default::default()
117        };
118        apply(state, Command::LayoutSetTree { tab_id: tab.to_string(), new_tree: Some(tree), correlation_id: String::new(), slices: None }).await;
119    }
120
121    async fn close_and_settle(state: &AppState, agent: &str, pane: &str) -> serde_json::Value {
122        let resp = handle_ui_browser_close(State(state.clone()), None, Json(UiBrowserCloseRequest { auth: auth(state, agent), pane: Some(pane.to_string()) }))
123            .await
124            .into_response();
125        assert_eq!(resp.status(), StatusCode::ACCEPTED);
126        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
127        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
128        let id = body["request_id"].as_str().unwrap().to_string();
129        crate::sagas::pending_shutdown::expire_now(&id);
130        crate::sagas::pending_shutdown::settled(&id).await;
131        body
132    }
133
134    #[tokio::test]
135    async fn an_agents_tab_closes_alone_when_the_pane_holds_a_tab_that_is_not_its_own() {
136        let state = test_state();
137        let (tab, caller, persons) = two_blocks(&state).await;
138        let agent = format!("close-tab-{}", uuid::Uuid::new_v4());
139        state.reactive_handler.register_agent(&agent, &caller, Some(&tab)).unwrap();
140        let mine = browser_block(&state, &tab, &agent).await;
141        stack_in_one_pane(&state, &tab, &[&mine, &persons]).await;
142
143        let body = close_and_settle(&state, &agent, &mine).await;
144
145        assert_eq!(body["tab"], mine.as_str(), "the answer names the tab");
146        assert_eq!(body["pane_closes"], false, "the person's tab keeps the pane");
147        let s = state.srv_state.lock().await;
148        assert!(!s.blocks.contains_key(&mine), "its own tab closed");
149        assert!(s.blocks.contains_key(&persons), "the other tab is untouched");
150        assert!(s.tabs[&tab].rootnode.is_some(), "the pane stays");
151    }
152
153    #[tokio::test]
154    async fn the_last_tab_takes_its_pane_with_it() {
155        let state = test_state();
156        let (tab, caller, _) = two_blocks(&state).await;
157        let agent = format!("close-last-{}", uuid::Uuid::new_v4());
158        state.reactive_handler.register_agent(&agent, &caller, Some(&tab)).unwrap();
159        let mine = browser_block(&state, &tab, &agent).await;
160        stack_in_one_pane(&state, &tab, &[&mine]).await;
161
162        let body = close_and_settle(&state, &agent, &mine).await;
163
164        assert_eq!(body["pane_closes"], true);
165        let s = state.srv_state.lock().await;
166        assert!(!s.blocks.contains_key(&mine));
167        assert!(s.tabs[&tab].rootnode.is_none(), "the pane went with its last tab");
168    }
169
170    #[tokio::test]
171    async fn a_tab_another_agent_opened_is_refused_and_stays() {
172        let state = test_state();
173        let (tab, caller, _) = two_blocks(&state).await;
174        let agent = format!("close-mine-{}", uuid::Uuid::new_v4());
175        state.reactive_handler.register_agent(&agent, &caller, Some(&tab)).unwrap();
176        let mine = browser_block(&state, &tab, &agent).await;
177        let theirs = browser_block(&state, &tab, "somebody-else").await;
178        stack_in_one_pane(&state, &tab, &[&mine, &theirs]).await;
179
180        let resp = handle_ui_browser_close(State(state.clone()), None, Json(UiBrowserCloseRequest { auth: auth(&state, &agent), pane: Some(theirs.clone()) }))
181            .await
182            .into_response();
183        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
184        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
185        assert!(String::from_utf8_lossy(&bytes).contains("not a browser pane you own"));
186        assert!(state.srv_state.lock().await.blocks.contains_key(&theirs));
187    }
188}