Skip to main content

agentmux_srv/sagas/
delete_block.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Phase E.5.7 (Step 5 PR 1) — DeleteBlock saga.
5//
6// Replaces the SQLite-first delete pattern in `service.rs`'s
7// `("object", "DeleteBlock")` handler with a reducer-driven saga.
8// The legacy handler called `wcore::delete_block` first and then
9// dispatched `Command::DeleteBlock` to keep the reducer in sync — a
10// short-circuit that pre-dates the saga coordinator + persist
11// subscriber pattern (closes gap §4 in
12// `docs/retro/reducer-architecture-gaps-2026-05-01.md`).
13//
14// **Steps:**
15// 0. `agent_teardown::run` for the block, with the caller's policy
16//    (`Policy::close()` by default, `Policy::quit()` from `self_quit`) — the same graceful
17//    shutdown the pane's × uses (interrupt a running turn, EOF, force-kill
18//    only at the deadline, release its processes, save final state),
19//    BEFORE the records go (SPEC_AGENT_PANE_CLOSE_GRACEFUL_SHUTDOWN_2026_09_18.md
20//    §4.2).
21// 1. `DeleteBlock { tab_id, block_id }` — reducer removes the block
22//    from canonical state and emits `Event::BlockDeleted`. The
23//    persist subscriber writes SQLite via `wcore::delete_block`.
24// 2. `LayoutDeleteNodeByBlock` (SPEC_864 site #6) — reducer prunes the
25//    block from `db_layout`, the single writer's own copy of the tree.
26//    For one tab of a stacked pane it removes just that member and keeps
27//    the pane and its other tabs; the last member takes the leaf.
28// 2b. `queue_source_layout_delete` — tells any frontend that already
29//    has this tab's tree loaded (via `LayoutState.pendingbackendactions`)
30//    to prune the node too. Added after
31//    `INVESTIGATION_LAYOUT_DEAD_SPACE_STALE_TREE_RESURRECTION_2026_07_08.md`
32//    found that without this, step 2's direct backend write is
33//    invisible to an already-loaded frontend, whose next unrelated
34//    edit in the tab silently resurrects the just-pruned node as a
35//    dangling reference.
36//
37// **Block controller side-effect:** the process is stopped gracefully by
38// step 0. `blockcontroller::delete_controller` then runs AFTER the saga,
39// whenever the reducer has removed the block (see the round-3 note in
40// `run`); by then it is idempotent cleanup of an already-stopped
41// controller, not a kill. (This header used to say the controller was
42// killed before the reducer dispatch — the legacy RPC handler's order,
43// long since replaced; that stale line misled a reader into thinking this
44// saga hard-kills.)
45//
46// This saga is therefore the right primitive for a close srv starts
47// itself on one tab: unlike `close_pane::run` with one id, which queues a
48// frontend action only when the whole leaf goes, step 2b updates an
49// already-loaded frontend.
50//
51// **Compensation:** delete sagas are awkward to compensate — once
52// the block row + controller are gone, "un-delete" requires
53// reconstructing both the SQLite row and the PTY/process subtree,
54// neither of which is meaningful from saga state. We follow the
55// brief's pragma: log a warning on dispatch failure, no automatic
56// re-create. The reducer's `DeleteBlock` is silent-no-op on missing
57// inputs (see reducer.rs handle_delete_block), so the only failure
58// path is mstore write errors surfaced by the persist subscriber —
59// in which case the controller is already gone (intentional; the
60// PTY can't be partially-killed) and the SQLite row may or may not
61// have been written. PR 2's `compensate_unresolved` resume scan
62// surfaces these via the durable saga log for operator follow-up.
63//
64// **Pre-condition:** the block must exist in the reducer state.
65// Without this, the reducer would silently no-op (handle_delete_block
66// returns an empty event vec on missing tab/block) and the user
67// would see "delete succeeded" while nothing happened. The saga
68// surfaces a clear "block not found" error instead. We check the
69// reducer state (not SQLite) because `Command::DeleteBlock` carries
70// `tab_id` looked up from the block's owning record in srv state
71// (service.rs: `s.blocks[block_id].tab_id`) and we want to validate
72// against the reducer's view of (tab → blocks) — that's what the
73// dispatch will mutate.
74
75use agentmux_common::ipc::Command;
76use serde_json::{json, Value};
77
78use super::{
79    alloc_saga_id, classify_run_saga_result, emit_saga_started, emit_terminal, run_saga, SagaCtx,
80};
81use crate::server::AppState;
82
83/// Run the DeleteBlock saga. On success returns
84/// `{"block_id": "...", "tab_id": "..."}`.
85pub async fn run(
86    state: &AppState,
87    tab_id: String,
88    block_id: String,
89) -> Result<Value, String> {
90    run_with_policy(state, tab_id, block_id, super::agent_teardown::Policy::close()).await.0
91}
92
93/// [`run`] with the teardown policy for the block (`self_quit` passes
94/// `Policy::quit()`). Returns the saga's result and the teardown's report;
95/// the report is there whenever the teardown ran, even if the close then
96/// failed, and `None` only when the close failed before it.
97pub async fn run_with_policy(
98    state: &AppState,
99    tab_id: String,
100    block_id: String,
101    policy: super::agent_teardown::Policy,
102) -> (Result<Value, String>, Option<super::agent_teardown::TeardownReport>) {
103    let mut report = None;
104    let result = run_inner_with_policy(state, tab_id, block_id, policy, &mut report).await;
105    (result, report)
106}
107
108async fn run_inner_with_policy(
109    state: &AppState,
110    tab_id: String,
111    block_id: String,
112    policy: super::agent_teardown::Policy,
113    report_out: &mut Option<super::agent_teardown::TeardownReport>,
114) -> Result<Value, String> {
115    // Pre-condition: block exists and is in the named tab. Reducer
116    // would silent-no-op otherwise (see handle_delete_block); the
117    // saga surfaces a clear error instead.
118    {
119        let s = state.srv_state.lock().await;
120        match s.blocks.get(&block_id) {
121            None => {
122                return Err(format!("DeleteBlock: block not found: {}", block_id));
123            }
124            Some(block) if block.tab_id != tab_id => {
125                return Err(format!(
126                    "DeleteBlock: block {} is in tab {}, not {}",
127                    block_id, block.tab_id, tab_id
128                ));
129            }
130            _ => {}
131        }
132        // A parked block (an agent's, delete-agent only) is in no tab: `tab_id` is empty.
133        if !tab_id.is_empty() && !s.tabs.contains_key(&tab_id) {
134            return Err(format!("DeleteBlock: tab not found: {}", tab_id));
135        }
136    }
137
138    let saga_id = alloc_saga_id(state);
139    if let Err(e) = emit_saga_started(
140        state,
141        saga_id,
142        "delete_block",
143        json!({
144            "tab_id": &tab_id,
145            "block_id": &block_id,
146        }),
147    )
148    .await
149    {
150        return Err(e);
151    }
152    // Stop the block's process and save its final state BEFORE its records
153    // are deleted — the same per-agent order the pane's × uses
154    // (`close_pane`, SPEC_AGENT_PANE_CLOSE_GRACEFUL_SHUTDOWN_2026_09_18.md
155    // §4.2). Deleting first left the controller's own exit cleanup writing
156    // to a block that no longer existed. After `emit_saga_started`, so a
157    // saga-start collision still has no side effect (round 1 below).
158    *report_out = Some(super::agent_teardown::run(state, &block_id, policy).await);
159    let ctx = SagaCtx::new(state, saga_id);
160    let result = run_saga("delete_block", run_inner(ctx, tab_id, block_id.clone())).await;
161    // Controller-kill ordering. Three rounds of bot review:
162    //   * Round 1 (agent): killed BEFORE emit_saga_started → reagent
163    //     P2: side-effect leak if start_saga collides.
164    //   * Round 2 (this PR): conditional on result.is_ok() → codex P2
165    //     round 2: leaks PTY when reducer succeeds but
166    //     `apply_event_to_mstore` fails inside `SagaCtx::dispatch`
167    //     (block already removed from reducer state, RPC returns
168    //     error, retry pre-check sees "block not found" → controller
169    //     never cleaned up).
170    //   * Round 3 (this fix): kill controller whenever the reducer
171    //     dispatched DeleteBlock — i.e., whenever block was removed
172    //     from reducer state. This includes both success and the
173    //     reducer-succeeded-mstore-failed cases. We approximate this
174    //     by checking reducer state for the block: if it's gone, the
175    //     reducer dispatched (regardless of mstore outcome), so kill
176    //     the controller. Idempotent on missing controller.
177    {
178        let block_still_in_reducer =
179            state.srv_state.lock().await.blocks.contains_key(&block_id);
180        if !block_still_in_reducer {
181            crate::sagas::agent_teardown::discard(&block_id);
182            // MPS persist_map is keyed by (event, scope) and its key set is
183            // never otherwise pruned — a deleted block's persisted history
184            // (install_progress, block:activity, ...) would linger for the
185            // life of the process. Purge it alongside the controller kill.
186            state.broker.purge_scope(&format!("block:{}", block_id));
187        }
188    }
189    if let Err(reason) = &result {
190        // The pane is showing the shutdown log and waiting; tell it why.
191        super::close_pane::publish_shutdown_error(state, &block_id, reason);
192    }
193    super::close_pane::finish_close(state, &block_id).await;
194    emit_terminal(state, saga_id, classify_run_saga_result(&result)).await;
195    result
196}
197
198async fn run_inner(
199    ctx: SagaCtx<'_>,
200    tab_id: String,
201    block_id: String,
202) -> Result<Value, String> {
203    // Step 1: dispatch DeleteBlock through the reducer. The persist
204    // subscriber sees the BlockDeleted event and runs
205    // `wcore::delete_block` (SQLite row deletes; the layout prune moved
206    // to Step 2 — SPEC_864 site #6).
207    if let Err(reason) = ctx
208        .dispatch(Command::DeleteBlock {
209            tab_id: tab_id.clone(),
210            block_id: block_id.clone(),
211        })
212        .await
213    {
214        // No automatic compensation — un-deleting a block requires
215        // reconstructing both SQLite + PTY which we cannot do from
216        // saga state. Surface the failure; PR 2's restart-recovery
217        // scan picks up the durable log row for operator review.
218        tracing::warn!(
219            tab_id = %tab_id,
220            block_id = %block_id,
221            "[saga] DeleteBlock dispatch failed (no automatic compensation): {}",
222            reason
223        );
224        return Err(format!("DeleteBlock: {}", reason));
225    }
226
227    // Step 2 (SPEC_864 site #6): prune the deleted block's layout node
228    // through the reducer — the single writer of db_layout — instead of
229    // the retired wcore-direct prune the persist subscriber used to run.
230    // The reducer resolves block→node itself (it owns the tree) and
231    // silently no-ops when the block has no node (frontend already
232    // pushed a pruned tree, block never laid out, empty tab). The
233    // resulting `LayoutNodeDeleted{new_tree, tree_cleared}` event is
234    // what the subscriber persists.
235    //
236    // Best-effort, mirroring the old wcore prune's `let _ =
237    // store.update(&mut layout)`: a prune failure must not fail the
238    // block deletion itself (the block + controller are already gone).
239    //
240    // CORRECTION (found via INVESTIGATION_LAYOUT_DEAD_SPACE_STALE_TREE_
241    // RESURRECTION_2026_07_08.md): this comment used to claim "an
242    // orphaned node is exactly what the frontend's own delete-push
243    // converges away" — that's backwards. The frontend's `LayoutModel`
244    // doesn't auto-sync from a bare backend rootnode write (see
245    // `layout_helpers.rs::queue_target_layout_insert`'s doc comment); a
246    // frontend that already has this tab's tree loaded is never told
247    // this dispatch happened, so its *next* unrelated edit re-pushes
248    // its stale copy — still containing this node — and resurrects the
249    // dangling reference instead of converging it away. Step 2b below
250    // closes that gap via the same `pendingbackendactions` channel
251    // tear-off/redock already use for exactly this reason.
252    // A parked block has no tab, so no layout to prune.
253    if tab_id.is_empty() {
254        return Ok(json!({ "tab_id": tab_id, "block_id": block_id }));
255    }
256    if let Err(reason) = ctx
257        .dispatch(Command::LayoutDeleteNodeByBlock {
258            tab_id: tab_id.clone(),
259            block_id: block_id.clone(),
260            correlation_id: String::new(),
261        })
262        .await
263    {
264        tracing::warn!(
265            tab_id = %tab_id,
266            block_id = %block_id,
267            "[saga] LayoutDeleteNodeByBlock dispatch failed (best-effort; the layout keeps a leaf for a deleted block until the next layout write prunes it): {}",
268            reason
269        );
270    }
271
272    // Step 2b: tell any frontend that already has this tab's layout
273    // tree loaded to prune the node too, via the same pendingbackendactions
274    // channel `queue_source_layout_delete` already uses for tear-off's
275    // source-tab prune. Without this, Step 2's direct reducer write is
276    // invisible to an already-loaded frontend, and its next unrelated
277    // edit in this tab resurrects the just-deleted node as a dangling
278    // reference (empty/dead pane). Best-effort for the same reason as
279    // Step 2 — the block is already gone either way.
280    if let Err(reason) =
281        crate::server::service::layout_helpers::queue_source_layout_delete(
282            ctx.state, &tab_id, &block_id,
283        )
284        .await
285    {
286        tracing::warn!(
287            tab_id = %tab_id,
288            block_id = %block_id,
289            "[saga] queue_source_layout_delete failed (best-effort; a frontend with a stale loaded copy of this tab may resurrect the node): {}",
290            reason
291        );
292    }
293
294    Ok(json!({
295        "tab_id": tab_id,
296        "block_id": block_id,
297    }))
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303    use crate::backend::obj::Block;
304    use crate::server::tests::{dispatch_apply, test_state};
305    use agentmux_common::ipc::Event;
306
307    /// Seed a workspace + tab + block and return their ids.
308    async fn seed() -> (
309        crate::server::AppState,
310        String, // workspace_id
311        String, // tab_id
312        String, // block_id
313    ) {
314        let state = test_state();
315        let ws_evs = dispatch_apply(
316            &state,
317            agentmux_common::ipc::Command::CreateWorkspace { name: "w".into() },
318        )
319        .await;
320        let ws_id = ws_evs
321            .iter()
322            .find_map(|e| match e {
323                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
324                _ => None,
325            })
326            .unwrap();
327        let tab_evs = dispatch_apply(
328            &state,
329            agentmux_common::ipc::Command::CreateTab {
330                workspace_id: ws_id.clone(),
331                name: "t".into(),
332            },
333        )
334        .await;
335        let tab_id = tab_evs
336            .iter()
337            .find_map(|e| match e {
338                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
339                _ => None,
340            })
341            .unwrap();
342        let blk_evs = dispatch_apply(
343            &state,
344            agentmux_common::ipc::Command::CreateBlock {
345                tab_id: tab_id.clone(),
346                meta: serde_json::Value::Null,
347            },
348        )
349        .await;
350        let block_id = blk_evs
351            .iter()
352            .find_map(|e| match e {
353                Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
354                _ => None,
355            })
356            .unwrap();
357        (state, ws_id, tab_id, block_id)
358    }
359
360    #[tokio::test]
361    async fn happy_path_removes_block_from_reducer_and_sqlite() {
362        let (state, _ws_id, tab_id, block_id) = seed().await;
363
364        // Sanity: block is present pre-delete.
365        {
366            let s = state.srv_state.lock().await;
367            assert!(s.blocks.contains_key(&block_id));
368            assert_eq!(s.tabs[&tab_id].block_ids, vec![block_id.clone()]);
369        }
370        assert!(state.mstore.get::<Block>(&block_id).unwrap().is_some());
371
372        let result = run(&state, tab_id.clone(), block_id.clone()).await.unwrap();
373        assert_eq!(result["block_id"], block_id);
374        assert_eq!(result["tab_id"], tab_id);
375
376        // Reducer: block gone, tab's block_ids empty.
377        let s = state.srv_state.lock().await;
378        assert!(!s.blocks.contains_key(&block_id));
379        assert!(s.tabs[&tab_id].block_ids.is_empty());
380        drop(s);
381
382        // SQLite: block gone.
383        assert!(state.mstore.get::<Block>(&block_id).unwrap().is_none());
384    }
385
386    #[tokio::test]
387    async fn saga_prunes_layout_through_reducer_coherently() {
388        // SPEC_864 site #6 — the layout prune is Step 2 of this saga
389        // (Command::LayoutDeleteNodeByBlock), not the retired
390        // wcore-direct write in the persist subscriber. Invariant:
391        // after the saga, the reducer's TabRecord tree and
392        // db_layout's rootnode agree (single-writer coherence), and a
393        // single-block tree ends genuinely empty on both sides.
394        let (state, _ws_id, tab_id, block_id) = seed().await;
395
396        // Seed a layout tree holding the block, reducer-routed +
397        // persisted (the LayoutSetTree path srv's seeders use).
398        let tree = agentmux_common::LayoutNode {
399            id: "n-solo".into(),
400            data: Some(agentmux_common::LayoutNodeData {
401                block_id: block_id.clone(),
402                ..Default::default()
403            }),
404            ..Default::default()
405        };
406        dispatch_apply(
407            &state,
408            agentmux_common::ipc::Command::LayoutSetTree {
409                tab_id: tab_id.clone(),
410                new_tree: Some(tree),
411                correlation_id: String::new(),
412                slices: None,
413            },
414        )
415        .await;
416        // Sanity: reducer + SQLite both hold the seeded tree.
417        {
418            let s = state.srv_state.lock().await;
419            assert!(s.tabs[&tab_id].rootnode.is_some());
420        }
421        let layout_id = state
422            .mstore
423            .get::<crate::backend::obj::Tab>(&tab_id)
424            .unwrap()
425            .unwrap()
426            .layoutstate;
427        assert!(state
428            .mstore
429            .get::<crate::backend::obj::LayoutState>(&layout_id)
430            .unwrap()
431            .unwrap()
432            .rootnode
433            .is_some());
434
435        run(&state, tab_id.clone(), block_id.clone()).await.unwrap();
436
437        // Reducer tree: pruned to empty (block was the sole leaf).
438        {
439            let s = state.srv_state.lock().await;
440            assert!(
441                s.tabs[&tab_id].rootnode.is_none(),
442                "reducer tree must be pruned by the saga's Step-2 dispatch"
443            );
444        }
445        // db_layout: matches the reducer (tree_cleared persisted the wipe).
446        assert!(
447            state
448                .mstore
449                .get::<crate::backend::obj::LayoutState>(&layout_id)
450                .unwrap()
451                .unwrap()
452                .rootnode
453                .is_none(),
454            "db_layout must agree with the reducer post-saga (single-writer coherence)"
455        );
456    }
457
458    #[tokio::test]
459    async fn saga_queues_a_pendingbackendactions_delete_for_a_stale_frontend() {
460        // Regression test for
461        // INVESTIGATION_LAYOUT_DEAD_SPACE_STALE_TREE_RESURRECTION_2026_07_08.md:
462        // Step 2 (LayoutDeleteNodeByBlock) alone prunes db_layout correctly
463        // but is invisible to a frontend that already has this tab's tree
464        // loaded — its next unrelated edit re-pushes its stale copy and
465        // resurrects the just-deleted node. Step 2b must queue a "delete"
466        // pendingbackendactions entry so that frontend converges instead.
467        let (state, _ws_id, tab_id, block_id) = seed().await;
468
469        let tree = agentmux_common::LayoutNode {
470            id: "n-solo".into(),
471            data: Some(agentmux_common::LayoutNodeData {
472                block_id: block_id.clone(),
473                ..Default::default()
474            }),
475            ..Default::default()
476        };
477        dispatch_apply(
478            &state,
479            agentmux_common::ipc::Command::LayoutSetTree {
480                tab_id: tab_id.clone(),
481                new_tree: Some(tree),
482                correlation_id: String::new(),
483                slices: None,
484            },
485        )
486        .await;
487
488        run(&state, tab_id.clone(), block_id.clone()).await.unwrap();
489
490        let tab = state
491            .mstore
492            .must_get::<crate::backend::obj::Tab>(&tab_id)
493            .unwrap();
494        let layout = state
495            .mstore
496            .must_get::<crate::backend::obj::LayoutState>(&tab.layoutstate)
497            .unwrap();
498        let actions = layout.pendingbackendactions.unwrap_or_default();
499        let delete_action = actions
500            .iter()
501            .find(|a| a.actiontype == "delete" && a.blockid == block_id);
502        assert!(
503            delete_action.is_some(),
504            "expected a queued 'delete' pendingbackendactions entry for the pruned block \
505             (matches LayoutTreeActionType.DeleteNode in frontend/layout/lib/types.ts), got: {actions:?}"
506        );
507    }
508
509    /// SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §2.2: deleting one tab
510    /// of a stacked pane (e.g. a terminal tab whose shell exited —
511    /// close-on-exit runs this saga) keeps the pane and its other tabs. It
512    /// used to delete the whole leaf, leaving the sibling (an agent, say)
513    /// running with no pane.
514    #[tokio::test]
515    async fn deleting_one_tab_of_a_stacked_pane_keeps_the_pane_and_its_sibling() {
516        let (state, _ws_id, tab_id, agent) = seed().await;
517        let term = dispatch_apply(
518            &state,
519            agentmux_common::ipc::Command::CreateBlock {
520                tab_id: tab_id.clone(),
521                meta: serde_json::Value::Null,
522            },
523        )
524        .await
525        .iter()
526        .find_map(|e| match e {
527            Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
528            _ => None,
529        })
530        .unwrap();
531        dispatch_apply(
532            &state,
533            agentmux_common::ipc::Command::LayoutSetTree {
534                tab_id: tab_id.clone(),
535                new_tree: Some(agentmux_common::LayoutNode {
536                    id: "pane".into(),
537                    data: Some(agentmux_common::LayoutNodeData {
538                        block_id: term.clone(),
539                        block_stack: vec![agent.clone(), term.clone()],
540                        active_block_id: term.clone(),
541                        ..Default::default()
542                    }),
543                    ..Default::default()
544                }),
545                correlation_id: String::new(),
546                slices: None,
547            },
548        )
549        .await;
550
551        run(&state, tab_id.clone(), term.clone()).await.unwrap();
552
553        let s = state.srv_state.lock().await;
554        assert!(s.blocks.contains_key(&agent), "sibling block survives");
555        let leaf = s.tabs[&tab_id].rootnode.as_ref().expect("the pane survives");
556        let data = leaf.data.as_ref().unwrap();
557        assert_eq!(data.block_stack, vec![agent.clone()]);
558        assert_eq!(data.block_id, agent, "the sibling becomes the visible tab");
559    }
560
561    #[tokio::test]
562    async fn rejects_when_block_not_found() {
563        let (state, _ws_id, tab_id, _block_id) = seed().await;
564        let err = run(&state, tab_id, "ghost-block".into()).await.unwrap_err();
565        assert!(err.contains("block not found"), "got: {}", err);
566    }
567
568    #[tokio::test]
569    async fn rejects_when_block_in_different_tab() {
570        let (state, _ws_id, tab_id, block_id) = seed().await;
571        // Create a second tab; ask to delete block via that tab's id.
572        let tab_evs = dispatch_apply(
573            &state,
574            agentmux_common::ipc::Command::CreateTab {
575                workspace_id: _ws_id.clone(),
576                name: "other".into(),
577            },
578        )
579        .await;
580        let other_tab = tab_evs
581            .iter()
582            .find_map(|e| match e {
583                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
584                _ => None,
585            })
586            .unwrap();
587        let err = run(&state, other_tab, block_id.clone()).await.unwrap_err();
588        assert!(
589            err.contains("is in tab") && err.contains(&tab_id),
590            "got: {}",
591            err
592        );
593        // Block must still be present (saga rejected pre-dispatch).
594        let s = state.srv_state.lock().await;
595        assert!(s.blocks.contains_key(&block_id));
596    }
597}