Skip to main content

agentmux_srv/server/service/
tab_lifecycle.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `workspace` service handlers — tab CRUD (`CreateTab`, `SetActiveTab`,
5//! `CloseTab`, `UpdateTabIds`, `ReorderTab`). Split out of `workspace.rs`;
6//! see that file's dispatcher for the full method list.
7
8use crate::backend::obj::*;
9use crate::backend::service::{self, CloseTabRtnType, WebCallType, WebReturnType};
10
11use super::super::AppState;
12use super::reducer_helpers::{
13    compensate_via_reducer, dispatch_to_reducer, dispatch_to_reducer_timed, publish_events, ReducerTiming,
14};
15
16// Phase E.2c.3b — CreateTab dispatches through the reducer.
17// The `pinned` argument from older clients is ignored:
18// pinning was a Waveterm feature removed from AgentMux.
19// Legacy SQLite databases may still have entries in
20// `Workspace.pinnedtabids`; bootstrap merges them into
21// `tab_ids` so they behave as regular tabs.
22pub(crate) async fn handle_create_tab(state: &AppState, call: &WebCallType) -> WebReturnType {
23    let store = &state.mstore;
24    let args = &call.args;
25    let ws_id: String = match service::get_arg(args, 0) {
26        Ok(v) => v,
27        Err(e) => return WebReturnType::error(e),
28    };
29    let tab_name: String = service::get_arg(args, 1).unwrap_or_default();
30    let activate: bool = service::get_arg(args, 2).unwrap_or(true);
31    // args[3] (`pinned`) intentionally ignored.
32    // An empty name stays empty: the reducer picks the next free `Tab {N}`
33    // and suffixes any name the workspace already has.
34    let events = dispatch_to_reducer(
35        state,
36        agentmux_common::ipc::Command::CreateTab {
37            workspace_id: ws_id.clone(),
38            name: tab_name.clone(),
39        },
40    )
41    .await;
42    // Surface reducer Error events (e.g., workspace not
43    // found) before any persistence work — they're not
44    // bug events, they're caller-visible failures, and the
45    // generic "did not emit TabCreated" message below would
46    // mask the real reason. Matches the SetActiveTab pattern.
47    // (reagent P1 #616.)
48    if let Some(err_msg) = events.iter().find_map(|e| match e {
49        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
50        _ => None,
51    }) {
52        return WebReturnType::error(err_msg);
53    }
54    let tab_id = events.iter().find_map(|e| match e {
55        agentmux_common::ipc::Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
56        _ => None,
57    });
58    // Apply synchronously to mstore (forward+compensate on
59    // failure — same pattern as CreateWorkspace in E.2c.2).
60    let mut apply_err: Option<String> = None;
61    for ev in &events {
62        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
63            apply_err = Some(e.to_string());
64            break;
65        }
66    }
67    if let Some(err) = apply_err {
68        if let Some(tid) = tab_id.as_ref() {
69            compensate_via_reducer(
70                state,
71                agentmux_common::ipc::Command::DeleteTab {
72                    workspace_id: ws_id.clone(),
73                    tab_id: tid.clone(),
74                    // Compensation must bypass the last-tab
75                    // guard to roll back a just-created sole
76                    // tab when its persist failed (codex P1
77                    // round 2 + P2 round 4 PR #633).
78                    force: true,
79                },
80                store,
81            )
82            .await;
83        }
84        return WebReturnType::error(format!("CreateTab: SQLite write failed: {}", err));
85    }
86    publish_events(state, &events);
87    // If `activate=true` and the reducer didn't auto-activate
88    // this as the first tab, dispatch SetActiveTab.
89    let auto_activated = events
90        .iter()
91        .any(|e| matches!(e, agentmux_common::ipc::Event::ActiveTabChanged { .. }));
92    if activate && !auto_activated {
93        if let Some(tid) = tab_id.as_ref() {
94            let active_events = dispatch_to_reducer(
95                state,
96                agentmux_common::ipc::Command::SetActiveTab {
97                    workspace_id: ws_id.clone(),
98                    tab_id: tid.clone(),
99                },
100            )
101            .await;
102            let mut active_err: Option<String> = None;
103            for ev in &active_events {
104                if let Err(e) =
105                    crate::persist_subscriber::apply_event_to_mstore(ev, store)
106                {
107                    active_err = Some(e.to_string());
108                    break;
109                }
110            }
111            if active_err.is_none() {
112                publish_events(state, &active_events);
113            }
114            // SetActiveTab failure is non-fatal here — the
115            // tab exists; activation can be retried by the
116            // caller. Log if it happened.
117            if let Some(err) = active_err {
118                tracing::warn!(
119                    "CreateTab: post-create activate failed: {}",
120                    err
121                );
122            }
123        }
124    }
125    match tab_id {
126        Some(id) => {
127            let mut updates = vec![];
128            if let Ok(tab) = store.must_get::<Tab>(&id) {
129                updates.push(MuxObjUpdate {
130                    updatetype: "update".into(),
131                    otype: OTYPE_TAB.to_string(),
132                    oid: id.clone(),
133                    obj: Some(mux_obj_to_value(&tab)),
134                });
135            }
136            if let Ok(ws) = store.must_get::<Workspace>(&ws_id) {
137                updates.push(MuxObjUpdate {
138                    updatetype: "update".into(),
139                    otype: OTYPE_WORKSPACE.to_string(),
140                    oid: ws_id.clone(),
141                    obj: Some(mux_obj_to_value(&ws)),
142                });
143            }
144            WebReturnType::success_data_updates(
145                serde_json::to_value(&id).unwrap_or_default(),
146                updates,
147            )
148        }
149        None => WebReturnType::error(
150            "CreateTab: reducer did not emit TabCreated".to_string(),
151        ),
152    }
153}
154
155/// A SetActiveTab that took longer than this is logged with where the time went.
156const SLOW_SET_ACTIVE_TAB: std::time::Duration = std::time::Duration::from_millis(200);
157
158/// Whether a SetActiveTab of this total length is logged (#47767).
159fn is_slow_set_active_tab(total: std::time::Duration) -> bool {
160    total > SLOW_SET_ACTIVE_TAB
161}
162
163/// One warn line when SetActiveTab was slow: the total, then the wait for the
164/// reducer mutex, the reducer, and the SQLite persist, so a slow tab click in
165/// the renderer log can be matched to the backend's share of it (#47767).
166fn log_slow_set_active_tab(
167    ws_id: &str,
168    tab_id: &str,
169    total: std::time::Duration,
170    timing: &ReducerTiming,
171    persist: std::time::Duration,
172) {
173    if !is_slow_set_active_tab(total) {
174        return;
175    }
176    tracing::warn!(
177        ws_id = %ws_id,
178        tab_id = %tab_id,
179        total_ms = total.as_millis() as u64,
180        queue_wait_ms = timing.lock_wait.as_millis() as u64,
181        reducer_ms = timing.reducer.as_millis() as u64,
182        persist_ms = persist.as_millis() as u64,
183        "[tab-switch:srv] SetActiveTab was slow"
184    );
185}
186
187// Phase E.2c.3 — SetActiveTab routes through the reducer.
188// Read-through reads (e.g., GetWorkspace) still hit mstore
189// during the migration window, so the synchronous
190// apply-to-mstore keeps them consistent.
191pub(crate) async fn handle_set_active_tab(state: &AppState, call: &WebCallType) -> WebReturnType {
192    let store = &state.mstore;
193    let args = &call.args;
194    let ws_id: String = match service::get_arg(args, 0) {
195        Ok(v) => v,
196        Err(e) => return WebReturnType::error(e),
197    };
198    let tab_id: String = match service::get_arg(args, 1) {
199        Ok(v) => v,
200        Err(e) => return WebReturnType::error(e),
201    };
202    // Phase E.2c.3b — pinning was removed from AgentMux
203    // (Waveterm legacy). All tabs are regular; dispatch
204    // straight through the reducer. Bootstrap merges any
205    // legacy `pinnedtabids` into the reducer's `tab_ids` so
206    // tabs from older databases are reachable as normal tabs.
207    let call_start = std::time::Instant::now();
208    let (events, timing) = dispatch_to_reducer_timed(
209        state,
210        agentmux_common::ipc::Command::SetActiveTab {
211            workspace_id: ws_id.clone(),
212            tab_id: tab_id.clone(),
213        },
214    )
215    .await;
216    // Reducer emits Event::Error on unknown workspace/tab —
217    // surface as RPC error.
218    if let Some(err_msg) = events.iter().find_map(|e| match e {
219        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
220        _ => None,
221    }) {
222        return WebReturnType::error(err_msg);
223    }
224    let persist_start = std::time::Instant::now();
225    // Apply synchronously. SetActiveTab is reversible at the
226    // reducer level (just write back the previous active id),
227    // but we don't track the previous id here; if SQLite
228    // fails, return the error and accept short-lived
229    // divergence on this RPC path. (Acceptable: SetActiveTab
230    // is a UI-driven action; the user can retry.)
231    let mut apply_err: Option<String> = None;
232    for ev in &events {
233        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
234            apply_err = Some(e.to_string());
235            break;
236        }
237    }
238    let persist = persist_start.elapsed();
239    if let Some(err) = apply_err {
240        return WebReturnType::error(format!("SetActiveTab: SQLite write failed: {}", err));
241    }
242    publish_events(state, &events);
243    log_slow_set_active_tab(&ws_id, &tab_id, call_start.elapsed(), &timing, persist);
244    if let Ok(ws) = store.must_get::<Workspace>(&ws_id) {
245        let update = MuxObjUpdate {
246            updatetype: "update".into(),
247            otype: OTYPE_WORKSPACE.to_string(),
248            oid: ws_id.clone(),
249            obj: Some(mux_obj_to_value(&ws)),
250        };
251        WebReturnType::success_with_updates(vec![update])
252    } else {
253        WebReturnType::success_empty()
254    }
255}
256
257// Phase E.5.7 (Step 5 PR 1) — CloseTab via DeleteTab saga.
258// Replaces the legacy SQLite-first pattern (wcore::delete_tab
259// followed by reducer-sync dispatch) with a saga-driven
260// reducer + persist-subscriber flow. The saga also enforces
261// the not-the-last-tab pre-condition mirrored from
262// TearOffTab; user-facing CloseTab now refuses to drain a
263// workspace to zero tabs (callers wanting full teardown
264// should issue DeleteWorkspace instead — that path migrates
265// in Step 5 PR 2).
266pub(crate) async fn handle_close_tab(state: &AppState, call: &WebCallType) -> WebReturnType {
267    let store = &state.mstore;
268    let args = &call.args;
269    let ws_id: String = match service::get_arg(args, 0) {
270        Ok(v) => v,
271        Err(e) => return WebReturnType::error(e),
272    };
273    let tab_id: String = match service::get_arg(args, 1) {
274        Ok(v) => v,
275        Err(e) => return WebReturnType::error(e),
276    };
277    if let Err(reason) =
278        crate::sagas::delete_tab::run(state, ws_id.clone(), tab_id.clone()).await
279    {
280        return WebReturnType::error(reason);
281    }
282    let rtn = CloseTabRtnType {
283        closewindow: false,
284        newactivetabid: String::new(),
285    };
286    let mut updates = vec![MuxObjUpdate {
287        updatetype: "delete".into(),
288        otype: OTYPE_TAB.to_string(),
289        oid: tab_id.clone(),
290        obj: None,
291    }];
292    if let Ok(ws) = store.must_get::<Workspace>(&ws_id) {
293        updates.push(MuxObjUpdate {
294            updatetype: "update".into(),
295            otype: OTYPE_WORKSPACE.to_string(),
296            oid: ws_id.clone(),
297            obj: Some(mux_obj_to_value(&ws)),
298        });
299    }
300    WebReturnType::success_data_updates(
301        serde_json::to_value(&rtn).unwrap_or_default(),
302        updates,
303    )
304}
305
306// Phase E.5.3 — UpdateTabIds migrated to ReorderTabsBulk
307// through the reducer. The legacy `pinned_tab_ids` arg is
308// ignored: pinning was a Waveterm feature removed from
309// AgentMux. Bootstrap merged any legacy `pinnedtabids` into
310// the reducer's `tab_ids`. The subscriber's
311// `apply_tabs_reordered_bulk` rewrites `Workspace.tabids`
312// and drains any leftover `Workspace.pinnedtabids` so the
313// UI's `[...pinnedtabids, ...tabids]` combine never
314// double-counts a tab once a workspace's tabs are
315// reordered through the reducer.
316pub(crate) async fn handle_update_tab_ids(state: &AppState, call: &WebCallType) -> WebReturnType {
317    let store = &state.mstore;
318    let args = &call.args;
319    let ws_id: String = match service::get_arg(args, 0) {
320        Ok(v) => v,
321        Err(e) => return WebReturnType::error(e),
322    };
323    let tab_ids: Vec<String> = match service::get_arg(args, 1) {
324        Ok(v) => v,
325        Err(e) => return WebReturnType::error(e),
326    };
327    // args[2] (pinned_tab_ids) intentionally ignored.
328    let events = dispatch_to_reducer(
329        state,
330        agentmux_common::ipc::Command::ReorderTabsBulk {
331            workspace_id: ws_id.clone(),
332            tab_ids,
333        },
334    )
335    .await;
336    if let Some(err_msg) = events.iter().find_map(|e| match e {
337        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
338        _ => None,
339    }) {
340        return WebReturnType::error(err_msg);
341    }
342    for ev in &events {
343        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
344            return WebReturnType::error(format!(
345                "UpdateTabIds: SQLite write failed: {}",
346                e
347            ));
348        }
349    }
350    publish_events(state, &events);
351    if let Ok(updated_ws) = store.must_get::<Workspace>(&ws_id) {
352        let update = MuxObjUpdate {
353            updatetype: "update".into(),
354            otype: OTYPE_WORKSPACE.to_string(),
355            oid: ws_id.clone(),
356            obj: Some(mux_obj_to_value(&updated_ws)),
357        };
358        return WebReturnType::success_with_updates(vec![update]);
359    }
360    WebReturnType::success_empty()
361}
362
363// Phase E.2c.3b — ReorderTab dispatches through the reducer.
364// Forward+compensate isn't useful here (reorder is its own
365// inverse), so on SQLite apply failure we just surface the
366// error and the reducer state ends up ahead of disk for the
367// remainder of the session — converges back at next restart
368// via bootstrap.
369pub(crate) async fn handle_reorder_tab(state: &AppState, call: &WebCallType) -> WebReturnType {
370    let store = &state.mstore;
371    let args = &call.args;
372    let ws_id: String = match service::get_arg(args, 0) {
373        Ok(v) => v,
374        Err(e) => return WebReturnType::error(e),
375    };
376    let tab_id: String = match service::get_arg(args, 1) {
377        Ok(v) => v,
378        Err(e) => return WebReturnType::error(e),
379    };
380    let new_index: usize = match service::get_arg(args, 2) {
381        Ok(v) => v,
382        Err(e) => return WebReturnType::error(e),
383    };
384    tracing::info!(ws_id = %ws_id, tab_id = %tab_id, new_index = %new_index, "[dnd:svc] ReorderTab");
385    // Clamp to u32::MAX rather than truncating via `as u32`.
386    // The reducer further clamps to `tab_ids.len() - 1` so an
387    // absurd usize ends up at the last position — matching
388    // the prior `wcore::reorder_tab` behaviour where any
389    // out-of-range usize clamped to the end. (codex P3 #617.)
390    let new_index_u32 = u32::try_from(new_index).unwrap_or(u32::MAX);
391    let events = dispatch_to_reducer(
392        state,
393        agentmux_common::ipc::Command::ReorderTab {
394            workspace_id: ws_id.clone(),
395            tab_id: tab_id.clone(),
396            new_index: new_index_u32,
397        },
398    )
399    .await;
400    // Surface reducer Error events.
401    if let Some(err_msg) = events.iter().find_map(|e| match e {
402        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
403        _ => None,
404    }) {
405        return WebReturnType::error(err_msg);
406    }
407    let mut apply_err: Option<String> = None;
408    for ev in &events {
409        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
410            apply_err = Some(e.to_string());
411            break;
412        }
413    }
414    if let Some(err) = apply_err {
415        return WebReturnType::error(format!("ReorderTab: SQLite write failed: {}", err));
416    }
417    publish_events(state, &events);
418    if let Ok(ws) = store.must_get::<Workspace>(&ws_id) {
419        let update = MuxObjUpdate {
420            updatetype: "update".into(),
421            otype: OTYPE_WORKSPACE.to_string(),
422            oid: ws_id.clone(),
423            obj: Some(mux_obj_to_value(&ws)),
424        };
425        WebReturnType::success_with_updates(vec![update])
426    } else {
427        WebReturnType::success_empty()
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434    use std::time::Duration;
435
436    #[test]
437    fn set_active_tab_is_logged_only_past_the_threshold() {
438        assert!(!is_slow_set_active_tab(Duration::from_millis(0)));
439        assert!(!is_slow_set_active_tab(Duration::from_millis(200)));
440        assert!(is_slow_set_active_tab(Duration::from_millis(201)));
441        assert!(is_slow_set_active_tab(Duration::from_secs(3)));
442    }
443}