Skip to main content

agentmux_common/
layout_intent.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Layout intents: the frontend's layout-tree actions, sent to srv instead of
5//! the tree they produce. Each variant is one `LayoutTreeActionType` of
6//! `frontend/layout/lib/types.ts`, with the same `type` tag and field names,
7//! so the frontend sends what its own reducer applied.
8//! docs/specs/SPEC_STRONG_REDUCER_AUTHORITY_LAYOUT_2026_06_30.md ยง4.
9//!
10//! The TypeScript derives are behind the `ts` feature, which only srv turns on.
11
12use serde::{Deserialize, Serialize};
13
14use crate::{LayoutNode, SplitPosition};
15
16/// One resize: a node and its new flex size (0 to 100).
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(export_to = "../../../frontend/types/rpc/"))]
19pub struct LayoutResizeOp {
20    #[serde(rename = "nodeId")]
21    pub node_id: String,
22    pub size: f64,
23}
24
25/// Where a pane that is moved to the layout's edge goes: a band across the whole top or the whole bottom of the
26/// layout, or across its middle; or a column down the whole of its left or right side.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(export_to = "../../../frontend/types/rpc/"))]
29#[serde(rename_all = "lowercase")]
30pub enum LayoutEdge {
31    Top,
32    Bottom,
33    Middle,
34    Left,
35    Right,
36}
37
38/// A layout edit, applied by srv's reducer to its own tree for the tab.
39/// Nodes the intent adds (`node`, `newNode`) carry the id the sender gave
40/// them; branches srv creates on the way get ids derived from the command's
41/// action id (`backend::layout::intent::derive_node_id`), so the sender can
42/// predict the whole result.
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(export_to = "../../../frontend/types/rpc/"))]
45#[serde(tag = "type", rename_all = "lowercase")]
46pub enum LayoutIntent {
47    /// Add `node` at the first free slot (`findNextInsertLocation`).
48    Insert {
49        #[cfg_attr(feature = "ts", ts(type = "any"))]
50        node: LayoutNode,
51        #[serde(default)]
52        magnified: bool,
53        #[serde(default)]
54        focused: bool,
55    },
56    /// Add `node` after the slot an index path names.
57    #[serde(rename = "insertatindex")]
58    InsertAtIndex {
59        #[cfg_attr(feature = "ts", ts(type = "any"))]
60        node: LayoutNode,
61        #[serde(rename = "indexArr")]
62        #[cfg_attr(feature = "ts", ts(type = "Array<number>"))]
63        index_arr: Vec<i64>,
64        #[serde(default)]
65        magnified: bool,
66        #[serde(default)]
67        focused: bool,
68    },
69    /// Remove a node (and everything under it).
70    Delete {
71        #[serde(rename = "nodeId")]
72        node_id: String,
73    },
74    /// Re-parent a node: the commit of a pane drag.
75    Move {
76        #[serde(rename = "nodeId")]
77        node_id: String,
78        #[serde(rename = "parentId", default, skip_serializing_if = "Option::is_none")]
79        #[cfg_attr(feature = "ts", ts(optional))]
80        parent_id: Option<String>,
81        #[cfg_attr(feature = "ts", ts(type = "number"))]
82        index: i64,
83        #[serde(rename = "insertAtRoot", default)]
84        insert_at_root: bool,
85    },
86    /// Move a pane to be a band across the whole layout: its width is the layout's, at the top, the bottom or the
87    /// middle of it, and the other panes keep their arrangement in the space that is left.
88    #[serde(rename = "movetoedge")]
89    MoveToEdge {
90        #[serde(rename = "nodeId")]
91        node_id: String,
92        edge: LayoutEdge,
93        /// The share of the layout the band takes, a fraction (a pinned pane unpinned into another tab keeps the
94        /// thickness it had); without it the band takes the default third.
95        #[serde(default, skip_serializing_if = "Option::is_none")]
96        size: Option<f64>,
97    },
98    /// Swap two nodes; each slot keeps its size.
99    Swap {
100        #[serde(rename = "node1Id")]
101        node1_id: String,
102        #[serde(rename = "node2Id")]
103        node2_id: String,
104    },
105    /// Set node sizes: the commit of a divider drag. All or nothing.
106    Resize {
107        #[serde(rename = "resizeOperations")]
108        resize_operations: Vec<LayoutResizeOp>,
109    },
110    /// Put `newNode` where `targetNodeId` is, keeping its size.
111    Replace {
112        #[serde(rename = "targetNodeId")]
113        target_node_id: String,
114        #[serde(rename = "newNode")]
115        #[cfg_attr(feature = "ts", ts(type = "any"))]
116        new_node: LayoutNode,
117        #[serde(default)]
118        focused: bool,
119    },
120    /// Put `newNode` beside `targetNodeId`, in a row.
121    #[serde(rename = "splithorizontal")]
122    SplitHorizontal {
123        #[serde(rename = "targetNodeId")]
124        target_node_id: String,
125        #[serde(rename = "newNode")]
126        #[cfg_attr(feature = "ts", ts(type = "any"))]
127        new_node: LayoutNode,
128        #[cfg_attr(feature = "ts", ts(type = r#""before" | "after""#))]
129        position: SplitPosition,
130        #[serde(rename = "sizeFraction", default, skip_serializing_if = "Option::is_none")]
131        #[cfg_attr(feature = "ts", ts(optional))]
132        size_fraction: Option<f64>,
133        #[serde(default)]
134        focused: bool,
135    },
136    /// Put `newNode` beside `targetNodeId`, in a column.
137    #[serde(rename = "splitvertical")]
138    SplitVertical {
139        #[serde(rename = "targetNodeId")]
140        target_node_id: String,
141        #[serde(rename = "newNode")]
142        #[cfg_attr(feature = "ts", ts(type = "any"))]
143        new_node: LayoutNode,
144        #[cfg_attr(feature = "ts", ts(type = r#""before" | "after""#))]
145        position: SplitPosition,
146        #[serde(rename = "sizeFraction", default, skip_serializing_if = "Option::is_none")]
147        #[cfg_attr(feature = "ts", ts(optional))]
148        size_fraction: Option<f64>,
149        #[serde(default)]
150        focused: bool,
151    },
152    /// Show a leaf as a header chip; its size is kept. Refused for the last
153    /// pane still showing content.
154    Minimize {
155        #[serde(rename = "nodeId")]
156        node_id: String,
157    },
158    /// Show a minimized leaf again.
159    Restore {
160        #[serde(rename = "nodeId")]
161        node_id: String,
162    },
163    /// Empty the tree.
164    Clear,
165    /// No tree change: only the focused and magnified pane, which travel
166    /// with every intent (a click, a magnify toggle).
167    View,
168}
169
170impl LayoutIntent {
171    /// The frontend's name for it, for logs and errors.
172    pub fn name(&self) -> &'static str {
173        match self {
174            Self::Insert { .. } => "insert",
175            Self::InsertAtIndex { .. } => "insertatindex",
176            Self::Delete { .. } => "delete",
177            Self::Move { .. } => "move",
178            Self::MoveToEdge { .. } => "movetoedge",
179            Self::Swap { .. } => "swap",
180            Self::Resize { .. } => "resize",
181            Self::Replace { .. } => "replace",
182            Self::SplitHorizontal { .. } => "splithorizontal",
183            Self::SplitVertical { .. } => "splitvertical",
184            Self::Minimize { .. } => "minimize",
185            Self::Restore { .. } => "restore",
186            Self::Clear => "clear",
187            Self::View => "view",
188        }
189    }
190}
191
192/// The focused and magnified pane the sender holds after the intent. Focus
193/// is the frontend's to pick (it keeps the focus history and the pane
194/// geometry that choose a successor), so srv stores it as sent, cleared if
195/// it names no node of the resulting tree.
196#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
197pub struct LayoutViewState {
198    pub focused_node_id: String,
199    pub magnified_node_id: String,
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn intents_parse_from_the_frontend_action_shape() {
208        let split: LayoutIntent = serde_json::from_value(serde_json::json!({
209            "type": "splithorizontal",
210            "targetNodeId": "t",
211            "newNode": {"id": "n", "flexDirection": "row", "size": 10, "data": {"blockId": "b"}},
212            "position": "after",
213            "sizeFraction": 0.5,
214            "focused": true
215        }))
216        .unwrap();
217        assert!(matches!(
218            split,
219            LayoutIntent::SplitHorizontal { position: SplitPosition::After, size_fraction: Some(f), focused: true, .. } if f == 0.5
220        ));
221        let resize: LayoutIntent = serde_json::from_value(serde_json::json!({
222            "type": "resize",
223            "resizeOperations": [{"nodeId": "a", "size": 12.5}]
224        }))
225        .unwrap();
226        assert_eq!(resize.name(), "resize");
227        let view: LayoutIntent = serde_json::from_value(serde_json::json!({"type": "view"})).unwrap();
228        assert_eq!(view, LayoutIntent::View);
229    }
230
231    #[test]
232    fn intents_round_trip() {
233        let intent = LayoutIntent::Move {
234            node_id: "a".into(),
235            parent_id: Some("p".into()),
236            index: 2,
237            insert_at_root: false,
238        };
239        let json = serde_json::to_value(&intent).unwrap();
240        assert_eq!(json["type"], "move");
241        assert_eq!(json["parentId"], "p");
242        assert_eq!(serde_json::from_value::<LayoutIntent>(json).unwrap(), intent);
243    }
244}