Skip to main content

agentmux_srv/server/service/
redock_origin.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where a torn-off pane came from, and where a redock puts it back
5//! (SPEC_FLOATING_PANE_REDOCK_TO_ORIGIN_2026_11_03.md).
6//!
7//! At tear-off the source tab's tree is read before the pane leaves it, and a small record goes into the
8//! block's meta (`floater:origin`, persisted with the block): the tab, the pane's tab-mate if one stays, and up
9//! to four neighbouring panes (nearest first) with the split axis, side and size share the pane had next to
10//! each. A redock by the button walks that record against the origin tab's tree as it is now and returns the
11//! first place that still exists; with none left it does what it always did. The functions that read and
12//! decide are pure, over a `LayoutNode`.
13
14use 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
23/// The block meta key that holds an `OriginRecord`.
24pub(crate) const META_KEY: &str = "floater:origin";
25
26/// How many neighbours are remembered.
27const MAX_ANCHORS: usize = 4;
28
29/// The share of the two panes' size the torn-off pane may take back, so a stale or odd size never gives a
30/// sliver or hides the neighbour.
31const FRACTION_RANGE: (f64, f64) = (0.15, 0.85);
32
33/// A neighbouring pane the torn-off pane can be put back beside.
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub(crate) struct Anchor {
36    /// A block of the neighbouring pane.
37    pub block_id: String,
38    /// Side by side (a row) rather than stacked (a column).
39    pub horizontal: bool,
40    /// The torn-off pane sat after the neighbour (to its right, or below it).
41    pub after: bool,
42    /// The share of the two panes' combined size the torn-off pane had.
43    pub fraction: f64,
44}
45
46/// Where a floating pane was torn from.
47#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
48pub(crate) struct OriginRecord {
49    pub tab_id: String,
50    pub workspace_id: String,
51    /// A block that stayed in the pane when only a pane tab left: the tab goes back into it.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub stack_mate: Option<String>,
54    /// Neighbouring panes, nearest first.
55    #[serde(default)]
56    pub anchors: Vec<Anchor>,
57}
58
59/// Where a redock puts the pane.
60#[derive(Debug, Clone, PartialEq)]
61pub(crate) enum Resolution {
62    /// As a tab of the pane that block is in.
63    StackMate(String),
64    /// Beside this neighbour, on its recorded side, with its recorded share.
65    Split(Anchor),
66    /// Nothing recognisable is left: where the caller was going to put it.
67    Fallback,
68}
69
70impl Resolution {
71    /// What the redock's answer calls it.
72    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
81/// The nodes from the root down to the pane holding `block_id`, as (parent, index of the child on the path),
82/// and that pane.
83fn 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
105/// The visible block of the first pane under `node` that is not a minimized chip.
106fn 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
121/// The record for a pane about to leave `tab_id`: `torn` are the blocks that leave, the first being the one the
122/// record is stored on. `None` when there is nothing to come back to (a pane alone in its tab, with no tab-mate).
123pub(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    // Level by level from the pane outward: its previous and next sibling, then its parent's.
138    '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
170/// Where `rec` puts the pane back, given the origin tab's tree as it is now. A tab-mate that is still in a pane
171/// wins (the pane never left); else the first neighbour that is still a shown pane, which is the nearest one
172/// since the list is ordered by nearness; else `Fallback`. "Beyond recognition" is exactly that last case: the
173/// tab is gone (the caller's check), or no recorded neighbour is a pane of it that is not a chip.
174pub(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
208/// The record for the blocks about to be torn out of `tab_id`, read from srv's tree. Call before they leave it.
209pub(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
220/// Keep `rec` on each of the blocks that left (whichever one a redock asks about finds it), so it survives a restart.
221pub(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
230/// Keep `rec` on the blocks that just left, or, when there is none to keep, drop any older one they carry.
231pub(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
238/// Drop the record from each of these blocks: the pane is docked again, by whatever path, or a new tear-off has
239/// nothing to remember and must not leave an older record to be found later.
240pub(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
252/// The record on `block_id` and where it resolves to now. `None`: no record, or its tab is gone or its workspace
253/// is open in no window (the pane would go where nobody sees it), which a caller treats as `Fallback`.
254pub(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
277/// Where a redock by the button goes: the origin's tab and workspace and how the pane is placed there, or, when
278/// nothing is recognisable, the tab the caller named and `Fallback`.
279pub(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
293/// Put `block_id` beside the neighbour `anchor` names, on its recorded side and with its recorded share. Falls
294/// back to the layout's next free place when that pane is gone by now (`place_block`).
295pub(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    /// `[a | b | c]` side by side, sizes 10, 20, 10.
343    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        // [a | [b / c / d] | e]: tearing off c has b and d beside it, then a and e around its column.
414        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}