Skip to main content

agentmux_srv/server/service/
tab_move.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `workspace` service handlers — drag-and-drop block/tab moves
5//! (`MoveBlockToTab`, `PromoteBlockToTab`, `MoveTabToWorkspace`,
6//! `RestoreTornOffTab`). Split out of `workspace.rs`; see that file's
7//! dispatcher for the full method list.
8
9use crate::backend::obj::*;
10use crate::backend::service::{self, WebCallType, WebReturnType};
11
12use super::super::AppState;
13use super::layout_helpers::{queue_source_layout_delete, setup_torn_off_block_layout};
14use super::reducer_helpers::{dispatch_to_reducer, publish_events};
15
16// Phase E.5.7 — MoveBlockToTab migrated to dispatch
17// Command::MoveBlock through the reducer. Auto-close empty
18// source tab still uses Command::DeleteTab. ws_id arg kept
19// for backward compat — used only for the post-op SQLite
20// refresh + auto-close workspace check.
21pub(crate) async fn handle_move_block_to_tab(state: &AppState, call: &WebCallType) -> WebReturnType {
22    let store = &state.mstore;
23    let args = &call.args;
24    let ws_id: String = match service::get_arg(args, 0) {
25        Ok(v) => v,
26        Err(e) => return WebReturnType::error(e),
27    };
28    let block_id: String = match service::get_arg(args, 1) {
29        Ok(v) => v,
30        Err(e) => return WebReturnType::error(e),
31    };
32    let source_tab_id: String = match service::get_arg(args, 2) {
33        Ok(v) => v,
34        Err(e) => return WebReturnType::error(e),
35    };
36    let dest_tab_id: String = match service::get_arg(args, 3) {
37        Ok(v) => v,
38        Err(e) => return WebReturnType::error(e),
39    };
40    let auto_close: bool = service::get_arg(args, 4).unwrap_or(true);
41    tracing::info!(ws_id = %ws_id, block_id = %block_id, source_tab = %source_tab_id, dest_tab = %dest_tab_id, "[dnd:svc] MoveBlockToTab via reducer");
42    // codex P2 #622: same-tab requests were no-ops in the
43    // prior wcore handler. The reducer's MoveBlock treats
44    // same source = dest as an in-tab reorder; with
45    // `dst_index: u32::MAX` it would silently move the block
46    // to the end of the list. Short-circuit to preserve the
47    // prior contract — a `MoveBlockToTab` whose dest equals
48    // the source is a UI quirk (e.g. drop on origin tab),
49    // not an intentional reorder.
50    if source_tab_id == dest_tab_id {
51        return WebReturnType::success_empty();
52    }
53    // Append to the destination: MoveBlock clamps dst_index to
54    // dst.block_ids.len(), so u32::MAX lands at the end.
55    let events = dispatch_to_reducer(
56        state,
57        agentmux_common::ipc::Command::MoveBlock {
58            block_id: block_id.clone(),
59            src_tab_id: source_tab_id.clone(),
60            dst_tab_id: dest_tab_id.clone(),
61            dst_index: u32::MAX,
62        },
63    )
64    .await;
65    if let Some(err_msg) = events.iter().find_map(|e| match e {
66        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
67        _ => None,
68    }) {
69        return WebReturnType::error(err_msg);
70    }
71    for ev in &events {
72        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
73            return WebReturnType::error(format!(
74                "MoveBlockToTab: SQLite write failed: {}",
75                e
76            ));
77        }
78    }
79    publish_events(state, &events);
80    // Auto-close the emptied source tab.
81    if auto_close {
82        let should_close = match store.must_get::<Tab>(&source_tab_id) {
83            Ok(t) => t.blockids.is_empty(),
84            Err(_) => false,
85        };
86        if should_close {
87            let total_tabs = match store.must_get::<Workspace>(&ws_id) {
88                Ok(ws) => ws.tabids.len() + ws.pinnedtabids.len(),
89                Err(_) => 0,
90            };
91            if total_tabs > 1 {
92                let close_events = dispatch_to_reducer(
93                    state,
94                    agentmux_common::ipc::Command::DeleteTab {
95                        workspace_id: ws_id.clone(),
96                        tab_id: source_tab_id.clone(),
97                        // Auto-close already gated on
98                        // `total_tabs > 1` above; reducer's
99                        // last-tab guard is defense-in-depth
100                        // for the race window.
101                        force: false,
102                    },
103                )
104                .await;
105                for ev in &close_events {
106                    let _ = crate::persist_subscriber::apply_event_to_mstore(ev, store);
107                }
108                publish_events(state, &close_events);
109            }
110        }
111    }
112    let mut updates = vec![];
113    if let Ok(src) = store.must_get::<Tab>(&source_tab_id) {
114        updates.push(MuxObjUpdate {
115            updatetype: "update".into(),
116            otype: OTYPE_TAB.to_string(),
117            oid: source_tab_id.clone(),
118            obj: Some(mux_obj_to_value(&src)),
119        });
120    }
121    if let Ok(dst) = store.must_get::<Tab>(&dest_tab_id) {
122        updates.push(MuxObjUpdate {
123            updatetype: "update".into(),
124            otype: OTYPE_TAB.to_string(),
125            oid: dest_tab_id.clone(),
126            obj: Some(mux_obj_to_value(&dst)),
127        });
128    }
129    if let Ok(ws) = store.must_get::<Workspace>(&ws_id) {
130        updates.push(MuxObjUpdate {
131            updatetype: "update".into(),
132            otype: OTYPE_WORKSPACE.to_string(),
133            oid: ws_id.clone(),
134            obj: Some(mux_obj_to_value(&ws)),
135        });
136    }
137    WebReturnType::success_with_updates(updates)
138}
139
140// Phase E.5.7 — PromoteBlockToTab migrated to saga
141// (CreateTab + MoveBlock). Layout setup + SetActiveTab +
142// auto-close source tab stay wcore-direct here (E.4 layout
143// territory). Same shape as TearOffBlock's RPC handler.
144pub(crate) async fn handle_promote_block_to_tab(state: &AppState, call: &WebCallType) -> WebReturnType {
145    let store = &state.mstore;
146    let args = &call.args;
147    let ws_id: String = match service::get_arg(args, 0) {
148        Ok(v) => v,
149        Err(e) => return WebReturnType::error(e),
150    };
151    let block_id: String = match service::get_arg(args, 1) {
152        Ok(v) => v,
153        Err(e) => return WebReturnType::error(e),
154    };
155    let source_tab_id: String = match service::get_arg(args, 2) {
156        Ok(v) => v,
157        Err(e) => return WebReturnType::error(e),
158    };
159    let auto_close: bool = service::get_arg(args, 3).unwrap_or(true);
160    tracing::info!(ws_id = %ws_id, block_id = %block_id, source_tab = %source_tab_id, "[dnd:svc] PromoteBlockToTab via saga");
161    let saga_result = crate::sagas::promote_block_to_tab::run(
162        state,
163        block_id.clone(),
164        source_tab_id.clone(),
165        ws_id.clone(),
166    )
167    .await;
168    let new_tab_oid = match saga_result {
169        Ok(v) => v
170            .get("new_tab_id")
171            .and_then(|v| v.as_str())
172            .unwrap_or_default()
173            .to_string(),
174        Err(reason) => return WebReturnType::error(reason),
175    };
176
177    // Layout setup: the rootnode for the new tab so
178    // the frontend renders the moved block correctly. Same
179    // helper TearOffBlock uses.
180    if let Err(e) = setup_torn_off_block_layout(state, &new_tab_oid, &block_id).await {
181        tracing::warn!(new_tab = %new_tab_oid, "PromoteBlockToTab: layout setup failed: {}", e);
182    }
183    // Source tab: queue layout-delete action.
184    if let Err(e) = queue_source_layout_delete(state, &source_tab_id, &block_id).await {
185        tracing::warn!(source_tab = %source_tab_id, "PromoteBlockToTab: source layout delete-action enqueue failed: {}", e);
186    }
187    // Set the new tab as active in the workspace via reducer.
188    let active_events = dispatch_to_reducer(
189        state,
190        agentmux_common::ipc::Command::SetActiveTab {
191            workspace_id: ws_id.clone(),
192            tab_id: new_tab_oid.clone(),
193        },
194    )
195    .await;
196    for ev in &active_events {
197        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
198            tracing::warn!("PromoteBlockToTab: SetActiveTab apply failed: {}", e);
199        }
200    }
201    publish_events(state, &active_events);
202
203    // Auto-close empty source tab (mirrors wcore behaviour).
204    if auto_close {
205        let should_close = match store.must_get::<Tab>(&source_tab_id) {
206            Ok(t) => t.blockids.is_empty(),
207            Err(_) => false,
208        };
209        if should_close {
210            let total_tabs = match store.must_get::<Workspace>(&ws_id) {
211                Ok(ws) => ws.tabids.len() + ws.pinnedtabids.len(),
212                Err(_) => 0,
213            };
214            if total_tabs > 1 {
215                let close_events = dispatch_to_reducer(
216                    state,
217                    agentmux_common::ipc::Command::DeleteTab {
218                        workspace_id: ws_id.clone(),
219                        tab_id: source_tab_id.clone(),
220                        // Auto-close already gated on
221                        // `total_tabs > 1` above; reducer's
222                        // last-tab guard is defense-in-depth
223                        // for the race window.
224                        force: false,
225                    },
226                )
227                .await;
228                for ev in &close_events {
229                    let _ = crate::persist_subscriber::apply_event_to_mstore(ev, store);
230                }
231                publish_events(state, &close_events);
232            }
233        }
234    }
235
236    let mut updates = vec![];
237    if let Ok(new_tab) = store.must_get::<Tab>(&new_tab_oid) {
238        updates.push(MuxObjUpdate {
239            updatetype: "update".into(),
240            otype: OTYPE_TAB.to_string(),
241            oid: new_tab_oid.clone(),
242            obj: Some(mux_obj_to_value(&new_tab)),
243        });
244    }
245    if let Ok(src) = store.must_get::<Tab>(&source_tab_id) {
246        updates.push(MuxObjUpdate {
247            updatetype: "update".into(),
248            otype: OTYPE_TAB.to_string(),
249            oid: source_tab_id.clone(),
250            obj: Some(mux_obj_to_value(&src)),
251        });
252    }
253    if let Ok(ws) = store.must_get::<Workspace>(&ws_id) {
254        updates.push(MuxObjUpdate {
255            updatetype: "update".into(),
256            otype: OTYPE_WORKSPACE.to_string(),
257            oid: ws_id.clone(),
258            obj: Some(mux_obj_to_value(&ws)),
259        });
260    }
261    WebReturnType::success_data_updates(
262        serde_json::to_value(&new_tab_oid).unwrap_or_default(),
263        updates,
264    )
265}
266
267// Phase E.5.5 — MoveTabToWorkspace migrated to dispatch
268// Command::MoveTab through the reducer. Closes codex P1 #621
269// (the saga's reducer-state pre-check rejected tear-off after
270// a wcore-direct cross-window drag had left state.tabs stale)
271// by routing all tab moves through the reducer so its view
272// always matches SQLite.
273pub(crate) async fn handle_move_tab_to_workspace(state: &AppState, call: &WebCallType) -> WebReturnType {
274    let store = &state.mstore;
275    let args = &call.args;
276    let tab_id: String = match service::get_arg(args, 0) {
277        Ok(v) => v,
278        Err(e) => return WebReturnType::error(e),
279    };
280    let source_ws_id: String = match service::get_arg(args, 1) {
281        Ok(v) => v,
282        Err(e) => return WebReturnType::error(e),
283    };
284    let dest_ws_id: String = match service::get_arg(args, 2) {
285        Ok(v) => v,
286        Err(e) => return WebReturnType::error(e),
287    };
288    let insert_index: Option<u32> = service::get_arg::<usize>(args, 3)
289        .ok()
290        .map(|v| v.try_into().unwrap_or(u32::MAX));
291    tracing::info!(tab_id = %tab_id, source_ws = %source_ws_id, dest_ws = %dest_ws_id, insert_index = ?insert_index, "[dnd:svc] MoveTabToWorkspace via reducer");
292    // Same-workspace short-circuit matches wcore behaviour.
293    // The reducer rejects same-workspace moves outright (use
294    // ReorderTab instead); for the RPC contract, treat it as
295    // a no-op success so existing callers don't see a
296    // behavioural regression.
297    if source_ws_id == dest_ws_id {
298        return WebReturnType::success_empty();
299    }
300    // The last-tab guard is the reducer's (`allow_empty_source: false`),
301    // so a concurrent move can't slip past a stale count.
302    let dst_index = insert_index.unwrap_or(u32::MAX);
303    let events = dispatch_to_reducer(
304        state,
305        agentmux_common::ipc::Command::MoveTab {
306            tab_id: tab_id.clone(),
307            src_workspace_id: source_ws_id.clone(),
308            dst_workspace_id: dest_ws_id.clone(),
309            dst_index,
310            allow_empty_source: false,
311        },
312    )
313    .await;
314    if let Some(err_msg) = events.iter().find_map(|e| match e {
315        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
316        _ => None,
317    }) {
318        if err_msg.contains(crate::reducer::MOVE_TAB_LAST_TAB_ERROR) {
319            return WebReturnType::error(crate::reducer::MOVE_TAB_LAST_TAB_ERROR.to_string());
320        }
321        return WebReturnType::error(err_msg);
322    }
323    for ev in &events {
324        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
325            return WebReturnType::error(format!(
326                "MoveTabToWorkspace: SQLite write failed: {}",
327                e
328            ));
329        }
330    }
331    publish_events(state, &events);
332    let mut updates = Vec::new();
333    if let Ok(src_ws) = store.must_get::<Workspace>(&source_ws_id) {
334        updates.push(MuxObjUpdate {
335            updatetype: "update".into(),
336            otype: OTYPE_WORKSPACE.to_string(),
337            oid: source_ws_id.clone(),
338            obj: Some(mux_obj_to_value(&src_ws)),
339        });
340    }
341    if let Ok(dst_ws) = store.must_get::<Workspace>(&dest_ws_id) {
342        updates.push(MuxObjUpdate {
343            updatetype: "update".into(),
344            otype: OTYPE_WORKSPACE.to_string(),
345            oid: dest_ws_id.clone(),
346            obj: Some(mux_obj_to_value(&dst_ws)),
347        });
348    }
349    WebReturnType::success_with_updates(updates)
350}
351
352// Phase E.5.6 — RestoreTornOffTab migrated to saga (MoveTab
353// back + conditional DeleteWorkspaceCascade if source becomes
354// empty). The legacy `was_pinned` arg is ignored — pinning
355// was removed from AgentMux in E.2c.3b; restored tabs always
356// land in `tab_ids`.
357pub(crate) async fn handle_restore_torn_off_tab(state: &AppState, call: &WebCallType) -> WebReturnType {
358    let store = &state.mstore;
359    let args = &call.args;
360    let tab_id: String = match service::get_arg(args, 0) {
361        Ok(v) => v,
362        Err(e) => return WebReturnType::error(e),
363    };
364    let source_ws_id: String = match service::get_arg(args, 1) {
365        Ok(v) => v,
366        Err(e) => return WebReturnType::error(e),
367    };
368    let dest_ws_id: String = match service::get_arg(args, 2) {
369        Ok(v) => v,
370        Err(e) => return WebReturnType::error(e),
371    };
372    let insert_index: Option<u32> = service::get_arg::<usize>(args, 3)
373        .ok()
374        .map(|v| v.try_into().unwrap_or(u32::MAX));
375    tracing::info!(tab_id = %tab_id, source_ws = %source_ws_id, dest_ws = %dest_ws_id, insert_index = ?insert_index, "[dnd:svc] RestoreTornOffTab via saga");
376    let saga_result = crate::sagas::restore_torn_off_tab::run(
377        state,
378        tab_id,
379        source_ws_id.clone(),
380        dest_ws_id.clone(),
381        insert_index,
382    )
383    .await;
384    match saga_result {
385        Ok(_) => {
386            let mut updates = Vec::new();
387            match store.get::<Workspace>(&source_ws_id) {
388                Ok(Some(src_ws)) => {
389                    updates.push(MuxObjUpdate {
390                        updatetype: "update".into(),
391                        otype: OTYPE_WORKSPACE.to_string(),
392                        oid: source_ws_id.clone(),
393                        obj: Some(mux_obj_to_value(&src_ws)),
394                    });
395                }
396                Ok(None) => {
397                    updates.push(MuxObjUpdate {
398                        updatetype: "delete".into(),
399                        otype: OTYPE_WORKSPACE.to_string(),
400                        oid: source_ws_id.clone(),
401                        obj: None,
402                    });
403                }
404                Err(_) => {}
405            }
406            if let Ok(dst_ws) = store.must_get::<Workspace>(&dest_ws_id) {
407                updates.push(MuxObjUpdate {
408                    updatetype: "update".into(),
409                    otype: OTYPE_WORKSPACE.to_string(),
410                    oid: dest_ws_id.clone(),
411                    obj: Some(mux_obj_to_value(&dst_ws)),
412                });
413            }
414            WebReturnType::success_with_updates(updates)
415        }
416        Err(reason) => WebReturnType::error(reason),
417    }
418}