1use agentmux_common::ipc::Command;
15use agentmux_common::{FlexDirection, LayoutNode, SplitPosition};
16use serde::{Deserialize, Serialize};
17
18use super::super::AppState;
19use super::layout_intents::{place_block, Placement};
20use super::reducer_helpers::{dispatch_to_reducer, publish_events};
21use crate::backend::layout::{find_leaf_containing_block, leaf_members};
22
23pub(crate) const META_KEY: &str = "floater:origin";
25
26const MAX_ANCHORS: usize = 4;
28
29const FRACTION_RANGE: (f64, f64) = (0.15, 0.85);
32
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub(crate) struct Anchor {
36 pub block_id: String,
38 pub horizontal: bool,
40 pub after: bool,
42 pub fraction: f64,
44}
45
46#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
48pub(crate) struct OriginRecord {
49 pub tab_id: String,
50 pub workspace_id: String,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub stack_mate: Option<String>,
54 #[serde(default)]
56 pub anchors: Vec<Anchor>,
57}
58
59#[derive(Debug, Clone, PartialEq)]
61pub(crate) enum Resolution {
62 StackMate(String),
64 Split(Anchor),
66 Fallback,
68}
69
70impl Resolution {
71 pub(crate) fn label(&self) -> &'static str {
73 match self {
74 Resolution::StackMate(_) => "stack",
75 Resolution::Split(_) => "neighbour",
76 Resolution::Fallback => "fallback",
77 }
78 }
79}
80
81fn path_to<'a>(
84 node: &'a LayoutNode,
85 block_id: &str,
86 path: &mut Vec<(&'a LayoutNode, usize)>,
87) -> Option<&'a LayoutNode> {
88 if node
89 .data
90 .as_ref()
91 .is_some_and(|d| d.block_id == block_id || d.block_stack.iter().any(|b| b == block_id))
92 {
93 return Some(node);
94 }
95 for (i, child) in node.children.iter().enumerate() {
96 path.push((node, i));
97 if let Some(found) = path_to(child, block_id, path) {
98 return Some(found);
99 }
100 path.pop();
101 }
102 None
103}
104
105fn first_shown_block(node: &LayoutNode) -> Option<String> {
107 if let Some(data) = node.data.as_ref() {
108 return (!node.minimized).then(|| data.block_id.clone());
109 }
110 node.children.iter().find_map(first_shown_block)
111}
112
113fn share(own: f32, other: f32) -> f64 {
114 let total = f64::from(own) + f64::from(other);
115 if total <= 0.0 {
116 return 0.5;
117 }
118 (f64::from(own) / total).clamp(FRACTION_RANGE.0, FRACTION_RANGE.1)
119}
120
121pub(crate) fn record_from_tree(
124 root: &LayoutNode,
125 torn: &[String],
126 tab_id: &str,
127 workspace_id: &str,
128) -> Option<OriginRecord> {
129 let first = torn.first()?;
130 let mut path = Vec::new();
131 let pane = path_to(root, first, &mut path)?;
132 let stack_mate = pane
133 .data
134 .as_ref()
135 .and_then(|d| leaf_members(d).into_iter().find(|m| !torn.contains(m)));
136 let mut anchors = Vec::new();
137 'levels: for (parent, idx) in path.iter().rev() {
139 let horizontal = parent.flex_direction == FlexDirection::Row;
140 let own = parent.children[*idx].size;
141 let before = idx.checked_sub(1).map(|i| (i, true));
142 let after = (idx + 1 < parent.children.len()).then_some((idx + 1, false));
143 for (i, sits_after) in before.into_iter().chain(after) {
144 let neighbour = &parent.children[i];
145 let Some(block_id) = first_shown_block(neighbour) else {
146 continue;
147 };
148 anchors.push(Anchor {
149 block_id,
150 horizontal,
151 after: sits_after,
152 fraction: share(own, neighbour.size),
153 });
154 if anchors.len() == MAX_ANCHORS {
155 break 'levels;
156 }
157 }
158 }
159 if anchors.is_empty() && stack_mate.is_none() {
160 return None;
161 }
162 Some(OriginRecord {
163 tab_id: tab_id.to_string(),
164 workspace_id: workspace_id.to_string(),
165 stack_mate,
166 anchors,
167 })
168}
169
170pub(crate) fn resolve(root: Option<&LayoutNode>, rec: &OriginRecord) -> Resolution {
175 let Some(root) = root else {
176 return Resolution::Fallback;
177 };
178 if let Some(mate) = rec
179 .stack_mate
180 .as_ref()
181 .filter(|m| find_leaf_containing_block(root, m).is_some())
182 {
183 return Resolution::StackMate(mate.clone());
184 }
185 rec.anchors
186 .iter()
187 .find(|a| find_leaf_containing_block(root, &a.block_id).is_some_and(|pane| !pane.minimized))
188 .map_or(Resolution::Fallback, |a| Resolution::Split(a.clone()))
189}
190
191async fn patch_block_meta(state: &AppState, block_id: &str, patch: serde_json::Value) {
192 let events = dispatch_to_reducer(
193 state,
194 Command::UpdateBlockMeta {
195 block_id: block_id.to_string(),
196 meta_patch: patch,
197 },
198 )
199 .await;
200 for ev in &events {
201 if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore) {
202 tracing::warn!(block = %block_id, "floater origin: meta write failed: {e}");
203 }
204 }
205 publish_events(state, &events);
206}
207
208pub(crate) async fn record_for(
210 state: &AppState,
211 tab_id: &str,
212 workspace_id: &str,
213 torn: &[String],
214) -> Option<OriginRecord> {
215 let s = state.srv_state.lock().await;
216 let root = s.tabs.get(tab_id)?.rootnode.as_ref()?;
217 record_from_tree(root, torn, tab_id, workspace_id)
218}
219
220pub(crate) async fn store(state: &AppState, blocks: &[String], rec: &OriginRecord) {
222 let Ok(value) = serde_json::to_value(rec) else {
223 return;
224 };
225 for block_id in blocks {
226 patch_block_meta(state, block_id, serde_json::json!({ META_KEY: value })).await;
227 }
228}
229
230pub(crate) async fn remember(state: &AppState, blocks: &[String], rec: Option<&OriginRecord>) {
232 match rec {
233 Some(rec) => store(state, blocks, rec).await,
234 None => clear(state, blocks).await,
235 }
236}
237
238pub(crate) async fn clear(state: &AppState, blocks: &[String]) {
241 for block_id in blocks {
242 let has_record = state
243 .mstore
244 .must_get::<crate::backend::obj::Block>(block_id)
245 .is_ok_and(|b| b.meta.contains_key(META_KEY));
246 if has_record {
247 patch_block_meta(state, block_id, serde_json::json!({ META_KEY: null })).await;
248 }
249 }
250}
251
252pub(crate) async fn resolve_for_block(
255 state: &AppState,
256 block_id: &str,
257) -> Option<(OriginRecord, Resolution)> {
258 let block = state
259 .mstore
260 .must_get::<crate::backend::obj::Block>(block_id)
261 .ok()?;
262 let rec: OriginRecord = serde_json::from_value(block.meta.get(META_KEY)?.clone()).ok()?;
263 let s = state.srv_state.lock().await;
264 let tab = s.tabs.get(&rec.tab_id)?;
265 if tab.workspace_id != rec.workspace_id
266 || !s
267 .windows
268 .values()
269 .any(|w| w.workspace_id == rec.workspace_id)
270 {
271 return None;
272 }
273 let resolution = resolve(tab.rootnode.as_ref(), &rec);
274 Some((rec, resolution))
275}
276
277pub(crate) async fn target_for(
280 state: &AppState,
281 block_id: &str,
282 fallback_tab_id: String,
283 fallback_ws_id: String,
284) -> (String, String, Resolution) {
285 match resolve_for_block(state, block_id).await {
286 Some((rec, resolution)) if resolution != Resolution::Fallback => {
287 (rec.tab_id, rec.workspace_id, resolution)
288 }
289 _ => (fallback_tab_id, fallback_ws_id, Resolution::Fallback),
290 }
291}
292
293pub(crate) async fn place_at_anchor(
296 state: &AppState,
297 tab_id: &str,
298 block_id: &str,
299 anchor: &Anchor,
300) -> Result<(), String> {
301 let placement = Placement::Split {
302 target_block_id: anchor.block_id.clone(),
303 horizontal: anchor.horizontal,
304 position: if anchor.after {
305 SplitPosition::After
306 } else {
307 SplitPosition::Before
308 },
309 size_fraction: Some(anchor.fraction),
310 focused: true,
311 };
312 place_block(state, tab_id, block_id, placement).await
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318 use agentmux_common::LayoutNodeData;
319
320 fn leaf(id: &str, block: &str, size: f32) -> LayoutNode {
321 LayoutNode {
322 id: id.into(),
323 size,
324 data: Some(LayoutNodeData {
325 block_id: block.into(),
326 ..Default::default()
327 }),
328 ..Default::default()
329 }
330 }
331
332 fn group(id: &str, dir: FlexDirection, children: Vec<LayoutNode>) -> LayoutNode {
333 LayoutNode {
334 id: id.into(),
335 flex_direction: dir,
336 size: 10.0,
337 children,
338 ..Default::default()
339 }
340 }
341
342 fn row() -> LayoutNode {
344 group(
345 "root",
346 FlexDirection::Row,
347 vec![
348 leaf("na", "a", 10.0),
349 leaf("nb", "b", 20.0),
350 leaf("nc", "c", 10.0),
351 ],
352 )
353 }
354
355 fn rec(root: &LayoutNode, torn: &[&str]) -> OriginRecord {
356 let torn: Vec<String> = torn.iter().map(|s| s.to_string()).collect();
357 record_from_tree(root, &torn, "tab", "ws").expect("a record")
358 }
359
360 fn without(root: &LayoutNode, block: &str) -> LayoutNode {
361 let mut out = root.clone();
362 out.children
363 .retain(|c| c.data.as_ref().is_none_or(|d| d.block_id != block));
364 out
365 }
366
367 #[test]
368 fn the_record_lists_the_neighbours_nearest_first_with_their_side_and_share() {
369 let r = rec(&row(), &["b"]);
370 assert_eq!(
371 (
372 r.tab_id.as_str(),
373 r.workspace_id.as_str(),
374 r.stack_mate.clone()
375 ),
376 ("tab", "ws", None)
377 );
378 assert_eq!(
379 r.anchors,
380 vec![
381 Anchor {
382 block_id: "a".into(),
383 horizontal: true,
384 after: true,
385 fraction: 20.0 / 30.0
386 },
387 Anchor {
388 block_id: "c".into(),
389 horizontal: true,
390 after: false,
391 fraction: 20.0 / 30.0
392 },
393 ]
394 );
395 }
396
397 #[test]
398 fn a_pane_alone_in_its_tab_has_no_record_and_a_stack_mate_alone_is_enough() {
399 assert_eq!(
400 record_from_tree(&leaf("only", "x", 10.0), &["x".to_string()], "tab", "ws"),
401 None
402 );
403 let mut pane = leaf("p", "a", 10.0);
404 pane.data.as_mut().unwrap().block_stack = vec!["a".into(), "b".into()];
405 let r =
406 record_from_tree(&pane, &["b".to_string()], "tab", "ws").expect("stack-mate record");
407 assert_eq!(r.stack_mate.as_deref(), Some("a"));
408 assert!(r.anchors.is_empty());
409 }
410
411 #[test]
412 fn the_record_goes_up_the_tree_for_more_neighbours_and_stops_at_four() {
413 let col = group(
415 "col",
416 FlexDirection::Column,
417 vec![
418 leaf("nb", "b", 10.0),
419 leaf("nc", "c", 10.0),
420 leaf("nd", "d", 10.0),
421 ],
422 );
423 let root = group(
424 "root",
425 FlexDirection::Row,
426 vec![leaf("na", "a", 10.0), col, leaf("ne", "e", 10.0)],
427 );
428 let r = rec(&root, &["c"]);
429 let ids: Vec<&str> = r.anchors.iter().map(|a| a.block_id.as_str()).collect();
430 assert_eq!(ids, ["b", "d", "a", "e"]);
431 assert!(
432 !r.anchors[0].horizontal && r.anchors[2].horizontal,
433 "the axis is each level's own"
434 );
435 assert_eq!(r.anchors.len(), MAX_ANCHORS);
436 }
437
438 #[test]
439 fn a_neighbour_that_is_a_chip_is_not_remembered() {
440 let mut root = row();
441 root.children[0].minimized = true;
442 let r = rec(&root, &["b"]);
443 assert_eq!(
444 r.anchors
445 .iter()
446 .map(|a| a.block_id.as_str())
447 .collect::<Vec<_>>(),
448 ["c"]
449 );
450 }
451
452 #[test]
453 fn a_neighbour_that_is_still_there_is_used_whatever_happened_to_sizes() {
454 let r = rec(&row(), &["b"]);
455 let mut resized = without(&row(), "b");
456 resized.children[0].size = 3.0;
457 resized.children[1].size = 40.0;
458 assert_eq!(
459 resolve(Some(&resized), &r),
460 Resolution::Split(r.anchors[0].clone())
461 );
462 }
463
464 #[test]
465 fn a_stack_mate_that_is_still_in_a_pane_wins_over_a_neighbour() {
466 let mut pane = leaf("nb", "b", 20.0);
467 pane.data.as_mut().unwrap().block_stack = vec!["b".into(), "t".into()];
468 let root = group(
469 "root",
470 FlexDirection::Row,
471 vec![leaf("na", "a", 10.0), pane, leaf("nc", "c", 10.0)],
472 );
473 let r = rec(&root, &["t"]);
474 assert_eq!(r.stack_mate.as_deref(), Some("b"));
475 assert_eq!(resolve(Some(&root), &r), Resolution::StackMate("b".into()));
476 }
477
478 #[test]
479 fn b_the_nearest_surviving_neighbour_is_used_when_the_first_is_gone() {
480 let r = rec(&row(), &["b"]);
481 let now = without(&without(&row(), "b"), "a");
482 assert_eq!(
483 resolve(Some(&now), &r),
484 Resolution::Split(r.anchors[1].clone())
485 );
486 }
487
488 #[test]
489 fn c_nothing_recognisable_falls_back() {
490 let r = rec(&row(), &["b"]);
491 assert_eq!(
492 resolve(Some(&leaf("x", "other", 10.0)), &r),
493 Resolution::Fallback,
494 "every neighbour closed"
495 );
496 assert_eq!(resolve(None, &r), Resolution::Fallback, "no tree");
497 let mut chips = without(&row(), "b");
498 chips.children.iter_mut().for_each(|c| c.minimized = true);
499 assert_eq!(
500 resolve(Some(&chips), &r),
501 Resolution::Fallback,
502 "the neighbours are chips now"
503 );
504 }
505
506 #[test]
507 fn the_record_round_trips_through_block_meta() {
508 let r = rec(&row(), &["b"]);
509 let back: OriginRecord = serde_json::from_value(serde_json::to_value(&r).unwrap()).unwrap();
510 assert_eq!(back, r);
511 }
512}