Skip to main content

agentmux_srv_core/backend/layout/
place.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where a pane sits in its tab, read from the tab's layout tree: its rectangle as fractions of the tab's area, and
5//! the edge it is on. The tree is the one place a pane's size is kept, so this is the answer for anything that needs
6//! a pane's place without a screen (a pinned pane unpinned into another tab, an agent asking where a pane is). It is
7//! the share each pane's flex size gives it; the gap between panes and a minimized pane's chip are the page's to draw.
8
9use agentmux_common::{FlexDirection, LayoutEdge, LayoutNode};
10
11/// A rectangle as fractions (0 to 1) of the tab's area.
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct FracRect {
14    pub left: f64,
15    pub top: f64,
16    pub width: f64,
17    pub height: f64,
18}
19
20impl FracRect {
21    const WHOLE: Self = Self { left: 0.0, top: 0.0, width: 1.0, height: 1.0 };
22}
23
24/// How near 1 a share must be to count as the whole of an axis: flex sizes are stored to two decimals.
25const SPANS: f64 = 0.999;
26
27/// The rectangle of every node of `root`'s tab, parents before children (the root is the whole area). A node's share of
28/// its parent's axis is its stored flex size over the sum of its siblings'; the stored tree is the only input, so a
29/// maximized pane and a minimized chip (display modes drawn over a tile) leave every rectangle as it is. The page's twin
30/// is `frontend/layout/lib/rectsOf.ts`; both are checked against `layout-rects-vectors.json`.
31pub fn rects_of(root: &LayoutNode) -> Vec<(String, FracRect)> {
32    fn walk(node: &LayoutNode, rect: FracRect, out: &mut Vec<(String, FracRect)>) {
33        out.push((node.id.clone(), rect));
34        let total: f64 = node.children.iter().map(|c| f64::from(c.size.max(0.0))).sum();
35        let row = node.flex_direction == FlexDirection::Row;
36        let mut before = 0.0;
37        for child in &node.children {
38            let share = if total > 0.0 { f64::from(child.size.max(0.0)) / total } else { 1.0 / node.children.len() as f64 };
39            let child_rect = if row {
40                FracRect { left: rect.left + before * rect.width, width: share * rect.width, ..rect }
41            } else {
42                FracRect { top: rect.top + before * rect.height, height: share * rect.height, ..rect }
43            };
44            walk(child, child_rect, out);
45            before += share;
46        }
47    }
48    let mut out = Vec::new();
49    walk(root, FracRect::WHOLE, &mut out);
50    out
51}
52
53/// The rectangle of node `node_id` in `root`'s tab; none when the tree does not hold it.
54pub fn frac_rect_of(root: &LayoutNode, node_id: &str) -> Option<FracRect> {
55    rects_of(root).into_iter().find(|(id, _)| id == node_id).map(|(_, rect)| rect)
56}
57
58/// One piece of the free space around a pane's rectangle: the subtree of the pane's own tab that fills it.
59#[derive(Debug, Clone, PartialEq)]
60pub struct Slot {
61    /// The id of the subtree (a pane, a stack, or a split of them) that fills this slot in the pane's own tab.
62    pub node_id: String,
63    pub rect: FracRect,
64}
65
66/// A pane's rectangle `rect` in its tab, and the `slots` the rest of that tab's area is cut into.
67#[derive(Debug, Clone, PartialEq)]
68pub struct Frame {
69    pub rect: FracRect,
70    /// The sibling subtrees along the path from the root to the pane, outermost first and in their order in the tree. Each
71    /// is the one the pane's own tab draws in that slot (the origin assignment), so the tab draws what it drew before the
72    /// pane left. The slots and `rect` tile the whole area, with no gap and no overlap.
73    pub slots: Vec<Slot>,
74}
75
76/// The frame of node `node_id` in `root`'s tab (SPEC_PIN_TRANSFORM_FACILITY_2026_12_02.md §3): its rectangle, and the free
77/// space around it cut into rectangles by the splits on the path from the root to it. In `[a | [b / c]]` the frame of `c`
78/// is the bottom right corner and two slots, `a`'s column and `b`'s cell; the frame of `a` is its column and one slot, the
79/// rest (a strip). A stack is one node, so it is framed whole. None when the tree does not hold the node, or the node is
80/// the root (a tab with nothing around it to frame).
81pub fn frame_for(root: &LayoutNode, node_id: &str) -> Option<Frame> {
82    fn path<'a>(node: &'a LayoutNode, id: &str, out: &mut Vec<&'a LayoutNode>) -> bool {
83        out.push(node);
84        if node.id == id || node.children.iter().any(|c| path(c, id, out)) {
85            return true;
86        }
87        out.pop();
88        false
89    }
90    let mut nodes = Vec::new();
91    if !path(root, node_id, &mut nodes) || nodes.len() < 2 {
92        return None;
93    }
94    let rects = rects_of(root);
95    let rect_of = |id: &str| rects.iter().find(|(r, _)| r == id).map(|(_, rect)| *rect);
96    let mut slots = Vec::new();
97    for pair in nodes.windows(2) {
98        let (parent, on_path) = (pair[0], pair[1]);
99        for sibling in parent.children.iter().filter(|c| c.id != on_path.id) {
100            slots.push(Slot { node_id: sibling.id.clone(), rect: rect_of(&sibling.id)? });
101        }
102    }
103    Some(Frame { rect: rect_of(node_id)?, slots })
104}
105
106/// The edge of the tab's area a pane at `rect` belongs to, and how thick a band across that edge it makes (a fraction
107/// of the area). A pane that runs the whole length of an edge (a full-height column, a full-width row) is on one of
108/// those edges, the nearer; any other pane on its nearest edge. On a tie: left, top, right, bottom.
109pub fn edge_band_of(rect: FracRect) -> (LayoutEdge, f64) {
110    let full_height = rect.height >= SPANS;
111    let full_width = rect.width >= SPANS;
112    let gaps = [
113        (LayoutEdge::Left, rect.left, full_height, rect.width),
114        (LayoutEdge::Top, rect.top, full_width, rect.height),
115        (LayoutEdge::Right, 1.0 - (rect.left + rect.width), full_height, rect.width),
116        (LayoutEdge::Bottom, 1.0 - (rect.top + rect.height), full_width, rect.height),
117    ];
118    let spanning = gaps.iter().any(|g| g.2);
119    let mut best = None::<(LayoutEdge, f64, f64)>;
120    for (edge, gap, spans, thick) in gaps {
121        if spanning && !spans {
122            continue;
123        }
124        if best.is_none_or(|b| gap < b.1 - 1e-9) {
125            best = Some((edge, gap, thick));
126        }
127    }
128    let (edge, _, thick) = best.expect("four edges were offered");
129    (edge, thick)
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use agentmux_common::LayoutNodeData;
136
137    fn leaf(id: &str, size: f32) -> LayoutNode {
138        LayoutNode { id: id.into(), size, data: Some(LayoutNodeData { block_id: id.into(), ..Default::default() }), ..Default::default() }
139    }
140
141    fn branch(id: &str, dir: FlexDirection, size: f32, children: Vec<LayoutNode>) -> LayoutNode {
142        LayoutNode { id: id.into(), flex_direction: dir, size, children, ..Default::default() }
143    }
144
145    /// `[a | [b / c]]`: a is a third of the width, b is the top 40% of the rest.
146    fn three() -> LayoutNode {
147        branch("root", FlexDirection::Row, 10.0, vec![leaf("a", 10.0), branch("right", FlexDirection::Column, 20.0, vec![leaf("b", 4.0), leaf("c", 6.0)])])
148    }
149
150    fn close(a: f64, b: f64) -> bool {
151        (a - b).abs() < 1e-9
152    }
153
154    #[test]
155    fn rects_follow_the_flex_sizes() {
156        let tree = three();
157        let a = frac_rect_of(&tree, "a").unwrap();
158        assert!(close(a.left, 0.0) && close(a.top, 0.0) && close(a.width, 1.0 / 3.0) && close(a.height, 1.0), "{a:?}");
159        let c = frac_rect_of(&tree, "c").unwrap();
160        assert!(close(c.left, 1.0 / 3.0) && close(c.top, 0.4) && close(c.width, 2.0 / 3.0) && close(c.height, 0.6), "{c:?}");
161        assert_eq!(frac_rect_of(&tree, "root"), Some(FracRect::WHOLE));
162        assert_eq!(frac_rect_of(&tree, "gone"), None);
163    }
164
165    #[test]
166    fn a_lone_pane_is_the_whole_area() {
167        assert_eq!(frac_rect_of(&leaf("a", 10.0), "a"), Some(FracRect::WHOLE));
168    }
169
170    #[test]
171    fn a_pane_that_runs_an_edge_is_a_band_on_it_at_its_own_thickness() {
172        let tree = three();
173        let (edge, thick) = edge_band_of(frac_rect_of(&tree, "a").unwrap());
174        assert!(edge == LayoutEdge::Left && close(thick, 1.0 / 3.0), "{edge:?} {thick}");
175        let right = FracRect { left: 0.75, top: 0.0, width: 0.25, height: 1.0 };
176        assert_eq!(edge_band_of(right), (LayoutEdge::Right, 0.25));
177        let bottom = FracRect { left: 0.0, top: 0.8, width: 1.0, height: 0.2 };
178        let (edge, thick) = edge_band_of(bottom);
179        assert!(edge == LayoutEdge::Bottom && close(thick, 0.2), "{edge:?} {thick}");
180    }
181
182    #[test]
183    fn a_pane_in_a_split_goes_to_its_nearest_edge() {
184        let tree = three();
185        // b: right two thirds, top 40%. It touches the top and the right; the top wins the tie.
186        let (edge, thick) = edge_band_of(frac_rect_of(&tree, "b").unwrap());
187        assert!(edge == LayoutEdge::Top && close(thick, 0.4), "{edge:?} {thick}");
188        let (edge, thick) = edge_band_of(frac_rect_of(&tree, "c").unwrap());
189        assert!(edge == LayoutEdge::Right && close(thick, 2.0 / 3.0), "{edge:?} {thick}");
190        let middle = FracRect { left: 0.1, top: 0.3, width: 0.3, height: 0.3 };
191        assert_eq!(edge_band_of(middle).0, LayoutEdge::Left);
192    }
193
194    #[test]
195    fn a_full_height_pane_is_not_put_on_the_top_though_it_touches_it() {
196        // A middle column: it touches the top and the bottom, and runs the left and right edges' length.
197        let column = FracRect { left: 0.5, top: 0.0, width: 0.2, height: 1.0 };
198        assert_eq!(edge_band_of(column).0, LayoutEdge::Right);
199    }
200
201    // ── Frames ──────────────────────────────────────────────────────────────────
202
203    fn slot_ids(frame: &Frame) -> Vec<&str> {
204        frame.slots.iter().map(|s| s.node_id.as_str()).collect()
205    }
206
207    fn area(r: FracRect) -> f64 {
208        r.width * r.height
209    }
210
211    fn overlap(a: FracRect, b: FracRect) -> f64 {
212        let w = (a.left + a.width).min(b.left + b.width) - a.left.max(b.left);
213        let h = (a.top + a.height).min(b.top + b.height) - a.top.max(b.top);
214        if w > 1e-9 && h > 1e-9 { w * h } else { 0.0 }
215    }
216
217    /// The frame and its slots tile the whole area: their areas add up to 1 and no two share any.
218    fn assert_tiles(frame: &Frame) {
219        let all: Vec<FracRect> = std::iter::once(frame.rect).chain(frame.slots.iter().map(|s| s.rect)).collect();
220        assert!(close(all.iter().map(|r| area(*r)).sum::<f64>(), 1.0), "{all:?}");
221        for (i, a) in all.iter().enumerate() {
222            for b in &all[i + 1..] {
223                assert!(overlap(*a, *b) == 0.0, "{a:?} overlaps {b:?}");
224            }
225        }
226    }
227
228    #[test]
229    fn a_pane_that_runs_an_edge_has_one_slot_the_strip_beside_it() {
230        let frame = frame_for(&three(), "a").unwrap();
231        assert!(close(frame.rect.width, 1.0 / 3.0) && close(frame.rect.height, 1.0), "{:?}", frame.rect);
232        assert_eq!(slot_ids(&frame), ["right"]);
233        let strip = frame.slots[0].rect;
234        assert!(close(strip.left, 1.0 / 3.0) && close(strip.width, 2.0 / 3.0) && close(strip.height, 1.0), "{strip:?}");
235        assert_tiles(&frame);
236    }
237
238    #[test]
239    fn a_corner_pane_has_a_slot_for_each_split_on_its_path() {
240        // c is the bottom right corner: a's column and b's cell are what is left.
241        let frame = frame_for(&three(), "c").unwrap();
242        assert_eq!(slot_ids(&frame), ["a", "b"]);
243        let [a, b] = [frame.slots[0].rect, frame.slots[1].rect];
244        assert!(close(a.width, 1.0 / 3.0) && close(a.height, 1.0), "{a:?}");
245        assert!(close(b.left, 1.0 / 3.0) && close(b.top, 0.0) && close(b.width, 2.0 / 3.0) && close(b.height, 0.4), "{b:?}");
246        assert_tiles(&frame);
247    }
248
249    #[test]
250    fn a_middle_pane_has_a_slot_on_each_side_and_the_first_and_last_have_one_side() {
251        let row = branch("r", FlexDirection::Row, 10.0, vec![leaf("x", 5.0), leaf("m", 10.0), leaf("y", 5.0)]);
252        let middle = frame_for(&row, "m").unwrap();
253        assert_eq!(slot_ids(&middle), ["x", "y"]);
254        assert!(close(middle.rect.left, 0.25) && close(middle.rect.width, 0.5), "{:?}", middle.rect);
255        assert_tiles(&middle);
256        let first = frame_for(&row, "x").unwrap();
257        assert_eq!(slot_ids(&first), ["m", "y"]);
258        assert_tiles(&first);
259        let last = frame_for(&row, "y").unwrap();
260        assert_eq!(slot_ids(&last), ["x", "m"]);
261        assert_tiles(&last);
262    }
263
264    #[test]
265    fn a_stack_is_framed_whole_like_any_pane() {
266        let mut stack = leaf("s", 10.0);
267        stack.data = Some(LayoutNodeData { block_id: "b2".into(), block_stack: vec!["b1".into(), "b2".into()], active_block_id: "b2".into(), ..Default::default() });
268        let tree = branch("r", FlexDirection::Row, 10.0, vec![leaf("a", 10.0), stack]);
269        let frame = frame_for(&tree, "s").unwrap();
270        assert_eq!(slot_ids(&frame), ["a"]);
271        assert!(close(frame.rect.left, 0.5) && close(frame.rect.width, 0.5), "{:?}", frame.rect);
272        assert_tiles(&frame);
273    }
274
275    #[test]
276    fn a_slot_is_the_whole_subtree_beside_the_pane_not_its_panes() {
277        // Pinning a leaves one slot that holds the split [b / c] as one: the origin tab draws it as it drew it.
278        let frame = frame_for(&three(), "a").unwrap();
279        assert_eq!(frame.slots, vec![Slot { node_id: "right".into(), rect: frac_rect_of(&three(), "right").unwrap() }]);
280        // A split is framed like a pane: pinning [b / c] as a whole leaves a's column.
281        assert_eq!(frame_for(&three(), "right").map(|f| f.slots.len()), Some(1));
282    }
283
284    #[test]
285    fn every_pane_of_every_case_tile_has_a_frame_that_tiles_the_area() {
286        for (name, tree) in rects_cases() {
287            for (id, _) in rects_of(&tree) {
288                match frame_for(&tree, &id) {
289                    Some(frame) => assert_tiles(&frame),
290                    None => assert_eq!(id, tree.id, "{name}: only the root has no frame"),
291                }
292            }
293        }
294    }
295
296    #[test]
297    fn no_frame_for_the_root_a_lone_pane_or_a_node_the_tree_does_not_hold() {
298        assert_eq!(frame_for(&three(), "root"), None);
299        assert_eq!(frame_for(&leaf("a", 10.0), "a"), None);
300        assert_eq!(frame_for(&three(), "gone"), None);
301    }
302
303    // ── Vectors shared with the frontend (`layoutRectsVectors.test.ts`) ──────────
304
305    const RECTS_VECTORS: &str = "../../frontend/layout/tests/fixtures/layout-rects-vectors.json";
306
307    fn sized(mut node: LayoutNode, size: f32) -> LayoutNode {
308        node.size = size;
309        node
310    }
311
312    fn minimized(mut node: LayoutNode) -> LayoutNode {
313        node.minimized = true;
314        node
315    }
316
317    fn rects_cases() -> Vec<(&'static str, LayoutNode)> {
318        let row = |id: &str, size: f32, kids: Vec<LayoutNode>| branch(id, FlexDirection::Row, size, kids);
319        let col = |id: &str, size: f32, kids: Vec<LayoutNode>| branch(id, FlexDirection::Column, size, kids);
320        vec![
321            ("a lone pane", leaf("a", 10.0)),
322            ("two side by side, even", row("r", 10.0, vec![leaf("a", 10.0), leaf("b", 10.0)])),
323            ("three in a row, uneven", row("r", 10.0, vec![leaf("a", 5.0), leaf("b", 10.0), leaf("c", 20.0)])),
324            ("a column of three", col("r", 10.0, vec![leaf("a", 10.0), leaf("b", 10.0), leaf("c", 10.0)])),
325            ("a, then b over c", three()),
326            (
327                "three levels deep",
328                row("r", 10.0, vec![leaf("a", 10.0), col("s", 10.0, vec![leaf("b", 10.0), row("t", 20.0, vec![leaf("c", 3.0), leaf("d", 7.0)])]), leaf("e", 10.0)]),
329            ),
330            (
331                "a minimized pane keeps its stored tile",
332                row("r", 10.0, vec![leaf("a", 10.0), col("s", 10.0, vec![minimized(leaf("b", 4.0)), leaf("c", 6.0)])]),
333            ),
334            // Sizes exact in f32, so the JSON the page reads is the number srv used.
335            ("sizes that are not whole", row("r", 10.0, vec![leaf("a", 0.75), leaf("b", 2.25), leaf("c", 1.0)])),
336            ("a zero size counts as no share", row("r", 10.0, vec![leaf("a", 0.0), leaf("b", 10.0)])),
337            ("all sizes zero share evenly", row("r", 10.0, vec![leaf("a", 0.0), leaf("b", 0.0), leaf("c", 0.0), leaf("d", 0.0)])),
338        ]
339    }
340
341    fn rects_vectors_json() -> serde_json::Value {
342        let cases: Vec<serde_json::Value> = rects_cases()
343            .into_iter()
344            .map(|(name, tree)| {
345                let rects: Vec<serde_json::Value> = rects_of(&tree)
346                    .into_iter()
347                    .map(|(id, r)| serde_json::json!({"id": id, "left": r.left, "top": r.top, "width": r.width, "height": r.height}))
348                    .collect();
349                serde_json::json!({"name": name, "tree": tree, "rects": rects})
350            })
351            .collect();
352        serde_json::json!({
353            "about": "Generated by crates/srv-core/src/backend/layout/place.rs (srv's rectangles for each tree). Regenerate with UPDATE_LAYOUT_RECTS_VECTORS=1 cargo test -p agentmux-srv-core rects_vectors.",
354            "cases": cases,
355        })
356    }
357
358    #[test]
359    fn rects_vectors_match_the_committed_file() {
360        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(RECTS_VECTORS);
361        let generated = rects_vectors_json();
362        // One case per line: a reviewable diff. Compared as text: serde_json's parser, without its float_roundtrip
363        // feature, can read a printed f64 one step off, so a parsed comparison would call the file stale.
364        let lines: Vec<String> = generated["cases"].as_array().unwrap().iter().map(|v| v.to_string()).collect();
365        let text = format!("{{\"about\":{},
366\"cases\":[
367{}
368]}}
369", generated["about"], lines.join(",
370"));
371        if std::env::var_os("UPDATE_LAYOUT_RECTS_VECTORS").is_some() {
372            std::fs::write(&path, &text).unwrap();
373        }
374        let committed = std::fs::read_to_string(&path)
375            .unwrap_or_else(|e| panic!("{}: {e}; generate it with UPDATE_LAYOUT_RECTS_VECTORS=1", path.display()))
376            .replace("
377", "
378");
379        assert!(
380            committed == text,
381            "{} is stale: regenerate it with UPDATE_LAYOUT_RECTS_VECTORS=1 cargo test -p agentmux-srv-core rects_vectors",
382            path.display()
383        );
384    }
385
386    #[test]
387    fn every_node_has_a_rectangle_parents_first_and_the_root_is_the_whole_area() {
388        let all = rects_of(&three());
389        assert_eq!(all.iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(), ["root", "a", "right", "b", "c"]);
390        assert_eq!(all[0].1, FracRect::WHOLE);
391    }
392}