Skip to main content

agentmux_srv/server/
pane_measure.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How big each docked pane is drawn, for `Pane layout` (docs/specs/SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md ยง2.3).
5//!
6//! A docked pane's pixel size is a layout result that only the window knows, so `Pane layout` asks each window for the
7//! panes of the tab it shows, in a `measurepanes` event, and the window answers with `pane.floatplaced` and `sizes` (the
8//! same request, wait and answer the floating panes use). A pane the window does not draw (its tab is not showing, the
9//! window is hidden or still starting) gets `size: null` and the reason, never a made-up size. `share` (the layout as
10//! stored) needs no window and is reported either way.
11
12use std::collections::HashMap;
13use std::sync::{Mutex, OnceLock};
14use std::time::Duration;
15
16use super::*;
17use crate::backend::mps_events::{MeasurePanes, MeasurePanesEvent};
18use crate::backend::rpc_types::MeasuredPane;
19
20/// How long `Pane layout` waits for a window to say how big its panes are.
21const WAIT: Duration = Duration::from_secs(2);
22
23/// What a window's answer is held in until the call that asked takes it.
24type Waiters = Mutex<HashMap<String, tokio::sync::oneshot::Sender<Vec<MeasuredPane>>>>;
25
26fn waiters() -> &'static Waiters {
27    static W: OnceLock<Waiters> = OnceLock::new();
28    W.get_or_init(Default::default)
29}
30
31/// A window's answer (`pane.floatplaced` with `sizes`). Whether a call was still waiting for it.
32pub(crate) fn answered(request_id: &str, sizes: Vec<MeasuredPane>) -> bool {
33    let tx = waiters().lock().unwrap_or_else(|e| e.into_inner()).remove(request_id);
34    tx.is_some_and(|tx| tx.send(sizes).is_ok())
35}
36
37/// Ask the window `window_id` how big it draws `blocks`, and wait for its answer.
38async fn ask(state: &AppState, window_id: &str, blocks: Vec<String>) -> Option<Vec<MeasuredPane>> {
39    let id = uuid::Uuid::new_v4().to_string();
40    // Registered before the window is told, so an answer cannot beat the waiter.
41    let (tx, rx) = tokio::sync::oneshot::channel();
42    waiters().lock().unwrap_or_else(|e| e.into_inner()).insert(id.clone(), tx);
43    state.broker.publish_event::<MeasurePanes>(&MeasurePanesEvent { request_id: id.clone(), block_ids: blocks }, vec![window_id.to_string()], 0);
44    match tokio::time::timeout(WAIT, rx).await {
45        Ok(Ok(sizes)) => Some(sizes),
46        _ => {
47            waiters().lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
48            None
49        }
50    }
51}
52
53/// The ids of the docked panes of a window's showing tab (a floating pane has a `rect`, not a size), or none.
54fn showing_panes(window: &serde_json::Value) -> Vec<String> {
55    let tabs = window.get("tabs").and_then(|t| t.as_array()).into_iter().flatten();
56    let showing = tabs.filter(|t| t.get("active").and_then(|a| a.as_bool()) == Some(true));
57    showing
58        .flat_map(|t| t.get("panes").and_then(|p| p.as_array()).into_iter().flatten())
59        .filter(|p| p.get("floating").and_then(|f| f.as_bool()) != Some(true))
60        .filter_map(|p| p.get("block_id").and_then(|b| b.as_str()).map(str::to_string))
61        .collect()
62}
63
64/// A pane's `size` from what its window said: whole CSS pixels, or `None` when the window does not draw it.
65fn size_of(answer: &[MeasuredPane], block: &str) -> Option<(u64, u64)> {
66    let m = answer.iter().find(|m| m.block_id == block)?;
67    match (m.width, m.height) {
68        (Some(w), Some(h)) if w > 0.0 && h > 0.0 => Some((w.round() as u64, h.round() as u64)),
69        _ => None,
70    }
71}
72
73/// Put `size` (`{ width, height }`, CSS pixels as drawn) on every docked pane of each window's showing tab, from the
74/// window's own answer; any other docked pane, and any whose window does not answer, gets `size: null` and why.
75pub(super) async fn report_docked(state: &AppState, layout: &mut serde_json::Value) {
76    let Some(windows) = layout.get_mut("windows").and_then(|w| w.as_array_mut()) else { return };
77    let asked: Vec<(String, Vec<String>)> = windows
78        .iter()
79        .filter_map(|w| Some((w.get("window_id")?.as_str()?.to_string(), showing_panes(w))))
80        .filter(|(_, panes)| !panes.is_empty())
81        .collect();
82    let answers = futures_util::future::join_all(asked.iter().map(|(win, panes)| ask(state, win, panes.clone()))).await;
83    for window in windows.iter_mut() {
84        let win = window.get("window_id").and_then(|w| w.as_str()).map(str::to_string).unwrap_or_default();
85        let showing = asked.iter().position(|(w, _)| *w == win);
86        let answer = showing.and_then(|i| answers[i].as_deref());
87        let tabs = window.get_mut("tabs").and_then(|t| t.as_array_mut()).into_iter().flatten();
88        for tab in tabs {
89            let active = tab.get("active").and_then(|a| a.as_bool()) == Some(true);
90            for pane in tab.get_mut("panes").and_then(|p| p.as_array_mut()).into_iter().flatten() {
91                if pane.get("floating").and_then(|f| f.as_bool()) == Some(true) {
92                    continue;
93                }
94                let block = pane.get("block_id").and_then(|b| b.as_str()).unwrap_or_default().to_string();
95                let measured = if active { answer.and_then(|a| size_of(a, &block)) } else { None };
96                match measured {
97                    Some((w, h)) => pane["size"] = json!({ "width": w, "height": h }),
98                    None => {
99                        pane["size"] = json!(null);
100                        pane["size_unavailable"] = json!(if !active {
101                            "its tab is not showing"
102                        } else if answer.is_none() {
103                            "the window did not answer (it may be hidden or still starting)"
104                        } else {
105                            "the window does not draw this pane now"
106                        });
107                    }
108                }
109            }
110        }
111    }
112}
113
114#[cfg(test)]
115#[path = "pane_measure_tests.rs"]
116mod tests;