agentmux_srv/server/remote_ops/
zoom_ops.rs1use axum::response::Response;
14use serde_json::{json, Value};
15
16use super::{AppState, RemoteCaller, RemoteRefusal, RemoteResult};
17use crate::backend::obj::{Tab, Window, Workspace};
18use crate::server::zoom::{run_in_tab, Scope};
19
20const REMOTE_WRITES_PER_MINUTE: usize = 10;
22
23#[derive(Debug, Clone, PartialEq, Eq)]
26struct Showing {
27 window: String,
28 tab: String,
29 pane: String,
30}
31
32fn showing(state: &AppState) -> Result<Showing, RemoteRefusal> {
33 let store = &state.mstore;
34 let failed = |e: String| RemoteRefusal::failed(format!("zoom: {e}"));
35 let client = crate::backend::wcore::get_client(store).map_err(|e| failed(e.to_string()))?;
37 let mut win = None;
38 for id in &client.windowids {
39 match store.get::<Window>(id).map_err(|e| failed(e.to_string()))? {
40 Some(w) if !w.workspaceid.is_empty() => {
41 win = Some(w);
42 break;
43 }
44 _ => {}
45 }
46 }
47 let win = win.ok_or_else(|| RemoteRefusal::new("not_found", "no window is open on that machine"))?;
48 let ws = store.get::<Workspace>(&win.workspaceid).map_err(|e| failed(e.to_string()))?.ok_or_else(|| RemoteRefusal::new("not_found", "that window has no workspace"))?;
49 let tab = store.get::<Tab>(&ws.activetabid).map_err(|e| failed(e.to_string()))?.ok_or_else(|| RemoteRefusal::new("not_found", "that window shows no tab"))?;
50 let pane = tab.blockids.iter().find(|b| !crate::server::zoom_browser::is_browser_pane(state, b)).cloned().ok_or_else(|| RemoteRefusal::new("not_found", "the tab on show has no pane the app window can route a zoom through (every pane is a browser pane)"))?;
52 Ok(Showing { window: win.oid, tab: tab.oid, pane })
53}
54
55fn check_target(now: &Showing, params: &Value) -> Result<(), RemoteRefusal> {
57 let text = |k: &str| params.get(k).and_then(Value::as_str).map(str::trim).unwrap_or_default();
58 let (window, tab) = (text("window"), text("tab"));
59 if window.is_empty() || tab.is_empty() {
60 return Err(RemoteRefusal::new("window_and_tab_required", "name the `window` and `tab` a Zoom get of that machine returned: a write never goes to whatever is in front"));
61 }
62 if window != now.window || tab != now.tab {
63 return Err(RemoteRefusal::new("tab_changed", format!("that window and tab are no longer the ones showing (now window {}, tab {}): Zoom get again", now.window, now.tab)));
64 }
65 Ok(())
66}
67
68fn body_of(params: &Value) -> Value {
70 let mut body = params.clone();
71 if let Some(m) = body.as_object_mut() {
72 m.remove("window");
73 m.remove("tab");
74 }
75 body
76}
77
78async fn value_of(resp: Response) -> RemoteResult {
79 let bytes = axum::body::to_bytes(resp.into_body(), 4 << 20).await.map_err(|e| RemoteRefusal::failed(format!("zoom: {e}")))?;
80 serde_json::from_slice(&bytes).map_err(|e| RemoteRefusal::failed(format!("zoom: {e}")))
81}
82
83async fn run(state: &AppState, caller: &RemoteCaller, action: &str, params: Value) -> RemoteResult {
84 if !params.is_object() {
85 return Err(RemoteRefusal::new("invalid_arg", "params must be an object"));
86 }
87 let now = showing(state)?;
88 if action != "get" {
89 check_target(&now, ¶ms)?;
90 }
91 let actor = caller.actor();
92 let scope = Scope { own_id: &now.pane, own_tab: &now.tab, agent: actor.clone(), rate_key: &actor, per_minute: REMOTE_WRITES_PER_MINUTE, remote: true };
93 let mut answer = value_of(run_in_tab(state, &scope, action, &body_of(¶ms)).await).await?;
94 if action == "get" {
95 name_window(&mut answer, &now.window);
96 }
97 Ok(answer)
98}
99
100fn name_window(answer: &mut Value, id: &str) {
103 let Some(a) = answer.as_object_mut() else { return };
104 let w = a.entry("window").or_insert_with(|| json!({}));
105 match w.as_object_mut() {
106 Some(m) => {
107 m.insert("id".into(), json!(id));
108 }
109 None => *w = json!({ "id": id }),
110 }
111}
112
113pub(super) async fn get(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
114 run(state, caller, "get", params).await
115}
116
117pub(super) async fn check(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
118 run(state, caller, "check", params).await
119}
120
121pub(super) async fn set(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
122 run(state, caller, "set", params).await
123}
124
125pub(super) async fn fit(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
126 run(state, caller, "fit", params).await
127}
128
129pub(super) async fn reset(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
130 run(state, caller, "reset", params).await
131}
132
133pub(super) async fn undo(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
134 run(state, caller, "undo", params).await
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 fn now() -> Showing {
142 Showing { window: "w1".into(), tab: "t1".into(), pane: "b1".into() }
143 }
144
145 #[test]
146 fn a_call_without_the_window_and_tab_it_was_given_is_refused() {
147 for p in [json!({}), json!({ "window": "w1" }), json!({ "tab": "t1" }), json!({ "window": " ", "tab": "t1" })] {
148 assert_eq!(check_target(&now(), &p).unwrap_err().code, "window_and_tab_required", "{p}");
149 }
150 }
151
152 #[test]
153 fn a_tab_that_is_no_longer_showing_is_refused_and_the_current_one_is_named() {
154 for p in [json!({ "window": "w1", "tab": "t2" }), json!({ "window": "w2", "tab": "t1" })] {
155 let e = check_target(&now(), &p).unwrap_err();
156 assert_eq!(e.code, "tab_changed");
157 assert!(e.message.contains("t1") && e.message.contains("w1"), "{}", e.message);
158 }
159 assert!(check_target(&now(), &json!({ "window": "w1", "tab": "t1" })).is_ok());
160 }
161
162 #[test]
163 fn the_local_action_gets_the_params_without_the_address() {
164 let b = body_of(&json!({ "window": "w1", "tab": "t1", "target": "pane", "block": "b1", "value": 0.8 }));
165 assert_eq!(b, json!({ "target": "pane", "block": "b1", "value": 0.8 }));
166 }
167
168 #[test]
169 fn reads_of_the_screen_need_an_approved_install_and_changes_need_one_too() {
170 for (op, changes) in [("zoom.get", false), ("zoom.check", false), ("zoom.set", true), ("zoom.fit", true), ("zoom.reset", true), ("zoom.undo", true)] {
171 let o = super::super::lookup(op).unwrap_or_else(|| panic!("{op} is not an operation"));
172 assert_eq!((o.changes_state, o.needs_approved_install), (changes, true), "{op}");
173 }
174 }
175
176 #[test]
177 fn a_get_names_the_window_beside_its_zoom_not_in_place_of_it() {
178 let mut a = json!({ "ok": true, "window": { "chrome": { "value": 1.2 } }, "tab": { "id": "t1" } });
179 name_window(&mut a, "w1");
180 assert_eq!(a["window"], json!({ "id": "w1", "chrome": { "value": 1.2 } }));
181 let mut b = json!({ "ok": true, "panes": [] });
182 name_window(&mut b, "w1");
183 assert_eq!(b["window"], json!({ "id": "w1" }));
184 }
185
186 #[test]
187 fn the_write_limit_over_host_is_lower_than_a_local_agent_s() {
188 assert!(REMOTE_WRITES_PER_MINUTE < 30);
189 }
190}