Skip to main content

agentmux_srv/sagas/
self_quit.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Self-quit — end ONE agent gracefully and close its own tab
5// (docs/specs/SPEC_AGENT_SELF_QUIT_2026_09_24.md §3, §4.3; Phase 1).
6//
7// Order (§4.3):
8// 1. Resolve who the agent is while it is still registered — shutdown
9//    unregisters the block, and a later lookup falls back to the bare id.
10// 2–4. `delete_block::run_with_policy(Policy::quit())`: the one teardown
11//    (`sagas::agent_teardown`, SPEC_AGENT_TEARDOWN_SINGLE_PATH_2026_10_01.md)
12//    releases its work claims, stops the `Shell()` children it spawned and
13//    shuts it down gracefully; then a stack-aware layout prune that keeps
14//    sibling tabs, and the frontend update for an already-loaded tree (§12.4).
15// 5. Audit, success or failure.
16//
17// Crons that target the agent are kept (decided Q2: a cron is a deliberate
18// schedule that resumes when the agent is reopened) and reported, so the
19// user can pause or delete them if they meant "stop everything".
20
21use serde::Serialize;
22
23use crate::server::AppState;
24
25/// Who asked.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum QuitOrigin {
28    /// The user typed `/shutdown` (or its aliases `/quit`, `/exit`) in the agent's composer.
29    UserSlash,
30    /// The user chose Shut down on the agent's row in My agents, or in its pane's menu.
31    UserMenu,
32    /// The agent's own `QuitSelf` tool, in a turn the user started (§6).
33    AgentTool,
34    /// Another agent's `Stop agents`, after the user's window ran out
35    /// (docs/specs/SPEC_STOP_AN_AGENT_ONE_WAY_AND_SHUTDOWN_TOAST_2026_10_23.md).
36    ExternalStop,
37}
38
39impl QuitOrigin {
40    pub fn as_str(self) -> &'static str {
41        match self {
42            QuitOrigin::UserSlash => "user_slash",
43            QuitOrigin::UserMenu => "user_menu",
44            QuitOrigin::AgentTool => "agent_tool",
45            QuitOrigin::ExternalStop => "external_stop",
46        }
47    }
48}
49
50/// Why `QuitSelf` doesn't proceed at once (§6.3). Until Phase 2b's override
51/// window exists, every one of these is a refusal (spec §9: the non-user path
52/// ships with 2b).
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum GateRefusal {
55    /// The controller can't say what started the turn (not a Claude
56    /// persistent agent, or a start nothing labelled).
57    Unknown,
58    /// The turn was started by something other than the user.
59    NotUserTurn,
60    /// The user started it, but other input got in since.
61    Tainted,
62    /// The quoted instruction isn't in the message that started the turn.
63    InstructionMismatch,
64    /// A Swarm broadcast started the turn. It is the user's word to quit, not
65    /// to upgrade AgentMux, which is once per machine (`gate_upgrade`).
66    BroadcastTurn,
67}
68
69impl GateRefusal {
70    pub fn as_str(self) -> &'static str {
71        match self {
72            GateRefusal::Unknown => "turn_origin_unknown",
73            GateRefusal::NotUserTurn => "not_user_turn",
74            GateRefusal::Tainted => "turn_tainted",
75            GateRefusal::InstructionMismatch => "user_instruction_mismatch",
76            GateRefusal::BroadcastTurn => "broadcast_turn",
77        }
78    }
79}
80
81fn normalized(s: &str) -> String {
82    s.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()
83}
84
85/// §6.3: the quote must appear in the user's message, whitespace- and
86/// case-insensitively. An empty quote never matches.
87pub fn quote_matches(user_text: &str, quote: &str) -> bool {
88    let q = normalized(quote);
89    !q.is_empty() && normalized(user_text).contains(&q)
90}
91
92/// The §6.3 gate: may `QuitSelf` proceed without asking the user?
93pub fn gate(
94    provenance: Option<&crate::backend::blockcontroller::health::TurnProvenance>,
95    user_instruction: &str,
96) -> Result<(), GateRefusal> {
97    use crate::backend::blockcontroller::health::TurnOrigin;
98    let p = provenance.ok_or(GateRefusal::Unknown)?;
99    if p.origin != TurnOrigin::User {
100        return Err(GateRefusal::NotUserTurn);
101    }
102    if p.tainted {
103        return Err(GateRefusal::Tainted);
104    }
105    match p.user_text.as_deref() {
106        Some(text) if quote_matches(text, user_instruction) => Ok(()),
107        _ => Err(GateRefusal::InstructionMismatch),
108    }
109}
110
111/// The gate for `App` `upgrade`: `gate`, except a Swarm broadcast doesn't count
112/// as the user's word. An upgrade restarts AgentMux once for the whole machine,
113/// so a broadcast to ten agents would have all ten try it; the user is asked
114/// instead. A broadcast still authorizes an agent quitting itself.
115pub fn gate_upgrade(
116    provenance: Option<&crate::backend::blockcontroller::health::TurnProvenance>,
117    user_instruction: &str,
118) -> Result<(), GateRefusal> {
119    gate(provenance, user_instruction)?;
120    match provenance {
121        Some(p) if p.is_broadcast() => Err(GateRefusal::BroadcastTurn),
122        _ => Ok(()),
123    }
124}
125
126/// Blocks with a `QuitSelf` waiting for their turn to end (§4.2's
127/// `mark_quitting`): a second call answers `already_quitting`.
128static QUITTING: std::sync::LazyLock<std::sync::Mutex<std::collections::HashSet<String>>> =
129    std::sync::LazyLock::new(Default::default);
130
131/// How long a scheduled quit waits for the turn to end (§4.2); after that
132/// the graceful shutdown interrupts it.
133pub const SELF_QUIT_TURN_GRACE: std::time::Duration = std::time::Duration::from_secs(30);
134
135pub fn is_quitting(block_id: &str) -> bool {
136    QUITTING.lock().unwrap_or_else(|e| e.into_inner()).contains(block_id)
137        || crate::backend::blockcontroller::is_closing(block_id)
138}
139
140/// §4.2: the tool call is part of the turn that asked for it, so quit when
141/// that turn ends (or after `SELF_QUIT_TURN_GRACE`), not now. Returns false
142/// when a quit is already scheduled or under way.
143pub fn schedule_after_turn(state: &AppState, block_id: &str, detail: String) -> bool {
144    {
145        let mut q = QUITTING.lock().unwrap_or_else(|e| e.into_inner());
146        if q.contains(block_id) || crate::backend::blockcontroller::is_closing(block_id) {
147            return false;
148        }
149        q.insert(block_id.to_string());
150    }
151    let (state, block_id) = (state.clone(), block_id.to_string());
152    tokio::spawn(async move {
153        let deadline = tokio::time::Instant::now() + SELF_QUIT_TURN_GRACE;
154        while tokio::time::Instant::now() < deadline
155            && crate::backend::blockcontroller::get_controller(&block_id)
156                .is_some_and(|c| c.get_runtime_status().turn_active)
157        {
158            tokio::time::sleep(std::time::Duration::from_millis(250)).await;
159        }
160        if let Err(e) = run_with(&state, &block_id, QuitOrigin::AgentTool, Some(&detail)).await {
161            tracing::warn!(block_id = %block_id, error = %e, "self-quit (agent tool) failed");
162        }
163        QUITTING.lock().unwrap_or_else(|e| e.into_inner()).remove(&block_id);
164    });
165    true
166}
167
168/// What shutting an agent down would end, read without ending it: what the confirm names.
169#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
170pub struct ShutdownPreview {
171    /// A turn is running.
172    pub working: bool,
173    /// Work items it has claimed.
174    pub claims: usize,
175    /// Cron jobs that target it (they are kept).
176    pub crons_targeting: Vec<String>,
177}
178
179/// [`ShutdownPreview`] of the agent in `block_id`.
180pub async fn preview(state: &AppState, block_id: &str) -> ShutdownPreview {
181    let working = crate::backend::blockcontroller::get_controller(block_id).is_some_and(|c| c.get_runtime_status().turn_active);
182    let who = crate::server::agent_resources::AgentIdentity::of(state, block_id);
183    let (work_store, jobs_store) = (state.work_store.clone(), crate::server::cron::jobs_store(state));
184    let (claims, crons_targeting) = tokio::task::spawn_blocking(move || {
185        let (a, u) = (who.agent_id, who.uid);
186        let items = work_store.work_queue_claimed_by(&a, u.as_deref().unwrap_or("")).unwrap_or_default();
187        let claims = crate::server::agent_resources::claims_held_by(&items, &a, u.as_deref()).len();
188        let crons = jobs_store
189            .and_then(|s| s.cron_list().ok())
190            .map(|jobs| crate::server::agent_resources::crons_targeting(&jobs, &a, u.as_deref()))
191            .unwrap_or_default();
192        (claims, crons)
193    })
194    .await
195    .unwrap_or_default();
196    ShutdownPreview { working, claims, crons_targeting }
197}
198
199#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
200pub struct QuitSummary {
201    /// `"quit"`, or `"already_quitting"` for a block whose close is already
202    /// under way (a second `/quit`, or `/quit` racing the pane ×).
203    pub status: &'static str,
204    pub agent: String,
205    pub released_claims: usize,
206    pub stopped_shells: usize,
207    /// Names of cron jobs still targeting the agent (kept, §4.3).
208    pub crons_targeting: Vec<String>,
209    /// Processes still running after the quit, as `name (pid N)`
210    /// (agent teardown spec §6.2 step 8, §7.3). Empty is the goal.
211    pub survivors: Vec<String>,
212    /// Running Docker Compose containers from the agent's folder, left
213    /// running (`agent_teardown::compose_containers_left`).
214    pub containers_left: Vec<String>,
215}
216
217pub async fn run(state: &AppState, block_id: &str, origin: QuitOrigin) -> Result<QuitSummary, String> {
218    run_with(state, block_id, origin, None).await
219}
220
221/// [`run`] with an audit detail (for `QuitSelf`: the reason and the user's
222/// quoted instruction).
223pub async fn run_with(state: &AppState, block_id: &str, origin: QuitOrigin, detail: Option<&str>) -> Result<QuitSummary, String> {
224    run_policy(state, block_id, origin, detail, crate::sagas::agent_teardown::Policy::quit()).await
225}
226
227/// A shutdown the person asked for. `stop_background` is their answer to "stop its background tasks
228/// too?": they are kept otherwise, as a quit has always kept them.
229pub async fn run_shutdown(state: &AppState, block_id: &str, origin: QuitOrigin, stop_background: bool) -> Result<QuitSummary, String> {
230    let mut policy = crate::sagas::agent_teardown::Policy::quit();
231    policy.stop_background = stop_background;
232    run_policy(state, block_id, origin, None, policy).await
233}
234
235async fn run_policy(
236    state: &AppState,
237    block_id: &str,
238    origin: QuitOrigin,
239    detail: Option<&str>,
240    policy: crate::sagas::agent_teardown::Policy,
241) -> Result<QuitSummary, String> {
242    if crate::backend::blockcontroller::is_closing(block_id) {
243        return Ok(QuitSummary { status: "already_quitting", ..Default::default() });
244    }
245    let tab_id = {
246        let s = state.srv_state.lock().await;
247        match s.blocks.get(block_id) {
248            Some(rec) => rec.tab_id.clone(),
249            None => return Err(format!("QuitAgent: block not found: {block_id}")),
250        }
251    };
252
253    // 1. Identity, before anything unregisters the block (the audit names
254    //    the agent even if the close fails).
255    let agent = crate::server::agent_resources::AgentIdentity::of(state, block_id).label(block_id);
256    // The agent is wanted stopped from here on, so a restart that lands mid-teardown doesn't bring it back.
257    use crate::server::app_api::agent_attach::{desired_of, set_desired, DESIRED_RUNNING, DESIRED_STOPPED};
258    let desired_before = state.mstore.must_get::<crate::backend::obj::Block>(block_id).ok().and_then(|b| desired_of(&b));
259    set_desired(&state.mstore, block_id, DESIRED_STOPPED);
260    // 2–4. One teardown with the quit policy: releases claims, stops its
261    //      shells and shuts it down, then the block is closed.
262    let (result, report) = crate::sagas::delete_block::run_with_policy(state, tab_id, block_id.to_string(), policy).await;
263    // A close that failed with the agent still running leaves it wanted as it was, not stopped.
264    if result.is_err() && crate::backend::blockcontroller::get_controller(block_id).is_some() {
265        set_desired(&state.mstore, block_id, desired_before.as_deref().unwrap_or(DESIRED_RUNNING));
266    }
267    // The real counts even when the close failed after the teardown ran.
268    let report = report.unwrap_or_default();
269    let (released_claims, stopped_shells, crons) =
270        (report.released_claims, report.stopped_shells, report.crons_targeting.clone());
271    let containers_left = report.containers_left.clone();
272    let survivors: Vec<String> = report
273        .survivors
274        .iter()
275        .map(|p| format!("{} (pid {})", crate::sagas::close_pane::short_command(&p.command), p.pid))
276        .collect();
277
278    // 5. Audit.
279    let request_id = uuid::Uuid::new_v4().to_string();
280    state.reactive_handler.log_fleet_action_audit(
281        None,
282        &agent,
283        block_id,
284        "agent.quit",
285        result.is_ok(),
286        result.as_ref().err().map(String::as_str),
287        &request_id,
288        Some(&match detail {
289            Some(d) => format!("{}: {d}", origin.as_str()),
290            None => origin.as_str().to_string(),
291        }),
292    );
293    tracing::info!(
294        block_id,
295        agent = %agent,
296        origin = origin.as_str(),
297        released_claims,
298        stopped_shells,
299        crons_targeting = crons.len(),
300        survivors = survivors.len(),
301        ok = result.is_ok(),
302        "self-quit"
303    );
304    result?;
305    Ok(QuitSummary { status: "quit", agent, released_claims, stopped_shells, crons_targeting: crons, survivors, containers_left })
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::server::agent_resources::{cron_targets, holds_claim};
312    use crate::server::tests::{dispatch_apply, test_state};
313    use agentmux_common::ipc::{Command, Event};
314
315    #[test]
316    fn claims_are_matched_by_uid_when_both_sides_have_one_else_by_name() {
317        assert!(holds_claim("Lark", "uid-lark", "Lark", Some("uid-lark")));
318        assert!(holds_claim("Lark", "", "Lark", Some("uid-lark")), "claimed before UIDs existed: by name");
319        assert!(!holds_claim("Lark", "uid-other", "Lark", Some("uid-lark")), "a same-named other agent");
320        assert!(!holds_claim("Korp", "uid-korp", "Lark", Some("uid-lark")));
321        assert!(holds_claim("Lark", "uid-other", "Lark", None), "no UID of our own: by name");
322        assert!(!holds_claim("", "", "", None), "an unknown agent releases nothing");
323    }
324
325    #[test]
326    fn crons_targeting_the_agent_are_matched_by_uid_or_name() {
327        assert!(cron_targets("Lark", "uid-lark", "Lark", Some("uid-lark")));
328        assert!(cron_targets("lark", "", "Lark", Some("uid-lark")), "legacy job, name only, case-insensitive");
329        assert!(!cron_targets("Lark", "uid-other", "Lark", Some("uid-lark")));
330        assert!(!cron_targets("Korp", "uid-korp", "Lark", Some("uid-lark")));
331    }
332
333    async fn seed_two_tab_pane(state: &AppState) -> (String, String, String) {
334        let ws = dispatch_apply(state, Command::CreateWorkspace { name: "w".into() })
335            .await
336            .iter()
337            .find_map(|e| match e {
338                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
339                _ => None,
340            })
341            .unwrap();
342        let tab_id = dispatch_apply(state, Command::CreateTab { workspace_id: ws, name: "t".into() })
343            .await
344            .iter()
345            .find_map(|e| match e {
346                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
347                _ => None,
348            })
349            .unwrap();
350        let mut blocks = Vec::new();
351        for _ in 0..2 {
352            blocks.push(
353                dispatch_apply(state, Command::CreateBlock { tab_id: tab_id.clone(), meta: serde_json::Value::Null })
354                    .await
355                    .iter()
356                    .find_map(|e| match e {
357                        Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
358                        _ => None,
359                    })
360                    .unwrap(),
361            );
362        }
363        let (a, b) = (blocks[0].clone(), blocks[1].clone());
364        let leaf = agentmux_common::LayoutNode {
365            id: "leaf".into(),
366            data: Some(agentmux_common::LayoutNodeData {
367                block_id: a.clone(),
368                block_stack: vec![a.clone(), b.clone()],
369                active_block_id: a.clone(),
370                ..Default::default()
371            }),
372            ..Default::default()
373        };
374        dispatch_apply(
375            state,
376            Command::LayoutSetTree { tab_id: tab_id.clone(), new_tree: Some(leaf), correlation_id: String::new(), slices: None },
377        )
378        .await;
379        (tab_id, a, b)
380    }
381
382    fn queued_deletes(state: &AppState, tab_id: &str) -> Vec<String> {
383        let tab = state.mstore.must_get::<crate::backend::obj::Tab>(tab_id).unwrap();
384        let layout = state.mstore.must_get::<crate::backend::obj::LayoutState>(&tab.layoutstate).unwrap();
385        layout
386            .pendingbackendactions
387            .unwrap_or_default()
388            .into_iter()
389            .filter(|a| a.actiontype == "delete")
390            .map(|a| a.blockid)
391            .collect()
392    }
393
394    /// Spec §3.2 + §12.4: quitting one tab of a two-tab pane closes only that
395    /// tab, keeps the pane and the sibling, and queues the frontend `delete`
396    /// so an already-loaded frontend drops the tab instead of resurrecting it.
397    #[tokio::test]
398    async fn quitting_one_tab_keeps_the_pane_and_tells_the_frontend() {
399        let state = test_state();
400        let (tab_id, a, b) = seed_two_tab_pane(&state).await;
401
402        let summary = run(&state, &a, QuitOrigin::UserSlash).await.expect("quit");
403        assert_eq!(summary.status, "quit");
404        assert_eq!((summary.released_claims, summary.stopped_shells), (0, 0));
405
406        let s = state.srv_state.lock().await;
407        assert!(!s.blocks.contains_key(&a), "the quitting tab is gone");
408        assert!(s.blocks.contains_key(&b), "the sibling tab keeps running");
409        assert!(s.tabs[&tab_id].rootnode.is_some(), "the pane survives");
410        drop(s);
411        assert_eq!(queued_deletes(&state, &tab_id), vec![a.clone()], "frontend told to drop the tab");
412
413        assert!(run(&state, &a, QuitOrigin::UserSlash).await.is_err(), "already gone: not found");
414    }
415
416    /// Shut down from My agents reaches an agent that has no pane: a parked block is in no tab, and
417    /// ending it removes it, with its tab and sibling untouched.
418    #[tokio::test]
419    async fn shutting_down_a_parked_agent_ends_it_and_leaves_its_old_tab_alone() {
420        let state = test_state();
421        let (tab_id, a, b) = seed_two_tab_pane(&state).await;
422        dispatch_apply(&state, Command::ParkBlock { tab_id: tab_id.clone(), block_id: a.clone() }).await;
423        assert_eq!(state.srv_state.lock().await.blocks[&a].tab_id, "", "parked: in no tab");
424
425        let summary = run_shutdown(&state, &a, QuitOrigin::UserMenu, false).await.expect("shut down");
426        assert_eq!(summary.status, "quit");
427
428        let s = state.srv_state.lock().await;
429        assert!(!s.blocks.contains_key(&a), "the parked agent is gone");
430        assert!(s.blocks.contains_key(&b), "the other pane's block is untouched");
431        assert_eq!(s.tabs[&tab_id].block_ids, vec![b.clone()]);
432    }
433
434    /// The same quit, reached by the menu: a block that isn't there is an error, not a silent success.
435    #[tokio::test]
436    async fn shutting_down_a_block_that_is_not_there_is_an_error() {
437        let state = test_state();
438        assert!(run_shutdown(&state, "no-such-block", QuitOrigin::UserMenu, true).await.is_err());
439    }
440
441    /// The preview reads what a shutdown would end and ends nothing: an agent with no turn, claim or
442    /// cron says so, and the block stays.
443    #[tokio::test]
444    async fn the_preview_of_an_idle_agent_is_empty_and_ends_nothing() {
445        let state = test_state();
446        let (_tab_id, a, _b) = seed_two_tab_pane(&state).await;
447        assert_eq!(preview(&state, &a).await, ShutdownPreview::default());
448        assert!(state.srv_state.lock().await.blocks.contains_key(&a));
449    }
450
451    #[test]
452    fn the_menu_and_the_slash_command_are_told_apart_in_the_audit() {
453        assert_eq!(QuitOrigin::UserMenu.as_str(), "user_menu");
454        assert_ne!(QuitOrigin::UserMenu.as_str(), QuitOrigin::UserSlash.as_str());
455    }
456
457    #[test]
458    fn the_quote_must_be_in_the_users_message_give_or_take_spacing_and_case() {
459        assert!(quote_matches("Finish the PR, then quit.", "then quit"));
460        assert!(quote_matches("finish the PR,\n  then   QUIT", "then quit"));
461        assert!(!quote_matches("finish the PR", "then quit"), "not what the user said");
462        assert!(!quote_matches("quit", ""), "an empty quote proves nothing");
463    }
464
465    #[test]
466    fn the_gate_passes_only_an_untainted_user_turn_with_a_matching_quote() {
467        use crate::backend::blockcontroller::health::{TurnOrigin, TurnProvenance};
468        let p = |origin, tainted, text: Option<&str>| TurnProvenance { origin, tainted, user_text: text.map(Into::into), broadcast: false };
469        let ok = p(TurnOrigin::User, false, Some("finish the PR then quit"));
470        assert_eq!(gate(Some(&ok), "then quit"), Ok(()));
471        assert_eq!(gate(None, "then quit"), Err(GateRefusal::Unknown));
472        assert_eq!(gate(Some(&p(TurnOrigin::Automated, false, None)), "quit"), Err(GateRefusal::NotUserTurn));
473        assert_eq!(gate(Some(&p(TurnOrigin::System, false, None)), "quit"), Err(GateRefusal::NotUserTurn));
474        assert_eq!(gate(Some(&p(TurnOrigin::User, true, Some("quit"))), "quit"), Err(GateRefusal::Tainted));
475        assert_eq!(gate(Some(&ok), "you may now exit"), Err(GateRefusal::InstructionMismatch));
476    }
477
478    #[test]
479    fn a_broadcast_turn_may_quit_an_agent_but_not_upgrade_agentmux() {
480        use crate::backend::blockcontroller::health::{TurnOrigin, TurnProvenance};
481        let broadcast = TurnProvenance {
482            origin: TurnOrigin::User,
483            tainted: false,
484            user_text: Some(
485                "[BROADCAST:FROM=user VIA=swarm TO=a RECIPIENTS=3 MSGID=m TS=1]
486upgrade now, then quit".into(),
487            ),
488            broadcast: true,
489        };
490        assert!(broadcast.is_broadcast());
491        assert_eq!(gate(Some(&broadcast), "then quit"), Ok(()), "quitting itself still works");
492        assert_eq!(gate_upgrade(Some(&broadcast), "upgrade now"), Err(GateRefusal::BroadcastTurn));
493        let typed = TurnProvenance { origin: TurnOrigin::User, tainted: false, user_text: Some("upgrade now".into()), broadcast: false };
494        assert!(!typed.is_broadcast());
495        assert_eq!(gate_upgrade(Some(&typed), "upgrade now"), Ok(()), "the user's own pane message upgrades");
496        assert_eq!(gate_upgrade(Some(&typed), "something else"), Err(GateRefusal::InstructionMismatch));
497        assert_eq!(gate_upgrade(None, "upgrade now"), Err(GateRefusal::Unknown));
498    }
499
500    #[tokio::test]
501    async fn a_block_already_closing_reports_already_quitting_and_touches_nothing() {
502        let state = test_state();
503        let (_tab, a, _b) = seed_two_tab_pane(&state).await;
504        crate::backend::blockcontroller::mark_closing(&a);
505        let summary = run(&state, &a, QuitOrigin::UserSlash).await.unwrap();
506        crate::backend::blockcontroller::unmark_closing(&a);
507        assert_eq!(summary.status, "already_quitting");
508        assert!(state.srv_state.lock().await.blocks.contains_key(&a), "left alone");
509    }
510}