Skip to main content

agentmux_srv_core/reducer/layout/
intent.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The `LayoutApplyIntent` arm: srv computes every layout edit the frontend
5//! makes. SPEC_STRONG_REDUCER_AUTHORITY_LAYOUT_2026_06_30.md ยง4.
6
7use agentmux_common::ipc::Event;
8use agentmux_common::{LayoutIntent, LayoutViewState};
9
10use super::{clear_dangling_focus_magnify, op_error, report_layout_violations, unknown_tab};
11use crate::backend::layout::intent::{apply_intent, migrate_legacy_minimize, NodeIds};
12use crate::state::State;
13
14/// How many applied intent ids a tab remembers for de-duplication: more than
15/// a frontend ever has in flight at once.
16pub(crate) const RECENT_INTENTS: usize = 64;
17
18/// Apply `intent` to a copy of the tab's tree, normalize it the way every
19/// layout write is (balance, prune references to deleted blocks, the
20/// invariant report), and commit it. A refused intent
21/// leaves the tab untouched and answers with an `Error` event.
22///
23/// Emits `LayoutTreeReplaced` (tree only) when the tree changed, and
24/// `FocusedNodeChanged` / `MagnifiedNodeChanged` when those did. A repeat of
25/// a recent `action_id` emits nothing.
26pub(crate) fn handle_layout_apply_intent(
27    state: &mut State,
28    tab_id: String,
29    intent: LayoutIntent,
30    action_id: String,
31    view: Option<LayoutViewState>,
32) -> Vec<Event> {
33    let live_blocks: std::collections::HashSet<String> = state.blocks.keys().cloned().collect();
34    let Some(tab) = state.tabs.get(&tab_id) else {
35        return unknown_tab(state, "LayoutApplyIntent", &tab_id);
36    };
37    if !action_id.is_empty() && tab.recent_intent_ids.contains(&action_id) {
38        return Vec::new();
39    }
40    let name = intent.name();
41    let mut tree = tab.rootnode.clone();
42    if let Some(root) = tree.as_mut() {
43        let migrated = migrate_legacy_minimize(root);
44        if migrated > 0 {
45            tracing::info!(tab_id = %tab_id, migrated, "layout intent: migrated legacy minimize fields");
46        }
47    }
48    let mut ids = NodeIds::new(&action_id);
49    let effect = match apply_intent(&mut tree, intent, &mut ids) {
50        Ok(effect) => effect,
51        Err(e) => return op_error(state, format!("LayoutApplyIntent {name}: {e} (tab {tab_id})")),
52    };
53    let pruned = crate::backend::layout::prune_dangling_block_refs(&mut tree, &live_blocks);
54    if pruned > 0 {
55        tracing::warn!(tab_id = %tab_id, pruned, "layout intent: pruned leaves of deleted blocks");
56    }
57
58    let tab = state.tabs.get_mut(&tab_id).expect("looked up above");
59    let (focused_before, magnified_before) = (tab.focused_node_id.clone(), tab.magnified_node_id.clone());
60    let tree_changed = tab.rootnode != tree;
61    tab.rootnode = tree;
62    if !action_id.is_empty() {
63        tab.recent_intent_ids.push(action_id);
64        if tab.recent_intent_ids.len() > RECENT_INTENTS {
65            tab.recent_intent_ids.remove(0);
66        }
67    }
68    match view {
69        Some(view) => {
70            tab.focused_node_id = view.focused_node_id;
71            tab.magnified_node_id = view.magnified_node_id;
72        }
73        None => {
74            if effect.clear {
75                tab.focused_node_id.clear();
76                tab.magnified_node_id.clear();
77            }
78            if effect.unfocus.as_deref() == Some(tab.focused_node_id.as_str()) {
79                tab.focused_node_id.clear();
80            }
81            if effect.unmagnify.as_deref() == Some(tab.magnified_node_id.as_str()) {
82                tab.magnified_node_id.clear();
83            }
84            if let Some(id) = effect.magnify {
85                tab.magnified_node_id = id;
86            }
87            if let Some(id) = effect.focus {
88                tab.focused_node_id = id;
89            }
90        }
91    }
92    clear_dangling_focus_magnify(tab);
93    let new_tree = tab.rootnode.clone();
94    let (focused, magnified) = (tab.focused_node_id.clone(), tab.magnified_node_id.clone());
95
96    let mut events = Vec::new();
97    if tree_changed {
98        report_layout_violations(&tab_id, "LayoutApplyIntent", &new_tree);
99        let v = state.bump_version();
100        events.push(Event::LayoutTreeReplaced {
101            tab_id: tab_id.clone(),
102            new_tree,
103            correlation_id: String::new(),
104            slices: None,
105            version: v,
106        });
107    }
108    if focused != focused_before {
109        let v = state.bump_version();
110        events.push(Event::FocusedNodeChanged { tab_id: tab_id.clone(), node_id: focused, version: v });
111    }
112    if magnified != magnified_before {
113        let v = state.bump_version();
114        events.push(Event::MagnifiedNodeChanged { tab_id, node_id: magnified, version: v });
115    }
116    events
117}
118
119#[cfg(test)]
120mod tests;