1use 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
28pub const OVERRIDE_WINDOW: std::time::Duration = std::time::Duration::from_secs(30);
31pub const SELF_QUIT_WINDOW: std::time::Duration = std::time::Duration::from_secs(15);
34pub const BROWSER_CLOSE_WINDOW: std::time::Duration = std::time::Duration::from_secs(10);
36
37pub 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}
50const KEEP_FINISHED_MS: i64 = 10 * 60 * 1000;
52
53#[derive(Clone, Debug)]
55pub enum Action {
56 SelfQuit { detail: String },
59 CloseTab { detail: String },
64 CloseTabs { block_ids: Vec<String>, detail: String },
67 ClosePane { block_ids: Vec<String> },
69 Stop { signal: Option<String>, stop_background: Option<bool> },
72 Release { to: String },
76}
77
78impl Action {
79 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 fn window(&self) -> std::time::Duration {
91 match self {
92 Action::SelfQuit { .. } => SELF_QUIT_WINDOW,
93 _ => OVERRIDE_WINDOW,
94 }
95 }
96
97 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 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 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 *stop_background = match (*stop_background, their_background) {
127 (Some(a), Some(b)) => Some(a || b),
128 (a, b) => a.or(b),
129 };
130 }
131 (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
145pub 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 action: Option<Action>,
156 requesters: Vec<(String, String, String)>,
161 covers: Vec<String>,
168 closing: bool,
171 told: Vec<(String, String)>,
174}
175
176static ENTRIES: LazyLock<Mutex<HashMap<String, Entry>>> = LazyLock::new(Default::default);
177
178#[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
190pub 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 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
202pub 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
221pub 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
230fn 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
239fn 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
265fn 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
274pub 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 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 if pending && (stronger || grew) {
339 let view = PendingView { joined: false, ..joined.clone() };
342 for b in &covers {
343 publish_pending(state, b, &view);
344 }
345 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 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
399fn 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; };
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 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
432pub 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
450fn 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
465fn 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
499fn 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
507fn 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 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 tokio::task::spawn_blocking(move || router.emit_shutdown(&block, Some(body), info));
530}
531
532pub 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
544const BY_MAX: usize = 64;
546
547pub(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
560pub(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
568fn 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
587fn 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
594pub fn audit_note(state: &AppState, v: &PendingView, by: &str, via: &str) -> String {
597 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
618fn toast_block(v: &PendingView) -> String {
620 if v.blocks.is_some() { batch::group(&v.request_id) } else { v.block_id.clone() }
621}
622
623fn 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 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 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 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#[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#[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
688pub fn keep(state: &AppState, block_id: &str, request_id: &str) -> &'static str {
691 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 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
717pub 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 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 #[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 #[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 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 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 assert_eq!(status(&v.request_id).unwrap().status, "superseded");
914 }
915
916 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 #[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 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 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 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 #[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 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 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 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 let body = toast_body(&v);
1060 assert_eq!(body, "AgentY asked to close it. It stays in My Agents, with its conversation.");
1061 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 #[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 #[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 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}