1use crate::backend::obj::*;
12
13use super::layout_intents::Placement;
14
15pub(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
38pub(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 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 super::reducer_helpers::seed_layout_via_reducer(state, new_tab_id, rootnode, String::new(), String::new()).await
67}
68
69fn 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
80pub(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
91pub(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
121pub(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
160pub(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
205pub(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
222pub(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
234fn 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
245pub(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
274pub(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 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
291pub(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 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 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 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}