1use agentmux_common::ipc::{Command, Event};
9use agentmux_common::{FlexDirection, LayoutClientSlices, LayoutEdge, LayoutIntent, LayoutNode, LayoutNodeData, LayoutViewState, SplitPosition};
10
11use crate::backend::obj::{LayoutActionData, LayoutState, Tab};
12
13use super::super::AppState;
14
15#[derive(Debug, Clone, PartialEq)]
17pub(crate) struct IntentOutcome {
18 pub applied: bool,
20 pub error: Option<String>,
21 pub version: u64,
23}
24
25pub(crate) async fn apply_layout_intent(
30 state: &AppState,
31 tab_id: &str,
32 intent: LayoutIntent,
33 action_id: &str,
34 view: Option<LayoutViewState>,
35) -> Result<IntentOutcome, String> {
36 let store = &state.mstore;
37 let layout_oid = store
38 .must_get::<Tab>(tab_id)
39 .map_err(|e| format!("layout intent: tab {tab_id}: {e}"))?
40 .layoutstate;
41 let row_version = || layout_row_version(store, tab_id);
42 let cmd = Command::LayoutApplyIntent {
43 tab_id: tab_id.to_string(),
44 intent,
45 action_id: action_id.to_string(),
46 view,
47 };
48 let (events, outcome) = {
49 let mut s = state.srv_state.lock().await;
50 let old_row = store.get::<LayoutState>(&layout_oid).map_err(|e| format!("layout intent: {e}"))?;
51 let ctx = crate::reducer::Ctx::new(None);
52 let events = crate::reducer::update(&mut s, cmd, &ctx);
53 if let Some(message) = events.iter().find_map(|e| match e {
54 Event::Error { message, .. } => Some(message.clone()),
55 _ => None,
56 }) {
57 tracing::info!(tab_id, action_id, "layout intent refused: {message}");
58 let outcome = IntentOutcome { applied: false, error: Some(message), version: row_version() };
59 (Vec::new(), outcome)
60 } else if let Some(err) = events
61 .iter()
62 .find_map(|ev| crate::persist_subscriber::apply_event_to_mstore(ev, store).err())
63 {
64 roll_back(&mut s, store, tab_id, action_id, old_row);
65 return Err(format!("layout intent: SQLite write failed: {err}"));
66 } else {
67 (events, IntentOutcome { applied: true, error: None, version: row_version() })
68 }
69 };
70 super::publish_events(state, &events);
71 Ok(outcome)
72}
73
74pub(crate) fn layout_row_version(store: &crate::backend::storage::store::Store, tab_id: &str) -> u64 {
76 store
77 .get::<Tab>(tab_id)
78 .ok()
79 .flatten()
80 .and_then(|tab| store.get::<LayoutState>(&tab.layoutstate).ok().flatten())
81 .map_or(0, |row| row.version as u64)
82}
83
84fn roll_back(
87 s: &mut crate::state::State,
88 store: &crate::backend::storage::store::Store,
89 tab_id: &str,
90 action_id: &str,
91 old_row: Option<LayoutState>,
92) {
93 let Some(old) = old_row else { return };
94 let rollback = Command::LayoutSetTree {
95 tab_id: tab_id.to_string(),
96 new_tree: old.rootnode.clone(),
97 correlation_id: String::new(),
98 slices: Some(LayoutClientSlices {
99 focused_node_id: old.focusednodeid.clone(),
100 magnified_node_id: old.magnifiednodeid.clone(),
101 pending_backend_actions: old.pendingbackendactions.as_ref().and_then(|v| serde_json::to_value(v).ok()),
102 }),
103 };
104 for ev in crate::reducer::update(s, rollback, &crate::reducer::Ctx::new(None)) {
105 if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(&ev, store) {
106 tracing::warn!(error = %e, "layout intent: rollback SQLite mirror failed");
107 }
108 }
109 if let Some(tab) = s.tabs.get_mut(tab_id) {
110 tab.recent_intent_ids.retain(|id| id != action_id);
111 }
112}
113
114#[derive(Debug, Clone, PartialEq)]
116pub(crate) enum Placement {
117 Append { focused: bool },
119 Split {
123 target_block_id: String,
124 horizontal: bool,
125 position: SplitPosition,
126 size_fraction: Option<f64>,
127 focused: bool,
128 },
129}
130
131pub(crate) async fn place_block(state: &AppState, tab_id: &str, block_id: &str, placement: Placement) -> Result<(), String> {
136 let node_id = uuid::Uuid::new_v4().to_string();
137 let action_id = uuid::Uuid::new_v4().to_string();
138 let leaf = LayoutNode {
139 id: node_id.clone(),
140 flex_direction: FlexDirection::Row,
141 size: crate::backend::layout::DEFAULT_NODE_SIZE,
142 data: Some(LayoutNodeData { block_id: block_id.to_string(), ..Default::default() }),
143 ..Default::default()
144 };
145 let mut placement = placement;
146 if let Placement::Split { target_block_id, horizontal, position, size_fraction, focused } = &placement {
147 let target_node_id = state.srv_state.lock().await.tabs.get(tab_id).and_then(|t| t.rootnode.as_ref()).and_then(|root| {
148 crate::backend::layout::find_leaf_containing_block(root, target_block_id).map(|n| n.id.clone())
149 });
150 if let Some(target_node_id) = target_node_id {
151 let new_node = leaf.clone();
152 let (position, size_fraction, focused) = (*position, *size_fraction, *focused);
153 let intent = if *horizontal {
154 LayoutIntent::SplitHorizontal { target_node_id, new_node, position, size_fraction, focused }
155 } else {
156 LayoutIntent::SplitVertical { target_node_id, new_node, position, size_fraction, focused }
157 };
158 if apply_layout_intent(state, tab_id, intent, &action_id, None).await?.applied {
159 let action = LayoutActionData {
160 actiontype: if *horizontal { "splithorizontal" } else { "splitvertical" }.to_string(),
161 actionid: action_id,
162 blockid: block_id.to_string(),
163 nodesizefraction: size_fraction,
164 focused,
165 targetblockid: target_block_id.clone(),
166 position: match position {
167 SplitPosition::Before => "before",
168 SplitPosition::After => "after",
169 }
170 .to_string(),
171 nodeid: Some(node_id),
172 ..Default::default()
173 };
174 return super::reducer_helpers::queue_layout_actions_via_reducer(state, tab_id, vec![action]).await;
175 }
176 }
177 placement = Placement::Append { focused: *focused };
178 }
179 let Placement::Append { focused } = placement else { unreachable!("a split fell back above") };
180 let outcome =
181 apply_layout_intent(state, tab_id, LayoutIntent::Insert { node: leaf, magnified: false, focused }, &action_id, None)
182 .await?;
183 if !outcome.applied {
184 return Err(format!("placing block {block_id}: {}", outcome.error.unwrap_or_default()));
185 }
186 let action = LayoutActionData {
187 actiontype: "insert".to_string(),
188 actionid: action_id,
189 blockid: block_id.to_string(),
190 focused,
191 nodeid: Some(node_id),
192 ..Default::default()
193 };
194 super::reducer_helpers::queue_layout_actions_via_reducer(state, tab_id, vec![action]).await
195}
196
197pub(crate) async fn block_is_minimized(state: &AppState, tab_id: &str, block_id: &str) -> bool {
199 let s = state.srv_state.lock().await;
200 s.tabs
201 .get(tab_id)
202 .and_then(|t| t.rootnode.as_ref())
203 .and_then(|root| crate::backend::layout::find_leaf_containing_block(root, block_id))
204 .is_some_and(|leaf| leaf.minimized)
205}
206
207pub(crate) async fn minimize_block_in_layout(state: &AppState, tab_id: &str, block_id: &str) -> Result<bool, String> {
211 let node_id = {
212 let s = state.srv_state.lock().await;
213 s.tabs
214 .get(tab_id)
215 .and_then(|t| t.rootnode.as_ref())
216 .and_then(|root| crate::backend::layout::find_leaf_containing_block(root, block_id))
217 .map(|leaf| leaf.id.clone())
218 };
219 let Some(node_id) = node_id else { return Ok(false) };
220 let action_id = uuid::Uuid::new_v4().to_string();
221 if !apply_layout_intent(state, tab_id, LayoutIntent::Minimize { node_id }, &action_id, None).await?.applied {
222 return Ok(false);
223 }
224 let action = LayoutActionData {
225 actiontype: "minimize".to_string(),
226 actionid: action_id,
227 blockid: block_id.to_string(),
228 ..Default::default()
229 };
230 super::reducer_helpers::queue_layout_actions_via_reducer(state, tab_id, vec![action]).await?;
231 Ok(true)
232}
233
234pub(crate) async fn move_block_to_edge(state: &AppState, tab_id: &str, block_id: &str, (edge, size): (LayoutEdge, Option<f64>)) -> Result<bool, String> {
238 let node_id = {
239 let s = state.srv_state.lock().await;
240 s.tabs
241 .get(tab_id)
242 .and_then(|t| t.rootnode.as_ref())
243 .and_then(|root| crate::backend::layout::find_leaf_containing_block(root, block_id))
244 .map(|leaf| leaf.id.clone())
245 };
246 let Some(node_id) = node_id else { return Ok(false) };
247 let action_id = uuid::Uuid::new_v4().to_string();
248 if !apply_layout_intent(state, tab_id, LayoutIntent::MoveToEdge { node_id, edge, size }, &action_id, None).await?.applied {
249 return Ok(false);
250 }
251 let position = serde_json::to_value(edge).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
252 let action = LayoutActionData { actiontype: "movetoedge".to_string(), actionid: action_id, blockid: block_id.to_string(), position, nodesizefraction: size, ..Default::default() };
253 super::reducer_helpers::queue_layout_actions_via_reducer(state, tab_id, vec![action]).await?;
254 Ok(true)
255}
256
257pub(crate) async fn remove_block_from_layout(state: &AppState, tab_id: &str, block_id: &str) -> Result<(), String> {
261 let cmd = Command::LayoutDeleteNodeByBlock {
262 tab_id: tab_id.to_string(),
263 block_id: block_id.to_string(),
264 correlation_id: String::new(),
265 };
266 let events = {
267 let mut s = state.srv_state.lock().await;
268 let events = crate::reducer::update(&mut s, cmd, &crate::reducer::Ctx::new(None));
269 if let Some(message) = events.iter().find_map(|e| match e {
270 Event::Error { message, .. } => Some(message.clone()),
271 _ => None,
272 }) {
273 return Err(message);
274 }
275 for ev in &events {
276 crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).map_err(|e| e.to_string())?;
277 }
278 events
279 };
280 super::publish_events(state, &events);
281 Ok(())
282}