1use 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
28const WRITES_PER_MINUTE: usize = 30;
30const PANE_FLOOR: f64 = 0.5;
32
33static WRITES: Mutex<Option<HashMap<String, VecDeque<Instant>>>> = Mutex::new(None);
35
36fn 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
50pub(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
63fn panes_asked(body: &Value) -> Result<Option<Vec<String>>, Response> {
66 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
83fn 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
105fn fit_request(body: &Value) -> Result<Option<Vec<String>>, Response> {
107 fit_options(body)?;
108 panes_asked(body)
109}
110
111fn 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
128fn 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
159fn 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
169async 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
203pub(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
214pub(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 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 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 (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 _ => ("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
304async 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}