Skip to main content

agentmux_srv/sagas/
tear_off_tab.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Phase E.5.5 — TearOffTab saga.
5//
6// Migrates the tear-off-tab flow from `wcore::tear_off_tab` (which
7// did two non-transactional SQLite writes outside the reducer) to a
8// reducer-driven multi-step that the persist subscriber writes to
9// SQLite event-by-event. Closes the smoke regression where the new
10// workspace existed in SQLite but the reducer didn't know about it,
11// so the new window's `CreateTab` call would fail.
12//
13// **Steps (mirrors `wcore::tear_off_tab`'s behaviour, NOT the
14// `SPEC_PHASE_E_SAGAS_2026-04-30.md` §6.1 step 3 `CreateWindow`):**
15//
16// 1. `CreateWorkspace { name: "" }` — empty-name matches wcore's
17//    behaviour; user renames after.
18// 2. `MoveTab { tab_id, src=source_ws, dst=new_ws, dst_index: 0 }`.
19//
20// The frontend separately calls the host's `tear_off_pool_promote`
21// to open the CEF window, then the new window's renderer registers
22// the (window_id, workspace_id) mapping via `WindowService.CreateWindow`.
23// Including `Command::CreateWindow` in the saga (per spec §6.1) is
24// deferred — it would require pre-assigning the window_id before
25// the CEF window opens, which the existing host pool-promote and
26// app-init.ts flow doesn't accommodate. See
27// `docs/retro/saga-coordinator-location-analysis-2026-04-30.md`
28// §4.2 — host CEF window creation stays outside the saga.
29//
30// **Pre-condition:** the source workspace has more than one tab.
31// The reducer's `MoveTab` enforces this atomically
32// (`allow_empty_source: false`); the saga also checks before issuing
33// any commands so the common case fails fast with a clear error.
34//
35// **Compensation:**
36// * Step 2 fails after step 1 succeeded (including a concurrent move
37//   that left the source with one tab) → `DeleteWorkspace { new_ws_id }`
38//   (the reducer cascades any tabs in it; the new workspace will be
39//   empty here since step 2 failed before moving the tab).
40// * Step 1 fails → nothing to compensate (reducer rejected without
41//   mutating).
42
43use agentmux_common::ipc::{Command, Event};
44use serde_json::{json, Value};
45
46use super::{
47    alloc_saga_id, classify_run_saga_result, emit_saga_started, emit_terminal, run_saga, SagaCtx,
48};
49use crate::server::AppState;
50
51/// Run the TearOffTab saga. On success, returns
52/// `{"new_workspace_id": "..."}`. On failure, the source workspace
53/// is unchanged (compensation has reverted any partial state).
54pub async fn run(
55    state: &AppState,
56    tab_id: String,
57    source_workspace_id: String,
58) -> Result<Value, String> {
59    // Fast-fail pre-check: source workspace must have more than one
60    // tab. Advisory only; the reducer's `MoveTab` guard in step 2 is
61    // the authority, so a concurrent move between this read and the
62    // dispatch is refused there and compensated. Include
63    // `pinnedtabids` — bootstrap merges them into the reducer's
64    // `tab_ids`, but legacy SQLite rows may still carry the entry.
65    {
66        let src_ws = match state.mstore.get::<crate::backend::obj::Workspace>(&source_workspace_id) {
67            Ok(Some(ws)) => ws,
68            Ok(None) => {
69                return Err(format!(
70                    "TearOffTab: source workspace not found: {}",
71                    source_workspace_id
72                ));
73            }
74            Err(e) => return Err(format!("TearOffTab: workspace read failed: {}", e)),
75        };
76        let in_workspace = src_ws.tabids.iter().any(|id| id == &tab_id)
77            || src_ws.pinnedtabids.iter().any(|id| id == &tab_id);
78        if !in_workspace {
79            return Err(format!(
80                "TearOffTab: tab {} is not in workspace {}",
81                tab_id, source_workspace_id
82            ));
83        }
84        let total_tabs = src_ws.tabids.len() + src_ws.pinnedtabids.len();
85        if total_tabs <= 1 {
86            return Err(format!(
87                "TearOffTab: cannot tear off last tab from workspace {}",
88                source_workspace_id
89            ));
90        }
91    }
92
93    let saga_id = alloc_saga_id(state);
94    if let Err(e) = emit_saga_started(
95        state,
96        saga_id,
97        "tear_off_tab",
98        serde_json::json!({
99            "tab_id": &tab_id,
100            "source_workspace_id": &source_workspace_id,
101        }),
102    )
103    .await
104    {
105        return Err(e);
106    }
107    let ctx = SagaCtx::new(state, saga_id);
108    let result = run_saga("tear_off_tab", run_inner(ctx, tab_id, source_workspace_id)).await;
109    emit_terminal(state, saga_id, classify_run_saga_result(&result)).await;
110    result
111}
112
113async fn run_inner(
114    ctx: SagaCtx<'_>,
115    tab_id: String,
116    source_workspace_id: String,
117) -> Result<Value, String> {
118    // Step 1: create the new workspace.
119    let create_events = ctx
120        .dispatch(Command::CreateWorkspace {
121            name: String::new(),
122        })
123        .await
124        .map_err(|e| format!("TearOffTab step 1 (CreateWorkspace): {}", e))?;
125    let new_workspace_id = create_events
126        .iter()
127        .find_map(|e| match e {
128            Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
129            _ => None,
130        })
131        .ok_or_else(|| {
132            "TearOffTab: CreateWorkspace did not emit WorkspaceCreated".to_string()
133        })?;
134
135    // Step 2: move the tab.
136    if let Err(reason) = ctx
137        .dispatch(Command::MoveTab {
138            tab_id: tab_id.clone(),
139            src_workspace_id: source_workspace_id.clone(),
140            dst_workspace_id: new_workspace_id.clone(),
141            dst_index: 0,
142            allow_empty_source: false,
143        })
144        .await
145    {
146        // Compensate: delete the empty workspace we just created.
147        // `force: false` — internal compensation, not a saga-driven
148        // cascade. (Step 5 PR 2 added the `force` flag for
149        // `delete_workspace` saga provenance.)
150        ctx.compensate(Command::DeleteWorkspace {
151            workspace_id: new_workspace_id.clone(),
152            force: false,
153        })
154        .await;
155        return Err(format!("TearOffTab step 2 (MoveTab): {}", reason));
156    }
157
158    Ok(json!({ "new_workspace_id": new_workspace_id }))
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    use crate::backend::obj::Workspace;
165    use crate::server::tests::test_state;
166
167    /// Boot a workspace + 2 tabs in the reducer + SQLite, mirroring
168    /// what bootstrap would do at startup. Returns `(state, ws_id,
169    /// tab_a_id, tab_b_id)`.
170    async fn seed_workspace_with_two_tabs() -> (
171        crate::server::AppState,
172        String,
173        String,
174        String,
175    ) {
176        let state = test_state();
177        // Use the reducer to create a workspace + 2 tabs so they end
178        // up in both reducer state and SQLite (the saga's pre-condition
179        // checks read reducer state).
180        let ws_events = crate::server::service::dispatch_to_reducer(
181            &state,
182            agentmux_common::ipc::Command::CreateWorkspace { name: "src".into() },
183        )
184        .await;
185        for ev in &ws_events {
186            crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).unwrap();
187        }
188        let ws_id = ws_events
189            .iter()
190            .find_map(|e| match e {
191                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
192                _ => None,
193            })
194            .unwrap();
195        let mut tab_ids = Vec::new();
196        for name in &["tab-a", "tab-b"] {
197            let tab_events = crate::server::service::dispatch_to_reducer(
198                &state,
199                agentmux_common::ipc::Command::CreateTab {
200                    workspace_id: ws_id.clone(),
201                    name: name.to_string(),
202                },
203            )
204            .await;
205            for ev in &tab_events {
206                crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).unwrap();
207            }
208            tab_ids.push(
209                tab_events
210                    .iter()
211                    .find_map(|e| match e {
212                        Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
213                        _ => None,
214                    })
215                    .unwrap(),
216            );
217        }
218        (state, ws_id, tab_ids[0].clone(), tab_ids[1].clone())
219    }
220
221    #[tokio::test]
222    async fn happy_path_creates_new_workspace_and_moves_tab() {
223        let (state, src_ws, tab_a, tab_b) = seed_workspace_with_two_tabs().await;
224        let result = run(&state, tab_a.clone(), src_ws.clone()).await.unwrap();
225        let new_ws_id = result["new_workspace_id"].as_str().unwrap();
226
227        // Reducer view: src has just tab_b; new_ws has tab_a.
228        let s = state.srv_state.lock().await;
229        assert_eq!(s.workspaces[&src_ws].tab_ids, vec![tab_b.clone()]);
230        assert_eq!(s.workspaces[new_ws_id].tab_ids, vec![tab_a.clone()]);
231        assert_eq!(s.tabs[&tab_a].workspace_id, new_ws_id);
232
233        // SQLite view: same.
234        let src_persist = state.mstore.get::<Workspace>(&src_ws).unwrap().unwrap();
235        let new_persist = state.mstore.get::<Workspace>(new_ws_id).unwrap().unwrap();
236        assert_eq!(src_persist.tabids, vec![tab_b]);
237        assert_eq!(new_persist.tabids, vec![tab_a]);
238    }
239
240    #[tokio::test]
241    async fn rejects_when_source_workspace_missing() {
242        let state = test_state();
243        let err = run(&state, "tab-1".into(), "no-such-ws".into()).await.unwrap_err();
244        assert!(err.contains("source workspace not found"), "got: {}", err);
245    }
246
247    #[tokio::test]
248    async fn rejects_last_tab() {
249        let state = test_state();
250        let ws_events = crate::server::service::dispatch_to_reducer(
251            &state,
252            agentmux_common::ipc::Command::CreateWorkspace { name: "src".into() },
253        )
254        .await;
255        for ev in &ws_events {
256            crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).unwrap();
257        }
258        let ws_id = ws_events
259            .iter()
260            .find_map(|e| match e {
261                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
262                _ => None,
263            })
264            .unwrap();
265        let tab_events = crate::server::service::dispatch_to_reducer(
266            &state,
267            agentmux_common::ipc::Command::CreateTab {
268                workspace_id: ws_id.clone(),
269                name: "only".into(),
270            },
271        )
272        .await;
273        for ev in &tab_events {
274            crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).unwrap();
275        }
276        let only_tab = tab_events
277            .iter()
278            .find_map(|e| match e {
279                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
280                _ => None,
281            })
282            .unwrap();
283        let err = run(&state, only_tab, ws_id).await.unwrap_err();
284        assert!(err.contains("last tab"), "got: {}", err);
285    }
286
287    /// The SQLite pre-check sees two tabs, but a concurrent move has
288    /// already left the reducer with one: the reducer refuses step 2
289    /// and the saga removes the workspace it created.
290    #[tokio::test]
291    async fn reducer_guard_refuses_when_precheck_is_stale() {
292        let (state, src_ws, tab_a, tab_b) = seed_workspace_with_two_tabs().await;
293        let other_ws = crate::server::service::dispatch_to_reducer(
294            &state,
295            Command::CreateWorkspace { name: "other".into() },
296        )
297        .await
298        .iter()
299        .find_map(|e| match e {
300            Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
301            _ => None,
302        })
303        .unwrap();
304        // Reducer-only move: SQLite still lists both tabs in src_ws.
305        let moved = crate::server::service::dispatch_to_reducer(
306            &state,
307            Command::MoveTab {
308                tab_id: tab_b,
309                src_workspace_id: src_ws.clone(),
310                dst_workspace_id: other_ws.clone(),
311                dst_index: 0,
312                allow_empty_source: false,
313            },
314        )
315        .await;
316        assert!(matches!(&moved[..], [Event::TabMoved { .. }]), "got {:?}", moved);
317        let workspaces_before = state.srv_state.lock().await.workspaces.len();
318
319        let err = run(&state, tab_a.clone(), src_ws.clone()).await.unwrap_err();
320        assert!(err.contains(crate::reducer::MOVE_TAB_LAST_TAB_ERROR), "got: {}", err);
321        let s = state.srv_state.lock().await;
322        assert_eq!(s.workspaces[&src_ws].tab_ids, vec![tab_a]);
323        assert_eq!(s.workspaces.len(), workspaces_before, "compensation removes the new workspace");
324    }
325}