agentmux_srv_core/backend/layout/mod.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pure layout-tree functions for the srv reducer: traversal, pane-tab
5//! stacks, the write-point integrity passes (dangling blocks, invariants),
6//! `balance_node`, and the frontend's tree actions as layout intents
7//! ([`intent`]). No I/O, no side effects.
8
9pub mod drop_split;
10pub mod intent;
11pub mod place;
12
13use agentmux_common::{FlexDirection, LayoutNode, StackMovePosition};
14
15// ── Error type ─────────────────────────────────────────────────────────────
16
17#[derive(Debug, Clone, PartialEq)]
18pub enum LayoutError {
19 NodeNotFound { id: String },
20 /// Caller tried to swap a node with itself.
21 SelfSwap,
22 /// Caller tried to swap, move, or magnify the root node.
23 RootCannotBeTarget,
24 /// A resize op had size outside [0.0, 100.0].
25 InvalidSize { node_id: String, size: f32 },
26 /// index_arr was empty or led to a non-existent location.
27 InvalidIndexPath,
28 /// A node failed the leaf-XOR-branch invariant during balance — it has
29 /// both `data` and `children`, or neither. The TS oracle (`validateNode`
30 /// in `layoutNode.ts`) throws "Invalid node" here.
31 InvalidNode { id: String },
32 /// The op targets a minimize-locked node (minimized leaf, slipped header,
33 /// or dissolved column). Minimized is a locked state — see
34 /// `docs/specs/SPEC_LAYOUT_MINIMIZE_LOCKED_STATE_REDESIGN_2026_07_16.md`.
35 NodeLocked { id: String },
36 /// An intent the reducer won't apply, with the reason.
37 Refused(String),
38}
39
40impl std::fmt::Display for LayoutError {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 match self {
43 Self::NodeNotFound { id } => write!(f, "node not found: {}", id),
44 Self::SelfSwap => write!(f, "cannot swap a node with itself"),
45 Self::RootCannotBeTarget => write!(f, "root node cannot be the target of this operation"),
46 Self::InvalidSize { node_id, size } => write!(f, "invalid size {:.2} for node {}", size, node_id),
47 Self::InvalidIndexPath => write!(f, "index_arr is empty or points to a non-existent location"),
48 Self::InvalidNode { id } => write!(f, "invalid node (leaf-XOR-branch violated): {}", id),
49 Self::NodeLocked { id } => write!(f, "node is minimize-locked: {}", id),
50 Self::Refused(reason) => f.write_str(reason),
51 }
52 }
53}
54
55// ── Constants ──────────────────────────────────────────────────────────────
56
57/// Maximum children before `insert_node`'s heuristic descends.
58/// Mirrors `frontend/layout/lib/layoutTree.ts::DEFAULT_MAX_CHILDREN`.
59pub const DEFAULT_MAX_CHILDREN: usize = 5;
60
61/// Default flex size for newly-inserted nodes.
62/// Mirrors `frontend/layout/lib/types.ts::DefaultNodeSize`.
63pub const DEFAULT_NODE_SIZE: f32 = 10.0;
64
65// ── Flex-direction utilities ───────────────────────────────────────────────
66
67/// Reverse a flex direction (Row ↔ Column).
68/// Mirrors `frontend/layout/lib/layoutNode.ts::reverseFlexDirection`.
69fn reverse_flex_direction(dir: FlexDirection) -> FlexDirection {
70 match dir {
71 FlexDirection::Row => FlexDirection::Column,
72 FlexDirection::Column => FlexDirection::Row,
73 }
74}
75
76// ── Tree traversal ─────────────────────────────────────────────────────────
77
78/// Find a node by id (immutable).
79pub fn find_node_by_id<'a>(tree: &'a LayoutNode, id: &str) -> Option<&'a LayoutNode> {
80 if tree.id == id {
81 return Some(tree);
82 }
83 for child in &tree.children {
84 if let Some(found) = find_node_by_id(child, id) {
85 return Some(found);
86 }
87 }
88 None
89}
90
91/// Find a node by id (mutable).
92pub fn find_node_by_id_mut<'a>(tree: &'a mut LayoutNode, id: &str) -> Option<&'a mut LayoutNode> {
93 if tree.id == id {
94 return Some(tree);
95 }
96 for child in &mut tree.children {
97 if let Some(found) = find_node_by_id_mut(child, id) {
98 return Some(found);
99 }
100 }
101 None
102}
103
104/// Find the id of the (first) leaf node whose `data.block_id` matches
105/// `block_id`. SPEC_864 site #6 — lets `LayoutDeleteNodeByBlock` resolve a
106/// block to its layout node inside the reducer arm (the reducer owns the
107/// tree; callers like the `delete_block` saga only know the block id).
108/// Blocks appear at most once in a well-formed tree; first match wins.
109#[cfg(test)]
110pub fn find_node_id_by_block(tree: &LayoutNode, block_id: &str) -> Option<String> {
111 if tree
112 .data
113 .as_ref()
114 .is_some_and(|d| d.block_id == block_id)
115 {
116 return Some(tree.id.clone());
117 }
118 for child in &tree.children {
119 if let Some(found) = find_node_id_by_block(child, block_id) {
120 return Some(found);
121 }
122 }
123 None
124}
125
126/// A leaf's members: its `block_stack`, or `[block_id]` for a leaf with no
127/// stack (mirrors the frontend's `effectiveStack`, `layoutStack.ts`).
128pub fn leaf_members(data: &agentmux_common::LayoutNodeData) -> Vec<String> {
129 if data.block_stack.is_empty() {
130 vec![data.block_id.clone()]
131 } else {
132 data.block_stack.clone()
133 }
134}
135
136/// Find the (first) leaf that has `block_id` as its visible block OR as any
137/// member of its `block_stack`. Unlike [`find_node_id_by_block`], which only
138/// matches the visible block, this finds the pane a background tab lives in.
139/// Returns the leaf node itself.
140pub fn find_leaf_containing_block<'a>(tree: &'a LayoutNode, block_id: &str) -> Option<&'a LayoutNode> {
141 if let Some(d) = tree.data.as_ref() {
142 if d.block_id == block_id || d.block_stack.iter().any(|b| b == block_id) {
143 return Some(tree);
144 }
145 }
146 tree.children
147 .iter()
148 .find_map(|child| find_leaf_containing_block(child, block_id))
149}
150
151/// Which tab becomes visible once the one at `removed_idx` of the ORIGINAL
152/// stack is gone: the nearest eligible member to its right, else the nearest
153/// to its left. `remaining` is the stack with it removed; `eligible` filters
154/// (e.g. "still exists"). The one rule every removal path uses — frontend
155/// `removeMemberFromStack` mirrors it (`frontend/layout/lib/stackMembers.ts`).
156/// SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.6.
157pub fn next_visible_member(
158 remaining: &[String],
159 removed_idx: usize,
160 eligible: impl Fn(&String) -> bool,
161) -> Option<String> {
162 let split = removed_idx.min(remaining.len());
163 remaining[split..]
164 .iter()
165 .find(|m| eligible(m))
166 .or_else(|| remaining[..split].iter().rev().find(|m| eligible(m)))
167 .cloned()
168}
169
170/// Add `block_id` to the tab stack of the pane holding `target_block_id`
171/// (as its visible tab or a background member). A pane with no stack yet
172/// becomes a two-member stack. Already a member → only (re)activated if
173/// asked. Returns false when no pane holds `target_block_id`.
174/// SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.2 (`LayoutStackPush`).
175pub fn push_stack_member(tree: &mut LayoutNode, target_block_id: &str, block_id: &str, activate: bool) -> bool {
176 if let Some(data) = tree.data.as_mut() {
177 if data.block_id == target_block_id || data.block_stack.iter().any(|b| b == target_block_id) {
178 if data.block_stack.is_empty() {
179 data.block_stack = vec![data.block_id.clone()];
180 data.active_block_id = data.block_id.clone();
181 }
182 if !data.block_stack.iter().any(|b| b == block_id) {
183 data.block_stack.push(block_id.to_string());
184 }
185 if activate {
186 data.block_id = block_id.to_string();
187 data.active_block_id = block_id.to_string();
188 }
189 return true;
190 }
191 }
192 tree.children
193 .iter_mut()
194 .any(|child| push_stack_member(child, target_block_id, block_id, activate))
195}
196
197/// Make `block_id` the visible tab of the pane whose stack holds it.
198/// Returns false when no pane's stack holds it.
199/// SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.2 (`LayoutStackActivate`).
200pub fn activate_stack_member(tree: &mut LayoutNode, block_id: &str) -> bool {
201 if let Some(data) = tree.data.as_mut() {
202 if leaf_members(data).iter().any(|m| m == block_id) {
203 data.block_id = block_id.to_string();
204 if !data.block_stack.is_empty() {
205 data.active_block_id = block_id.to_string();
206 }
207 return true;
208 }
209 }
210 tree.children.iter_mut().any(|child| activate_stack_member(child, block_id))
211}
212
213/// Remove `block_id` from the stack of the leaf holding it, WITHOUT removing
214/// the leaf, when that leaf has other members. If it was the visible tab, the
215/// right-hand neighbour becomes visible (the new last member when it was
216/// rightmost) — the same rule as the frontend's `removeMemberFromStack`
217/// (`frontend/layout/lib/stackMembers.ts`). Returns false and changes nothing
218/// when `block_id` is in no leaf or is its leaf's only member (removing it
219/// means removing the leaf — the caller's job).
220/// SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.4.
221pub fn remove_stack_member(tree: &mut LayoutNode, block_id: &str) -> bool {
222 if let Some(data) = tree.data.as_mut() {
223 let members = leaf_members(data);
224 if let Some(idx) = members.iter().position(|m| m == block_id) {
225 if members.len() <= 1 {
226 return false;
227 }
228 let next: Vec<String> = members.into_iter().filter(|m| m != block_id).collect();
229 if data.block_id == block_id || data.active_block_id == block_id {
230 let visible = next_visible_member(&next, idx, |_| true).expect("next is non-empty");
231 data.block_id = visible.clone();
232 data.active_block_id = visible;
233 }
234 data.block_stack = next;
235 return true;
236 }
237 }
238 tree.children
239 .iter_mut()
240 .any(|child| remove_stack_member(child, block_id))
241}
242
243/// Move `block_id` to `position` relative to `target_block_id`: a same-leaf
244/// reorder when both are already members of one leaf's stack, otherwise a
245/// cross-leaf move (removed from its source leaf via [`remove_stack_member`],
246/// placed into `target_block_id`'s leaf via a position-aware push). Returns
247/// `false`, leaving the tree untouched, when either block doesn't exist in
248/// the tree.
249///
250/// When `block_id` is its source leaf's ONLY member, the cross-leaf move
251/// empties that pane, so the source leaf is deleted from the tree and the
252/// tree balanced, as the frontend does ([`intent::delete_and_balance`]). This is a move:
253/// the block itself lives on in the destination.
254/// [`source_leaf_emptied_by_move`] tells a caller in advance whether this
255/// will happen, so it can reconcile focus/magnify that pointed at that leaf.
256/// SPEC_PANE_TAB_DRAG_LANDING_FLASH_AND_LAST_TAB_CLOSE_2026_09_24.md §4.3.
257///
258/// Deliberately NOT a same-leaf-and-cross-leaf-both composition of
259/// `remove_stack_member` + a push: `remove_stack_member`'s neighbour
260/// reassignment assumes the member is actually leaving its leaf, and wrongly
261/// switches the visible tab if applied to a same-leaf reorder of the
262/// currently-visible member (see
263/// `move_stack_member_reorder_does_not_change_which_tab_is_visible` in
264/// `tests.rs`). The same-leaf branch below never touches
265/// `block_id`/`active_block_id` unless `activate` is explicitly set.
266///
267/// SPEC_PANE_TAB_DRAG_AND_DROP_2026_09_19.md §4.1.
268pub fn move_stack_member(
269 tree: &mut LayoutNode,
270 block_id: &str,
271 target_block_id: &str,
272 position: StackMovePosition,
273 activate: bool,
274) -> bool {
275 if block_id == target_block_id {
276 // Not a real move — nothing to reorder against — but still confirm
277 // the block actually exists (a bogus self-target must not report
278 // success), and still honor `activate` exactly like every other
279 // branch below does (ReAgent P1 on PR #3441: this used to
280 // short-circuit before either check).
281 if find_leaf_containing_block(tree, block_id).is_none() {
282 return false;
283 }
284 return if activate { activate_stack_member(tree, block_id) } else { true };
285 }
286 let Some(source_leaf) = find_leaf_containing_block(tree, block_id) else {
287 return false;
288 };
289 let source_node_id = source_leaf.id.clone();
290 let source_members = leaf_members(source_leaf.data.as_ref().expect("leaf has data"));
291 if source_members.iter().any(|m| m == target_block_id) {
292 return reorder_within_leaf(tree, block_id, target_block_id, position, activate);
293 }
294 // Validate the destination exists BEFORE mutating anything — otherwise
295 // a bad `target_block_id` would still remove `block_id` from its source
296 // leaf and then fail to place it anywhere, corrupting the tree.
297 if find_leaf_containing_block(tree, target_block_id).is_none() {
298 return false;
299 }
300 if source_members.len() <= 1 {
301 // The pane's only tab: the move empties it, so the pane goes. Place
302 // the block first (located by block id, which survives the collapse
303 // below), then delete the source leaf by node id — both inside this
304 // one `&mut` edit, so no caller ever sees the block in two leaves or
305 // in none. The source can't be the root: the destination is a
306 // different leaf in the same tree, so the root has ≥2 leaves under it.
307 if tree.id == source_node_id {
308 return false;
309 }
310 if !push_stack_member_at(tree, target_block_id, block_id, position, activate) {
311 return false;
312 }
313 return intent::delete_and_balance(tree, &source_node_id).is_ok();
314 }
315 if !remove_stack_member(tree, block_id) {
316 return false;
317 }
318 push_stack_member_at(tree, target_block_id, block_id, position, activate)
319}
320
321/// Move every block in `block_ids` that is not already in `target_block_id`'s
322/// leaf into it, appended in the order given (each as [`move_stack_member`]
323/// with [`StackMovePosition::End`] would), then make `activate_block_id` the
324/// leaf's visible tab when it is one of its members.
325///
326/// All or nothing: it works on a copy and replaces `tree` only when every
327/// step succeeded, so a block missing from the tree, a missing target, or a
328/// refused step leaves the tree as it was and returns `None`. On success it
329/// returns the node ids of the panes emptied (and so removed) by the move, in
330/// the order they went. Blocks already in the target's leaf stay where they
331/// are, and a repeated id is moved once.
332/// SPEC_PANE_TAB_MULTI_SELECT_MOVE_AND_COLLAPSED_EXPAND_2026_10_24.md §5.
333pub fn move_stack_members(
334 tree: &mut LayoutNode,
335 block_ids: &[String],
336 target_block_id: &str,
337 activate_block_id: Option<&str>,
338) -> Option<Vec<String>> {
339 let mut work = tree.clone();
340 let target_members = leaf_members(find_leaf_containing_block(&work, target_block_id)?.data.as_ref()?);
341 let mut seen: Vec<&str> = Vec::new();
342 let mut emptied = Vec::new();
343 for block_id in block_ids {
344 find_leaf_containing_block(&work, block_id)?;
345 if target_members.iter().any(|m| m == block_id) || seen.contains(&block_id.as_str()) {
346 continue;
347 }
348 seen.push(block_id);
349 if let Some(node_id) = source_leaf_emptied_by_move(&work, block_id, target_block_id) {
350 emptied.push(node_id);
351 }
352 if !move_stack_member(&mut work, block_id, target_block_id, StackMovePosition::End, false) {
353 return None;
354 }
355 }
356 if let Some(active) = activate_block_id {
357 let leaf = find_leaf_containing_block(&work, target_block_id)?;
358 if !leaf_members(leaf.data.as_ref()?).iter().any(|m| m == active) || !activate_stack_member(&mut work, active) {
359 return None;
360 }
361 }
362 *tree = work;
363 Some(emptied)
364}
365
366/// The node id of `block_id`'s leaf, when `move_stack_member(tree, block_id,
367/// target_block_id, ..)` would delete that leaf: `block_id` is its only
368/// member and `target_block_id` lives in a different leaf. `None` for every
369/// other move (reorder, multi-member source, missing blocks, self-target).
370pub fn source_leaf_emptied_by_move(tree: &LayoutNode, block_id: &str, target_block_id: &str) -> Option<String> {
371 if block_id == target_block_id {
372 return None;
373 }
374 let source = find_leaf_containing_block(tree, block_id)?;
375 let members = leaf_members(source.data.as_ref()?);
376 if members.len() != 1 || source.id == tree.id {
377 return None;
378 }
379 find_leaf_containing_block(tree, target_block_id)
380 .filter(|target| target.id != source.id)
381 .map(|_| source.id.clone())
382}
383
384/// Splice `block_id` to `position` relative to `target_block_id` within the
385/// SAME leaf's stack. Both must already be members of that leaf (checked by
386/// the caller, `move_stack_member`). Only touches `block_id`/`active_block_id`
387/// when `activate` is set — a reorder alone never changes which member is
388/// visible.
389fn reorder_within_leaf(
390 tree: &mut LayoutNode,
391 block_id: &str,
392 target_block_id: &str,
393 position: StackMovePosition,
394 activate: bool,
395) -> bool {
396 if let Some(data) = tree.data.as_mut() {
397 let members = leaf_members(data);
398 if members.iter().any(|m| m == block_id) && members.iter().any(|m| m == target_block_id) {
399 let mut next: Vec<String> = members.into_iter().filter(|m| m != block_id).collect();
400 let target_idx = next.iter().position(|m| m == target_block_id).expect("target survives removal");
401 let insert_at = match position {
402 StackMovePosition::Before => target_idx,
403 StackMovePosition::After => target_idx + 1,
404 StackMovePosition::End => next.len(),
405 };
406 next.insert(insert_at, block_id.to_string());
407 data.block_stack = next;
408 if activate {
409 data.block_id = block_id.to_string();
410 data.active_block_id = block_id.to_string();
411 }
412 return true;
413 }
414 }
415 tree.children
416 .iter_mut()
417 .any(|child| reorder_within_leaf(child, block_id, target_block_id, position, activate))
418}
419
420/// Position-aware variant of [`push_stack_member`]: adds `block_id` to the
421/// stack of the leaf holding `target_block_id`, at `position` relative to
422/// `target_block_id` instead of always appending. Promotes a single-block
423/// leaf (empty `block_stack`) into a real stack first, exactly like
424/// `push_stack_member` does.
425fn push_stack_member_at(
426 tree: &mut LayoutNode,
427 target_block_id: &str,
428 block_id: &str,
429 position: StackMovePosition,
430 activate: bool,
431) -> bool {
432 if let Some(data) = tree.data.as_mut() {
433 if data.block_id == target_block_id || data.block_stack.iter().any(|b| b == target_block_id) {
434 if data.block_stack.is_empty() {
435 data.block_stack = vec![data.block_id.clone()];
436 data.active_block_id = data.block_id.clone();
437 }
438 if !data.block_stack.iter().any(|b| b == block_id) {
439 let target_idx = data.block_stack.iter().position(|b| b == target_block_id).expect("target present");
440 let insert_at = match position {
441 StackMovePosition::Before => target_idx,
442 StackMovePosition::After => target_idx + 1,
443 StackMovePosition::End => data.block_stack.len(),
444 };
445 data.block_stack.insert(insert_at, block_id.to_string());
446 }
447 if activate {
448 data.block_id = block_id.to_string();
449 data.active_block_id = block_id.to_string();
450 }
451 return true;
452 }
453 }
454 tree.children
455 .iter_mut()
456 .any(|child| push_stack_member_at(child, target_block_id, block_id, position, activate))
457}
458
459/// Removes every leaf whose `data.block_id` is not in `live_block_ids`,
460/// using the same collapse semantics as an explicit user delete
461/// (`delete_node`'s single-child-parent promotion). Returns the number of
462/// leaves pruned (0 = tree was already clean — the common case, so this is
463/// cheap to call unconditionally on every write).
464///
465/// This is the reducer's referential-integrity enforcement for `db_layout`,
466/// added after
467/// `docs/investigations/INVESTIGATION_LAYOUT_DEAD_SPACE_STALE_TREE_RESURRECTION_2026_07_08.md`
468/// found that a single point-fix (notifying the frontend on one specific
469/// delete path) only closes the one mechanism it targets — any other
470/// current or future caller that writes a stale/bad tree without going
471/// through that same notification channel can still leave a dangling
472/// `blockId` behind. Calling this at every layout-tree write site in the
473/// reducer (the single writer of `db_layout` since SPEC_864) makes "no
474/// layout leaf ever references a nonexistent block" an unconditional
475/// invariant of the write path itself, not a property individual callers
476/// have to remember to uphold — the same shape as WRR (Window Reality
477/// Reconciliation, `crates/cef/src/wrr/`) enforcing "no window/pool
478/// drift" at the point where reality is observed, rather than trusting
479/// every caller to keep the model in sync.
480///
481/// Re-scans the tree fresh after each removal rather than working off a
482/// pre-computed list of dangling node ids, since `delete_node`'s
483/// single-child collapse can rewrite a surviving parent's id out from
484/// under a stale id — see the comment on `delete_recursive`. Terminates
485/// because each iteration strictly shrinks the tree (bounded by leaf
486/// count).
487pub fn prune_dangling_block_refs(
488 root: &mut Option<LayoutNode>,
489 live_block_ids: &std::collections::HashSet<String>,
490) -> usize {
491 let mut pruned = 0;
492 // In-pane tabs: if a leaf's ACTIVE block went dangling through some
493 // path other than `closeBlockInStack` (which always reactivates a live
494 // neighbor before removing a block), but a live sibling still sits in
495 // `block_stack`, reactivate that sibling in place rather than letting
496 // the whole-leaf scan below delete the entire leaf — that would
497 // silently discard the still-live sibling blocks along with it. MUST
498 // run before the whole-leaf loop so that loop sees the repaired
499 // `block_id`. Leaves with no live sibling are left untouched here —
500 // `block_id` still points at the dangling id, so the loop below
501 // correctly identifies and deletes the (genuinely fully-dead) leaf.
502 if let Some(tree) = root.as_mut() {
503 pruned += reactivate_dangling_active_stack_members(tree, live_block_ids);
504 }
505 loop {
506 let Some(tree) = root.as_ref() else { break };
507 let Some(dangling_id) = first_dangling_leaf_id(tree, live_block_ids) else { break };
508 pruned += 1;
509 if tree.id == dangling_id {
510 // Root is itself the dangling leaf (single-block tab) —
511 // delete_node leaves root deletion to the caller.
512 *root = None;
513 continue;
514 }
515 if let Some(t) = root.as_mut() {
516 // Pruning is a removal too: if the pruned pane was the only one showing content (or the
517 // one a delete just restored), the nearest minimized pane is shown, as after a close.
518 let before = intent::leaf_ids(t);
519 // A `NodeNotFound` here would mean the id vanished via this
520 // same loop's prior collapse without our fresh re-scan
521 // catching it first — shouldn't happen given the re-scan, but
522 // isn't a correctness problem either way: the node is gone,
523 // which is the outcome we wanted.
524 let _ = delete_node(t, &dangling_id);
525 intent::restore_nearest_if_all_minimized(t, &before, std::slice::from_ref(&dangling_id));
526 }
527 }
528 // In-pane tabs (SPEC_PANE_TAB_STRIP_AGENT_TERMINAL_2026_07_20.md §4.3):
529 // a surviving leaf's ACTIVE block (`data.block_id`) is already
530 // guaranteed live by the loop above, but a non-active `block_stack`
531 // member's block can independently be deleted without ever making the
532 // leaf itself dangling — the leaf still renders fine via its active
533 // member. Without this pass those ids would linger in `block_stack`
534 // forever, so a later tab-switch could try to activate a block that no
535 // longer exists.
536 if let Some(tree) = root.as_mut() {
537 pruned += prune_dangling_stack_members(tree, live_block_ids);
538 }
539 pruned
540}
541
542/// Recursively repair leaves whose ACTIVE block (`data.block_id`) is
543/// dangling but a live sibling still exists in `block_stack`: drop the
544/// dead entry from the stack and reactivate the first remaining live
545/// member (`block_id`/`active_block_id` both updated). Leaves with no live
546/// sibling are left with `block_id` still pointing at the dangling id —
547/// the caller's whole-leaf pass then correctly deletes them, same as
548/// before this function existed. Returns the number of leaves repaired.
549fn reactivate_dangling_active_stack_members(
550 node: &mut LayoutNode,
551 live_block_ids: &std::collections::HashSet<String>,
552) -> usize {
553 let mut repaired = 0;
554 if let Some(data) = node.data.as_mut() {
555 if !data.block_stack.is_empty() && !live_block_ids.contains(&data.block_id) {
556 // Drop the dangling active member from the stack — it's gone
557 // either way, whether or not a live sibling survives it.
558 // Its replacement follows the same right-hand-neighbour rule as
559 // every other removal (`next_visible_member`) — this used to pick
560 // the FIRST live member, disagreeing with the frontend.
561 let dead_idx = data.block_stack.iter().position(|id| id == &data.block_id).unwrap_or(0);
562 data.block_stack.retain(|id| id != &data.block_id);
563 if let Some(replacement) =
564 next_visible_member(&data.block_stack, dead_idx, |id| live_block_ids.contains(id))
565 {
566 data.block_id = replacement.clone();
567 data.active_block_id = replacement;
568 repaired += 1;
569 }
570 // else: block_id is untouched (still the dangling id) — no live
571 // sibling to fall back to, so this leaf is genuinely fully dead.
572 }
573 }
574 for child in &mut node.children {
575 repaired += reactivate_dangling_active_stack_members(child, live_block_ids);
576 }
577 repaired
578}
579
580/// Recursively drop dead entries from every leaf's `block_stack`. The
581/// active member (`data.block_id`) is never removed here — by the time
582/// this runs, the caller's whole-leaf pruning loop has already guaranteed
583/// it's live. Returns the number of stack entries removed.
584fn prune_dangling_stack_members(
585 node: &mut LayoutNode,
586 live_block_ids: &std::collections::HashSet<String>,
587) -> usize {
588 let mut removed = 0;
589 if let Some(data) = node.data.as_mut() {
590 if !data.block_stack.is_empty() {
591 let before = data.block_stack.len();
592 data.block_stack
593 .retain(|id| id == &data.block_id || live_block_ids.contains(id));
594 removed += before - data.block_stack.len();
595 }
596 }
597 for child in &mut node.children {
598 removed += prune_dangling_stack_members(child, live_block_ids);
599 }
600 removed
601}
602
603/// A minimize-locked node: a minimized leaf (`minimizedSize`), a slipped
604/// header (`slipMinimize`), or a dissolved column (`columnDissolve`). The
605/// fields are written by the frontend minimize subsystem and round-trip
606/// through the untyped `extra` catch-all on this side. Mirrors
607/// `isNodeLocked` in `frontend/layout/lib/layoutMinimize.ts`.
608pub fn is_node_locked(node: &LayoutNode) -> bool {
609 // Current model: the `minimized` display-mode flag (geometry derived at
610 // render on the frontend; stored sizes never touched). The remaining keys
611 // are legacy markers from the pre-display-mode model, recognized until
612 // persisted trees are migrated by the frontend's `rebuildMinimizedSet`.
613 node.minimized
614 || node.extra.contains_key("minimizedSize")
615 || node.extra.contains_key("slipMinimize")
616 || node.extra.contains_key("columnDissolve")
617}
618
619/// True when a node renders as minimized: a locked leaf, or a branch whose
620/// every child is effectively minimized (a stacked chip strip). Mirrors
621/// `isEffectivelyMinimized` in `frontend/layout/lib/layoutInvariants.ts`.
622/// Reducer guards use THIS (not `is_node_locked`): a fully-collapsed branch
623/// has no branch-level marker in the display-mode model, but its stored size
624/// becomes load-bearing again the moment a child restores — so it must be
625/// just as untargetable as a minimized leaf.
626pub fn is_effectively_minimized(node: &LayoutNode) -> bool {
627 if node.children.is_empty() {
628 return is_node_locked(node);
629 }
630 node.children.iter().all(is_effectively_minimized)
631}
632
633/// Layout doctor — structural invariant validation, mirroring
634/// `validateLayoutInvariants` in `frontend/layout/lib/layoutInvariants.ts`
635/// (keep the check lists in sync). Returns human-readable violation strings;
636/// empty = healthy. Never mutates. Reducer choke points call this after
637/// prune/enforce and `tracing::error!` any findings, so a corrupted tree is
638/// attributed to the write that produced it instead of being reconstructed
639/// later from db_layout archaeology (issue #2179).
640pub fn validate_layout_invariants(root: &Option<LayoutNode>) -> Vec<String> {
641 let mut violations = Vec::new();
642 fn short(id: &str) -> &str {
643 &id[..id.len().min(8)]
644 }
645 fn walk(node: &LayoutNode, is_root: bool, violations: &mut Vec<String>) {
646 let is_branch = !node.children.is_empty();
647 let is_leaf = node.data.is_some();
648 let has = |k: &str| node.extra.contains_key(k);
649
650 // I1 — leaf XOR branch.
651 if is_branch == is_leaf {
652 violations.push(format!(
653 "LEAF_XOR_BRANCH @ {}: data {}, children {}",
654 short(&node.id),
655 if is_leaf { "present" } else { "absent" },
656 if is_branch { "present" } else { "absent" }
657 ));
658 }
659 // I2 — the `minimized` flag and the legacy minimizedSize/slipMinimize
660 // markers are leaf-only.
661 if is_branch && (node.minimized || has("minimizedSize") || has("slipMinimize")) {
662 violations.push(format!(
663 "MIN_MARKER_ON_BRANCH @ {}: branch has {}",
664 short(&node.id),
665 if node.minimized {
666 "minimized"
667 } else if has("minimizedSize") {
668 "minimizedSize"
669 } else {
670 "slipMinimize"
671 }
672 ));
673 }
674 // I3 — columnDissolve is branch-only.
675 if !is_branch && has("columnDissolve") {
676 violations.push(format!("DISSOLVE_ON_LEAF @ {}", short(&node.id)));
677 }
678 // I4 — a dissolved column must stack vertically (#2176 signature).
679 if has("columnDissolve") && node.flex_direction != FlexDirection::Column {
680 violations.push(format!(
681 "DISSOLVED_NOT_COLUMN @ {}: flex_direction={:?}",
682 short(&node.id),
683 node.flex_direction
684 ));
685 }
686 // I5 — every child of a dissolved column is itself locked.
687 if has("columnDissolve") {
688 for c in &node.children {
689 if !is_node_locked(c) {
690 violations.push(format!(
691 "DISSOLVED_CHILD_UNLOCKED @ {}: inside dissolved column {}",
692 short(&c.id),
693 short(&node.id)
694 ));
695 }
696 }
697 }
698 let locked_size = node.extra.get("minimizedLockedSize").and_then(|v| v.as_f64());
699 // I6 — a locked node's size honors its recorded lock (#2180).
700 if is_node_locked(node) {
701 if let Some(ls) = locked_size {
702 if (node.size - ls as f32).abs() > 1e-4 {
703 violations.push(format!(
704 "LOCK_SIZE_MISMATCH @ {}: size={} locked={}",
705 short(&node.id),
706 node.size,
707 ls
708 ));
709 }
710 }
711 } else if locked_size.is_some() {
712 // I7 — minimizedLockedSize must not outlive its lock marker.
713 violations.push(format!("ORPHAN_LOCKED_SIZE @ {}", short(&node.id)));
714 }
715 // I8 — sizes are positive.
716 if !is_root && !(node.size > 0.0) {
717 violations.push(format!("NONPOSITIVE_SIZE @ {}: size={}", short(&node.id), node.size));
718 }
719 // I10 — a pane's tab stack is consistent: the visible block is a
720 // member, `active_block_id` agrees with it, and no block appears
721 // twice (SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.1, I2).
722 if let Some(data) = node.data.as_ref().filter(|d| !d.block_stack.is_empty()) {
723 if !data.block_stack.contains(&data.block_id) {
724 violations.push(format!("STACK_VISIBLE_NOT_MEMBER @ {}", short(&node.id)));
725 }
726 if !data.active_block_id.is_empty() && data.active_block_id != data.block_id {
727 violations.push(format!("STACK_ACTIVE_MISMATCH @ {}", short(&node.id)));
728 }
729 let unique: std::collections::HashSet<&String> = data.block_stack.iter().collect();
730 if unique.len() != data.block_stack.len() {
731 violations.push(format!("STACK_DUPLICATE_MEMBER @ {}", short(&node.id)));
732 }
733 }
734 for c in &node.children {
735 walk(c, false, violations);
736 }
737 }
738 if let Some(tree) = root {
739 walk(tree, true, &mut violations);
740 // I9 — at least one pane stays expanded. A tree whose every leaf is
741 // minimize-locked is an all-headers window with nothing restorable
742 // in view; the frontend's minimize toggle guards against producing
743 // this (`countExpandedLeaves` in layoutMinimize.ts).
744 fn count_leaves(node: &LayoutNode, leaves: &mut usize, expanded: &mut usize) {
745 if node.children.is_empty() {
746 if node.data.is_some() {
747 *leaves += 1;
748 if !is_node_locked(node) {
749 *expanded += 1;
750 }
751 }
752 return;
753 }
754 for c in &node.children {
755 count_leaves(c, leaves, expanded);
756 }
757 }
758 let (mut leaves, mut expanded) = (0usize, 0usize);
759 count_leaves(tree, &mut leaves, &mut expanded);
760 if leaves > 0 && expanded == 0 {
761 violations.push(format!(
762 "ALL_LEAVES_LOCKED @ {}: all {} leaves are minimize-locked; no expanded pane remains",
763 &tree.id[..tree.id.len().min(8)],
764 leaves
765 ));
766 }
767 // I11 — a block is in at most one pane (the tree half of
768 // SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.1 I1; the other
769 // half, "in at least one", needs the tab's blocks: `unplaced_blocks`).
770 let mut pane_of: std::collections::HashMap<String, &str> = std::collections::HashMap::new();
771 for_each_leaf(tree, &mut |leaf, data| {
772 for member in leaf_members(data) {
773 if let Some(first) = pane_of.insert(member.clone(), &leaf.id).filter(|first| *first != leaf.id) {
774 violations.push(format!("BLOCK_IN_TWO_PANES @ {}: also in {}", short(&member), short(first)));
775 }
776 }
777 });
778 }
779 violations
780}
781
782/// The tab's blocks that are in no pane of its tree: the other half of I1
783/// (SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.1). Briefly true of a
784/// block on its way into a pane (a queued placement the frontend hasn't
785/// applied yet); a block that stays unplaced is an orphan.
786pub fn unplaced_blocks(root: &Option<LayoutNode>, block_ids: &[String]) -> Vec<String> {
787 let mut placed = std::collections::HashSet::new();
788 if let Some(tree) = root {
789 for_each_leaf(tree, &mut |_, data| placed.extend(leaf_members(data)));
790 }
791 block_ids.iter().filter(|b| !placed.contains(*b)).cloned().collect()
792}
793
794/// Visit every leaf (a node with `data`), depth first.
795fn for_each_leaf<'a>(node: &'a LayoutNode, f: &mut impl FnMut(&'a LayoutNode, &'a agentmux_common::LayoutNodeData)) {
796 if let Some(data) = node.data.as_ref() {
797 f(node, data);
798 }
799 for child in &node.children {
800 for_each_leaf(child, f);
801 }
802}
803
804/// First leaf (depth-first) whose `data.block_id` is set but not present in
805/// `live_block_ids`. `data.block_id` is only ever non-empty on leaves —
806/// container/group nodes have `data: None` (see `add_intermediate_node` in
807/// `intent.rs`).
808fn first_dangling_leaf_id(
809 node: &LayoutNode,
810 live_block_ids: &std::collections::HashSet<String>,
811) -> Option<String> {
812 if let Some(data) = &node.data {
813 if !data.block_id.is_empty() && !live_block_ids.contains(&data.block_id) {
814 return Some(node.id.clone());
815 }
816 }
817 for child in &node.children {
818 if let Some(found) = first_dangling_leaf_id(child, live_block_ids) {
819 return Some(found);
820 }
821 }
822 None
823}
824
825// ── Insert-location heuristic ──────────────────────────────────────────────
826
827/// Candidate for insertion location, collected during tree traversal.
828struct InsertCandidate<'a> {
829 node: &'a LayoutNode,
830 index: usize,
831 depth: usize,
832}
833
834fn collect_insert_candidates<'a>(
835 node: &'a LayoutNode,
836 max_children: usize,
837 depth: usize,
838 out: &mut Vec<InsertCandidate<'a>>,
839) {
840 // Minimized is a locked state: never a blind-insert target. Without
841 // this, `add_intermediate_node` (`intent.rs`) promoting a minimized leaf into a branch
842 // could leave the tree in a state where an agent/API-driven insert
843 // silently un-collapses a fully-minimized subtree (every child
844 // minimized → one child isn't anymore, with no user action on that
845 // branch at all). Mirrors `findNextInsertLocationHelper`'s guard in
846 // `frontend/layout/lib/layoutNode.ts` (2026-07-18). For a branch this
847 // also skips recursing into its children — they're all effectively
848 // minimized too by definition, so recursion would find nothing anyway.
849 if is_effectively_minimized(node) {
850 return;
851 }
852 // Leaf node (has data but no children) — TS returns index 1.
853 if node.data.is_some() && node.children.is_empty() {
854 out.push(InsertCandidate { node, index: 1, depth });
855 return;
856 }
857 if node.children.len() < max_children {
858 out.push(InsertCandidate {
859 node,
860 index: node.children.len(),
861 depth,
862 });
863 }
864 // TS iterates children in REVERSE order.
865 for child in node.children.iter().rev() {
866 collect_insert_candidates(child, max_children, depth + 1, out);
867 }
868}
869
870// ── Core operations ────────────────────────────────────────────────────────
871
872/// Remove the node with the given id from the tree.
873/// Returns `Ok(())` on success, or `Err(NodeNotFound)` if `node_id` is not
874/// in the tree. Callers are responsible for clearing `focused_node_id` if
875/// needed (spec §7.1). Collapses single-child parents.
876pub fn delete_node(root: &mut LayoutNode, node_id: &str) -> Result<(), LayoutError> {
877 if root.id == node_id {
878 // Root deletion is handled by the caller setting root = None.
879 return Ok(());
880 }
881 match delete_recursive(root, node_id) {
882 true => Ok(()),
883 false => Err(LayoutError::NodeNotFound { id: node_id.to_string() }),
884 }
885}
886
887/// Recursive delete. Returns `true` when the node was found and removed,
888/// `false` when not found.
889fn delete_recursive(node: &mut LayoutNode, target_id: &str) -> bool {
890 let idx = node.children.iter().position(|c| c.id == target_id);
891 if let Some(i) = idx {
892 // Found target as a direct child — remove it.
893 node.children.remove(i);
894 // Collapse: if only one child remains, promote it, with its
895 // `minimized` flag and `extra` (unknown-field catch-all from #688/#689).
896 if node.children.len() == 1 {
897 let sole = node.children.remove(0);
898 node.id = sole.id;
899 node.size = sole.size;
900 node.data = sole.data;
901 node.flex_direction = sole.flex_direction;
902 node.children = sole.children;
903 node.minimized = sole.minimized;
904 node.extra = sole.extra;
905 }
906 return true;
907 }
908 // Not a direct child — recurse.
909 for child in &mut node.children {
910 if delete_recursive(child, target_id) {
911 return true;
912 }
913 }
914 false
915}
916
917fn find_parent_id(root: &LayoutNode, child_id: &str) -> Option<String> {
918 if root.children.iter().any(|c| c.id == child_id) {
919 return Some(root.id.clone());
920 }
921 for child in &root.children {
922 if let Some(pid) = find_parent_id(child, child_id) {
923 return Some(pid);
924 }
925 }
926 None
927}
928
929// ── Tree normalization (balanceNode) ────────────────────────────────────────
930
931/// Validate the leaf-XOR-branch invariant. Mirrors `validateNode` in
932/// `frontend/layout/lib/layoutNode.ts`: a node must have **either** `data`
933/// **or** `children`, never both and never neither. (In TS the "empty
934/// children array" case is a separate check; here an empty `children` vec
935/// with no `data` is the same "neither" case and is rejected by the single
936/// XOR below.)
937fn validate_node(node: &LayoutNode) -> bool {
938 let has_children = !node.children.is_empty();
939 let has_data = node.data.is_some();
940 has_children != has_data
941}
942
943/// Port of `balanceNode` in `frontend/layout/lib/layoutNode.ts`. Recursively
944/// normalizes the tree: validates each node, alternates child flex direction,
945/// hoists redundant single-child-branch chains, drops empty branches, and
946/// collapses a branch with a single leaf child into that leaf.
947///
948/// Returns `Err(InvalidNode)` where the TS oracle throws "Invalid node", so
949/// the reducer can surface an `Event::Error` rather than panic.
950///
951/// Faithfulness notes (matched to the TS oracle, deliberately NOT "improved"):
952/// - The direction flip mutates only the *iterated* child; hoisted
953/// grandchildren are returned unflipped (a later pass alternates them) —
954/// matches the TS `flatMap`.
955/// - `_slipAnchor` (read from the untyped `extra` catch-all, where the
956/// frontend stores it) suppresses the single-child-branch hoist.
957/// - `columnDissolve` (same `extra` catch-all) suppresses the direction-flip
958/// alternation, so a dissolved column's own children stay stacked.
959/// - The single-leaf collapse copies the child's `data` + `id` only; the node
960/// keeps its own `size` / `flex_direction` / `extra` — exactly as TS does.
961pub fn balance_node(node: &mut LayoutNode) -> Result<(), LayoutError> {
962 // BEFORE-walk: validate, then rebuild children (flip / hoist / drop).
963 if !validate_node(node) {
964 return Err(LayoutError::InvalidNode { id: node.id.clone() });
965 }
966 let parent_flex = node.flex_direction;
967 let mut rebuilt: Vec<LayoutNode> = Vec::with_capacity(node.children.len());
968 for mut child in std::mem::take(&mut node.children) {
969 // A dissolved column (`columnDissolve` set, in `extra`) must keep the
970 // flexDirection it had when its leaf children were minimized — that's
971 // what stacks them vertically inside the header strip. It's nested
972 // under a sibling column of the same direction by design (see
973 // `_dissolveColumn` in layoutMinimize.ts), so the alternation rule
974 // below would otherwise flip it and lay the headers out sideways.
975 let column_dissolve = child.extra.contains_key("columnDissolve");
976 if child.flex_direction == parent_flex && !column_dissolve {
977 child.flex_direction = reverse_flex_direction(parent_flex);
978 }
979 let slip_anchor = child
980 .extra
981 .get("_slipAnchor")
982 .and_then(|v| v.as_bool())
983 .unwrap_or(false);
984 // Hoist: child has exactly one child and that grandchild is itself a
985 // branch (TS `child.children[0].children` truthy) — replace `child`
986 // with the grandchild's children. Suppressed for slip anchors.
987 if child.children.len() == 1 && !child.children[0].children.is_empty() && !slip_anchor {
988 let grandchild = child.children.remove(0);
989 rebuilt.extend(grandchild.children);
990 continue;
991 }
992 // Drop an empty branch (no data, no children). A leaf (data present,
993 // children empty) is kept — TS `children?.length === 0` is false for a
994 // leaf whose `children` is `undefined`.
995 if child.children.is_empty() && child.data.is_none() {
996 continue;
997 }
998 rebuilt.push(child);
999 }
1000 node.children = rebuilt;
1001
1002 // Recurse into the rebuilt children (walkNodes' `forEach`, which iterates
1003 // the post-rebuild children because the before-callback ran first).
1004 for child in &mut node.children {
1005 balance_node(child)?;
1006 }
1007
1008 // AFTER-walk: collapse a single leaf child into this node, with its `minimized` flag: a
1009 // chip left alone in its column stays a chip (as `delete_recursive` keeps it).
1010 if node.children.len() == 1 && node.children[0].children.is_empty() {
1011 let only = node.children.remove(0);
1012 node.data = only.data;
1013 node.id = only.id;
1014 node.minimized = only.minimized;
1015 node.children = Vec::new();
1016 }
1017 Ok(())
1018}
1019
1020// ── Tests ──────────────────────────────────────────────────────────────────
1021#[cfg(test)]
1022mod tests;