Skip to main content

agentmux_srv/server/service/
layout_helpers.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Layout-tree + pending-action writers used by the tear-off / promote /
5//! redock handlers. SPEC_864 Phase 3/4 — all of them route through the
6//! reducer (`seed_layout_via_reducer` / `queue_layout_actions_via_reducer`);
7//! nothing here writes mstore directly anymore.
8//! `setup_torn_off_block_layout` is re-exported crate-wide (the pane
9//! app-API uses it).
10
11use crate::backend::obj::*;
12
13use super::layout_intents::Placement;
14
15/// Phase E.5.5 — set up the layout tree for a tab that just received
16/// its first block via the TearOffBlock saga. Called from the
17/// TearOffBlock / PromoteBlockToTab handlers and the floating
18/// `pane.open` path after the saga's reducer-state portion
19/// (CreateTab + MoveBlock) completes. (NOT RedockFloatingPane — that
20/// redocks into an EXISTING tab and goes through
21/// `queue_target_layout_insert`/`_split` instead; reagent P2 on #1971.)
22///
23/// SPEC_864 Phase 3 — reducer-routed: dispatches `LayoutSetTree` via
24/// `seed_layout_via_reducer` (single writer of `db_layout`; the reducer's
25/// `TabRecord.rootnode` stays authoritative) instead of the retired
26/// wcore-direct `rootnode` write. Every caller runs post-saga,
27/// so the tab is always reducer-known. Best-effort at the call sites: a
28/// failure leaves the new tab with the moved block but a malformed layout;
29/// the user-visible symptom is an empty render in the new window.
30pub(crate) async fn setup_torn_off_block_layout(
31    state: &super::super::AppState,
32    new_tab_id: &str,
33    block_id: &str,
34) -> Result<(), String> {
35    setup_torn_off_stack_layout(state, new_tab_id, block_id, &[]).await
36}
37
38/// [`setup_torn_off_block_layout`] for a whole pane torn off with its tabs:
39/// the one leaf holds `members` as its `block_stack` (in order), with
40/// `block_id` the visible one. Fewer than two members seed a plain leaf.
41pub(crate) async fn setup_torn_off_stack_layout(
42    state: &super::super::AppState,
43    new_tab_id: &str,
44    block_id: &str,
45    members: &[String],
46) -> Result<(), String> {
47    let order = crate::sagas::tear_off_block::tear_off_order(block_id, members);
48    let stack = if order.len() > 1 { order_stack(&order, members) } else { Vec::new() };
49    let node_id = uuid::Uuid::new_v4().to_string();
50    // Phase E.4.B Phase 2 — construct typed LayoutNode (was inline JSON).
51    let rootnode = LayoutNode {
52        id: node_id,
53        flex_direction: FlexDirection::Row,
54        size: 1.0,
55        children: Vec::new(),
56        data: Some(LayoutNodeData {
57            block_id: block_id.to_string(),
58            active_block_id: if stack.is_empty() { String::new() } else { block_id.to_string() },
59            block_stack: stack,
60            ..Default::default()
61        }),
62        ..Default::default()
63    };
64    // Focused id stays empty — the legacy writer never set it for a
65    // torn-off tab; the frontend focuses on load.
66    super::reducer_helpers::seed_layout_via_reducer(state, new_tab_id, rootnode, String::new(), String::new()).await
67}
68
69/// The stack as the caller gave it (`tear_off_order` moves the visible block
70/// first, but the pane's tab order is the order of `members`).
71fn order_stack(order: &[String], members: &[String]) -> Vec<String> {
72    members.iter().filter(|m| order.contains(m)).fold(Vec::new(), |mut acc, m| {
73        if !acc.contains(m) {
74            acc.push(m.clone());
75        }
76        acc
77    })
78}
79
80/// Place a block (re-docked, re-placed by the orphan reaper) at the first
81/// free slot of its tab: srv's tree first, then the queued `insert` for the
82/// window showing the tab (`layout_intents::place_block`).
83pub(crate) async fn queue_target_layout_insert(
84    state: &super::super::AppState,
85    target_tab_id: &str,
86    block_id: &str,
87) -> Result<(), String> {
88    super::layout_intents::place_block(state, target_tab_id, block_id, Placement::Append { focused: true }).await
89}
90
91/// Tell the frontend that `block_id` was added — already, in the reducer — as
92/// a tab of the pane holding `target_block_id`, the visible one when `activate`
93/// (`Command::CreateBlockInStack`). Matches
94/// `LayoutTreeActionType.StackPush = "stackpush"` in
95/// `frontend/layout/lib/types.ts`. SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.3.
96pub(crate) async fn queue_target_stack_push(
97    state: &super::super::AppState,
98    tab_id: &str,
99    block_id: &str,
100    target_block_id: &str,
101    activate: bool,
102) -> Result<(), String> {
103    let action = LayoutActionData {
104        actiontype: "stackpush".to_string(),
105        actionid: uuid::Uuid::new_v4().to_string(),
106        blockid: block_id.to_string(),
107        nodesize: None,
108        nodesizefraction: None,
109        indexarr: None,
110        focused: activate,
111        magnified: false,
112        ephemeral: false,
113        targetblockid: target_block_id.to_string(),
114        position: String::new(),
115        nodeid: None,
116        queuedat: None,
117    };
118    super::reducer_helpers::queue_layout_actions_via_reducer(state, tab_id, vec![action]).await
119}
120
121/// Tell the frontend that `block_id` was moved — already, in the reducer —
122/// to `position` relative to `target_block_id` (`Command::LayoutStackMove`):
123/// a same-pane reorder when both are already in one leaf's stack, otherwise
124/// a cross-pane move. Matches `LayoutTreeActionType.StackMove = "stackmove"`
125/// in `frontend/layout/lib/types.ts`. `position` is the same
126/// `"before"`/`"after"`/`"end"` string `pane.moveTab`'s caller supplied —
127/// reused verbatim, not re-derived, so the frontend applies the identical
128/// operation rather than inferring it from resulting tree state. `activate`
129/// rides on `LayoutActionData.focused` — the same field `queue_target_stack_push`
130/// above already overloads for this purpose (both carry the caller's
131/// `activate` value: a new tab and a reorder may or may not be shown).
132/// SPEC_PANE_TAB_DRAG_AND_DROP_2026_09_19.md §4.1, Phase 3.
133pub(crate) async fn queue_target_stack_move(
134    state: &super::super::AppState,
135    tab_id: &str,
136    block_id: &str,
137    target_block_id: &str,
138    position: &str,
139    activate: bool,
140    action_id: &str,
141) -> Result<(), String> {
142    let action = LayoutActionData {
143        actiontype: "stackmove".to_string(),
144        actionid: action_id_or_new(action_id),
145        blockid: block_id.to_string(),
146        nodesize: None,
147        nodesizefraction: None,
148        indexarr: None,
149        focused: activate,
150        magnified: false,
151        ephemeral: false,
152        targetblockid: target_block_id.to_string(),
153        position: position.to_string(),
154        nodeid: None,
155        queuedat: None,
156    };
157    super::reducer_helpers::queue_layout_actions_via_reducer(state, tab_id, vec![action]).await
158}
159
160/// Tell the frontend that several blocks were moved — already, in the
161/// reducer — to the end of `target_block_id`'s pane (`Command::LayoutStackMoveMany`):
162/// one `stackmove` per block, in order, the visible tab's (when it is one of
163/// them) carrying `focused`; and a `stackactivate` when the visible tab is a
164/// member of that pane that was not moved. The ids are `<action_id>:<index>`,
165/// which the calling frontend registered as its own.
166/// SPEC_PANE_TAB_MULTI_SELECT_MOVE_AND_COLLAPSED_EXPAND_2026_10_24.md §5.
167pub(crate) async fn queue_target_stack_moves(
168    state: &super::super::AppState,
169    tab_id: &str,
170    block_ids: &[String],
171    target_block_id: &str,
172    activate_block_id: Option<&str>,
173    action_id: &str,
174) -> Result<(), String> {
175    let nth = |i: usize| if action_id.is_empty() { String::new() } else { format!("{action_id}:{i}") };
176    let mut actions: Vec<LayoutActionData> = block_ids
177        .iter()
178        .enumerate()
179        .map(|(i, block_id)| LayoutActionData {
180            actiontype: "stackmove".to_string(),
181            actionid: action_id_or_new(&nth(i)),
182            blockid: block_id.clone(),
183            nodesize: None,
184            nodesizefraction: None,
185            indexarr: None,
186            focused: activate_block_id == Some(block_id.as_str()),
187            magnified: false,
188            ephemeral: false,
189            targetblockid: target_block_id.to_string(),
190            position: "end".to_string(),
191            nodeid: None,
192            queuedat: None,
193        })
194        .collect();
195    if let Some(active) = activate_block_id.filter(|a| !block_ids.iter().any(|b| b == a)) {
196        actions.push(LayoutActionData {
197            actiontype: "stackactivate".to_string(),
198            actionid: action_id_or_new(&nth(block_ids.len())),
199            ..source_delete_action(active)
200        });
201    }
202    super::reducer_helpers::queue_layout_actions_via_reducer(state, tab_id, actions).await
203}
204
205/// Tell the frontend that `block_id` became the visible tab of its pane
206/// (`Command::LayoutStackActivate`). Matches
207/// `LayoutTreeActionType.StackActivate = "stackactivate"`.
208pub(crate) async fn queue_stack_activate(
209    state: &super::super::AppState,
210    tab_id: &str,
211    block_id: &str,
212    action_id: &str,
213) -> Result<(), String> {
214    let action = LayoutActionData {
215        actiontype: "stackactivate".to_string(),
216        actionid: action_id_or_new(action_id),
217        ..source_delete_action(block_id)
218    };
219    super::reducer_helpers::queue_layout_actions_via_reducer(state, tab_id, vec![action]).await
220}
221
222/// Tell the frontend that `block_id` left its pane (one tab of a stack, or the
223/// pane with its last tab): the `delete` action, under the caller's id.
224pub(crate) async fn queue_stack_remove(
225    state: &super::super::AppState,
226    tab_id: &str,
227    block_id: &str,
228    action_id: &str,
229) -> Result<(), String> {
230    let action = LayoutActionData { actionid: action_id_or_new(action_id), ..source_delete_action(block_id) };
231    super::reducer_helpers::queue_layout_actions_via_reducer(state, tab_id, vec![action]).await
232}
233
234/// The id a frontend minted for its own command, so that frontend skips the
235/// queued copy (`processedActionIds`, layoutPersistence.ts); a fresh one when
236/// it sent none or an unusable one.
237fn action_id_or_new(action_id: &str) -> String {
238    if action_id.is_empty() || action_id.len() > 64 {
239        uuid::Uuid::new_v4().to_string()
240    } else {
241        action_id.to_string()
242    }
243}
244
245/// Phase 4b/4c — place a redocked block in the exact slot the ghost
246/// overlay previewed: a split of the pane holding `target_block_id`.
247///
248/// `dir` is the window's `DropDirection`. The split each one makes is listed
249/// once, for srv and for the window's preview of the drop
250/// (`backend::layout::drop_split`): a side of the pane takes half of it, the
251/// side of its whole group a narrow band of it, and the middle (or an unknown
252/// code) has no split, so the block goes to the first free slot instead. See
253/// `ANALYSIS_FLOATING_PANE_GHOST_LANDING_DISCONNECT_2026_07_04.md`.
254pub(super) async fn queue_target_layout_split(
255    state: &super::super::AppState,
256    target_tab_id: &str,
257    block_id: &str,
258    target_block_id: &str,
259    dir: u8,
260) -> Result<(), String> {
261    let Some(split) = crate::backend::layout::drop_split::drop_split(dir) else {
262        return queue_target_layout_insert(state, target_tab_id, block_id).await;
263    };
264    let placement = Placement::Split {
265        target_block_id: target_block_id.to_string(),
266        horizontal: split.horizontal,
267        position: split.position,
268        size_fraction: Some(split.size_fraction),
269        focused: true,
270    };
271    super::layout_intents::place_block(state, target_tab_id, block_id, placement).await
272}
273
274/// Take a block that moved (tear-off, promote, redock) or was deleted
275/// (`sagas::delete_block`, `sagas::close_pane`) out of its source tab's
276/// layout: srv's tree, then a queued `delete` so a window that already shows
277/// the tab drops it too (a window that missed it would show a pane whose block
278/// is gone; `INVESTIGATION_LAYOUT_DEAD_SPACE_STALE_TREE_RESURRECTION_2026_07_08.md`).
279pub(crate) async fn queue_source_layout_delete(
280    state: &super::super::AppState,
281    source_tab_id: &str,
282    block_id: &str,
283) -> Result<(), String> {
284    // srv's own tree first (a no-op when a caller already took it out), so
285    // the window's mirror of the `delete` is never the only copy of it.
286    super::layout_intents::remove_block_from_layout(state, source_tab_id, block_id).await?;
287    super::reducer_helpers::queue_layout_actions_via_reducer(state, source_tab_id, vec![source_delete_action(block_id)])
288        .await
289}
290
291/// The frontend `delete` action for one block: its handler removes just that
292/// stack member (the leaf goes with the last one) and never runs `closeNode`.
293pub(crate) fn source_delete_action(block_id: &str) -> LayoutActionData {
294    LayoutActionData {
295        actiontype: "delete".to_string(),
296        actionid: uuid::Uuid::new_v4().to_string(),
297        blockid: block_id.to_string(),
298        nodesize: None,
299        nodesizefraction: None,
300        indexarr: None,
301        focused: false,
302        magnified: false,
303        ephemeral: false,
304        targetblockid: String::new(),
305        position: String::new(),
306        nodeid: None,
307        queuedat: None,
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314    use crate::server::tests::{dispatch_apply, test_state};
315    use agentmux_common::ipc::{Command, Event};
316
317    /// A reducer-known tab (the queue helpers dispatch through the reducer,
318    /// which rejects unknown tabs) holding one pane of block `target`.
319    /// Returns `(tab_id, target)`.
320    async fn tab_with_one_pane(state: &crate::server::AppState) -> (String, String) {
321        let ws = dispatch_apply(state, Command::CreateWorkspace { name: "ws".into() }).await;
322        let Some(Event::WorkspaceCreated { workspace_id, .. }) = ws.first() else { panic!("{ws:?}") };
323        let tab = dispatch_apply(state, Command::CreateTab { workspace_id: workspace_id.clone(), name: "t1".into() }).await;
324        let tab_id = tab
325            .iter()
326            .find_map(|e| match e {
327                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
328                _ => None,
329            })
330            .unwrap();
331        let target = new_block(state, &tab_id).await;
332        super::super::layout_intents::place_block(state, &tab_id, &target, Placement::Append { focused: false })
333            .await
334            .unwrap();
335        (tab_id, target)
336    }
337
338    async fn new_block(state: &crate::server::AppState, tab_id: &str) -> String {
339        let ev = dispatch_apply(state, Command::CreateBlock { tab_id: tab_id.into(), meta: serde_json::Value::Null }).await;
340        ev.iter()
341            .find_map(|e| match e {
342                Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
343                _ => None,
344            })
345            .unwrap()
346    }
347
348    fn pending_actions(state: &crate::server::AppState, tab_id: &str) -> Vec<LayoutActionData> {
349        let tab = state.mstore.must_get::<Tab>(tab_id).unwrap();
350        let layout = state.mstore.must_get::<LayoutState>(&tab.layoutstate).unwrap();
351        layout.pendingbackendactions.unwrap_or_default()
352    }
353
354    fn last_action(state: &crate::server::AppState, tab_id: &str) -> LayoutActionData {
355        pending_actions(state, tab_id).last().expect("an action was queued").clone()
356    }
357
358    async fn stored_tree(state: &crate::server::AppState, tab_id: &str) -> agentmux_common::LayoutNode {
359        let tab = state.mstore.must_get::<Tab>(tab_id).unwrap();
360        let row = state.mstore.must_get::<LayoutState>(&tab.layoutstate).unwrap();
361        assert_eq!(row.rootnode, state.srv_state.lock().await.tabs[tab_id].rootnode, "the row is the reducer tree");
362        row.rootnode.expect("a tree")
363    }
364
365    #[tokio::test]
366    async fn a_split_is_placed_in_srv_and_queued_with_its_node_id_and_fraction() {
367        // Phase 4c: every non-Center direction carries `nodesizefraction`, the
368        // exact share of the target's live size; see
369        // ANALYSIS_FLOATING_PANE_GHOST_LANDING_DISCONNECT_2026_07_04.md.
370        let cases: &[(u8, &str, &str, f64)] = &[
371            (0, "splitvertical", "before", 0.5),
372            (4, "splitvertical", "before", 0.2),
373            (2, "splitvertical", "after", 0.5),
374            (6, "splitvertical", "after", 0.2),
375            (3, "splithorizontal", "before", 0.5),
376            (7, "splithorizontal", "before", 0.2),
377            (1, "splithorizontal", "after", 0.5),
378            (5, "splithorizontal", "after", 0.2),
379        ];
380        for &(dir, expected_type, expected_pos, expected_fraction) in cases {
381            let state = test_state();
382            let (tab_id, target) = tab_with_one_pane(&state).await;
383            let block = new_block(&state, &tab_id).await;
384            queue_target_layout_split(&state, &tab_id, &block, &target, dir).await.unwrap();
385            let action = last_action(&state, &tab_id);
386            assert_eq!(action.actiontype, expected_type, "dir={dir}");
387            assert_eq!(action.position, expected_pos, "dir={dir}");
388            assert_eq!(action.nodesizefraction, Some(expected_fraction), "dir={dir}");
389            assert_eq!(action.targetblockid, target);
390            let tree = stored_tree(&state, &tab_id).await;
391            let leaf = crate::backend::layout::find_leaf_containing_block(&tree, &block).expect("placed in srv");
392            assert_eq!(action.nodeid.as_deref(), Some(leaf.id.as_str()), "dir={dir}");
393            assert!((leaf.size - 10.0 * expected_fraction as f32).abs() < 1e-4, "dir={dir}: size {}", leaf.size);
394        }
395    }
396
397    #[tokio::test]
398    async fn center_unknown_dirs_and_a_missing_target_fall_back_to_an_insert() {
399        let state = test_state();
400        let (tab_id, target) = tab_with_one_pane(&state).await;
401        for (dir, against) in [(8u8, target.as_str()), (200u8, target.as_str()), (1u8, "no-such-block")] {
402            let block = new_block(&state, &tab_id).await;
403            queue_target_layout_split(&state, &tab_id, &block, against, dir).await.unwrap();
404            let action = last_action(&state, &tab_id);
405            assert_eq!(action.actiontype, "insert", "dir={dir}");
406            assert_eq!(action.nodesizefraction, None, "dir={dir}");
407            let tree = stored_tree(&state, &tab_id).await;
408            assert!(crate::backend::layout::find_leaf_containing_block(&tree, &block).is_some(), "dir={dir}");
409        }
410    }
411
412    #[tokio::test]
413    async fn a_source_delete_takes_the_block_out_of_srv_first() {
414        let state = test_state();
415        let (tab_id, target) = tab_with_one_pane(&state).await;
416        let other = new_block(&state, &tab_id).await;
417        queue_target_layout_insert(&state, &tab_id, &other).await.unwrap();
418        queue_source_layout_delete(&state, &tab_id, &other).await.unwrap();
419        let tree = stored_tree(&state, &tab_id).await;
420        assert!(crate::backend::layout::find_leaf_containing_block(&tree, &other).is_none());
421        assert!(crate::backend::layout::find_leaf_containing_block(&tree, &target).is_some());
422        assert_eq!(last_action(&state, &tab_id).actiontype, "delete");
423        // Again, once it is gone: srv has nothing left to do, the window still hears.
424        queue_source_layout_delete(&state, &tab_id, &other).await.unwrap();
425        assert_eq!(pending_actions(&state, &tab_id).iter().filter(|a| a.actiontype == "delete").count(), 2);
426    }
427
428    #[tokio::test]
429    async fn queue_helpers_error_on_reducer_unknown_tab() {
430        let state = test_state();
431        let err = queue_source_layout_delete(&state, "ghost-tab", "b1")
432            .await
433            .expect_err("unknown tab must error");
434        assert!(err.contains("unknown tab"), "got: {err}");
435    }
436}