1use 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
15fn 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
23pub(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
50pub(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 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 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 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 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 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 return Vec::new();
180 }
181 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 let (was_focused, was_magnified) = clear_dangling_focus_magnify(tab);
201
202 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
223fn 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
248fn 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
257pub(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 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 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 None => return Vec::new(),
301 };
302 handle_layout_delete_node(state, tab_id, node_id, correlation_id)
303}
304
305pub(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
345fn 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 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
408pub(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; };
439 events.extend(handle_layout_stack_push(state, tab_id, target_block_id, block_id, activate, String::new()));
440 events
441}
442
443pub(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 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 tree_cleared: false,
497 was_focused,
498 was_magnified,
499 correlation_id,
500 version: v,
501 }]
502}
503
504pub(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 tree_cleared: false,
546 was_focused,
547 was_magnified,
548 correlation_id,
549 version: v,
550 }]
551}
552
553fn 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
564fn 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;