Skip to main content

agentmux_srv_core/backend/
shutdown_events.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The shutdown events an agent pane's close and its pending window publish, and the cleaner for the text
5//! they show. They live in the core so `backend/` names them without reaching up into `sagas/`; the sagas
6//! re-export them under their old paths. The wire shape is pinned by `sagas/shutdown_events_tests.rs`.
7
8use serde::Serialize;
9
10/// `agent:shutdown` — the shutdown log a closing pane shows
11/// (SPEC_AGENT_SELF_QUIT_2026_09_24.md §5.5, §12.1).
12pub const EVENT_AGENT_SHUTDOWN: &str = "agent:shutdown";
13
14/// One `agent:shutdown` line (`mps_events::AgentShutdown`): its order, step and text, and what
15/// the step adds.
16#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
17#[ts(export, export_to = "../../../frontend/types/rpc/")]
18pub struct ShutdownLineEvent {
19    pub block_id: String,
20    #[ts(type = "number")]
21    pub seq: u64,
22    pub step: String,
23    pub text: String,
24    #[serde(flatten)]
25    pub extra: ShutdownExtra,
26}
27
28/// What a shutdown line can add beyond its step and text. Each is omitted when absent.
29#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, ts_rs::TS)]
30#[ts(export, export_to = "../../../frontend/types/rpc/")]
31pub struct ShutdownExtra {
32    /// `kill`: how long the agent had before it was killed.
33    #[serde(skip_serializing_if = "Option::is_none")]
34    #[ts(optional, type = "number")]
35    pub forced_after_ms: Option<u64>,
36    /// `error`: why the pane couldn't close.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    #[ts(optional)]
39    pub error: Option<String>,
40    /// `container`: a Compose container left running, and that it was left.
41    #[serde(skip_serializing_if = "Option::is_none")]
42    #[ts(optional)]
43    pub container: Option<String>,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    #[ts(optional)]
46    pub outcome: Option<String>,
47    /// `process` / `survivor`: one of the agent's processes, and what became of it.
48    #[serde(skip_serializing_if = "Option::is_none")]
49    #[ts(optional)]
50    pub process: Option<ShutdownProcess>,
51}
52
53#[derive(Debug, Clone, PartialEq, serde::Serialize, ts_rs::TS)]
54#[ts(export, export_to = "../../../frontend/types/rpc/")]
55pub struct ShutdownProcess {
56    pub pid: u32,
57    pub name: String,
58    /// `killed`, `stopped`, `survived` or `escaped`.
59    pub outcome: String,
60}
61
62pub const EVENT_SHUTDOWN_PENDING: &str = "agent:shutdown-pending";
63pub const EVENT_SHUTDOWN_PENDING_CLEARED: &str = "agent:shutdown-pending-cleared";
64
65/// A request as the caller and the frontend see it (§12.2).
66#[derive(Clone, Debug, Serialize, PartialEq, Eq, ts_rs::TS)]
67#[ts(export, export_to = "../../../frontend/types/rpc/")]
68pub struct PendingView {
69    pub request_id: String,
70    pub block_id: String,
71    /// Who asked: an agent id, or `cron` etc.
72    pub by: String,
73    /// The agent being shut down, resolved when asked (it may be gone after).
74    pub target: String,
75    /// The tool: `QuitSelf`, `ClosePane`, `FleetBulkStop`.
76    pub via: String,
77    /// Why, in the asker's words, cleaned for display (`clean_reason`): never
78    /// the raw text. Shown on the pane banner only; an OS toast leaves it out.
79    pub reason: String,
80    /// What happens if the window runs out: `stop` (the agent stops, its pane
81    /// stays), `close_tab` (it stops and its tab closes) or `close_pane`.
82    #[ts(type = r#""stop" | "close_tab" | "close_pane""#)]
83    pub effect: &'static str,
84    #[ts(type = "number")]
85    pub deadline_ms: i64,
86    /// `pending` → `kept_by_user`, or `proceeding` → `shut_down` / `failed` /
87    /// `superseded` (the user closed it themselves meanwhile).
88    #[ts(type = r#""pending" | "kept_by_user" | "proceeding" | "shut_down" | "failed" | "superseded""#)]
89    pub status: &'static str,
90    #[serde(skip_serializing_if = "Option::is_none")]
91    #[ts(optional)]
92    pub error: Option<String>,
93    /// A request for several agents at once (`Stop agents`): the ones still waiting. Absent for one.
94    #[serde(skip_serializing_if = "Option::is_none")]
95    #[ts(optional)]
96    pub blocks: Option<Vec<BatchBlock>>,
97    /// What became of each agent of such a request: kept by the user, or how its close ended. Filled as
98    /// the user keeps one, and once the request settles.
99    #[serde(skip_serializing_if = "Option::is_none")]
100    #[ts(optional)]
101    pub outcomes: Option<Vec<BlockOutcome>>,
102    /// This caller joined a request already open for the block rather than
103    /// opening one. Never stored; set on the view `request` returns.
104    #[serde(skip)]
105    #[ts(skip)]
106    pub joined: bool,
107}
108
109/// `agent:shutdown-pending-cleared`: the request ended, and how.
110#[derive(Clone, Debug, Serialize, ts_rs::TS)]
111#[ts(export, export_to = "../../../frontend/types/rpc/")]
112pub struct PendingClearedEvent {
113    pub block_id: String,
114    pub request_id: String,
115    pub outcome: String,
116}
117
118/// An agent of a batch.
119#[derive(Clone, Debug, Serialize, PartialEq, Eq, ts_rs::TS)]
120#[ts(export, export_to = "../../../frontend/types/rpc/")]
121pub struct BatchBlock {
122    pub block_id: String,
123    /// Its display name, cleaned for the user.
124    pub name: String,
125}
126
127/// What became of one agent of a batch.
128#[derive(Clone, Debug, Serialize, PartialEq, Eq, ts_rs::TS)]
129#[ts(export, export_to = "../../../frontend/types/rpc/")]
130pub struct BlockOutcome {
131    pub block_id: String,
132    pub name: String,
133    /// `kept_by_user`, or how its close ended: `shut_down`, `superseded` (already gone) or `failed`.
134    #[ts(type = r#""kept_by_user" | "shut_down" | "superseded" | "failed""#)]
135    pub outcome: &'static str,
136    #[serde(skip_serializing_if = "Option::is_none")]
137    #[ts(optional)]
138    pub error: Option<String>,
139}
140
141/// The longest reason the banner shows.
142pub const REASON_MAX: usize = 120;
143/// Shown in place of a reason that looks like it holds a credential or asks
144/// for something destructive.
145pub const REASON_HIDDEN: &str = "Reason hidden: it looks sensitive.";
146
147/// A caller's reason, cleaned for the user to read (spec §3.11). Replaced
148/// wholesale by `REASON_HIDDEN` when it trips the keyword list the jekt tier
149/// gate and notification previews use; otherwise its first line, control and
150/// bidi-override characters removed, whitespace collapsed, cut at
151/// `REASON_MAX`. Markup is not interpreted here: the banner renders it as
152/// text and a toast never carries it.
153pub fn clean_reason(raw: &str) -> String {
154    if crate::backend::reactive::sanitize::is_sensitive_message(raw) {
155        return REASON_HIDDEN.to_string();
156    }
157    let Some(first) = raw.lines().map(str::trim).find(|l| !l.is_empty()) else {
158        return String::new();
159    };
160    clean_line(first, REASON_MAX)
161}
162
163/// `workspace:stop` — a headless workspace is going to stop at a time, or is not any more
164/// (`server::host_control`, which the registered external host calls). It carries no words of a person's or an
165/// agent's: `reason` is one of a fixed set of phrases.
166pub const EVENT_WORKSPACE_STOP: &str = "workspace:stop";
167
168/// A workspace stop as the page shows it: `pending` with the stop time and why, or `cleared`.
169#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, ts_rs::TS)]
170#[ts(export, export_to = "../../../frontend/types/rpc/")]
171pub struct WorkspaceStopView {
172    #[ts(type = r#""pending" | "cleared""#)]
173    pub status: &'static str,
174    /// When the workspace stops (unix ms); 0 when `cleared`.
175    #[ts(type = "number")]
176    pub stop_at_ms: i64,
177    /// `person`, `timer`, `credit` or `cap`; empty when `cleared`.
178    pub reason_id: String,
179    /// The reason as a person reads it ("you asked", "nothing has happened for 50 minutes"); empty when `cleared`.
180    pub reason: String,
181}
182
183/// One line for display: bidi-override characters removed, control characters
184/// turned into spaces, whitespace collapsed, cut at `max` characters.
185pub fn clean_line(raw: &str, max: usize) -> String {
186    let cleaned: String = raw
187        .chars()
188        .filter(|c| !crate::backend::notify::router::is_bidi_control(*c))
189        .map(|c| if c.is_control() { ' ' } else { c })
190        .collect();
191    let line = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");
192    let mut out: String = line.chars().take(max).collect();
193    if line.chars().count() > max {
194        out.push('…');
195    }
196    out
197}