Skip to main content

agentmux_srv/sagas/
close_pane.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// ClosePane saga — closes every block in a pane, each one stopped before its
5// records are deleted. docs/specs/SPEC_AGENT_PANE_CLOSE_GRACEFUL_SHUTDOWN_2026_09_18.md
6//
7// A pane (layout leaf) can hold several blocks as tabs (`block_stack`). The
8// pane's × used to send one `DeleteBlock` for the visible tab only, leaving
9// every other tab's agent running with no pane (§2 of the spec), and the
10// `ClosePane` MCP tool had the same gap (#3202). This saga takes the whole set.
11//
12// **Steps (§4.2, §9.2):**
13// 1. `agent_teardown::run_many(.., Policy::close())` over every block at
14//    once, one deadline (SPEC_AGENT_TEARDOWN_SINGLE_PATH_2026_10_01.md): refuse
15//    respawn and messaging delivery, interrupt any turn, let the process
16//    exit (force-kill at the deadline), THEN drop its process tracker, then
17//    save final state (`session:active_pid` cleared, instance row `stopped`
18//    + `ended_at`) while the block record still exists.
19// 2. `DeleteBlock { tab_id, block_id }` through the reducer, per block.
20//
21// **Then, once for the pane:** if every member of the leaf is gone, delete
22// the leaf (`LayoutDeleteNode`) and queue one frontend `delete` for it.
23// A leaf that still has a live member keeps its pane: closing one tab of a
24// stack must never take its siblings with it. Just the closed tabs leave
25// srv's tree (`LayoutDeleteNodeByBlock`), whichever frontend flow closed them.
26//
27// **Compensation:** none, same as `delete_block` — a stopped process and a
28// deleted record cannot be recreated from saga state. A block whose
29// `DeleteBlock` dispatch fails stays in the tab with its process stopped;
30// closing it again finishes the job.
31
32use agentmux_common::ipc::Command;
33use serde_json::{json, Value};
34
35use super::{
36    alloc_saga_id, classify_run_saga_result, emit_saga_started, emit_terminal, run_saga, SagaCtx,
37};
38use crate::backend::blockcontroller;
39use crate::server::AppState;
40
41/// Close `block_ids` (normally every member of one pane's stack). Ids that no
42/// longer exist are skipped; ids in different tabs are rejected. On success
43/// returns `{"tab_id": "...", "block_ids": [...closed...], "leaf_removed": bool}`.
44pub async fn run(state: &AppState, block_ids: Vec<String>) -> Result<Value, String> {
45    run_with(state, block_ids, CloseOpts::default()).await
46}
47
48/// How the caller's frontend handles the layout.
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub struct CloseOpts {
51    /// The frontend kept the pane on screen (showing the shutdown log,
52    /// SPEC_AGENT_SELF_QUIT_2026_09_24.md §5.5) instead of removing it first,
53    /// so srv must queue a frontend `delete` for EVERY closed member — the
54    /// frontend removes each as it arrives, the last one taking the pane.
55    /// `false` (the historical flow): the frontend already removed what it
56    /// closed, and one `delete` for the visible block covers a whole leaf.
57    pub frontend_waits: bool,
58    /// Park the agents' blocks whatever `agents:always_available` says: the explicit detach
59    /// (`Agents detach`), where the setting only decides what a plain close does.
60    pub park_agents: bool,
61}
62
63pub async fn run_with(state: &AppState, block_ids: Vec<String>, opts: CloseOpts) -> Result<Value, String> {
64    let mut ids: Vec<String> = Vec::new();
65    for id in block_ids {
66        if !id.is_empty() && !ids.contains(&id) {
67            ids.push(id);
68        }
69    }
70    if ids.is_empty() {
71        return Err("ClosePane: no block ids".to_string());
72    }
73
74    let (tab_id, present, leaf_to_delete) = {
75        let s = state.srv_state.lock().await;
76        let mut tab_id: Option<String> = None;
77        let mut present = Vec::new();
78        for id in &ids {
79            let Some(block) = s.blocks.get(id) else {
80                continue; // already gone
81            };
82            match &tab_id {
83                None => tab_id = Some(block.tab_id.clone()),
84                Some(t) if *t != block.tab_id => {
85                    return Err(format!(
86                        "ClosePane: blocks span tabs ({} is in {}, not {})",
87                        id, block.tab_id, t
88                    ));
89                }
90                Some(_) => {}
91            }
92            present.push(id.clone());
93        }
94        let Some(tab_id) = tab_id else {
95            return Err(format!("ClosePane: block not found: {}", ids.join(", ")));
96        };
97        if !s.tabs.contains_key(&tab_id) {
98            return Err(format!("ClosePane: tab not found: {}", tab_id));
99        }
100        // The leaf to remove: the one holding these blocks, and only if none
101        // of its members survives this close.
102        let leaf_to_delete = s
103            .tabs
104            .get(&tab_id)
105            .and_then(|t| t.rootnode.as_ref())
106            .and_then(|root| {
107                present
108                    .iter()
109                    .find_map(|id| crate::backend::layout::find_leaf_containing_block(root, id))
110            })
111            .and_then(|leaf| {
112                let data = leaf.data.as_ref()?;
113                let all_closing = crate::backend::layout::leaf_members(data)
114                    .iter()
115                    .all(|m| ids.contains(m) || !s.blocks.contains_key(m));
116                all_closing.then(|| (leaf.id.clone(), data.block_id.clone()))
117            });
118        (tab_id, present, leaf_to_delete)
119    };
120
121    let saga_id = alloc_saga_id(state);
122    emit_saga_started(
123        state,
124        saga_id,
125        "close_pane",
126        json!({
127            "tab_id": &tab_id,
128            "block_ids": &present,
129        }),
130    )
131    .await?;
132    let ctx = SagaCtx::new(state, saga_id);
133    let result = run_saga(
134        "close_pane",
135        run_inner(ctx, tab_id, present.clone(), leaf_to_delete, opts, gone_before(&ids, &present)),
136    )
137    .await;
138    for id in &present {
139        finish_close(state, id).await;
140    }
141    emit_terminal(state, saga_id, classify_run_saga_result(&result)).await;
142    result
143}
144
145async fn run_inner(
146    ctx: SagaCtx<'_>,
147    tab_id: String,
148    block_ids: Vec<String>,
149    leaf_to_delete: Option<(String, String)>,
150    opts: CloseOpts,
151    // Asked for, but already gone before this close: a waiting frontend still
152    // shows them, so they get a frontend `delete` too.
153    gone: Vec<String>,
154) -> Result<Value, String> {
155    let mut failures = Vec::new();
156    let mut failed_ids: Vec<&String> = Vec::new();
157    // An agent's block outlives its pane when `agents:always_available` is on: parked, not stopped
158    // or deleted. Its pane leaves the layout below like any other member's.
159    let parked = super::park_agents::park_agent_blocks(&ctx, &block_ids, opts.park_agents).await;
160    // An explicit park never falls through to a stop and a delete: what could not be parked stays as it is.
161    if opts.park_agents {
162        let left = super::park_agents::not_parked(&block_ids, &parked);
163        if !left.is_empty() {
164            return Err(format!("ClosePane: could not park {}: it is left running and in its pane", left.join(", ")));
165        }
166    }
167    let closing = super::park_agents::not_parked(&block_ids, &parked);
168    super::agent_teardown::run_many(ctx.state, &closing, super::agent_teardown::Policy::close()).await;
169    for block_id in &closing {
170        if let Err(reason) = ctx
171            .dispatch(Command::DeleteBlock {
172                tab_id: tab_id.clone(),
173                block_id: block_id.clone(),
174            })
175            .await
176        {
177            tracing::warn!(
178                tab_id = %tab_id,
179                block_id = %block_id,
180                "[saga] ClosePane: DeleteBlock dispatch failed (process already stopped): {}",
181                reason
182            );
183            failures.push(format!("{block_id}: {reason}"));
184            failed_ids.push(block_id);
185        }
186    }
187
188    // A member whose delete failed still exists; removing the leaf now would
189    // leave it in the tab with no pane — the orphan this saga exists to
190    // prevent. Return before touching the layout (as `delete_block` does);
191    // the pane stays, and closing it again finishes the job.
192    if !failures.is_empty() {
193        // A waiting frontend still shows every member, including the ones
194        // that DID close — tell it to drop those, or they'd stay on screen
195        // with nothing behind them (ReAgent P1 on #3784). The failed ones stay
196        // and show the error.
197        if opts.frontend_waits {
198            let mut closed: Vec<String> = block_ids.iter().filter(|id| !failed_ids.contains(id)).cloned().collect();
199            closed.extend(gone.iter().cloned());
200            queue_member_deletes(ctx.state, &tab_id, &closed).await;
201        }
202        // Only the members that failed show the error; the ones that closed
203        // are on their way out (ReAgent P2 on #3784).
204        let reason = format!("ClosePane: {}", failures.join("; "));
205        for id in &failed_ids {
206            publish_shutdown_error(ctx.state, id, &reason);
207        }
208        return Err(reason);
209    }
210
211    let leaf_removed = leaf_to_delete.is_some();
212    // A kept pane loses just these tabs in srv's own tree too, before any
213    // frontend is told: the frontend shows srv's stored tree whenever its own
214    // differs (#4946), so a member left here came back as a "(No View)" tab.
215    // Removing a member no pane holds any more (the frontend's own
216    // `pane.removeTab` got there first) changes nothing.
217    if !leaf_removed {
218        for block_id in block_ids.iter().chain(gone.iter()) {
219            if let Err(reason) = ctx
220                .dispatch(Command::LayoutDeleteNodeByBlock {
221                    tab_id: tab_id.clone(),
222                    block_id: block_id.clone(),
223                    correlation_id: String::new(),
224                })
225                .await
226            {
227                tracing::warn!(
228                    tab_id = %tab_id,
229                    block_id = %block_id,
230                    "[saga] ClosePane: LayoutDeleteNodeByBlock failed (best-effort): {}",
231                    reason
232                );
233            }
234        }
235    }
236    // srv's tree loses the pane BEFORE any frontend is told to (what `delete_block` does too): the
237    // frontend shows srv's stored tree whenever its own differs, and reads it at the moment the queued
238    // action reaches it. Queued first, the row it read was the one with the pane still in it, and when
239    // the row that followed didn't reach it, it showed the pane again with nothing behind it: an empty
240    // spot in the layout, now and then, for as long as the tab stayed open. Queued after, every row
241    // that holds the `delete` also holds the tree without the pane.
242    if let Some((node_id, _)) = &leaf_to_delete {
243        // Best-effort, as in `delete_block`: the blocks are already gone.
244        if let Err(reason) = ctx
245            .dispatch(Command::LayoutDeleteNode {
246                tab_id: tab_id.clone(),
247                node_id: node_id.clone(),
248                correlation_id: String::new(),
249            })
250            .await
251        {
252            tracing::warn!(
253                tab_id = %tab_id,
254                node_id = %node_id,
255                "[saga] ClosePane: LayoutDeleteNode failed (best-effort): {}",
256                reason
257            );
258        }
259    }
260    tell_frontend(ctx.state, &tab_id, &block_ids, &gone, leaf_to_delete.as_ref(), opts.frontend_waits).await;
261
262    Ok(json!({
263        "tab_id": tab_id,
264        "block_ids": block_ids,
265        "leaf_removed": leaf_removed,
266    }))
267}
268
269/// Tell the window the pane is gone, after srv's own tree already lost it. A window that still shows
270/// every member (`frontend_waits`, §5.5) gets one `delete` each, in one batch: its handler removes just
271/// that member, and the last one removes the leaf. That is queued whether or not the leaf goes, since
272/// closing one tab of a kept pane needs it just as much. Otherwise one `delete` for the pane, keyed on
273/// its visible block, not one per member, which is what produced the "could not find leaf node with
274/// blockId" errors when each member sent its own.
275async fn tell_frontend(
276    state: &AppState,
277    tab_id: &str,
278    block_ids: &[String],
279    gone: &[String],
280    leaf_to_delete: Option<&(String, String)>,
281    frontend_waits: bool,
282) {
283    if frontend_waits {
284        let closed: Vec<String> = block_ids.iter().chain(gone).cloned().collect();
285        queue_member_deletes(state, tab_id, &closed).await;
286    } else if let Some((_, visible_block_id)) = leaf_to_delete {
287        if let Err(reason) =
288            crate::server::service::layout_helpers::queue_source_layout_delete(state, tab_id, visible_block_id).await
289        {
290            tracing::warn!(
291                tab_id = %tab_id,
292                block_id = %visible_block_id,
293                "[saga] ClosePane: queue_source_layout_delete failed (best-effort): {}",
294                reason
295            );
296        }
297    }
298}
299
300/// Serialises tab closes within one workspace, from `delete_tab`'s last-tab
301/// pre-check through its `DeleteTab` dispatch (spec §9.5). One lock per
302/// workspace id; entries are tiny and bounded by the number of workspaces.
303pub(crate) async fn workspace_close_lock(workspace_id: &str) -> tokio::sync::OwnedMutexGuard<()> {
304    static LOCKS: std::sync::LazyLock<
305        std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>,
306    > = std::sync::LazyLock::new(Default::default);
307    let lock = LOCKS
308        .lock()
309        .unwrap()
310        .entry(workspace_id.to_string())
311        .or_default()
312        .clone();
313    lock.lock_owned().await
314}
315
316/// The requested ids that no longer existed when this close began.
317fn gone_before(requested: &[String], present: &[String]) -> Vec<String> {
318    requested.iter().filter(|id| !present.contains(id)).cloned().collect()
319}
320
321/// One frontend `delete` per closed member, in one batch (best-effort: the
322/// blocks are already gone).
323async fn queue_member_deletes(state: &AppState, tab_id: &str, block_ids: &[String]) {
324    if block_ids.is_empty() {
325        return;
326    }
327    let actions = block_ids
328        .iter()
329        .map(|id| crate::server::service::layout_helpers::source_delete_action(id))
330        .collect();
331    if let Err(reason) = crate::server::service::reducer_helpers::queue_layout_actions_via_reducer(state, tab_id, actions).await {
332        tracing::warn!(tab_id = %tab_id, "[saga] ClosePane: queueing frontend deletes failed (best-effort): {}", reason);
333    }
334}
335
336#[cfg(test)]
337pub(crate) use crate::backend::shutdown_events::EVENT_AGENT_SHUTDOWN;
338pub use crate::backend::shutdown_events::{ShutdownExtra, ShutdownLineEvent, ShutdownProcess};
339
340/// The extra for a line about one of the agent's processes.
341pub(crate) fn process_extra(pid: u32, command: &str, outcome: &str) -> ShutdownExtra {
342    ShutdownExtra { process: Some(ShutdownProcess { pid, name: short_command(command), outcome: outcome.to_string() }), ..Default::default() }
343}
344
345/// Orders the lines: strictly increasing across the process, so per block too.
346static SHUTDOWN_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
347
348/// Display lines stay one short line (spec §12.1).
349const SHUTDOWN_LINE_MAX: usize = 80;
350
351fn clip(s: &str, max: usize) -> String {
352    if s.chars().count() <= max {
353        return s.to_string();
354    }
355    let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
356    out.push('…');
357    out
358}
359
360/// The program and its first arguments — enough to recognise it.
361pub(crate) fn short_command(command: &str) -> String {
362    let command = command.trim();
363    if command.is_empty() {
364        return "process".to_string();
365    }
366    clip(command, 48)
367}
368
369pub(crate) fn process_line(command: &str, pid: u32, killed: bool) -> String {
370    clip(&format!("{} (pid {pid}) — {}", short_command(command), if killed { "killed" } else { "stopped" }), SHUTDOWN_LINE_MAX)
371}
372
373/// The agent-process line for a shutdown outcome: `(step, text, extra)`.
374pub(crate) fn exit_line(
375    label: &str,
376    outcome: &blockcontroller::StopOutcome,
377    elapsed: std::time::Duration,
378) -> (&'static str, String, ShutdownExtra) {
379    use blockcontroller::StopOutcome::*;
380    match outcome {
381        Killed => (
382            "kill",
383            clip(&format!("{label} — killed after {} s", elapsed.as_secs().max(1)), SHUTDOWN_LINE_MAX),
384            ShutdownExtra { forced_after_ms: Some(elapsed.as_millis() as u64), ..Default::default() },
385        ),
386        Exited => ("exit", clip(&format!("{label} — exited"), SHUTDOWN_LINE_MAX), ShutdownExtra::default()),
387        Stopped => ("exit", clip(&format!("{label} — stopped"), SHUTDOWN_LINE_MAX), ShutdownExtra::default()),
388        NotRunning => ("exit", clip(&format!("{label} — was not running"), SHUTDOWN_LINE_MAX), ShutdownExtra::default()),
389    }
390}
391
392/// Publish one `agent:shutdown` line, scoped to the block. Display only: the
393/// saga's own result stays the source of truth.
394pub(crate) fn publish_shutdown(state: &AppState, block_id: &str, step: &str, text: String, extra: ShutdownExtra) {
395    let line = ShutdownLineEvent {
396        block_id: block_id.to_string(),
397        seq: SHUTDOWN_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
398        step: step.to_string(),
399        text,
400        extra,
401    };
402    state.broker.publish_event::<crate::backend::mps_events::AgentShutdown>(&line, vec![format!("block:{block_id}")], 0);
403}
404
405/// A close that failed after its shutdown: the pane stays open showing why.
406pub(crate) fn publish_shutdown_error(state: &AppState, block_id: &str, reason: &str) {
407    publish_shutdown(
408        state,
409        block_id,
410        "error",
411        clip(&format!("couldn't close: {reason}"), SHUTDOWN_LINE_MAX),
412        ShutdownExtra { error: Some(reason.to_string()), ..Default::default() },
413    );
414}
415
416/// Clear `session:active_pid` (so the next boot doesn't read this as an
417/// interrupted session) and mark the local instance row stopped. The session
418/// id itself is left everywhere it is — block meta, instance row, shared
419/// registry — so reopening the agent resumes it (spec §4.2 step 6).
420pub(crate) fn save_final_state(state: &AppState, block_id: &str) {
421    use crate::backend::blockcontroller::session_recovery;
422
423    let has_active_pid = state
424        .mstore
425        .get::<crate::backend::obj::Block>(block_id)
426        .ok()
427        .flatten()
428        .is_some_and(|b| {
429            b.meta
430                .get(session_recovery::META_SESSION_ACTIVE_PID)
431                .is_some_and(|v| !v.is_null())
432        });
433    if has_active_pid {
434        session_recovery::clear_active_pid(&state.mstore, block_id);
435    }
436
437    match state.mstore.instance_get_by_block_id(block_id) {
438        Ok(Some(instance)) => {
439            let now_ms = agentmux_common::time::now_ms();
440            let upd = crate::backend::storage::agents::InstanceUpdate {
441                status: Some(
442                    crate::backend::storage::agents::InstanceStatus::Stopped
443                        .as_str()
444                        .to_string(),
445                ),
446                ended_at: Some(now_ms),
447                ..Default::default()
448            };
449            if let Err(e) = state.mstore.instance_update_partial(&instance.id, &upd) {
450                tracing::warn!(
451                    block_id = %block_id,
452                    instance_id = %instance.id,
453                    error = %e,
454                    "ClosePane: failed to mark instance stopped"
455                );
456            }
457        }
458        Ok(None) => {}
459        Err(e) => {
460            tracing::debug!(block_id = %block_id, error = %e, "ClosePane: instance lookup failed");
461        }
462    }
463}
464
465/// After the saga: purge the block's persisted broker history and its tool
466/// statuses, and lift the respawn guard. If the block somehow survived
467/// (dispatch failed), it keeps its stopped state and can be closed again.
468pub(crate) async fn finish_close(state: &AppState, block_id: &str) {
469    let gone = !state.srv_state.lock().await.blocks.contains_key(block_id);
470    if gone {
471        state.broker.purge_scope(&format!("block:{}", block_id));
472        state.dock_snapshots.evict_block(block_id);
473    }
474    blockcontroller::unmark_closing(block_id);
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480    use crate::backend::obj::Block;
481    use crate::server::tests::{dispatch_apply, test_state};
482    use agentmux_common::ipc::Event;
483
484    async fn seed_tab(state: &AppState) -> (String, String) {
485        let ws_id = dispatch_apply(state, Command::CreateWorkspace { name: "w".into() })
486            .await
487            .iter()
488            .find_map(|e| match e {
489                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
490                _ => None,
491            })
492            .unwrap();
493        let tab_id = dispatch_apply(
494            state,
495            Command::CreateTab {
496                workspace_id: ws_id.clone(),
497                name: "t".into(),
498            },
499        )
500        .await
501        .iter()
502        .find_map(|e| match e {
503            Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
504            _ => None,
505        })
506        .unwrap();
507        (ws_id, tab_id)
508    }
509
510    async fn seed_block(state: &AppState, tab_id: &str) -> String {
511        dispatch_apply(
512            state,
513            Command::CreateBlock {
514                tab_id: tab_id.to_string(),
515                meta: serde_json::Value::Null,
516            },
517        )
518        .await
519        .iter()
520        .find_map(|e| match e {
521            Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
522            _ => None,
523        })
524        .unwrap()
525    }
526
527    fn stack_leaf(id: &str, stack: &[&str], visible: &str) -> agentmux_common::LayoutNode {
528        agentmux_common::LayoutNode {
529            id: id.into(),
530            data: Some(agentmux_common::LayoutNodeData {
531                block_id: visible.to_string(),
532                block_stack: stack.iter().map(|s| s.to_string()).collect(),
533                active_block_id: visible.to_string(),
534                ..Default::default()
535            }),
536            ..Default::default()
537        }
538    }
539
540    async fn set_tree(state: &AppState, tab_id: &str, tree: agentmux_common::LayoutNode) {
541        dispatch_apply(
542            state,
543            Command::LayoutSetTree {
544                tab_id: tab_id.to_string(),
545                new_tree: Some(tree),
546                correlation_id: String::new(),
547                slices: None,
548            },
549        )
550        .await;
551    }
552
553    fn queued_deletes(state: &AppState, tab_id: &str) -> Vec<String> {
554        let tab = state.mstore.must_get::<crate::backend::obj::Tab>(tab_id).unwrap();
555        let layout = state
556            .mstore
557            .must_get::<crate::backend::obj::LayoutState>(&tab.layoutstate)
558            .unwrap();
559        layout
560            .pendingbackendactions
561            .unwrap_or_default()
562            .into_iter()
563            .filter(|a| a.actiontype == "delete")
564            .map(|a| a.blockid)
565            .collect()
566    }
567
568    /// The incident (spec §2): a pane holding [A, B, C] with A visible. Closing
569    /// it must remove all three blocks, not just A, and prune the leaf once.
570    #[tokio::test]
571    async fn a_waiting_frontend_gets_one_delete_per_member_for_a_whole_pane() {
572        let state = test_state();
573        let (_ws, tab_id) = seed_tab(&state).await;
574        let a = seed_block(&state, &tab_id).await;
575        let b = seed_block(&state, &tab_id).await;
576        set_tree(&state, &tab_id, stack_leaf("leaf", &[&a, &b], &a)).await;
577
578        let out = run_with(&state, vec![a.clone(), b.clone()], CloseOpts { frontend_waits: true, ..Default::default() }).await.unwrap();
579        assert_eq!(out["leaf_removed"], true);
580        // The frontend still shows both tabs: one `delete` each, the last
581        // taking the pane — never only the visible one (§5.5).
582        assert_eq!(queued_deletes(&state, &tab_id), vec![a.clone(), b.clone()]);
583    }
584
585    /// The empty spot a closed default agent pane left now and then: the frontend shows srv's stored
586    /// tree whenever its own differs, and it reads that row when the queued `delete` reaches it. So
587    /// srv's tree must lose the pane BEFORE the `delete` is queued; queued first, the row the frontend
588    /// read still held the pane and it showed it again with its block gone.
589    #[tokio::test]
590    async fn the_tree_loses_the_pane_before_a_waiting_frontend_is_told() {
591        let state = test_state();
592        let (_ws, tab_id) = seed_tab(&state).await;
593        let a = seed_block(&state, &tab_id).await;
594        let b = seed_block(&state, &tab_id).await;
595        let tree = agentmux_common::LayoutNode {
596            id: "root".into(),
597            children: vec![stack_leaf("agent", &[&a], &a), stack_leaf("other", &[&b], &b)],
598            ..Default::default()
599        };
600        set_tree(&state, &tab_id, tree).await;
601        let mut events = state.srv_events_tx.subscribe();
602
603        run_with(&state, vec![a.clone()], CloseOpts { frontend_waits: true, ..Default::default() }).await.unwrap();
604
605        let mut seen = Vec::new();
606        while let Ok(ev) = events.try_recv() {
607            match ev {
608                Event::LayoutNodeDeleted { .. } => seen.push("tree"),
609                Event::LayoutBackendActionsQueued { .. } => seen.push("queued"),
610                _ => {}
611            }
612        }
613        assert_eq!(seen, vec!["tree", "queued"], "the row that holds the delete already holds the pruned tree");
614        assert_eq!(queued_deletes(&state, &tab_id), vec![a.clone()]);
615    }
616
617    #[tokio::test]
618    async fn a_waiting_frontend_is_told_about_one_closed_tab_of_a_kept_pane() {
619        let state = test_state();
620        let (_ws, tab_id) = seed_tab(&state).await;
621        let a = seed_block(&state, &tab_id).await;
622        let b = seed_block(&state, &tab_id).await;
623        set_tree(&state, &tab_id, stack_leaf("leaf", &[&a, &b], &a)).await;
624
625        let out = run_with(&state, vec![a.clone()], CloseOpts { frontend_waits: true, ..Default::default() }).await.unwrap();
626        assert_eq!(out["leaf_removed"], false);
627        assert!(state.srv_state.lock().await.blocks.contains_key(&b), "sibling survives");
628        assert_eq!(queued_deletes(&state, &tab_id), vec![a.clone()], "the kept pane drops just that tab");
629        // srv's stored tree drops it too: the frontend shows that tree when
630        // its own differs, and a member left in it came back as "(No View)".
631        assert_eq!(stored_stack(&state, &tab_id), (vec![b.clone()], b.clone()));
632    }
633
634    /// The stored layout's one leaf: its tabs and the visible one.
635    fn stored_stack(state: &AppState, tab_id: &str) -> (Vec<String>, String) {
636        let tab = state.mstore.must_get::<crate::backend::obj::Tab>(tab_id).unwrap();
637        let layout = state.mstore.must_get::<crate::backend::obj::LayoutState>(&tab.layoutstate).unwrap();
638        let data = layout.rootnode.and_then(|n| n.data).expect("the pane is kept");
639        let stack = if data.block_stack.is_empty() { vec![data.block_id.clone()] } else { data.block_stack };
640        (stack, data.block_id)
641    }
642
643    /// The shutdown log (§5.5, §12.1): ordered lines scoped to the block,
644    /// ending in `done`. A block with no running controller still says so.
645    #[tokio::test]
646    async fn shutdown_publishes_an_ordered_log_scoped_to_the_block() {
647        let state = test_state();
648        let seen: std::sync::Arc<std::sync::Mutex<Vec<(Vec<String>, serde_json::Value)>>> = Default::default();
649        let sink = seen.clone();
650        state.broker.add_observer(std::sync::Arc::new(move |ev: &crate::backend::mps::MuxEvent| {
651            if ev.event == EVENT_AGENT_SHUTDOWN {
652                sink.lock().unwrap().push((ev.scopes.clone(), ev.data.clone().unwrap_or_default()));
653            }
654        }));
655        let (_ws, tab_id) = seed_tab(&state).await;
656        let a = seed_block(&state, &tab_id).await;
657        set_tree(&state, &tab_id, stack_leaf("leaf", &[&a], &a)).await;
658
659        run(&state, vec![a.clone()]).await.unwrap();
660
661        let seen = seen.lock().unwrap();
662        let steps: Vec<&str> = seen.iter().map(|(_, d)| d["step"].as_str().unwrap()).collect();
663        assert_eq!(steps, vec!["exit", "saved", "done"]);
664        assert_eq!(seen[0].1["text"], "agent — was not running");
665        assert!(seen.iter().all(|(scopes, d)| scopes == &vec![format!("block:{a}")] && d["block_id"] == a.as_str()));
666        let seqs: Vec<u64> = seen.iter().map(|(_, d)| d["seq"].as_u64().unwrap()).collect();
667        assert!(seqs.windows(2).all(|w| w[0] < w[1]), "strictly increasing: {seqs:?}");
668    }
669
670    #[test]
671    fn shutdown_lines_stay_short_and_say_what_happened() {
672        let (step, text, extra) =
673            exit_line("Camper", &blockcontroller::StopOutcome::Killed, std::time::Duration::from_millis(5_200));
674        assert_eq!((step, text.as_str()), ("kill", "Camper — killed after 5 s"));
675        assert_eq!(extra.forced_after_ms, Some(5_200));
676        assert_eq!(exit_line("Camper", &blockcontroller::StopOutcome::Exited, Default::default()).1, "Camper — exited");
677        assert_eq!(process_line("node dev-server.js", 4312, false), "node dev-server.js (pid 4312) — stopped");
678        let long = process_line(&"x".repeat(200), 1, true);
679        assert!(long.chars().count() <= SHUTDOWN_LINE_MAX && long.ends_with("— killed"), "{long}");
680        assert_eq!(short_command("   "), "process");
681    }
682
683    /// ReAgent P1 on #3784: a waiting frontend is told to drop members that
684    /// were already gone, not left showing them with nothing behind.
685    #[tokio::test]
686    async fn a_waiting_frontend_also_drops_members_that_were_already_gone() {
687        let state = test_state();
688        let (_ws, tab_id) = seed_tab(&state).await;
689        let a = seed_block(&state, &tab_id).await;
690        let b = seed_block(&state, &tab_id).await;
691        set_tree(&state, &tab_id, stack_leaf("leaf", &[&a, &b], &a)).await;
692        run(&state, vec![b.clone()]).await.unwrap(); // b closed elsewhere first
693        let before = queued_deletes(&state, &tab_id).len();
694
695        run_with(&state, vec![a.clone(), b.clone()], CloseOpts { frontend_waits: true, ..Default::default() }).await.unwrap();
696        let queued = queued_deletes(&state, &tab_id);
697        assert_eq!(&queued[before..], &[a.clone(), b.clone()], "both leave the waiting frontend");
698    }
699
700    #[test]
701    fn gone_before_lists_requested_ids_missing_at_the_start() {
702        let ids = vec!["a".to_string(), "b".to_string(), "c".to_string()];
703        assert_eq!(gone_before(&ids, &["a".to_string(), "c".to_string()]), vec!["b".to_string()]);
704        assert!(gone_before(&ids, &ids).is_empty());
705    }
706
707    #[tokio::test]
708    async fn closing_a_stacked_pane_removes_every_member() {
709        let state = test_state();
710        let (_ws, tab_id) = seed_tab(&state).await;
711        let a = seed_block(&state, &tab_id).await;
712        let b = seed_block(&state, &tab_id).await;
713        let c = seed_block(&state, &tab_id).await;
714        set_tree(&state, &tab_id, stack_leaf("leaf", &[&a, &b, &c], &a)).await;
715
716        let out = run(&state, vec![a.clone(), b.clone(), c.clone()]).await.unwrap();
717        assert_eq!(out["leaf_removed"], true);
718
719        {
720            let s = state.srv_state.lock().await;
721            for id in [&a, &b, &c] {
722                assert!(!s.blocks.contains_key(id), "block {id} must be deleted");
723            }
724            assert!(s.tabs[&tab_id].block_ids.is_empty(), "no member left in tab.blockids");
725            assert!(s.tabs[&tab_id].rootnode.is_none(), "leaf pruned");
726        }
727        for id in [&a, &b, &c] {
728            assert!(state.mstore.get::<Block>(id).unwrap().is_none());
729            assert!(!blockcontroller::is_closing(id), "respawn guard lifted after close");
730        }
731        assert_eq!(queued_deletes(&state, &tab_id), vec![a.clone()], "one frontend prune, for the visible block");
732    }
733
734    /// Closing one tab of a stack (the tab's own ×) must leave the pane and its
735    /// other tabs alone — even when the closed tab is the visible one in the
736    /// backend's copy of the tree.
737    #[tokio::test]
738    async fn closing_one_member_keeps_the_pane_and_its_siblings() {
739        let state = test_state();
740        let (_ws, tab_id) = seed_tab(&state).await;
741        let a = seed_block(&state, &tab_id).await;
742        let b = seed_block(&state, &tab_id).await;
743        set_tree(&state, &tab_id, stack_leaf("leaf", &[&a, &b], &a)).await;
744
745        let out = run(&state, vec![a.clone()]).await.unwrap();
746        assert_eq!(out["leaf_removed"], false);
747
748        let s = state.srv_state.lock().await;
749        assert!(!s.blocks.contains_key(&a));
750        assert!(s.blocks.contains_key(&b), "sibling survives");
751        assert_eq!(s.tabs[&tab_id].block_ids, vec![b.clone()]);
752        assert!(s.tabs[&tab_id].rootnode.is_some(), "pane survives");
753        drop(s);
754        assert!(queued_deletes(&state, &tab_id).is_empty());
755        assert_eq!(stored_stack(&state, &tab_id), (vec![b.clone()], b.clone()), "and leaves srv's tree");
756    }
757
758    fn sample_agent(id: &str) -> crate::backend::storage::agents::AgentDefinition {
759        crate::backend::storage::agents::AgentDefinition {
760            icon: "✦".to_string(),
761            ..crate::backend::storage::agents::test_agent_def(id, id, "claude", "host", 0, "")
762        }
763    }
764
765    /// Ordering (spec §4.2): final state is saved while the block still
766    /// exists — `session:active_pid` cleared and the instance row marked
767    /// stopped — and the session id is kept.
768    #[tokio::test]
769    async fn final_state_is_saved_before_the_block_is_deleted() {
770        use crate::backend::storage::agents::AgentInstance;
771        let state = test_state();
772        let (_ws, tab_id) = seed_tab(&state).await;
773        let a = seed_block(&state, &tab_id).await;
774
775        let mut meta = crate::backend::obj::MetaMapType::new();
776        meta.insert(
777            crate::backend::blockcontroller::session_recovery::META_SESSION_ACTIVE_PID.to_string(),
778            serde_json::json!(4242),
779        );
780        crate::server::service::update_object_meta(&state.mstore, &format!("block:{a}"), &meta).unwrap();
781
782        let mut def = sample_agent("def-close");
783        state.mstore.agent_def_insert(&mut def).unwrap();
784        state
785            .mstore
786            .instance_create(&AgentInstance {
787                session_id: "sess-keep".to_string(),
788                ..crate::backend::storage::agents::test_agent_instance("def-close", "def-close", &a, 1000)
789            })
790            .unwrap();
791
792        // Run only the pre-delete half and observe the block while it exists.
793        crate::sagas::agent_teardown::run_many(&state, std::slice::from_ref(&a), crate::sagas::agent_teardown::Policy::close()).await;
794        let block = state.mstore.get::<Block>(&a).unwrap().expect("block still exists");
795        assert!(
796            block
797                .meta
798                .get(crate::backend::blockcontroller::session_recovery::META_SESSION_ACTIVE_PID)
799                .is_none_or(|v| v.is_null()),
800            "active pid cleared before delete"
801        );
802        let inst = state.mstore.instance_get_by_block_id(&a).unwrap().unwrap();
803        assert_eq!(inst.status, "stopped");
804        assert!(inst.ended_at > 0);
805        assert_eq!(inst.session_id, "sess-keep", "session id kept for resume");
806        assert!(blockcontroller::is_closing(&a), "respawn refused mid-close");
807        finish_close(&state, &a).await;
808    }
809
810    #[tokio::test]
811    async fn rejects_blocks_from_different_tabs() {
812        let state = test_state();
813        let (ws, tab1) = seed_tab(&state).await;
814        let tab2 = dispatch_apply(
815            &state,
816            Command::CreateTab {
817                workspace_id: ws,
818                name: "t2".into(),
819            },
820        )
821        .await
822        .iter()
823        .find_map(|e| match e {
824            Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
825            _ => None,
826        })
827        .unwrap();
828        let a = seed_block(&state, &tab1).await;
829        let b = seed_block(&state, &tab2).await;
830        let err = run(&state, vec![a.clone(), b.clone()]).await.unwrap_err();
831        assert!(err.contains("span tabs"), "got: {err}");
832        let s = state.srv_state.lock().await;
833        assert!(s.blocks.contains_key(&a) && s.blocks.contains_key(&b), "nothing closed");
834    }
835
836    #[tokio::test]
837    async fn skips_ids_that_are_already_gone() {
838        let state = test_state();
839        let (_ws, tab_id) = seed_tab(&state).await;
840        let a = seed_block(&state, &tab_id).await;
841        let out = run(&state, vec!["ghost".into(), a.clone()]).await.unwrap();
842        assert_eq!(out["block_ids"], json!([a]));
843        let err = run(&state, vec!["ghost".into()]).await.unwrap_err();
844        assert!(err.contains("block not found"), "got: {err}");
845    }
846
847    /// A controller whose graceful shutdown takes `delay`.
848    struct SlowStop {
849        block_id: String,
850        delay: std::time::Duration,
851    }
852
853    impl blockcontroller::Controller for SlowStop {
854        fn start(&self, _: crate::backend::obj::MetaMapType, _: Option<Value>, _: bool) -> Result<(), String> {
855            Ok(())
856        }
857        fn stop(&self, _: bool, _: &str) -> Result<(), String> {
858            Ok(())
859        }
860        fn shutdown(&self, _deadline: std::time::Instant) -> blockcontroller::ShutdownFuture {
861            let delay = self.delay;
862            Box::pin(async move {
863                tokio::time::sleep(delay).await;
864                blockcontroller::StopOutcome::Exited
865            })
866        }
867        fn get_runtime_status(&self) -> blockcontroller::BlockControllerRuntimeStatus {
868            blockcontroller::BlockControllerRuntimeStatus {
869                blockid: self.block_id.clone(),
870                ..Default::default()
871            }
872        }
873        fn send_input(&self, _: blockcontroller::BlockInputUnion, _: Option<u64>) -> Result<(), String> {
874            Ok(())
875        }
876        fn controller_type(&self) -> &str {
877            "slow-stop-test"
878        }
879        fn block_id(&self) -> &str {
880            &self.block_id
881        }
882        fn as_any(&self) -> &dyn std::any::Any {
883            self
884        }
885    }
886
887    fn register_slow(block_id: &str, delay_ms: u64) {
888        blockcontroller::register_controller(
889            block_id,
890            std::sync::Arc::new(SlowStop {
891                block_id: block_id.to_string(),
892                delay: std::time::Duration::from_millis(delay_ms),
893            }),
894        );
895    }
896
897    /// Spec §9.2: agents in one close stop concurrently under one deadline.
898    /// Three that each take 1s finish in about 1s, not 3s.
899    #[tokio::test]
900    async fn agents_in_one_close_stop_concurrently() {
901        let state = test_state();
902        let (_ws, tab_id) = seed_tab(&state).await;
903        let mut ids = Vec::new();
904        for _ in 0..3 {
905            let id = seed_block(&state, &tab_id).await;
906            register_slow(&id, 1000);
907            ids.push(id);
908        }
909        let started = std::time::Instant::now();
910        crate::sagas::agent_teardown::run_many(&state, &ids, crate::sagas::agent_teardown::Policy::close()).await;
911        let elapsed = started.elapsed();
912        assert!(elapsed < std::time::Duration::from_millis(2500), "sequential? took {elapsed:?}");
913        for id in &ids {
914            assert!(blockcontroller::get_controller(id).is_none(), "controller removed");
915            finish_close(&state, id).await;
916        }
917    }
918
919    /// A teardown finishes even when its caller is dropped mid-way: the
920    /// host gives `CloseWindow` 2 s and then hangs up, which drops the
921    /// handler, and a graceful close takes longer than that.
922    #[tokio::test]
923    async fn a_teardown_outlives_a_dropped_caller() {
924        let state = test_state();
925        let (_ws, tab_id) = seed_tab(&state).await;
926        let a = seed_block(&state, &tab_id).await;
927        register_slow(&a, 500);
928        let caller = {
929            let (st, a) = (state.clone(), a.clone());
930            tokio::spawn(async move {
931                crate::sagas::agent_teardown::run_many(&st, std::slice::from_ref(&a), crate::sagas::agent_teardown::Policy::close())
932                    .await;
933            })
934        };
935        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
936        caller.abort();
937        let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
938        while !(blockcontroller::is_closing(&a) && !blockcontroller::closing_blocks_still_running().contains(&a)) {
939            assert!(std::time::Instant::now() < until, "the teardown was cut short with its caller");
940            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
941        }
942        assert!(blockcontroller::get_controller(&a).is_none());
943        finish_close(&state, &a).await;
944    }
945
946    /// The tool status cache had no eviction with the pane: a closed pane's tool calls stayed
947    /// until the process ended.
948    #[tokio::test]
949    async fn a_closed_pane_takes_its_tool_statuses_and_a_surviving_one_keeps_them() {
950        let state = test_state();
951        let (_ws, tab_id) = seed_tab(&state).await;
952        let kept = seed_block(&state, &tab_id).await;
953        let gone = "a-block-that-was-deleted".to_string();
954        for id in [&kept, &gone] {
955            state.dock_snapshots.push_delta(
956                id,
957                crate::backend::dock_snapshot::DockNodeSnapshot {
958                    node_id: "n1".to_string(),
959                    tool_name: "Bash".to_string(),
960                    status: "running".to_string(),
961                    timestamp: None,
962                    observed_at: 1,
963                    run_in_background: None,
964                },
965            );
966        }
967        finish_close(&state, &gone).await;
968        finish_close(&state, &kept).await;
969        assert!(state.dock_snapshots.get(&gone, 2).is_empty(), "the deleted block's statuses went with it");
970        assert_eq!(state.dock_snapshots.get(&kept, 2).len(), 1, "a block that is still there keeps its own");
971    }
972
973    /// Agent teardown spec §6.6: a pane close takes its PtyShell drawers
974    /// (sub-blocks) server-side, whether or not the pane is mounted to send
975    /// `deletesubblock`.
976    #[tokio::test]
977    async fn a_pane_close_takes_its_drawers() {
978        let state = test_state();
979        let (_ws, tab_id) = seed_tab(&state).await;
980        let a = seed_block(&state, &tab_id).await;
981        let drawer = format!("drawer-of-{a}");
982        let mut block = state.mstore.must_get::<crate::backend::obj::Block>(&a).unwrap();
983        block.subblockids = Some(vec![drawer.clone()]);
984        state.mstore.update(&mut block).unwrap();
985        register_slow(&a, 0);
986        register_slow(&drawer, 0);
987
988        crate::sagas::agent_teardown::run_many(&state, std::slice::from_ref(&a), crate::sagas::agent_teardown::Policy::close()).await;
989        assert!(blockcontroller::get_controller(&drawer).is_none(), "the drawer's controller is gone");
990        assert!(blockcontroller::get_controller(&a).is_none());
991        assert!(!blockcontroller::is_closing(&drawer), "a drawer isn't left unable to respawn");
992        finish_close(&state, &a).await;
993    }
994
995    /// Agent teardown spec §7.4: Stop keeps the agent's background tasks
996    /// unless asked, and stops them (tree and all) when asked. The block and
997    /// its record stay either way.
998    #[tokio::test]
999    async fn stop_keeps_background_tasks_unless_asked() {
1000        let state = test_state();
1001        let (_ws, tab_id) = seed_tab(&state).await;
1002        let a = seed_block(&state, &tab_id).await;
1003        // A stand-in dev server, its own process group like bashwrap's.
1004        #[cfg(windows)]
1005        let mut dev = std::process::Command::new("cmd").args(["/C", "ping -n 30 127.0.0.1 > nul"]).spawn().unwrap();
1006        #[cfg(unix)]
1007        let mut dev = {
1008            use std::os::unix::process::CommandExt as _;
1009            std::process::Command::new("sh").args(["-c", "sleep 30"]).process_group(0).spawn().unwrap()
1010        };
1011        let now = agentmux_common::time::now_ms() as i64;
1012        state.mstore.background_task_observe("bg-dev", &a, "task dev", now, now).unwrap();
1013        state.mstore.background_task_set_pid("bg-dev", dev.id() as i64).unwrap();
1014
1015        register_slow(&a, 0);
1016        let kept = crate::sagas::agent_teardown::stop(&state, &a, true, Some(false)).await.unwrap();
1017        assert_eq!(kept.stopped_background, 0);
1018        assert!(dev.try_wait().unwrap().is_none(), "kept running");
1019
1020        register_slow(&a, 0);
1021        let stopped = crate::sagas::agent_teardown::stop(&state, &a, true, Some(true)).await.unwrap();
1022        assert_eq!(stopped.stopped_background, 1);
1023        let until = std::time::Instant::now() + std::time::Duration::from_secs(10);
1024        while dev.try_wait().unwrap().is_none() && std::time::Instant::now() < until {
1025            std::thread::sleep(std::time::Duration::from_millis(50));
1026        }
1027        assert!(dev.try_wait().unwrap().is_some(), "the background task was stopped");
1028        assert!(state.srv_state.lock().await.blocks.contains_key(&a), "Stop keeps the block");
1029        assert!(
1030            crate::sagas::agent_teardown::stop(&state, "no-such-block", true, None).await.unwrap_err().starts_with("NOT_RUNNING"),
1031        );
1032        blockcontroller::delete_controller(&a);
1033    }
1034
1035    /// A controller whose stop fails.
1036    struct FailingStop(String);
1037
1038    impl blockcontroller::Controller for FailingStop {
1039        fn start(&self, _: crate::backend::obj::MetaMapType, _: Option<Value>, _: bool) -> Result<(), String> {
1040            Ok(())
1041        }
1042        fn stop(&self, _: bool, _: &str) -> Result<(), String> {
1043            Err("stop_subprocess: no such process".into())
1044        }
1045        fn get_runtime_status(&self) -> blockcontroller::BlockControllerRuntimeStatus {
1046            blockcontroller::BlockControllerRuntimeStatus { blockid: self.0.clone(), ..Default::default() }
1047        }
1048        fn send_input(&self, _: blockcontroller::BlockInputUnion, _: Option<u64>) -> Result<(), String> {
1049            Ok(())
1050        }
1051        fn controller_type(&self) -> &str {
1052            "failing-stop-test"
1053        }
1054        fn block_id(&self) -> &str {
1055            &self.0
1056        }
1057        fn as_any(&self) -> &dyn std::any::Any {
1058            self
1059        }
1060    }
1061
1062    /// ReAgent P1 on #4174: a Stop whose CLI stop fails reports the error and
1063    /// touches nothing else; the agent is still running, so its background
1064    /// tasks (and claims) stay.
1065    #[tokio::test]
1066    async fn a_failed_stop_is_an_error_and_keeps_everything() {
1067        let state = test_state();
1068        let (_ws, tab_id) = seed_tab(&state).await;
1069        let a = seed_block(&state, &tab_id).await;
1070        #[cfg(windows)]
1071        let mut dev = std::process::Command::new("cmd").args(["/C", "ping -n 30 127.0.0.1 > nul"]).spawn().unwrap();
1072        #[cfg(unix)]
1073        let mut dev = {
1074            use std::os::unix::process::CommandExt as _;
1075            std::process::Command::new("sh").args(["-c", "sleep 30"]).process_group(0).spawn().unwrap()
1076        };
1077        let now = agentmux_common::time::now_ms() as i64;
1078        state.mstore.background_task_observe("bg-keep", &a, "task dev", now, now).unwrap();
1079        state.mstore.background_task_set_pid("bg-keep", dev.id() as i64).unwrap();
1080        blockcontroller::register_controller(&a, std::sync::Arc::new(FailingStop(a.clone())));
1081
1082        let err = crate::sagas::agent_teardown::stop(&state, &a, true, Some(true)).await.unwrap_err();
1083        assert!(err.contains("no such process"), "the stop's own error: {err}");
1084        std::thread::sleep(std::time::Duration::from_millis(300));
1085        assert!(dev.try_wait().unwrap().is_none(), "the background task was not stopped");
1086
1087        blockcontroller::take_controller(&a);
1088        let _ = dev.kill();
1089        let _ = dev.wait();
1090    }
1091
1092    /// App exit lists every controller; a drawer is left to its parent's
1093    /// cascade, not torn down twice at once (ReAgent P2 on #4164).
1094    #[tokio::test]
1095    async fn app_exit_leaves_drawers_to_their_parent() {
1096        let state = test_state();
1097        let (_ws, tab_id) = seed_tab(&state).await;
1098        let a = seed_block(&state, &tab_id).await;
1099        let b = seed_block(&state, &tab_id).await;
1100        let drawer = format!("drawer-of-{a}");
1101        let mut block = state.mstore.must_get::<crate::backend::obj::Block>(&a).unwrap();
1102        block.subblockids = Some(vec![drawer.clone()]);
1103        state.mstore.update(&mut block).unwrap();
1104        let ids = crate::sagas::agent_teardown::without_sub_blocks(&state, vec![a.clone(), drawer, b.clone()]);
1105        assert_eq!(ids, vec![a, b]);
1106    }
1107
1108    /// Spec §9.5: closing the last window tab is refused BEFORE any agent in
1109    /// it is stopped — otherwise a refused close leaves a tab of stopped
1110    /// agents.
1111    #[tokio::test]
1112    async fn last_tab_close_is_refused_without_stopping_its_agents() {
1113        let state = test_state();
1114        let (ws, tab_id) = seed_tab(&state).await;
1115        let a = seed_block(&state, &tab_id).await;
1116        register_slow(&a, 0);
1117
1118        let err = crate::sagas::delete_tab::run(&state, ws, tab_id).await.unwrap_err();
1119        assert!(err.contains("last tab"), "got: {err}");
1120        assert!(blockcontroller::get_controller(&a).is_some(), "agent must not be stopped");
1121        assert!(!blockcontroller::is_closing(&a));
1122        blockcontroller::delete_controller(&a);
1123    }
1124
1125    /// Closing a window tab stops its agents (through the shared shutdown)
1126    /// and deletes the tab.
1127    #[tokio::test]
1128    async fn window_tab_close_stops_its_agents() {
1129        let state = test_state();
1130        let (ws, tab1) = seed_tab(&state).await;
1131        let tab2 = dispatch_apply(
1132            &state,
1133            Command::CreateTab {
1134                workspace_id: ws.clone(),
1135                name: "t2".into(),
1136            },
1137        )
1138        .await
1139        .iter()
1140        .find_map(|e| match e {
1141            Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
1142            _ => None,
1143        })
1144        .unwrap();
1145        let a = seed_block(&state, &tab2).await;
1146        let b = seed_block(&state, &tab2).await;
1147        register_slow(&a, 300);
1148        register_slow(&b, 300);
1149
1150        crate::sagas::delete_tab::run(&state, ws, tab2.clone()).await.unwrap();
1151
1152        assert!(blockcontroller::get_controller(&a).is_none());
1153        assert!(blockcontroller::get_controller(&b).is_none());
1154        assert!(!blockcontroller::is_closing(&a) && !blockcontroller::is_closing(&b));
1155        let s = state.srv_state.lock().await;
1156        assert!(!s.tabs.contains_key(&tab2));
1157        assert!(s.tabs.contains_key(&tab1));
1158    }
1159
1160    /// A reopen racing a close waits for the old process instead of calling
1161    /// it gone the moment its controller leaves the registry (spec §9.6).
1162    #[tokio::test]
1163    async fn waiting_on_a_closing_block_returns_once_it_has_stopped() {
1164        let id = format!("closing-wait-{}", uuid::Uuid::new_v4());
1165        blockcontroller::mark_closing(&id);
1166        let waiter_id = id.clone();
1167        let waiter = tokio::spawn(async move {
1168            let started = std::time::Instant::now();
1169            blockcontroller::wait_closing_stopped(&waiter_id, std::time::Duration::from_secs(5)).await;
1170            started.elapsed()
1171        });
1172        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1173        blockcontroller::mark_closing_stopped(&id);
1174        let waited = waiter.await.unwrap();
1175        assert!(waited >= std::time::Duration::from_millis(250), "returned early: {waited:?}");
1176        assert!(waited < std::time::Duration::from_secs(2), "missed the signal: {waited:?}");
1177        blockcontroller::unmark_closing(&id);
1178    }
1179
1180    #[test]
1181    fn closing_guard_blocks_resync() {
1182        let block = Block {
1183            oid: "closing-guard-blk".to_string(),
1184            parentoref: String::new(),
1185            version: 1,
1186            runtimeopts: None,
1187            stickers: None,
1188            meta: {
1189                let mut m = crate::backend::obj::MetaMapType::new();
1190                m.insert("controller".to_string(), json!("shell"));
1191                m
1192            },
1193            subblockids: None,
1194        };
1195        blockcontroller::mark_closing(&block.oid);
1196        let err = blockcontroller::resync_controller(
1197            &block, "tab-1", None, false, true, None, None, None, None, None, None, None,
1198            std::sync::Arc::from("test-boot"), "test-key", None,
1199        )
1200        .unwrap_err();
1201        blockcontroller::unmark_closing(&block.oid);
1202        assert!(err.contains("is closing"), "got: {err}");
1203        assert!(blockcontroller::get_controller(&block.oid).is_none());
1204    }
1205}