Skip to main content

agentmux_srv/server/
browser_retake.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/ui/browser/retake` and `/handoff_status`: an agent drives again a pane the person took over once they
5//! gave it back, and asks what became of a hand-off whose call it lost
6//! (docs/specs/SPEC_BROWSER_RETAKE_AND_COMMANDEER_2026_11_04.md ยง1). Neither goes through `target_block_id`: a retake is
7//! asked for a pane the agent no longer owns, so the rule is `browser_owner::may_retake`, and the caller's identity is
8//! checked the same way every agent browser call checks it. The person's Give back arrives from the host
9//! (`give_back`, called by `handle_host_browser_attention`), never from a client.
10
11use axum::extract::State;
12use axum::http::StatusCode;
13use axum::response::IntoResponse;
14use axum::Json;
15use serde_json::json;
16
17use crate::server::browser_owner;
18use crate::server::ui_handlers::{err_response, verified_block_id};
19use crate::server::AppState;
20
21fn trimmed(v: &Option<String>) -> Option<&str> {
22    v.as_deref().map(str::trim).filter(|s| !s.is_empty())
23}
24
25pub(crate) async fn handle_ui_browser_retake(
26    State(state): State<AppState>,
27    caller: Option<axum::Extension<crate::server::caller::Caller>>,
28    Json(req): Json<agentmux_common::api_types::UiBrowserRetakeRequest>,
29) -> impl IntoResponse {
30    if let Err(e) = verified_block_id(&state, caller.as_deref(), &req.auth) {
31        return err_response(StatusCode::UNAUTHORIZED, e);
32    }
33    let agent = req.auth.agent_id.as_str();
34    let Some(pane) = trimmed(&req.pane) else {
35        return err_response(StatusCode::BAD_REQUEST, "Browser retake needs pane: the id of the pane the user took over".to_string());
36    };
37    let block = match state.mstore.get::<crate::backend::obj::Block>(pane) {
38        Ok(Some(b)) => b,
39        Ok(None) => return err_response(StatusCode::NOT_FOUND, format!("no pane {pane:?} (it may have been closed)")),
40        Err(e) => return err_response(StatusCode::INTERNAL_SERVER_ERROR, format!("load pane {pane:?}: {e}")),
41    };
42    if block.meta.get("view").and_then(|v| v.as_str()) != Some("browser") {
43        return err_response(StatusCode::BAD_REQUEST, format!("pane {pane:?} is not a browser pane"));
44    }
45    match browser_owner::owner_of(pane) {
46        Some(owner) if owner.eq_ignore_ascii_case(agent) => {
47            return (StatusCode::OK, Json(json!({ "ok": true, "data": { "pane": pane, "already": true } }))).into_response();
48        }
49        Some(_) => {
50            return err_response(
51                StatusCode::FORBIDDEN,
52                format!("pane {pane:?} is a browser pane another agent drives; you can retake only a pane you lost to the user"),
53            );
54        }
55        None => {}
56    }
57    // The person's Give back is not the only way back: a pane they have left alone for a minute is the agent's again.
58    // Asked only when that is what decides, so a pane given back or never lost costs no host call.
59    let since_input = if browser_owner::takeover_in_use(&block, pane, agent).is_some() {
60        since_person_input(&state, pane).await
61    } else {
62        None
63    };
64    if let Err(e) = browser_owner::may_retake(&block, pane, agent, since_input) {
65        return err_response(StatusCode::CONFLICT, e);
66    }
67    // The person's Take over ended the pane's site limit; the pane's header still names it, so the limit comes back
68    // with the agent, before it drives.
69    if let Some(list) = limit_of(&block) {
70        crate::server::browser_allowlist::limit_new_pane(&state, pane, Some(list)).await;
71    }
72    // The header reads these keys: written before the agent drives, so the person never sees an agent driving unlabelled.
73    if let Err(e) = crate::server::http_shell::broadcast_meta_update(&state, pane, &browser_owner::retaken_meta(agent)) {
74        return err_response(StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't show you as the pane's driver: {e}"));
75    }
76    browser_owner::record(pane, agent);
77    tracing::info!(agent_id = %agent, pane = %pane, "[browser-owner] agent retook the pane");
78    (StatusCode::OK, Json(json!({ "ok": true, "data": { "pane": pane, "already": false } }))).into_response()
79}
80
81/// How long ago the host last saw the person use `pane`'s page (`Duration::MAX` if it never has), or None when the host
82/// cannot say, which keeps the pane the person's until they give it back.
83pub(crate) async fn since_person_input(state: &AppState, pane: &str) -> Option<std::time::Duration> {
84    let host = crate::server::ui_handlers::get_host_ipc(state).await.ok()?;
85    // Not `post_to_host_awake`: a sleeping pane has no page to use, and asking must not wake it.
86    let answer = crate::server::host_http::post_to_host(
87        &state.http_client,
88        &host,
89        "last_input",
90        json!({ "block_id": pane }),
91        Some(std::time::Duration::from_secs(5)),
92    )
93    .await
94    .ok()?;
95    if answer.get("ok").and_then(|v| v.as_bool()) != Some(true) {
96        return None;
97    }
98    let idle = answer.pointer("/data/idle_secs")?;
99    Some(idle.as_u64().map_or(std::time::Duration::MAX, std::time::Duration::from_secs))
100}
101
102/// The sites the pane was limited to, as its header recorded them (`browser:allowed_origins`).
103fn limit_of(block: &crate::backend::obj::Block) -> Option<Vec<String>> {
104    let list = block.meta.get(crate::server::browser_allowlist::ALLOWED_META_KEY)?.as_array()?;
105    Some(list.iter().filter_map(|o| o.as_str().map(str::to_string)).collect())
106}
107
108/// The person's Give back on `block_id`, relayed by the host: the agent that drove the pane last may retake it. Written
109/// to the block's meta too, so it holds after an srv restart.
110pub(crate) fn give_back(state: &AppState, block_id: &str) -> axum::response::Response {
111    let block = match state.mstore.get::<crate::backend::obj::Block>(block_id) {
112        Ok(Some(b)) => b,
113        _ => return err_response(StatusCode::NOT_FOUND, format!("no pane {block_id:?}")),
114    };
115    let Some(agent) = block.meta.get(browser_owner::LAST_DRIVER_META_KEY).and_then(|v| v.as_str()) else {
116        return err_response(StatusCode::NOT_FOUND, "no agent drove that pane".to_string());
117    };
118    if browser_owner::owner_of(block_id).is_some() {
119        return err_response(StatusCode::CONFLICT, "an agent drives that pane: Take over comes first".to_string());
120    }
121    let mut meta = crate::backend::obj::MetaMapType::new();
122    meta.insert(browser_owner::GIVEN_BACK_META_KEY.to_string(), json!(agent));
123    if let Err(e) = crate::server::http_shell::broadcast_meta_update(state, block_id, &meta) {
124        return err_response(StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't give the pane back: {e}"));
125    }
126    browser_owner::mark_given_back(block_id);
127    tracing::info!(pane = %block_id, agent_id = %agent, "[browser-owner] the person gave the pane back");
128    (StatusCode::OK, Json(json!({ "ok": true }))).into_response()
129}
130
131pub(crate) async fn handle_ui_browser_handoff_status(
132    State(state): State<AppState>,
133    caller: Option<axum::Extension<crate::server::caller::Caller>>,
134    Json(req): Json<agentmux_common::api_types::UiBrowserHandoffStatusRequest>,
135) -> impl IntoResponse {
136    if let Err(e) = verified_block_id(&state, caller.as_deref(), &req.auth) {
137        return err_response(StatusCode::UNAUTHORIZED, e);
138    }
139    let (id, pane) = (trimmed(&req.handoff_id), trimmed(&req.pane));
140    if id.is_none() && pane.is_none() {
141        return err_response(
142            StatusCode::BAD_REQUEST,
143            "Browser handoff_status needs handoff_id (the hand-off's answer carries it) or pane".to_string(),
144        );
145    }
146    match crate::server::browser_handoffs::status(&req.auth.agent_id, id, pane) {
147        Some(s) => {
148            let data = json!({
149                "handoff_id": s.id,
150                "pane": s.pane,
151                "status": s.state.as_str(),
152                "started_secs_ago": s.started_secs_ago,
153                "ended_secs_ago": s.ended_secs_ago,
154                "open_secs": s.open_secs,
155            });
156            (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
157        }
158        None => err_response(StatusCode::NOT_FOUND, "no hand-off of yours matches that (they are kept for 24 hours)".to_string()),
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use crate::backend::obj::MetaMapType;
166    use crate::server::tests::test_state;
167    use agentmux_common::api_types::{UiAutomationAuth, UiBrowserRetakeRequest};
168
169    fn auth(state: &AppState, agent_id: &str) -> UiAutomationAuth {
170        let key = state.mstore.agent_jekt_key_ensure(agent_id).unwrap();
171        let ts_secs = agentmux_common::time::now_secs();
172        let sig = agentmux_common::jekt_sign::sign_jekt(&key, "ui-automation-identity", agent_id, "__srv__", ts_secs, "");
173        UiAutomationAuth { agent_id: agent_id.to_string(), ts_secs, sig }
174    }
175
176    async fn retake_status(state: &AppState, agent: &str, pane: &str) -> StatusCode {
177        let req = UiBrowserRetakeRequest { auth: auth(state, agent), pane: Some(pane.to_string()) };
178        handle_ui_browser_retake(State(state.clone()), None, Json(req)).await.into_response().status()
179    }
180
181    fn clear(key: &str) -> MetaMapType {
182        let mut m = MetaMapType::new();
183        m.insert(key.to_string(), serde_json::Value::Null);
184        m
185    }
186
187    #[tokio::test]
188    async fn a_taken_over_pane_is_retaken_only_after_give_back() {
189        let state = test_state();
190        let own = uuid::Uuid::new_v4().to_string();
191        let pane = uuid::Uuid::new_v4().to_string();
192        crate::server::browser_attention::tests::browser_block(&state, &own);
193        crate::server::browser_attention::tests::browser_block(&state, &pane);
194        let agent = format!("retake-{}", uuid::Uuid::new_v4());
195        state.reactive_handler.register_agent(&agent, &own, None).unwrap();
196
197        // Never driven by this agent: refused.
198        assert_eq!(retake_status(&state, &agent, &pane).await, StatusCode::CONFLICT);
199
200        // The agent drives it, the person takes it over: refused until they give it back.
201        browser_owner::record(&pane, &agent);
202        let oref = format!("block:{pane}");
203        browser_owner::guard_client_meta_write(&oref, &clear(browser_owner::OWNER_META_KEY)).unwrap();
204        assert_eq!(retake_status(&state, &agent, &pane).await, StatusCode::CONFLICT, "the person is still using it");
205        assert!(browser_owner::owner_of(&pane).is_none());
206
207        // The person's Give back arrives from the host (not a client write): it needs an agent that drove the pane.
208        let mut driver = MetaMapType::new();
209        driver.insert(browser_owner::LAST_DRIVER_META_KEY.to_string(), json!(agent));
210        crate::server::http_shell::broadcast_meta_update(&state, &pane, &driver).unwrap();
211        assert_eq!(give_back(&state, &pane).status(), StatusCode::OK);
212        assert_eq!(retake_status(&state, &agent, &pane).await, StatusCode::OK);
213        assert_eq!(browser_owner::owner_of(&pane).as_deref(), Some(agent.as_str()));
214        let block = state.mstore.must_get::<crate::backend::obj::Block>(&pane).unwrap();
215        assert_eq!(block.meta.get(browser_owner::OWNER_META_KEY).and_then(|v| v.as_str()), Some(agent.as_str()));
216        assert_eq!(block.meta.get(browser_owner::LAST_DRIVER_META_KEY).and_then(|v| v.as_str()), Some(agent.as_str()));
217
218        // Already driving it: fine, and nothing changes.
219        assert_eq!(retake_status(&state, &agent, &pane).await, StatusCode::OK);
220        browser_owner::forget(&pane);
221    }
222
223    /// A host that answers `last_input` with `idle_secs` (null: the person never used the page), on a port of its own.
224    async fn fake_host(state: &AppState, idle_secs: Option<u64>) {
225        use axum::{routing::post, Router};
226        let app = Router::new().route(
227            "/agentmux/browser/last_input",
228            post(move |Json(_b): Json<serde_json::Value>| async move {
229                Json(json!({ "ok": true, "data": { "idle_secs": idle_secs } }))
230            }),
231        );
232        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
233        let port = listener.local_addr().unwrap().port();
234        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
235        *state.host_ipc.lock().await = Some(crate::server::state::HostIpc { port, token: "host-ipc-token".into() });
236    }
237
238    #[tokio::test]
239    async fn a_pane_the_person_has_left_alone_for_a_minute_is_retaken_without_give_back() {
240        let state = test_state();
241        let own = uuid::Uuid::new_v4().to_string();
242        let pane = uuid::Uuid::new_v4().to_string();
243        crate::server::browser_attention::tests::browser_block(&state, &own);
244        crate::server::browser_attention::tests::browser_block(&state, &pane);
245        let agent = format!("retake-{}", uuid::Uuid::new_v4());
246        state.reactive_handler.register_agent(&agent, &own, None).unwrap();
247        browser_owner::record(&pane, &agent);
248        browser_owner::guard_client_meta_write(&format!("block:{pane}"), &clear(browser_owner::OWNER_META_KEY)).unwrap();
249
250        // No host to ask: only Give back counts.
251        assert_eq!(retake_status(&state, &agent, &pane).await, StatusCode::CONFLICT, "the host cannot say");
252
253        // The person typed 5 s ago: still theirs, even though they took it over long ago.
254        browser_owner::age_lost(&pane, std::time::Duration::from_secs(600));
255        fake_host(&state, Some(5)).await;
256        assert_eq!(retake_status(&state, &agent, &pane).await, StatusCode::CONFLICT, "typed 5 s ago");
257
258        // Idle 120 s, and the Take over was longer ago still: the agent's again.
259        fake_host(&state, Some(120)).await;
260        assert_eq!(retake_status(&state, &agent, &pane).await, StatusCode::OK, "idle 120 s");
261        assert_eq!(browser_owner::owner_of(&pane).as_deref(), Some(agent.as_str()));
262        browser_owner::forget(&pane);
263
264        // Never used the page since the host started: counts from the Take over click.
265        browser_owner::record(&pane, &agent);
266        browser_owner::guard_client_meta_write(&format!("block:{pane}"), &clear(browser_owner::OWNER_META_KEY)).unwrap();
267        fake_host(&state, None).await;
268        assert_eq!(retake_status(&state, &agent, &pane).await, StatusCode::CONFLICT, "took over just now");
269        browser_owner::age_lost(&pane, std::time::Duration::from_secs(61));
270        assert_eq!(retake_status(&state, &agent, &pane).await, StatusCode::OK, "took over 61 s ago, never touched the page");
271        browser_owner::forget(&pane);
272    }
273
274    #[tokio::test]
275    async fn another_agent_cannot_retake_and_a_driven_pane_is_not_retaken() {
276        let state = test_state();
277        let (own_a, own_b) = (uuid::Uuid::new_v4().to_string(), uuid::Uuid::new_v4().to_string());
278        let pane = uuid::Uuid::new_v4().to_string();
279        for b in [&own_a, &own_b, &pane] {
280            crate::server::browser_attention::tests::browser_block(&state, b);
281        }
282        let (a, b) = (format!("retake-a-{}", uuid::Uuid::new_v4()), format!("retake-b-{}", uuid::Uuid::new_v4()));
283        state.reactive_handler.register_agent(&a, &own_a, None).unwrap();
284        state.reactive_handler.register_agent(&b, &own_b, None).unwrap();
285
286        browser_owner::record(&pane, &a);
287        assert_eq!(retake_status(&state, &b, &pane).await, StatusCode::FORBIDDEN, "a pane another agent drives");
288        let oref = format!("block:{pane}");
289        browser_owner::guard_client_meta_write(&oref, &clear(browser_owner::OWNER_META_KEY)).unwrap();
290        let mut driver = MetaMapType::new();
291        driver.insert(browser_owner::LAST_DRIVER_META_KEY.to_string(), json!(a));
292        crate::server::http_shell::broadcast_meta_update(&state, &pane, &driver).unwrap();
293        assert_eq!(give_back(&state, &pane).status(), StatusCode::OK);
294        assert_eq!(retake_status(&state, &b, &pane).await, StatusCode::CONFLICT, "given back to a, not to b");
295        assert_eq!(retake_status(&state, &a, "no-such-pane").await, StatusCode::NOT_FOUND);
296    }
297
298    #[tokio::test]
299    async fn a_retake_brings_the_sites_limit_back_and_a_give_back_needs_a_last_driver() {
300        let state = test_state();
301        let own = uuid::Uuid::new_v4().to_string();
302        let pane = uuid::Uuid::new_v4().to_string();
303        crate::server::browser_attention::tests::browser_block(&state, &own);
304        crate::server::browser_attention::tests::browser_block(&state, &pane);
305        let agent = format!("retake-{}", uuid::Uuid::new_v4());
306        state.reactive_handler.register_agent(&agent, &own, None).unwrap();
307        assert_eq!(give_back(&state, &pane).status(), StatusCode::NOT_FOUND, "no agent drove it");
308
309        let sites = vec!["https://example.com".to_string()];
310        let mut meta = browser_owner::driver_meta(&agent);
311        meta.insert(crate::server::browser_allowlist::ALLOWED_META_KEY.to_string(), json!(sites));
312        crate::server::http_shell::broadcast_meta_update(&state, &pane, &meta).unwrap();
313        crate::server::browser_allowlist::set(&pane, sites.clone());
314        browser_owner::record(&pane, &agent);
315        assert_eq!(give_back(&state, &pane).status(), StatusCode::CONFLICT, "an agent drives it");
316
317        browser_owner::guard_client_meta_write(&format!("block:{pane}"), &clear(browser_owner::OWNER_META_KEY)).unwrap();
318        assert_eq!(crate::server::browser_allowlist::list_for(&pane), None, "the Take over ended the limit");
319        assert_eq!(give_back(&state, &pane).status(), StatusCode::OK);
320        assert_eq!(retake_status(&state, &agent, &pane).await, StatusCode::OK);
321        assert_eq!(crate::server::browser_allowlist::list_for(&pane), Some(sites), "the limit came back with the agent");
322        let block = state.mstore.must_get::<crate::backend::obj::Block>(&pane).unwrap();
323        assert!(block.meta.get(browser_owner::GIVEN_BACK_META_KEY).is_none_or(|v| v.is_null()), "the Give back is spent");
324        crate::server::browser_allowlist::drop_pane(&pane);
325        browser_owner::forget(&pane);
326    }
327}