Skip to main content

agentmux_srv_core/backend/layout/
intent.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Layout intents applied to a tree: a step-for-step port of the frontend's
5//! tree actions (`frontend/layout/lib/layoutTree.ts`, with `addChildAt` and
6//! `addIntermediateNode` from `layoutNode.ts`), followed by the same
7//! `balance_node` the frontend runs after every action. The frontend applies
8//! an action locally as a prediction and srv's result is the one that is
9//! stored, so the two must agree: `intent_vectors` replays one shared set of
10//! random sequences through both. Where the frontend would corrupt the tree
11//! (a move into the moved node's own subtree, a swap of a node with its
12//! ancestor) or apply half an action (an invalid resize), srv refuses instead.
13//! SPEC_STRONG_REDUCER_AUTHORITY_LAYOUT_2026_06_30.md §4.
14
15use agentmux_common::{FlexDirection, LayoutEdge, LayoutIntent, LayoutNode, LayoutNodeData, LayoutResizeOp, SplitPosition};
16
17use super::{
18    balance_node, collect_insert_candidates, find_node_by_id, find_node_by_id_mut, find_parent_id,
19    is_effectively_minimized, LayoutError, DEFAULT_MAX_CHILDREN, DEFAULT_NODE_SIZE,
20};
21
22/// The id of the `n`th node (from 1) an intent creates: the action id with its
23/// first eight hex digits replaced by `n`, or `<action id>-<n>` when the action
24/// id isn't a UUID. The frontend derives the same ids (`deriveNodeId`,
25/// `layoutNode.ts`), so the branches both sides create are named alike.
26pub fn derive_node_id(action_id: &str, n: u32) -> String {
27    if action_id.len() >= 9 && action_id.as_bytes()[8] == b'-' && action_id.is_char_boundary(8) {
28        format!("{:08x}{}", n, &action_id[8..])
29    } else {
30        format!("{action_id}-{n}")
31    }
32}
33
34/// Mints the ids for the nodes one intent creates, in creation order.
35pub struct NodeIds {
36    action_id: String,
37    used: u32,
38}
39
40impl NodeIds {
41    pub fn new(action_id: &str) -> Self {
42        Self { action_id: action_id.to_string(), used: 0 }
43    }
44
45    fn next(&mut self) -> String {
46        self.used += 1;
47        derive_node_id(&self.action_id, self.used)
48    }
49}
50
51/// What an intent does to focus and magnify, as the frontend's action
52/// functions write them. Applied only when the sender didn't say which pane it
53/// has focused (srv's own placements).
54#[derive(Debug, Default, Clone, PartialEq)]
55pub struct ViewEffect {
56    pub focus: Option<String>,
57    pub magnify: Option<String>,
58    /// Clear focus if it is this node (a delete).
59    pub unfocus: Option<String>,
60    /// Clear magnify if it is this node (a minimize).
61    pub unmagnify: Option<String>,
62    /// Clear focus and magnify (a clear).
63    pub clear: bool,
64}
65
66/// Apply `intent` to `root`, then normalize it (`balance_node`). On an error
67/// `root` may be half-edited: callers apply to a copy.
68pub fn apply_intent(
69    root: &mut Option<LayoutNode>,
70    intent: LayoutIntent,
71    ids: &mut NodeIds,
72) -> Result<ViewEffect, LayoutError> {
73    let effect = apply_unbalanced(root, intent, ids)?;
74    if let Some(tree) = root.as_mut() {
75        balance_node(tree)?;
76    }
77    Ok(effect)
78}
79
80fn apply_unbalanced(
81    root: &mut Option<LayoutNode>,
82    intent: LayoutIntent,
83    ids: &mut NodeIds,
84) -> Result<ViewEffect, LayoutError> {
85    let mut effect = ViewEffect::default();
86    match intent {
87        LayoutIntent::Insert { node, magnified, focused } => {
88            let node_id = node.id.clone();
89            let was_empty = root.is_none();
90            insert_node(root, node, ids)?;
91            set_insert_effect(&mut effect, node_id, was_empty, magnified, focused);
92        }
93        LayoutIntent::InsertAtIndex { node, index_arr, magnified, focused } => {
94            let node_id = node.id.clone();
95            let was_empty = root.is_none();
96            insert_node_at_index(root, node, &index_arr, ids)?;
97            set_insert_effect(&mut effect, node_id, was_empty, magnified, focused);
98        }
99        LayoutIntent::Delete { node_id } => {
100            let before = root.as_ref().map(leaf_ids).unwrap_or_default();
101            let removed = root.as_ref().and_then(|t| find_node_by_id(t, &node_id)).map(leaf_ids).unwrap_or_default();
102            delete_node(root, &node_id)?;
103            if let Some(tree) = root.as_mut() {
104                restore_nearest_if_all_minimized(tree, &before, &removed);
105            }
106            effect.unfocus = Some(node_id);
107        }
108        LayoutIntent::Move { node_id, parent_id, index, insert_at_root } => {
109            if insert_at_root {
110                // Only a drop onto a single-pane root produces it, and then
111                // nothing else is in the tree to move.
112                return Err(LayoutError::Refused("move: insertAtRoot is not supported".into()));
113            }
114            let parent_id = parent_id.ok_or_else(|| LayoutError::Refused("move: no parentId".into()))?;
115            move_node(tree_mut(root)?, &node_id, &parent_id, index, ids)?;
116        }
117        LayoutIntent::MoveToEdge { node_id, edge, size } => move_to_edge(root, &node_id, (edge, size), ids)?,
118        LayoutIntent::Swap { node1_id, node2_id } => swap_nodes(tree_mut(root)?, &node1_id, &node2_id)?,
119        LayoutIntent::Resize { resize_operations } => resize_nodes(tree_mut(root)?, &resize_operations)?,
120        LayoutIntent::Replace { target_node_id, new_node, focused } => {
121            let new_id = new_node.id.clone();
122            replace_node(tree_mut(root)?, &target_node_id, new_node)?;
123            if focused {
124                effect.focus = Some(new_id);
125            }
126        }
127        LayoutIntent::SplitHorizontal { target_node_id, new_node, position, size_fraction, focused } => {
128            let new_id = new_node.id.clone();
129            split(root, &target_node_id, new_node, position, size_fraction, FlexDirection::Row, ids)?;
130            if focused {
131                effect.focus = Some(new_id);
132            }
133        }
134        LayoutIntent::SplitVertical { target_node_id, new_node, position, size_fraction, focused } => {
135            let new_id = new_node.id.clone();
136            split(root, &target_node_id, new_node, position, size_fraction, FlexDirection::Column, ids)?;
137            if focused {
138                effect.focus = Some(new_id);
139            }
140        }
141        LayoutIntent::Minimize { node_id } => {
142            set_minimized(tree_mut(root)?, &node_id, true)?;
143            effect.unmagnify = Some(node_id);
144        }
145        LayoutIntent::Restore { node_id } => restore_node(root, &node_id, ids)?,
146        LayoutIntent::Clear => {
147            *root = None;
148            effect.clear = true;
149        }
150        LayoutIntent::View => {}
151    }
152    Ok(effect)
153}
154
155/// `insertNode`'s focus/magnify writes: magnify only into a non-empty tree.
156fn set_insert_effect(effect: &mut ViewEffect, node_id: String, was_empty: bool, magnified: bool, focused: bool) {
157    if magnified && !was_empty {
158        effect.magnify = Some(node_id.clone());
159        effect.focus = Some(node_id.clone());
160    }
161    if focused {
162        effect.focus = Some(node_id);
163    }
164}
165
166fn tree_mut(root: &mut Option<LayoutNode>) -> Result<&mut LayoutNode, LayoutError> {
167    root.as_mut().ok_or_else(|| LayoutError::Refused("the layout is empty".into()))
168}
169
170fn not_found(id: &str) -> LayoutError {
171    LayoutError::NodeNotFound { id: id.to_string() }
172}
173
174fn reverse(dir: FlexDirection) -> FlexDirection {
175    match dir {
176        FlexDirection::Row => FlexDirection::Column,
177        FlexDirection::Column => FlexDirection::Row,
178    }
179}
180
181fn new_node(
182    flex_direction: FlexDirection,
183    size: f32,
184    children: Vec<LayoutNode>,
185    data: Option<LayoutNodeData>,
186    ids: &mut NodeIds,
187) -> LayoutNode {
188    LayoutNode { id: ids.next(), flex_direction, size, children, data, ..Default::default() }
189}
190
191// ── layoutNode.ts primitives ────────────────────────────────────────────────
192
193/// `addChildAt`: a child with the parent's direction gives up its own
194/// children to the parent (a branch) or flips (a leaf).
195fn add_child_at(node: &mut LayoutNode, idx: i64, mut child: LayoutNode, ids: &mut NodeIds) {
196    if node.children.is_empty() {
197        add_intermediate_node(node, ids);
198    }
199    let to_add = if child.flex_direction != node.flex_direction {
200        vec![child]
201    } else if !child.children.is_empty() {
202        child.children
203    } else {
204        child.flex_direction = reverse(node.flex_direction);
205        vec![child]
206    };
207    if node.children.len() as i64 <= idx {
208        node.children.extend(to_add);
209    } else if idx >= 0 {
210        let at = idx as usize;
211        node.children.splice(at..at, to_add);
212    }
213}
214
215/// `addIntermediateNode`: push a node's data (or children) one level down.
216/// The new child takes the node's id and the node a fresh one, so whatever
217/// pointed at the node (focus) now points at its content.
218fn add_intermediate_node(node: &mut LayoutNode, ids: &mut NodeIds) {
219    let mut intermediate = if node.data.is_some() {
220        let mut leaf = new_node(reverse(node.flex_direction), DEFAULT_NODE_SIZE, Vec::new(), node.data.take(), ids);
221        // `minimized` belongs to the content, not the branch it becomes.
222        leaf.minimized = std::mem::take(&mut node.minimized);
223        leaf
224    } else {
225        let inner = new_node(node.flex_direction, DEFAULT_NODE_SIZE, std::mem::take(&mut node.children), None, ids);
226        new_node(reverse(node.flex_direction), DEFAULT_NODE_SIZE, vec![inner], None, ids)
227    };
228    std::mem::swap(&mut intermediate.id, &mut node.id);
229    node.children = vec![intermediate];
230}
231
232/// `removeChild`: the first child with this id at or after `starting`.
233fn remove_child(parent: &mut LayoutNode, child_id: &str, starting: usize) {
234    if let Some(i) = parent.children.iter().skip(starting).position(|c| c.id == child_id) {
235        parent.children.remove(starting + i);
236    }
237}
238
239// ── layoutTree.ts actions ───────────────────────────────────────────────────
240
241fn insert_node(root: &mut Option<LayoutNode>, node: LayoutNode, ids: &mut NodeIds) -> Result<(), LayoutError> {
242    let Some(tree) = root.as_mut() else {
243        *root = Some(node);
244        return Ok(());
245    };
246    // No slot is unlocked only when every pane is minimized. The new pane then goes in at the root, after the
247    // chips, and shows: a tab always shows one pane (SPEC_DRAG_MINIMIZED_PANES_2026_10_20.md §3 C, item 8).
248    // `insertNode` (layoutTree.ts) does the same.
249    let (loc_id, index) = next_insert_location(tree).unwrap_or_else(|| (tree.id.clone(), tree.children.len().max(1)));
250    let loc = find_node_by_id_mut(tree, &loc_id).ok_or_else(|| not_found(&loc_id))?;
251    add_child_at(loc, index as i64, node, ids);
252    Ok(())
253}
254
255/// `findNextInsertLocation`: the lowest-scoring slot, ties to the first found.
256fn next_insert_location(tree: &LayoutNode) -> Option<(String, usize)> {
257    let mut candidates = Vec::new();
258    collect_insert_candidates(tree, DEFAULT_MAX_CHILDREN, 1, &mut candidates);
259    let score = |depth: usize, index: usize| (depth as f64).powi((index + DEFAULT_MAX_CHILDREN) as i32);
260    candidates
261        .iter()
262        .enumerate()
263        .min_by(|(ia, a), (ib, b)| {
264            score(a.depth, a.index)
265                .partial_cmp(&score(b.depth, b.index))
266                .unwrap_or(std::cmp::Ordering::Equal)
267                .then(ia.cmp(ib))
268        })
269        .map(|(_, c)| (c.node.id.clone(), c.index))
270}
271
272fn insert_node_at_index(
273    root: &mut Option<LayoutNode>,
274    node: LayoutNode,
275    index_arr: &[i64],
276    ids: &mut NodeIds,
277) -> Result<(), LayoutError> {
278    let Some(tree) = root.as_mut() else {
279        *root = Some(node);
280        return Ok(());
281    };
282    let (loc_id, index) = insert_location_from_index_arr(tree, index_arr).ok_or(LayoutError::InvalidIndexPath)?;
283    let loc = find_node_by_id_mut(tree, &loc_id).ok_or_else(|| not_found(&loc_id))?;
284    if is_effectively_minimized(loc) {
285        return Err(LayoutError::NodeLocked { id: loc_id });
286    }
287    add_child_at(loc, index + 1, node, ids);
288    Ok(())
289}
290
291/// `findInsertLocationFromIndexArr`, including its arithmetic for negative
292/// indices. A path that leaves the tree is refused.
293fn insert_location_from_index_arr(node: &LayoutNode, index_arr: &[i64]) -> Option<(String, i64)> {
294    let (&first, rest) = index_arr.split_first()?;
295    let len = node.children.len().max(1) as i64;
296    let next = if first < 0 { len - first.max(-len) } else { first.min(len - 1) };
297    if rest.is_empty() || node.children.is_empty() {
298        return Some((node.id.clone(), next));
299    }
300    let child = node.children.get(usize::try_from(next).ok()?)?;
301    insert_location_from_index_arr(child, rest)
302}
303
304/// `deleteNode`: unlink the node. The parent it leaves is tidied by the
305/// balance pass that follows, not here.
306fn delete_node(root: &mut Option<LayoutNode>, node_id: &str) -> Result<(), LayoutError> {
307    let tree = root.as_mut().ok_or_else(|| not_found(node_id))?;
308    if tree.id == node_id {
309        *root = None;
310        return Ok(());
311    }
312    let parent_id = find_parent_id(tree, node_id).ok_or_else(|| not_found(node_id))?;
313    let parent = find_node_by_id_mut(tree, &parent_id).ok_or_else(|| not_found(&parent_id))?;
314    remove_child(parent, node_id, 0);
315    Ok(())
316}
317
318/// The `delete` intent on a tree whose root stays: unlink the node, then
319/// balance (what the frontend does when a move empties a pane).
320pub fn delete_and_balance(root: &mut LayoutNode, node_id: &str) -> Result<(), LayoutError> {
321    if root.id == node_id {
322        return Err(LayoutError::RootCannotBeTarget);
323    }
324    let before = leaf_ids(root);
325    let removed = find_node_by_id(root, node_id).map(leaf_ids).unwrap_or_default();
326    let parent_id = find_parent_id(root, node_id).ok_or_else(|| not_found(node_id))?;
327    let parent = find_node_by_id_mut(root, &parent_id).ok_or_else(|| not_found(&parent_id))?;
328    remove_child(parent, node_id, 0);
329    restore_nearest_if_all_minimized(root, &before, &removed);
330    balance_node(root)
331}
332
333/// The panes in reading order (depth first), to find "the nearest pane".
334pub(crate) fn leaf_ids(node: &LayoutNode) -> Vec<String> {
335    fn walk(node: &LayoutNode, out: &mut Vec<String>) {
336        if node.children.is_empty() {
337            if node.data.is_some() {
338                out.push(node.id.clone());
339            }
340        } else {
341            node.children.iter().for_each(|c| walk(c, out));
342        }
343    }
344    let mut out = Vec::new();
345    walk(node, &mut out);
346    out
347}
348
349/// After a pane or a container left the tree (`removed`: its panes, in reading order): if every
350/// pane left is minimized, restore the nearest one, the pane that followed it in reading order or
351/// else the one before it, so a tab always shows one. `before` is the reading order with the
352/// removed panes still in it. `deleteNode` (layoutTree.ts) does the same.
353pub(crate) fn restore_nearest_if_all_minimized(tree: &mut LayoutNode, before: &[String], removed: &[String]) {
354    if expanded_leaves(tree) > 0 {
355        return;
356    }
357    let at = removed.first().and_then(|first| before.iter().position(|id| id == first)).unwrap_or(0);
358    let (prior, rest) = before.split_at(at);
359    let after = rest.iter().filter(|id| !removed.contains(id));
360    for id in after.chain(prior.iter().rev()) {
361        if let Some(node) = find_node_by_id_mut(tree, id) {
362            if node.children.is_empty() && node.data.is_some() {
363                node.minimized = false;
364                return;
365            }
366        }
367    }
368}
369
370/// `moveNode`: insert the node at its new place, then remove it from the old
371/// one, which leaves a same-parent move one slot earlier when it moves right.
372fn move_node(tree: &mut LayoutNode, node_id: &str, parent_id: &str, index: i64, ids: &mut NodeIds) -> Result<(), LayoutError> {
373    if tree.id == node_id {
374        return Err(LayoutError::RootCannotBeTarget);
375    }
376    let mut node = find_node_by_id(tree, node_id).ok_or_else(|| not_found(node_id))?.clone();
377    let parent = find_node_by_id(tree, parent_id).ok_or_else(|| not_found(parent_id))?;
378    // A chip moves like any pane and stays a chip; a strip of chips does not move; only a chip
379    // may go into a chip or a strip of them (`moveIsLockedByMinimize`, layoutTree.ts).
380    if !node.children.is_empty() && is_effectively_minimized(&node) {
381        return Err(LayoutError::NodeLocked { id: node_id.to_string() });
382    }
383    if is_effectively_minimized(parent) && !super::is_node_locked(&node) {
384        return Err(LayoutError::NodeLocked { id: parent_id.to_string() });
385    }
386    if find_node_by_id(&node, parent_id).is_some() {
387        return Err(LayoutError::Refused(format!("move: {parent_id} is inside the moved node {node_id}")));
388    }
389    if index < 0 {
390        return Err(LayoutError::Refused(format!("move: negative index {index}")));
391    }
392    let old_parent_id = find_parent_id(tree, node_id).ok_or_else(|| not_found(node_id))?;
393    let mut starting = 0;
394    if old_parent_id == parent_id {
395        let current = parent.children.iter().position(|c| c.id == node_id).unwrap_or(0) as i64;
396        if current >= index {
397            starting = index as usize + 1;
398        }
399    } else {
400        node.size = DEFAULT_NODE_SIZE;
401    }
402    let parent = find_node_by_id_mut(tree, parent_id).ok_or_else(|| not_found(parent_id))?;
403    add_child_at(parent, index, node, ids);
404    let old_parent = find_node_by_id_mut(tree, &old_parent_id).ok_or_else(|| not_found(&old_parent_id))?;
405    remove_child(old_parent, node_id, starting);
406    Ok(())
407}
408
409/// The flex size of a band that takes `size` (a fraction, between a tenth and a half) of the layout beside the children of
410/// `rest`; the default third without one. Rounded to hundredths: the page computes the same (`bandBeside`, layoutTree.ts).
411fn band_beside(rest: &LayoutNode, size: Option<f64>) -> f32 {
412    let Some(share) = size.map(|f| f.clamp(0.1, 0.5)) else { return BAND_SIZE };
413    let others: f64 = rest.children.iter().map(|c| f64::from(c.size)).sum();
414    round_hundredths(others * share / (1.0 - share))
415}
416
417/// The flex sizes of a band and of the rest wrapped beside it, the band taking `size` of the two.
418fn band_and_rest(size: Option<f64>) -> (f32, f32) {
419    let Some(share) = size.map(|f| f.clamp(0.1, 0.5)) else { return (BAND_SIZE, BESIDE_BAND_SIZE) };
420    let whole = 3.0 * f64::from(DEFAULT_NODE_SIZE);
421    (round_hundredths(whole * share), round_hundredths(whole * (1.0 - share)))
422}
423
424fn round_hundredths(x: f64) -> f32 {
425    ((x * 100.0).round() / 100.0) as f32
426}
427
428/// Flex size of a band, and of the rest of the layout beside a band that wraps it (a third of the layout).
429const BAND_SIZE: f32 = DEFAULT_NODE_SIZE;
430const BESIDE_BAND_SIZE: f32 = 2.0 * DEFAULT_NODE_SIZE;
431/// Flex size of each half of the rest of the layout, above and below a band across the middle.
432const HALF_SIZE: f32 = 1.5 * DEFAULT_NODE_SIZE;
433
434/// `moveToEdge` (layoutTree.ts): take the pane out of the layout, then put it back as a band across the whole of it.
435/// The rest is balanced first, and what the band goes into depends on how it is arranged:
436/// - a column of rows: the band is one more row, first, last, or in the middle;
437/// - one row of columns, or one pane: the band is above (or below) the rest, which becomes the rest of a new column;
438/// - across the middle of a row of columns: its first half above the band, the others below it.
439/// A column down the left or right side is the same turned: one more column of a row of columns, first or last; else the
440/// rest (a column of rows, or one pane) is wrapped in a new row beside it.
441/// Nothing changes where the rest is one pane and the band is asked for the middle. The pane's own place closes.
442/// The middle of a column is after half of its rows, rounded up.
443fn move_to_edge(root: &mut Option<LayoutNode>, node_id: &str, (edge, size): (LayoutEdge, Option<f64>), ids: &mut NodeIds) -> Result<(), LayoutError> {
444    let tree = tree_mut(root)?;
445    if tree.id == node_id {
446        return Err(LayoutError::RootCannotBeTarget);
447    }
448    let node = find_node_by_id(tree, node_id).ok_or_else(|| not_found(node_id))?;
449    if !node.children.is_empty() && is_effectively_minimized(node) {
450        return Err(LayoutError::NodeLocked { id: node_id.to_string() });
451    }
452    // Worked on a copy: a refusal below leaves the layout as it was.
453    let mut node = node.clone();
454    let mut rest = tree.clone();
455    delete_and_balance(&mut rest, node_id)?;
456    // A row or column left holding one branch is that branch (the pane that left was its other child).
457    while rest.children.len() == 1 && !rest.children[0].children.is_empty() {
458        let only = rest.children.remove(0);
459        rest = only;
460    }
461    node.size = BAND_SIZE;
462    let in_column = rest.flex_direction == FlexDirection::Column && !rest.children.is_empty();
463    let in_row = rest.flex_direction == FlexDirection::Row && !rest.children.is_empty();
464    let placed = match edge {
465        LayoutEdge::Top | LayoutEdge::Bottom if in_column => {
466            let at = if edge == LayoutEdge::Top { 0 } else { rest.children.len() as i64 };
467            node.size = band_beside(&rest, size);
468            add_child_at(&mut rest, at, node, ids);
469            rest
470        }
471        LayoutEdge::Middle if in_column => {
472            let at = rest.children.len().div_ceil(2) as i64;
473            add_child_at(&mut rest, at, node, ids);
474            rest
475        }
476        LayoutEdge::Left | LayoutEdge::Right if in_row => {
477            let at = if edge == LayoutEdge::Left { 0 } else { rest.children.len() as i64 };
478            node.size = band_beside(&rest, size);
479            add_child_at(&mut rest, at, node, ids);
480            rest
481        }
482        LayoutEdge::Left | LayoutEdge::Right => {
483            (node.size, rest.size) = band_and_rest(size);
484            let children = if edge == LayoutEdge::Left { vec![node, rest] } else { vec![rest, node] };
485            new_node(FlexDirection::Row, DEFAULT_NODE_SIZE, children, None, ids)
486        }
487        LayoutEdge::Top | LayoutEdge::Bottom => {
488            (node.size, rest.size) = band_and_rest(size);
489            let children = if edge == LayoutEdge::Top { vec![node, rest] } else { vec![rest, node] };
490            new_node(FlexDirection::Column, DEFAULT_NODE_SIZE, children, None, ids)
491        }
492        LayoutEdge::Middle if rest.children.len() >= 2 => {
493            let mut above = std::mem::take(&mut rest.children);
494            let below = above.split_off(above.len().div_ceil(2));
495            let above = new_node(FlexDirection::Row, HALF_SIZE, above, None, ids);
496            let below = new_node(FlexDirection::Row, HALF_SIZE, below, None, ids);
497            new_node(FlexDirection::Column, DEFAULT_NODE_SIZE, vec![above, node, below], None, ids)
498        }
499        LayoutEdge::Middle => return Err(LayoutError::Refused("movetoedge: one pane has no middle to put a band across".into())),
500    };
501    *tree = placed;
502    Ok(())
503}
504
505/// `swapNode`: exchange two nodes; each slot keeps its size.
506fn swap_nodes(tree: &mut LayoutNode, node1_id: &str, node2_id: &str) -> Result<(), LayoutError> {
507    if node1_id == tree.id || node2_id == tree.id {
508        return Err(LayoutError::RootCannotBeTarget);
509    }
510    if node1_id == node2_id {
511        return Err(LayoutError::SelfSwap);
512    }
513    let node1 = find_node_by_id(tree, node1_id).ok_or_else(|| not_found(node1_id))?.clone();
514    let node2 = find_node_by_id(tree, node2_id).ok_or_else(|| not_found(node2_id))?.clone();
515    // A chip swaps like any pane and keeps its state; a strip of chips does not swap.
516    for (id, node) in [(node1_id, &node1), (node2_id, &node2)] {
517        if !node.children.is_empty() && is_effectively_minimized(node) {
518            return Err(LayoutError::NodeLocked { id: id.to_string() });
519        }
520    }
521    if find_node_by_id(&node1, node2_id).is_some() || find_node_by_id(&node2, node1_id).is_some() {
522        return Err(LayoutError::Refused("swap: one node contains the other".into()));
523    }
524    let slot1 = slot_of(tree, node1_id)?;
525    let slot2 = slot_of(tree, node2_id)?;
526    let (size1, size2) = (node1.size, node2.size);
527    let (mut into_slot1, mut into_slot2) = (node2, node1);
528    into_slot1.size = size1;
529    into_slot2.size = size2;
530    // By index, found before either write: with one parent, the first write
531    // leaves two children with node2's id.
532    place(tree, &slot1, into_slot1)?;
533    place(tree, &slot2, into_slot2)
534}
535
536/// A node's parent id and its index there.
537fn slot_of(tree: &LayoutNode, node_id: &str) -> Result<(String, usize), LayoutError> {
538    let parent_id = find_parent_id(tree, node_id).ok_or_else(|| not_found(node_id))?;
539    let parent = find_node_by_id(tree, &parent_id).ok_or_else(|| not_found(&parent_id))?;
540    let index = parent.children.iter().position(|c| c.id == node_id).ok_or_else(|| not_found(node_id))?;
541    Ok((parent_id, index))
542}
543
544fn place(tree: &mut LayoutNode, (parent_id, index): &(String, usize), node: LayoutNode) -> Result<(), LayoutError> {
545    let parent = find_node_by_id_mut(tree, parent_id).ok_or_else(|| not_found(parent_id))?;
546    let slot = parent.children.get_mut(*index).ok_or_else(|| not_found(parent_id))?;
547    *slot = node;
548    Ok(())
549}
550
551/// `resizeNode`, all or nothing: every op is checked before any applies.
552fn resize_nodes(tree: &mut LayoutNode, ops: &[LayoutResizeOp]) -> Result<(), LayoutError> {
553    for op in ops {
554        let node = find_node_by_id(tree, &op.node_id).ok_or_else(|| not_found(&op.node_id))?;
555        if is_effectively_minimized(node) {
556            return Err(LayoutError::NodeLocked { id: op.node_id.clone() });
557        }
558        if op.node_id.is_empty() || !(0.0..=100.0).contains(&op.size) {
559            return Err(LayoutError::InvalidSize { node_id: op.node_id.clone(), size: op.size as f32 });
560        }
561    }
562    for op in ops {
563        if let Some(node) = find_node_by_id_mut(tree, &op.node_id) {
564            node.size = op.size as f32;
565        }
566    }
567    Ok(())
568}
569
570/// `replaceNode`: the new node takes the target's slot and size.
571fn replace_node(tree: &mut LayoutNode, target_id: &str, mut new_node: LayoutNode) -> Result<(), LayoutError> {
572    if tree.id == target_id {
573        new_node.size = tree.size;
574        *tree = new_node;
575        return Ok(());
576    }
577    let parent_id = find_parent_id(tree, target_id).ok_or_else(|| not_found(target_id))?;
578    let parent = find_node_by_id_mut(tree, &parent_id).ok_or_else(|| not_found(&parent_id))?;
579    let slot = parent.children.iter_mut().find(|c| c.id == target_id).ok_or_else(|| not_found(target_id))?;
580    new_node.size = slot.size;
581    *slot = new_node;
582    Ok(())
583}
584
585/// `splitHorizontal` / `splitVertical`: splice next to the target in a parent
586/// already running in `direction`, else wrap the target and the new node in a
587/// new `direction` branch that takes the target's old footprint.
588fn split(
589    root: &mut Option<LayoutNode>,
590    target_id: &str,
591    mut new_node: LayoutNode,
592    position: SplitPosition,
593    size_fraction: Option<f64>,
594    direction: FlexDirection,
595    ids: &mut NodeIds,
596) -> Result<(), LayoutError> {
597    let tree = tree_mut(root)?;
598    let target = find_node_by_id_mut(tree, target_id).ok_or_else(|| not_found(target_id))?;
599    if is_effectively_minimized(target) {
600        return Err(LayoutError::NodeLocked { id: target_id.to_string() });
601    }
602    let original_size = target.size;
603    if let Some(fraction) = size_fraction {
604        // `applySizeFraction`: carve the new node out of the target.
605        let fraction = fraction.clamp(0.05, 0.95);
606        new_node.size = (fraction * f64::from(original_size)) as f32;
607        target.size = ((1.0 - fraction) * f64::from(original_size)) as f32;
608    }
609    let ordered = |target: LayoutNode, new_node: LayoutNode| match position {
610        SplitPosition::Before => vec![new_node, target],
611        SplitPosition::After => vec![target, new_node],
612    };
613    let Some(parent_id) = find_parent_id(tree, target_id) else {
614        let target = root.take().expect("checked above");
615        *root = Some(new_node_group(direction, original_size, ordered(target, new_node), ids));
616        return Ok(());
617    };
618    let parent = find_node_by_id_mut(tree, &parent_id).ok_or_else(|| not_found(&parent_id))?;
619    let index = parent.children.iter().position(|c| c.id == target_id).ok_or_else(|| not_found(target_id))?;
620    if parent.flex_direction == direction {
621        let at = match position {
622            SplitPosition::Before => index,
623            SplitPosition::After => index + 1,
624        };
625        parent.children.insert(at, new_node);
626    } else {
627        let target = parent.children.remove(index);
628        let group = new_node_group(direction, original_size, ordered(target, new_node), ids);
629        parent.children.insert(index, group);
630    }
631    Ok(())
632}
633
634fn new_node_group(direction: FlexDirection, size: f32, children: Vec<LayoutNode>, ids: &mut NodeIds) -> LayoutNode {
635    new_node(direction, size, children, None, ids)
636}
637
638/// `minimizeNode` / `restoreNode`: set a leaf's display-mode flag. Minimizing
639/// the last pane still showing content is refused: the window always keeps
640/// one (`countExpandedLeaves`, layoutMinimize.ts).
641fn set_minimized(tree: &mut LayoutNode, node_id: &str, minimized: bool) -> Result<(), LayoutError> {
642    let expanded = expanded_leaves(tree);
643    let node = find_node_by_id_mut(tree, node_id).ok_or_else(|| not_found(node_id))?;
644    if !node.children.is_empty() {
645        return Err(LayoutError::Refused(format!("{node_id} is not a pane (minimize is leaf-only)")));
646    }
647    if minimized && !node.minimized && expanded <= 1 {
648        return Err(LayoutError::Refused(format!("{node_id} is the last pane showing content")));
649    }
650    node.minimized = minimized;
651    Ok(())
652}
653
654/// `restoreNode`: show a minimized leaf again. A chip docked onto a pane of its Row (it has no
655/// column of its own: `resolveRowSlipTargets`, layoutSlip.ts) grows in that pane's column rather
656/// than in the column it was minimized from: the chips docked onto the same pane move into the
657/// pane's column in the order they were stacked, where chips render in place, and the restored one
658/// grows vertically in its own spot (`moveStackIntoDockColumn`, layoutRestore.ts).
659fn restore_node(root: &mut Option<LayoutNode>, node_id: &str, ids: &mut NodeIds) -> Result<(), LayoutError> {
660    let tree = tree_mut(root)?;
661    let stack = docked_stack_of(tree, node_id);
662    set_minimized(tree, node_id, false)?;
663    if let Some((row_id, dock_id, item_ids)) = stack {
664        move_stack_into_dock_column(tree, &row_id, &dock_id, &item_ids, ids)?;
665    }
666    Ok(())
667}
668
669/// The index of the sibling a child of a Row docks onto: the nearest expanded one, right-preferred,
670/// else left (`resolveRowSlipTargets`). None for an expanded child, or when every sibling is a chip.
671fn slip_dock_index(children: &[LayoutNode], i: usize) -> Option<usize> {
672    if !is_effectively_minimized(&children[i]) {
673        return None;
674    }
675    let expanded = |j: &usize| !is_effectively_minimized(&children[*j]);
676    ((i + 1)..children.len()).find(expanded).or_else(|| (0..i).rev().find(expanded))
677}
678
679/// The Row, the pane and the chips (in stacking order) a restore of `node_id` involves, when that
680/// pane is a chip docked onto a sibling in its Row (`dockedStackOf`, layoutRestore.ts).
681fn docked_stack_of(tree: &LayoutNode, node_id: &str) -> Option<(String, String, Vec<String>)> {
682    let node = find_node_by_id(tree, node_id)?;
683    if !node.children.is_empty() || !node.minimized {
684        return None;
685    }
686    let mut top = node_id.to_string();
687    let mut parent = find_node_by_id(tree, &find_parent_id(tree, &top)?)?;
688    while is_effectively_minimized(parent) {
689        top = parent.id.clone();
690        parent = find_node_by_id(tree, &find_parent_id(tree, &top)?)?;
691    }
692    if parent.flex_direction != FlexDirection::Row {
693        return None;
694    }
695    let at = parent.children.iter().position(|c| c.id == top)?;
696    let dock = &parent.children[slip_dock_index(&parent.children, at)?];
697    let items = (0..parent.children.len())
698        .filter(|i| slip_dock_index(&parent.children, *i).is_some_and(|j| parent.children[j].id == dock.id))
699        .map(|i| parent.children[i].id.clone())
700        .collect();
701    Some((parent.id.clone(), dock.id.clone(), items))
702}
703
704/// `moveStackIntoDockColumn` (layoutRestore.ts): the chips docked onto `dock_id` go into its column,
705/// in front of its panes. A pane that is not a column yet becomes one, with the chips above it.
706fn move_stack_into_dock_column(
707    tree: &mut LayoutNode,
708    row_id: &str,
709    dock_id: &str,
710    item_ids: &[String],
711    ids: &mut NodeIds,
712) -> Result<(), LayoutError> {
713    let row = find_node_by_id_mut(tree, row_id).ok_or_else(|| not_found(row_id))?;
714    let dock_index = row.children.iter().position(|c| c.id == dock_id).ok_or_else(|| not_found(dock_id))?;
715    let dock = &row.children[dock_index];
716    let column = !dock.children.is_empty() && dock.flex_direction == FlexDirection::Column;
717    // Each moved pane gets a share the column's own panes have, in the column's units.
718    let share = if column {
719        let sizes: Vec<f64> = dock.children.iter().map(|c| f64::from(c.size)).filter(|s| *s > 0.0).collect();
720        if sizes.is_empty() { DEFAULT_NODE_SIZE } else { (sizes.iter().sum::<f64>() / sizes.len() as f64) as f32 }
721    } else {
722        dock.size
723    };
724    let (items, rest): (Vec<LayoutNode>, Vec<LayoutNode>) =
725        std::mem::take(&mut row.children).into_iter().partition(|c| item_ids.contains(&c.id));
726    row.children = rest;
727    // A stack of chips that is itself a column gives its panes to the column.
728    let mut moved: Vec<LayoutNode> = items
729        .into_iter()
730        .flat_map(|item| {
731            if !item.children.is_empty() && item.flex_direction == FlexDirection::Column {
732                item.children
733            } else {
734                vec![item]
735            }
736        })
737        .collect();
738    for leaf in moved.iter_mut().filter(|n| n.children.is_empty()) {
739        leaf.size = share;
740    }
741    let dock_index = row.children.iter().position(|c| c.id == dock_id).ok_or_else(|| not_found(dock_id))?;
742    if column {
743        let dock = &mut row.children[dock_index];
744        moved.append(&mut dock.children);
745        dock.children = moved;
746    } else {
747        let dock = row.children.remove(dock_index);
748        let size = dock.size;
749        moved.push(dock);
750        row.children.insert(dock_index, new_node_group(FlexDirection::Column, size, moved, ids));
751    }
752    Ok(())
753}
754
755/// Leaves still showing content.
756fn expanded_leaves(node: &LayoutNode) -> usize {
757    if node.children.is_empty() {
758        return usize::from(node.data.is_some() && !super::is_node_locked(node));
759    }
760    node.children.iter().map(expanded_leaves).sum()
761}
762
763// ── Legacy minimize fields ───────────────────────────────────────────────────
764
765/// Migrate the pre-display-mode minimize fields to the `minimized` flag. This is
766/// the only place it happens: srv runs it on every tree it loads at bootstrap
767/// (`heal_loaded_layout`) and before every intent, so the window is never given
768/// a tree that carries them. Returns how many fields it migrated (0 for a
769/// current tree).
770pub fn migrate_legacy_minimize(root: &mut LayoutNode) -> usize {
771    migrate_node(root, DEFAULT_NODE_SIZE)
772}
773
774fn migrate_node(node: &mut LayoutNode, sane_share: f32) -> usize {
775    let mut migrated = 0;
776    let is_leaf = node.children.is_empty();
777    if let Some(original) = node.extra.remove("minimizedSize") {
778        if is_leaf {
779            if let Some(size) = original.as_f64() {
780                node.size = size as f32;
781            }
782            node.minimized = true;
783        }
784        migrated += 1;
785    }
786    if node.extra.remove("slipMinimize").is_some() {
787        node.size = sane_share;
788        if is_leaf {
789            node.minimized = true;
790        }
791        migrated += 1;
792    }
793    if node.extra.remove("columnDissolve").is_some() {
794        node.size = sane_share;
795        migrated += 1;
796    }
797    for key in ["minimizedLockedSize", "_slipAnchor"] {
798        if node.extra.remove(key).is_some() {
799            migrated += 1;
800        }
801    }
802    for i in 0..node.children.len() {
803        let share = mean_sibling_size(&node.children, i);
804        migrated += migrate_node(&mut node.children[i], share);
805    }
806    migrated
807}
808
809/// The mean size of child `i`'s positive-sized siblings, else the default.
810fn mean_sibling_size(children: &[LayoutNode], i: usize) -> f32 {
811    let sizes: Vec<f32> = children
812        .iter()
813        .enumerate()
814        .filter(|(j, c)| *j != i && c.size > 0.0)
815        .map(|(_, c)| c.size)
816        .collect();
817    if sizes.is_empty() {
818        DEFAULT_NODE_SIZE
819    } else {
820        sizes.iter().sum::<f32>() / sizes.len() as f32
821    }
822}
823
824#[cfg(test)]
825mod tests;
826
827#[cfg(test)]
828mod edge_tests;