Skip to main content

agentmux_srv/server/
pane_place.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's `resize`, `move` and `place` of a floating pane it opened, and where each such pane is, for
5//! `Pane layout` (docs/specs/SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md §2.2, §2.3, §2.4, §3).
6//!
7//! srv cannot reach a window's screen, so it asks the floating window itself, in the `placefloatingpane`
8//! event, and the window answers with `pane.floatplaced`, the same request, wait and answer an open uses
9//! (`app_api::floater_place`). The window resolves the request against the work area of its own monitor,
10//! sets its rect without raising or activating it, and says where it went. An agent acts only on a pane
11//! its opener record names it for (`pane_openers`).
12
13use 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
23/// How long `Pane layout` waits for a floating window to say where it is.
24const MEASURE_WAIT: Duration = Duration::from_secs(2);
25
26/// The refusal for a pane the caller did not open.
27pub(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
30/// Why `agent` may not resize, move, place, dock or float `block_id`: it did not open it, or it is still a background
31/// session (kept above every display until `Browser show` shows it, which holds the caps a shown pane is under).
32pub(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/// What a `Pane` placement action does to the window.
41#[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    /// What the window leaves as it is: a resize its position, a move its size.
59    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
68/// The action and its arguments, checked: each action takes what it changes and refuses the rest, in words
69/// that say which action to use instead. The request comes back as the floating-open shape the shared checks read.
70pub(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/// What the window did with a question.
96#[derive(Debug)]
97pub(crate) enum Asked {
98    /// The window said it could not.
99    Failed(String),
100    /// The window did not answer in time (hidden, or still starting).
101    NoAnswer,
102}
103
104/// The window of the floating pane `block_id`: the srv window row of the workspace it is alone in.
105pub(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
111/// Ask the floating window `win` to apply `place` (or, with none, to say where it is) and wait for its answer.
112pub(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    // Registered before the window is told, so an answer cannot beat the waiter.
122    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
140/// Where `agent` stands with `block_id`: refused with the status and text the agent gets, or the window to ask.
141async 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
156/// `POST /api/v1/pane/place` — an agent's `resize`, `move` or `place` of a floating pane it opened. Answers with
157/// where the window is now (`placed`, in CSS pixels from the work area's top-left, `clamped` when it had to be
158/// pulled in).
159pub(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    // Docking and floating move the pane between a tab and a window of its own (`pane_dock`); the rest set a rect.
169    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        // Pinning a pane to the window (`pane_pin`): the same shelf the person's thumbtack uses.
173        "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    // The same ten a minute as an open, so a loop of placements is stopped.
186    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
199/// Whether the person tacked the floating pane `block_id` (its header's always-on-top pin): the block's meta says so.
200fn 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
204/// `Pane layout`'s report of the floating panes agents opened: each gets `floating: true` and, from its window, `rect`
205/// (`x`, `y`, `width`, `height` in CSS pixels from the work area's top-left, and `display_scale`) and `always_on_top` (the person's tack). A window that
206/// does not answer gets `rect: null` and the reason. Panes nobody opened as a floater are left as they are.
207pub(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        // A floating window is alone in its own tab: its `rect` says how big it is, a share of that tab would not.
238        if let Some(o) = pane.as_object_mut() {
239            o.remove("share");
240        }
241        // The tack is the block's own meta, which the host writes through (`set_floating_always_on_top`).
242        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;