Skip to main content

agentmux_srv/server/service/
pane_share.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What fraction of its tab's area each docked pane has, from the layout tree srv holds
5//! (docs/specs/SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md ยง2.3): `Pane layout`'s `share`.
6//!
7//! A node's `size` is a flex unit among its siblings, so a leaf's share is the product, down the path from the root,
8//! of its size over the sum of its siblings' sizes. Panes stacked as tabs of one leaf all have that leaf's share.
9//! It is the layout as stored: what the window draws can differ by gaps and minimum sizes, which the measured pixel
10//! `size` (not part of this module) shows.
11
12use std::collections::HashMap;
13
14use agentmux_common::LayoutNode;
15
16/// The share of the tab (0 to 1) of every block the layout `root` holds.
17pub(crate) fn shares(root: &LayoutNode) -> HashMap<String, f64> {
18    fn walk(node: &LayoutNode, share: f64, out: &mut HashMap<String, f64>) {
19        if node.children.is_empty() {
20            if let Some(data) = &node.data {
21                let stack = if data.block_stack.is_empty() { std::slice::from_ref(&data.block_id) } else { data.block_stack.as_slice() };
22                for block in stack.iter().filter(|b| !b.is_empty()) {
23                    out.insert(block.clone(), share);
24                }
25            }
26            return;
27        }
28        let total: f64 = node.children.iter().map(|c| f64::from(c.size).max(0.0)).sum();
29        let each = 1.0 / node.children.len() as f64;
30        for child in &node.children {
31            let of_parent = if total > 0.0 { f64::from(child.size).max(0.0) / total } else { each };
32            walk(child, share * of_parent, out);
33        }
34    }
35    let mut out = HashMap::new();
36    walk(root, 1.0, &mut out);
37    out
38}
39
40/// A share as `Pane layout` shows it: to three places.
41pub(crate) fn rounded(share: f64) -> f64 {
42    (share * 1000.0).round() / 1000.0
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48    use agentmux_common::{FlexDirection, LayoutNodeData};
49    use serde_json::json;
50
51    fn leaf(block: &str, size: f32) -> LayoutNode {
52        LayoutNode { id: format!("n-{block}"), size, data: Some(LayoutNodeData { block_id: block.into(), ..Default::default() }), ..Default::default() }
53    }
54
55    fn group(direction: FlexDirection, size: f32, children: Vec<LayoutNode>) -> LayoutNode {
56        LayoutNode { id: "g".into(), flex_direction: direction, size, children, ..Default::default() }
57    }
58
59    #[test]
60    fn a_lone_pane_has_the_whole_tab() {
61        assert_eq!(shares(&leaf("a", 1.0))["a"], 1.0);
62    }
63
64    #[test]
65    fn siblings_share_by_their_sizes_and_nested_groups_multiply() {
66        // a takes 2 of 3 of the width; b and c split the rest of it by height, 1 to 3.
67        let root = group(FlexDirection::Row, 1.0, vec![leaf("a", 2.0), group(FlexDirection::Column, 1.0, vec![leaf("b", 1.0), leaf("c", 3.0)])]);
68        let s = shares(&root);
69        assert!((s["a"] - 2.0 / 3.0).abs() < 1e-9, "{s:?}");
70        assert!((s["b"] - 1.0 / 12.0).abs() < 1e-9, "{s:?}");
71        assert!((s["c"] - 3.0 / 12.0).abs() < 1e-9, "{s:?}");
72        assert!((s.values().sum::<f64>() - 1.0).abs() < 1e-9, "the panes fill the tab: {s:?}");
73    }
74
75    #[test]
76    fn panes_stacked_as_tabs_of_one_leaf_have_that_leafs_share() {
77        let mut stacked = leaf("b2", 1.0);
78        stacked.data = Some(LayoutNodeData { block_id: "b2".into(), block_stack: vec!["b1".into(), "b2".into()], active_block_id: "b2".into(), ..Default::default() });
79        let s = shares(&group(FlexDirection::Row, 1.0, vec![leaf("a", 1.0), stacked]));
80        assert_eq!((s["a"], s["b1"], s["b2"]), (0.5, 0.5, 0.5));
81    }
82
83    #[test]
84    fn sizes_that_are_zero_split_the_space_equally_rather_than_dividing_by_zero() {
85        let s = shares(&group(FlexDirection::Row, 1.0, vec![leaf("a", 0.0), leaf("b", 0.0)]));
86        assert_eq!((s["a"], s["b"]), (0.5, 0.5));
87    }
88
89    #[tokio::test]
90    async fn the_layout_report_gives_each_docked_pane_its_share_and_a_pane_in_no_leaf_none() {
91        use crate::backend::obj::{Block, LayoutState, Tab, Window, Workspace};
92        let store = crate::server::tests::test_state().mstore;
93        let id = |name: &str| format!("{name}-{}", uuid::Uuid::new_v4());
94        let (win, ws, tab, layout) = (id("win"), id("ws"), id("tab"), id("layout"));
95        let blocks = [id("a"), id("b"), id("loose")];
96        for b in &blocks {
97            store.insert(&mut Block { oid: b.clone(), ..Default::default() }).unwrap();
98        }
99        let root = group(FlexDirection::Row, 1.0, vec![leaf(&blocks[0], 1.0), leaf(&blocks[1], 3.0)]);
100        store.insert(&mut LayoutState { oid: layout.clone(), rootnode: Some(root), ..Default::default() }).unwrap();
101        store.insert(&mut Tab { oid: tab.clone(), layoutstate: layout, blockids: blocks.to_vec(), ..Default::default() }).unwrap();
102        store.insert(&mut Workspace { oid: ws.clone(), tabids: vec![tab.clone()], activetabid: tab, ..Default::default() }).unwrap();
103        store.insert(&mut Window { oid: win, workspaceid: ws, ..Default::default() }).unwrap();
104
105        let report = crate::server::service::agent_layout(&store);
106
107        let ours = report["windows"].as_array().unwrap().iter().flat_map(|w| w["tabs"].as_array().unwrap().iter()).flat_map(|t| t["panes"].as_array().unwrap().iter()).filter(|p| blocks.iter().any(|b| p["block_id"] == *b)).collect::<Vec<_>>();
108        assert_eq!(ours.len(), 3);
109        let share = |b: &String| ours.iter().find(|p| p["block_id"] == *b).unwrap().get("share").cloned();
110        assert_eq!((share(&blocks[0]), share(&blocks[1])), (Some(json!(0.25)), Some(json!(0.75))));
111        assert_eq!(share(&blocks[2]), None, "a block made with no placement is in the tab but in no pane");
112    }
113
114    #[test]
115    fn a_share_is_shown_to_three_places() {
116        assert_eq!(rounded(1.0 / 3.0), 0.333);
117        assert_eq!(rounded(0.5), 0.5);
118    }
119}