1use std::sync::Mutex;
25use std::time::Duration;
26
27use axum::extract::State;
28use axum::http::StatusCode;
29use axum::response::{IntoResponse, Response};
30use axum::Json;
31use serde::Deserialize;
32use serde_json::json;
33
34use super::external_host::{host, Refusal};
35use super::AppState;
36use crate::backend::blockcontroller::{get_all_controllers, shell::ShellController, STATUS_RUNNING};
37use crate::backend::shutdown_events::WorkspaceStopView;
38
39pub(crate) const ACTIVE_WINDOW_MS: i64 = 10 * 60 * 1000;
41const MAX_DEADLINE_SECS: u64 = 120;
43const MAX_AHEAD_MS: u64 = 7 * 24 * 60 * 60 * 1000;
45const SKEW_MS: u64 = 60 * 1000;
47const NOTE_KEY: &str = "workspace-stop";
49const REMIND_BEFORE_MS: u64 = 60 * 1000;
51
52fn current_ms() -> u64 {
53 agentmux_common::time::now_ms_u64()
54}
55
56fn refused((status, error): Refusal) -> Response {
57 (status, Json(json!({ "ok": false, "error": error }))).into_response()
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub(crate) struct Seen {
63 pub turn_active: bool,
64 pub last_output_ms: Option<i64>,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub(crate) struct Activity {
69 pub busy: bool,
70 pub agents_working: usize,
71 pub last_output_at: Option<i64>,
72}
73
74pub(crate) fn summarize(running: &[Seen], now_ms: i64) -> Activity {
77 let recent = |s: &Seen| s.last_output_ms.is_some_and(|t| now_ms - t <= ACTIVE_WINDOW_MS);
78 let agents_working = running.iter().filter(|s| s.turn_active && recent(s)).count();
79 Activity {
80 busy: agents_working > 0 || running.iter().any(recent),
81 agents_working,
82 last_output_at: running.iter().filter_map(|s| s.last_output_ms).max(),
83 }
84}
85
86fn running_panes(now_ms: i64) -> Vec<Seen> {
87 get_all_controllers()
88 .values()
89 .filter_map(|ctrl| {
90 let status = ctrl.get_runtime_status();
91 if status.shellprocstatus != STATUS_RUNNING {
92 return None;
93 }
94 let last_output_ms = match ctrl.as_any().downcast_ref::<ShellController>() {
95 Some(shell) => shell.last_output_secs_ago().map(|secs| now_ms - secs as i64 * 1000),
96 None => ctrl.last_output_ms(),
97 };
98 Some(Seen { turn_active: status.turn_active, last_output_ms })
99 })
100 .collect()
101}
102
103#[derive(Debug, Deserialize)]
104#[serde(rename_all = "camelCase")]
105pub(crate) struct ActivityRequest {
106 v: u32,
107 workspace: String,
108 issued_at: u64,
109 sig: String,
110}
111
112pub(crate) async fn handle_activity(Json(req): Json<ActivityRequest>) -> Response {
114 let Some(host) = host() else { return not_registered() };
115 if req.v != 1 {
116 return refused((StatusCode::BAD_REQUEST, "unsupported version"));
117 }
118 if let Err(r) = host.check_call("activity", &req.workspace, req.issued_at, "", &req.sig, agentmux_common::time::now_secs_u64()) {
119 return refused(r);
120 }
121 let now = current_ms() as i64;
122 let a = summarize(&running_panes(now), now);
123 let keep = current().1.map(|k| json!({ "minutes": k.minutes, "by": k.by, "atMs": k.at_ms }));
124 Json(json!({ "ok": true, "busy": a.busy, "agentsWorking": a.agents_working, "lastOutputAt": a.last_output_at, "keepRunning": keep })).into_response()
125}
126
127#[derive(Debug, Deserialize)]
128#[serde(rename_all = "camelCase")]
129pub(crate) struct ShutdownRequest {
130 v: u32,
131 workspace: String,
132 issued_at: u64,
133 deadline_seconds: u64,
134 sig: String,
135}
136
137pub(crate) async fn handle_shutdown(State(state): State<AppState>, Json(req): Json<ShutdownRequest>) -> Response {
140 let Some(host) = host() else { return not_registered() };
141 if req.v != 1 || !(1..=MAX_DEADLINE_SECS).contains(&req.deadline_seconds) {
142 return refused((StatusCode::BAD_REQUEST, "a field is not valid"));
143 }
144 let args = req.deadline_seconds.to_string();
145 if let Err(r) = host.check_call("shutdown", &req.workspace, req.issued_at, &args, &req.sig, agentmux_common::time::now_secs_u64()) {
146 return refused(r);
147 }
148 tracing::info!(deadline_seconds = req.deadline_seconds, "the external host asked for a graceful shutdown");
149 let mut teardown = tokio::spawn({
152 let state = state.clone();
153 async move { crate::sagas::agent_teardown::app_exit(&state).await }
154 });
155 match tokio::time::timeout(Duration::from_secs(req.deadline_seconds), &mut teardown).await {
156 Ok(Ok(closed)) => Json(json!({ "ok": true, "done": true, "closed": closed })).into_response(),
157 Ok(Err(e)) => {
158 tracing::warn!("the graceful shutdown task ended abnormally: {e}");
159 refused((StatusCode::INTERNAL_SERVER_ERROR, "the shutdown did not complete"))
160 }
161 Err(_) => Json(json!({ "ok": true, "done": false })).into_response(),
162 }
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub(crate) enum Reason {
168 Person,
169 Timer { idle_minutes: u32 },
170 Credit,
171 Cap,
172}
173
174impl Reason {
175 pub(crate) fn id(self) -> &'static str {
176 match self {
177 Reason::Person => "person",
178 Reason::Timer { .. } => "timer",
179 Reason::Credit => "credit",
180 Reason::Cap => "cap",
181 }
182 }
183
184 pub(crate) fn phrase(self) -> String {
186 match self {
187 Reason::Person => "you asked".to_string(),
188 Reason::Timer { idle_minutes } => format!("nothing has happened for {idle_minutes} minutes"),
189 Reason::Credit => "your credit ran out".to_string(),
190 Reason::Cap => "a daily cap was reached".to_string(),
191 }
192 }
193}
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub(crate) struct Stop {
198 pub at_ms: u64,
199 pub reason: Reason,
200}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub(crate) enum Notice {
205 Set(Stop),
206 Clear,
207}
208
209pub(crate) fn parse_notice(stop_at: Option<u64>, reason: Option<&str>, idle_minutes: Option<u32>, now_ms: u64) -> Result<Notice, &'static str> {
212 let (Some(at_ms), Some(reason)) = (stop_at, reason) else {
213 return match (stop_at, reason, idle_minutes) {
214 (None, None, None) => Ok(Notice::Clear),
215 _ => Err("a stop needs both a time and a reason"),
216 };
217 };
218 if at_ms.saturating_add(SKEW_MS) < now_ms || at_ms > now_ms.saturating_add(MAX_AHEAD_MS) {
219 return Err("the stop time is not within a week ahead");
220 }
221 let reason = match (reason, idle_minutes) {
222 ("timer", Some(m)) if (1..=1440).contains(&m) => Reason::Timer { idle_minutes: m },
223 ("timer", _) => return Err("a timer stop needs idleMinutes between 1 and 1440"),
224 (_, Some(_)) => return Err("idleMinutes goes only with a timer stop"),
225 ("person", None) => Reason::Person,
226 ("credit", None) => Reason::Credit,
227 ("cap", None) => Reason::Cap,
228 _ => return Err("the reason is not one of person, timer, credit, cap"),
229 };
230 Ok(Notice::Set(Stop { at_ms, reason }))
231}
232
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub(crate) enum Plan {
236 Nothing,
238 Announce(Stop),
239 Cancel,
240}
241
242pub(crate) fn plan(held: Option<Stop>, notice: Notice) -> Plan {
243 match (held, notice) {
244 (Some(h), Notice::Set(s)) if h == s => Plan::Nothing,
245 (_, Notice::Set(s)) => Plan::Announce(s),
246 (Some(_), Notice::Clear) => Plan::Cancel,
247 (None, Notice::Clear) => Plan::Nothing,
248 }
249}
250
251pub(crate) fn clock(at_ms: u64) -> String {
253 let secs = at_ms / 1000;
254 format!("{:02}:{:02} UTC", (secs / 3600) % 24, (secs / 60) % 60)
255}
256
257pub(crate) fn stop_note(stop: Stop) -> String {
259 format!("This workspace stops at {} because {}. Your conversation is saved.", clock(stop.at_ms), stop.reason.phrase())
260}
261
262pub(crate) fn remind_note(stop: Stop) -> String {
264 format!("This workspace stops in about a minute, at {}, because {}. Your conversation is saved.", clock(stop.at_ms), stop.reason.phrase())
265}
266
267pub(crate) const CANCEL_NOTE: &str = "The workspace's stop was cancelled; it keeps running.";
269
270#[derive(Debug, Clone, PartialEq, Eq)]
272pub(crate) struct KeepRunning {
273 pub minutes: u32,
274 pub by: String,
275 pub at_ms: u64,
276}
277
278pub(crate) const MAX_KEEP_MINUTES: u32 = 240;
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub(crate) enum KeepRefusal {
284 Minutes,
285 NoStop,
286}
287
288impl KeepRefusal {
289 pub(crate) fn message(self) -> &'static str {
290 match self {
291 KeepRefusal::Minutes => "minutes is a whole number from 1 to 240",
292 KeepRefusal::NoStop => "the workspace has no stop pending, so there is nothing to put back",
293 }
294 }
295}
296
297#[derive(Debug, Default)]
300pub(crate) struct Held {
301 stop: Option<Stop>,
302 keep: Option<KeepRunning>,
303 generation: u64,
304}
305
306impl Held {
307 fn take(&mut self, notice: Notice) -> Option<(Plan, u64)> {
310 let what = plan(self.stop, notice);
311 match what {
312 Plan::Nothing => return None,
313 Plan::Announce(s) => self.stop = Some(s),
314 Plan::Cancel => self.stop = None,
315 }
316 self.keep = None;
317 self.generation += 1;
318 Some((what, self.generation))
319 }
320
321 pub(crate) fn ask_keep_running(&mut self, minutes: u32, by: &str, at_ms: u64) -> Result<KeepRunning, KeepRefusal> {
324 if !(1..=MAX_KEEP_MINUTES).contains(&minutes) {
325 return Err(KeepRefusal::Minutes);
326 }
327 if self.stop.is_none() {
328 return Err(KeepRefusal::NoStop);
329 }
330 let keep = KeepRunning { minutes, by: by.to_string(), at_ms };
331 self.keep = Some(keep.clone());
332 Ok(keep)
333 }
334}
335
336static HELD: Mutex<Held> = Mutex::new(Held { stop: None, keep: None, generation: 0 });
337
338fn held() -> std::sync::MutexGuard<'static, Held> {
339 HELD.lock().unwrap_or_else(|e| e.into_inner())
340}
341
342pub(crate) fn current() -> (Option<Stop>, Option<KeepRunning>) {
344 let h = held();
345 (h.stop, h.keep.clone())
346}
347
348pub(crate) fn ask_keep_running(minutes: u32, by: &str) -> Result<KeepRunning, KeepRefusal> {
350 held().ask_keep_running(minutes, by, current_ms())
351}
352
353#[derive(Debug, Deserialize)]
354#[serde(rename_all = "camelCase")]
355pub(crate) struct NoticeRequest {
356 v: u32,
357 workspace: String,
358 issued_at: u64,
359 stop_at: Option<u64>,
360 reason: Option<String>,
361 idle_minutes: Option<u32>,
362 sig: String,
363}
364
365fn text_of(v: Option<impl ToString>) -> String {
366 v.map_or_else(|| "-".to_string(), |x| x.to_string())
367}
368
369fn tell_agents(state: &AppState, text: &str) {
370 for agent in crate::backend::reactive::get_global_handler().list_agents() {
371 if let Err(e) = state.reactive_handler.hold_system_note(&agent.agent_id, NOTE_KEY, text) {
372 tracing::debug!(agent = %agent.agent_id, "workspace stop note not held: {e}");
373 }
374 }
375}
376
377fn publish(state: &AppState, view: &WorkspaceStopView) {
378 state.broker.publish_event::<crate::backend::mps_events::WorkspaceStop>(view, vec![], 1);
379}
380
381pub(crate) async fn handle_notice(State(state): State<AppState>, Json(req): Json<NoticeRequest>) -> Response {
383 let Some(host) = host() else { return not_registered() };
384 if req.v != 1 {
385 return refused((StatusCode::BAD_REQUEST, "unsupported version"));
386 }
387 let args = format!("{},{},{}", text_of(req.stop_at), text_of(req.reason.as_deref()), text_of(req.idle_minutes));
389 if let Err(r) = host.check_call("notice", &req.workspace, req.issued_at, &args, &req.sig, agentmux_common::time::now_secs_u64()) {
390 return refused(r);
391 }
392 let notice = match parse_notice(req.stop_at, req.reason.as_deref(), req.idle_minutes, current_ms()) {
393 Ok(n) => n,
394 Err(why) => return refused((StatusCode::BAD_REQUEST, why)),
395 };
396 apply(&state, notice);
397 Json(json!({ "ok": true })).into_response()
398}
399
400fn apply(state: &AppState, notice: Notice) {
402 let Some((what, generation)) = held().take(notice) else { return };
403 match what {
404 Plan::Announce(stop) => {
405 tracing::info!(reason = stop.reason.id(), stop_at_ms = stop.at_ms, "the external host set a workspace stop");
406 publish(state, &WorkspaceStopView { status: "pending", stop_at_ms: stop.at_ms as i64, reason_id: stop.reason.id().to_string(), reason: stop.reason.phrase() });
407 tell_agents(state, &stop_note(stop));
408 remind_later(state.clone(), stop, generation);
409 }
410 Plan::Cancel => {
411 tracing::info!("the external host cancelled the workspace stop");
412 publish(state, &WorkspaceStopView { status: "cleared", stop_at_ms: 0, reason_id: String::new(), reason: String::new() });
413 tell_agents(state, CANCEL_NOTE);
414 }
415 Plan::Nothing => {}
416 }
417}
418
419fn remind_later(state: AppState, stop: Stop, generation: u64) {
421 let wait = stop.at_ms.saturating_sub(REMIND_BEFORE_MS).saturating_sub(current_ms());
422 if wait == 0 {
423 return;
424 }
425 tokio::spawn(async move {
426 tokio::time::sleep(Duration::from_millis(wait)).await;
427 if held().generation == generation {
428 tell_agents(&state, &remind_note(stop));
429 }
430 });
431}
432
433fn not_registered() -> Response {
434 refused((StatusCode::NOT_FOUND, "no external host is registered"))
435}
436
437#[cfg(test)]
438#[path = "host_control_tests.rs"]
439mod tests;