Skip to main content

agentmux_srv_core/reducer/
layout.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use agentmux_common::ipc::{ErrorCode, Event};
5
6use crate::state::State;
7
8pub mod heal;
9pub mod intent;
10pub(crate) use heal::heal_loaded_layout;
11pub(super) use intent::handle_layout_apply_intent;
12#[allow(unused_imports)]
13pub(crate) use intent::RECENT_INTENTS;
14
15/// A tree srv seeds wholesale (a restored session's saved layout) can carry the pre-display-mode
16/// minimize fields; the window converts nothing, so they are converted here.
17fn migrate_seeded_tree(root: &mut Option<agentmux_common::LayoutNode>) {
18    if let Some(root) = root.as_mut() {
19        crate::backend::layout::intent::migrate_legacy_minimize(root);
20    }
21}
22
23/// Phase E.4 (Option A) — set the focused layout-node id on a tab.
24/// Errors (non-fatal) if the tab is unknown to the reducer; no-op
25/// short-circuit when the value is already current. Empty `node_id`
26/// clears the field. Bumps the version only on real changes so a
27/// burst of identical sets doesn't churn the event stream.
28pub(super) fn handle_set_focused_node(state: &mut State, tab_id: String, node_id: String) -> Vec<Event> {
29    let Some(tab) = state.tabs.get_mut(&tab_id) else {
30        let v = state.bump_version();
31        return vec![Event::Error {
32            code: ErrorCode::InvalidCommand,
33            message: format!("SetFocusedNode: unknown tab {}", tab_id),
34            fatal: false,
35            version: v,
36        }];
37    };
38    if tab.focused_node_id == node_id {
39        return Vec::new();
40    }
41    tab.focused_node_id = node_id.clone();
42    let v = state.bump_version();
43    vec![Event::FocusedNodeChanged {
44        tab_id,
45        node_id,
46        version: v,
47    }]
48}
49
50/// Phase E.4 (Option A) — set the magnified layout-node id on a tab.
51/// Same shape as `handle_set_focused_node`. Empty `node_id` is the
52/// toggle-off / clear case.
53pub(super) fn handle_set_magnified_node(state: &mut State, tab_id: String, node_id: String) -> Vec<Event> {
54    let Some(tab) = state.tabs.get_mut(&tab_id) else {
55        let v = state.bump_version();
56        return vec![Event::Error {
57            code: ErrorCode::InvalidCommand,
58            message: format!("SetMagnifiedNode: unknown tab {}", tab_id),
59            fatal: false,
60            version: v,
61        }];
62    };
63    if tab.magnified_node_id == node_id {
64        return Vec::new();
65    }
66    tab.magnified_node_id = node_id.clone();
67    let v = state.bump_version();
68    vec![Event::MagnifiedNodeChanged {
69        tab_id,
70        node_id,
71        version: v,
72    }]
73}
74
75pub(super) fn handle_layout_set_tree(
76    state: &mut State,
77    tab_id: String,
78    new_tree: Option<agentmux_common::LayoutNode>,
79    correlation_id: String,
80    slices: Option<agentmux_common::LayoutClientSlices>,
81) -> Vec<Event> {
82    // Computed before the `state.tabs` borrow below — `blocks` and `tabs`
83    // are disjoint fields, but an owned snapshot avoids any doubt.
84    let live_blocks: std::collections::HashSet<String> = state.blocks.keys().cloned().collect();
85    let Some(tab) = state.tabs.get_mut(&tab_id) else {
86        let v = state.bump_version();
87        return vec![Event::Error {
88            code: ErrorCode::InvalidCommand,
89            message: format!("LayoutSetTree: unknown tab {}", tab_id),
90            fatal: false,
91            version: v,
92        }];
93    };
94    tab.rootnode = new_tree.clone();
95    // SPEC_864 Phase 2 — a seeding `LayoutSetTree` (srv's own; windows send
96    // intents) carries focus/magnify in `slices`
97    // (REPLACE semantics; empty string = clear). pending_backend_actions
98    // is not modeled in TabRecord — it rides the event through to the
99    // persist subscriber untouched.
100    if let Some(s) = &slices {
101        tab.focused_node_id = s.focused_node_id.clone();
102        tab.magnified_node_id = s.magnified_node_id.clone();
103    }
104    // When the tree is wiped, focused/magnified ids would point at
105    // non-existent nodes; clear them (the persist side does the same).
106    if new_tree.is_none() {
107        tab.focused_node_id = String::new();
108        tab.magnified_node_id = String::new();
109    }
110    let (pushed_focused, pushed_magnified) = (tab.focused_node_id.clone(), tab.magnified_node_id.clone());
111    // Referential-integrity enforcement (see
112    // `backend::layout::prune_dangling_block_refs`'s doc comment): this is
113    // the exact vector — a wholesale tree replace — that once let a stale
114    // frontend copy resurrect a deleted block's leaf. Windows no longer push
115    // trees, but srv's seeders still replace whole trees here
116    // (INVESTIGATION_LAYOUT_DEAD_SPACE_STALE_TREE_RESURRECTION_2026_07_08.md).
117    // Re-derive `new_tree`/the event from the now-authoritative (possibly
118    // pruned) `tab.rootnode` rather than the caller's original value, so
119    // what gets persisted matches what the reducer actually holds — a
120    // pruned `tab.rootnode` with a stale `new_tree` in the emitted event
121    // would just move the divergence downstream instead of closing it.
122    migrate_seeded_tree(&mut tab.rootnode);
123    let pruned = crate::backend::layout::prune_dangling_block_refs(&mut tab.rootnode, &live_blocks);
124    if pruned > 0 {
125        clear_dangling_focus_magnify(tab);
126        tracing::warn!(
127            tab_id = %tab_id,
128            pruned,
129            "reducer: LayoutSetTree pruned dangling layout leaf/leaves referencing since-deleted blocks"
130        );
131    }
132    report_layout_violations(&tab_id, "LayoutSetTree", &tab.rootnode);
133    let new_tree = tab.rootnode.clone();
134    // A prune can clear focus/magnify; the persisted row must get the same
135    // values. With slices they ride the event; without, they get their own.
136    let (focused, magnified) = (tab.focused_node_id.clone(), tab.magnified_node_id.clone());
137    let mut slices = slices;
138    if let Some(s) = slices.as_mut() {
139        s.focused_node_id = focused.clone();
140        s.magnified_node_id = magnified.clone();
141    }
142    let slices_carry_focus = slices.is_some();
143    let v = state.bump_version();
144    let mut events = vec![Event::LayoutTreeReplaced {
145        tab_id: tab_id.clone(),
146        new_tree,
147        correlation_id,
148        slices,
149        version: v,
150    }];
151    if !slices_carry_focus && focused != pushed_focused {
152        let v = state.bump_version();
153        events.push(Event::FocusedNodeChanged { tab_id: tab_id.clone(), node_id: focused, version: v });
154    }
155    if !slices_carry_focus && magnified != pushed_magnified {
156        let v = state.bump_version();
157        events.push(Event::MagnifiedNodeChanged { tab_id, node_id: magnified, version: v });
158    }
159    events
160}
161
162pub(super) fn handle_layout_delete_node(
163    state: &mut State,
164    tab_id: String,
165    node_id: String,
166    correlation_id: String,
167) -> Vec<Event> {
168    let Some(tab) = state.tabs.get_mut(&tab_id) else {
169        let v = state.bump_version();
170        return vec![Event::Error {
171            code: ErrorCode::InvalidCommand,
172            message: format!("LayoutDeleteNode: unknown tab {}", tab_id),
173            fatal: false,
174            version: v,
175        }];
176    };
177    if tab.rootnode.is_none() {
178        // Empty tree — nothing to delete; idempotent no-op (no event).
179        return Vec::new();
180    }
181    // The frontend's delete, then its balance pass (the `delete` intent), so
182    // the window that mirrors this removal ends with the same tree.
183    let mut tree = tab.rootnode.clone();
184    let delete = agentmux_common::LayoutIntent::Delete { node_id: node_id.clone() };
185    let mut ids = crate::backend::layout::intent::NodeIds::new(&correlation_id);
186    if let Err(e) = crate::backend::layout::intent::apply_intent(&mut tree, delete, &mut ids) {
187        let v = state.bump_version();
188        return vec![Event::Error {
189            code: ErrorCode::InvalidCommand,
190            message: format!("LayoutDeleteNode: {} (tab {})", e, tab_id),
191            fatal: false,
192            version: v,
193        }];
194    }
195    tab.rootnode = tree;
196
197    // Focus or magnify can name a node the delete took: a descendant of a
198    // removed container, or a branch the balance pass collapsed into its one
199    // remaining leaf. Clear whichever no longer resolves.
200    let (was_focused, was_magnified) = clear_dangling_focus_magnify(tab);
201
202    // SPEC_864 site #6 — carry the resulting tree so the persist
203    // subscriber can write db_layout without re-running the algebra
204    // (the single-writer shape of every layout arm). A delete is
205    // the one structural op that can legitimately EMPTY the tree
206    // (root-orphan case), so `tree_cleared` disambiguates a real clear
207    // from a version-skewed sender's absent field.
208    let new_tree = tab.rootnode.clone();
209    let tree_cleared = new_tree.is_none();
210    let v = state.bump_version();
211    vec![Event::LayoutNodeDeleted {
212        tab_id,
213        node_id,
214        new_tree,
215        tree_cleared,
216        was_focused,
217        was_magnified,
218        correlation_id,
219        version: v,
220    }]
221}
222
223/// Clear the tab's focus/magnify ids when they no longer resolve to a node
224/// in its (already-edited) tree. Returns `(was_focused, was_magnified)`:
225/// whether each one was cleared. Shared by every edit that can remove a leaf
226/// (a node delete, a pane tab move that empties its source pane, a
227/// `LayoutSetTree` prune); see `handle_layout_delete_node` for the two ways
228/// an id can dangle after a delete.
229fn clear_dangling_focus_magnify(tab: &mut crate::state::TabRecord) -> (bool, bool) {
230    let dangles = |id: &str| -> bool {
231        !id.is_empty()
232            && tab
233                .rootnode
234                .as_ref()
235                .is_none_or(|root| crate::backend::layout::find_node_by_id(root, id).is_none())
236    };
237    let was_focused = dangles(&tab.focused_node_id);
238    let was_magnified = dangles(&tab.magnified_node_id);
239    if was_focused {
240        tab.focused_node_id = String::new();
241    }
242    if was_magnified {
243        tab.magnified_node_id = String::new();
244    }
245    (was_focused, was_magnified)
246}
247
248/// Layout doctor (#2179): attribute any structural corruption to the write
249/// that made it, loudly, instead of letting it persist silently.
250fn report_layout_violations(tab_id: &str, op: &str, tree: &Option<agentmux_common::LayoutNode>) {
251    let violations = crate::backend::layout::validate_layout_invariants(tree);
252    if !violations.is_empty() {
253        tracing::error!(tab_id, op, violations = ?violations, "layout-doctor: invariant violation(s) after a layout write");
254    }
255}
256
257/// SPEC_864 site #6 — delete the layout node holding `block_id`.
258/// Resolution happens here because the reducer owns the tree; the
259/// caller (the `delete_block` saga) only knows the block id.
260///
261/// Unresolved block → silent idempotent no-op (empty event vec), NOT an
262/// error: every `delete_block` saga run dispatches this, and a block
263/// may legitimately have no layout node (a layout intent already
264/// removed it, the block was floating/never laid out, or the tab tree
265/// is empty).
266pub(super) fn handle_layout_delete_node_by_block(
267    state: &mut State,
268    tab_id: String,
269    block_id: String,
270    correlation_id: String,
271) -> Vec<Event> {
272    // One tab of a stacked pane: remove just that member and keep the pane
273    // and its other tabs. Deleting the whole leaf (the old behaviour, via
274    // `find_node_id_by_block` on the visible block) took every sibling tab
275    // with it. SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.4.
276    if let Some(root) = state.tabs.get_mut(&tab_id).and_then(|tab| tab.rootnode.as_mut()) {
277        if crate::backend::layout::remove_stack_member(root, &block_id) {
278            let new_tree = state.tabs.get(&tab_id).and_then(|tab| tab.rootnode.clone());
279            let v = state.bump_version();
280            return vec![Event::LayoutTreeReplaced {
281                tab_id,
282                new_tree,
283                correlation_id,
284                // Tree only: focus, magnify, leaf order and the pending
285                // action queue are left exactly as they are.
286                slices: None,
287                version: v,
288            }];
289        }
290    }
291    let node_id = match state
292        .tabs
293        .get(&tab_id)
294        .and_then(|tab| tab.rootnode.as_ref())
295        .and_then(|root| crate::backend::layout::find_leaf_containing_block(root, &block_id))
296        .map(|leaf| leaf.id.clone())
297    {
298        Some(id) => id,
299        // Unknown tab, empty tree, or block not in the tree — no-op.
300        None => return Vec::new(),
301    };
302    handle_layout_delete_node(state, tab_id, node_id, correlation_id)
303}
304
305/// SPEC_864 Phase 4 — append backend actions to a tab's
306/// `pendingbackendactions` queue. The reducer does NOT model the queue
307/// in `TabRecord` (it tells a window what srv already did to the tree; it
308/// is not layout-tree state), so this arm only validates and passes the
309/// payload through; the persist subscriber APPENDs it to
310/// `LayoutState.pendingbackendactions`.
311///
312/// `actions` must be a non-empty JSON array of `LayoutActionData`
313/// objects (the type lives in `agentmux-srv::backend::obj`, not the
314/// common crate — hence the raw-value carriage).
315pub(super) fn handle_layout_queue_backend_actions(
316    state: &mut State,
317    tab_id: String,
318    actions: serde_json::Value,
319    correlation_id: String,
320) -> Vec<Event> {
321    if !state.tabs.contains_key(&tab_id) {
322        return unknown_tab(state, "LayoutQueueBackendActions", &tab_id);
323    }
324    match actions.as_array() {
325        Some(arr) if !arr.is_empty() => {}
326        _ => {
327            return op_error(
328                state,
329                format!(
330                    "LayoutQueueBackendActions: actions must be a non-empty JSON array (tab {})",
331                    tab_id
332                ),
333            )
334        }
335    }
336    let v = state.bump_version();
337    vec![Event::LayoutBackendActionsQueued {
338        tab_id,
339        actions,
340        correlation_id,
341        version: v,
342    }]
343}
344
345// ── Pane tabs (SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.2) ─────────
346
347/// Apply a pane-tab edit to the tab's tree and emit the tree-only
348/// `LayoutTreeReplaced` (no slices: focus, magnify, leaf order and the
349/// pending-action queue are untouched). `edit` returns false when it found
350/// nothing to act on.
351fn stack_tree_edit(
352    state: &mut State,
353    op: &str,
354    tab_id: String,
355    correlation_id: String,
356    not_found: String,
357    edit: impl FnOnce(&mut agentmux_common::LayoutNode) -> bool,
358) -> Vec<Event> {
359    let applied = match state.tabs.get_mut(&tab_id) {
360        None => return unknown_tab(state, op, &tab_id),
361        Some(tab) => tab.rootnode.as_mut().is_some_and(edit),
362    };
363    if !applied {
364        return op_error(state, format!("{op}: {not_found} (tab {tab_id})"));
365    }
366    let new_tree = state.tabs.get(&tab_id).and_then(|tab| tab.rootnode.clone());
367    report_layout_violations(&tab_id, op, &new_tree);
368    let v = state.bump_version();
369    vec![Event::LayoutTreeReplaced {
370        tab_id,
371        new_tree,
372        correlation_id,
373        slices: None,
374        version: v,
375    }]
376}
377
378pub(super) fn handle_layout_stack_push(
379    state: &mut State,
380    tab_id: String,
381    target_block_id: String,
382    block_id: String,
383    activate: bool,
384    correlation_id: String,
385) -> Vec<Event> {
386    // Only a block that lives in this tab may join one of its panes.
387    if state.blocks.get(&block_id).map(|b| b.tab_id.as_str()) != Some(tab_id.as_str()) {
388        return op_error(state, format!("LayoutStackPush: block {block_id} is not in tab {tab_id}"));
389    }
390    let not_found = format!("no pane holds block {target_block_id}");
391    stack_tree_edit(state, "LayoutStackPush", tab_id, correlation_id, not_found, |root| {
392        crate::backend::layout::push_stack_member(root, &target_block_id, &block_id, activate)
393    })
394}
395
396pub(super) fn handle_layout_stack_activate(
397    state: &mut State,
398    tab_id: String,
399    block_id: String,
400    correlation_id: String,
401) -> Vec<Event> {
402    let not_found = format!("no pane holds block {block_id}");
403    stack_tree_edit(state, "LayoutStackActivate", tab_id, correlation_id, not_found, |root| {
404        crate::backend::layout::activate_stack_member(root, &block_id)
405    })
406}
407
408/// Create a block and place it in a pane's tab stack in one step. Placement
409/// is validated FIRST: if no pane holds `target_block_id`, nothing is created
410/// — a block never exists without a pane. `block_id` is the dispatcher's `Ctx::new_id`.
411pub(super) fn handle_create_block_in_stack(
412    state: &mut State,
413    tab_id: String,
414    target_block_id: String,
415    block_id: String,
416    meta: serde_json::Value,
417    activate: bool,
418) -> Vec<Event> {
419    let Some(tab) = state.tabs.get(&tab_id) else {
420        return unknown_tab(state, "CreateBlockInStack", &tab_id);
421    };
422    let placeable = tab
423        .rootnode
424        .as_ref()
425        .is_some_and(|root| crate::backend::layout::find_leaf_containing_block(root, &target_block_id).is_some());
426    if !placeable {
427        return op_error(
428            state,
429            format!("CreateBlockInStack: no pane holds block {target_block_id} (tab {tab_id})"),
430        );
431    }
432    let mut events = super::block::create_block_with_id(state, tab_id.clone(), block_id, meta);
433    let Some(block_id) = events.iter().find_map(|e| match e {
434        Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
435        _ => None,
436    }) else {
437        return events; // the create itself failed; its Error event says why
438    };
439    events.extend(handle_layout_stack_push(state, tab_id, target_block_id, block_id, activate, String::new()));
440    events
441}
442
443/// Reorder `block_id` within its own pane, or move it into a different
444/// pane — a same-leaf reorder never changes which member is visible unless
445/// `activate` is set. Refuses (an `Error` event, tree untouched) when either
446/// block doesn't exist in the tab's tree.
447///
448/// Moving a pane's ONLY tab into another pane empties it, and the emptied
449/// pane is removed (`move_stack_member`). That one case can leave focus or
450/// magnify pointing at a node that's gone, so instead of the tree-only
451/// `LayoutTreeReplaced` it's reported exactly like a node delete: focus and
452/// magnify reconciled, and a `LayoutNodeDeleted` for the source leaf that
453/// carries the full resulting tree (the tab's new member included). No block
454/// is deleted either way — the moved block lives on in its new pane.
455/// SPEC_PANE_TAB_DRAG_AND_DROP_2026_09_19.md §4.1,
456/// SPEC_PANE_TAB_DRAG_LANDING_FLASH_AND_LAST_TAB_CLOSE_2026_09_24.md §4.3.
457pub(super) fn handle_layout_stack_move(
458    state: &mut State,
459    tab_id: String,
460    block_id: String,
461    target_block_id: String,
462    position: agentmux_common::StackMovePosition,
463    activate: bool,
464    correlation_id: String,
465) -> Vec<Event> {
466    let not_found = format!("block {block_id} or {target_block_id} not found");
467    let emptied_source = state
468        .tabs
469        .get(&tab_id)
470        .and_then(|tab| tab.rootnode.as_ref())
471        .and_then(|root| crate::backend::layout::source_leaf_emptied_by_move(root, &block_id, &target_block_id));
472    let Some(source_node_id) = emptied_source else {
473        return stack_tree_edit(state, "LayoutStackMove", tab_id, correlation_id, not_found, |root| {
474            crate::backend::layout::move_stack_member(root, &block_id, &target_block_id, position, activate)
475        });
476    };
477
478    // The emptied-pane case. `source_leaf_emptied_by_move` only returns Some
479    // for a tab that exists with a tree, so both lookups below succeed.
480    let tab = state.tabs.get_mut(&tab_id).expect("resolved above");
481    let applied = tab.rootnode.as_mut().is_some_and(|root| {
482        crate::backend::layout::move_stack_member(root, &block_id, &target_block_id, position, activate)
483    });
484    if !applied {
485        return op_error(state, format!("LayoutStackMove: {not_found} (tab {tab_id})"));
486    }
487    let (was_focused, was_magnified) = clear_dangling_focus_magnify(tab);
488    let new_tree = tab.rootnode.clone();
489    report_layout_violations(&tab_id, "LayoutStackMove", &new_tree);
490    let v = state.bump_version();
491    vec![Event::LayoutNodeDeleted {
492        tab_id,
493        node_id: source_node_id,
494        new_tree,
495        // The destination leaf is still there, so the tree is never empty.
496        tree_cleared: false,
497        was_focused,
498        was_magnified,
499        correlation_id,
500        version: v,
501    }]
502}
503
504/// `Command::LayoutStackMoveMany`: several Pane Tabs into one pane in one edit
505/// (`move_stack_members`). Reported like `LayoutStackMove`: a plain
506/// `LayoutTreeReplaced` normally, and, when panes were emptied and removed,
507/// a `LayoutNodeDeleted` with focus and magnify reconciled (it carries the
508/// full resulting tree, and the first removed pane's id).
509/// SPEC_PANE_TAB_MULTI_SELECT_MOVE_AND_COLLAPSED_EXPAND_2026_10_24.md §5.
510pub(super) fn handle_layout_stack_move_many(
511    state: &mut State,
512    tab_id: String,
513    block_ids: Vec<String>,
514    target_block_id: String,
515    activate_block_id: Option<String>,
516    correlation_id: String,
517) -> Vec<Event> {
518    const OP: &str = "LayoutStackMoveMany";
519    let not_found = format!("a block of {block_ids:?} or {target_block_id} not found, or the move was refused");
520    let Some(tab) = state.tabs.get_mut(&tab_id) else {
521        return unknown_tab(state, OP, &tab_id);
522    };
523    let outcome = tab.rootnode.as_mut().and_then(|root| {
524        crate::backend::layout::move_stack_members(root, &block_ids, &target_block_id, activate_block_id.as_deref())
525    });
526    let Some(emptied) = outcome else {
527        return op_error(state, format!("{OP}: {not_found} (tab {tab_id})"));
528    };
529    let Some(first_removed) = emptied.into_iter().next() else {
530        let new_tree = state.tabs.get(&tab_id).and_then(|tab| tab.rootnode.clone());
531        report_layout_violations(&tab_id, OP, &new_tree);
532        let v = state.bump_version();
533        return vec![Event::LayoutTreeReplaced { tab_id, new_tree, correlation_id, slices: None, version: v }];
534    };
535    let tab = state.tabs.get_mut(&tab_id).expect("resolved above");
536    let (was_focused, was_magnified) = clear_dangling_focus_magnify(tab);
537    let new_tree = tab.rootnode.clone();
538    report_layout_violations(&tab_id, OP, &new_tree);
539    let v = state.bump_version();
540    vec![Event::LayoutNodeDeleted {
541        tab_id,
542        node_id: first_removed,
543        new_tree,
544        // The destination leaf is still there, so the tree is never empty.
545        tree_cleared: false,
546        was_focused,
547        was_magnified,
548        correlation_id,
549        version: v,
550    }]
551}
552
553/// `Event::Error` for an unknown tab.
554fn unknown_tab(state: &mut State, op: &str, tab_id: &str) -> Vec<Event> {
555    let v = state.bump_version();
556    vec![Event::Error {
557        code: ErrorCode::InvalidCommand,
558        message: format!("{}: unknown tab {}", op, tab_id),
559        fatal: false,
560        version: v,
561    }]
562}
563
564/// `Event::Error` for an operation failure (pure-fn or balance error).
565fn op_error(state: &mut State, message: String) -> Vec<Event> {
566    let v = state.bump_version();
567    vec![Event::Error {
568        code: ErrorCode::InvalidCommand,
569        message,
570        fatal: false,
571        version: v,
572    }]
573}
574
575#[cfg(test)]
576mod tests;