Skip to main content

agentmux_srv_core/reducer/
pin.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pinning a pane to its window (`docs/specs/SPEC_PIN_TRANSFORM_FACILITY_2026_12_02.md` ยง9). A pin is a flag on a
5//! block in the workspace's `pins`: the block stays in its tab and in that tab's layout, so a pin or an unpin moves
6//! nothing. The pin follows its block from tab to tab inside the window, and goes when the block is no longer a pane
7//! of one of the window's tabs (closed, parked, moved or torn off to another window, or its tab closed or moved), or
8//! when its pane is left the only pane of its tab: `settle`, run after every command, is the one place that says so.
9
10use agentmux_common::ipc::Event;
11use agentmux_common::pin::{next_order, refuse_pin, REFUSE_ALONE, REFUSE_MAXIMIZED};
12use agentmux_common::PinRecord;
13
14use crate::backend::layout::find_leaf_containing_block;
15
16use crate::state::State;
17
18use super::invalid_command;
19
20/// Whether the pane that holds `block_id` is the only pane of its tab, by the tab's layout. False while the layout does
21/// not hold the block (a pane on its way into the tab).
22fn is_alone(state: &State, block_id: &str) -> bool {
23    let root = state.blocks.get(block_id).and_then(|b| state.tabs.get(&b.tab_id)).and_then(|t| t.rootnode.as_ref());
24    root.is_some_and(|r| r.children.is_empty() && find_leaf_containing_block(r, block_id).is_some())
25}
26
27/// Whether the pane that holds `block_id` is maximized in its tab.
28fn is_maximized(state: &State, block_id: &str) -> bool {
29    let Some(tab) = state.blocks.get(block_id).and_then(|b| state.tabs.get(&b.tab_id)) else { return false };
30    let leaf = tab.rootnode.as_ref().and_then(|r| find_leaf_containing_block(r, block_id));
31    leaf.is_some_and(|l| !tab.magnified_node_id.is_empty() && tab.magnified_node_id == l.id)
32}
33
34/// Drop every pin that no longer holds, and say so (one `PinsChanged` per workspace that lost one). A pin holds while
35/// its block is a pane of one of the workspace's tabs and that pane is not the only pane of its tab (drawn over the
36/// other tabs, a lone pane would cover each of them whole). Run after every command, so whichever one took the pane
37/// away or emptied the tab around it (a close, a park, a move, a tear-off, a closed or moved tab, a new layout), the
38/// rule is in one place.
39pub(super) fn settle(state: &mut State) -> Vec<Event> {
40    let holds = |state: &State, tab_ids: &[String], block_id: &str| {
41        state.blocks.get(block_id).is_some_and(|b| tab_ids.contains(&b.tab_id)) && !is_alone(state, block_id)
42    };
43    let stale: Vec<String> = state
44        .workspaces
45        .iter()
46        .filter(|(_, w)| w.pins.iter().any(|p| !holds(state, &w.tab_ids, &p.block_id)))
47        .map(|(id, _)| id.clone())
48        .collect();
49    let mut events = Vec::new();
50    for workspace_id in stale {
51        let tab_ids = state.workspaces[&workspace_id].tab_ids.clone();
52        let mut pins = state.workspaces[&workspace_id].pins.clone();
53        pins.retain(|p| holds(state, &tab_ids, &p.block_id));
54        state.workspaces.get_mut(&workspace_id).expect("listed above").pins = pins.clone();
55        let version = state.bump_version();
56        events.push(Event::PinsChanged { workspace_id, pins, version });
57    }
58    events
59}
60
61/// Run a pin command (`PinBlock` or `UnpinBlock`); any other command is refused.
62pub(super) fn handle(state: &mut State, cmd: agentmux_common::ipc::Command) -> Vec<Event> {
63    use agentmux_common::ipc::Command;
64    match cmd {
65        Command::PinBlock { workspace_id, block_id } => handle_pin_block(state, workspace_id, block_id),
66        Command::UnpinBlock { workspace_id, block_id } => handle_unpin_block(state, workspace_id, block_id),
67        other => invalid_command(state, format!("not a pin command: {other:?}")),
68    }
69}
70
71/// Add `block_id`'s pin. Refused when the block is not a pane of one of the workspace's tabs, is pinned already, the
72/// window has its one pin, or the pane is the only pane of its tab or maximized.
73fn handle_pin_block(state: &mut State, workspace_id: String, block_id: String) -> Vec<Event> {
74    let Some(workspace) = state.workspaces.get(&workspace_id) else {
75        return invalid_command(state, format!("PinBlock: workspace not found: {workspace_id}"));
76    };
77    match state.blocks.get(&block_id) {
78        None => return invalid_command(state, format!("PinBlock: block not found: {block_id}")),
79        Some(b) if !workspace.tab_ids.contains(&b.tab_id) => {
80            return invalid_command(state, format!("PinBlock: block {block_id} is not a pane of a tab of workspace {workspace_id}"));
81        }
82        Some(_) => {}
83    }
84    let by_place = if is_alone(state, &block_id) { Some(REFUSE_ALONE) } else { is_maximized(state, &block_id).then_some(REFUSE_MAXIMIZED) };
85    if let Some(reason) = refuse_pin(&workspace.pins, &block_id).or(by_place) {
86        return invalid_command(state, format!("PinBlock: {reason}"));
87    }
88    let order = next_order(&workspace.pins);
89    let workspace = state.workspaces.get_mut(&workspace_id).expect("checked above");
90    workspace.pins.push(PinRecord { block_id, order });
91    let pins = workspace.pins.clone();
92    let version = state.bump_version();
93    vec![Event::PinsChanged { workspace_id, pins, version }]
94}
95
96/// Drop `block_id`'s pin. Refused when the pane is not pinned.
97fn handle_unpin_block(state: &mut State, workspace_id: String, block_id: String) -> Vec<Event> {
98    let Some(workspace) = state.workspaces.get_mut(&workspace_id) else {
99        return invalid_command(state, format!("UnpinBlock: workspace not found: {workspace_id}"));
100    };
101    if !workspace.pins.iter().any(|p| p.block_id == block_id) {
102        return invalid_command(state, format!("UnpinBlock: that pane is not pinned: {block_id}"));
103    }
104    workspace.pins.retain(|p| p.block_id != block_id);
105    let pins = workspace.pins.clone();
106    let version = state.bump_version();
107    vec![Event::PinsChanged { workspace_id, pins, version }]
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use crate::reducer::test_support::*;
114    use crate::reducer::update;
115    use agentmux_common::ipc::Command;
116
117    /// A workspace "w" with tabs "t1" and "t2"; "t1" holds blocks "a", "b", "c"; "t2" holds "d". A second workspace
118    /// "x" with tab "x1".
119    fn seeded() -> State {
120        let mut state = State::default();
121        update(&mut state, Command::CreateWorkspace { name: "w".into() }, &ctx_with_id("w"));
122        update(&mut state, Command::CreateWorkspace { name: "x".into() }, &ctx_with_id("x"));
123        for (ws, t) in [("w", "t1"), ("w", "t2"), ("x", "x1")] {
124            update(&mut state, Command::CreateTab { workspace_id: ws.into(), name: t.into() }, &ctx_with_id(t));
125        }
126        for (tab, blocks) in [("t1", ["a", "b", "c"].as_slice()), ("t2", ["d"].as_slice())] {
127            for b in blocks {
128                update(&mut state, Command::CreateBlock { tab_id: tab.into(), meta: serde_json::Value::Null }, &ctx_with_id(b));
129            }
130        }
131        state
132    }
133
134    fn pin(state: &mut State, id: &str) -> Vec<Event> {
135        update(state, Command::PinBlock { workspace_id: "w".into(), block_id: id.into() }, &ctx(1))
136    }
137
138    fn unpin(state: &mut State, id: &str) -> Vec<Event> {
139        update(state, Command::UnpinBlock { workspace_id: "w".into(), block_id: id.into() }, &ctx(1))
140    }
141
142    fn pinned(state: &State) -> Vec<&str> {
143        state.workspaces["w"].pins.iter().map(|p| p.block_id.as_str()).collect()
144    }
145
146    #[test]
147    fn pinning_and_unpinning_move_nothing() {
148        let mut state = seeded();
149        let before = (state.tabs.clone(), state.blocks.clone());
150        let events = pin(&mut state, "a");
151        let [Event::PinsChanged { workspace_id, pins, .. }] = events.as_slice() else { panic!("{events:?}") };
152        assert_eq!((workspace_id.as_str(), pins.len()), ("w", 1));
153        assert_eq!(pinned(&state), vec!["a"]);
154        assert_eq!((state.tabs.clone(), state.blocks.clone()), before, "the block is where it was, in its tab's order");
155
156        let events = unpin(&mut state, "a");
157        assert!(matches!(events.as_slice(), [Event::PinsChanged { pins, .. }] if pins.is_empty()), "{events:?}");
158        assert_eq!((state.tabs.clone(), state.blocks.clone()), before);
159    }
160
161    #[test]
162    fn a_window_has_one_pin_and_a_pane_is_pinned_once() {
163        let mut state = seeded();
164        pin(&mut state, "a");
165        assert!(matches!(pin(&mut state, "a").as_slice(), [Event::Error { .. }]), "pinned already");
166        let second = pin(&mut state, "d");
167        let [Event::Error { message, .. }] = second.as_slice() else { panic!("{second:?}") };
168        assert!(message.contains(agentmux_common::pin::REFUSE_FULL), "{message}");
169        assert_eq!(pinned(&state), vec!["a"], "a refusal changes nothing");
170        unpin(&mut state, "a");
171        assert!(matches!(pin(&mut state, "d").as_slice(), [Event::PinsChanged { .. }]), "the freed room can be used");
172    }
173
174    #[test]
175    fn only_a_pane_of_the_workspaces_tabs_is_pinned() {
176        let mut state = seeded();
177        assert!(matches!(pin(&mut state, "gone").as_slice(), [Event::Error { .. }]));
178        update(&mut state, Command::CreateBlock { tab_id: "x1".into(), meta: serde_json::Value::Null }, &ctx_with_id("e"));
179        assert!(matches!(pin(&mut state, "e").as_slice(), [Event::Error { .. }]), "a pane of another window");
180        update(&mut state, Command::ParkBlock { tab_id: "t1".into(), block_id: "b".into() }, &ctx(1));
181        assert!(matches!(pin(&mut state, "b").as_slice(), [Event::Error { .. }]), "a parked block is in no tab");
182        let other = update(&mut state, Command::PinBlock { workspace_id: "nope".into(), block_id: "a".into() }, &ctx(1));
183        assert!(matches!(other.as_slice(), [Event::Error { .. }]));
184        assert!(pinned(&state).is_empty());
185    }
186
187    #[test]
188    fn unpinning_needs_a_pin() {
189        let mut state = seeded();
190        assert!(matches!(unpin(&mut state, "a").as_slice(), [Event::Error { .. }]), "never pinned");
191        pin(&mut state, "a");
192        assert!(matches!(unpin(&mut state, "b").as_slice(), [Event::Error { .. }]));
193        assert_eq!(pinned(&state), vec!["a"]);
194    }
195
196    #[test]
197    fn closing_or_parking_a_pinned_pane_takes_its_pin_with_it() {
198        for park in [false, true] {
199            let mut state = seeded();
200            pin(&mut state, "a");
201            let cmd = if park {
202                Command::ParkBlock { tab_id: "t1".into(), block_id: "a".into() }
203            } else {
204                Command::DeleteBlock { tab_id: "t1".into(), block_id: "a".into() }
205            };
206            let events = update(&mut state, cmd, &ctx(1));
207            let Some(Event::PinsChanged { pins, .. }) = events.last() else { panic!("{events:?}") };
208            assert!(pins.is_empty(), "park={park}");
209            assert!(matches!(pin(&mut state, "c").as_slice(), [Event::PinsChanged { .. }]), "the freed room can be used");
210        }
211    }
212
213    #[test]
214    fn closing_another_pane_leaves_the_pin() {
215        let mut state = seeded();
216        pin(&mut state, "a");
217        let events = update(&mut state, Command::DeleteBlock { tab_id: "t1".into(), block_id: "b".into() }, &ctx(1));
218        assert!(!events.iter().any(|e| matches!(e, Event::PinsChanged { .. })), "{events:?}");
219        assert_eq!(pinned(&state), vec!["a"]);
220    }
221
222    #[test]
223    fn a_command_that_changes_no_pin_says_nothing_of_pins() {
224        let mut state = seeded();
225        pin(&mut state, "a");
226        let events = update(&mut state, Command::Ping { nonce: 1 }, &ctx(1));
227        assert!(matches!(events.as_slice(), [Event::Pong { .. }]), "{events:?}");
228    }
229
230    #[test]
231    fn a_pin_follows_its_pane_to_another_tab_of_the_window_and_not_to_another_window() {
232        let mut state = seeded();
233        pin(&mut state, "a");
234        let moved = update(&mut state, Command::MoveBlock { block_id: "a".into(), src_tab_id: "t1".into(), dst_tab_id: "t2".into(), dst_index: 0 }, &ctx(1));
235        assert!(matches!(moved.as_slice(), [Event::BlockMoved { .. }]), "{moved:?}");
236        assert_eq!((state.blocks["a"].tab_id.as_str(), pinned(&state)), ("t2", vec!["a"]), "still pinned, in its new tab");
237
238        let left = update(&mut state, Command::MoveBlock { block_id: "a".into(), src_tab_id: "t2".into(), dst_tab_id: "x1".into(), dst_index: 0 }, &ctx(1));
239        assert!(matches!(left.as_slice(), [Event::BlockMoved { .. }, Event::PinsChanged { pins, .. }] if pins.is_empty()), "{left:?}");
240        assert_eq!(state.blocks["a"].tab_id, "x1");
241        assert!(pinned(&state).is_empty());
242    }
243
244    #[test]
245    fn closing_the_tab_of_a_pinned_pane_takes_its_pin() {
246        let mut state = seeded();
247        pin(&mut state, "d");
248        let events = update(&mut state, Command::DeleteTab { workspace_id: "w".into(), tab_id: "t2".into(), force: false }, &ctx(1));
249        assert!(events.iter().any(|e| matches!(e, Event::PinsChanged { pins, .. } if pins.is_empty())), "{events:?}");
250        assert!(pinned(&state).is_empty());
251    }
252
253    #[test]
254    fn a_tab_moved_to_another_window_leaves_its_pin_behind() {
255        let mut state = seeded();
256        pin(&mut state, "d");
257        let cmd = Command::MoveTab { tab_id: "t2".into(), src_workspace_id: "w".into(), dst_workspace_id: "x".into(), dst_index: 0, allow_empty_source: false };
258        let events = update(&mut state, cmd, &ctx(1));
259        assert!(matches!(events.first(), Some(Event::TabMoved { .. })), "{events:?}");
260        assert!(events.iter().any(|e| matches!(e, Event::PinsChanged { workspace_id, pins, .. } if workspace_id == "w" && pins.is_empty())), "{events:?}");
261        assert!(pinned(&state).is_empty());
262    }
263
264    fn leaf(id: &str) -> agentmux_common::LayoutNode {
265        let data = agentmux_common::LayoutNodeData { block_id: id.into(), ..Default::default() };
266        agentmux_common::LayoutNode { id: format!("n-{id}"), data: Some(data), ..Default::default() }
267    }
268
269    fn row(children: Vec<agentmux_common::LayoutNode>) -> agentmux_common::LayoutNode {
270        agentmux_common::LayoutNode { id: "root".into(), children, ..Default::default() }
271    }
272
273    #[test]
274    fn the_only_pane_of_a_tab_and_a_maximized_pane_are_not_pinned() {
275        let mut state = seeded();
276        state.tabs.get_mut("t2").unwrap().rootnode = Some(leaf("d"));
277        let alone = pin(&mut state, "d");
278        assert!(matches!(alone.as_slice(), [Event::Error { message, .. }] if message.contains(REFUSE_ALONE)), "{alone:?}");
279
280        let t1 = state.tabs.get_mut("t1").unwrap();
281        t1.rootnode = Some(row(vec![leaf("a"), leaf("b")]));
282        t1.magnified_node_id = "n-a".into();
283        let maximized = pin(&mut state, "a");
284        assert!(matches!(maximized.as_slice(), [Event::Error { message, .. }] if message.contains(REFUSE_MAXIMIZED)), "{maximized:?}");
285        assert!(matches!(pin(&mut state, "b").as_slice(), [Event::PinsChanged { .. }]), "its neighbour can be");
286    }
287
288    #[test]
289    fn a_pinned_pane_left_alone_in_its_tab_is_unpinned() {
290        let mut state = seeded();
291        state.tabs.get_mut("t1").unwrap().rootnode = Some(row(vec![leaf("a"), leaf("b")]));
292        pin(&mut state, "a");
293        // Its neighbour leaves the layout: the next command, whatever it is, finds the pane alone.
294        state.tabs.get_mut("t1").unwrap().rootnode = Some(leaf("a"));
295        let events = update(&mut state, Command::Ping { nonce: 1 }, &ctx(1));
296        assert!(matches!(events.last(), Some(Event::PinsChanged { pins, .. }) if pins.is_empty()), "{events:?}");
297        assert!(pinned(&state).is_empty());
298    }
299
300    #[test]
301    fn a_pinned_pane_on_its_way_into_a_tab_of_one_pane_stays_pinned() {
302        let mut state = seeded();
303        state.tabs.get_mut("t1").unwrap().rootnode = Some(row(vec![leaf("a"), leaf("b")]));
304        state.tabs.get_mut("t2").unwrap().rootnode = Some(leaf("d"));
305        pin(&mut state, "a");
306        // The block is in t2 before t2's layout holds it: t2's one leaf is another pane.
307        update(&mut state, Command::MoveBlock { block_id: "a".into(), src_tab_id: "t1".into(), dst_tab_id: "t2".into(), dst_index: 0 }, &ctx(1));
308        assert_eq!(pinned(&state), vec!["a"]);
309    }
310
311    #[test]
312    fn deleting_the_workspace_takes_its_pins() {
313        let mut state = seeded();
314        pin(&mut state, "a");
315        let events = update(&mut state, Command::DeleteWorkspace { workspace_id: "w".into(), force: true }, &ctx(1));
316        let Some(Event::WorkspaceDeleted { block_ids, .. }) = events.first() else { panic!("{events:?}") };
317        assert!(block_ids.contains(&"a".to_string()));
318        assert!(!state.workspaces.contains_key("w") && !state.blocks.contains_key("a"));
319    }
320}