Skip to main content

agentmux_srv/sagas/
tear_off_block.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Phase E.5.5 — TearOffBlock saga.
5//
6// Migrates the reducer-state portion of `wcore::tear_off_block` to
7// a reducer-driven multi-step. The original wcore function does
8// substantial layout work (rebuilds the new tab's `LayoutState`
9// rootnode, queues a layout-delete action on the source
10// tab's pendingbackendactions) — that's E.4 territory and stays
11// wcore-direct in the RPC handler that wraps this saga. The
12// reducer/SQLite portion is what fixes the smoke regression
13// (the new workspace was invisible to the reducer because wcore
14// bypassed it).
15//
16// **Steps:**
17// 1. `CreateWorkspace { name: "" }`
18// 2. `CreateTab { workspace_id: new_ws_id, name: "" }`
19// 3. `MoveBlock { block_id, src=source_tab, dst=new_tab, dst_index: 0 }`
20//    — then one more `MoveBlock` per other member when a whole pane (its
21//    full tab stack) is torn off, in stack order, after the visible one so
22//    that the new tab's `blockids[0]` is the visible block.
23//
24// Auto-close-source-tab and layout setup are NOT here — see the
25// RPC handler in `service.rs` for those steps.
26//
27// **Compensation:**
28// * Step 3 fails after step 1+2 → `DeleteWorkspace { new_ws_id }`
29//   (cascades through tabs to blocks; no blocks landed in the new
30//   tab at this point). When the failing move is not the first, the
31//   members already moved go back to the source tab first, or the
32//   cascade would delete them.
33// * Step 2 fails after step 1 → `DeleteWorkspace { new_ws_id }`.
34// * Step 1 fails → nothing to compensate.
35
36use agentmux_common::ipc::{Command, Event};
37use serde_json::{json, Value};
38
39use super::{
40    alloc_saga_id, classify_run_saga_result, emit_saga_started, emit_terminal, run_saga, SagaCtx,
41};
42use crate::server::AppState;
43
44/// Run the TearOffBlock saga for ONE block. On success, returns
45/// `{"new_workspace_id": "...", "new_tab_id": "..."}`.
46pub async fn run(
47    state: &AppState,
48    block_id: String,
49    source_tab_id: String,
50    source_workspace_id: String,
51) -> Result<Value, String> {
52    run_stack(state, block_id, Vec::new(), source_tab_id, source_workspace_id).await
53}
54
55/// The blocks a tear-off moves, in the order they move: `block_id` (the
56/// visible tab) first, then the other `members` in their given order. Empty
57/// or without `block_id` in it, `members` means just `block_id`; repeats are
58/// dropped.
59pub(crate) fn tear_off_order(block_id: &str, members: &[String]) -> Vec<String> {
60    let mut order = vec![block_id.to_string()];
61    if members.iter().any(|m| m == block_id) {
62        for m in members {
63            if !order.contains(m) {
64                order.push(m.clone());
65            }
66        }
67    }
68    order
69}
70
71/// Run the TearOffBlock saga for a whole pane: `members` is its tab stack in
72/// order, `block_id` the visible one (see [`tear_off_order`]). Same return
73/// value as [`run`].
74pub async fn run_stack(
75    state: &AppState,
76    block_id: String,
77    members: Vec<String>,
78    source_tab_id: String,
79    source_workspace_id: String,
80) -> Result<Value, String> {
81    let order = tear_off_order(&block_id, &members);
82    // Pre-condition: block exists and belongs to source_tab; source
83    // tab is in source_workspace. Reducer would catch the structural
84    // mismatch via MoveBlock validation, but check up-front so we
85    // don't allocate a workspace + tab and then have to compensate.
86    {
87        let s = state.srv_state.lock().await;
88        // R3 diagnostic (#1681): a tear-off that references a workspace/tab/block
89        // this srv never created points at a frontend↔backend desync (a window
90        // bootstrapped a workspace that was never persisted), NOT a simple
91        // structural mismatch. The pre-condition used to reject SILENTLY (no log
92        // line — only an http-perf 0.05ms blip), which is why the 2nd-window
93        // tear-off failure was so hard to attribute. Log the full state context
94        // at ERROR on every rejection so a single repro is conclusive: does the
95        // source workspace exist in srv at all?
96        let reject = |reason: &str, s: &crate::state::State| {
97            tracing::error!(
98                target: "dnd:svc",
99                reason = %reason,
100                block_id = %block_id,
101                source_tab_id = %source_tab_id,
102                source_workspace_id = %source_workspace_id,
103                source_ws_exists = s.workspaces.contains_key(&source_workspace_id),
104                source_tab_exists = s.tabs.contains_key(&source_tab_id),
105                block_exists = s.blocks.contains_key(&block_id),
106                known_workspaces = s.workspaces.len(),
107                known_tabs = s.tabs.len(),
108                known_blocks = s.blocks.len(),
109                "[dnd:svc] TearOffBlock REJECTED — possible frontend/backend workspace desync"
110            );
111        };
112        for member in &order {
113            match s.blocks.get(member) {
114                None => {
115                    reject("block_not_found", &s);
116                    return Err(format!("TearOffBlock: block not found: {}", member));
117                }
118                Some(block) if block.tab_id != source_tab_id => {
119                    reject("block_in_other_tab", &s);
120                    return Err(format!(
121                        "TearOffBlock: block {} is in tab {}, not {}",
122                        member, block.tab_id, source_tab_id
123                    ));
124                }
125                _ => {}
126            }
127        }
128        match s.tabs.get(&source_tab_id) {
129            None => {
130                reject("source_tab_not_found", &s);
131                return Err(format!(
132                    "TearOffBlock: source tab not found: {}",
133                    source_tab_id
134                ));
135            }
136            Some(tab) if tab.workspace_id != source_workspace_id => {
137                reject("tab_in_other_workspace", &s);
138                return Err(format!(
139                    "TearOffBlock: tab {} is in workspace {}, not {}",
140                    source_tab_id, tab.workspace_id, source_workspace_id
141                ));
142            }
143            _ => {}
144        }
145    }
146
147    let saga_id = alloc_saga_id(state);
148    if let Err(e) = emit_saga_started(
149        state,
150        saga_id,
151        "tear_off_block",
152        serde_json::json!({
153            "block_id": &block_id,
154            "members": &order,
155            "source_tab_id": &source_tab_id,
156        }),
157    )
158    .await
159    {
160        return Err(e);
161    }
162    let ctx = SagaCtx::new(state, saga_id);
163    let result = run_saga("tear_off_block", run_inner(ctx, order, source_tab_id)).await;
164    emit_terminal(state, saga_id, classify_run_saga_result(&result)).await;
165    result
166}
167
168async fn run_inner(
169    ctx: SagaCtx<'_>,
170    order: Vec<String>,
171    source_tab_id: String,
172) -> Result<Value, String> {
173    // Step 1: new workspace.
174    let create_ws_events = ctx
175        .dispatch(Command::CreateWorkspace {
176            name: String::new(),
177        })
178        .await
179        .map_err(|e| format!("TearOffBlock step 1 (CreateWorkspace): {}", e))?;
180    let new_workspace_id = create_ws_events
181        .iter()
182        .find_map(|e| match e {
183            Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
184            _ => None,
185        })
186        .ok_or_else(|| {
187            "TearOffBlock: CreateWorkspace did not emit WorkspaceCreated".to_string()
188        })?;
189
190    // Step 2: new tab in the new workspace.
191    let create_tab_events = match ctx
192        .dispatch(Command::CreateTab {
193            workspace_id: new_workspace_id.clone(),
194            name: String::new(),
195        })
196        .await
197    {
198        Ok(evs) => evs,
199        Err(reason) => {
200            // `force: false` — internal compensation (Step 5 PR 2).
201            ctx.compensate(Command::DeleteWorkspace {
202                workspace_id: new_workspace_id.clone(),
203                force: false,
204            })
205            .await;
206            return Err(format!("TearOffBlock step 2 (CreateTab): {}", reason));
207        }
208    };
209    let new_tab_id = create_tab_events
210        .iter()
211        .find_map(|e| match e {
212            Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
213            _ => None,
214        })
215        .ok_or_else(|| {
216            "TearOffBlock: CreateTab did not emit TabCreated".to_string()
217        })?;
218
219    // Step 3: move the blocks, the visible one first (so it is the new tab's
220    // `blockids[0]`), the rest after it in stack order.
221    for (i, member) in order.iter().enumerate() {
222        if let Err(reason) = ctx
223            .dispatch(Command::MoveBlock {
224                block_id: member.clone(),
225                src_tab_id: source_tab_id.clone(),
226                dst_tab_id: new_tab_id.clone(),
227                dst_index: i as u32,
228            })
229            .await
230        {
231            // Put the members that already moved back where they were, or
232            // deleting the workspace would delete them with it.
233            for moved in order[..i].iter().rev() {
234                ctx.compensate(Command::MoveBlock {
235                    block_id: moved.clone(),
236                    src_tab_id: new_tab_id.clone(),
237                    dst_tab_id: source_tab_id.clone(),
238                    dst_index: u32::MAX,
239                })
240                .await;
241            }
242            // Compensate: delete the workspace (cascades the empty tab).
243            // `force: false` — internal compensation (Step 5 PR 2).
244            ctx.compensate(Command::DeleteWorkspace {
245                workspace_id: new_workspace_id.clone(),
246                force: false,
247            })
248            .await;
249            return Err(format!("TearOffBlock step 3 (MoveBlock {}): {}", member, reason));
250        }
251    }
252
253    Ok(json!({
254        "new_workspace_id": new_workspace_id,
255        "new_tab_id": new_tab_id,
256    }))
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262    use crate::backend::obj::{Block, Tab};
263    use crate::server::tests::{dispatch_apply, test_state};
264
265    #[tokio::test]
266    async fn happy_path_creates_workspace_tab_and_moves_block() {
267        let state = test_state();
268        // Seed: workspace with one tab containing a block.
269        let ws_evs = dispatch_apply(
270            &state,
271            agentmux_common::ipc::Command::CreateWorkspace { name: "src".into() },
272        )
273        .await;
274        let ws_id = ws_evs
275            .iter()
276            .find_map(|e| match e {
277                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
278                _ => None,
279            })
280            .unwrap();
281        let tab_evs = dispatch_apply(
282            &state,
283            agentmux_common::ipc::Command::CreateTab {
284                workspace_id: ws_id.clone(),
285                name: "t".into(),
286            },
287        )
288        .await;
289        let tab_id = tab_evs
290            .iter()
291            .find_map(|e| match e {
292                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
293                _ => None,
294            })
295            .unwrap();
296        let blk_evs = dispatch_apply(
297            &state,
298            agentmux_common::ipc::Command::CreateBlock {
299                tab_id: tab_id.clone(),
300                meta: serde_json::Value::Null,
301            },
302        )
303        .await;
304        let block_id = blk_evs
305            .iter()
306            .find_map(|e| match e {
307                Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
308                _ => None,
309            })
310            .unwrap();
311
312        let result = run(&state, block_id.clone(), tab_id.clone(), ws_id.clone())
313            .await
314            .unwrap();
315        let new_ws_id = result["new_workspace_id"].as_str().unwrap();
316        let new_tab_id = result["new_tab_id"].as_str().unwrap();
317
318        // Reducer: source tab has no blocks; new tab has the block.
319        let s = state.srv_state.lock().await;
320        assert!(s.tabs[&tab_id].block_ids.is_empty());
321        assert_eq!(
322            s.tabs[new_tab_id].block_ids,
323            vec![block_id.clone()],
324            "block should be in new tab"
325        );
326        assert_eq!(s.blocks[&block_id].tab_id, new_tab_id);
327        assert_eq!(s.workspaces[new_ws_id].tab_ids, vec![new_tab_id.to_string()]);
328
329        // SQLite: matches.
330        drop(s);
331        let new_tab = state.mstore.get::<Tab>(new_tab_id).unwrap().unwrap();
332        assert_eq!(new_tab.blockids, vec![block_id.clone()]);
333        let block = state.mstore.get::<Block>(&block_id).unwrap().unwrap();
334        assert_eq!(block.parentoref, format!("tab:{}", new_tab_id));
335    }
336
337    #[tokio::test]
338    async fn rejects_when_block_not_in_source_tab() {
339        let state = test_state();
340        let ws_evs = dispatch_apply(
341            &state,
342            agentmux_common::ipc::Command::CreateWorkspace { name: "w".into() },
343        )
344        .await;
345        let ws_id = ws_evs
346            .iter()
347            .find_map(|e| match e {
348                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
349                _ => None,
350            })
351            .unwrap();
352        let _ = dispatch_apply(
353            &state,
354            agentmux_common::ipc::Command::CreateTab {
355                workspace_id: ws_id.clone(),
356                name: "t".into(),
357            },
358        )
359        .await;
360        let err = run(
361            &state,
362            "ghost-block".into(),
363            "ghost-tab".into(),
364            ws_id,
365        )
366        .await
367        .unwrap_err();
368        assert!(err.contains("block not found") || err.contains("source tab not found"), "got: {}", err);
369    }
370}