Skip to main content

agentmux_srv/sagas/pending_shutdown/
batch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One window for several agents (`SPEC_COUNTDOWN_BUTTONS_AND_BATCH_AGENT_ACTIONS_2026_10_28.md` ยง4).
5//! A `Stop agents` over five agents is one request: one deadline, one OS notification ("Closing 5
6//! agents: A, B, C and 2 more in 30 s") with Keep running and Close now for all of them, and one
7//! audit entry. Each agent's own pane keeps its banner, and its Keep running keeps that agent only.
8//!
9//! A block that already has an active request joins that one, as it always did; only the blocks no
10//! request covers are put in the new one.
11
12use super::*;
13
14/// The notification group of a batch's toast: it is no one block's, so the request is its own.
15pub(super) const GROUP_PREFIX: &str = "batch:";
16
17pub(super) fn group(request_id: &str) -> String {
18    format!("{GROUP_PREFIX}{request_id}")
19}
20
21/// The name the user knows the agent in `block_id` by.
22fn block_name(state: &AppState, block_id: &str) -> String {
23    let named = state
24        .mstore
25        .get::<crate::backend::obj::Block>(block_id)
26        .ok()
27        .flatten()
28        .map(|b| crate::backend::obj::meta_get_string(&b.meta, "agentName", ""))
29        .filter(|n| !n.trim().is_empty())
30        .or_else(|| state.reactive_handler.get_agent_by_block(block_id).map(|a| a.agent_id))
31        .unwrap_or_else(|| block_id.to_string());
32    clean_by(&named)
33}
34
35/// What a toast calls the agents closing, within the notification's name limit: `lark`, or
36/// `5 agents: A, B, C and 2 more` with as many names as fit.
37pub(super) fn subject(names: &[&str]) -> String {
38    const LIMIT: usize = 32;
39    let n = names.len();
40    if n == 1 {
41        return names[0].to_string();
42    }
43    for shown in (1..=n).rev() {
44        let list = names[..shown].join(", ");
45        let text = if shown == n { format!("{n} agents: {list}") } else { format!("{n} agents: {list} and {} more", n - shown) };
46        if text.chars().count() <= LIMIT {
47            return text;
48        }
49    }
50    format!("{n} agents")
51}
52
53/// Ask to close `blocks` (agent tabs) behind one window. Returns one view per block, in order: the
54/// blocks put in the new request share its id (each view names its own block and agent), the others
55/// are whatever request already covered them. With fewer than two blocks free it is the ordinary
56/// request per block.
57pub fn request_batch(state: &AppState, blocks: &[String], by: &str, reason: &str, detail: &str) -> Vec<PendingView> {
58    let one = |b: &str| request(state, b, by, "FleetBulkStop", reason, Action::CloseTab { detail: detail.to_string() });
59    let named: Vec<(String, String)> = blocks.iter().map(|b| (b.clone(), block_name(state, b))).collect();
60    let shown_by = clean_by(&asker_name(state, by));
61    let opened = {
62        let mut map = entries();
63        prune(&mut map, now_ms());
64        let fresh: Vec<&(String, String)> = named
65            .iter()
66            .filter(|(b, _)| !map.values().any(|e| is_active(e.view.status) && e.covers.iter().any(|c| c == b)))
67            .collect();
68        if fresh.len() < 2 {
69            None
70        } else {
71            let ids: Vec<String> = fresh.iter().map(|(b, _)| b.clone()).collect();
72            let view = PendingView {
73                request_id: uuid::Uuid::new_v4().to_string(),
74                block_id: ids[0].clone(),
75                by: shown_by,
76                target: fresh.iter().map(|(_, n)| n.as_str()).collect::<Vec<_>>().join(", "),
77                via: "FleetBulkStop".to_string(),
78                reason: clean_reason(reason),
79                effect: "close_tab",
80                deadline_ms: now_ms() + OVERRIDE_WINDOW.as_millis() as i64,
81                status: "pending",
82                error: None,
83                blocks: Some(fresh.iter().map(|(b, n)| BatchBlock { block_id: b.clone(), name: n.clone() }).collect()),
84                outcomes: None,
85                joined: false,
86            };
87            map.insert(
88                view.request_id.clone(),
89                Entry {
90                    view: view.clone(),
91                    kept: Arc::new(tokio::sync::Notify::new()),
92                    finished_at_ms: None,
93                    action: Some(Action::CloseTabs { block_ids: ids.clone(), detail: detail.to_string() }),
94                    requesters: vec![(by.to_string(), "FleetBulkStop".to_string(), reason.trim().to_string())],
95                    covers: ids,
96                    closing: false,
97                    told: Vec::new(),
98                },
99            );
100            Some(view)
101        }
102    };
103    let Some(view) = opened else {
104        return blocks.iter().map(|b| one(b)).collect();
105    };
106    for b in view.blocks.iter().flatten() {
107        publish_pending(state, &b.block_id, &view);
108    }
109    raise_toast(state, &view);
110    tracing::info!(request_id = %view.request_id, agents = view.blocks.as_ref().map_or(0, Vec::len), by, "shutdown pending for several agents: the user can keep any of them");
111    spawn_window(state, view.clone(), OVERRIDE_WINDOW);
112    let in_batch = |b: &str| view.blocks.iter().flatten().any(|x| x.block_id == b);
113    blocks
114        .iter()
115        .map(|b| {
116            if !in_batch(b) {
117                return one(b);
118            }
119            let target = state.reactive_handler.get_agent_by_block(b).map(|a| a.agent_id).unwrap_or_else(|| b.clone());
120            PendingView { block_id: b.clone(), target, ..view.clone() }
121        })
122        .collect()
123}
124
125/// The OS notification of a batch: what will happen to how many, the time left, and the two buttons.
126pub(super) fn raise_toast(state: &AppState, view: &PendingView) {
127    let Some(router) = notify_router(state) else { return };
128    let names: Vec<&str> = view.blocks.iter().flatten().map(|b| b.name.as_str()).collect();
129    if names.is_empty() {
130        return;
131    }
132    let body = if names.len() == 1 {
133        format!("{} asked to close it. It stays in My Agents, with its conversation.", view.by)
134    } else {
135        format!("{} asked to close them. They stay in My Agents, with their conversations.", view.by)
136    };
137    let info = crate::backend::notify::policy::ShutdownInfo {
138        deadline_ms: view.deadline_ms,
139        effect: view.effect,
140        running: true,
141        request_id: view.request_id.clone(),
142        labels: None,
143    };
144    router.emit_group(&group(&view.request_id), &subject(&names), Some(body), info);
145}
146
147/// "Keep running" on one agent's banner of a batch: that agent leaves the request and the others and
148/// the clock are untouched. When none is left the request is `kept_by_user`. `None` when the request
149/// is not a batch or the block is not one of its agents (the whole-request keep applies).
150pub(super) fn keep_member(state: &AppState, block_id: &str, request_id: &str) -> Option<&'static str> {
151    let (view, left) = {
152        let mut map = entries();
153        let e = map.get_mut(request_id)?;
154        if e.view.blocks.is_none() || !e.covers.iter().any(|b| b == block_id) {
155            return None;
156        }
157        if e.view.status != "pending" || e.closing {
158            return Some("too_late");
159        }
160        let name = e.view.blocks.iter().flatten().find(|b| b.block_id == block_id).map(|b| b.name.clone()).unwrap_or_default();
161        e.covers.retain(|b| b != block_id);
162        if let Some(Action::CloseTabs { block_ids, .. }) = e.action.as_mut() {
163            block_ids.retain(|b| b != block_id);
164        }
165        if let Some(blocks) = e.view.blocks.as_mut() {
166            blocks.retain(|b| b.block_id != block_id);
167        }
168        e.view.outcomes.get_or_insert_with(Vec::new).push(BlockOutcome { block_id: block_id.to_string(), name, outcome: "kept_by_user", error: None });
169        if e.covers.is_empty() {
170            e.view.status = "kept_by_user";
171            e.finished_at_ms = Some(now_ms());
172            e.kept.notify_one();
173        }
174        (e.view.clone(), e.covers.clone())
175    };
176    let data = PendingClearedEvent { block_id: block_id.to_string(), request_id: request_id.to_string(), outcome: "kept_by_user".to_string() };
177    state.broker.publish_event::<crate::backend::mps_events::AgentShutdownPendingCleared>(&data, vec![format!("block:{block_id}")], 1);
178    if left.is_empty() {
179        if let Some(router) = notify_router(state) {
180            router.resolve_nonblocking(&group(request_id), crate::backend::notify::policy::Family::Shutdown);
181        }
182        audit(state, request_id, &format!("kept_by_user ({})", summary(&view)), None);
183        tell_requesters(state, request_id);
184    } else {
185        // The banners and the toast name who is still closing.
186        for b in &left {
187            publish_pending(state, b, &view);
188        }
189        raise_toast(state, &view);
190    }
191    tracing::info!(block_id, request_id, "shutdown pending for several agents: one kept by the user");
192    Some("kept_by_user")
193}
194
195/// The whole request kept (the toast's Keep running): every agent still in it is recorded as kept.
196pub(super) fn mark_all_kept(e: &mut Entry) {
197    let Some(blocks) = e.view.blocks.as_ref() else { return };
198    let kept: Vec<BlockOutcome> = blocks
199        .iter()
200        .map(|b| BlockOutcome { block_id: b.block_id.clone(), name: b.name.clone(), outcome: "kept_by_user", error: None })
201        .collect();
202    e.view.outcomes.get_or_insert_with(Vec::new).extend(kept);
203}
204
205/// `A: kept_by_user, B: shut_down`: the outcomes as the audit note keeps them.
206fn summary(view: &PendingView) -> String {
207    view.outcomes.iter().flatten().map(|o| format!("{}: {}", o.name, o.outcome)).collect::<Vec<_>>().join(", ")
208}
209
210/// Close each agent still in the request, all at once as separate requests would have, and record how
211/// each ended. The request's own status is `failed` if any close failed (with each error named),
212/// else `shut_down` if any closed, else `superseded`.
213pub(super) async fn run(state: &AppState, v: &PendingView, block_ids: Vec<String>, detail: String) -> (&'static str, Option<String>, String) {
214    let name_of = |b: &str| v.blocks.iter().flatten().find(|x| x.block_id == b).map_or_else(|| b.to_string(), |x| x.name.clone());
215    let closes = block_ids.iter().map(|b| {
216        let detail = detail.clone();
217        async move { run_action(state, b, Action::CloseTab { detail }).await }
218    });
219    let results = futures_util::future::join_all(closes).await;
220    let ended: Vec<BlockOutcome> = block_ids
221        .iter()
222        .zip(results)
223        .map(|(b, r)| {
224            let (outcome, error) = match r {
225                Ok(()) => ("shut_down", None),
226                // Already gone: the user closed or stopped it meanwhile.
227                Err(e) if e.contains("block not found") || e.starts_with("NOT_RUNNING") => ("superseded", None),
228                Err(e) => ("failed", Some(e)),
229            };
230            BlockOutcome { block_id: b.clone(), name: name_of(b), outcome, error }
231        })
232        .collect();
233    let failed: Vec<String> = ended.iter().filter(|o| o.outcome == "failed").map(|o| format!("{}: {}", o.name, o.error.as_deref().unwrap_or("close failed"))).collect();
234    let status = if !failed.is_empty() {
235        "failed"
236    } else if ended.iter().any(|o| o.outcome == "shut_down") {
237        "shut_down"
238    } else {
239        "superseded"
240    };
241    // Recorded before the status settles, so a waiter that sees the status sees every outcome.
242    let all = {
243        let mut map = entries();
244        let Some(e) = map.get_mut(&v.request_id) else { return (status, (!failed.is_empty()).then(|| failed.join("; ")), status.to_string()) };
245        e.view.outcomes.get_or_insert_with(Vec::new).extend(ended);
246        e.view.clone()
247    };
248    (status, (!failed.is_empty()).then(|| failed.join("; ")), format!("{status} ({})", summary(&all)))
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::server::tests::test_state;
255
256    fn ids(n: usize) -> Vec<String> {
257        (0..n).map(|i| format!("blk-batch-{i}-{}", uuid::Uuid::new_v4().simple())).collect()
258    }
259
260    #[test]
261    fn the_toast_names_as_many_agents_as_fit() {
262        assert_eq!(subject(&["lark"]), "lark");
263        assert_eq!(subject(&["A", "B", "C", "D", "E"]), "5 agents: A, B, C, D, E");
264        assert_eq!(subject(&["Alpha", "Bravo", "Charlie", "Delta", "Echo"]), "5 agents: Alpha and 4 more");
265        assert_eq!(subject(&["A very long agent name indeed", "B"]), "2 agents");
266    }
267
268    /// Five targets, one window; the pane banners and the toast are that request's.
269    #[tokio::test]
270    async fn five_agents_are_one_request_and_each_view_names_its_own_block() {
271        let state = test_state();
272        let blocks = ids(5);
273        let views = request_batch(&state, &blocks, "AgentY", "tidying", "asked by AgentY");
274        assert_eq!(views.len(), 5);
275        assert!(views.iter().all(|v| v.request_id == views[0].request_id && v.status == "pending"), "one window");
276        assert_eq!(views.iter().map(|v| v.block_id.clone()).collect::<Vec<_>>(), blocks);
277        assert_eq!(status(&views[0].request_id).unwrap().blocks.unwrap().len(), 5);
278        for b in &blocks {
279            assert_eq!(active_for(b).map(|v| v.request_id), Some(views[0].request_id.clone()));
280        }
281        assert_eq!(keep(&state, &group(&views[0].request_id), &views[0].request_id), "kept_by_user", "the toast keeps all");
282        assert_eq!(status(&views[0].request_id).unwrap().outcomes.unwrap().len(), 5);
283    }
284
285    /// Keep running on one agent's banner keeps that agent only: four are left, the clock is the same.
286    #[tokio::test]
287    async fn keeping_one_leaves_the_others_and_the_clock() {
288        let state = test_state();
289        let blocks = ids(5);
290        let views = request_batch(&state, &blocks, "AgentY", "", "");
291        let id = views[0].request_id.clone();
292        let deadline = views[0].deadline_ms;
293        assert_eq!(keep(&state, &blocks[2], &id), "kept_by_user");
294        let now = status(&id).unwrap();
295        assert_eq!((now.status, now.deadline_ms), ("pending", deadline));
296        assert_eq!(now.blocks.as_ref().unwrap().len(), 4);
297        assert!(active_for(&blocks[2]).is_none(), "the kept agent is free again");
298        assert_eq!(keep(&state, &blocks[2], &id), "too_late", "once");
299        expire_now(&id);
300        let done = settled(&id).await;
301        let outcomes = done.outcomes.expect("every agent has an outcome");
302        assert_eq!(outcomes.len(), 5);
303        assert_eq!(outcomes.iter().filter(|o| o.outcome == "kept_by_user").map(|o| o.block_id.as_str()).collect::<Vec<_>>(), vec![blocks[2].as_str()]);
304        assert!(outcomes.iter().filter(|o| o.outcome != "kept_by_user").count() == 4);
305    }
306
307    #[tokio::test]
308    async fn keeping_the_last_agent_keeps_the_request() {
309        let state = test_state();
310        let blocks = ids(2);
311        let views = request_batch(&state, &blocks, "AgentY", "", "");
312        let id = views[0].request_id.clone();
313        assert_eq!(keep(&state, &blocks[0], &id), "kept_by_user");
314        assert_eq!(status(&id).unwrap().status, "pending");
315        assert_eq!(keep(&state, &blocks[1], &id), "kept_by_user");
316        assert_eq!(settled(&id).await.status, "kept_by_user");
317    }
318
319    /// Close now (the toast's second button) closes the rest at once; a second press is too late.
320    #[tokio::test]
321    async fn close_now_on_the_group_closes_every_agent_once() {
322        let state = test_state();
323        let blocks = ids(3);
324        let views = request_batch(&state, &blocks, "AgentY", "", "");
325        let id = views[0].request_id.clone();
326        assert_eq!(close_now(&state, &group(&id), &id), "closed_now");
327        let done = settled(&id).await;
328        assert_eq!(done.outcomes.unwrap().len(), 3);
329        assert_eq!(close_now(&state, &group(&id), &id), "too_late");
330    }
331
332    /// A block some request already covers joins that request; the others share a new one.
333    #[tokio::test]
334    async fn a_block_with_a_window_already_joins_it() {
335        let state = test_state();
336        let blocks = ids(3);
337        let first = request(&state, &blocks[0], "Korp", "QuitSelf", "", Action::SelfQuit { detail: String::new() });
338        let views = request_batch(&state, &blocks, "AgentY", "", "");
339        assert_eq!(views[0].request_id, first.request_id);
340        assert!(views[0].joined);
341        assert_eq!(views[1].request_id, views[2].request_id);
342        assert_ne!(views[1].request_id, first.request_id);
343        assert_eq!(status(&views[1].request_id).unwrap().blocks.unwrap().len(), 2);
344        keep(&state, &blocks[0], &first.request_id);
345        keep(&state, &group(&views[1].request_id), &views[1].request_id);
346    }
347
348    /// With one block free there is nothing to batch: the ordinary request.
349    #[tokio::test]
350    async fn one_free_block_is_an_ordinary_request() {
351        let state = test_state();
352        let blocks = ids(2);
353        let first = request(&state, &blocks[0], "Korp", "QuitSelf", "", Action::SelfQuit { detail: String::new() });
354        let views = request_batch(&state, &blocks, "AgentY", "", "");
355        assert!(views[1].blocks.is_none(), "not a batch");
356        assert_ne!(views[1].request_id, first.request_id);
357        keep(&state, &blocks[0], &first.request_id);
358        keep(&state, &blocks[1], &views[1].request_id);
359    }
360}