Skip to main content

agentmux_srv_core/reducer/
tab.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use agentmux_common::ipc::Event;
5
6use crate::state::State;
7
8
9use crate::state::TabRecord;
10
11use super::invalid_command;
12
13/// Phase E.2b — create a tab with the caller-minted `tab_id`
14/// (`Ctx::new_id`) inside a workspace. Refuses (non-fatal `Event::Error`)
15/// a missing parent or an id already in use. On success: appends to the
16/// workspace's `tab_ids`, inserts into `state.tabs`, emits
17/// `Event::TabCreated`. If the workspace had no active tab, the new tab
18/// also becomes active and an `Event::ActiveTabChanged` is emitted
19/// alongside.
20pub(super) fn handle_create_tab(
21    state: &mut State,
22    workspace_id: String,
23    tab_id: String,
24    name: String,
25) -> Vec<Event> {
26    if state.tabs.contains_key(&tab_id) {
27        return invalid_command(state, format!("CreateTab: id already in use: {}", tab_id));
28    }
29    let Some(workspace_record) = state.workspaces.get(&workspace_id) else {
30        return invalid_command(state, format!("CreateTab: workspace not found: {}", workspace_id));
31    };
32    // codex P2 #622: auto-generate `Tab N` when name is empty,
33    // matching `wcore::create_tab`'s default-naming behaviour. The
34    // counter uses the reducer's tab_ids length + 1 (matching the
35    // old SQLite-side count: tabids.len() + pinnedtabids.len() + 1
36    // — pinnedtabids stays at zero in production since pinning
37    // was removed in E.2c.3b, so reducer-only counting matches).
38    let resolved_name = if name.is_empty() {
39        next_default_tab_name(state, &workspace_id, workspace_record.tab_ids.len() + 1)
40    } else {
41        free_tab_name(state, &workspace_id, &name, None)
42    };
43    state.tabs.insert(
44        tab_id.clone(),
45        TabRecord {
46            tab_id: tab_id.clone(),
47            workspace_id: workspace_id.clone(),
48            name: resolved_name.clone(),
49            block_ids: Vec::new(),
50            focused_node_id: String::new(),
51            magnified_node_id: String::new(),
52            rootnode: None,
53            recent_intent_ids: Vec::new(),
54        },
55    );
56    let workspace = state.workspaces.get_mut(&workspace_id).expect("checked");
57    workspace.tab_ids.push(tab_id.clone());
58    let activated = if workspace.active_tab_id.is_none() {
59        workspace.active_tab_id = Some(tab_id.clone());
60        true
61    } else {
62        false
63    };
64    let mut events = Vec::with_capacity(2);
65    let v = state.bump_version();
66    events.push(Event::TabCreated {
67        workspace_id: workspace_id.clone(),
68        tab_id: tab_id.clone(),
69        name: resolved_name,
70        version: v,
71    });
72    if activated {
73        let v2 = state.bump_version();
74        events.push(Event::ActiveTabChanged {
75            workspace_id,
76            tab_id: Some(tab_id),
77            version: v2,
78        });
79    }
80    events
81}
82
83/// `desired`, or the first of `desired (2)`, `desired (3)`, … that no other tab
84/// in the workspace uses (compared ignoring case and surrounding spaces), so
85/// "Tab 4 in this window" never names two places. A trailing ` (n)` on
86/// `desired` is dropped first, so a name that was already suffixed doesn't
87/// grow `(2) (2)`. `own_tab_id` is the tab being renamed or moved, which
88/// doesn't count against itself.
89fn free_tab_name(state: &State, workspace_id: &str, desired: &str, own_tab_id: Option<&str>) -> String {
90    let Some(workspace) = state.workspaces.get(workspace_id) else {
91        return desired.to_string();
92    };
93    let taken: std::collections::HashSet<String> = workspace
94        .tab_ids
95        .iter()
96        .filter(|id| Some(id.as_str()) != own_tab_id)
97        .filter_map(|id| state.tabs.get(id))
98        .map(|t| t.name.trim().to_lowercase())
99        .collect();
100    if !taken.contains(desired.trim().to_lowercase().as_str()) {
101        return desired.to_string();
102    }
103    let base = strip_copy_suffix(desired.trim());
104    (2u32..)
105        .map(|n| format!("{base} ({n})"))
106        .find(|candidate| !taken.contains(&candidate.to_lowercase()))
107        .expect("an unbounded range always yields a free name")
108}
109
110/// The default name for a new tab: `Tab {first}`, or the next number up that
111/// the workspace doesn't already use (closing a middle tab leaves the count
112/// below the highest number in use).
113fn next_default_tab_name(state: &State, workspace_id: &str, first: usize) -> String {
114    (first..)
115        .map(|n| format!("Tab {n}"))
116        .find(|candidate| free_tab_name(state, workspace_id, candidate, None) == *candidate)
117        .expect("an unbounded range always yields a free name")
118}
119
120/// `name` without a trailing ` (n)` counter of up to three digits, when what is
121/// left isn't empty: the counters `free_tab_name` generates (it counts well past
122/// 99 for a name shared by that many tabs). A four-digit number is the user's
123/// own ("Report (2024)").
124fn strip_copy_suffix(name: &str) -> &str {
125    let Some(open) = name.rfind(" (") else {
126        return name;
127    };
128    let counter = &name[open + 2..];
129    match counter.strip_suffix(')') {
130        Some(digits) if (1..=3).contains(&digits.len()) && digits.bytes().all(|b| b.is_ascii_digit()) && open > 0 => {
131            &name[..open]
132        }
133        _ => name,
134    }
135}
136
137/// The tab that takes over as active when the active tab leaves
138/// `tab_ids` from `removed_pos`: the next tab, or the previous one if it
139/// was last, or `None` if none is left. `tab_ids` is the list after the
140/// removal. Deleting and moving a tab out both use it.
141fn neighbour_tab(tab_ids: &[String], removed_pos: usize) -> Option<String> {
142    tab_ids
143        .get(removed_pos)
144        .or_else(|| removed_pos.checked_sub(1).and_then(|i| tab_ids.get(i)))
145        .cloned()
146}
147
148/// Phase E.2b — delete a tab from a workspace. Idempotent: deleting
149/// a missing tab is a silent no-op. If the deleted tab was the
150/// active tab, the workspace's active tab becomes its neighbour
151/// (`neighbour_tab`), and an `Event::ActiveTabChanged` is emitted
152/// alongside `Event::TabDeleted`.
153pub(super) fn handle_delete_tab(
154    state: &mut State,
155    workspace_id: String,
156    tab_id: String,
157    force: bool,
158) -> Vec<Event> {
159    let Some(workspace) = state.workspaces.get_mut(&workspace_id) else {
160        return Vec::new();
161    };
162    let Some(pos) = workspace.tab_ids.iter().position(|t| t == &tab_id) else {
163        return Vec::new();
164    };
165    // Last-tab guard, here rather than in the caller so two concurrent
166    // closes can't both pass a stale count (#633). User flows (CloseTab →
167    // DeleteTab saga) pass `force: false`; compensation paths (`CreateTab`
168    // rollback, `PromoteBlockToTab` compensate) pass `force: true`.
169    if !force && workspace.tab_ids.len() <= 1 {
170        return invalid_command(
171            state,
172            format!(
173                "DeleteTab: refusing to delete the last tab in workspace {} (would leave empty workspace; pass force=true for compensation paths)",
174                workspace_id,
175            ),
176        );
177    }
178    workspace.tab_ids.remove(pos);
179    let active_changed = if workspace.active_tab_id.as_deref() == Some(tab_id.as_str()) {
180        let new_active = neighbour_tab(&workspace.tab_ids, pos);
181        workspace.active_tab_id = new_active.clone();
182        Some(new_active)
183    } else {
184        None
185    };
186    let removed_tab = state.tabs.remove(&tab_id);
187    // Phase E.3 — cascade to blocks. Subscribers observing TabDeleted
188    // are expected to drop dependent block state (no per-block
189    // BlockDeleted events emitted; mirrors workspace→tabs cascade
190    // semantics). `block_ids` on the event below carries the cascaded ids
191    // anyway (issue #2218, B.4) — the host uses it to tear down any
192    // browser-pane renderer that was never live/loaded in a window and so
193    // never got a chance to reach the renderer-mediated close path.
194    let cascaded_block_ids: Vec<String> = removed_tab
195        .as_ref()
196        .map(|t| t.block_ids.clone())
197        .unwrap_or_default();
198    if let Some(tab) = &removed_tab {
199        for block_id in &tab.block_ids {
200            state.blocks.remove(block_id);
201        }
202    }
203    let mut events = Vec::with_capacity(2);
204    let v = state.bump_version();
205    events.push(Event::TabDeleted {
206        workspace_id: workspace_id.clone(),
207        tab_id,
208        block_ids: cascaded_block_ids,
209        version: v,
210    });
211    if let Some(new_active) = active_changed {
212        let v2 = state.bump_version();
213        events.push(Event::ActiveTabChanged {
214            workspace_id,
215            tab_id: new_active,
216            version: v2,
217        });
218    }
219    events
220}
221
222/// Phase E.2b — set a workspace's active tab. No-op if already
223/// active. Errors (non-fatal) if the workspace doesn't exist or the
224/// tab isn't in that workspace's tab list.
225pub(super) fn handle_set_active_tab(
226    state: &mut State,
227    workspace_id: String,
228    tab_id: String,
229) -> Vec<Event> {
230    let Some(workspace) = state.workspaces.get_mut(&workspace_id) else {
231        return invalid_command(state, format!("SetActiveTab: workspace not found: {}", workspace_id));
232    };
233    if !workspace.tab_ids.iter().any(|t| t == &tab_id) {
234        return invalid_command(state, format!("SetActiveTab: tab {} not in workspace {}", tab_id, workspace_id));
235    }
236    if workspace.active_tab_id.as_deref() == Some(tab_id.as_str()) {
237        return Vec::new();
238    }
239    workspace.active_tab_id = Some(tab_id.clone());
240    let v = state.bump_version();
241    vec![Event::ActiveTabChanged {
242        workspace_id,
243        tab_id: Some(tab_id),
244        version: v,
245    }]
246}
247
248/// Phase E.2c.3b — reorder a tab within its workspace's
249/// `tab_ids`. `new_index` is clamped to `tab_ids.len()`. No-op
250/// if the tab is already at that position. Errors (non-fatal) if
251/// the workspace doesn't exist or the tab isn't in its tab list.
252pub(super) fn handle_reorder_tab(
253    state: &mut State,
254    workspace_id: String,
255    tab_id: String,
256    new_index: u32,
257) -> Vec<Event> {
258    let Some(workspace) = state.workspaces.get_mut(&workspace_id) else {
259        return invalid_command(state, format!("ReorderTab: workspace not found: {}", workspace_id));
260    };
261    let Some(current_pos) = workspace.tab_ids.iter().position(|t| t == &tab_id) else {
262        return invalid_command(state, format!("ReorderTab: tab {} not in workspace {}", tab_id, workspace_id));
263    };
264    let len = workspace.tab_ids.len();
265    let target = (new_index as usize).min(len.saturating_sub(1));
266    if current_pos == target {
267        return Vec::new();
268    }
269    let id = workspace.tab_ids.remove(current_pos);
270    workspace.tab_ids.insert(target, id);
271    let v = state.bump_version();
272    vec![Event::TabReordered {
273        workspace_id,
274        tab_id,
275        new_index: target as u32,
276        version: v,
277    }]
278}
279
280/// Phase E.5.3 — replace a workspace's `tab_ids` with the given
281/// list. Validates the workspace exists and the new list is a
282/// permutation of the current set (same elements, possibly
283/// different order). No-op if identical.
284pub(super) fn handle_reorder_tabs_bulk(
285    state: &mut State,
286    workspace_id: String,
287    tab_ids: Vec<String>,
288) -> Vec<Event> {
289    // SPEC_864 Phase 5 — strict validation reinstated. The codex P1 #620
290    // membership relaxation existed because `MoveTabToWorkspace` and
291    // `PromoteBlockToTab` used to write through wcore without dispatching
292    // reducer commands, leaving `workspace.tab_ids` stale here. Both are
293    // now reducer-routed (`MoveTabToWorkspace` dispatches `MoveTab`
294    // directly; `PromoteBlockToTab`, `TearOffBlock`, and `TearOffTab` run
295    // through sagas whose steps dispatch `CreateTab`/`MoveTab`/`MoveBlock`)
296    // — every path that changes a workspace's tab set now updates the
297    // reducer in the same step, so `tab_ids` can't legitimately drift
298    // from SQLite anymore. `tab_ids` must be a permutation of the
299    // reducer's own set, not a caller-asserted replacement.
300    let Some(current) = state.workspaces.get(&workspace_id).map(|w| w.tab_ids.clone()) else {
301        return invalid_command(state, format!("ReorderTabsBulk: workspace not found: {}", workspace_id));
302    };
303    {
304        let mut seen: std::collections::HashSet<&String> =
305            std::collections::HashSet::with_capacity(tab_ids.len());
306        for id in &tab_ids {
307            if !seen.insert(id) {
308                return invalid_command(state, format!("ReorderTabsBulk: tab_ids contains duplicate entry: {}", id));
309            }
310        }
311    }
312    if current.len() != tab_ids.len()
313        || !current.iter().all(|id| tab_ids.contains(id))
314    {
315        return invalid_command(
316            state,
317            format!(
318                "ReorderTabsBulk: tab_ids must be a permutation of the workspace's current tabs (got {:?}, expected a permutation of {:?})",
319                tab_ids, current
320            ),
321        );
322    }
323    if current == tab_ids {
324        return Vec::new();
325    }
326    state.workspaces.get_mut(&workspace_id).expect("checked above").tab_ids = tab_ids.clone();
327    let v = state.bump_version();
328    vec![Event::TabsReorderedBulk {
329        workspace_id,
330        tab_ids,
331        version: v,
332    }]
333}
334
335/// Phase E.5.5 — move a tab from `src_workspace_id` to
336/// `dst_workspace_id`, inserting at `dst_index` (clamped to dst's
337/// length). Updates the tab's `workspace_id`, removes it from src's
338/// `tab_ids`, inserts into dst's `tab_ids`. If the tab was src's
339/// `active_tab_id`, src's active becomes its neighbour, as when the
340/// tab is deleted (`neighbour_tab`).
341///
342/// Errors when:
343/// * source / dest workspace not found,
344/// * tab not found,
345/// * `tab.workspace_id != src_workspace_id` (caller-side bug),
346/// * `src_workspace_id == dst_workspace_id` (use `ReorderTab` for
347///   intra-workspace reorders — same-workspace moves through this
348///   path would create ambiguity around `dst_index` semantics),
349/// * the tab is the source's last tab and `allow_empty_source` is
350///   false. The guard lives here, not in callers, so two concurrent
351///   moves out of a two-tab workspace can't both pass a stale count.
352pub(super) fn handle_move_tab(
353    state: &mut State,
354    tab_id: String,
355    src_workspace_id: String,
356    dst_workspace_id: String,
357    dst_index: u32,
358    allow_empty_source: bool,
359) -> Vec<Event> {
360    if src_workspace_id == dst_workspace_id {
361        return invalid_command(state, "MoveTab: src and dst workspaces are identical; use ReorderTab");
362    }
363    // Strict validation (Phase E.4 strict-mode flip): the
364    // migration-tolerant lazy-import fallback (codex P1 round-2
365    // #621) was removed once the soak window closed with no
366    // `lazy-import` warnings observed in production. All reducer-
367    // routed paths now keep `state.tabs` and
368    // `state.workspaces[*].tab_ids` consistent with SQLite, so we
369    // can reject unknown tabs and workspace_id mismatches outright.
370    if !state.workspaces.contains_key(&src_workspace_id) {
371        return invalid_command(state, format!("MoveTab: src workspace not found: {}", src_workspace_id));
372    }
373    if !state.workspaces.contains_key(&dst_workspace_id) {
374        return invalid_command(state, format!("MoveTab: dst workspace not found: {}", dst_workspace_id));
375    }
376    let tab_workspace_id: Option<String> =
377        state.tabs.get(&tab_id).map(|t| t.workspace_id.clone());
378    match tab_workspace_id {
379        None => {
380            return invalid_command(state, format!("MoveTab: tab not found in state: {}", tab_id));
381        }
382        Some(actual_ws) if actual_ws != src_workspace_id => {
383            return invalid_command(
384                state,
385                format!(
386                    "MoveTab: workspace_id mismatch — tab {} belongs to {}, not {}",
387                    tab_id, actual_ws, src_workspace_id
388                ),
389            );
390        }
391        Some(_) => {}
392    }
393    if !allow_empty_source && state.workspaces[&src_workspace_id].tab_ids.len() <= 1 {
394        return invalid_command(
395            state,
396            format!(
397                "MoveTab: {} {} (pass allow_empty_source=true for draining flows)",
398                crate::reducer::MOVE_TAB_LAST_TAB_ERROR,
399                src_workspace_id,
400            ),
401        );
402    }
403
404    // Remove from src.
405    let new_src_active_tab_id: Option<String> = {
406        let src = state.workspaces.get_mut(&src_workspace_id).expect("checked");
407        if let Some(pos) = src.tab_ids.iter().position(|id| id == &tab_id) {
408            src.tab_ids.remove(pos);
409            if src.active_tab_id.as_deref() == Some(tab_id.as_str()) {
410                src.active_tab_id = neighbour_tab(&src.tab_ids, pos);
411            }
412        }
413        src.active_tab_id.clone()
414    };
415
416    // Insert into dst at the clamped index and make the moved tab dst's
417    // active tab, so a tear-off never leaves the destination with no
418    // active tab (#621).
419    let final_dst_index: u32 = {
420        let dst = state.workspaces.get_mut(&dst_workspace_id).expect("checked");
421        let clamped = (dst_index as usize).min(dst.tab_ids.len());
422        dst.tab_ids.insert(clamped, tab_id.clone());
423        dst.active_tab_id = Some(tab_id.clone());
424        clamped as u32
425    };
426
427    // Update the tab's parent.
428    state
429        .tabs
430        .get_mut(&tab_id)
431        .expect("checked")
432        .workspace_id = dst_workspace_id.clone();
433
434    // The destination may already have a tab by this name: the moved tab
435    // takes a suffix, so the window never holds two of one name.
436    let current_name = state.tabs[&tab_id].name.clone();
437    let moved_name = free_tab_name(state, &dst_workspace_id, &current_name, Some(&tab_id));
438
439    let v = state.bump_version();
440    let mut events = vec![Event::TabMoved {
441        tab_id: tab_id.clone(),
442        src_workspace_id,
443        dst_workspace_id,
444        dst_index: final_dst_index,
445        new_src_active_tab_id,
446        new_dst_active_tab_id: Some(tab_id.clone()),
447        version: v,
448    }];
449    if moved_name != current_name {
450        state.tabs.get_mut(&tab_id).expect("checked").name = moved_name.clone();
451        let v = state.bump_version();
452        events.push(Event::TabRenamed {
453            tab_id,
454            name: moved_name,
455            version: v,
456        });
457    }
458    events
459}
460
461/// Phase E.5.3 — rename a tab. Errors if missing; no-op if the
462/// name is unchanged.
463pub(super) fn handle_rename_tab(state: &mut State, tab_id: String, name: String) -> Vec<Event> {
464    let Some(tab) = state.tabs.get(&tab_id) else {
465        return invalid_command(state, format!("RenameTab: tab not found: {}", tab_id));
466    };
467    let name = free_tab_name(state, &tab.workspace_id.clone(), &name, Some(&tab_id));
468    let tab = state.tabs.get_mut(&tab_id).expect("checked");
469    if tab.name == name {
470        return Vec::new();
471    }
472    tab.name = name.clone();
473    let v = state.bump_version();
474    vec![Event::TabRenamed {
475        tab_id,
476        name,
477        version: v,
478    }]
479}
480
481/// Phase E.5.3 — pass-through for tab meta updates. Same shape as
482/// `handle_update_workspace_meta`.
483pub(super) fn handle_update_tab_meta(
484    state: &mut State,
485    tab_id: String,
486    meta_patch: serde_json::Value,
487) -> Vec<Event> {
488    if !state.tabs.contains_key(&tab_id) {
489        return invalid_command(state, format!("UpdateTabMeta: tab not found: {}", tab_id));
490    }
491    let v = state.bump_version();
492    vec![Event::TabMetaUpdated {
493        tab_id,
494        meta_patch,
495        version: v,
496    }]
497}
498
499#[cfg(test)]
500mod tests;