Skip to main content

agentmux_srv/server/service/
pin.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `workspace` service handlers for pinning a pane to its window: `PinBlockToWindow` and `UnpinBlockFromWindow`
5//! (`docs/specs/SPEC_PIN_TRANSFORM_FACILITY_2026_12_02.md` ยง9). A pin is a flag: the pane stays in its tab and in that
6//! tab's layout, and the page draws it over the other tabs at the place it has in its own. So a pin, and an unpin in
7//! the pane's own tab, are one reducer command and change no layout. Unpinned in another tab, the pane moves into that
8//! tab: onto the edge it was on, at its own thickness.
9
10use agentmux_common::ipc::{Command, Event};
11
12use crate::backend::layout::place::{edge_band_of, frac_rect_of};
13use crate::backend::obj::*;
14use crate::backend::service::{self, WebCallType, WebReturnType};
15
16use super::super::AppState;
17use super::layout_helpers::queue_source_layout_delete;
18use super::layout_intents::Placement;
19use super::reducer_helpers::{dispatch_to_reducer, publish_events};
20
21/// Run a command through the reducer, store its events and publish them. Its refusal is the error.
22async fn run_command(state: &AppState, cmd: Command) -> Result<Vec<Event>, String> {
23    let events = dispatch_to_reducer(state, cmd).await;
24    if let Some(message) = events.iter().find_map(|e| match e {
25        Event::Error { message, .. } => Some(message.clone()),
26        _ => None,
27    }) {
28        return Err(message);
29    }
30    for ev in &events {
31        crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).map_err(|e| format!("pin: SQLite write failed: {e}"))?;
32    }
33    publish_events(state, &events);
34    Ok(events)
35}
36
37/// The tabs of the pane that holds `block_id` in tab `tab_id`'s layout, in order, and the one showing. A pane with no
38/// stack (or a block the tree does not hold) is just itself.
39async fn stack_in(state: &AppState, tab_id: &str, block_id: &str) -> (Vec<String>, String) {
40    let s = state.srv_state.lock().await;
41    let leaf = s.tabs.get(tab_id).and_then(|t| t.rootnode.as_ref()).and_then(|root| crate::backend::layout::find_leaf_containing_block(root, block_id));
42    match leaf.and_then(|n| n.data.as_ref()) {
43        Some(data) => {
44            let members = crate::backend::layout::leaf_members(data);
45            let active = if data.active_block_id.is_empty() { data.block_id.clone() } else { data.active_block_id.clone() };
46            (members, active)
47        }
48        None => (vec![block_id.to_string()], block_id.to_string()),
49    }
50}
51
52/// The workspace meta key the tear-off saga sets on the workspace of a pane torn into a window of its own: a floating
53/// window has one pane and no tabs to follow, so a pane of it is not pinnable.
54pub(crate) const FLOATING_WORKSPACE_META: &str = "pane:floating";
55
56/// Mark `workspace_id`, the workspace of a window a pane was just torn into, as a floating window's. Not a step of the
57/// tear-off saga: the saga's recovery has no inverse for a meta patch, and deleting the workspace removes the mark anyway.
58pub(crate) async fn mark_floating_window(state: &AppState, workspace_id: &str) {
59    let cmd = Command::UpdateWorkspaceMeta { workspace_id: workspace_id.into(), meta_patch: serde_json::json!({ FLOATING_WORKSPACE_META: true }) };
60    if let Err(e) = run_command(state, cmd).await {
61        tracing::warn!(workspace_id, "TearOffBlock: marking the floating window failed: {e}");
62    }
63}
64
65/// Whether `block_id` is a pane of a floating window: the workspace of its tab carries the tear-off's mark.
66pub(crate) async fn in_floating_window(state: &AppState, block_id: &str) -> bool {
67    let ws = {
68        let s = state.srv_state.lock().await;
69        s.blocks.get(block_id).and_then(|b| s.tabs.get(&b.tab_id)).map(|t| t.workspace_id.clone())
70    };
71    ws.and_then(|ws| state.mstore.get::<Workspace>(&ws).ok().flatten())
72        .is_some_and(|w| w.meta.get(FLOATING_WORKSPACE_META).and_then(|v| v.as_bool()) == Some(true))
73}
74
75/// The pin of the pane that holds `block_id` in workspace `workspace_id`: the pin of `block_id` itself, or of the tab
76/// of its stack that has one (only one tab of a pinned pane does).
77pub(crate) fn pin_holding(s: &crate::state::State, workspace_id: &str, block_id: &str) -> Option<agentmux_common::PinRecord> {
78    let ws = s.workspaces.get(workspace_id)?;
79    if let Some(p) = ws.pins.iter().find(|p| p.block_id == block_id) {
80        return Some(p.clone());
81    }
82    let root = s.tabs.get(&s.blocks.get(block_id)?.tab_id)?.rootnode.as_ref()?;
83    let members = crate::backend::layout::leaf_members(crate::backend::layout::find_leaf_containing_block(root, block_id)?.data.as_ref()?);
84    ws.pins.iter().find(|p| members.contains(&p.block_id)).cloned()
85}
86
87/// Where the pane that holds `block_id` sits in its own tab, as fractions of the tab's area: the place a pinned pane
88/// is drawn at in every tab. None when its tab's layout does not hold it.
89pub(crate) fn pane_rect(s: &crate::state::State, block_id: &str) -> Option<crate::backend::layout::place::FracRect> {
90    let root = s.tabs.get(&s.blocks.get(block_id)?.tab_id)?.rootnode.as_ref()?;
91    frac_rect_of(root, &crate::backend::layout::find_leaf_containing_block(root, block_id)?.id)
92}
93
94/// Pin the pane that holds `block_id` to the window of workspace `workspace_id`. Nothing moves. Refused for a floating
95/// pane, and by the reducer's rules.
96pub(crate) async fn pin_block(state: &AppState, workspace_id: &str, block_id: &str) -> Result<(), String> {
97    if in_floating_window(state, block_id).await {
98        return Err("A floating pane is its own window and cannot be pinned: dock it into a tab first.".into());
99    }
100    if pin_holding(&*state.srv_state.lock().await, workspace_id, block_id).is_some() {
101        return Err("that pane is already pinned".into());
102    }
103    // The reducer owns the rules (one pin a window, not the only pane of its tab, not a maximized pane): its refusal is
104    // said as it is, without the command's name.
105    let cmd = Command::PinBlock { workspace_id: workspace_id.into(), block_id: block_id.into() };
106    run_command(state, cmd).await.map_err(|e| e.strip_prefix("PinBlock: ").unwrap_or(&e).to_string())?;
107    Ok(())
108}
109
110/// The rest of a stack, in order, as tabs of the pane `stack[0]` that is already in `tab_id`'s layout; `active` shows.
111async fn stack_into_tab(state: &AppState, tab_id: &str, stack: &[String], active: &str) -> Result<(), String> {
112    let Some(first) = stack.first() else { return Ok(()) };
113    for member in &stack[1..] {
114        super::tear_off::redock_as_tab(state, tab_id, member, first, false).await?;
115    }
116    if active != first.as_str() && stack.iter().any(|m| m == active) {
117        super::tear_off::redock_as_tab(state, tab_id, active, first, true).await?;
118    }
119    Ok(())
120}
121
122/// What a failed `move_pane` puts back: where each block sat in its tab's list, and each tab's layout row.
123struct Undo {
124    /// The blocks a move was tried on, with the place each had in the source tab's block list. A block is listed before its
125    /// move runs: a move the reducer applied but the store refused is moved back too, and one the reducer refused is not
126    /// in the other tab, so its move back is a refusal that changes nothing.
127    moved: Vec<(String, u32)>,
128    layouts: Vec<(String, LayoutState)>,
129    /// Every block has moved, so the layouts may have changed too.
130    layouts_touched: bool,
131    /// The window's pins as they were: placing a pane alone in an empty tab settles its pin away, and a failed move
132    /// brings the pane back to its own tab, where it stays pinned.
133    pins: Option<(String, Vec<agentmux_common::PinRecord>)>,
134}
135
136/// A tab's layout row as it is now (none when the tab has none).
137fn layout_row(state: &AppState, tab_id: &str) -> Option<(String, LayoutState)> {
138    let tab = state.mstore.get::<Tab>(tab_id).ok().flatten()?;
139    let row = state.mstore.get::<LayoutState>(&tab.layoutstate).ok().flatten()?;
140    Some((tab_id.to_string(), row))
141}
142
143/// Move the pane `stack` (its tabs, in order; `active` shows) from tab `src` into tab `dst`, as a band on `band`'s
144/// edge at its thickness: the blocks first, then out of the one layout and into the other. All or nothing: a step
145/// that fails puts back the blocks already moved, at their places in the source tab, and both tabs' layouts.
146async fn move_pane(state: &AppState, (src, dst): (&str, &str), (stack, active): (&[String], &str), band: Option<(agentmux_common::LayoutEdge, f64)>) -> Result<(), String> {
147    let places: Vec<u32> = {
148        let s = state.srv_state.lock().await;
149        let listed = s.tabs.get(src).map(|t| t.block_ids.clone()).unwrap_or_default();
150        stack.iter().map(|m| listed.iter().position(|b| b == m).unwrap_or(listed.len()) as u32).collect()
151    };
152    let pins = {
153        let s = state.srv_state.lock().await;
154        s.tabs.get(src).and_then(|t| s.workspaces.get(&t.workspace_id).map(|w| (t.workspace_id.clone(), w.pins.clone())))
155    };
156    let mut undo = Undo { moved: Vec::new(), layouts: [src, dst].iter().filter_map(|t| layout_row(state, t)).collect(), layouts_touched: false, pins };
157    let result = move_pane_steps(state, (src, dst), (stack, active), band, (&places, &mut undo)).await;
158    if result.is_err() {
159        put_pane_back(state, (src, dst), undo).await;
160    }
161    result
162}
163
164async fn move_pane_steps(
165    state: &AppState,
166    (src, dst): (&str, &str),
167    (stack, active): (&[String], &str),
168    band: Option<(agentmux_common::LayoutEdge, f64)>,
169    (places, undo): (&[u32], &mut Undo),
170) -> Result<(), String> {
171    for (member, place) in stack.iter().zip(places) {
172        undo.moved.push((member.clone(), *place));
173        run_command(state, Command::MoveBlock { block_id: member.clone(), src_tab_id: src.into(), dst_tab_id: dst.into(), dst_index: u32::MAX }).await?;
174    }
175    undo.layouts_touched = true;
176    for member in stack {
177        queue_source_layout_delete(state, src, member).await?;
178    }
179    super::layout_intents::place_block(state, dst, &stack[0], Placement::Append { focused: true }).await?;
180    stack_into_tab(state, dst, stack, active).await?;
181    // A tab with no other pane refuses the edge (the pane is the whole tab), which is already where it should be.
182    if let Some((edge, size)) = band {
183        super::layout_intents::move_block_to_edge(state, dst, &stack[0], (edge, Some(size))).await?;
184    }
185    Ok(())
186}
187
188/// Undo a `move_pane` that failed: each moved block goes back to its place in `src` (the earliest place first, so each
189/// lands where it was), then, when the layouts were reached, both layouts are set back as they were. Best effort: the
190/// caller is already returning the error that started it, and tells the windows what is left (`pin_updates`).
191async fn put_pane_back(state: &AppState, (src, dst): (&str, &str), undo: Undo) {
192    let mut moved = undo.moved;
193    moved.sort_by_key(|(_, place)| *place);
194    for (block_id, place) in moved {
195        let back = Command::MoveBlock { block_id, src_tab_id: dst.into(), dst_tab_id: src.into(), dst_index: place };
196        super::reducer_helpers::compensate_via_reducer(state, back, &state.mstore).await;
197    }
198    if !undo.layouts_touched {
199        return;
200    }
201    for (tab_id, old) in undo.layouts {
202        let slices = agentmux_common::LayoutClientSlices {
203            focused_node_id: old.focusednodeid.clone(),
204            magnified_node_id: old.magnifiednodeid.clone(),
205            pending_backend_actions: old.pendingbackendactions.as_ref().and_then(|v| serde_json::to_value(v).ok()),
206        };
207        let set = Command::LayoutSetTree { tab_id, new_tree: old.rootnode.clone(), correlation_id: String::new(), slices: Some(slices) };
208        super::reducer_helpers::compensate_via_reducer(state, set, &state.mstore).await;
209    }
210    put_pins_back(state, undo.pins).await;
211}
212
213/// Pin again each pane that was pinned and no longer is: the reducer unpinned it when it was placed alone in an empty tab.
214/// Run once the pane is back in its own tab (the reducer refuses a pin on the only pane of a tab, so before that it would be refused).
215async fn put_pins_back(state: &AppState, pins: Option<(String, Vec<agentmux_common::PinRecord>)>) {
216    let Some((workspace_id, before)) = pins else { return };
217    let now = state.srv_state.lock().await.workspaces.get(&workspace_id).map(|w| w.pins.clone()).unwrap_or_default();
218    for pin in before.iter().filter(|p| !now.iter().any(|n| n.block_id == p.block_id)) {
219        let again = Command::PinBlock { workspace_id: workspace_id.clone(), block_id: pin.block_id.clone() };
220        super::reducer_helpers::compensate_via_reducer(state, again, &state.mstore).await;
221    }
222}
223
224/// Unpin the pane that holds `block_id`. In its own tab (or with no `dst_tab_id`) only the pin goes. In another tab,
225/// the tab that is showing, the pane and all of its stack of pane tabs become a pane of that tab first, on the edge it
226/// was on; its own tab keeps its other panes.
227pub(crate) async fn unpin_block(state: &AppState, workspace_id: &str, block_id: &str, dst_tab_id: &str) -> Result<(), String> {
228    let (pin, home, band) = {
229        let s = state.srv_state.lock().await;
230        let pin = pin_holding(&s, workspace_id, block_id).ok_or_else(|| format!("that pane is not pinned: {block_id}"))?;
231        let home = s.blocks.get(&pin.block_id).map(|b| b.tab_id.clone()).unwrap_or_default();
232        if !dst_tab_id.is_empty() && dst_tab_id != home && !s.workspaces.get(workspace_id).is_some_and(|w| w.tab_ids.iter().any(|t| t == dst_tab_id)) {
233            return Err(format!("tab {dst_tab_id} is not a tab of this window"));
234        }
235        (pin.clone(), home, pane_rect(&s, &pin.block_id).map(edge_band_of))
236    };
237    if !dst_tab_id.is_empty() && dst_tab_id != home {
238        let (stack, active) = stack_in(state, &home, &pin.block_id).await;
239        if let Err(e) = move_pane(state, (&home, dst_tab_id), (&stack, &active), band).await {
240            tracing::error!(dst_tab = %dst_tab_id, "UnpinBlockFromWindow: moving the pane failed; it stays pinned: {e}");
241            // The windows saw the steps that did succeed: tell them the tabs and layouts as they are put back.
242            pin_updates(state, workspace_id, &[&home, dst_tab_id]);
243            return Err(format!("unpin failed: {e}"));
244        }
245    }
246    // A pane that came into an empty tab is alone there, and the reducer has unpinned it already.
247    let still = state.srv_state.lock().await.workspaces.get(workspace_id).is_some_and(|w| w.pins.iter().any(|p| p.block_id == pin.block_id));
248    if still {
249        run_command(state, Command::UnpinBlock { workspace_id: workspace_id.into(), block_id: pin.block_id }).await?;
250    }
251    Ok(())
252}
253
254/// The object updates a pin change owes the renderers: the tabs and their layouts (layouts first, as
255/// `tear_off::redock_updates` explains), then the workspace.
256fn pin_updates(state: &AppState, workspace_id: &str, tab_ids: &[&str]) -> Vec<MuxObjUpdate> {
257    let store = &state.mstore;
258    let mut updates = Vec::new();
259    for tab_id in tab_ids {
260        let Ok(tab) = store.must_get::<Tab>(tab_id) else { continue };
261        if let Ok(layout) = store.must_get::<LayoutState>(&tab.layoutstate) {
262            updates.push(MuxObjUpdate {
263                updatetype: "update".into(),
264                otype: OTYPE_LAYOUT.to_string(),
265                oid: tab.layoutstate.clone(),
266                obj: Some(mux_obj_to_value(&layout)),
267            });
268        }
269        updates.push(MuxObjUpdate { updatetype: "update".into(), otype: OTYPE_TAB.to_string(), oid: tab_id.to_string(), obj: Some(mux_obj_to_value(&tab)) });
270    }
271    if let Ok(ws) = store.must_get::<Workspace>(workspace_id) {
272        updates.push(MuxObjUpdate { updatetype: "update".into(), otype: OTYPE_WORKSPACE.to_string(), oid: workspace_id.to_string(), obj: Some(mux_obj_to_value(&ws)) });
273    }
274    state.event_bus.broadcast_mux_obj_updates(&updates);
275    updates
276}
277
278/// `PinBlockToWindow(workspaceId, blockId)`.
279pub(crate) async fn handle_pin_block_to_window(state: &AppState, call: &WebCallType) -> WebReturnType {
280    let args = &call.args;
281    let parsed = (|| -> Result<(String, String), String> { Ok((service::get_arg(args, 0)?, service::get_arg(args, 1)?)) })();
282    let (ws_id, block_id) = match parsed {
283        Ok(v) => v,
284        Err(e) => return WebReturnType::error(e),
285    };
286    tracing::info!(ws_id = %ws_id, block_id = %block_id, "[pin:svc] PinBlockToWindow");
287    if let Err(e) = pin_block(state, &ws_id, &block_id).await {
288        return WebReturnType::error(e);
289    }
290    WebReturnType::success_with_updates(pin_updates(state, &ws_id, &[]))
291}
292
293/// `UnpinBlockFromWindow(workspaceId, blockId, showingTabId)`: the tab that is showing takes the pane when it is not
294/// the pane's own.
295pub(crate) async fn handle_unpin_block_from_window(state: &AppState, call: &WebCallType) -> WebReturnType {
296    let args = &call.args;
297    let parsed = (|| -> Result<(String, String, String), String> { Ok((service::get_arg(args, 0)?, service::get_arg(args, 1)?, service::get_arg(args, 2)?)) })();
298    let (ws_id, block_id, dst_tab_id) = match parsed {
299        Ok(v) => v,
300        Err(e) => return WebReturnType::error(e),
301    };
302    tracing::info!(ws_id = %ws_id, block_id = %block_id, dst_tab = %dst_tab_id, "[pin:svc] UnpinBlockFromWindow");
303    let home = state.srv_state.lock().await.blocks.get(&block_id).map(|b| b.tab_id.clone()).unwrap_or_default();
304    if let Err(e) = unpin_block(state, &ws_id, &block_id, &dst_tab_id).await {
305        return WebReturnType::error(e);
306    }
307    let touched: Vec<&str> = if dst_tab_id.is_empty() || dst_tab_id == home { Vec::new() } else { vec![home.as_str(), dst_tab_id.as_str()] };
308    WebReturnType::success_with_updates(pin_updates(state, &ws_id, &touched))
309}
310
311#[cfg(test)]
312#[path = "pin_tests.rs"]
313mod tests;