Skip to main content

agentmux_srv/server/
browser_zoom.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's zoom of a browser pane it drives (docs/specs/SPEC_BROWSER_PANE_AGENT_ZOOM_2026_11_10.md).
5//! The host does the zoom (`/agentmux/browser/zoom`: emulation on the pane's own browser); this checks that the
6//! pane is the caller's, remembers which panes are zoomed and by whom, and gives the agent's `Browser` tool the
7//! line it ends every answer with while one is, so a stale zoom is never a surprise.
8
9use std::collections::{BTreeMap, HashMap};
10use std::sync::{Mutex, OnceLock};
11
12use axum::extract::State;
13use axum::http::StatusCode;
14use axum::response::IntoResponse;
15use axum::Json;
16use serde_json::{json, Value};
17
18use crate::server::ui_handlers::{err_response, get_host_ipc, proxy_to_host_timeout, target_block_id};
19use crate::server::AppState;
20
21/// A pane the host has zoomed: the agent that did it, and what to tell that agent.
22#[derive(Debug, Clone, PartialEq)]
23struct Zoomed {
24    agent: String,
25    line: String,
26}
27
28fn zoomed() -> &'static Mutex<HashMap<String, Zoomed>> {
29    static Z: OnceLock<Mutex<HashMap<String, Zoomed>>> = OnceLock::new();
30    Z.get_or_init(Default::default)
31}
32
33/// How long the host has to fit a pane (it reflows the page and measures it).
34const HOST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
35/// How long it has to say how a pane is zoomed now (it only reads its own record).
36const STATUS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
37
38/// `POST /api/v1/ui/browser/zoom` — zoom a pane the caller drives, or put it back (`reset`).
39pub(crate) async fn handle_ui_browser_zoom(
40    State(state): State<AppState>,
41    caller: Option<axum::Extension<crate::server::caller::Caller>>,
42    Json(req): Json<agentmux_common::api_types::UiBrowserZoomRequest>,
43) -> impl IntoResponse {
44    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
45        Ok(b) => b,
46        Err((code, e)) => return err_response(code, e),
47    };
48    let host = match get_host_ipc(&state).await {
49        Ok(h) => h,
50        Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
51    };
52    let body = json!({
53        "block_id": block_id,
54        "factor": req.factor,
55        "width": req.width,
56        "fit": req.fit.unwrap_or(false),
57        "reset": req.reset.unwrap_or(false),
58    });
59    let host_resp = match proxy_to_host_timeout(&state, &host, "zoom", body, Some(HOST_TIMEOUT)).await {
60        Ok(v) => v,
61        Err(e) => return err_response(StatusCode::BAD_GATEWAY, e),
62    };
63    if host_resp.get("ok").and_then(|v| v.as_bool()) != Some(true) {
64        let err = host_resp.get("error").and_then(|v| v.as_str()).unwrap_or("unknown host error").to_string();
65        return err_response(StatusCode::BAD_REQUEST, err);
66    }
67    let data = host_resp.get("data").cloned().unwrap_or(Value::Null);
68    set(&block_id, &req.auth.agent_id, &data);
69    tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser zoom");
70    (StatusCode::OK, Json(json!({ "ok": true, "data": data }))).into_response()
71}
72
73/// Remember the host's answer: the pane is zoomed (with the line to show), or it is not.
74pub(crate) fn remember(block_id: &str, agent: &str, data: &Value) {
75    set(block_id, agent, data);
76}
77
78fn set(block_id: &str, agent: &str, data: &Value) {
79    let mut map = zoomed().lock().unwrap_or_else(|p| p.into_inner());
80    match (data.get("zoomed").and_then(|z| z.as_bool()), data.get("line").and_then(|l| l.as_str())) {
81        (Some(true), Some(line)) => {
82            map.insert(block_id.to_string(), Zoomed { agent: agent.to_string(), line: line.to_string() });
83        }
84        _ => {
85            map.remove(block_id);
86        }
87    }
88}
89
90/// The lines for `agent`'s `Browser` tool to end an answer with: one per pane of theirs that is zoomed, as the
91/// host holds it now. The host changes a zoom on its own (it follows a resize, drops one it could not apply, and
92/// loses one with a browser that slept), so each pane is asked about; a host that cannot be reached leaves what
93/// was recorded. Asked without waking a pane that sleeps.
94pub(crate) async fn notes(state: &AppState, agent: &str) -> Vec<Value> {
95    let panes: Vec<String> = zoomed()
96        .lock()
97        .unwrap_or_else(|p| p.into_inner())
98        .iter()
99        .filter(|(_, z)| z.agent == agent)
100        .map(|(pane, _)| pane.clone())
101        .collect();
102    if panes.is_empty() {
103        return Vec::new();
104    }
105    if let Ok(host) = get_host_ipc(state).await {
106        for pane in panes {
107            let body = json!({ "block_id": pane, "status": true });
108            let asked = crate::server::host_http::post_to_host(&state.http_client, &host, "zoom", body, Some(STATUS_TIMEOUT)).await;
109            if let Some(data) = asked.ok().filter(|r| r.get("ok").and_then(|o| o.as_bool()) == Some(true)).and_then(|r| r.get("data").cloned()) {
110                set(&pane, agent, &data);
111            }
112        }
113    }
114    notes_for(agent)
115}
116
117fn notes_for(agent: &str) -> Vec<Value> {
118    let map = zoomed().lock().unwrap_or_else(|p| p.into_inner());
119    let mut notes: Vec<Value> = map
120        .iter()
121        .filter(|(_, z)| z.agent == agent)
122        .map(|(pane, z)| json!({ "pane": pane, "line": z.line }))
123        .collect();
124    notes.sort_by(|a, b| a["pane"].as_str().cmp(&b["pane"].as_str()));
125    notes
126}
127
128/// The panes the host should put back, and forget here: those no longer owned by the agent that zoomed them, or
129/// handed to the person. (The host also drops a zoom on a pane that is not owned at all.) `owners` is every
130/// owned pane with its owner.
131fn stale(owners: &BTreeMap<String, String>, handed: &[String]) -> Vec<String> {
132    stale_in(&mut zoomed().lock().unwrap_or_else(|p| p.into_inner()), owners, handed)
133}
134
135fn stale_in(map: &mut HashMap<String, Zoomed>, owners: &BTreeMap<String, String>, handed: &[String]) -> Vec<String> {
136    let gone: Vec<String> = map
137        .iter()
138        .filter(|(pane, z)| owners.get(*pane) != Some(&z.agent) || handed.contains(*pane))
139        .map(|(pane, _)| pane.clone())
140        .collect();
141    for pane in &gone {
142        map.remove(pane);
143    }
144    gone
145}
146
147/// Part of the push of the owned panes: forget the zoom of every pane that stopped being the zoomer's, and
148/// tell the host to put each back, in case another agent now owns one (the host only knows a pane is owned).
149pub(crate) async fn reconcile(state: &AppState, host: &crate::server::HostIpc, handed: &[String]) {
150    for pane in stale(&crate::server::browser_owner::all_owners(), handed) {
151        let _ = proxy_to_host_timeout(state, host, "zoom", json!({ "block_id": pane, "reset": true }), Some(HOST_TIMEOUT)).await;
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    fn data(zoomed: bool, line: &str) -> Value {
160        json!({ "zoomed": zoomed, "line": line })
161    }
162
163    #[test]
164    fn a_zoomed_pane_is_told_to_its_agent_only_until_it_is_put_back() {
165        set("zt-pane-1", "agent-a", &data(true, "viewport 1280x720 CSS, shown at 50%"));
166        assert_eq!(notes_for("agent-a").iter().filter(|n| n["pane"] == "zt-pane-1").count(), 1);
167        assert!(notes_for("agent-b").iter().all(|n| n["pane"] != "zt-pane-1"));
168        set("zt-pane-1", "agent-a", &data(false, "zoom is off (100%)"));
169        assert!(notes_for("agent-a").iter().all(|n| n["pane"] != "zt-pane-1"));
170    }
171
172    #[test]
173    fn a_pane_that_changed_hands_or_went_to_the_person_is_forgotten() {
174        let z = |a: &str| Zoomed { agent: a.to_string(), line: "viewport 640x400 CSS, shown at 200%".to_string() };
175        let mut map = HashMap::from([("p2".to_string(), z("agent-a")), ("p3".to_string(), z("agent-a")), ("p4".to_string(), z("agent-a")), ("p5".to_string(), z("agent-a"))]);
176        let owners = BTreeMap::from([
177            ("p2".to_string(), "agent-a".to_string()),
178            ("p3".to_string(), "agent-b".to_string()),
179            ("p4".to_string(), "agent-a".to_string()),
180        ]);
181        let mut gone = stale_in(&mut map, &owners, &["p4".to_string()]);
182        gone.sort();
183        // p3 changed hands, p4 went to the person, p5 is no longer owned at all; p2 stays.
184        assert_eq!(gone, vec!["p3".to_string(), "p4".to_string(), "p5".to_string()]);
185        assert_eq!(map.keys().collect::<Vec<_>>(), vec!["p2"]);
186    }
187
188    #[test]
189    fn an_answer_without_a_line_is_not_a_zoom() {
190        set("zt-pane-5", "agent-a", &json!({ "zoomed": true }));
191        assert!(notes_for("agent-a").iter().all(|n| n["pane"] != "zt-pane-5"));
192    }
193}