Skip to main content

agentmux_srv_core/
reducer.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Phase E — srv reducer.
5//
6// The "same discipline as `agentmux-launcher::reducer`" below means exactly
7// that: same purity rules, same `agentmux_common::ipc::{Command, Event}` wire
8// types. Only `State` differs (each crate's own) and which variants this
9// `update` actually handles — workspaces/tabs/blocks, not window/process.
10// Two reducers by design; see
11// docs/architecture/DECISION_SAGA_REDUCER_TWO_FRAMEWORKS_2026_09_07.md.
12//
13// Pure functional core: `update(&mut State, Command, &Ctx) -> Vec<Event>`.
14// Never blocks, never awaits, never does I/O. Same discipline as
15// `agentmux-launcher::reducer`. Mutex held only during dispatch
16// (sub-millisecond).
17//
18// Arms, by domain module: lifecycle (Register / Goodbye / Ping /
19// GetSrvSnapshot), workspace, tab, block, window (window↔workspace
20// mapping), and layout (tree, focus/magnify, pane-tab stacks, backend
21// action queue). Multi-step flows (tear-off, restore, move) are sagas
22// that dispatch these atomic arms.
23//
24// `Command::GetEvents` is intercepted by the IPC server before
25// reaching the reducer (server queries the event log; reducer
26// stays pure). The reducer's arm exists only for match
27// exhaustiveness; same pattern as the launcher reducer.
28
29
30pub mod block;
31pub mod layout;
32pub(crate) use layout::heal_loaded_layout;
33pub mod lifecycle;
34pub mod pin;
35pub mod snapshot;
36pub mod tab;
37#[cfg(any(test, feature = "test-support"))]
38mod test_support;
39pub mod window;
40pub mod workspace;
41
42use agentmux_common::ipc::{Command, ErrorCode, Event};
43use crate::state::State;
44
45
46/// Text in the `MoveTab` last-tab refusal; `MoveTabToWorkspace` matches on
47/// it to return its long-standing error string unchanged.
48pub const MOVE_TAB_LAST_TAB_ERROR: &str = "cannot move last tab out of workspace";
49
50/// Per-dispatch context, built by the caller so `update` stays pure.
51#[derive(Debug, Clone)]
52pub struct Ctx {
53    /// The pid the dispatching connection registered.
54    pub registered_pid: Option<u32>,
55    /// The id a `CreateWorkspace`, `CreateTab` or `CreateBlock` arm gives the
56    /// new entity. Other arms ignore it.
57    pub new_id: String,
58}
59
60impl Ctx {
61    /// A context for one dispatch, with a freshly minted `new_id`. Build one
62    /// per dispatch: a reused context makes a second create refuse the id.
63    pub fn new(registered_pid: Option<u32>) -> Self {
64        Self {
65            registered_pid,
66            new_id: uuid::Uuid::new_v4().to_string(),
67        }
68    }
69}
70
71/// The non-fatal `Event::Error` reply an arm gives a command it refuses,
72/// leaving state untouched.
73fn error_event(state: &mut State, code: ErrorCode, message: impl Into<String>) -> Vec<Event> {
74    let version = state.bump_version();
75    vec![Event::Error {
76        code,
77        message: message.into(),
78        fatal: false,
79        version,
80    }]
81}
82
83/// `error_event` with `ErrorCode::InvalidCommand`, the code nearly every
84/// refusal uses.
85fn invalid_command(state: &mut State, message: impl Into<String>) -> Vec<Event> {
86    error_event(state, ErrorCode::InvalidCommand, message)
87}
88
89pub fn update(state: &mut State, cmd: Command, ctx: &Ctx) -> Vec<Event> {
90    let mut events = run(state, cmd, ctx);
91    events.extend(pin::settle(state));
92    events
93}
94
95fn run(state: &mut State, cmd: Command, ctx: &Ctx) -> Vec<Event> {
96    match cmd {
97        Command::Register { kind, pid, version } => lifecycle::handle_register(state, kind, pid, version),
98        Command::Goodbye => lifecycle::handle_goodbye(state, ctx),
99        Command::Ping { nonce } => {
100            let v = state.bump_version();
101            vec![Event::Pong { nonce, version: v }]
102        }
103        Command::GetSrvSnapshot => snapshot::handle_get_srv_snapshot(state),
104        Command::GetEvents { .. } => Vec::new(), // intercepted by server; unreachable
105        Command::CreateWorkspace { name } => {
106            workspace::handle_create_workspace(state, ctx.new_id.clone(), name)
107        }
108        Command::DeleteWorkspace { workspace_id, force } => {
109            workspace::handle_delete_workspace(state, workspace_id, force)
110        }
111        Command::CreateTab { workspace_id, name } => {
112            tab::handle_create_tab(state, workspace_id, ctx.new_id.clone(), name)
113        }
114        Command::DeleteTab { workspace_id, tab_id, force } => tab::handle_delete_tab(state, workspace_id, tab_id, force),
115        Command::SetActiveTab { workspace_id, tab_id } => {
116            tab::handle_set_active_tab(state, workspace_id, tab_id)
117        }
118        Command::ReorderTab {
119            workspace_id,
120            tab_id,
121            new_index,
122        } => tab::handle_reorder_tab(state, workspace_id, tab_id, new_index),
123        Command::CreateBlock { tab_id, meta } => {
124            block::create_block_with_id(state, tab_id, ctx.new_id.clone(), meta)
125        }
126        Command::DeleteBlock { tab_id, block_id } => block::handle_delete_block(state, tab_id, block_id),
127        Command::SetFocusedNode { tab_id, node_id } => {
128            layout::handle_set_focused_node(state, tab_id, node_id)
129        }
130        Command::SetMagnifiedNode { tab_id, node_id } => {
131            layout::handle_set_magnified_node(state, tab_id, node_id)
132        }
133        // Layout tree arms. Every one has a producer and is persisted from
134        // its event.
135        Command::LayoutSetTree {
136            tab_id,
137            new_tree,
138            correlation_id,
139            slices,
140        } => layout::handle_layout_set_tree(state, tab_id, new_tree, correlation_id, slices),
141        Command::LayoutDeleteNode {
142            tab_id,
143            node_id,
144            correlation_id,
145        } => layout::handle_layout_delete_node(state, tab_id, node_id, correlation_id),
146        // SPEC_864 site #6 — block→node resolution in the arm; silent
147        // no-op when the block has no layout node (see the handler doc).
148        Command::LayoutDeleteNodeByBlock {
149            tab_id,
150            block_id,
151            correlation_id,
152        } => layout::handle_layout_delete_node_by_block(state, tab_id, block_id, correlation_id),
153        // SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.2 — pane tabs.
154        Command::LayoutStackPush {
155            tab_id,
156            target_block_id,
157            block_id,
158            activate,
159            correlation_id,
160        } => layout::handle_layout_stack_push(state, tab_id, target_block_id, block_id, activate, correlation_id),
161        Command::LayoutStackActivate {
162            tab_id,
163            block_id,
164            correlation_id,
165        } => layout::handle_layout_stack_activate(state, tab_id, block_id, correlation_id),
166        Command::CreateBlockInStack {
167            tab_id,
168            target_block_id,
169            meta,
170            activate,
171        } => layout::handle_create_block_in_stack(state, tab_id, target_block_id, ctx.new_id.clone(), meta, activate),
172        // SPEC_PANE_TAB_DRAG_AND_DROP_2026_09_19.md §4.1 — reorder within a
173        // pane or move a tab into a different pane.
174        Command::LayoutStackMove {
175            tab_id,
176            block_id,
177            target_block_id,
178            position,
179            activate,
180            correlation_id,
181        } => layout::handle_layout_stack_move(state, tab_id, block_id, target_block_id, position, activate, correlation_id),
182        // SPEC_PANE_TAB_MULTI_SELECT_MOVE_AND_COLLAPSED_EXPAND_2026_10_24.md §5
183        // — several tabs into one pane, atomically.
184        Command::LayoutStackMoveMany {
185            tab_id,
186            block_ids,
187            target_block_id,
188            activate_block_id,
189            correlation_id,
190        } => layout::handle_layout_stack_move_many(state, tab_id, block_ids, target_block_id, activate_block_id, correlation_id),
191        // SPEC_STRONG_REDUCER_AUTHORITY_LAYOUT_2026_06_30.md §4 — every
192        // layout edit the frontend makes, computed here.
193        Command::LayoutApplyIntent {
194            tab_id,
195            intent,
196            action_id,
197            view,
198        } => layout::handle_layout_apply_intent(state, tab_id, intent, action_id, view),
199        // SPEC_864 Phase 4 — queue-append pass-through (the reducer does
200        // not model pendingbackendactions in TabRecord; the persist
201        // subscriber appends to db_layout from the event).
202        Command::LayoutQueueBackendActions {
203            tab_id,
204            actions,
205            correlation_id,
206        } => layout::handle_layout_queue_backend_actions(state, tab_id, actions, correlation_id),
207        Command::CreateWindow {
208            window_id,
209            workspace_id,
210        } => window::handle_create_window(state, window_id, workspace_id),
211        Command::CloseWindowInternal { window_id } => {
212            window::handle_close_window_internal(state, window_id)
213        }
214        Command::SwitchWorkspace {
215            window_id,
216            workspace_id,
217        } => window::handle_switch_workspace(state, window_id, workspace_id),
218        Command::ReorderTabsBulk {
219            workspace_id,
220            tab_ids,
221        } => tab::handle_reorder_tabs_bulk(state, workspace_id, tab_ids),
222        Command::RenameWorkspace { workspace_id, name } => {
223            workspace::handle_rename_workspace(state, workspace_id, name)
224        }
225        Command::RenameTab { tab_id, name } => tab::handle_rename_tab(state, tab_id, name),
226        Command::UpdateWorkspaceMeta {
227            workspace_id,
228            meta_patch,
229        } => workspace::handle_update_workspace_meta(state, workspace_id, meta_patch),
230        Command::UpdateTabMeta {
231            tab_id,
232            meta_patch,
233        } => tab::handle_update_tab_meta(state, tab_id, meta_patch),
234        Command::UpdateBlockMeta {
235            block_id,
236            meta_patch,
237        } => block::handle_update_block_meta(state, block_id, meta_patch),
238        Command::UpdateWindowMeta {
239            window_id,
240            meta_patch,
241        } => window::handle_update_window_meta(state, window_id, meta_patch),
242        Command::MoveTab {
243            tab_id,
244            src_workspace_id,
245            dst_workspace_id,
246            dst_index,
247            allow_empty_source,
248        } => tab::handle_move_tab(
249            state,
250            tab_id,
251            src_workspace_id,
252            dst_workspace_id,
253            dst_index,
254            allow_empty_source,
255        ),
256        Command::MoveBlock {
257            block_id,
258            src_tab_id,
259            dst_tab_id,
260            dst_index,
261        } => block::handle_move_block(state, block_id, src_tab_id, dst_tab_id, dst_index),
262        pin_cmd @ (Command::PinBlock { .. } | Command::UnpinBlock { .. }) => pin::handle(state, pin_cmd),
263        Command::ParkBlock { tab_id, block_id } => block::handle_park_block(state, tab_id, block_id),
264        Command::AttachBlock { block_id, dst_tab_id, dst_index } => {
265            block::handle_attach_block(state, block_id, dst_tab_id, dst_index)
266        }
267        // Anything else (launcher-domain commands, unimplemented layout
268        // ops) is a non-fatal protocol error that changes no state.
269        other => invalid_command(state, format!("srv reducer does not accept: {:?}", other)),
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276    use crate::reducer::test_support::*;
277
278    // This test exercises the `update()` dispatch fallback itself (the
279    // catch-all `other => { ... InvalidCommand ... }` arm above) rather
280    // than any single domain submodule's logic, so it stays here instead
281    // of moving to a `reducer::*` submodule.
282    #[test]
283    fn unaccepted_command_returns_invalid_command_error() {
284        let mut state = State::default();
285        let events = update(
286            &mut state,
287            Command::ReportWindowOpened {
288                label: "main".into(),
289                kind: agentmux_common::ipc::WindowKind::FullInstance,
290                parent_label: None,
291            },
292            &ctx(1),
293        );
294        assert!(matches!(
295            &events[0],
296            Event::Error {
297                code: ErrorCode::InvalidCommand,
298                fatal: false,
299                ..
300            }
301        ));
302    }
303}