Skip to main content

agentmux_srv/sagas/
restore_torn_off_tab.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Phase E.5.6 — RestoreTornOffTab saga.
5//
6// Drops the torn-off tab back into the destination workspace and,
7// if the source workspace became empty, deletes it (cascade).
8//
9// **Steps:**
10// 1. `MoveTab { tab_id, src=source_ws, dst=dest_ws, dst_index }`
11// 2. If post-move state shows source workspace's `tab_ids` is
12//    empty → `DeleteWorkspace { source_ws }` (cascade is built in;
13//    no surviving tabs to handle).
14//    Otherwise → done.
15//
16// **Compensation:**
17// * Step 1 fails → nothing to compensate (reducer rejected without
18//   mutating; tab is still in source).
19// * Step 2 fails → tab is already restored to dest; the orphan
20//   source workspace persists. Log the failure but return success
21//   (the user-visible operation succeeded; the orphan is a soft
22//   cleanup gap that the next user action — close window, etc. —
23//   will catch).
24//
25// **Pinning note:** the legacy `was_pinned` arg of `RestoreTornOffTab`
26// is ignored. Pinning was a Waveterm feature removed from AgentMux
27// (per E.2c.3b). Restored tabs always land in `tab_ids`.
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 RestoreTornOffTab saga. On success, returns
38/// `{"source_workspace_deleted": <bool>}`.
39pub async fn run(
40    state: &AppState,
41    tab_id: String,
42    source_workspace_id: String,
43    dest_workspace_id: String,
44    insert_index: Option<u32>,
45) -> Result<Value, String> {
46    // Pre-condition checks read SQLite, not reducer state. During
47    // the migration window, wcore-direct paths (PromoteBlockToTab,
48    // etc.) leave reducer.tabs / workspaces stale relative to disk;
49    // a reducer-state pre-check would falsely reject valid restores
50    // (codex P1 round-2 #621).
51    {
52        let src_ws = match state.mstore.get::<crate::backend::obj::Workspace>(&source_workspace_id) {
53            Ok(Some(ws)) => ws,
54            Ok(None) => {
55                return Err(format!(
56                    "RestoreTornOffTab: source workspace not found: {}",
57                    source_workspace_id
58                ));
59            }
60            Err(e) => {
61                return Err(format!(
62                    "RestoreTornOffTab: workspace read failed: {}",
63                    e
64                ));
65            }
66        };
67        if state
68            .mstore
69            .get::<crate::backend::obj::Workspace>(&dest_workspace_id)
70            .map(|w| w.is_none())
71            .unwrap_or(true)
72        {
73            return Err(format!(
74                "RestoreTornOffTab: dest workspace not found: {}",
75                dest_workspace_id
76            ));
77        }
78        let in_workspace = src_ws.tabids.iter().any(|id| id == &tab_id)
79            || src_ws.pinnedtabids.iter().any(|id| id == &tab_id);
80        if !in_workspace {
81            return Err(format!(
82                "RestoreTornOffTab: tab {} is not in workspace {}",
83                tab_id, source_workspace_id
84            ));
85        }
86    }
87
88    let dst_index = insert_index.unwrap_or(u32::MAX);
89
90    let saga_id = alloc_saga_id(state);
91    if let Err(e) = emit_saga_started(
92        state,
93        saga_id,
94        "restore_torn_off_tab",
95        serde_json::json!({
96            "tab_id": &tab_id,
97            "source_workspace_id": &source_workspace_id,
98            "dest_workspace_id": &dest_workspace_id,
99            "insert_index": dst_index,
100        }),
101    )
102    .await
103    {
104        return Err(e);
105    }
106    let ctx = SagaCtx::new(state, saga_id);
107    let result = run_saga(
108        "restore_torn_off_tab",
109        run_inner(ctx, tab_id, source_workspace_id, dest_workspace_id, dst_index),
110    )
111    .await;
112    emit_terminal(state, saga_id, classify_run_saga_result(&result)).await;
113    result
114}
115
116async fn run_inner(
117    ctx: SagaCtx<'_>,
118    tab_id: String,
119    source_workspace_id: String,
120    dest_workspace_id: String,
121    dst_index: u32,
122) -> Result<Value, String> {
123    // Step 1: move the tab. The torn-off workspace usually holds only
124    // this tab, so the move may drain it; step 2 then deletes it.
125    ctx.dispatch(Command::MoveTab {
126        tab_id: tab_id.clone(),
127        src_workspace_id: source_workspace_id.clone(),
128        dst_workspace_id: dest_workspace_id.clone(),
129        dst_index,
130        allow_empty_source: true,
131    })
132    .await
133    .map_err(|e| format!("RestoreTornOffTab step 1 (MoveTab): {}", e))?;
134
135    // Step 2: check post-move state, conditionally delete source.
136    let source_now_empty = {
137        let s = ctx.state_lock().await;
138        s.workspaces
139            .get(&source_workspace_id)
140            .map(|ws| ws.tab_ids.is_empty())
141            .unwrap_or(true)
142    };
143
144    let mut source_deleted = false;
145    if source_now_empty {
146        // Best-effort delete; log + soft-fail on reducer rejection
147        // (tab is already restored, which is what the user asked for).
148        match ctx
149            .dispatch(Command::DeleteWorkspace {
150                workspace_id: source_workspace_id.clone(),
151                // `force: false` — sub-step within restore_torn_off_tab,
152                // not the dedicated `delete_workspace` saga (Step 5 PR 2).
153                // The workspace is already empty here so cascade-vs-saga
154                // distinction is moot; the flag is provenance-only.
155                force: false,
156            })
157            .await
158        {
159            Ok(_) => source_deleted = true,
160            Err(e) => {
161                tracing::warn!(
162                    saga_id = ctx.saga_id(),
163                    "[saga] RestoreTornOffTab: source workspace cleanup failed: {} (orphan workspace {})",
164                    e,
165                    source_workspace_id
166                );
167            }
168        }
169    }
170
171    Ok(json!({ "source_workspace_deleted": source_deleted }))
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177    use agentmux_common::ipc::Event;
178    use crate::backend::obj::Workspace;
179    use crate::server::tests::{dispatch_apply, test_state};
180
181    /// Seeds a "torn-off" workspace (single tab) and a destination
182    /// workspace (its own tab). Returns (state, torn_ws, torn_tab,
183    /// dest_ws, dest_tab).
184    async fn seed_torn_off_state() -> (crate::server::AppState, String, String, String, String) {
185        let state = test_state();
186        let mut ws_ids = Vec::new();
187        let mut tab_ids = Vec::new();
188        for ws_name in &["torn", "dest"] {
189            let ws_evs = dispatch_apply(
190                &state,
191                agentmux_common::ipc::Command::CreateWorkspace {
192                    name: ws_name.to_string(),
193                },
194            )
195            .await;
196            let ws_id = ws_evs
197                .iter()
198                .find_map(|e| match e {
199                    Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
200                    _ => None,
201                })
202                .unwrap();
203            let tab_evs = dispatch_apply(
204                &state,
205                agentmux_common::ipc::Command::CreateTab {
206                    workspace_id: ws_id.clone(),
207                    name: format!("{}-tab", ws_name),
208                },
209            )
210            .await;
211            let tab_id = tab_evs
212                .iter()
213                .find_map(|e| match e {
214                    Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
215                    _ => None,
216                })
217                .unwrap();
218            ws_ids.push(ws_id);
219            tab_ids.push(tab_id);
220        }
221        (
222            state,
223            ws_ids[0].clone(),
224            tab_ids[0].clone(),
225            ws_ids[1].clone(),
226            tab_ids[1].clone(),
227        )
228    }
229
230    #[tokio::test]
231    async fn happy_path_moves_tab_back_and_deletes_empty_source() {
232        let (state, torn_ws, torn_tab, dest_ws, _dest_tab) = seed_torn_off_state().await;
233        let result = run(&state, torn_tab.clone(), torn_ws.clone(), dest_ws.clone(), Some(0))
234            .await
235            .unwrap();
236        assert_eq!(result["source_workspace_deleted"], true);
237
238        // Reducer: source workspace gone; tab is in dest.
239        let s = state.srv_state.lock().await;
240        assert!(!s.workspaces.contains_key(&torn_ws));
241        assert!(s.workspaces[&dest_ws].tab_ids.contains(&torn_tab));
242        assert_eq!(s.tabs[&torn_tab].workspace_id, dest_ws);
243        drop(s);
244
245        // SQLite: source workspace row gone too.
246        assert!(state.mstore.get::<Workspace>(&torn_ws).unwrap().is_none());
247    }
248
249    #[tokio::test]
250    async fn skips_delete_when_source_still_has_tabs() {
251        let (state, torn_ws, torn_tab, dest_ws, _) = seed_torn_off_state().await;
252        // Add a second tab to torn so it doesn't become empty.
253        let _ = dispatch_apply(
254            &state,
255            agentmux_common::ipc::Command::CreateTab {
256                workspace_id: torn_ws.clone(),
257                name: "extra".into(),
258            },
259        )
260        .await;
261
262        let result = run(&state, torn_tab, torn_ws.clone(), dest_ws, Some(0))
263            .await
264            .unwrap();
265        assert_eq!(
266            result["source_workspace_deleted"], false,
267            "source ws should survive when it still has tabs"
268        );
269        // Source still in reducer.
270        let s = state.srv_state.lock().await;
271        assert!(s.workspaces.contains_key(&torn_ws));
272    }
273}