1use 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
37pub 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 {
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 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 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 match ctx
149 .dispatch(Command::DeleteWorkspace {
150 workspace_id: source_workspace_id.clone(),
151 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 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 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 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 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 let s = state.srv_state.lock().await;
271 assert!(s.workspaces.contains_key(&torn_ws));
272 }
273}