1use std::time::Duration;
14
15use agentmux_common::api_types::PanePlaceRequest;
16use agentmux_common::place_args::PlaceArgs;
17
18use super::app_api::floater_place;
19use super::*;
20use crate::backend::mps_events::{PlaceFloatingPane, PlaceFloatingPaneEvent};
21use crate::backend::rpc_types::{CommandPaneOpenData, Placed};
22
23const MEASURE_WAIT: Duration = Duration::from_secs(2);
25
26pub(crate) const NOT_YOURS: &str =
28 "NOT_YOURS: you can place only panes you opened; ask the person to move it, or open your own";
29
30pub(crate) fn placement_refusal(agent: &str, block_id: &str) -> Option<(StatusCode, String)> {
33 if !super::pane_openers::opened_by(block_id, agent) {
34 return Some((StatusCode::FORBIDDEN, NOT_YOURS.to_string()));
35 }
36 super::pane_openers::is_background(block_id)
37 .then(|| (StatusCode::CONFLICT, format!("BACKGROUND_SESSION: {block_id} is a background browser session no screen shows: Browser show makes it a floating pane first")))
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub(crate) enum Op {
43 Resize,
44 Move,
45 Place,
46}
47
48impl Op {
49 fn parse(op: &str) -> Result<Self, String> {
50 match op {
51 "resize" => Ok(Op::Resize),
52 "move" => Ok(Op::Move),
53 "place" => Ok(Op::Place),
54 other => Err(format!("INVALID_ARG: {other:?} is not a placement action: use resize, move, place, dock or float")),
55 }
56 }
57
58 fn keep(self) -> Option<&'static str> {
60 match self {
61 Op::Resize => Some("position"),
62 Op::Move => Some("size"),
63 Op::Place => None,
64 }
65 }
66}
67
68pub(crate) fn check(op: &str, p: &PlaceArgs) -> Result<(Op, CommandPaneOpenData), String> {
71 let op = Op::parse(op)?;
72 let sized = p.width.is_some() || p.height.is_some();
73 let placed = p.spot.is_some() || p.x.is_some() || p.y.is_some();
74 match op {
75 Op::Resize if !sized => return Err("INVALID_ARG: resize needs width and/or height (CSS pixels such as 900, or a share such as \"60%\")".into()),
76 Op::Resize if placed => return Err("INVALID_ARG: resize changes the size only: use move for a position, or place for both".into()),
77 Op::Move if !placed => return Err("INVALID_ARG: move needs spot, or x and y".into()),
78 Op::Move if sized => return Err("INVALID_ARG: move changes the position only: use resize for a size, or place for both".into()),
79 Op::Place if !sized && !placed => return Err("INVALID_ARG: place needs a size, a position, or both".into()),
80 _ => {}
81 }
82 let cmd = CommandPaneOpenData {
83 floating: Some(true),
84 width: p.width.clone(),
85 height: p.height.clone(),
86 spot: p.spot.clone(),
87 x: p.x,
88 y: p.y,
89 ..Default::default()
90 };
91 floater_place::check(&cmd)?;
92 Ok((op, cmd))
93}
94
95#[derive(Debug)]
97pub(crate) enum Asked {
98 Failed(String),
100 NoAnswer,
102}
103
104pub(crate) async fn window_of(state: &AppState, block_id: &str) -> Option<String> {
106 let s = state.srv_state.lock().await;
107 let ws = &s.tabs.get(&s.blocks.get(block_id)?.tab_id)?.workspace_id;
108 s.windows.iter().find(|(_, w)| &w.workspace_id == ws).map(|(id, _)| id.clone())
109}
110
111pub(crate) async fn ask(
113 state: &AppState,
114 win: String,
115 block_id: &str,
116 keep: Option<&str>,
117 place: Option<&CommandPaneOpenData>,
118 wait: Duration,
119) -> Result<Placed, Asked> {
120 let id = uuid::Uuid::new_v4().to_string();
121 let rx = floater_place::expect(&id);
123 let event = PlaceFloatingPaneEvent {
124 request_id: id.clone(),
125 block_id: block_id.to_string(),
126 keep: keep.map(str::to_string),
127 place: place.map(|cmd| floater_place::place_for(cmd, id.clone(), 0, None)),
128 };
129 state.broker.publish_event::<PlaceFloatingPane>(&event, vec![win], 0);
130 match tokio::time::timeout(wait, rx).await {
131 Ok(Ok(Ok(placed))) => Ok(placed),
132 Ok(Ok(Err(why))) => Err(Asked::Failed(why)),
133 _ => {
134 floater_place::forget(&id);
135 Err(Asked::NoAnswer)
136 }
137 }
138}
139
140async fn floater_of(state: &AppState, agent: &str, block_id: &str) -> Result<String, (StatusCode, String)> {
142 if let Some(refusal) = placement_refusal(agent, block_id) {
143 return Err(refusal);
144 }
145 if !super::pane_openers::is_floating(block_id) {
146 return Err((
147 StatusCode::CONFLICT,
148 format!("NOT_FLOATING: {block_id} is docked in a tab, not a floating window: open a pane with floating: true to place it"),
149 ));
150 }
151 window_of(state, block_id).await.ok_or_else(|| {
152 (StatusCode::CONFLICT, format!("NOT_FLOATING: the floating window of {block_id} is not open (the person may have closed it)"))
153 })
154}
155
156pub(super) async fn handle_pane_place(
160 State(state): State<AppState>,
161 caller: Option<axum::Extension<super::caller::Caller>>,
162 Json(req): Json<PanePlaceRequest>,
163) -> impl IntoResponse {
164 let refuse = |status: StatusCode, text: String| (status, Json(json!({ "error": text }))).into_response();
165 let Some(agent) = caller.as_ref().and_then(|c| c.0.uid()).map(str::to_string) else {
166 return refuse(StatusCode::FORBIDDEN, "an agent known by its token places its own panes; the person drags a window".into());
167 };
168 match req.op.as_str() {
170 "dock" => return super::pane_dock::dock(&state, &agent, &req).await,
171 "float" => return super::pane_dock::float(&state, &agent, &req).await,
172 "pin" => return super::pane_pin::pin(&state, &agent, &req).await,
174 "unpin" => return super::pane_pin::unpin(&state, &agent, &req).await,
175 _ => {}
176 }
177 let (op, cmd) = match check(&req.op, &req.place) {
178 Ok(x) => x,
179 Err(e) => return refuse(StatusCode::BAD_REQUEST, e),
180 };
181 let win = match floater_of(&state, &agent, &req.target_id).await {
182 Ok(w) => w,
183 Err((status, text)) => return refuse(status, text),
184 };
185 if let Err(text) = super::deeplink_guard::check_place_rate(&agent) {
187 return refuse(StatusCode::TOO_MANY_REQUESTS, text);
188 }
189 match ask(&state, win, &req.target_id, op.keep(), Some(&cmd), floater_place::WAIT).await {
190 Ok(placed) => (StatusCode::OK, Json(json!({ "pane": req.target_id, "placed": placed }))).into_response(),
191 Err(Asked::Failed(why)) => refuse(StatusCode::BAD_GATEWAY, format!("the floating window could not do it: {why}")),
192 Err(Asked::NoAnswer) => refuse(
193 StatusCode::GATEWAY_TIMEOUT,
194 "NO_ANSWER: the floating window did not answer (it may be hidden or still starting): try again".into(),
195 ),
196 }
197}
198
199fn is_tacked(mstore: &crate::backend::storage::store::Store, block_id: &str) -> bool {
201 mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten().is_some_and(|b| b.meta.get("pane:floating_ontop").and_then(|v| v.as_bool()) == Some(true))
202}
203
204pub(super) async fn report_floaters(state: &AppState, layout: &mut serde_json::Value) {
208 let Some(windows) = layout.get_mut("windows").and_then(|w| w.as_array_mut()) else { return };
209 let panes = || {
210 windows
211 .iter()
212 .flat_map(|w| w.get("tabs").and_then(|t| t.as_array()).into_iter().flatten())
213 .flat_map(|t| t.get("panes").and_then(|p| p.as_array()).into_iter().flatten())
214 .filter_map(|p| p.get("block_id").and_then(|b| b.as_str()))
215 .filter(|b| super::pane_openers::is_floating(b))
216 .map(str::to_string)
217 .collect::<Vec<_>>()
218 };
219 let floaters = panes();
220 if floaters.is_empty() {
221 return;
222 }
223 let tacked: Vec<String> = floaters.iter().filter(|b| is_tacked(&state.mstore, b)).cloned().collect();
224 let measured = futures_util::future::join_all(floaters.iter().map(|block| async move {
225 let Some(win) = window_of(state, block).await else { return (block.clone(), None) };
226 (block.clone(), Some(ask(state, win, block, None, None, MEASURE_WAIT).await))
227 }))
228 .await;
229 for pane in windows
230 .iter_mut()
231 .flat_map(|w| w.get_mut("tabs").and_then(|t| t.as_array_mut()).into_iter().flatten())
232 .flat_map(|t| t.get_mut("panes").and_then(|p| p.as_array_mut()).into_iter().flatten())
233 {
234 let Some(block) = pane.get("block_id").and_then(|b| b.as_str()).map(str::to_string) else { continue };
235 let Some((_, answer)) = measured.iter().find(|(b, _)| *b == block) else { continue };
236 pane["floating"] = json!(true);
237 if let Some(o) = pane.as_object_mut() {
239 o.remove("share");
240 }
241 pane["always_on_top"] = json!(tacked.contains(&block));
243 match answer {
244 Some(Ok(p)) => {
245 pane["rect"] = json!({ "x": p.x, "y": p.y, "width": p.width, "height": p.height, "display_scale": p.display_scale });
246 }
247 Some(Err(Asked::Failed(why))) => {
248 pane["rect"] = json!(null);
249 pane["rect_unavailable"] = json!(format!("the window could not say: {why}"));
250 }
251 Some(Err(Asked::NoAnswer)) => {
252 pane["rect"] = json!(null);
253 pane["rect_unavailable"] = json!("the window did not answer (it may be hidden or still starting)");
254 }
255 None => {
256 pane["rect"] = json!(null);
257 pane["rect_unavailable"] = json!("the window is not open");
258 }
259 }
260 }
261}
262
263#[cfg(test)]
264#[path = "pane_place_tests.rs"]
265mod tests;