Skip to main content

agentmux_srv/sagas/
redock_floating_pane.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// RedockFloatingPane saga — moves a block from a floating pane's
5// (single-block) workspace into an existing tab in a different
6// workspace. The inverse of `tear_off_block`.
7//
8// Used by the floating-pane re-dock flow (Phase 4a per
9// `docs/specs/SPEC_FLOATING_PANE_REDOCK_2026-05-27.md`): the user
10// drops a floater over another agentmux window's tile area; that
11// window's frontend computes the drop and calls this RPC.
12//
13// **Steps:**
14// 1. `MoveBlock { block_id, src=source_tab, dst=target_tab,
15//    dst_index: <position in target> }`
16//
17// After the move:
18// * Source workspace's tab is empty → frontend's empty-tab watcher
19//   (PR #1089) closes the floating window.
20// * Target tab's `blockids` now includes the moved block. The handler
21//   (`handle_redock_floating_pane`, tear_off.rs) then places it in the
22//   target tab's layout and takes it out of the source's; the saga itself
23//   does not touch LayoutState.
24//
25// **Compensation:** single-step saga, so no in-saga compensation
26// chain needed. If MoveBlock fails, the reducer's validation rejects
27// up-front and nothing has changed yet.
28
29use agentmux_common::ipc::Command;
30use serde_json::{json, Value};
31
32use super::{
33    alloc_saga_id, classify_run_saga_result, emit_saga_started, emit_terminal, run_saga, SagaCtx,
34};
35use crate::server::AppState;
36
37/// Run the RedockFloatingPane saga. On success, returns
38/// `{ "block_id": "...", "target_tab_id": "..." }`.
39///
40/// `dst_index` defaults to the end of the target tab's blockids if
41/// callers don't have a specific drop position (Phase 4a MVP). Phase
42/// 4b polish will let callers specify a drop position relative to a
43/// target leaf + direction (left/right/top/bottom/into).
44pub async fn run(
45    state: &AppState,
46    block_id: String,
47    source_tab_id: String,
48    source_workspace_id: String,
49    target_tab_id: String,
50    target_workspace_id: String,
51    dst_index: Option<u32>,
52) -> Result<Value, String> {
53    // Pre-conditions: block exists and belongs to source_tab; source
54    // tab is in source_workspace; target tab is in target_workspace;
55    // source != target (callers should already check, but a no-op
56    // re-dock is a programmer mistake worth surfacing).
57    let dst_index_resolved = {
58        let s = state.srv_state.lock().await;
59        match s.blocks.get(&block_id) {
60            None => {
61                return Err(format!(
62                    "RedockFloatingPane: block not found: {}",
63                    block_id
64                ));
65            }
66            Some(block) if block.tab_id != source_tab_id => {
67                return Err(format!(
68                    "RedockFloatingPane: block {} is in tab {}, not {}",
69                    block_id, block.tab_id, source_tab_id
70                ));
71            }
72            _ => {}
73        }
74        match s.tabs.get(&source_tab_id) {
75            None => {
76                return Err(format!(
77                    "RedockFloatingPane: source tab not found: {}",
78                    source_tab_id
79                ));
80            }
81            Some(tab) if tab.workspace_id != source_workspace_id => {
82                return Err(format!(
83                    "RedockFloatingPane: source tab {} is in workspace {}, not {}",
84                    source_tab_id, tab.workspace_id, source_workspace_id
85                ));
86            }
87            _ => {}
88        }
89        let target_tab = match s.tabs.get(&target_tab_id) {
90            None => {
91                return Err(format!(
92                    "RedockFloatingPane: target tab not found: {}",
93                    target_tab_id
94                ));
95            }
96            Some(tab) if tab.workspace_id != target_workspace_id => {
97                return Err(format!(
98                    "RedockFloatingPane: target tab {} is in workspace {}, not {}",
99                    target_tab_id, tab.workspace_id, target_workspace_id
100                ));
101            }
102            Some(tab) => tab,
103        };
104        if source_tab_id == target_tab_id {
105            return Err(
106                "RedockFloatingPane: source and target are the same tab — use MoveBlockToTab"
107                    .to_string(),
108            );
109        }
110        // Default insertion: append at the end of the target tab's
111        // blockids.
112        dst_index.unwrap_or(target_tab.block_ids.len() as u32)
113    };
114
115    let saga_id = alloc_saga_id(state);
116    if let Err(e) = emit_saga_started(
117        state,
118        saga_id,
119        "redock_floating_pane",
120        json!({
121            "block_id": &block_id,
122            "source_tab_id": &source_tab_id,
123            "target_tab_id": &target_tab_id,
124            "dst_index": dst_index_resolved,
125        }),
126    )
127    .await
128    {
129        return Err(e);
130    }
131    let ctx = SagaCtx::new(state, saga_id);
132    let result = run_saga(
133        "redock_floating_pane",
134        run_inner(
135            ctx,
136            block_id,
137            source_tab_id,
138            target_tab_id,
139            dst_index_resolved,
140        ),
141    )
142    .await;
143    emit_terminal(state, saga_id, classify_run_saga_result(&result)).await;
144    result
145}
146
147async fn run_inner(
148    ctx: SagaCtx<'_>,
149    block_id: String,
150    source_tab_id: String,
151    target_tab_id: String,
152    dst_index: u32,
153) -> Result<Value, String> {
154    ctx.dispatch(Command::MoveBlock {
155        block_id: block_id.clone(),
156        src_tab_id: source_tab_id,
157        dst_tab_id: target_tab_id.clone(),
158        dst_index,
159    })
160    .await
161    .map_err(|e| format!("RedockFloatingPane MoveBlock: {}", e))?;
162    // An agent's floating pane that is docked again no longer counts toward its limit of floating panes.
163    crate::server::pane_openers::set_floating(&block_id, false);
164
165    // A redocked pane is no longer "Always on top": drop the tack so a later
166    // tear-off starts untacked (SPEC_FLOATING_PANE_ALWAYS_ON_TOP_2026_09_27
167    // §6.3, owner decision §9.1). Best-effort — the pane is already
168    // redocked, and a leftover key only means the next tear-off re-applies
169    // the tack.
170    if let Err(e) = ctx
171        .dispatch(Command::UpdateBlockMeta {
172            block_id: block_id.clone(),
173            meta_patch: json!({ "pane:floating_ontop": null }),
174        })
175        .await
176    {
177        tracing::warn!(block_id = %block_id, "RedockFloatingPane: clearing pane:floating_ontop failed: {e}");
178    }
179
180    Ok(json!({
181        "block_id": block_id,
182        "target_tab_id": target_tab_id,
183        "dst_index": dst_index,
184    }))
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use crate::backend::obj::{Block, Tab};
191    use crate::server::tests::{dispatch_apply, test_state};
192    use agentmux_common::ipc::Event;
193
194    async fn seed_workspace_with_block(
195        state: &crate::server::AppState,
196        ws_name: &str,
197    ) -> (String, String, String) {
198        let ws_evs = dispatch_apply(
199            state,
200            Command::CreateWorkspace {
201                name: ws_name.into(),
202            },
203        )
204        .await;
205        let ws_id = ws_evs
206            .iter()
207            .find_map(|e| match e {
208                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
209                _ => None,
210            })
211            .unwrap();
212        let tab_evs = dispatch_apply(
213            state,
214            Command::CreateTab {
215                workspace_id: ws_id.clone(),
216                name: "t".into(),
217            },
218        )
219        .await;
220        let tab_id = tab_evs
221            .iter()
222            .find_map(|e| match e {
223                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
224                _ => None,
225            })
226            .unwrap();
227        let blk_evs = dispatch_apply(
228            state,
229            Command::CreateBlock {
230                tab_id: tab_id.clone(),
231                meta: Value::Null,
232            },
233        )
234        .await;
235        let block_id = blk_evs
236            .iter()
237            .find_map(|e| match e {
238                Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
239                _ => None,
240            })
241            .unwrap();
242        (ws_id, tab_id, block_id)
243    }
244
245    #[tokio::test]
246    async fn happy_path_moves_block_between_workspaces() {
247        let state = test_state();
248        let (src_ws, src_tab, block_id) = seed_workspace_with_block(&state, "src").await;
249        // Seed a destination workspace with one tab (no blocks yet).
250        let dst_ws_evs = dispatch_apply(
251            &state,
252            Command::CreateWorkspace { name: "dst".into() },
253        )
254        .await;
255        let dst_ws = dst_ws_evs
256            .iter()
257            .find_map(|e| match e {
258                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
259                _ => None,
260            })
261            .unwrap();
262        let dst_tab_evs = dispatch_apply(
263            &state,
264            Command::CreateTab {
265                workspace_id: dst_ws.clone(),
266                name: "dt".into(),
267            },
268        )
269        .await;
270        let dst_tab = dst_tab_evs
271            .iter()
272            .find_map(|e| match e {
273                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
274                _ => None,
275            })
276            .unwrap();
277
278        let agent = format!("redock-agent-{block_id}");
279        crate::server::pane_openers::record(&block_id, &agent, true);
280        assert_eq!(crate::server::pane_openers::floaters_of(&agent), vec![block_id.clone()]);
281
282        let result = run(
283            &state,
284            block_id.clone(),
285            src_tab.clone(),
286            src_ws.clone(),
287            dst_tab.clone(),
288            dst_ws.clone(),
289            None,
290        )
291        .await
292        .unwrap();
293        assert_eq!(result["block_id"], block_id);
294        assert_eq!(result["target_tab_id"], dst_tab);
295        // Docked again: it keeps its opener but no longer counts as one of the agent's floating panes.
296        assert!(crate::server::pane_openers::floaters_of(&agent).is_empty());
297        assert_eq!(crate::server::pane_openers::opener_of(&block_id).as_deref(), Some(agent.as_str()));
298        crate::server::pane_openers::forget(&block_id);
299
300        // Reducer: source tab is empty; target tab has the block.
301        let s = state.srv_state.lock().await;
302        assert!(s.tabs[&src_tab].block_ids.is_empty());
303        assert_eq!(s.tabs[&dst_tab].block_ids, vec![block_id.clone()]);
304        assert_eq!(s.blocks[&block_id].tab_id, dst_tab);
305
306        // SQLite: matches.
307        drop(s);
308        let dst_tab_obj = state.mstore.get::<Tab>(&dst_tab).unwrap().unwrap();
309        assert_eq!(dst_tab_obj.blockids, vec![block_id.clone()]);
310        let block = state.mstore.get::<Block>(&block_id).unwrap().unwrap();
311        assert_eq!(block.parentoref, format!("tab:{}", dst_tab));
312    }
313
314    #[tokio::test]
315    async fn redock_clears_the_always_on_top_tack_and_keeps_other_meta() {
316        let state = test_state();
317        let (src_ws, src_tab, block_id) = seed_workspace_with_block(&state, "src").await;
318        dispatch_apply(
319            &state,
320            Command::UpdateBlockMeta {
321                block_id: block_id.clone(),
322                meta_patch: serde_json::json!({ "pane:floating_ontop": true, "frame:hue": 200 }),
323            },
324        )
325        .await;
326        let dst_ws = dispatch_apply(&state, Command::CreateWorkspace { name: "dst".into() })
327            .await
328            .iter()
329            .find_map(|e| match e {
330                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
331                _ => None,
332            })
333            .unwrap();
334        let dst_tab = dispatch_apply(
335            &state,
336            Command::CreateTab { workspace_id: dst_ws.clone(), name: "dt".into() },
337        )
338        .await
339        .iter()
340        .find_map(|e| match e {
341            Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
342            _ => None,
343        })
344        .unwrap();
345
346        run(&state, block_id.clone(), src_tab, src_ws, dst_tab, dst_ws, None)
347            .await
348            .unwrap();
349
350        let block = state.mstore.get::<Block>(&block_id).unwrap().unwrap();
351        assert!(
352            !block.meta.contains_key("pane:floating_ontop"),
353            "redock must drop the tack: {:?}",
354            block.meta
355        );
356        assert_eq!(block.meta.get("frame:hue"), Some(&serde_json::json!(200)), "other meta is kept");
357    }
358
359    #[tokio::test]
360    async fn rejects_when_source_and_target_are_same_tab() {
361        let state = test_state();
362        let (ws, tab, block_id) = seed_workspace_with_block(&state, "w").await;
363        let err = run(
364            &state,
365            block_id,
366            tab.clone(),
367            ws.clone(),
368            tab,
369            ws,
370            None,
371        )
372        .await
373        .unwrap_err();
374        assert!(
375            err.contains("source and target are the same tab"),
376            "got: {}",
377            err
378        );
379    }
380
381    #[tokio::test]
382    async fn rejects_when_block_not_in_source_tab() {
383        let state = test_state();
384        let (ws, tab, _block_id) = seed_workspace_with_block(&state, "w").await;
385        let dst_ws_evs = dispatch_apply(
386            &state,
387            Command::CreateWorkspace { name: "dst".into() },
388        )
389        .await;
390        let dst_ws = dst_ws_evs
391            .iter()
392            .find_map(|e| match e {
393                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
394                _ => None,
395            })
396            .unwrap();
397        let dst_tab_evs = dispatch_apply(
398            &state,
399            Command::CreateTab {
400                workspace_id: dst_ws.clone(),
401                name: "dt".into(),
402            },
403        )
404        .await;
405        let dst_tab = dst_tab_evs
406            .iter()
407            .find_map(|e| match e {
408                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
409                _ => None,
410            })
411            .unwrap();
412        let err = run(
413            &state,
414            "ghost-block".into(),
415            tab,
416            ws,
417            dst_tab,
418            dst_ws,
419            None,
420        )
421        .await
422        .unwrap_err();
423        assert!(err.contains("block not found"), "got: {}", err);
424    }
425}