Skip to main content

agentmux_srv/server/
zoom.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The routes of the `Zoom` tool (docs/specs/SPEC_MUXAPI_ZOOM_2026_11_24.md): an agent reads and sets the zoom of the
5//! panes in its own tab and of its own window's chrome.
6//!
7//!   POST /api/v1/ui/zoom/{get,set,reset,undo,fit,check}  { agent_id, scope?, target?, block?, blocks?, value?, token?, chrome?, max?, min_text_px?, axis?, apply? }
8//!
9//! The agent's token decides who acts and which pane is its own; nothing in the body can say "my pane". A block in the
10//! body is a target, checked against the tab that holds the caller's own pane (a pinned pane's tab is the one showing,
11//! and the pinned panes count as in it). The window that holds that pane applies the change and tells the person
12//! (frontend/app/store/zoom-agent.ts), so these routes only carry the call: they never take focus.
13
14use std::collections::{HashMap, VecDeque};
15use std::sync::Mutex;
16use std::time::{Duration, Instant};
17
18use axum::extract::{Path, State};
19use axum::response::{IntoResponse, Response};
20use axum::Json;
21use serde_json::{json, Value};
22
23use super::caller::Caller;
24use super::AppState;
25use crate::backend::obj::{Block, LayoutState, Tab, Workspace};
26use crate::backend::storage::store::Store;
27
28/// The most writes (`set`, `reset`) one agent makes in a minute.
29const WRITES_PER_MINUTE: usize = 30;
30/// The least a pane may be zoomed to: a `max` below it names no zoom a pane can have.
31const PANE_FLOOR: f64 = 0.5;
32
33/// The write times of each agent in the last minute.
34static WRITES: Mutex<Option<HashMap<String, VecDeque<Instant>>>> = Mutex::new(None);
35
36/// Counts a write by `agent` at `now`; over the limit it says in how many milliseconds one is free again.
37fn take_write(log: &mut HashMap<String, VecDeque<Instant>>, agent: &str, now: Instant, limit: usize) -> Result<(), u64> {
38    let times = log.entry(agent.to_string()).or_default();
39    while times.front().is_some_and(|t| now.duration_since(*t) >= Duration::from_secs(60)) {
40        times.pop_front();
41    }
42    if times.len() >= limit {
43        let free_at = *times.front().expect("a full log has a first entry") + Duration::from_secs(60);
44        return Err(free_at.saturating_duration_since(now).as_millis() as u64 + 1);
45    }
46    times.push_back(now);
47    Ok(())
48}
49
50/// A refusal: HTTP 200 with the spec's `{ok:false, error, message}` shape, so the agent reads it as an answer.
51pub(super) fn refuse(error: &str, message: impl Into<String>, extra: Value) -> Response {
52    let mut v = json!({ "ok": false, "error": error, "message": message.into() });
53    if let (Some(v), Some(extra)) = (v.as_object_mut(), extra.as_object()) {
54        v.extend(extra.clone());
55    }
56    Json(v).into_response()
57}
58
59pub(super) fn text(body: &Value, key: &str) -> String {
60    body.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_string()
61}
62
63/// The panes a `fit` or `check` names: `blocks` (a list), or `block` (one pane, or "all" for every pane of the tab, which
64/// is none named). `None` means every pane of the tab.
65fn panes_asked(body: &Value) -> Result<Option<Vec<String>>, Response> {
66    // A `blocks` that is not a list (a string, a number) is a mistake, not "every pane": fit would then change them all.
67    if body.get("blocks").is_some_and(|b| !b.is_array() && !b.is_null()) {
68        return Err(refuse("not_found", "blocks is a list of pane ids from get", json!({})));
69    }
70    if let Some(list) = body.get("blocks").and_then(Value::as_array) {
71        let ids: Vec<String> = list.iter().filter_map(Value::as_str).map(str::to_string).collect();
72        if ids.len() != list.len() || ids.is_empty() {
73            return Err(refuse("not_found", "blocks is a list of pane ids from get", json!({})));
74        }
75        return Ok(Some(ids));
76    }
77    match text(body, "block").as_str() {
78        "" | "all" => Ok(None),
79        one => Ok(Some(vec![one.to_string()])),
80    }
81}
82
83/// The options of a `fit` or `check`, refused when they are not what the search can use: an `axis` other than x, y or both
84/// would skip every scroller and call a pane clean; a `max` that is not a number from the pane floor up would be searched as
85/// NaN or refused as "too narrow"; a `min_text_px` that is not above zero would pass any text.
86fn fit_options(body: &Value) -> Result<(), Response> {
87    let bad = |what: &str, why: &str| -> Result<(), Response> { Err(refuse("not_found", format!("{what} {why}"), json!({}))) };
88    match body.get("axis") {
89        None | Some(Value::Null) => {}
90        Some(Value::String(a)) if matches!(a.as_str(), "x" | "y" | "both") => {}
91        Some(_) => return bad("axis", "is \"x\", \"y\" or \"both\""),
92    }
93    match body.get("max") {
94        None | Some(Value::Null) => {}
95        Some(v) if v.as_f64().is_some_and(|m| m.is_finite() && m >= PANE_FLOOR) => {}
96        Some(_) => return bad("max", &format!("is a zoom of {PANE_FLOOR} or more")),
97    }
98    match body.get("min_text_px") {
99        None | Some(Value::Null) => Ok(()),
100        Some(v) if v.as_f64().is_some_and(|m| m.is_finite() && m > 0.0 && m <= 100.0) => Ok(()),
101        Some(_) => bad("min_text_px", "is a size in pixels above 0, up to 100"),
102    }
103}
104
105/// `fit_options`, then the panes a `fit` or `check` names (`panes_asked`).
106fn fit_request(body: &Value) -> Result<Option<Vec<String>>, Response> {
107    fit_options(body)?;
108    panes_asked(body)
109}
110
111/// Every tab of the pane that holds `block_id` (a stack), `block_id` first; just `block_id` when its layout does not say.
112fn stack_of(store: &Store, block_id: &str) -> Vec<String> {
113    let members = store
114        .get::<Block>(block_id)
115        .ok()
116        .flatten()
117        .and_then(|b| b.parentoref.strip_prefix("tab:").map(str::to_string))
118        .and_then(|tab| store.get::<Tab>(&tab).ok().flatten())
119        .and_then(|tab| store.get::<LayoutState>(&tab.layoutstate).ok().flatten())
120        .and_then(|l| l.rootnode)
121        .and_then(|root| crate::backend::layout::find_leaf_containing_block(&root, block_id).and_then(|leaf| leaf.data.as_ref().map(crate::backend::layout::leaf_members)))
122        .unwrap_or_default();
123    let mut all = vec![block_id.to_string()];
124    all.extend(members.into_iter().filter(|m| m != block_id));
125    all
126}
127
128/// The panes on screen with tab `own_tab`: its own, and the window's pinned pane when that is a pane of another tab
129/// (it is drawn over this one), with every tab of its stack. Returns the tab's id too.
130fn tab_panes(store: &Store, own_tab: &str) -> (String, Vec<String>) {
131    let mut panes = store.get::<Tab>(own_tab).ok().flatten().map(|t| t.blockids).unwrap_or_default();
132    let ws = store.get_all::<Workspace>().ok().and_then(|all| all.into_iter().find(|w| w.tabids.iter().chain(w.pinnedtabids.iter()).any(|t| t == own_tab)));
133    for pin in ws.map(|w| w.pins).unwrap_or_default() {
134        for member in stack_of(store, &pin.block_id) {
135            if !panes.contains(&member) {
136                panes.push(member);
137            }
138        }
139    }
140    (own_tab.to_string(), panes)
141}
142
143pub(crate) async fn handle_zoom(State(state): State<AppState>, caller: Option<axum::Extension<Caller>>, Path(action): Path<String>, Json(body): Json<Value>) -> Response {
144    let forbid = |e: &str| (axum::http::StatusCode::FORBIDDEN, Json(json!({ "error": e }))).into_response();
145    let Some(uid) = caller.as_deref().and_then(Caller::uid).map(str::to_string) else {
146        return forbid("FORBIDDEN: this acts for an agent, so the request must carry that agent's token");
147    };
148    let claimed = text(&body, "agent_id");
149    let proven = {
150        let (mstore, uid) = (state.mstore.clone(), uid.clone());
151        tokio::task::spawn_blocking(move || super::actor::proven_slug(&mstore, &uid, &claimed)).await.ok().flatten()
152    };
153    let Some(slug) = proven else {
154        return forbid("FORBIDDEN: the token's agent doesn't answer to that agent_id");
155    };
156    act(&state, &uid, &slug, &action, &body).await
157}
158
159/// Whether a `get`, `set` or `reset` selects the one pane in `block`: a `get` of the window (`scope: "window"`), a `set` or
160/// `reset` of the chrome or of `all` panes name more than a pane, so a browser block beside them does not take the call over.
161fn names_one_pane(action: &str, body: &Value) -> bool {
162    match action {
163        "get" => text(body, "scope") != "window",
164        "set" | "reset" => text(body, "target") == "pane",
165        _ => false,
166    }
167}
168
169/// A browser pane the caller drives is zoomed by emulation, whichever tab it is in (spec 4.2): `Some(answer)` when the
170/// call names one, `None` for every other call.
171async fn browser_pane_call(state: &AppState, own_id: &str, slug: &str, action: &str, body: &Value) -> Option<Response> {
172    let named = text(body, "block");
173    let is_browser = !named.is_empty() && names_one_pane(action, body) && super::zoom_browser::is_browser_pane(state, &named);
174    if !is_browser {
175        return None;
176    }
177    if matches!(action, "set" | "reset") {
178        let mut log = WRITES.lock().unwrap_or_else(|e| e.into_inner());
179        if let Err(retry_ms) = take_write(log.get_or_insert_with(HashMap::new), slug, Instant::now(), WRITES_PER_MINUTE) {
180            return Some(refuse("rate_limited", format!("at most {WRITES_PER_MINUTE} zoom changes a minute: wait and try again"), json!({ "retry_after_ms": retry_ms })));
181        }
182    }
183    Some(super::zoom_browser::run(state, own_id, slug, action, body).await)
184}
185
186async fn act(state: &AppState, uid: &str, slug: &str, action: &str, body: &Value) -> Response {
187    if !["get", "set", "reset", "undo", "fit", "check"].contains(&action) {
188        return refuse("not_found", format!("Zoom has no action {action:?}; use get, set, reset, undo, fit or check"), json!({}));
189    }
190    let own = match super::app_api::agent_block::find_agent_block_by_uid(&state.mstore, uid) {
191        Ok(Some(o)) => o,
192        _ => return refuse("not_found", "you have no pane in a window, so there is no tab or window to zoom", json!({})),
193    };
194    let own_id = own.block.oid.clone();
195    if let Some(answer) = browser_pane_call(state, &own_id, slug, action, body).await {
196        return answer;
197    }
198    let own_tab = own.tab_id.clone().unwrap_or_default();
199    let scope = Scope { own_id: &own_id, own_tab: &own_tab, agent: super::ui_shortcuts::agent_name(slug), rate_key: slug, per_minute: WRITES_PER_MINUTE, remote: false };
200    run_in_tab(state, &scope, action, body).await
201}
202
203/// Whose call it is and where: the pane that routes it to a window, that pane's tab, the name the notice shows, and the
204/// write limit. A remote caller has no pane here: `own_id` is only a pane of the tab it was told it was zooming.
205pub(super) struct Scope<'a> {
206    pub own_id: &'a str,
207    pub own_tab: &'a str,
208    pub agent: String,
209    pub rate_key: &'a str,
210    pub per_minute: usize,
211    pub remote: bool,
212}
213
214/// An action on the panes of `scope.own_tab`, as `scope.agent`.
215pub(super) async fn run_in_tab(state: &AppState, scope: &Scope<'_>, action: &str, body: &Value) -> Response {
216    let own_id = scope.own_id.to_string();
217    let (tab, panes) = tab_panes(&state.mstore, scope.own_tab);
218    let in_tab = |b: &str| panes.iter().any(|p| p == b);
219    let not_in_tab = |b: &str| refuse("not_in_your_tab", format!("{b} is not in your tab: ask the agent that is in that tab, or have the pane moved into yours"), json!({ "tab": tab }));
220    let agent = scope.agent.clone();
221    // A remote caller names its pane: it has none here to default to.
222    let own_default = |what: &str| -> Result<String, Response> {
223        match (text(body, "block"), scope.remote) {
224            (b, _) if !b.is_empty() => Ok(b),
225            (_, true) => Err(refuse("not_found", format!("{what} over host needs `block`: a block id from a Zoom get of that machine"), json!({}))),
226            _ => Ok(own_id.clone()),
227        }
228    };
229    // fit with `apply: false` only measures, so it is not a write.
230    let write = matches!(action, "set" | "reset") || (action == "fit" && body.get("apply").and_then(Value::as_bool) != Some(false));
231
232    let (op, args) = match action {
233        "get" => {
234            let scope = Some(text(body, "scope")).filter(|s| !s.is_empty()).unwrap_or_else(|| "tab".into());
235            let blocks: Vec<String> = match (scope.as_str(), text(body, "block")) {
236                ("window", _) => vec![],
237                (_, b) if !b.is_empty() => {
238                    if !in_tab(&b) {
239                        return not_in_tab(&b);
240                    }
241                    vec![b]
242                }
243                _ => panes.clone(),
244            };
245            ("get", json!({ "blocks": blocks }))
246        }
247        "set" => {
248            let target = text(body, "target");
249            let block = match own_default("set") {
250                Ok(b) => b,
251                Err(e) if target == "pane" => return e,
252                Err(_) => String::new(),
253            };
254            match target.as_str() {
255                "pane" if !in_tab(&block) => return not_in_tab(&block),
256                "pane" | "chrome" => {}
257                _ => return refuse("not_found", "set needs target: \"pane\" (with block, default your own pane) or \"chrome\"", json!({})),
258            }
259            ("set", json!({ "agent": agent, "target": target, "block": (target == "pane").then_some(block), "value": body.get("value") }))
260        }
261        "reset" => {
262            let target = text(body, "target");
263            let block = match own_default("reset") {
264                Ok(b) => b,
265                Err(e) if target == "pane" => return e,
266                Err(_) => String::new(),
267            };
268            match target.as_str() {
269                "pane" if !in_tab(&block) => return not_in_tab(&block),
270                "pane" | "chrome" | "all" => {}
271                _ => return refuse("not_found", "reset needs target: \"pane\", \"chrome\" or \"all\" (every pane in your tab)", json!({})),
272            }
273            let blocks = if target == "all" { panes.clone() } else { vec![] };
274            (
275                "reset",
276                json!({ "agent": agent, "target": target, "block": (target == "pane").then_some(block), "blocks": blocks, "chrome": body.get("chrome").and_then(Value::as_bool).unwrap_or(false) }),
277            )
278        }
279        "check" | "fit" => {
280            let wanted = match fit_request(body) {
281                Ok(w) => w,
282                Err(e) => return e,
283            };
284            let all = wanted.is_none();
285            let blocks: Vec<String> = match wanted {
286                None => panes.clone(),
287                Some(w) => {
288                    if let Some(b) = w.iter().find(|b| !in_tab(b)) {
289                        return not_in_tab(b);
290                    }
291                    w
292                }
293            };
294            // `check` reads only blocks, axis and minTextPx; the rest is for `fit`.
295            (action, json!({ "agent": agent, "blocks": blocks, "max": body.get("max"), "axis": body.get("axis"), "minTextPx": body.get("min_text_px"), "apply": body.get("apply"), "all": all }))
296        }
297        // The panes in the caller's tab now: a pane that has moved to another tab since is left alone.
298        _ => ("undo", json!({ "agent": agent, "token": body.get("token"), "panes": panes })),
299    };
300
301    send_to_window(state, scope, action, (op, args), write, &tab).await
302}
303
304/// Counts a write against the caller's limit, then has the window that holds the scope's pane do `op`.
305async fn send_to_window(state: &AppState, scope: &Scope<'_>, action: &str, (op, args): (&str, Value), write: bool, tab: &str) -> Response {
306    let (own_id, slug) = (scope.own_id, scope.rate_key);
307    if write {
308        let now = Instant::now();
309        let mut log = WRITES.lock().unwrap_or_else(|e| e.into_inner());
310        if let Err(retry_ms) = take_write(log.get_or_insert_with(HashMap::new), slug, now, scope.per_minute) {
311            return refuse("rate_limited", format!("at most {} zoom changes a minute: wait and try again", scope.per_minute), json!({ "retry_after_ms": retry_ms }));
312        }
313    }
314    tracing::info!(agent_id = %slug, block_id = %own_id, action, remote = scope.remote, "[zoom] agent zoom call");
315    let mut answer = match super::ui_handlers::proxy_value(state, "zoom_op", json!({ "block_id": own_id, "op": op, "args": args }), Duration::from_secs(10)).await {
316        Ok(v) => v,
317        Err((_, e)) => return refuse("window_unreachable", format!("the window that holds your pane did not answer: {e}"), json!({})),
318    };
319    if action == "get" {
320        if let Some(a) = answer.as_object_mut() {
321            a.insert("tab".into(), if scope.remote { json!({ "id": tab }) } else { json!({ "id": tab, "own_pane": own_id }) });
322        }
323    }
324    Json(answer).into_response()
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    #[test]
332    fn the_thirty_first_write_in_a_minute_waits_for_the_first_to_age() {
333        let mut log = HashMap::new();
334        let t0 = Instant::now();
335        for i in 0..WRITES_PER_MINUTE {
336            assert!(take_write(&mut log, "opaz", t0 + Duration::from_millis(i as u64), WRITES_PER_MINUTE).is_ok());
337        }
338        let retry = take_write(&mut log, "opaz", t0 + Duration::from_secs(10), WRITES_PER_MINUTE).unwrap_err();
339        assert!((49_000..=50_100).contains(&retry), "{retry}");
340        assert!(take_write(&mut log, "loap", t0, WRITES_PER_MINUTE).is_ok(), "each agent has its own limit");
341        assert!(take_write(&mut log, "opaz", t0 + Duration::from_secs(61), WRITES_PER_MINUTE).is_ok(), "a minute later it is free");
342    }
343
344    fn store_with_pin() -> Store {
345        let store = Store::open_in_memory().unwrap();
346        for (id, blocks) in [("t1", vec!["a", "p"]), ("t2", vec!["b"])] {
347            let mut t = Tab { oid: id.into(), blockids: blocks.into_iter().map(String::from).collect(), ..Default::default() };
348            store.insert(&mut t).unwrap();
349        }
350        let pins = vec![agentmux_common::PinRecord { block_id: "p".into(), order: 0 }];
351        let mut ws = Workspace { oid: "ws".into(), tabids: vec!["t1".into(), "t2".into()], activetabid: "t2".into(), pins, ..Default::default() };
352        store.insert(&mut ws).unwrap();
353        store
354    }
355
356    #[test]
357    fn a_tab_is_its_panes_and_the_windows_pinned_pane_once() {
358        let store = store_with_pin();
359        assert_eq!(tab_panes(&store, "t1"), ("t1".to_string(), vec!["a".to_string(), "p".to_string()]), "its own tab lists it once");
360        assert_eq!(tab_panes(&store, "t2").1, vec!["b".to_string(), "p".to_string()], "another tab has it drawn over its panes");
361    }
362
363    #[test]
364    fn the_pinned_pane_brings_every_tab_of_its_stack() {
365        let store = store_with_pin();
366        for id in ["p", "q"] {
367            let mut b = Block { oid: id.into(), parentoref: "tab:t1".into(), ..Default::default() };
368            store.insert(&mut b).unwrap();
369        }
370        let leaf = |id: &str, stack: &[&str]| agentmux_common::LayoutNode {
371            id: id.into(),
372            size: 10.0,
373            data: Some(agentmux_common::LayoutNodeData {
374                block_id: stack[0].into(),
375                active_block_id: stack[0].into(),
376                block_stack: stack.iter().map(|s| s.to_string()).collect(),
377                ..Default::default()
378            }),
379            ..Default::default()
380        };
381        let root = agentmux_common::LayoutNode { id: "root".into(), size: 10.0, children: vec![leaf("n1", &["a"]), leaf("n2", &["p", "q"])], ..Default::default() };
382        let mut layout = LayoutState { oid: "l1".into(), rootnode: Some(root), ..Default::default() };
383        store.insert(&mut layout).unwrap();
384        let mut t = store.get::<Tab>("t1").unwrap().unwrap();
385        t.layoutstate = "l1".into();
386        t.blockids = vec!["a".into(), "p".into(), "q".into()];
387        store.update(&mut t).unwrap();
388        assert_eq!(tab_panes(&store, "t2").1, vec!["b".to_string(), "p".to_string(), "q".to_string()], "the other tab of the stack is drawn too");
389        assert_eq!(tab_panes(&store, "t1").1, vec!["a".to_string(), "p".to_string(), "q".to_string()], "and listed once in its own tab");
390    }
391
392    #[test]
393    fn a_browser_block_takes_a_call_over_only_when_the_call_selects_that_pane() {
394        assert!(names_one_pane("get", &json!({ "block": "b" })));
395        assert!(names_one_pane("get", &json!({ "block": "b", "scope": "tab" })));
396        assert!(!names_one_pane("get", &json!({ "block": "b", "scope": "window" })));
397        assert!(names_one_pane("set", &json!({ "block": "b", "target": "pane", "value": 1 })));
398        assert!(names_one_pane("reset", &json!({ "block": "b", "target": "pane" })));
399        for target in ["all", "chrome", ""] {
400            assert!(!names_one_pane("reset", &json!({ "block": "b", "target": target, "chrome": true })), "{target}");
401            assert!(!names_one_pane("set", &json!({ "block": "b", "target": target })), "{target}");
402        }
403        assert!(!names_one_pane("undo", &json!({ "block": "b", "target": "pane" })));
404    }
405
406    #[test]
407    fn fit_and_check_refuse_options_the_search_cannot_use() {
408        assert!(fit_options(&json!({})).is_ok());
409        assert!(fit_options(&json!({ "axis": "both", "max": 1.2, "min_text_px": 10 })).is_ok());
410        assert!(fit_options(&json!({ "axis": null, "max": null, "min_text_px": null })).is_ok());
411        for bad in [
412            json!({ "axis": "z" }),
413            json!({ "axis": 1 }),
414            json!({ "max": "big" }),
415            json!({ "max": 0 }),
416            json!({ "max": 0.4 }),
417            json!({ "max": -1 }),
418            json!({ "min_text_px": 0 }),
419            json!({ "min_text_px": -3 }),
420            json!({ "min_text_px": "8" }),
421            json!({ "min_text_px": 5000 }),
422        ] {
423            assert!(fit_options(&bad).is_err(), "{bad}");
424        }
425        assert!(fit_request(&json!({ "axis": "z", "block": "a" })).is_err(), "options are read before the panes");
426    }
427
428    #[test]
429    fn fit_and_check_name_panes_by_list_by_one_or_all_of_the_tab() {
430        let asked = |v: Value| panes_asked(&v).ok().unwrap();
431        assert_eq!(asked(json!({ "blocks": ["a", "b"] })), Some(vec!["a".to_string(), "b".to_string()]));
432        assert_eq!(asked(json!({ "block": "a" })), Some(vec!["a".to_string()]));
433        assert_eq!(asked(json!({ "block": "all" })), None);
434        assert_eq!(asked(json!({})), None);
435        assert!(panes_asked(&json!({ "blocks": [] })).is_err(), "an empty list names nothing");
436        assert!(panes_asked(&json!({ "blocks": ["a", 7] })).is_err(), "a list of ids, not numbers");
437        for not_a_list in [json!("a"), json!(7), json!({ "x": 1 }), json!(true)] {
438            assert!(panes_asked(&json!({ "blocks": not_a_list })).is_err(), "{not_a_list}: not a list is not every pane");
439        }
440        assert_eq!(asked(json!({ "blocks": null })), None, "null is absent");
441    }
442
443    #[test]
444    fn a_pane_of_another_tab_is_not_in_the_callers() {
445        let store = store_with_pin();
446        assert!(!tab_panes(&store, "t1").1.iter().any(|p| p == "b"));
447    }
448}