Skip to main content

agentmux_srv/server/app_api/
pane_tabs.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Pane Tab edit commands (`pane.moveTab`, `pane.moveTabs`, `pane.activateTab`, `pane.removeTab`):
5//! resolve the block's tab, dispatch the reducer command, publish, and queue the matching layout action for
6//! other views. Split out of `pane.rs`, which `open_pane` and the other pane commands fill.
7
8use super::*;
9
10/// Core `pane.moveTab` logic — reorder `cmd.block_id` within its own pane, or
11/// move it into a different pane (`Command::LayoutStackMove`). Queues a
12/// `stackmove` layout action so any OTHER window/tab viewing the same
13/// `db_layout` sees the change (mirrors `stack_onto_block_id`'s `stackpush`
14/// queue above); the calling frontend applies its own optimistic local edit
15/// directly and skips the queued copy by its `action_id`.
16/// SPEC_PANE_TAB_DRAG_AND_DROP_2026_09_19.md §4.1, Phase 3.
17pub(crate) async fn move_tab(state: &AppState, cmd: CommandPaneMoveTabData) -> Result<PaneTabEditResult, String> {
18    let position = match cmd.position.as_str() {
19        "before" => agentmux_common::StackMovePosition::Before,
20        "after" => agentmux_common::StackMovePosition::After,
21        "end" => agentmux_common::StackMovePosition::End,
22        other => return Err(format!("pane.moveTab: invalid position '{other}' (expected before/after/end)")),
23    };
24    // Cross-pane moves (Phase 4, SPEC_PANE_TAB_DRAG_AND_DROP_2026_09_19.md
25    // §3.4) were rejected here through Phase 3 (Codex P2 on PR #3444) —
26    // the frontend's pending-action handler didn't yet mirror a cross-leaf
27    // "stackmove" to other windows/tabs watching this layout. That gap is
28    // now closed (layoutPersistence.ts's StackMove case, via
29    // moveMemberAcrossStacks), so both same-pane and cross-pane targets are
30    // accepted here — Command::LayoutStackMove already validates everything
31    // else (existence, non-empty source, etc.) via move_stack_member.
32    let (tab_id, _) = apply_pane_tab_command(state, "pane.moveTab", &cmd.block_id, |tab_id| {
33        agentmux_common::ipc::Command::LayoutStackMove {
34            tab_id,
35            block_id: cmd.block_id.clone(),
36            target_block_id: cmd.target_block_id.clone(),
37            position,
38            activate: cmd.activate,
39            correlation_id: String::new(),
40        }
41    })
42    .await?;
43    let queued = crate::server::service::layout_helpers::queue_target_stack_move(
44        state,
45        &tab_id,
46        &cmd.block_id,
47        &cmd.target_block_id,
48        &cmd.position,
49        cmd.activate,
50        cmd.action_id.as_deref().unwrap_or_default(),
51    )
52    .await;
53    tracing::info!(block_id = %cmd.block_id, target = %cmd.target_block_id, position = %cmd.position, "pane.moveTab");
54    Ok(edit_result(state, &tab_id, "pane.moveTab", &cmd.block_id, queued))
55}
56
57/// Core `pane.moveTabs` logic: several tabs into one pane in one reducer edit
58/// (`Command::LayoutStackMoveMany`), then one queued `stackmove` per block (and
59/// a `stackactivate` when the visible tab is a member that did not move) so any
60/// OTHER window viewing the layout follows. The calling frontend has already
61/// made the same edit and skips every queued copy by its base `action_id`.
62/// SPEC_PANE_TAB_MULTI_SELECT_MOVE_AND_COLLAPSED_EXPAND_2026_10_24.md §5.
63pub(crate) async fn move_tabs(state: &AppState, cmd: CommandPaneMoveTabsData) -> Result<PaneTabEditResult, String> {
64    if cmd.block_ids.is_empty() {
65        return Err("pane.moveTabs: block_ids is empty".to_string());
66    }
67    let (tab_id, _) = apply_pane_tab_command(state, "pane.moveTabs", &cmd.target_block_id, |tab_id| {
68        agentmux_common::ipc::Command::LayoutStackMoveMany {
69            tab_id,
70            block_ids: cmd.block_ids.clone(),
71            target_block_id: cmd.target_block_id.clone(),
72            activate_block_id: cmd.activate_block_id.clone(),
73            correlation_id: String::new(),
74        }
75    })
76    .await?;
77    let queued = crate::server::service::layout_helpers::queue_target_stack_moves(
78        state,
79        &tab_id,
80        &cmd.block_ids,
81        &cmd.target_block_id,
82        cmd.activate_block_id.as_deref(),
83        cmd.action_id.as_deref().unwrap_or_default(),
84    )
85    .await;
86    tracing::info!(count = cmd.block_ids.len(), target = %cmd.target_block_id, "pane.moveTabs");
87    Ok(edit_result(state, &tab_id, "pane.moveTabs", &cmd.target_block_id, queued))
88}
89
90/// `pane.activateTab`: make `block_id` its pane's visible tab
91/// (`Command::LayoutStackActivate`), then queue a `stackactivate` under the
92/// caller's action id for any other view of the tab.
93pub(crate) async fn activate_tab(state: &AppState, cmd: CommandPaneTabData) -> Result<PaneTabEditResult, String> {
94    let block_id = cmd.block_id.clone();
95    let (tab_id, _) = apply_pane_tab_command(state, "pane.activateTab", &cmd.block_id, |tab_id| {
96        agentmux_common::ipc::Command::LayoutStackActivate { tab_id, block_id, correlation_id: String::new() }
97    })
98    .await?;
99    let action_id = cmd.action_id.as_deref().unwrap_or_default();
100    let queued = crate::server::service::layout_helpers::queue_stack_activate(state, &tab_id, &cmd.block_id, action_id).await;
101    Ok(edit_result(state, &tab_id, "pane.activateTab", &cmd.block_id, queued))
102}
103
104/// `pane.removeTab`: take `block_id` out of its pane — that one tab of a
105/// stack, or the pane with its last tab (`Command::LayoutDeleteNodeByBlock`) —
106/// then queue the `delete` under the caller's action id. The block itself is
107/// closed by `ClosePane`, which the caller sends next. A block in no pane is a
108/// no-op: nothing is queued and the revision is 0.
109pub(crate) async fn remove_tab(state: &AppState, cmd: CommandPaneTabData) -> Result<PaneTabEditResult, String> {
110    let block_id = cmd.block_id.clone();
111    let (tab_id, changed) = apply_pane_tab_command(state, "pane.removeTab", &cmd.block_id, |tab_id| {
112        agentmux_common::ipc::Command::LayoutDeleteNodeByBlock { tab_id, block_id, correlation_id: String::new() }
113    })
114    .await?;
115    if !changed {
116        let version = crate::server::service::layout_intents::layout_row_version(&state.mstore, &tab_id);
117        return Ok(PaneTabEditResult { version });
118    }
119    let action_id = cmd.action_id.as_deref().unwrap_or_default();
120    let queued = crate::server::service::layout_helpers::queue_stack_remove(state, &tab_id, &cmd.block_id, action_id).await;
121    Ok(edit_result(state, &tab_id, "pane.removeTab", &cmd.block_id, queued))
122}
123
124/// Resolve `block_id`'s tab, then dispatch `cmd` → mstore → publish, the
125/// shape every pane-tab RPC shares. Returns the tab and whether the reducer
126/// changed anything.
127async fn apply_pane_tab_command(
128    state: &AppState,
129    op: &str,
130    block_id: &str,
131    cmd: impl FnOnce(String) -> agentmux_common::ipc::Command,
132) -> Result<(String, bool), String> {
133    let tab_id = resolve_tab_id_for_block(&state.mstore, block_id).map_err(|e| format!("{op}: {e}"))?;
134    let events = crate::server::service::dispatch_to_reducer(state, cmd(tab_id.clone())).await;
135    if let Some(msg) = events.iter().find_map(|e| match e {
136        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
137        _ => None,
138    }) {
139        return Err(format!("{op}: {msg}"));
140    }
141    for ev in &events {
142        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore) {
143            tracing::warn!("{op}: mstore apply failed: {e}");
144        }
145    }
146    crate::server::service::publish_events(state, &events);
147    Ok((tab_id, !events.is_empty()))
148}
149
150/// What a pane-tab RPC answers: the row's version once the change is stored. A
151/// failed queue is logged, not returned: the tree change already happened.
152fn edit_result(state: &AppState, tab_id: &str, op: &str, block_id: &str, queued: Result<(), String>) -> PaneTabEditResult {
153    if let Err(e) = queued {
154        tracing::warn!(block_id, "{op}: queueing the frontend action failed: {e}");
155    }
156    let version = crate::server::service::layout_intents::layout_row_version(&state.mstore, tab_id);
157    PaneTabEditResult { version }
158}