Skip to main content

agentmux_srv_core/backend/layout/
drop_split.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The split of a hovered pane that a drop on one of its sides commits, by the
5//! drop direction the window sends (a redock of a floating pane, a move
6//! between window tabs, a pane docked beside another).
7//!
8//! The splits are not written here: they are
9//! `frontend/layout/lib/drop-splits.json`, the list the window shows its drop
10//! from (`dropSplits.ts`). What the window shows for a direction and what srv
11//! commits for it are one entry of that list. srv's tree for every entry is in
12//! `frontend/layout/tests/fixtures/drop-split-vectors.json`, which the
13//! window's reducer replays (`dropSplits.test.ts`).
14
15use std::sync::LazyLock;
16
17use agentmux_common::SplitPosition;
18use serde::Deserialize;
19
20/// One split of the list: the direction that asks for it and the split it makes.
21#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub struct DropSplit {
24    /// The window's `DropDirection` code.
25    pub direction: u8,
26    /// Side by side (`splithorizontal`), else one above the other.
27    pub horizontal: bool,
28    pub position: SplitPosition,
29    /// The share of the hovered pane the new pane takes.
30    pub size_fraction: f64,
31}
32
33#[derive(Deserialize)]
34struct DropSplitsFile {
35    splits: Vec<DropSplit>,
36}
37
38static DROP_SPLITS: LazyLock<Vec<DropSplit>> = LazyLock::new(|| {
39    serde_json::from_str::<DropSplitsFile>(include_str!("../../../../../frontend/layout/lib/drop-splits.json"))
40        .expect("frontend/layout/lib/drop-splits.json is the shared list of drop splits and must parse")
41        .splits
42});
43
44/// Every split srv commits for a drop on a pane's side.
45pub fn drop_splits() -> &'static [DropSplit] {
46    &DROP_SPLITS
47}
48
49/// The split srv commits for `direction`; `None` where it has no split (the
50/// middle of a pane, an unknown code) and the block is inserted instead.
51pub fn drop_split(direction: u8) -> Option<DropSplit> {
52    drop_splits().iter().copied().find(|s| s.direction == direction)
53}
54
55#[cfg(test)]
56mod tests {
57    use agentmux_common::{FlexDirection, LayoutIntent, LayoutNode, LayoutNodeData};
58
59    use super::super::intent::{apply_intent, NodeIds};
60    use super::*;
61
62    #[test]
63    fn the_list_is_the_four_sides_of_a_pane_and_the_four_beside_its_group() {
64        // The window's DropDirection: Top, Right, Bottom, Left, then the Outer four.
65        let expected: &[(u8, bool, SplitPosition, f64)] = &[
66            (0, false, SplitPosition::Before, 0.5),
67            (1, true, SplitPosition::After, 0.5),
68            (2, false, SplitPosition::After, 0.5),
69            (3, true, SplitPosition::Before, 0.5),
70            (4, false, SplitPosition::Before, 0.2),
71            (5, true, SplitPosition::After, 0.2),
72            (6, false, SplitPosition::After, 0.2),
73            (7, true, SplitPosition::Before, 0.2),
74        ];
75        let listed: Vec<_> = drop_splits().iter().map(|s| (s.direction, s.horizontal, s.position, s.size_fraction)).collect();
76        assert_eq!(listed, expected);
77    }
78
79    #[test]
80    fn a_direction_is_listed_once_and_the_rest_have_no_split() {
81        for direction in 0..=u8::MAX {
82            let listed = drop_splits().iter().filter(|s| s.direction == direction).count();
83            assert_eq!(listed, usize::from(direction < 8), "direction {direction}");
84            assert_eq!(drop_split(direction).is_some(), direction < 8, "direction {direction}");
85        }
86    }
87
88    // ── Vectors shared with the frontend ───────────────────────────────────
89
90    const VECTORS: &str = "../../frontend/layout/tests/fixtures/drop-split-vectors.json";
91    const ACTION: &str = "a0000001-0000-4000-8000-00000000abcd";
92
93    fn leaf(id: &str) -> LayoutNode {
94        LayoutNode {
95            id: id.into(),
96            flex_direction: FlexDirection::Row,
97            size: 10.0,
98            data: Some(LayoutNodeData { block_id: format!("b-{id}"), ..Default::default() }),
99            ..Default::default()
100        }
101    }
102
103    fn branch(id: &str, dir: FlexDirection, children: Vec<LayoutNode>) -> LayoutNode {
104        LayoutNode { id: id.into(), flex_direction: dir, size: 10.0, children, ..Default::default() }
105    }
106
107    /// The hovered pane is `t` in each.
108    fn trees() -> Vec<(&'static str, LayoutNode)> {
109        vec![
110            ("a lone pane", leaf("t")),
111            ("a pane in a row", branch("r", FlexDirection::Row, vec![leaf("a"), leaf("t"), leaf("c")])),
112            ("a pane in a column", branch("r", FlexDirection::Column, vec![leaf("a"), leaf("t")])),
113        ]
114    }
115
116    /// The intent `place_block` applies for `split` (crates/srv/src/server/service/layout_intents.rs).
117    fn intent_of(split: DropSplit) -> LayoutIntent {
118        let (target_node_id, new_node) = ("t".to_string(), leaf("n"));
119        let (position, size_fraction, focused) = (split.position, Some(split.size_fraction), true);
120        if split.horizontal {
121            LayoutIntent::SplitHorizontal { target_node_id, new_node, position, size_fraction, focused }
122        } else {
123            LayoutIntent::SplitVertical { target_node_id, new_node, position, size_fraction, focused }
124        }
125    }
126
127    fn vectors_json() -> serde_json::Value {
128        let mut cases = Vec::new();
129        for (name, tree) in trees() {
130            for split in drop_splits() {
131                let intent = intent_of(*split);
132                let mut root = Some(tree.clone());
133                apply_intent(&mut root, intent.clone(), &mut NodeIds::new(ACTION)).expect("srv splits the pane");
134                cases.push(serde_json::json!({
135                    "name": name,
136                    "direction": split.direction,
137                    "actionId": ACTION,
138                    "initial": tree,
139                    "intent": intent,
140                    "final": root,
141                }));
142            }
143        }
144        serde_json::json!({
145            "about": "Generated by crates/srv-core/src/backend/layout/drop_split.rs (srv's tree for every split of frontend/layout/lib/drop-splits.json). Regenerate with UPDATE_DROP_SPLIT_VECTORS=1 cargo test -p agentmux-srv-core drop_split_vectors.",
146            "cases": cases,
147        })
148    }
149
150    /// srv's trees for the list are the committed ones; the frontend replays
151    /// the same file through its own reducer.
152    #[test]
153    fn drop_split_vectors_match_the_committed_file() {
154        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(VECTORS);
155        let generated = vectors_json();
156        if std::env::var_os("UPDATE_DROP_SPLIT_VECTORS").is_some() {
157            // One case per line: a reviewable diff.
158            let lines: Vec<String> = generated["cases"].as_array().unwrap().iter().map(|v| v.to_string()).collect();
159            let text = format!("{{\"about\":{},\n\"cases\":[\n{}\n]}}\n", generated["about"], lines.join(",\n"));
160            std::fs::write(&path, text).unwrap();
161        }
162        let committed: serde_json::Value = serde_json::from_str(
163            &std::fs::read_to_string(&path)
164                .unwrap_or_else(|e| panic!("{}: {e}; generate it with UPDATE_DROP_SPLIT_VECTORS=1", path.display())),
165        )
166        .unwrap();
167        assert_eq!(committed["about"], generated["about"], "the file's first line");
168        let (committed, generated) = (committed["cases"].as_array().unwrap(), generated["cases"].as_array().unwrap());
169        assert_eq!(committed.len(), generated.len(), "the number of cases");
170        for (was, now) in committed.iter().zip(generated) {
171            assert!(
172                was == now,
173                "{} is stale: regenerate it with UPDATE_DROP_SPLIT_VECTORS=1 cargo test -p agentmux-srv-core drop_split_vectors\n the file has: {was}\n srv makes:    {now}",
174                path.display()
175            );
176        }
177    }
178}