Skip to main content

agentmux_srv_core/reducer/
block.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::BlockRecord;
10
11use super::invalid_command;
12
13/// Phase E.3 — create a block with the caller-minted `block_id`
14/// (`Ctx::new_id`) inside a tab. Refuses (non-fatal `Event::Error`) a
15/// missing tab or an id already in use. On success: appends to the tab's
16/// `block_ids`, inserts into `state.blocks`, emits `Event::BlockCreated`.
17pub(super) fn create_block_with_id(
18    state: &mut State,
19    tab_id: String,
20    block_id: String,
21    meta: serde_json::Value,
22) -> Vec<Event> {
23    if state.blocks.contains_key(&block_id) {
24        return invalid_command(state, format!("CreateBlock: id already in use: {}", block_id));
25    }
26    if !state.tabs.contains_key(&tab_id) {
27        return invalid_command(state, format!("CreateBlock: tab not found: {}", tab_id));
28    }
29    state.blocks.insert(
30        block_id.clone(),
31        BlockRecord {
32            block_id: block_id.clone(),
33            tab_id: tab_id.clone(),
34        },
35    );
36    let tab = state.tabs.get_mut(&tab_id).expect("checked");
37    tab.block_ids.push(block_id.clone());
38    let v = state.bump_version();
39    vec![Event::BlockCreated {
40        tab_id,
41        block_id,
42        meta,
43        version: v,
44    }]
45}
46
47/// Phase E.3 — delete a block from a tab. Idempotent: deleting a
48/// missing tab or missing block is a silent no-op.
49pub(super) fn handle_delete_block(state: &mut State, tab_id: String, block_id: String) -> Vec<Event> {
50    delete_block(state, tab_id, block_id)
51}
52
53fn delete_block(state: &mut State, tab_id: String, block_id: String) -> Vec<Event> {
54    // A parked block is in no tab, so it is deleted with an empty `tab_id` (an agent's delete).
55    // Any other block with no tab, or a tab-less delete of a block that has one, is not this.
56    if tab_id.is_empty() {
57        if !state.blocks.get(&block_id).is_some_and(|b| b.tab_id.is_empty()) {
58            return Vec::new();
59        }
60        state.blocks.remove(&block_id);
61        let v = state.bump_version();
62        return vec![Event::BlockDeleted { tab_id, block_id, version: v }];
63    }
64    let Some(tab) = state.tabs.get_mut(&tab_id) else {
65        return Vec::new();
66    };
67    let Some(pos) = tab.block_ids.iter().position(|b| b == &block_id) else {
68        return Vec::new();
69    };
70    tab.block_ids.remove(pos);
71    state.blocks.remove(&block_id);
72    let v = state.bump_version();
73    vec![Event::BlockDeleted {
74        tab_id,
75        block_id,
76        version: v,
77    }]
78}
79
80/// Phase E.5.5 — move a block from `src_tab_id` to `dst_tab_id` at
81/// `dst_index` (clamped). Updates `block.tab_id`. Cross-tab moves
82/// AND intra-tab repositioning both go through this command (the
83/// caller specifies the destination index regardless).
84///
85/// Errors when source / dest tab missing, block missing, or
86/// `block.tab_id != src_tab_id`.
87pub(super) fn handle_move_block(
88    state: &mut State,
89    block_id: String,
90    src_tab_id: String,
91    dst_tab_id: String,
92    dst_index: u32,
93) -> Vec<Event> {
94    let validation_error: Option<String> = {
95        if !state.tabs.contains_key(&src_tab_id) {
96            Some(format!("MoveBlock: src tab not found: {}", src_tab_id))
97        } else if !state.tabs.contains_key(&dst_tab_id) {
98            Some(format!("MoveBlock: dst tab not found: {}", dst_tab_id))
99        } else {
100            match state.blocks.get(&block_id) {
101                None => Some(format!("MoveBlock: block not found: {}", block_id)),
102                Some(block) if block.tab_id != src_tab_id => Some(format!(
103                    "MoveBlock: block {} belongs to tab {}, not {}",
104                    block_id, block.tab_id, src_tab_id
105                )),
106                _ => None,
107            }
108        }
109    };
110    if let Some(message) = validation_error {
111        return invalid_command(state, message);
112    }
113
114    // Special-case intra-tab move: remove and re-insert in the same
115    // tab. The clamp is computed AFTER the removal so dst_index
116    // refers to the post-removal list (matches the spec's "position
117    // in dst.tab_ids AFTER insertion" semantics for cross-tab moves).
118    let final_dst_index: u32 = if src_tab_id == dst_tab_id {
119        let tab = state.tabs.get_mut(&src_tab_id).expect("checked");
120        tab.block_ids.retain(|id| id != &block_id);
121        let clamped = (dst_index as usize).min(tab.block_ids.len());
122        tab.block_ids.insert(clamped, block_id.clone());
123        clamped as u32
124    } else {
125        // Remove from src.
126        state
127            .tabs
128            .get_mut(&src_tab_id)
129            .expect("checked")
130            .block_ids
131            .retain(|id| id != &block_id);
132        // Insert into dst.
133        let dst = state.tabs.get_mut(&dst_tab_id).expect("checked");
134        let clamped = (dst_index as usize).min(dst.block_ids.len());
135        dst.block_ids.insert(clamped, block_id.clone());
136        // Update parent.
137        state.blocks.get_mut(&block_id).expect("checked").tab_id = dst_tab_id.clone();
138        clamped as u32
139    };
140
141    let v = state.bump_version();
142    vec![Event::BlockMoved {
143        block_id,
144        src_tab_id,
145        dst_tab_id,
146        dst_index: final_dst_index,
147        version: v,
148    }]
149}
150
151/// Take a block out of `tab_id` and keep it: it leaves the tab's `block_ids`, stays in
152/// `state.blocks` with an empty `tab_id` (parked), and nothing is deleted. Idempotent: a
153/// missing tab, or a block that is not in that tab, is a silent no-op.
154pub(super) fn handle_park_block(state: &mut State, tab_id: String, block_id: String) -> Vec<Event> {
155    park_block(state, tab_id, block_id)
156}
157
158fn park_block(state: &mut State, tab_id: String, block_id: String) -> Vec<Event> {
159    let Some(tab) = state.tabs.get_mut(&tab_id) else {
160        return Vec::new();
161    };
162    let Some(pos) = tab.block_ids.iter().position(|b| b == &block_id) else {
163        return Vec::new();
164    };
165    tab.block_ids.remove(pos);
166    if let Some(block) = state.blocks.get_mut(&block_id) {
167        block.tab_id = String::new();
168    }
169    let v = state.bump_version();
170    vec![Event::BlockParked { tab_id, block_id, version: v }]
171}
172
173/// Put a parked block into `dst_tab_id` at `dst_index` (clamped). Errors when the tab or the
174/// block is missing, or the block is in a tab already (move it with `MoveBlock`).
175pub(super) fn handle_attach_block(state: &mut State, block_id: String, dst_tab_id: String, dst_index: u32) -> Vec<Event> {
176    let error = if !state.tabs.contains_key(&dst_tab_id) {
177        Some(format!("AttachBlock: dst tab not found: {}", dst_tab_id))
178    } else {
179        match state.blocks.get(&block_id) {
180            None => Some(format!("AttachBlock: block not found: {}", block_id)),
181            Some(block) if !block.tab_id.is_empty() => {
182                Some(format!("AttachBlock: block {} is in tab {}, not parked", block_id, block.tab_id))
183            }
184            _ => None,
185        }
186    };
187    if let Some(message) = error {
188        return invalid_command(state, message);
189    }
190    let dst = state.tabs.get_mut(&dst_tab_id).expect("checked");
191    let at = (dst_index as usize).min(dst.block_ids.len());
192    dst.block_ids.insert(at, block_id.clone());
193    state.blocks.get_mut(&block_id).expect("checked").tab_id = dst_tab_id.clone();
194    let v = state.bump_version();
195    vec![Event::BlockAttached { block_id, dst_tab_id, dst_index: at as u32, version: v }]
196}
197
198/// Phase E.5.3 — pass-through for block meta updates. Same shape.
199pub(super) fn handle_update_block_meta(
200    state: &mut State,
201    block_id: String,
202    meta_patch: serde_json::Value,
203) -> Vec<Event> {
204    if !state.blocks.contains_key(&block_id) {
205        return invalid_command(state, format!("UpdateBlockMeta: block not found: {}", block_id));
206    }
207    let v = state.bump_version();
208    vec![Event::BlockMetaUpdated {
209        block_id,
210        meta_patch,
211        version: v,
212    }]
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use crate::reducer::test_support::*;
219    use crate::reducer::update;
220    use agentmux_common::ipc::Command;
221
222    #[test]
223    fn create_block_validates_tab_exists() {
224        let mut state = State::default();
225        let events = update(
226            &mut state,
227            Command::CreateBlock { tab_id: "no-such-tab".into(), meta: serde_json::Value::Null },
228            &ctx(1),
229        );
230        assert!(matches!(&events[0], Event::Error { .. }));
231        assert!(state.blocks.is_empty());
232    }
233
234    #[test]
235    fn create_block_appends_to_tab_block_ids() {
236        let mut state = State::default();
237        let ws_id = create_workspace(&mut state, "w");
238        let tab_id = create_tab(&mut state, &ws_id, "t");
239        let events = update(
240            &mut state,
241            Command::CreateBlock { tab_id: tab_id.clone(), meta: serde_json::Value::Null },
242            &ctx(2),
243        );
244        assert!(matches!(&events[0], Event::BlockCreated { .. }));
245        let block_id = match &events[0] {
246            Event::BlockCreated { block_id, .. } => block_id.clone(),
247            _ => panic!(),
248        };
249        assert_eq!(state.tabs[&tab_id].block_ids, vec![block_id.clone()]);
250        assert_eq!(state.blocks[&block_id].tab_id, tab_id);
251    }
252
253    #[test]
254    fn delete_block_removes_from_state_and_tab() {
255        let mut state = State::default();
256        let ws_id = create_workspace(&mut state, "w");
257        let tab_id = create_tab(&mut state, &ws_id, "t");
258        let _ = update(
259            &mut state,
260            Command::CreateBlock { tab_id: tab_id.clone(), meta: serde_json::Value::Null },
261            &ctx(2),
262        );
263        let block_id = state.tabs[&tab_id].block_ids[0].clone();
264        let events = update(
265            &mut state,
266            Command::DeleteBlock {
267                tab_id: tab_id.clone(),
268                block_id: block_id.clone(),
269            },
270            &ctx(3),
271        );
272        assert!(matches!(&events[0], Event::BlockDeleted { .. }));
273        assert!(!state.blocks.contains_key(&block_id));
274        assert!(state.tabs[&tab_id].block_ids.is_empty());
275    }
276
277    #[test]
278    fn delete_block_unknown_silent_no_op() {
279        let mut state = State::default();
280        let ws_id = create_workspace(&mut state, "w");
281        let tab_id = create_tab(&mut state, &ws_id, "t");
282        let events = update(
283            &mut state,
284            Command::DeleteBlock {
285                tab_id,
286                block_id: "ghost".into(),
287            },
288            &ctx(2),
289        );
290        assert!(events.is_empty());
291    }
292
293    // ---- Phase E.5.5 — MoveBlock tests ----
294
295    #[test]
296    fn move_block_cross_tab_updates_lists_and_parent() {
297        let mut state = State::default();
298        let ws = create_workspace(&mut state, "w");
299        let src_tab = create_tab(&mut state, &ws, "src");
300        let dst_tab = create_tab(&mut state, &ws, "dst");
301        let block = create_block(&mut state, &src_tab);
302        let dst_existing = create_block(&mut state, &dst_tab);
303        let events = update(
304            &mut state,
305            Command::MoveBlock {
306                block_id: block.clone(),
307                src_tab_id: src_tab.clone(),
308                dst_tab_id: dst_tab.clone(),
309                dst_index: 0,
310            },
311            &ctx(2),
312        );
313        assert!(matches!(&events[0], Event::BlockMoved { .. }));
314        assert_eq!(state.tabs[&src_tab].block_ids, Vec::<String>::new());
315        assert_eq!(state.tabs[&dst_tab].block_ids, vec![block.clone(), dst_existing]);
316        assert_eq!(state.blocks[&block].tab_id, dst_tab);
317    }
318
319    #[test]
320    fn park_keeps_the_block_in_state_but_in_no_tab() {
321        let mut state = State::default();
322        let ws = create_workspace(&mut state, "w");
323        let tab = create_tab(&mut state, &ws, "t");
324        let (keep, parked) = (create_block(&mut state, &tab), create_block(&mut state, &tab));
325        let events = update(&mut state, Command::ParkBlock { tab_id: tab.clone(), block_id: parked.clone() }, &ctx(2));
326        assert!(matches!(&events[0], Event::BlockParked { .. }));
327        assert_eq!(state.tabs[&tab].block_ids, vec![keep]);
328        assert_eq!(state.blocks[&parked].tab_id, "");
329        // Again, and for a block or tab that is not there: nothing happens.
330        assert!(update(&mut state, Command::ParkBlock { tab_id: tab.clone(), block_id: parked.clone() }, &ctx(3)).is_empty());
331        assert!(update(&mut state, Command::ParkBlock { tab_id: "ghost".into(), block_id: parked }, &ctx(4)).is_empty());
332    }
333
334    #[test]
335    fn a_parked_block_is_deleted_with_no_tab_and_no_other_block_is() {
336        let mut state = State::default();
337        let ws = create_workspace(&mut state, "w");
338        let tab = create_tab(&mut state, &ws, "t");
339        let (shown, parked) = (create_block(&mut state, &tab), create_block(&mut state, &tab));
340        update(&mut state, Command::ParkBlock { tab_id: tab.clone(), block_id: parked.clone() }, &ctx(2));
341
342        // A block that has a tab is not deleted by a tab-less delete.
343        assert!(update(&mut state, Command::DeleteBlock { tab_id: String::new(), block_id: shown.clone() }, &ctx(3)).is_empty());
344        assert!(state.blocks.contains_key(&shown));
345
346        let events = update(&mut state, Command::DeleteBlock { tab_id: String::new(), block_id: parked.clone() }, &ctx(4));
347        assert!(matches!(&events[..], [Event::BlockDeleted { tab_id, block_id, .. }] if tab_id.is_empty() && *block_id == parked));
348        assert!(!state.blocks.contains_key(&parked));
349        assert_eq!(state.tabs[&tab].block_ids, vec![shown], "the tab is untouched");
350        assert!(update(&mut state, Command::DeleteBlock { tab_id: String::new(), block_id: parked }, &ctx(5)).is_empty(), "again: nothing");
351    }
352
353    #[test]
354    fn attach_puts_a_parked_block_into_any_tab_at_a_clamped_index() {
355        let mut state = State::default();
356        let ws = create_workspace(&mut state, "w");
357        let (src, dst) = (create_tab(&mut state, &ws, "src"), create_tab(&mut state, &ws, "dst"));
358        let block = create_block(&mut state, &src);
359        let first = create_block(&mut state, &dst);
360        update(&mut state, Command::ParkBlock { tab_id: src.clone(), block_id: block.clone() }, &ctx(2));
361        let events = update(&mut state, Command::AttachBlock { block_id: block.clone(), dst_tab_id: dst.clone(), dst_index: 99 }, &ctx(3));
362        match &events[0] {
363            Event::BlockAttached { dst_index, .. } => assert_eq!(*dst_index, 1),
364            other => panic!("expected BlockAttached, got {:?}", other),
365        }
366        assert_eq!(state.tabs[&dst].block_ids, vec![first, block.clone()]);
367        assert_eq!(state.blocks[&block].tab_id, dst);
368        assert!(state.tabs[&src].block_ids.is_empty());
369    }
370
371    #[test]
372    fn attach_refuses_a_block_that_is_in_a_tab_and_unknown_ids() {
373        let mut state = State::default();
374        let ws = create_workspace(&mut state, "w");
375        let (a, b) = (create_tab(&mut state, &ws, "a"), create_tab(&mut state, &ws, "b"));
376        let block = create_block(&mut state, &a);
377        let attach = |block_id: &str, tab: &str| Command::AttachBlock { block_id: block_id.into(), dst_tab_id: tab.into(), dst_index: 0 };
378        let events = update(&mut state, attach(&block, &b), &ctx(2));
379        assert!(matches!(&events[0], Event::Error { message, .. } if message.contains("not parked")), "{events:?}");
380        assert!(matches!(&update(&mut state, attach("ghost", &b), &ctx(3))[0], Event::Error { .. }));
381        assert!(matches!(&update(&mut state, attach(&block, "ghost"), &ctx(4))[0], Event::Error { .. }));
382        assert_eq!(state.tabs[&a].block_ids, vec![block]);
383        assert!(state.tabs[&b].block_ids.is_empty());
384    }
385
386    #[test]
387    fn move_block_intra_tab_repositions() {
388        let mut state = State::default();
389        let ws = create_workspace(&mut state, "w");
390        let tab = create_tab(&mut state, &ws, "t");
391        let b1 = create_block(&mut state, &tab);
392        let b2 = create_block(&mut state, &tab);
393        let b3 = create_block(&mut state, &tab);
394        // Move b1 to position 2 (end after removal).
395        let events = update(
396            &mut state,
397            Command::MoveBlock {
398                block_id: b1.clone(),
399                src_tab_id: tab.clone(),
400                dst_tab_id: tab.clone(),
401                dst_index: 2,
402            },
403            &ctx(2),
404        );
405        match &events[0] {
406            Event::BlockMoved { dst_index, .. } => assert_eq!(*dst_index, 2),
407            other => panic!("expected BlockMoved, got {:?}", other),
408        }
409        assert_eq!(state.tabs[&tab].block_ids, vec![b2, b3, b1]);
410    }
411
412    #[test]
413    fn move_block_rejects_unknown_src_or_dst_or_block() {
414        let mut state = State::default();
415        let ws = create_workspace(&mut state, "w");
416        let tab = create_tab(&mut state, &ws, "t");
417        let other_tab = create_tab(&mut state, &ws, "other");
418        let block = create_block(&mut state, &tab);
419
420        let events = update(
421            &mut state,
422            Command::MoveBlock {
423                block_id: block.clone(),
424                src_tab_id: "ghost-src".into(),
425                dst_tab_id: other_tab.clone(),
426                dst_index: 0,
427            },
428            &ctx(2),
429        );
430        assert!(matches!(&events[0], Event::Error { .. }));
431
432        let events = update(
433            &mut state,
434            Command::MoveBlock {
435                block_id: block.clone(),
436                src_tab_id: tab.clone(),
437                dst_tab_id: "ghost-dst".into(),
438                dst_index: 0,
439            },
440            &ctx(3),
441        );
442        assert!(matches!(&events[0], Event::Error { .. }));
443
444        let events = update(
445            &mut state,
446            Command::MoveBlock {
447                block_id: "ghost-block".into(),
448                src_tab_id: tab,
449                dst_tab_id: other_tab,
450                dst_index: 0,
451            },
452            &ctx(4),
453        );
454        assert!(matches!(&events[0], Event::Error { .. }));
455    }
456
457    #[test]
458    fn move_block_rejects_when_block_belongs_to_different_tab() {
459        let mut state = State::default();
460        let ws = create_workspace(&mut state, "w");
461        let real_src = create_tab(&mut state, &ws, "real");
462        let other = create_tab(&mut state, &ws, "other");
463        let dst = create_tab(&mut state, &ws, "dst");
464        let block = create_block(&mut state, &real_src);
465        let events = update(
466            &mut state,
467            Command::MoveBlock {
468                block_id: block,
469                src_tab_id: other,
470                dst_tab_id: dst,
471                dst_index: 0,
472            },
473            &ctx(2),
474        );
475        match &events[0] {
476            Event::Error { message, .. } => {
477                assert!(message.contains("belongs to tab"), "got: {}", message);
478            }
479            other => panic!("expected Error, got {:?}", other),
480        }
481    }
482
483    #[test]
484    fn create_block_takes_its_id_from_ctx() {
485        let mut state = State::default();
486        let ws = create_workspace(&mut state, "w");
487        let tab = create_tab(&mut state, &ws, "t");
488        let events = update(
489            &mut state,
490            Command::CreateBlock { tab_id: tab.clone(), meta: serde_json::Value::Null },
491            &ctx_with_id("block-fixed"),
492        );
493        assert!(matches!(&events[0], Event::BlockCreated { block_id, .. } if block_id == "block-fixed"));
494        assert_eq!(state.tabs[&tab].block_ids, vec!["block-fixed".to_string()]);
495    }
496
497    #[test]
498    fn create_block_refuses_an_id_in_use() {
499        let mut state = State::default();
500        let ws = create_workspace(&mut state, "w");
501        let tab = create_tab(&mut state, &ws, "t");
502        let cmd = || Command::CreateBlock { tab_id: tab.clone(), meta: serde_json::Value::Null };
503        update(&mut state, cmd(), &ctx_with_id("dup"));
504        let events = update(&mut state, cmd(), &ctx_with_id("dup"));
505        assert!(matches!(&events[..], [Event::Error { message, .. }] if message.contains("already in use")));
506        assert_eq!(state.tabs[&tab].block_ids, vec!["dup".to_string()]);
507    }
508
509    #[test]
510    fn update_block_meta_passes_patch_through_without_touching_state() {
511        let mut state = State::default();
512        let ws = create_workspace(&mut state, "w");
513        let tab = create_tab(&mut state, &ws, "t");
514        let block = create_block(&mut state, &tab);
515        let before = state.blocks[&block].clone();
516        let patch = serde_json::json!({ "view": "term" });
517        let events = update(
518            &mut state,
519            Command::UpdateBlockMeta { block_id: block.clone(), meta_patch: patch.clone() },
520            &ctx(1),
521        );
522        assert!(matches!(
523            &events[..],
524            [Event::BlockMetaUpdated { block_id, meta_patch, .. }] if *block_id == block && *meta_patch == patch
525        ));
526        assert_eq!(state.blocks[&block], before);
527    }
528
529    #[test]
530    fn update_meta_of_unknown_block_errors() {
531        let mut state = State::default();
532        let events = update(
533            &mut state,
534            Command::UpdateBlockMeta { block_id: "ghost".into(), meta_patch: serde_json::json!({}) },
535            &ctx(1),
536        );
537        assert!(matches!(
538            &events[..],
539            [Event::Error { code: agentmux_common::ipc::ErrorCode::InvalidCommand, message, .. }]
540                if message.contains("UpdateBlockMeta")
541        ));
542    }
543}