Skip to main content

agentmux_srv/sagas/
pending_shutdown.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// External shutdown: 30 seconds (15 for an agent's own quit, 10 for a browser pane's close) for the user to override
5// (docs/specs/SPEC_AGENT_SELF_QUIT_2026_09_24.md §6.5, contract §12.2–12.3).
6//
7// A shutdown the user didn't ask for doesn't happen at once. `request` marks
8// the agent pending, tells the user (the pane banner via
9// `agent:shutdown-pending`, and an OS notification), and waits
10// `OVERRIDE_WINDOW`. `keep` — the banner's "Keep running" — cancels it.
11// Otherwise the shutdown goes ahead. The caller is answered at once with a
12// request id and reads the outcome from `status`.
13
14use std::collections::HashMap;
15use std::sync::{Arc, LazyLock, Mutex};
16
17use crate::server::AppState;
18
19mod batch;
20pub use batch::request_batch;
21pub use crate::backend::shutdown_events::{clean_reason, BatchBlock, BlockOutcome, PendingClearedEvent, PendingView};
22#[cfg(test)]
23pub use crate::backend::shutdown_events::{EVENT_SHUTDOWN_PENDING, EVENT_SHUTDOWN_PENDING_CLEARED, REASON_HIDDEN};
24use crate::backend::shutdown_events::clean_line;
25#[cfg(test)]
26use crate::backend::shutdown_events::REASON_MAX;
27
28/// How long the user has to keep what another agent asked to stop or close: 30 s, the
29/// default for a human override.
30pub const OVERRIDE_WINDOW: std::time::Duration = std::time::Duration::from_secs(30);
31/// An agent's own quit, from a turn the user didn't start: it waits for that turn to end
32/// anyway, so its window stays short.
33pub const SELF_QUIT_WINDOW: std::time::Duration = std::time::Duration::from_secs(15);
34/// Closing a browser pane: it holds no conversation to lose, and the person is looking at it.
35pub const BROWSER_CLOSE_WINDOW: std::time::Duration = std::time::Duration::from_secs(10);
36
37/// How long the user has to keep these panes when an agent asks to close them: `BROWSER_CLOSE_WINDOW` when every one
38/// is a browser pane, else `OVERRIDE_WINDOW`.
39pub fn close_window(state: &AppState, block_ids: &[String]) -> std::time::Duration {
40    let is_browser = |id: &String| {
41        let block = state.mstore.get::<crate::backend::obj::Block>(id).ok().flatten();
42        block.is_some_and(|b| b.meta.get("view").and_then(|v| v.as_str()) == Some("browser"))
43    };
44    if !block_ids.is_empty() && block_ids.iter().all(is_browser) {
45        BROWSER_CLOSE_WINDOW
46    } else {
47        OVERRIDE_WINDOW
48    }
49}
50/// Finished requests stay answerable this long, then are dropped.
51const KEEP_FINISHED_MS: i64 = 10 * 60 * 1000;
52
53/// What happens if the user lets the window run out.
54#[derive(Clone, Debug)]
55pub enum Action {
56    /// The agent's own `QuitSelf` from a turn the user didn't start: the same
57    /// self-quit, after its turn ends (§4.2).
58    SelfQuit { detail: String },
59    /// Another agent's `Stop agents`: end that one agent and close its tab,
60    /// as the user's tab × does, keeping the pane's other tabs. No wait for
61    /// its turn to end: it is stopped from outside, mid-turn or not
62    /// (docs/specs/SPEC_STOP_AN_AGENT_ONE_WAY_AND_SHUTDOWN_TOAST_2026_10_23.md §3.1).
63    CloseTab { detail: String },
64    /// Another agent's `Stop agents` over several agents at once: one window for all of them, each
65    /// closed as a `CloseTab` is. The user can keep one of them (`batch::keep_member`) or all.
66    CloseTabs { block_ids: Vec<String>, detail: String },
67    /// Another agent's `ClosePane block_id=`: close the named tab (and its pane when it was the last).
68    ClosePane { block_ids: Vec<String> },
69    /// Stop the controller and keep the block, as `agent.stop` does. Internal
70    /// only (the fork slug migration): no tool an agent can call opens one.
71    Stop { signal: Option<String>, stop_background: Option<bool> },
72    /// Another AgentMux asked this instance to let go of the agent (Take over):
73    /// stop it gracefully and leave its lease to the other instance. `to` names
74    /// the asking instance, for the pane's "taken over" row.
75    Release { to: String },
76}
77
78impl Action {
79    /// Each does all the one below it does: closing the pane ends the agent
80    /// and its siblings, a self-quit stops it and closes its tab.
81    fn rank(&self) -> u8 {
82        match self {
83            Action::Stop { .. } | Action::Release { .. } => 0,
84            Action::SelfQuit { .. } | Action::CloseTab { .. } | Action::CloseTabs { .. } => 1,
85            Action::ClosePane { .. } => 2,
86        }
87    }
88
89    /// How long the user has to keep it.
90    fn window(&self) -> std::time::Duration {
91        match self {
92            Action::SelfQuit { .. } => SELF_QUIT_WINDOW,
93            _ => OVERRIDE_WINDOW,
94        }
95    }
96
97    /// What the user is told will happen: `PendingView::effect`.
98    fn effect(&self) -> &'static str {
99        match self {
100            Action::Stop { .. } | Action::Release { .. } => "stop",
101            Action::SelfQuit { .. } | Action::CloseTab { .. } | Action::CloseTabs { .. } => "close_tab",
102            Action::ClosePane { .. } => "close_pane",
103        }
104    }
105
106    /// Every block this shuts down: the whole pane for a close, else the one.
107    fn covers(&self, block_id: &str) -> Vec<String> {
108        let mut blocks = vec![block_id.to_string()];
109        if let Action::ClosePane { block_ids } | Action::CloseTabs { block_ids, .. } = self {
110            blocks.extend(block_ids.iter().filter(|b| b.as_str() != block_id).cloned());
111        }
112        blocks
113    }
114
115    /// Folds in a joiner's action of the same kind, so what runs covers
116    /// both (ReAgent P2 on #3798): the more forceful stop, every pane asked
117    /// for. A self-quit is the same either way; its detail is audit text.
118    fn merge(&mut self, other: Action) {
119        match (self, other) {
120            (Action::Stop { signal, stop_background }, Action::Stop { signal: theirs, stop_background: their_background }) => {
121                let forceful = |s: &Option<String>| matches!(s.as_deref(), Some("SIGKILL") | Some("SIGTERM"));
122                if theirs.as_deref() == Some("SIGKILL") || (signal.is_none() && forceful(&theirs)) {
123                    *signal = theirs;
124                }
125                // Stopping the background tasks too is the more forceful ask.
126                *stop_background = match (*stop_background, their_background) {
127                    (Some(a), Some(b)) => Some(a || b),
128                    (a, b) => a.or(b),
129                };
130            }
131            // A release does all a stop does, and hands the lease over too.
132            (this, Action::Release { to }) if matches!(this, Action::Stop { .. }) => *this = Action::Release { to },
133            (Action::ClosePane { block_ids }, Action::ClosePane { block_ids: theirs }) => {
134                for b in theirs {
135                    if !block_ids.contains(&b) {
136                        block_ids.push(b);
137                    }
138                }
139            }
140            _ => {}
141        }
142    }
143}
144
145/// How long a caller should wait, at least, for a request with this deadline.
146pub fn wait_at_least_ms(deadline_ms: i64) -> u64 {
147    (deadline_ms - now_ms()).max(0) as u64
148}
149
150struct Entry {
151    view: PendingView,
152    kept: Arc<tokio::sync::Notify>,
153    finished_at_ms: Option<i64>,
154    /// Taken when the window runs out and the shutdown begins.
155    action: Option<Action>,
156    /// Everyone who asked, as (by, via, reason as sent): later requests for the
157    /// same block join this one rather than open a second window. The audit
158    /// keeps each reason exactly as its caller sent it; only `view.reason`, which
159    /// the user is shown, is cleaned (`clean_reason`).
160    requesters: Vec<(String, String, String)>,
161    /// Every block it shuts down (`Action::covers`). A request naming any of
162    /// them joins this one, Keep running works from any of their banners,
163    /// and the banner shows on each — a pane's close covers all its tabs
164    /// (ReAgent P1 on #3798: keyed on the named block alone, two closes
165    /// naming two tabs of one pane got two windows, and keeping one didn't
166    /// stop the other closing the whole pane).
167    covers: Vec<String>,
168    /// The person chose Close now: the window task is about to begin it, so a second press or a
169    /// Keep running finds `too_late`.
170    closing: bool,
171    /// Callers that did not wait for the window (`Stop pane`, `Stop agents`), as (agent, tool): each is
172    /// told once, by an `[AgentMux]` note, if the user keeps what they asked to close or the close fails.
173    told: Vec<(String, String)>,
174}
175
176static ENTRIES: LazyLock<Mutex<HashMap<String, Entry>>> = LazyLock::new(Default::default);
177
178/// A request opened on another AgentMux instance on this machine (a
179/// cross-channel `FleetBulkStop` target, whose user is asked there): where
180/// its status lives. `status` for these is proxied (see `remote_for`).
181#[derive(Clone, Debug, PartialEq, Eq)]
182pub struct RemoteRequest {
183    pub local_url: String,
184    pub auth_key: String,
185    remembered_at_ms: i64,
186}
187
188static REMOTE: LazyLock<Mutex<HashMap<String, RemoteRequest>>> = LazyLock::new(Default::default);
189
190/// Remember that `request_id` lives on the instance at `local_url`.
191pub fn remember_remote(request_id: &str, local_url: &str, auth_key: &str) {
192    let now = now_ms();
193    let mut map = REMOTE.lock().unwrap_or_else(|e| e.into_inner());
194    // Long after any window has settled, like finished local requests.
195    map.retain(|_, r| now - r.remembered_at_ms < KEEP_FINISHED_MS + OVERRIDE_WINDOW.as_millis() as i64);
196    map.insert(
197        request_id.to_string(),
198        RemoteRequest { local_url: local_url.to_string(), auth_key: auth_key.to_string(), remembered_at_ms: now },
199    );
200}
201
202/// The instance a forwarded request lives on, if it is one.
203pub fn remote_for(request_id: &str) -> Option<RemoteRequest> {
204    REMOTE.lock().unwrap_or_else(|e| e.into_inner()).get(request_id).cloned()
205}
206
207use agentmux_common::time::now_ms;
208
209fn entries() -> std::sync::MutexGuard<'static, HashMap<String, Entry>> {
210    ENTRIES.lock().unwrap_or_else(|e| e.into_inner())
211}
212
213fn prune(map: &mut HashMap<String, Entry>, now: i64) {
214    map.retain(|_, e| e.finished_at_ms.is_none_or(|t| now - t < KEEP_FINISHED_MS));
215}
216
217fn is_active(status: &str) -> bool {
218    matches!(status, "pending" | "proceeding")
219}
220
221/// The request for this block still waiting on the user or already under
222/// way, if any.
223pub fn active_for(block_id: &str) -> Option<PendingView> {
224    entries()
225        .values()
226        .find(|e| is_active(e.view.status) && e.covers.iter().any(|b| b == block_id))
227        .map(|e| e.view.clone())
228}
229
230/// Every block a request covers; empty once it's forgotten.
231fn covers_of(request_id: &str) -> Vec<String> {
232    entries().get(request_id).map(|e| e.covers.clone()).unwrap_or_default()
233}
234
235pub fn status(request_id: &str) -> Option<PendingView> {
236    entries().get(request_id).map(|e| e.view.clone())
237}
238
239/// `pending` → `proceeding`, atomically, handing over the action to run:
240/// exactly one of the window running out and the user's Keep running wins
241/// (ReAgent P1 on #3789 — checking and setting under separate locks let a
242/// late check see `pending` after a keep).
243fn begin(request_id: &str) -> Option<Action> {
244    let mut map = entries();
245    match map.get_mut(request_id) {
246        Some(e) if e.view.status == "pending" => {
247            e.view.status = "proceeding";
248            e.action.take()
249        }
250        _ => None,
251    }
252}
253
254fn set_status(request_id: &str, status: &'static str, error: Option<String>) -> Option<PendingView> {
255    let mut map = entries();
256    let e = map.get_mut(request_id)?;
257    e.view.status = status;
258    e.view.error = error;
259    if status != "pending" && status != "proceeding" {
260        e.finished_at_ms = Some(now_ms());
261    }
262    Some(e.view.clone())
263}
264
265/// `agent:shutdown-pending` for `view`, to the pane at `block_id`.
266fn publish_pending(state: &AppState, block_id: &str, view: &PendingView) {
267    state.broker.publish_event::<crate::backend::mps_events::AgentShutdownPending>(view, vec![format!("block:{block_id}")], 1);
268}
269
270fn notify_router(state: &AppState) -> Option<Arc<crate::backend::notify::router::Router>> {
271    crate::backend::notify::router::get(&state.broker)
272}
273
274/// Ask to shut `block_id` down, subject to the user's override. A request
275/// already pending — or under way — for the block is joined instead: the clock
276/// never restarts, and no second window opens beside it (ReAgent P1 on #3789:
277/// a second banner's Keep running could not stop the first). A joiner whose
278/// action does more (see `Action::rank`) replaces the pending action and is
279/// named on the banner, so nobody is told the outcome of less than they asked
280/// for (ReAgent P1 on #3798). The returned view says whose request it is: a
281/// caller whose `by`/`via` differ has joined someone else's.
282pub fn request(state: &AppState, block_id: &str, by: &str, via: &str, reason: &str, action: Action) -> PendingView {
283    let window = action.window();
284    request_within(state, block_id, by, via, reason, action, window)
285}
286
287pub(crate) fn request_within(
288    state: &AppState,
289    block_id: &str,
290    by: &str,
291    via: &str,
292    reason: &str,
293    action: Action,
294    window: std::time::Duration,
295) -> PendingView {
296    let new_covers = action.covers(block_id);
297    // What the user sees is the cleaned text; `by` and `via` keep their raw
298    // form for the audit (`requesters`).
299    let shown_by = clean_by(&asker_name(state, by));
300    let shown_reason = clean_reason(reason);
301    let view = {
302        let mut map = entries();
303        prune(&mut map, now_ms());
304        if let Some(existing) = map
305            .values_mut()
306            .find(|e| is_active(e.view.status) && e.covers.iter().any(|b| new_covers.contains(b)))
307        {
308            let mut grew = false;
309            for b in &new_covers {
310                if !existing.covers.contains(b) {
311                    existing.covers.push(b.clone());
312                    grew = true;
313                }
314            }
315            if !existing.requesters.iter().any(|(b, v, _)| b == by && v == via) {
316                existing.requesters.push((by.to_string(), via.to_string(), reason.trim().to_string()));
317            }
318            let pending = existing.view.status == "pending";
319            let stronger = pending && existing.action.as_ref().is_some_and(|cur| action.rank() > cur.rank());
320            if pending && !stronger {
321                if let Some(cur) = existing.action.as_mut().filter(|cur| cur.rank() == action.rank()) {
322                    cur.merge(action.clone());
323                }
324            }
325            if stronger {
326                existing.view.effect = action.effect();
327                existing.action = Some(action);
328                existing.view.by = shown_by.clone();
329                existing.view.via = via.to_string();
330                if !shown_reason.is_empty() {
331                    existing.view.reason = shown_reason.clone();
332                }
333            }
334            let joined = PendingView { joined: true, ..existing.view.clone() };
335            let covers = existing.covers.clone();
336            drop(map);
337            // Only while the countdown runs: once under way there is no banner.
338            if pending && (stronger || grew) {
339                // Same request and deadline; the banner names the new asker,
340                // and shows on every tab it now covers.
341                let view = PendingView { joined: false, ..joined.clone() };
342                for b in &covers {
343                    publish_pending(state, b, &view);
344                }
345                // A request that now does more (a stop upgraded to a close) must
346                // not leave the notification saying the old thing: the same
347                // request and deadline, the new wording, replacing the toast.
348                if stronger {
349                    raise_toast(state, &view);
350                }
351            }
352            return joined;
353        }
354        let view = PendingView {
355            request_id: uuid::Uuid::new_v4().to_string(),
356            block_id: block_id.to_string(),
357            by: shown_by.clone(),
358            target: state
359                .reactive_handler
360                .get_agent_by_block(block_id)
361                .map(|a| a.agent_id)
362                .unwrap_or_else(|| block_id.to_string()),
363            via: via.to_string(),
364            reason: shown_reason,
365            effect: action.effect(),
366            deadline_ms: now_ms() + window.as_millis() as i64,
367            status: "pending",
368            error: None,
369            blocks: None,
370            outcomes: None,
371            joined: false,
372        };
373        map.insert(
374            view.request_id.clone(),
375            Entry {
376                view: view.clone(),
377                kept: Arc::new(tokio::sync::Notify::new()),
378                finished_at_ms: None,
379                action: Some(action),
380                requesters: vec![(by.to_string(), via.to_string(), reason.trim().to_string())],
381                covers: new_covers.clone(),
382                closing: false, told: Vec::new(),
383            },
384        );
385        view
386    };
387    // The banner on every tab it covers (persisted, so a window opened during
388    // the countdown shows it too) and the OS notification.
389    for b in &new_covers {
390        publish_pending(state, b, &view);
391    }
392    raise_toast(state, &view);
393    tracing::info!(block_id, by, via, request_id = %view.request_id, window_s = window.as_secs(), "shutdown pending: the user can keep it");
394
395    spawn_window(state, view.clone(), window);
396    view
397}
398
399/// Wait out the window (or the user's Keep running / Close now), then run what was asked and settle.
400fn spawn_window(state: &AppState, v: PendingView, window: std::time::Duration) {
401    let kept = entries().get(&v.request_id).map(|e| e.kept.clone());
402    let state = state.clone();
403    tokio::spawn(async move {
404        if let Some(kept) = kept {
405            tokio::select! {
406                _ = tokio::time::sleep(window) => {}
407                _ = kept.notified() => {}
408            }
409        }
410        let Some(action) = begin(&v.request_id) else {
411            return; // kept by the user
412        };
413        cleared(&state, &v, "proceeding");
414        let (status, error, shown) = match action {
415            Action::CloseTabs { block_ids, detail } => batch::run(&state, &v, block_ids, detail).await,
416            action => {
417                let (status, error) = match run_action(&state, &v.block_id, action).await {
418                    Ok(()) => ("shut_down", None),
419                    // Already gone: the user closed or stopped it meanwhile.
420                    Err(e) if e.contains("block not found") || e.starts_with("NOT_RUNNING") => ("superseded", None),
421                    Err(e) => ("failed", Some(e)),
422                };
423                (status, error, status.to_string())
424            }
425        };
426        audit(&state, &v.request_id, &shown, error.as_deref());
427        set_status(&v.request_id, status, error);
428        tell_requesters(&state, &v.request_id);
429    });
430}
431
432/// Have `by` told, by one `[AgentMux]` note, how `request_id` ended if the user kept what `via` asked to
433/// close or the close failed. For a caller that did not wait for the window; a close that went ahead
434/// says nothing, as the caller asked for it. A request that has already ended tells at once.
435pub fn tell_when_settled(state: &AppState, request_id: &str, by: &str, via: &str) {
436    let ended = {
437        let mut map = entries();
438        let Some(e) = map.get_mut(request_id) else { return };
439        if is_active(e.view.status) {
440            if !e.told.iter().any(|(b, v)| b == by && v == via) {
441                e.told.push((by.to_string(), via.to_string()));
442            }
443            return;
444        }
445        e.view.clone()
446    };
447    send_settled_note(state, &ended, by, via);
448}
449
450/// The note for everyone `tell_when_settled` registered, once the request has ended.
451fn tell_requesters(state: &AppState, request_id: &str) {
452    let Some((view, told)) = entries().get_mut(request_id).map(|e| (e.view.clone(), std::mem::take(&mut e.told))) else { return };
453    for (by, via) in told {
454        send_settled_note(state, &view, &by, &via);
455    }
456}
457
458fn send_settled_note(state: &AppState, v: &PendingView, by: &str, via: &str) {
459    let Some(text) = settled_text(v, via) else { return };
460    if let Err(e) = state.reactive_handler.hold_system_note(by, &format!("shutdown:{}", v.request_id), &text) {
461        tracing::debug!(by, request_id = %v.request_id, "shutdown note not held: {e}");
462    }
463}
464
465/// What a caller that did not wait is told of an ended request: which agents the user kept running and
466/// which closes failed. `None` when everything it asked for was closed (or was already gone).
467fn settled_text(v: &PendingView, via: &str) -> Option<String> {
468    let (kept, failed): (Vec<String>, Vec<String>) = match v.outcomes.as_ref() {
469        Some(all) => (
470            all.iter().filter(|o| o.outcome == "kept_by_user").map(|o| o.name.clone()).collect(),
471            all.iter().filter(|o| o.outcome == "failed").map(|o| format!("{}: {}", o.name, o.error.as_deref().unwrap_or("close failed"))).collect(),
472        ),
473        None => match v.status {
474            "kept_by_user" => (vec![v.target.clone()], Vec::new()),
475            "failed" => (Vec::new(), vec![format!("{}: {}", v.target, v.error.as_deref().unwrap_or("close failed"))]),
476            _ => (Vec::new(), Vec::new()),
477        },
478    };
479    let mut parts = Vec::new();
480    if !kept.is_empty() {
481        parts.push(format!("the user chose to keep {} running, so it was not closed", kept.join(", ")));
482    }
483    if !failed.is_empty() {
484        parts.push(format!("closing failed for {}", failed.join("; ")));
485    }
486    if parts.is_empty() {
487        return None;
488    }
489    let tool = match via {
490        "ClosePane" => "Stop pane",
491        "FleetBulkStop" => "Stop agents",
492        "QuitAgent" => "QuitAgent call",
493        "ShutdownAgent" => "ShutdownAgent call",
494        other => other,
495    };
496    Some(format!("[AgentMux] Your {tool} (request {}): {}.", v.request_id, parts.join("; ")))
497}
498
499/// Whether the block's session is running, not merely registered: a stopped
500/// agent keeps its controller (`Policy::stop`), and the Keep running button of
501/// its notification would restart nothing (it reads "Keep open" instead).
502fn session_running(block_id: &str) -> bool {
503    crate::backend::blockcontroller::get_controller(block_id)
504        .is_some_and(|c| c.get_runtime_status().shellprocstatus == crate::backend::blockcontroller::STATUS_RUNNING)
505}
506
507/// The OS notification for `view`'s request: what will happen, the time left
508/// to its deadline, and Keep running. Raised when the request opens, and again
509/// when a stronger request takes it over (the same toast is replaced in place,
510/// since both share the block's notification group).
511fn raise_toast(state: &AppState, view: &PendingView) {
512    if view.blocks.is_some() {
513        return batch::raise_toast(state, view);
514    }
515    let Some(router) = notify_router(state) else { return };
516    // Fixed wording and the asker's cleaned name; never the reason, which is
517    // the asker's own text (spec §3.11). An OS toast also lands in the Action
518    // Center and on a lock screen.
519    let body = toast_body(view);
520    let block = view.block_id.clone();
521    let info = crate::backend::notify::policy::ShutdownInfo {
522        deadline_ms: view.deadline_ms,
523        effect: view.effect,
524        running: session_running(&view.block_id),
525        request_id: view.request_id.clone(),
526        labels: None,
527    };
528    // `emit_shutdown` reads the block (blocking): off the async workers.
529    tokio::task::spawn_blocking(move || router.emit_shutdown(&block, Some(body), info));
530}
531
532/// The OS notification's body for a pending shutdown. App-controlled text and
533/// the asker's name (cleaned); the reason is left out on purpose. "My Agents"
534/// is only for a closed agent tab: a pane close now reaches only panes that hold
535/// no agent (a browser, an editor), which have no conversation to keep.
536pub fn toast_body(v: &PendingView) -> String {
537    match v.effect {
538        "stop" => format!("{} asked to stop it. Open it to keep it running.", v.by),
539        "close_pane" => format!("{} asked to close it.", v.by),
540        _ => format!("{} asked to close it. It stays in My Agents, with its conversation.", v.by),
541    }
542}
543
544/// The longest asker name the banner and toast show.
545const BY_MAX: usize = 64;
546
547/// The asker as the user knows them: the display name of the agent whose id `by`
548/// is (`QTest`, not `qtest`), else `by` as given (a fixed app string, a name
549/// another AgentMux claims, or an agent that is not running).
550pub(crate) fn asker_name(state: &AppState, by: &str) -> String {
551    state
552        .reactive_handler
553        .get_agent(by)
554        .and_then(|a| state.mstore.get::<crate::backend::obj::Block>(&a.block_id).ok().flatten())
555        .map(|b| crate::backend::obj::meta_get_string(&b.meta, "agentName", ""))
556        .filter(|n| !n.trim().is_empty())
557        .unwrap_or_else(|| by.to_string())
558}
559
560/// The asker's name, cleaned for display. Normally a verified agent id; the
561/// only other sources are fixed app strings and a name another AgentMux on
562/// this machine claims (cross-channel), so it gets the same treatment.
563pub(crate) fn clean_by(raw: &str) -> String {
564    let line = clean_line(raw, BY_MAX);
565    if line.is_empty() { "An agent".to_string() } else { line }
566}
567
568/// The outcome, once per requester, each as its own source (§6.5 step 8).
569fn audit(state: &AppState, request_id: &str, outcome: &str, error: Option<&str>) {
570    let Some((v, requesters)) = entries().get(request_id).map(|e| (e.view.clone(), e.requesters.clone())) else {
571        return;
572    };
573    for (by, via, reason) in requesters {
574        state.reactive_handler.log_fleet_action_audit(
575            Some(&by),
576            &v.target,
577            &v.block_id,
578            "agent.shutdown_override",
579            error.is_none(),
580            error,
581            &v.request_id,
582            Some(&settled_note(outcome, &v, &via, &reason)),
583        );
584    }
585}
586
587/// One requester's audit note when the request settles: the outcome, how it
588/// asked, and its reason exactly as sent (never the cleaned text the user saw).
589fn settled_note(outcome: &str, v: &PendingView, via: &str, reason: &str) -> String {
590    let ran = if via == v.via { String::new() } else { format!(" (ran as {} by {})", v.via, v.by) };
591    format!("{outcome} | via {via}{ran} | {reason}")
592}
593
594/// The request-time audit note: whether this caller opened the window or
595/// joined someone else's.
596pub fn audit_note(state: &AppState, v: &PendingView, by: &str, via: &str) -> String {
597    // `v.by` is the name `request_within` showed, so the raw `by` is resolved the same way.
598    let shown_by = clean_by(&asker_name(state, by));
599    if !v.joined {
600        "pending user override".to_string()
601    } else if v.by == shown_by && v.via == via {
602        format!("joined its own pending request {}", v.request_id)
603    } else {
604        format!("joined {} by {}'s pending request", v.via, v.by)
605    }
606}
607
608fn cleared(state: &AppState, v: &PendingView, outcome: &str) {
609    let data = PendingClearedEvent { block_id: v.block_id.clone(), request_id: v.request_id.clone(), outcome: outcome.to_string() };
610    for b in covers_of(&v.request_id) {
611        state.broker.publish_event::<crate::backend::mps_events::AgentShutdownPendingCleared>(&data, vec![format!("block:{b}")], 1);
612    }
613    if let Some(router) = notify_router(state) {
614        router.resolve_nonblocking(&toast_block(v), crate::backend::notify::policy::Family::Shutdown);
615    }
616}
617
618/// The block (or, for a request over several agents, the group) its OS notification belongs to.
619fn toast_block(v: &PendingView) -> String {
620    if v.blocks.is_some() { batch::group(&v.request_id) } else { v.block_id.clone() }
621}
622
623/// Whether a press or banner naming `block_id` is about this request: one of its blocks, or its toast's group.
624fn names(e: &Entry, block_id: &str) -> bool {
625    e.covers.iter().any(|b| b == block_id) || (e.view.blocks.is_some() && block_id == batch::group(&e.view.request_id))
626}
627
628async fn run_action(state: &AppState, block_id: &str, action: Action) -> Result<(), String> {
629    match action {
630        Action::SelfQuit { detail } => {
631            // The agent asked from inside a turn: let it finish (§4.2).
632            let deadline = tokio::time::Instant::now() + super::self_quit::SELF_QUIT_TURN_GRACE;
633            while tokio::time::Instant::now() < deadline
634                && crate::backend::blockcontroller::get_controller(block_id)
635                    .is_some_and(|c| c.get_runtime_status().turn_active)
636            {
637                tokio::time::sleep(std::time::Duration::from_millis(250)).await;
638            }
639            super::self_quit::run_with(state, block_id, super::self_quit::QuitOrigin::AgentTool, Some(&detail))
640                .await
641                .map(|_| ())
642        }
643        Action::CloseTab { detail } => {
644            // Stopped from outside: no wait for the turn to end. One tab only:
645            // `self_quit` closes through `delete_block`, which prunes just this
646            // stack member and keeps the pane's other tabs.
647            super::self_quit::run_with(state, block_id, super::self_quit::QuitOrigin::ExternalStop, Some(&detail))
648                .await
649                .map(|_| ())
650        }
651        Action::CloseTabs { .. } => Err("a batch closes through batch::run".to_string()),
652        // The window still shows every tab it was asked to close, whether or not its pane stays: the
653        // frontend is told to drop each one (a kept pane just loses that tab; the last takes the pane).
654        Action::ClosePane { block_ids } => {
655            let opts = super::close_pane::CloseOpts { frontend_waits: true, ..Default::default() };
656            super::close_pane::run_with(state, block_ids, opts).await.map(|_| ())
657        }
658        Action::Stop { signal, stop_background } => {
659            crate::server::app_api::agent_io::stop_one_agent_block(state, block_id, signal.as_deref(), stop_background)
660                .await
661                .map(|_| ())
662        }
663        Action::Release { to } => crate::server::agent_takeover::release_block(state, block_id, &to),
664    }
665}
666
667/// Tests: end the window now, as if it ran out.
668#[cfg(test)]
669pub fn expire_now(request_id: &str) {
670    if let Some(e) = entries().get(request_id) {
671        e.kept.notify_one();
672    }
673}
674
675/// Wait until a request settles; its final view. Tests only.
676#[cfg(test)]
677pub async fn settled(request_id: &str) -> PendingView {
678    for _ in 0..400 {
679        let v = status(request_id).expect("known request");
680        if !matches!(v.status, "pending" | "proceeding") {
681            return v;
682        }
683        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
684    }
685    panic!("request {request_id} never settled");
686}
687
688/// "Keep running" (§12.3). `kept_by_user` if the request was still pending,
689/// `too_late` if the shutdown had already begun (or it isn't this block's).
690pub fn keep(state: &AppState, block_id: &str, request_id: &str) -> &'static str {
691    // On one agent's banner of a request over several, keeping keeps that agent only.
692    if let Some(outcome) = batch::keep_member(state, block_id, request_id) {
693        return outcome;
694    }
695    let view = {
696        let mut map = entries();
697        match map.get_mut(request_id) {
698            Some(e) if names(e, block_id) && e.view.status == "pending" && !e.closing => {
699                // Decided here, under the lock; the window task only wakes to
700                // find it no longer pending.
701                batch::mark_all_kept(e);
702                e.view.status = "kept_by_user";
703                e.finished_at_ms = Some(now_ms());
704                e.kept.notify_one();
705                e.view.clone()
706            }
707            _ => return "too_late",
708        }
709    };
710    cleared(state, &view, "kept_by_user");
711    audit(state, request_id, "kept_by_user", None);
712    tell_requesters(state, request_id);
713    tracing::info!(block_id, request_id, by = %view.by, "shutdown pending: kept by the user");
714    "kept_by_user"
715}
716
717/// "Close now" (the second button of the banner and the toast): the person ends the wait, and the
718/// shutdown begins at once as it would at the deadline. `closed_now` if the request was still
719/// pending, `too_late` if it was kept, had begun, or is not this block's. Only the person's: the
720/// RPC and the toast press that call it are proven by the caller.
721pub fn close_now(state: &AppState, block_id: &str, request_id: &str) -> &'static str {
722    {
723        let mut map = entries();
724        match map.get_mut(request_id) {
725            Some(e) if names(e, block_id) && e.view.status == "pending" && !e.closing => {
726                // The window task is waiting on this: it wakes, finds the request still pending and begins.
727                e.closing = true;
728                e.kept.notify_one();
729            }
730            _ => return "too_late",
731        }
732    }
733    audit(state, request_id, "closed_now_by_user", None);
734    tracing::info!(block_id, request_id, "shutdown pending: the user closed it now");
735    "closed_now"
736}
737
738#[cfg(test)]
739mod tests {
740    use super::*;
741    use crate::server::tests::test_state;
742
743    #[tokio::test]
744    async fn a_request_is_pending_then_a_second_one_keeps_the_same_clock() {
745        let state = test_state();
746        let a = request(&state, "blk-p1", "Korp", "QuitSelf", "done", Action::SelfQuit { detail: String::new() });
747        assert_eq!(a.status, "pending");
748        let b = request(&state, "blk-p1", "cron", "QuitSelf", "again", Action::SelfQuit { detail: String::new() });
749        assert_eq!((b.request_id.as_str(), b.deadline_ms), (a.request_id.as_str(), a.deadline_ms), "never restarts the clock");
750        assert_eq!(active_for("blk-p1").map(|v| v.request_id), Some(a.request_id.clone()));
751        assert_eq!(keep(&state, "blk-p1", &a.request_id), "kept_by_user");
752    }
753
754    /// A close takes 10 s only when every pane in it is a browser pane.
755    #[tokio::test]
756    async fn a_browser_pane_close_has_a_shorter_window() {
757        let state = test_state();
758        let (browser, other) = (uuid::Uuid::new_v4().to_string(), uuid::Uuid::new_v4().to_string());
759        crate::server::browser_attention::tests::browser_block(&state, &browser);
760        assert_eq!(close_window(&state, &[browser.clone()]), BROWSER_CLOSE_WINDOW);
761        assert_eq!(close_window(&state, &[browser.clone(), other]), OVERRIDE_WINDOW, "stacked with a pane that is not one");
762        assert_eq!(close_window(&state, &[uuid::Uuid::new_v4().to_string()]), OVERRIDE_WINDOW, "an unknown pane");
763        assert_eq!(close_window(&state, &[]), OVERRIDE_WINDOW);
764    }
765
766    /// "Close now" ends the wait and the shutdown begins at once, once; a kept request, one that has
767    /// begun and another block's name are `too_late`.
768    #[tokio::test]
769    async fn close_now_ends_the_wait_and_the_shutdown_begins_once() {
770        let state = test_state();
771        let a = request(&state, "blk-now1", "Korp", "FleetBulkStop", "", Action::Stop { signal: None, stop_background: None });
772        assert_eq!(close_now(&state, "blk-now1", &a.request_id), "closed_now");
773        let done = settled(&a.request_id).await;
774        assert!(matches!(done.status, "shut_down" | "superseded" | "failed"), "it began well before its 30 s: {}", done.status);
775        assert_eq!(close_now(&state, "blk-now1", &a.request_id), "too_late", "once");
776
777        let b = request(&state, "blk-now2", "Korp", "FleetBulkStop", "", Action::Stop { signal: None, stop_background: None });
778        assert_eq!(keep(&state, "blk-now2", &b.request_id), "kept_by_user");
779        assert_eq!(close_now(&state, "blk-now2", &b.request_id), "too_late", "a kept request is not closed");
780
781        let c = request(&state, "blk-now3", "Korp", "FleetBulkStop", "", Action::Stop { signal: None, stop_background: None });
782        assert_eq!(close_now(&state, "blk-other", &c.request_id), "too_late", "not this block's request");
783        assert_eq!(status(&c.request_id).unwrap().status, "pending");
784        assert_eq!(keep(&state, "blk-now3", &c.request_id), "kept_by_user");
785    }
786
787    #[tokio::test]
788    async fn a_request_under_way_is_returned_too_so_no_second_window_opens() {
789        let state = test_state();
790        let a = request(&state, "blk-p3", "Korp", "QuitSelf", "done", Action::SelfQuit { detail: String::new() });
791        assert!(begin(&a.request_id).is_some(), "the window ran out");
792        let b = request(&state, "blk-p3", "Korp", "QuitSelf", "again", Action::SelfQuit { detail: String::new() });
793        assert_eq!((b.request_id.as_str(), b.status), (a.request_id.as_str(), "proceeding"));
794        assert_eq!(keep(&state, "blk-p3", &a.request_id), "too_late");
795        assert!(begin(&a.request_id).is_none(), "the action runs once");
796    }
797
798    #[tokio::test]
799    async fn a_stronger_request_joins_and_takes_over_the_pending_action() {
800        let state = test_state();
801        let stop = request(&state, "blk-p4", "an agent", "FleetBulkStop", "", Action::Stop { signal: None, stop_background: None });
802        let close = request(
803            &state,
804            "blk-p4",
805            "Korp",
806            "ClosePane",
807            "stuck",
808            Action::ClosePane { block_ids: vec!["blk-p4".into()] },
809        );
810        assert_eq!(close.request_id, stop.request_id, "one window per block");
811        assert_eq!((close.by.as_str(), close.via.as_str(), close.deadline_ms), ("Korp", "ClosePane", stop.deadline_ms));
812        assert!(matches!(begin(&stop.request_id), Some(Action::ClosePane { .. })), "the pane closes: it does all a stop does");
813
814        // A weaker joiner neither downgrades it nor takes the banner.
815        let quit = request(&state, "blk-p5", "Camper", "QuitSelf", "done", Action::SelfQuit { detail: String::new() });
816        let again = request(&state, "blk-p5", "an agent", "FleetBulkStop", "", Action::Stop { signal: None, stop_background: None });
817        assert_eq!((again.request_id.as_str(), again.via.as_str()), (quit.request_id.as_str(), "QuitSelf"));
818        assert!(matches!(begin(&quit.request_id), Some(Action::SelfQuit { .. })));
819        let requesters = entries().get(&quit.request_id).unwrap().requesters.clone();
820        assert_eq!(requesters.len(), 2, "both are audited when it settles");
821    }
822
823    #[tokio::test]
824    async fn an_explicit_stop_background_is_carried_and_the_stronger_ask_wins() {
825        let state = test_state();
826        let a = request(&state, "blk-stop-bg-opt", "Korp", "AgentStop", "", Action::Stop { signal: None, stop_background: Some(false) });
827        let b = request(&state, "blk-stop-bg-opt", "Korp", "AgentStop", "", Action::Stop { signal: None, stop_background: Some(true) });
828        assert_eq!(a.request_id, b.request_id);
829        let got = begin(&a.request_id);
830        assert!(matches!(got, Some(Action::Stop { stop_background: Some(true), .. })), "stopping the background tasks too wins: {got:?}");
831    }
832
833    #[tokio::test]
834    async fn a_joiner_of_the_same_kind_is_folded_in_not_dropped() {
835        let state = test_state();
836        let a = request(&state, "blk-p6", "Korp", "FleetBulkStop", "", Action::Stop { signal: None, stop_background: None });
837        assert!(!a.joined);
838        let b = request(&state, "blk-p6", "Korp", "FleetBulkStop", "", Action::Stop { signal: Some("SIGKILL".into()), stop_background: None });
839        assert!(b.joined && b.request_id == a.request_id);
840        assert_eq!(audit_note(&state, &b, "Korp", "FleetBulkStop"), format!("joined its own pending request {}", a.request_id));
841        assert!(matches!(begin(&a.request_id), Some(Action::Stop { signal: Some(s), .. }) if s == "SIGKILL"), "the forceful stop wins");
842
843        let c = request(&state, "blk-p7", "Korp", "ClosePane", "", Action::ClosePane { block_ids: vec!["x".into()] });
844        request(&state, "blk-p7", "Posa", "ClosePane", "", Action::ClosePane { block_ids: vec!["x".into(), "y".into()] });
845        assert!(matches!(begin(&c.request_id), Some(Action::ClosePane { block_ids }) if block_ids == vec!["x".to_string(), "y".to_string()]));
846    }
847
848    #[tokio::test]
849    async fn closes_naming_two_tabs_of_one_pane_share_one_window() {
850        let state = test_state();
851        let pane = || Action::ClosePane { block_ids: vec!["tab-a".into(), "tab-b".into()] };
852        let a = request(&state, "tab-a", "Korp", "ClosePane", "", pane());
853        let b = request(&state, "tab-b", "Posa", "ClosePane", "", pane());
854        assert!(b.joined && b.request_id == a.request_id, "one pane, one window");
855        assert_eq!(active_for("tab-b").map(|v| v.request_id), Some(a.request_id.clone()));
856        assert_eq!(keep(&state, "tab-b", &a.request_id), "kept_by_user", "kept from the other tab's banner");
857        assert!(begin(&a.request_id).is_none(), "nothing closes");
858
859        // A pending stop on one tab is joined — and taken over — by its pane's close.
860        let stop = request(&state, "tab-d", "an agent", "FleetBulkStop", "", Action::Stop { signal: None, stop_background: None });
861        let close = request(&state, "tab-c", "Korp", "ClosePane", "", Action::ClosePane { block_ids: vec!["tab-c".into(), "tab-d".into()] });
862        assert_eq!(close.request_id, stop.request_id);
863        assert_eq!(active_for("tab-c").map(|v| v.via), Some("ClosePane".to_string()));
864        assert!(matches!(begin(&stop.request_id), Some(Action::ClosePane { .. })));
865    }
866
867    #[tokio::test]
868    async fn keep_running_cancels_it_and_a_second_keep_is_too_late() {
869        let state = test_state();
870        let v = request(&state, "blk-p2", "Korp", "QuitSelf", "done", Action::SelfQuit { detail: String::new() });
871        assert_eq!(keep(&state, "blk-p2", &v.request_id), "kept_by_user");
872        assert_eq!(status(&v.request_id).unwrap().status, "kept_by_user");
873        assert_eq!(active_for("blk-p2"), None);
874        assert_eq!(keep(&state, "blk-p2", &v.request_id), "too_late");
875        assert_eq!(keep(&state, "some-other-block", &v.request_id), "too_late", "only the block it was for");
876    }
877
878    #[tokio::test]
879    async fn keep_and_the_window_running_out_never_both_win() {
880        let state = test_state();
881        for i in 0..50 {
882            let block = format!("blk-race-{i}");
883            let v = request_within(&state, &block, "Korp", "QuitSelf", "r", Action::SelfQuit { detail: String::new() }, std::time::Duration::ZERO);
884            let kept = keep(&state, &block, &v.request_id);
885            for _ in 0..100 {
886                if !matches!(status(&v.request_id).unwrap().status, "pending" | "proceeding") {
887                    break;
888                }
889                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
890            }
891            let end = status(&v.request_id).unwrap().status;
892            if kept == "kept_by_user" {
893                assert_eq!(end, "kept_by_user", "a kept request must never go ahead");
894            } else {
895                assert_ne!(end, "kept_by_user");
896            }
897        }
898    }
899
900    #[tokio::test]
901    async fn with_no_override_it_goes_ahead_after_the_window() {
902        let state = test_state();
903        let window = std::time::Duration::from_millis(50);
904        let v = request_within(&state, "blk-gone", "Korp", "QuitSelf", "done", Action::SelfQuit { detail: String::new() }, window);
905        for _ in 0..100 {
906            if !matches!(status(&v.request_id).unwrap().status, "pending" | "proceeding") {
907                break;
908            }
909            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
910        }
911        // The block doesn't exist in this test state, so the shutdown finds
912        // nothing to close: superseded, not failed.
913        assert_eq!(status(&v.request_id).unwrap().status, "superseded");
914    }
915
916    /// A controller that reports whatever process status it is given.
917    struct Reporting(String, &'static str);
918    impl crate::backend::blockcontroller::Controller for Reporting {
919        fn start(&self, _: crate::backend::obj::MetaMapType, _: Option<serde_json::Value>, _: bool) -> Result<(), String> {
920            Ok(())
921        }
922        fn stop(&self, _: bool, _: &str) -> Result<(), String> {
923            Ok(())
924        }
925        fn get_runtime_status(&self) -> crate::backend::blockcontroller::BlockControllerRuntimeStatus {
926            crate::backend::blockcontroller::BlockControllerRuntimeStatus {
927                blockid: self.0.clone(),
928                shellprocstatus: self.1.to_string(),
929                ..Default::default()
930            }
931        }
932        fn send_input(&self, _: crate::backend::blockcontroller::BlockInputUnion, _: Option<u64>) -> Result<(), String> {
933            Ok(())
934        }
935        fn controller_type(&self) -> &str {
936            "stub"
937        }
938        fn block_id(&self) -> &str {
939            &self.0
940        }
941        fn as_any(&self) -> &dyn std::any::Any {
942            self
943        }
944    }
945
946    /// A stopped agent keeps its controller registered; only a running session
947    /// is "Keep running" (#5397).
948    #[test]
949    fn a_registered_but_stopped_session_is_not_running() {
950        let id = |p: &str| format!("{p}-{}", uuid::Uuid::new_v4());
951        let (live, stopped, gone) = (id("sr-live"), id("sr-stopped"), id("sr-gone"));
952        for (block, status) in [(&live, crate::backend::blockcontroller::STATUS_RUNNING), (&stopped, crate::backend::blockcontroller::STATUS_DONE)] {
953            crate::backend::blockcontroller::register_controller(block, Arc::new(Reporting(block.clone(), status)));
954        }
955        assert!(session_running(&live));
956        assert!(!session_running(&stopped), "registered, but its process ended");
957        assert!(!session_running(&gone), "no controller at all");
958        crate::backend::blockcontroller::delete_controller(&live);
959        crate::backend::blockcontroller::delete_controller(&stopped);
960    }
961
962    fn close_tab() -> Action {
963        Action::CloseTab { detail: "asked by AgentY (Stop agents)".into() }
964    }
965
966    #[tokio::test]
967    async fn a_tab_close_covers_one_block_and_a_pane_close_takes_it_over() {
968        let state = test_state();
969        let tab = request(&state, "ct-a", "AgentY", "FleetBulkStop", "", close_tab());
970        assert_eq!(tab.effect, "close_tab");
971        // The tab beside it has a window of its own: a tab close covers one block.
972        let beside = request(&state, "ct-b", "AgentY", "FleetBulkStop", "", close_tab());
973        assert_ne!(beside.request_id, tab.request_id);
974        assert_eq!(active_for("ct-a").map(|v| v.request_id), Some(tab.request_id.clone()));
975
976        // A pane close for the tab joins its window and does more, so it wins.
977        let pane = request(&state, "ct-a", "Korp", "ClosePane", "", Action::ClosePane { block_ids: vec!["ct-a".into()] });
978        assert_eq!(pane.request_id, tab.request_id);
979        assert_eq!(status(&tab.request_id).unwrap().effect, "close_pane", "what the user is told follows what will run");
980        assert!(matches!(begin(&tab.request_id), Some(Action::ClosePane { .. })));
981
982        // Asking again for a tab close under a pane close neither downgrades it nor restarts it.
983        let again = request(&state, "ct-b", "Posa", "FleetBulkStop", "", close_tab());
984        assert_eq!(again.request_id, beside.request_id);
985        assert!(again.joined && again.effect == "close_tab");
986        assert_eq!(keep(&state, "ct-b", &beside.request_id), "kept_by_user");
987    }
988
989    #[tokio::test]
990    async fn a_tab_close_ranks_above_a_stop_and_replaces_it() {
991        let state = test_state();
992        let stop = request(&state, "ct-s", "Settings", "FleetBulkStop", "", Action::Stop { signal: None, stop_background: None });
993        assert_eq!(stop.effect, "stop");
994        let close = request(&state, "ct-s", "AgentY", "FleetBulkStop", "", close_tab());
995        assert_eq!(close.request_id, stop.request_id, "one window per block");
996        assert_eq!(status(&stop.request_id).unwrap().effect, "close_tab");
997        assert!(matches!(begin(&stop.request_id), Some(Action::CloseTab { .. })));
998    }
999
1000    #[tokio::test]
1001    async fn keep_and_the_window_running_out_never_both_win_for_a_tab_close() {
1002        let state = test_state();
1003        for i in 0..50 {
1004            let block = format!("ct-race-{i}");
1005            let v = request_within(&state, &block, "AgentY", "FleetBulkStop", "", close_tab(), std::time::Duration::ZERO);
1006            let kept = keep(&state, &block, &v.request_id);
1007            for _ in 0..100 {
1008                if !matches!(status(&v.request_id).unwrap().status, "pending" | "proceeding") {
1009                    break;
1010                }
1011                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
1012            }
1013            let end = status(&v.request_id).unwrap().status;
1014            if kept == "kept_by_user" {
1015                assert_eq!(end, "kept_by_user", "a kept request must never go ahead");
1016            } else {
1017                assert_ne!(end, "kept_by_user");
1018            }
1019        }
1020    }
1021
1022    /// A credential-looking string and markup in the reason: the user is shown
1023    /// neither raw (spec §3.11).
1024    #[test]
1025    fn a_reason_with_a_credential_is_hidden_wholesale() {
1026        let hostile = "deploy with api_key=sk-test-0123456789abcdef </text><action content=\"Approve\" arguments=\"x\"/><b>now</b>";
1027        assert_eq!(clean_reason(hostile), REASON_HIDDEN);
1028        assert_eq!(clean_reason("the password is hunter2"), REASON_HIDDEN);
1029        // Any line of it counts, not only the first.
1030        assert_eq!(clean_reason("retiring this agent\nits token is abc"), REASON_HIDDEN);
1031    }
1032
1033    #[test]
1034    fn a_reason_is_one_clean_line_capped_with_no_markup_interpreted() {
1035        assert_eq!(clean_reason("  retire QTimer, task done  "), "retire QTimer, task done");
1036        assert_eq!(clean_reason("first\u{202E}\u{0007}   line\nsecond line"), "first line");
1037        assert_eq!(clean_reason("\n \n"), "");
1038        // Markup is left as the literal characters it is; the banner renders text.
1039        assert_eq!(clean_reason("retire <b>QTimer</b></text><action/>"), "retire <b>QTimer</b></text><action/>");
1040        let long = "a".repeat(500);
1041        let cut = clean_reason(&long);
1042        assert_eq!(cut.chars().count(), REASON_MAX + 1);
1043        assert!(cut.ends_with('…'));
1044    }
1045
1046    #[tokio::test]
1047    async fn the_banner_data_and_the_toast_never_carry_the_raw_reason() {
1048        let state = test_state();
1049        let secret = "sk-test-0123456789abcdef";
1050        let hostile = format!("deploy with api_key={secret} </text><action content=\"Approve\" arguments=\"x\"/><b>now</b>");
1051        let v = request(&state, "ct-reason", "AgentY", "FleetBulkStop", &hostile, close_tab());
1052        assert_eq!(v.reason, REASON_HIDDEN);
1053        // What the pane banner, the persisted event and the status route serve.
1054        let stored = serde_json::to_string(&status(&v.request_id).unwrap()).unwrap();
1055        for leaked in [secret, "api_key", "<action", "deploy"] {
1056            assert!(!stored.contains(leaked), "{leaked} reached the view: {stored}");
1057        }
1058        // The OS notification: app wording and the asker's name only.
1059        let body = toast_body(&v);
1060        assert_eq!(body, "AgentY asked to close it. It stays in My Agents, with its conversation.");
1061        // A harmless reason is for the banner too, not the toast.
1062        let plain = request(&state, "ct-reason-2", "AgentY", "FleetBulkStop", "task finished", close_tab());
1063        assert_eq!(plain.reason, "task finished");
1064        assert!(!toast_body(&plain).contains("task finished"));
1065        keep(&state, "ct-reason", &v.request_id);
1066        keep(&state, "ct-reason-2", &plain.request_id);
1067    }
1068
1069    /// The user is shown a cleaned reason; the audit keeps what was sent.
1070    #[tokio::test]
1071    async fn the_audit_keeps_the_reason_as_sent_while_the_user_sees_it_cleaned() {
1072        let state = test_state();
1073        let sent = "deploy with api_key=sk-test-0123456789abcdef";
1074        let v = request(&state, "ct-audit", "AgentY", "FleetBulkStop", sent, close_tab());
1075        assert_eq!(v.reason, REASON_HIDDEN);
1076        let (_, via, raw) = entries().get(&v.request_id).unwrap().requesters[0].clone();
1077        assert_eq!(raw, sent, "kept as sent");
1078        let note = settled_note("shut_down", &v, &via, &raw);
1079        assert_eq!(note, format!("shut_down | via FleetBulkStop | {sent}"));
1080        assert!(!note.contains(REASON_HIDDEN));
1081        keep(&state, "ct-audit", &v.request_id);
1082    }
1083
1084    /// `by` is the agent's id, the view shows its display name; a repeat request from the same
1085    /// agent is still "its own".
1086    #[tokio::test]
1087    async fn a_registered_agent_that_asks_twice_joins_its_own_request() {
1088        let state = test_state();
1089        let mut block = crate::backend::obj::Block { oid: "ct-reg-asker".into(), parentoref: String::new(), version: 1, runtimeopts: None, stickers: None, meta: Default::default(), subblockids: None };
1090        block.meta.insert("agentName".into(), serde_json::json!("QTest"));
1091        state.mstore.insert(&mut block).unwrap();
1092        state.reactive_handler.register_agent("qtest", "ct-reg-asker", None).unwrap();
1093        let a = request(&state, "ct-reg-target", "qtest", "FleetBulkStop", "", close_tab());
1094        assert_eq!(a.by, "QTest");
1095        let b = request(&state, "ct-reg-target", "qtest", "FleetBulkStop", "", close_tab());
1096        assert!(b.joined);
1097        assert_eq!(audit_note(&state, &b, "qtest", "FleetBulkStop"), format!("joined its own pending request {}", a.request_id));
1098        assert!(audit_note(&state, &b, "someone-else", "FleetBulkStop").contains("by QTest's pending request"));
1099        keep(&state, "ct-reg-target", &a.request_id);
1100    }
1101
1102    #[tokio::test]
1103    async fn the_asker_s_name_is_cleaned_for_display() {
1104        let state = test_state();
1105        let v = request(&state, "ct-by", "Ev\u{202E}il\u{0007}", "FleetBulkStop", "", close_tab());
1106        assert_eq!(v.by, "Evil");
1107        assert_eq!(audit_note(&state, &PendingView { joined: true, ..v.clone() }, "Ev\u{202E}il\u{0007}", "FleetBulkStop"), format!("joined its own pending request {}", v.request_id));
1108        keep(&state, "ct-by", &v.request_id);
1109    }
1110
1111    #[test]
1112    fn the_stop_effect_keeps_its_own_wording() {
1113        let stop = PendingView {
1114            request_id: "r".into(),
1115            block_id: "b".into(),
1116            by: "Settings".into(),
1117            target: "t".into(),
1118            via: "FleetBulkStop".into(),
1119            reason: String::new(),
1120            effect: "stop",
1121            deadline_ms: 0,
1122            status: "pending",
1123            error: None,
1124            blocks: None,
1125            outcomes: None,
1126            joined: false,
1127        };
1128        assert_eq!(toast_body(&stop), "Settings asked to stop it. Open it to keep it running.");
1129        // A pane with no agent in it has no conversation to keep: no My Agents claim.
1130        assert_eq!(toast_body(&PendingView { effect: "close_pane", ..stop.clone() }), "Settings asked to close it.");
1131        assert!(toast_body(&PendingView { effect: "close_tab", ..stop }).contains("My Agents"));
1132    }
1133}