Skip to main content

agentmux_srv/server/app_api/
editor_pick.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which Editor pane an agent's open goes into, when a tab has several.
5//!
6//! The order is fixed, so the same layout always gives the same answer:
7//! 1. one the tab shows now (the front tab of its pane, not minimized, not behind a magnified pane);
8//! 2. the nearest to the pane that asked, by distance in the layout tree, with one after it (below or
9//!    to its right) before one before it;
10//! 3. the focused pane;
11//! 4. one that needs no switch of its pane's tab;
12//! 5. the first in layout order.
13
14use crate::backend::obj::LayoutState;
15use agentmux_common::LayoutNode;
16
17/// The Editor chosen, and a sentence for the log saying why.
18pub(super) struct Pick {
19    pub block_id: String,
20    pub why: &'static str,
21}
22
23/// The child indexes from `node` down to the pane holding `block_id` (in its stack or in front).
24fn path_to(node: &LayoutNode, block_id: &str) -> Option<Vec<usize>> {
25    if node.children.is_empty() {
26        let holds = node
27            .data
28            .as_ref()
29            .is_some_and(|d| d.block_id == block_id || d.block_stack.iter().any(|b| b == block_id));
30        return holds.then(Vec::new);
31    }
32    node.children.iter().enumerate().find_map(|(i, child)| {
33        let mut path = path_to(child, block_id)?;
34        path.insert(0, i);
35        Some(path)
36    })
37}
38
39/// Steps between two panes through their nearest common branch.
40fn tree_distance(a: &[usize], b: &[usize]) -> usize {
41    let shared = a.iter().zip(b).take_while(|(x, y)| x == y).count();
42    (a.len() - shared) + (b.len() - shared)
43}
44
45/// Whether showing `block_id` takes switching its pane to it: it is a background tab of a pane stack.
46pub(super) fn needs_activation(layout: &LayoutState, block_id: &str) -> bool {
47    let shown = super::shown_block_ids(layout);
48    !shown.iter().any(|s| s == block_id)
49        && layout
50            .rootnode
51            .as_ref()
52            .and_then(|root| crate::backend::layout::find_leaf_containing_block(root, block_id))
53            .and_then(|leaf| leaf.data.as_ref())
54            .is_some_and(|d| d.block_stack.len() > 1 && d.block_id != block_id)
55}
56
57/// The Editor of `editors` (in layout order) an open from the pane `caller` should go into.
58pub(super) fn choose(layout: &LayoutState, caller: Option<&str>, editors: &[String]) -> Option<Pick> {
59    let root = layout.rootnode.as_ref()?;
60    let shown = super::shown_block_ids(layout);
61    let caller_path = caller.and_then(|c| path_to(root, c));
62    let mut ranked: Vec<_> = editors
63        .iter()
64        .enumerate()
65        .map(|(order, id)| {
66            let path = path_to(root, id);
67            let on_screen = shown.contains(id);
68            let (distance, after) = match (&caller_path, &path) {
69                (Some(from), Some(to)) => (tree_distance(from, to), to > from),
70                _ => (usize::MAX, false),
71            };
72            let focused = !layout.focusednodeid.is_empty()
73                && crate::backend::layout::find_leaf_containing_block(root, id).is_some_and(|l| l.id == layout.focusednodeid);
74            let key = (!on_screen, distance, !after, !focused, needs_activation(layout, id), order);
75            (key, id, on_screen, editors.len())
76        })
77        .collect();
78    ranked.sort_by(|a, b| a.0.cmp(&b.0));
79    let (_, id, on_screen, count) = ranked.into_iter().next()?;
80    let on_screen_count = editors.iter().filter(|e| shown.contains(e)).count();
81    let why = match (on_screen, on_screen_count, count) {
82        (_, _, 1) => "the tab's only Editor pane",
83        (true, 1, _) => "the only Editor pane the tab shows",
84        (true, _, _) => "the Editor pane the tab shows nearest to the pane that asked",
85        (false, _, _) => "no Editor pane is on screen: the nearest one that is hidden",
86    };
87    Some(Pick { block_id: id.clone(), why })
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    fn leaf(id: &str, block: &str) -> LayoutNode {
95        LayoutNode {
96            id: id.into(),
97            data: Some(agentmux_common::LayoutNodeData { block_id: block.into(), ..Default::default() }),
98            ..Default::default()
99        }
100    }
101    fn stack(id: &str, front: &str, members: &[&str]) -> LayoutNode {
102        let mut node = leaf(id, front);
103        let data = node.data.as_mut().unwrap();
104        data.block_stack = members.iter().map(|m| m.to_string()).collect();
105        data.active_block_id = front.into();
106        node
107    }
108    fn group(id: &str, children: Vec<LayoutNode>) -> LayoutNode {
109        LayoutNode { id: id.into(), children, ..Default::default() }
110    }
111    fn layout(root: LayoutNode) -> LayoutState {
112        LayoutState { rootnode: Some(root), ..Default::default() }
113    }
114    fn names(ids: &[&str]) -> Vec<String> {
115        ids.iter().map(|s| s.to_string()).collect()
116    }
117    fn pick(layout: &LayoutState, caller: &str, editors: &[&str]) -> String {
118        choose(layout, Some(caller), &names(editors)).unwrap().block_id
119    }
120
121    /// The reported layout: the agent's pane bottom left with an empty Editor beside it, and an Editor
122    /// that comes first in layout order inside a pane group at the top right.
123    #[test]
124    fn the_editor_next_to_the_caller_wins_over_one_first_in_layout_order() {
125        let tree = group(
126            "root",
127            vec![
128                group("top", vec![leaf("t1", "kcont"), stack("grp", "ed-group", &["help", "ed-group"])]),
129                group("bottom", vec![leaf("agent", "agent"), leaf("free", "ed-free")]),
130            ],
131        );
132        let l = layout(tree);
133        assert_eq!(pick(&l, "agent", &["ed-group", "ed-free"]), "ed-free");
134    }
135
136    #[test]
137    fn an_editor_on_screen_wins_over_a_nearer_one_that_is_hidden() {
138        let mut hidden = leaf("hid", "ed-hidden");
139        hidden.minimized = true;
140        let l = layout(group("root", vec![leaf("agent", "agent"), hidden, leaf("far", "ed-far")]));
141        assert_eq!(pick(&l, "agent", &["ed-hidden", "ed-far"]), "ed-far");
142        // With none on screen, the nearest hidden one is chosen.
143        let mut a = leaf("a", "ed-a");
144        a.minimized = true;
145        let mut b = leaf("b", "ed-b");
146        b.minimized = true;
147        let l = layout(group("root", vec![a, leaf("agent", "agent"), b]));
148        assert_eq!(pick(&l, "agent", &["ed-a", "ed-b"]), "ed-b", "one after the caller is nearer first");
149    }
150
151    #[test]
152    fn at_equal_distance_the_one_below_or_to_the_right_comes_first() {
153        let l = layout(group("root", vec![leaf("before", "ed-before"), leaf("agent", "agent"), leaf("after", "ed-after")]));
154        assert_eq!(pick(&l, "agent", &["ed-before", "ed-after"]), "ed-after");
155    }
156
157    #[test]
158    fn then_the_focused_pane_then_layout_order() {
159        // Both before the caller and equally far from it.
160        let tree = group("root", vec![leaf("e1", "ed-1"), leaf("e2", "ed-2"), group("g", vec![leaf("agent", "agent"), leaf("x", "x")])]);
161        let mut l = layout(tree);
162        assert_eq!(pick(&l, "agent", &["ed-1", "ed-2"]), "ed-1", "layout order when nothing else decides");
163        l.focusednodeid = "e2".into();
164        assert_eq!(pick(&l, "agent", &["ed-1", "ed-2"]), "ed-2", "the focused pane");
165    }
166
167    #[test]
168    fn a_background_tab_is_the_last_resort_and_says_it_needs_switching() {
169        let l = layout(group("root", vec![leaf("agent", "agent"), stack("s", "term", &["term", "ed-back"])]));
170        assert!(needs_activation(&l, "ed-back"));
171        assert!(!needs_activation(&l, "term"));
172        assert_eq!(pick(&l, "agent", &["ed-back"]), "ed-back");
173    }
174
175    #[test]
176    fn the_reason_is_named() {
177        let l = layout(group("root", vec![leaf("agent", "agent"), leaf("e", "ed")]));
178        assert_eq!(choose(&l, Some("agent"), &names(&["ed"])).unwrap().why, "the tab's only Editor pane");
179        let l = layout(group("root", vec![leaf("agent", "agent"), leaf("e1", "ed-1"), leaf("e2", "ed-2")]));
180        assert_eq!(
181            choose(&l, Some("agent"), &names(&["ed-1", "ed-2"])).unwrap().why,
182            "the Editor pane the tab shows nearest to the pane that asked"
183        );
184        assert!(choose(&l, Some("agent"), &[]).is_none());
185    }
186}