Skip to main content

agentmux_srv/server/app_api/
floater_place.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What an agent asked for a floating pane, checked here, resolved by the window
5//! (docs/specs/SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md §2.1, §3).
6//!
7//! srv cannot reach a window's screen, so the request goes to the caller's own window in the
8//! `openfloatingpane` event and the window answers with `pane.floatplaced`, the same request, wait and
9//! answer shape `block.reveal` uses. This module checks the arguments, fills the defaults (a browser's
10//! size and place), builds the event's `place` and holds the waits.
11
12use std::collections::HashMap;
13use std::sync::{Mutex, OnceLock};
14use std::time::Duration;
15
16use crate::backend::mps_events::FloaterPlace;
17use crate::backend::rpc_types::{CommandPaneOpenData, Placed};
18
19/// How long an open waits for its window to say where it put the pane. A window that is hidden or still
20/// starting answers late: the open then says `queued`.
21pub(crate) const WAIT: Duration = Duration::from_secs(5);
22
23/// The most floating panes one agent has open at a time.
24pub(crate) const MAX_FLOATERS: usize = 4;
25
26/// A floating browser an agent opens with no size: 1040 x 760 CSS pixels, at most 90% of the work area, flush right.
27const BROWSER_WIDTH: f64 = 1040.0;
28const BROWSER_HEIGHT: f64 = 760.0;
29const BROWSER_MAX_SHARE: f64 = 0.9;
30const BROWSER_SPOT: &str = "right";
31
32/// The named places in the work area.
33pub(crate) const SPOTS: [&str; 9] =
34    ["center", "right", "left", "top", "bottom", "top-right", "top-left", "bottom-right", "bottom-left"];
35
36/// Copies the floating-pane request of `from` onto `to`, for a request that was rebuilt from a fixed field list.
37pub(crate) fn carry_over(from: &CommandPaneOpenData, to: &mut CommandPaneOpenData) {
38    to.floating = from.floating;
39    to.width = from.width.clone();
40    to.height = from.height.clone();
41    to.spot = from.spot.clone();
42    to.x = from.x;
43    to.y = from.y;
44}
45
46/// Whether the request names any placement.
47pub(crate) fn names_placement(cmd: &CommandPaneOpenData) -> bool {
48    cmd.width.is_some() || cmd.height.is_some() || cmd.spot.is_some() || cmd.x.is_some() || cmd.y.is_some()
49}
50
51/// One size argument: a positive number of CSS pixels, or a share of the work area (`"60%"`).
52fn check_size(name: &str, v: &serde_json::Value) -> Result<(), String> {
53    let bad = || format!("INVALID_ARG: {name} is a number of CSS pixels (such as 900) or a share of the work area (such as \"60%\"), not {v}");
54    match v {
55        serde_json::Value::Number(n) => n.as_f64().filter(|f| f.is_finite() && *f > 0.0).map(|_| ()).ok_or_else(bad),
56        serde_json::Value::String(s) => {
57            let share = s.trim().strip_suffix('%').and_then(|n| n.trim().parse::<f64>().ok());
58            share.filter(|p| p.is_finite() && *p > 0.0 && *p <= 100.0).map(|_| ()).ok_or_else(bad)
59        }
60        _ => Err(bad()),
61    }
62}
63
64/// The placement arguments, checked. They place a floating pane, so without `floating: true` they are refused,
65/// and the text says what to add.
66pub(crate) fn check(cmd: &CommandPaneOpenData) -> Result<(), String> {
67    if !names_placement(cmd) {
68        return Ok(());
69    }
70    if cmd.floating != Some(true) {
71        return Err("INVALID_ARG: width, height, spot, x and y place a floating pane: add floating: true".to_string());
72    }
73    if let Some(w) = &cmd.width {
74        check_size("width", w)?;
75    }
76    if let Some(h) = &cmd.height {
77        check_size("height", h)?;
78    }
79    if let Some(spot) = cmd.spot.as_deref() {
80        if !SPOTS.contains(&spot) {
81            return Err(format!("INVALID_ARG: spot {spot:?} is not one of {}", SPOTS.join(", ")));
82        }
83    }
84    match (cmd.x, cmd.y) {
85        (Some(_), None) | (None, Some(_)) => {
86            return Err("INVALID_ARG: x and y go together: give both, or use spot (x and y win over spot)".to_string())
87        }
88        (Some(x), Some(y)) if !(x.is_finite() && y.is_finite()) => return Err("INVALID_ARG: x and y are numbers of CSS pixels".to_string()),
89        _ => {}
90    }
91    Ok(())
92}
93
94/// A floating browser an agent opens with no size is 1040 x 760 flush right, unless the request says otherwise;
95/// each of width, height and the place keeps what the agent gave. Returns the share cap that goes with the default.
96pub(crate) fn browser_defaults(cmd: &mut CommandPaneOpenData) -> Option<f64> {
97    let sized = cmd.width.is_some() || cmd.height.is_some();
98    if cmd.width.is_none() {
99        cmd.width = Some(serde_json::json!(BROWSER_WIDTH));
100    }
101    if cmd.height.is_none() {
102        cmd.height = Some(serde_json::json!(BROWSER_HEIGHT));
103    }
104    if cmd.spot.is_none() && cmd.x.is_none() {
105        cmd.spot = Some(BROWSER_SPOT.to_string());
106        cmd.floater_default_place = true;
107    }
108    (!sized).then_some(BROWSER_MAX_SHARE)
109}
110
111/// A browser open's floating arguments onto the pane request, checked, with a floating browser's defaults. The
112/// opener is the caller's token's UID, as `pane.open` records an agent's pane; the signed id for a caller with none.
113pub(crate) fn for_browser(
114    cmd: &mut CommandPaneOpenData,
115    req: &agentmux_common::api_types::UiBrowserOpenRequest,
116    caller: Option<&crate::server::caller::Caller>,
117) -> Result<(), String> {
118    let place = &req.place;
119    (cmd.width, cmd.height, cmd.spot, cmd.x, cmd.y) = (place.width.clone(), place.height.clone(), place.spot.clone(), place.x, place.y);
120    cmd.opener = Some(caller.and_then(|c| c.uid()).map_or_else(|| req.auth.agent_id.clone(), str::to_string));
121    cmd.floating = req.floating.filter(|f| *f);
122    // A background session is a floating window no screen shows; `visible: false` wins over `floating: false`.
123    if req.visible == Some(false) {
124        if let Some(why) = background_refusal(BACKGROUND_PLATFORM) {
125            return Err(why);
126        }
127        (cmd.floating, cmd.background) = (Some(true), true);
128    }
129    check(cmd)?;
130    // A floating browser with no size is 1040 x 760 flush right, held to 90% of the work area.
131    if cmd.floating == Some(true) {
132        cmd.floater_max_share = browser_defaults(cmd);
133    }
134    Ok(())
135}
136
137/// `agent:floatbrowsers`: the person has chosen that every browser an agent opens floats, unless the open says where
138/// it goes (docs/specs/SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md §4, choice 1). Off by default.
139pub(crate) const SETTING_FLOAT_BROWSERS: &str = "agent:floatbrowsers";
140
141/// Whether a browser open floats by the setting: it is on, the open said nothing about `floating` (an explicit
142/// `floating: false` keeps the browser docked) and named no split, and the agent has room under its cap of four.
143/// A default never refuses an open: at the cap the browser opens docked, as it would with the setting off.
144pub(crate) fn float_default(on: bool, asked: Option<bool>, split: bool, open: usize) -> bool {
145    on && asked.is_none() && !split && open < MAX_FLOATERS
146}
147
148/// Make a browser open float when `agent:floatbrowsers` says so ([`float_default`], and under the shared rate limit
149/// of an agent's floating opens), with a floating browser's defaults. A background session is refused here when it
150/// would pass a cap ([`background_limit`]) or the shared rate limit.
151pub(crate) async fn float_by_setting(state: &crate::server::AppState, cmd: &mut CommandPaneOpenData, asked: Option<bool>) -> Result<(), String> {
152    let Some(agent) = cmd.opener.clone() else { return Ok(()) };
153    if cmd.background {
154        let (mine, all) = (live_background(state, Some(&agent)).await, live_background(state, None).await.len());
155        return background_limit(&mine, all).map_or_else(|| crate::server::deeplink_guard::check_place_rate(&agent), Err);
156    }
157    let on = state.config_watcher.get_settings().extra.get(SETTING_FLOAT_BROWSERS).and_then(serde_json::Value::as_bool).unwrap_or(false);
158    let split = cmd.split_direction.as_deref().is_some_and(|d| !d.is_empty());
159    // The cheap checks first: the rate limit counts only an open that goes on to float.
160    if !on || asked.is_some() || split {
161        return Ok(());
162    }
163    let open = live_floaters(state, &agent).await.len();
164    if float_default(on, asked, split, open) && crate::server::deeplink_guard::check_place_rate(&agent).is_ok() {
165        cmd.floating = Some(true);
166        cmd.floater_max_share = browser_defaults(cmd);
167    }
168    Ok(())
169}
170
171/// The `data` of a browser open's answer: the pane, what it browses as, and for a floating open where its window went.
172pub(crate) fn open_answer(result: &crate::backend::rpc_types::PaneOpenResult, browsing_as: &str) -> serde_json::Value {
173    let mut data = serde_json::json!({ "pane": result.block_id, "browsing_as": browsing_as });
174    if let Some(placed) = &result.placed {
175        data["placed"] = serde_json::json!(placed);
176    }
177    if result.queued {
178        data["queued"] = serde_json::json!(true);
179    }
180    if crate::server::pane_openers::is_background(&result.block_id) {
181        data["background"] = serde_json::json!(true);
182    }
183    data
184}
185
186/// The event's `place` for `cmd`, with the id the window answers with. `cascade` is how many floating panes the
187/// agent already has open; it steps a window only when the agent named no place.
188pub(crate) fn place_for(cmd: &CommandPaneOpenData, request_id: String, cascade: usize, max_share: Option<f64>) -> FloaterPlace {
189    FloaterPlace {
190        request_id,
191        width: cmd.width.clone(),
192        height: cmd.height.clone(),
193        spot: cmd.spot.clone(),
194        x: cmd.x,
195        y: cmd.y,
196        max_share,
197        // A place the agent named is where it goes: only a window with no say in its place steps over.
198        cascade: if (cmd.spot.is_some() || cmd.x.is_some()) && !cmd.floater_default_place { 0 } else { cascade.min(MAX_FLOATERS) as u32 },
199        activate: false,
200        background: cmd.background,
201    }
202}
203
204/// The floating panes `agent` has open now: the ones its record names whose block is still there.
205pub(crate) async fn live_floaters(state: &crate::server::AppState, agent: &str) -> Vec<String> {
206    let named = crate::server::pane_openers::floaters_of(agent);
207    let s = state.srv_state.lock().await;
208    named.into_iter().filter(|b| s.blocks.contains_key(b)).collect()
209}
210
211/// Whether this system keeps a window placed above every display off every screen (checked on Windows and macOS).
212pub(crate) const BACKGROUND_PLATFORM: bool = cfg!(any(windows, target_os = "macos"));
213
214/// The refusal for a background session on a system that cannot keep its window off every screen, or none. Windows and macOS keep a
215/// window placed above every display there (checked live on each); an X11 window manager may move it onto a screen (one did),
216/// so a session is refused there until the window can be kept hidden by other means (the person would see a window the agent said was hidden).
217pub(crate) fn background_refusal(supported: bool) -> Option<String> {
218    (!supported).then(|| "BACKGROUND_UNAVAILABLE: a background session needs a window kept above every display, which this system may not allow; it works on Windows and macOS only for now. Open the page as a floating pane (floating: true) and Browser close it when you are done".to_string())
219}
220
221/// The most background browser sessions one agent holds, and the most on the machine
222/// (docs/specs/SPEC_BACKGROUND_BROWSER_SESSIONS_2026_11_28.md §3).
223pub(crate) const MAX_BACKGROUND_PER_AGENT: usize = 2;
224pub(crate) const MAX_BACKGROUND_PER_MACHINE: usize = 6;
225
226/// The background sessions whose block is still there, of `agent` or (with none) of every agent.
227pub(crate) async fn live_background(state: &crate::server::AppState, agent: Option<&str>) -> Vec<String> {
228    let named = match agent {
229        Some(a) => crate::server::pane_openers::background_of(a),
230        None => crate::server::pane_openers::all_background(),
231    };
232    let s = state.srv_state.lock().await;
233    named.into_iter().filter(|b| s.blocks.contains_key(b)).collect()
234}
235
236/// The refusal for a background session that would pass a cap (`mine` and `all` are the live counts), or none.
237pub(crate) fn background_limit(mine: &[String], all: usize) -> Option<String> {
238    if mine.len() >= MAX_BACKGROUND_PER_AGENT {
239        return Some(format!(
240            "BACKGROUND_LIMIT: you hold {} background browser sessions ({}): Browser close one first, or Browser show it",
241            mine.len(),
242            mine.join(", ")
243        ));
244    }
245    (all >= MAX_BACKGROUND_PER_MACHINE).then(|| format!("BACKGROUND_LIMIT: {all} background browser sessions are open on this machine, the most there can be: try again when one closes"))
246}
247
248/// The refusal for an agent that has [`MAX_FLOATERS`] floating panes open.
249pub(crate) fn limit_text(open: &[String]) -> String {
250    format!(
251        "FLOATER_LIMIT: you have {} floating panes open ({}): dock or close one first",
252        open.len(),
253        open.join(", ")
254    )
255}
256
257/// What the window said.
258pub(crate) type Answer = Result<Placed, String>;
259
260fn waiters() -> &'static Mutex<HashMap<String, tokio::sync::oneshot::Sender<Answer>>> {
261    static W: OnceLock<Mutex<HashMap<String, tokio::sync::oneshot::Sender<Answer>>>> = OnceLock::new();
262    W.get_or_init(Default::default)
263}
264
265/// Wait for the answer to the `openfloatingpane` that carries `request_id`: register before publishing.
266pub(crate) fn expect(request_id: &str) -> tokio::sync::oneshot::Receiver<Answer> {
267    let (tx, rx) = tokio::sync::oneshot::channel();
268    waiters().lock().unwrap_or_else(|e| e.into_inner()).insert(request_id.to_string(), tx);
269    rx
270}
271
272/// Stop waiting for `request_id` (its answer did not come in time).
273pub(crate) fn forget(request_id: &str) {
274    waiters().lock().unwrap_or_else(|e| e.into_inner()).remove(request_id);
275}
276
277/// A window's answer (`pane.floatplaced`). Whether a caller was still waiting for it.
278pub(crate) fn answered(request_id: &str, answer: Answer) -> bool {
279    let tx = waiters().lock().unwrap_or_else(|e| e.into_inner()).remove(request_id);
280    tx.is_some_and(|tx| tx.send(answer).is_ok())
281}
282
283#[cfg(test)]
284#[path = "tests/floater_place_tests.rs"]
285mod tests;