Skip to main content

agentmux_srv/server/
pane_dock.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's `dock` and `float` of a pane it opened (docs/specs/SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md
5//! §2.2, §3): a floating pane goes back into a tab, a docked one gets a window of its own. Both run the tear-off
6//! and redock the person's drag runs (`service::tear_off`), so the pane, its block id and everything that finds it
7//! by that id (the `Browser*` tools, the opener record) are unchanged by the move. Only a pane the caller opened.
8
9use agentmux_common::api_types::PanePlaceRequest;
10
11use super::app_api::floater_place;
12use super::*;
13use crate::backend::obj::Block;
14use crate::backend::rpc_types::{CommandPaneOpenData, PaneOpenResult};
15use crate::backend::service::WebCallType;
16
17fn refuse(status: StatusCode, text: impl Into<String>) -> Response {
18    (status, Json(json!({ "error": text.into() }))).into_response()
19}
20
21/// The tab and workspace a block is in now.
22async fn home_of(state: &AppState, block_id: &str) -> Option<(String, String)> {
23    let s = state.srv_state.lock().await;
24    let tab = s.blocks.get(block_id)?.tab_id.clone();
25    let ws = s.tabs.get(&tab)?.workspace_id.clone();
26    Some((tab, ws))
27}
28
29/// The redock's direction code for a side of the caller's pane (`layout_helpers::queue_target_layout_split`).
30pub(crate) fn split_code(split: &str) -> Option<u8> {
31    match split {
32        "up" => Some(0),
33        "right" => Some(1),
34        "down" => Some(2),
35        "left" => Some(3),
36        _ => None,
37    }
38}
39
40fn service_call(method: &str, args: Vec<serde_json::Value>) -> WebCallType {
41    WebCallType { service: "block".to_string(), method: method.to_string(), uicontext: None, args }
42}
43
44/// Redock the floating pane `target` (in `src`, a tab and its workspace) into `tgt`: beside `beside`'s pane on its
45/// side code, or, with none, where it was torn from when that place can still be found. The pane is no floater after.
46async fn redock_into(
47    state: &AppState,
48    target: &str,
49    src: (&str, &str),
50    tgt: (&str, &str),
51    beside: Option<(&str, u8)>,
52) -> Result<serde_json::Value, String> {
53    // [block, source tab, source workspace, target tab, target workspace, beside block, side, as tab, members, active, to origin]
54    let call = service_call(
55        "RedockFloatingPane",
56        vec![
57            json!(target),
58            json!(src.0),
59            json!(src.1),
60            json!(tgt.0),
61            json!(tgt.1),
62            beside.map_or(serde_json::Value::Null, |(b, _)| json!(b)),
63            beside.map_or(serde_json::Value::Null, |(_, c)| json!(c)),
64            json!(false),
65            json!(null),
66            json!(null),
67            json!(beside.is_none()),
68        ],
69    );
70    let ret = crate::server::service::handle_redock_floating_pane(state, &call).await;
71    if let Some(e) = ret.error {
72        return Err(e);
73    }
74    super::pane_openers::set_floating(target, false);
75    Ok(ret.data.unwrap_or_default())
76}
77
78/// A Stop of the agent `agent_uid`: each floating pane it opened is docked into the tab `home_block` (its own pane)
79/// is in, where it was torn from when that place can still be found. Nothing is closed. Returns how many were docked.
80pub(crate) async fn dock_all(state: &AppState, agent_uid: &str, home_block: &str) -> usize {
81    let Some((tgt_tab, tgt_ws)) = home_of(state, home_block).await else { return 0 };
82    let mut docked = 0;
83    for pane in floater_place::live_floaters(state, agent_uid).await {
84        let Some((src_tab, src_ws)) = home_of(state, &pane).await else { continue };
85        if src_tab == tgt_tab {
86            continue;
87        }
88        match redock_into(state, &pane, (&src_tab, &src_ws), (&tgt_tab, &tgt_ws), None).await {
89            Ok(_) => docked += 1,
90            Err(e) => tracing::warn!(pane = %pane, "agent stop: a floating pane could not be docked: {e}"),
91        }
92    }
93    docked
94}
95
96/// `dock`: a floating pane the caller opened goes back into the caller's own tab, beside the caller's pane on the
97/// side `split` names, or where it was torn from when that place can still be found. The window closes with its
98/// last pane.
99pub(super) async fn dock(state: &AppState, agent: &str, req: &PanePlaceRequest) -> Response {
100    let p = &req.place;
101    if p.width.is_some() || p.height.is_some() || p.spot.is_some() || p.x.is_some() || p.y.is_some() {
102        return refuse(StatusCode::BAD_REQUEST, "INVALID_ARG: dock takes no size or place: it takes split (right, left, down, up) to say which side of your pane, or nothing");
103    }
104    let target = req.target_id.as_str();
105    if let Some((status, text)) = super::pane_place::placement_refusal(agent, target) {
106        return refuse(status, text);
107    }
108    if !super::pane_openers::is_floating(target) {
109        return refuse(StatusCode::CONFLICT, format!("NOT_FLOATING: {target} is already docked in a tab"));
110    }
111    let split = match req.split.as_deref().filter(|s| !s.is_empty()) {
112        None => None,
113        Some(s) => match split_code(s) {
114            Some(code) => Some(code),
115            None => return refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: split {s:?} is not one of right, left, down, up")),
116        },
117    };
118    let Some(own) = req.block_id.as_deref().filter(|b| !b.is_empty()) else {
119        return refuse(StatusCode::BAD_REQUEST, "MISSING_ARG: dock puts the pane in your own tab, and your own pane is not known here");
120    };
121    let (Some((src_tab, src_ws)), Some((tgt_tab, tgt_ws))) = (home_of(state, target).await, home_of(state, own).await) else {
122        return refuse(StatusCode::NOT_FOUND, format!("that pane is gone: {target} or your own pane is no longer in a tab"));
123    };
124    if src_tab == tgt_tab {
125        return refuse(StatusCode::CONFLICT, format!("NOT_FLOATING: {target} is already in your tab"));
126    }
127    let beside = split.map(|c| (own, c));
128    let ret = match redock_into(state, target, (&src_tab, &src_ws), (&tgt_tab, &tgt_ws), beside).await {
129        Ok(data) => data,
130        Err(e) => return refuse(StatusCode::BAD_GATEWAY, format!("the pane could not be docked: {e}")),
131    };
132    let at = ret.get("placed").cloned().unwrap_or(json!(null));
133    (StatusCode::OK, Json(json!({ "pane": target, "docked": true, "tab_id": tgt_tab, "placed_by": at }))).into_response()
134}
135
136/// `float`: a docked pane the caller opened gets a window of its own, placed as an open's `floating` places one
137/// (the same size, spot, x and y; none gives the default, a browser's 1040 x 760 flush right).
138pub(super) async fn float(state: &AppState, agent: &str, req: &PanePlaceRequest) -> Response {
139    match float_pane(state, agent, &req.target_id, &req.place).await {
140        Ok(body) => (StatusCode::OK, Json(body)).into_response(),
141        Err((status, text)) => refuse(status, text),
142    }
143}
144
145/// Float the docked pane `target`, which `agent` opened: the answer of a `float` call, or the status and text it is
146/// refused with. A browser's page is made again in the new window, so it reloads at its address.
147pub(crate) async fn float_pane(
148    state: &AppState,
149    agent: &str,
150    target: &str,
151    place: &agentmux_common::place_args::PlaceArgs,
152) -> Result<serde_json::Value, (StatusCode, String)> {
153    let mut cmd = CommandPaneOpenData {
154        floating: Some(true),
155        opener: Some(agent.to_string()),
156        width: place.width.clone(),
157        height: place.height.clone(),
158        spot: place.spot.clone(),
159        x: place.x,
160        y: place.y,
161        ..Default::default()
162    };
163    floater_place::check(&cmd).map_err(|e| (StatusCode::BAD_REQUEST, e))?;
164    if let Some(refusal) = super::pane_place::placement_refusal(agent, target) {
165        return Err(refusal);
166    }
167    if super::pane_openers::is_floating(target) {
168        return Err((StatusCode::CONFLICT, format!("NOT_DOCKED: {target} is already a floating window: use resize, move or place")));
169    }
170    let Some((src_tab, src_ws)) = home_of(state, target).await else {
171        return Err((StatusCode::NOT_FOUND, format!("that pane is gone: {target} is no longer in a tab")));
172    };
173    let open = floater_place::live_floaters(state, agent).await;
174    if open.len() >= floater_place::MAX_FLOATERS {
175        return Err((StatusCode::TOO_MANY_REQUESTS, floater_place::limit_text(&open)));
176    }
177    super::deeplink_guard::check_place_rate(agent).map_err(|text| (StatusCode::TOO_MANY_REQUESTS, text))?;
178    let view = state.mstore.get::<Block>(target).ok().flatten().map(|b| crate::backend::obj::meta_get_string(&b.meta, "view", "")).unwrap_or_default();
179    if view == "browser" {
180        cmd.floater_max_share = floater_place::browser_defaults(&mut cmd);
181    }
182    let call = service_call("TearOffBlock", vec![json!(target), json!(src_tab), json!(src_ws)]);
183    let ret = crate::server::service::handle_tear_off_block(state, &call).await;
184    if let Some(e) = ret.error {
185        return Err((StatusCode::BAD_GATEWAY, format!("the pane could not be floated: {e}")));
186    }
187    if let Some(updates) = &ret.updates {
188        // The tear-off's updates reach only a window that asked; the others learn of the new workspace here.
189        state.event_bus.broadcast_mux_obj_updates(updates);
190    }
191    let Some(new_ws) = ret.data.as_ref().and_then(|d| d.as_str()).map(str::to_string) else {
192        return Err((StatusCode::BAD_GATEWAY, "the pane could not be floated: no workspace was made for it".to_string()));
193    };
194    super::pane_openers::set_floating(target, true);
195    let mut result = PaneOpenResult::docked(target.to_string(), String::new(), view, false);
196    super::app_api::pane::announce_floater(state, &src_ws, &new_ws, &cmd, &mut result, open.len()).await;
197    let mut body = json!({ "pane": target });
198    if let Some(placed) = &result.placed {
199        body["placed"] = json!(placed);
200    }
201    if result.queued {
202        body["queued"] = json!(true);
203    }
204    Ok(body)
205}
206
207/// A browser handoff that asked for `floating: true`: the pane the person is asked to work in gets a window of its own
208/// first, at a browser's default size and place (docs/specs/SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md §4,
209/// choice 1, opt in: the page is made again in the new window, so it reloads). `None` when the agent did not ask;
210/// else `{ "floated": true }`, or `{ "floated": false, "why": ... }` when the pane stays where it is (it is not
211/// the caller's, the cap of four, the rate limit, a popup window, a pane already waiting on the person): the handoff goes on either way and the banner shows there.
212pub(crate) async fn float_for_handoff(state: &AppState, asked: Option<bool>, agent: Option<&str>, pane: &str, popup: bool) -> Option<serde_json::Value> {
213    if asked != Some(true) {
214        return None;
215    }
216    // Floating makes the page again, which would close a popup window and strand a banner the host could not show.
217    let stays = if popup {
218        Some("the handoff is for a popup window, which stays with its page")
219    } else if super::browser_attention::waiting_on_user(pane).is_some() {
220        Some("the pane is already waiting on the person")
221    } else {
222        None
223    };
224    if let Some(why) = stays {
225        return Some(json!({ "floated": false, "why": why }));
226    }
227    let Some(agent) = agent else { return Some(json!({ "floated": false, "why": "only an agent known by its token floats a pane" })) };
228    if super::pane_openers::opened_by(pane, agent) && super::pane_openers::is_floating(pane) {
229        return Some(json!({ "floated": true }));
230    }
231    Some(match float_pane(state, agent, pane, &Default::default()).await {
232        Ok(_) => json!({ "floated": true }),
233        Err((_, why)) => json!({ "floated": false, "why": why }),
234    })
235}
236
237#[cfg(test)]
238#[path = "pane_dock_tests.rs"]
239mod tests;