1use serde::Serialize;
37
38use crate::backend::blockcontroller;
39pub(crate) use crate::backend::work_claims::release_claims;
40use crate::server::agent_resources::{self, AgentIdentity, AgentResources};
41use crate::server::AppState;
42
43use super::close_pane::{exit_line, process_extra, process_line, publish_shutdown, save_final_state, short_command, ShutdownExtra};
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub enum CliStop {
48 Graceful,
52 StopOnly { graceful: bool },
56 Replace,
61}
62
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub struct Policy {
67 pub cli: CliStop,
68 pub release_claims: bool,
71 pub stop_shell_sessions: bool,
73 pub stop_background: bool,
77 pub stop_container: bool,
81 pub dock_floaters: bool,
85}
86
87impl Policy {
88 pub const fn close() -> Self {
92 Self { cli: CliStop::Graceful, release_claims: false, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false }
93 }
94 pub const fn quit() -> Self {
96 Self { cli: CliStop::Graceful, release_claims: true, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false }
97 }
98 pub const fn stop(graceful: bool, stop_background: bool) -> Self {
102 Self { cli: CliStop::StopOnly { graceful }, release_claims: true, stop_shell_sessions: false, stop_background, stop_container: false, dock_floaters: true }
103 }
104 pub const fn stop_cli_only(graceful: bool) -> Self {
108 Self { cli: CliStop::StopOnly { graceful }, release_claims: false, stop_shell_sessions: false, stop_background: false, stop_container: false, dock_floaters: false }
109 }
110 pub const fn replace() -> Self {
112 Self { cli: CliStop::Replace, release_claims: false, stop_shell_sessions: false, stop_background: false, stop_container: false, dock_floaters: false }
113 }
114 pub const fn app_exit() -> Self {
118 Self { cli: CliStop::Graceful, release_claims: false, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false }
119 }
120}
121
122pub const SETTING_STOP_KEEPS_BACKGROUND: &str = "agent:stopkeepsbackground";
126
127pub const APP_EXIT_CAP: std::time::Duration = agentmux_common::process::SRV_APP_EXIT_CAP;
132
133const SHELL_SWEEP_GRACE: std::time::Duration = std::time::Duration::from_millis(800);
135
136#[derive(Clone, Debug, Default, Serialize)]
138pub struct TeardownReport {
139 pub block_id: String,
140 pub agent: String,
142 pub released_claims: usize,
143 pub stopped_shells: usize,
144 pub crons_targeting: Vec<String>,
146 pub stopped_background: usize,
148 #[serde(skip_serializing_if = "Option::is_none")]
151 pub stop_error: Option<String>,
152 pub stopped_container: Option<String>,
154 #[serde(skip_serializing_if = "Vec::is_empty")]
157 pub containers_left: Vec<String>,
158 pub survivors: Vec<agent_resources::ProcessEntry>,
161 pub before: AgentResources,
163}
164
165static CLOSES: std::sync::LazyLock<tokio_util::task::TaskTracker> =
170 std::sync::LazyLock::new(tokio_util::task::TaskTracker::new);
171
172pub(crate) async fn detached<T: Send + 'static>(fut: impl std::future::Future<Output = T> + Send + 'static) -> Option<T> {
175 CLOSES.spawn(fut).await.ok()
176}
177
178pub async fn run_many(state: &AppState, block_ids: &[String], policy: Policy) -> Vec<TeardownReport> {
181 let deadline = std::time::Instant::now() + blockcontroller::SHUTDOWN_GRACE;
182 let teardowns = block_ids.iter().map(|id| {
183 let (st, id) = (state.clone(), id.clone());
184 async move {
185 let report = detached({
186 let id = id.clone();
187 async move { run_one(&st, &id, policy, deadline).await }
188 })
189 .await;
190 report.unwrap_or_else(|| {
191 tracing::error!(block_id = %id, "agent_teardown: teardown panicked");
192 TeardownReport { agent: id.clone(), block_id: id, ..Default::default() }
193 })
194 }
195 });
196 futures_util::future::join_all(teardowns).await
197}
198
199pub async fn run(state: &AppState, block_id: &str, policy: Policy) -> TeardownReport {
201 run_many(state, std::slice::from_ref(&block_id.to_string()), policy)
202 .await
203 .pop()
204 .unwrap_or_default()
205}
206
207pub fn stop_now(block_id: &str, graceful: bool) -> Result<(), String> {
211 debug_assert!(matches!(Policy::stop_cli_only(graceful).cli, CliStop::StopOnly { .. }));
212 let ctrl = blockcontroller::get_controller(block_id)
213 .ok_or_else(|| format!("NOT_RUNNING: no controller for block {block_id}"))?;
214 ctrl.stop(graceful, blockcontroller::STATUS_DONE)?;
215 crate::server::browser_session_close::close_for_stop(block_id);
217 Ok(())
218}
219
220pub async fn stop(state: &AppState, block_id: &str, graceful: bool, stop_background: Option<bool>) -> Result<TeardownReport, String> {
226 if blockcontroller::get_controller(block_id).is_none() {
227 return Err(format!("NOT_RUNNING: no controller for block {block_id}"));
228 }
229 let stop_background = stop_background.unwrap_or_else(|| !stop_keeps_background(state));
230 let report = run(state, block_id, Policy::stop(graceful, stop_background)).await;
231 match report.stop_error {
232 Some(e) => Err(e),
233 None => {
234 use crate::server::app_api::agent_attach::{set_desired, DESIRED_STOPPED};
236 set_desired(&state.mstore, block_id, DESIRED_STOPPED);
237 Ok(report)
238 }
239 }
240}
241
242fn stop_keeps_background(state: &AppState) -> bool {
243 state
244 .config_watcher
245 .get_settings()
246 .extra
247 .get(SETTING_STOP_KEEPS_BACKGROUND)
248 .and_then(|v| v.as_bool())
249 .unwrap_or(true)
250}
251
252pub fn discard(block_id: &str) {
258 blockcontroller::delete_controller(block_id);
259}
260
261pub fn replace_now(ctrl: &dyn blockcontroller::Controller) -> Result<(), String> {
265 debug_assert!(matches!(Policy::replace().cli, CliStop::Replace));
266 ctrl.stop_for_replace(blockcontroller::STATUS_DONE)
267}
268
269pub async fn app_exit(state: &AppState) -> usize {
275 crate::backend::blockcontroller::durable_ssh::note_app_exiting();
278 let all: Vec<String> = blockcontroller::get_all_controllers().into_keys().collect();
279 let ids = {
282 let (st, ids) = (state.clone(), all.clone());
283 tokio::task::spawn_blocking(move || without_sub_blocks(&st, ids)).await.unwrap_or(all)
284 };
285 let cap = APP_EXIT_CAP.saturating_sub(SHELL_SWEEP_GRACE);
286 record_turns_in_flight(state, &ids).await;
289 crate::server::restart_resume::record_running_at_exit(state, &ids).await;
291 let all_closed = async {
292 run_many(state, &ids, Policy::app_exit()).await;
293 CLOSES.close();
297 CLOSES.wait().await;
298 };
299 if tokio::time::timeout(cap, all_closed).await.is_err() {
300 tracing::warn!(agents = ids.len(), "app exit: teardown hit the cap; the launcher's backstop takes the rest");
301 }
302 let live = state.shell_sessions.stop_all();
305 if live > 0 {
306 tracing::info!(count = live, "app exit: stopping leftover persistent shells");
307 tokio::time::sleep(SHELL_SWEEP_GRACE).await;
308 }
309 ids.len()
310}
311
312async fn record_turns_in_flight(state: &AppState, ids: &[String]) {
318 let controllers = blockcontroller::get_all_controllers();
319 let busy: Vec<String> = ids
320 .iter()
321 .filter(|id| controllers.get(*id).is_some_and(|c| c.get_runtime_status().turn_active))
322 .cloned()
323 .collect();
324 let st = state.clone();
325 let agents = tokio::task::spawn_blocking(move || {
326 distinct_agents(busy.iter().filter_map(|id| {
327 let block = st.mstore.get::<crate::backend::obj::Block>(id).ok().flatten()?;
328 Some(crate::backend::obj::meta_get_string(&block.meta, "agentId", ""))
329 }))
330 })
331 .await
332 .unwrap_or_default();
333 if let Some(paths) = agentmux_common::DataPaths::from_env() {
334 crate::backend::upgrade_notice::record_interrupted(&paths.instance_dir, &agents, agentmux_common::time::now_ms());
335 }
336 if !agents.is_empty() {
337 tracing::info!(count = agents.len(), "app exit: agents with a turn in flight recorded");
338 }
339}
340
341async fn note_turn_cut_off_by_quit(state: &AppState, block_id: &str) {
346 let st = state.clone();
347 let id = block_id.to_string();
348 let agent = tokio::task::spawn_blocking(move || {
349 if !crate::server::service::session_closed::quit_under_way(&st.mstore) {
350 return None;
351 }
352 let block = st.mstore.get::<crate::backend::obj::Block>(&id).ok().flatten()?;
353 distinct_agents([crate::backend::obj::meta_get_string(&block.meta, "agentId", "")]).pop()
354 })
355 .await
356 .ok()
357 .flatten();
358 if let (Some(agent), Some(paths)) = (agent, agentmux_common::DataPaths::from_env()) {
359 crate::backend::upgrade_notice::record_interrupted(&paths.instance_dir, &[agent], agentmux_common::time::now_ms());
360 }
361}
362
363fn distinct_agents(ids: impl IntoIterator<Item = String>) -> Vec<String> {
366 let mut agents: Vec<String> = ids.into_iter().map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).collect();
367 agents.sort();
368 agents.dedup();
369 agents
370}
371
372pub(crate) fn without_sub_blocks(state: &AppState, ids: Vec<String>) -> Vec<String> {
375 let subs: std::collections::HashSet<String> = ids
376 .iter()
377 .filter_map(|id| state.mstore.get::<crate::backend::obj::Block>(id).ok().flatten())
378 .flat_map(|b| b.subblockids.unwrap_or_default())
379 .collect();
380 ids.into_iter().filter(|id| !subs.contains(id)).collect()
381}
382
383async fn run_one(state: &AppState, block_id: &str, policy: Policy, deadline: std::time::Instant) -> TeardownReport {
384 let started = std::time::Instant::now();
385 let who = AgentIdentity::of(state, block_id);
387 let before = {
390 let (st, id) = (state.clone(), block_id.to_string());
391 tokio::task::spawn_blocking(move || agent_resources::snapshot(&st, &id))
392 .await
393 .unwrap_or_default()
394 };
395 let mut report = TeardownReport {
396 block_id: block_id.to_string(),
397 agent: who.label(block_id),
398 before: before.clone(),
399 ..Default::default()
400 };
401
402 if let CliStop::StopOnly { graceful } = policy.cli {
405 if let Err(e) = stop_now(block_id, graceful) {
406 tracing::warn!(block_id = %block_id, error = %e, "agent_teardown: stop failed; nothing else touched");
407 report.stop_error = Some(e);
408 return report;
409 }
410 }
411
412 if policy.release_claims {
414 let reason = if matches!(policy.cli, CliStop::StopOnly { .. }) { "agent stopped" } else { "agent quit" };
415 let (released, crons) = release_claims_and_list_crons(state, &who, reason).await;
416 report.released_claims = released;
417 report.crons_targeting = crons;
418 }
419 if let (true, Some(uid)) = (policy.dock_floaters, who.uid.as_deref()) {
420 crate::server::browser_session_close::close_for_stop(block_id);
422 crate::server::pane_dock::dock_all(state, uid, block_id).await;
423 }
424 if policy.stop_shell_sessions {
425 report.stopped_shells = before
426 .shell_sessions
427 .iter()
428 .filter(|s| state.shell_sessions.stop(&s.shell_id))
429 .count();
430 }
431
432 if policy.stop_background && !before.background_tasks.is_empty() {
433 report.stopped_background = stop_background_tasks(&before).await;
434 }
435
436 match policy.cli {
437 CliStop::StopOnly { .. } => {} CliStop::Replace => {
439 if let Some(ctrl) = blockcontroller::get_controller(block_id) {
440 if let Err(e) = replace_now(ctrl.as_ref()) {
441 tracing::debug!(block_id = %block_id, error = %e, "agent_teardown: replace");
442 }
443 }
444 }
445 CliStop::Graceful => {
446 close_sub_blocks(state, &before.sub_blocks, deadline).await;
449 report.survivors = close_cli(state, block_id, &who, &before, deadline, started).await;
450 if policy.stop_container {
451 report.stopped_container = stop_container(state, block_id, &before, deadline).await;
452 }
453 report.containers_left = compose_containers_left(state, block_id, &before, deadline).await;
454 }
455 }
456 report
457}
458
459async fn stop_container(
463 state: &AppState,
464 block_id: &str,
465 before: &AgentResources,
466 deadline: std::time::Instant,
467) -> Option<String> {
468 let name = before.container.clone()?;
469 let shared = {
470 let (st, id, n) = (state.clone(), block_id.to_string(), name.clone());
471 tokio::task::spawn_blocking(move || agent_resources::container_shared(&st, &id, &n)).await.unwrap_or(true)
472 };
473 if shared {
474 tracing::info!(block_id = %block_id, container = %name, "agent_teardown: container still in use; kept");
475 return None;
476 }
477 let cm = state.container_manager.get().await?;
478 let grace = deadline.saturating_duration_since(std::time::Instant::now()).as_secs().max(1) as i64;
479 match cm.stop(&name, grace).await {
480 Ok(()) => {
481 publish_shutdown(state, block_id, "container", format!("stopped container {name}"), ShutdownExtra::default());
482 Some(name)
483 }
484 Err(e) => {
485 tracing::warn!(block_id = %block_id, container = %name, error = %e, "agent_teardown: container stop failed");
486 None
487 }
488 }
489}
490
491async fn compose_containers_left(
497 state: &AppState,
498 block_id: &str,
499 before: &AgentResources,
500 deadline: std::time::Instant,
501) -> Vec<String> {
502 let dir = std::path::PathBuf::from(&before.cwd);
503 let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from);
504 if before.cwd.is_empty() || dir.parent().is_none() || home.as_deref() == Some(dir.as_path()) {
505 return Vec::new();
506 }
507 let Some(cm) = state.container_manager.get().await else { return Vec::new() };
508 let wait = deadline.saturating_duration_since(std::time::Instant::now()).max(std::time::Duration::from_secs(1));
510 let names = match tokio::time::timeout(wait, cm.running_compose_containers_under(&dir)).await {
511 Ok(Ok(names)) => names,
512 Ok(Err(e)) => {
513 tracing::warn!(block_id = %block_id, error = %e, "agent_teardown: listing Compose containers failed");
514 return Vec::new();
515 }
516 Err(_) => {
517 tracing::warn!(block_id = %block_id, "agent_teardown: Docker didn't list Compose containers in time");
518 return Vec::new();
519 }
520 };
521 for name in &names {
522 publish_shutdown(
523 state,
524 block_id,
525 "container",
526 format!("container {name} (Docker Compose, in this agent's folder) is still running"),
527 ShutdownExtra { container: Some(name.clone()), outcome: Some("left".into()), ..Default::default() },
528 );
529 }
530 names
531}
532
533async fn stop_background_tasks(before: &AgentResources) -> usize {
536 let tasks = before.background_tasks.clone();
537 tokio::task::spawn_blocking(move || {
538 let pids = agent_resources::live_background_pids(&tasks);
539 for pid in &pids {
540 tracing::info!(pid, "agent_teardown: stopping a background task");
541 agentmux_common::process::kill_process_group(*pid);
542 }
543 pids.len()
544 })
545 .await
546 .unwrap_or(0)
547}
548
549async fn close_sub_blocks(state: &AppState, sub_blocks: &[String], deadline: std::time::Instant) {
552 if sub_blocks.is_empty() {
553 return;
554 }
555 let subs = sub_blocks.iter().map(|id| Box::pin(run_one(state, id, Policy::close(), deadline)));
556 futures_util::future::join_all(subs).await;
557 for id in sub_blocks {
561 blockcontroller::unmark_closing(id);
562 }
563}
564
565async fn close_cli(
569 state: &AppState,
570 block_id: &str,
571 who: &AgentIdentity,
572 before: &AgentResources,
573 deadline: std::time::Instant,
574 started: std::time::Instant,
575) -> Vec<agent_resources::ProcessEntry> {
576 let label = if who.agent_id.is_empty() { "agent".to_string() } else { who.agent_id.clone() };
577 blockcontroller::mark_closing(block_id);
581 state.reactive_handler.unregister_block(block_id);
582 crate::server::agent_handlers::container_turn::cancel_prestart(block_id);
584 let ctrl = blockcontroller::take_controller(block_id);
585 let (controller_type, outcome) = match ctrl {
588 Some(ctrl) => {
589 if ctrl.get_runtime_status().turn_active {
590 publish_shutdown(state, block_id, "interrupt", "turn interrupted".into(), ShutdownExtra::default());
591 note_turn_cut_off_by_quit(state, block_id).await;
592 }
593 let outcome = ctrl.shutdown(deadline).await;
594 (ctrl.controller_type().to_string(), outcome)
595 }
596 None => (String::new(), blockcontroller::StopOutcome::NotRunning),
597 };
598 let (step, text, extra) = exit_line(&label, &outcome, started.elapsed());
599 publish_shutdown(state, block_id, step, text, extra);
600 terminate_members(state, block_id, deadline).await;
603 let alive: std::collections::HashSet<u32> =
607 state.process_tracker.list_block(block_id).into_iter().map(|p| p.pid).collect();
608 blockcontroller::release_block_processes(block_id);
609 for p in &before.processes {
610 let killed = alive.contains(&p.pid);
611 publish_shutdown(
612 state,
613 block_id,
614 "process",
615 process_line(&p.command, p.pid, killed),
616 process_extra(p.pid, &p.command, if killed { "killed" } else { "stopped" }),
617 );
618 }
619 let mut survivors = verify_gone(&before.processes).await;
622 for p in &survivors {
623 publish_shutdown(
624 state,
625 block_id,
626 "survivor",
627 format!("still running: {} (pid {})", short_command(&p.command), p.pid),
628 process_extra(p.pid, &p.command, "survived"),
629 );
630 }
631 for p in escaped(block_id, &survivors).await {
635 publish_shutdown(
636 state,
637 block_id,
638 "survivor",
639 format!("still running, outside the agent's tracking: {} (pid {})", short_command(&p.command), p.pid),
640 process_extra(p.pid, &p.command, "escaped"),
641 );
642 survivors.push(p);
643 }
644 blockcontroller::mark_closing_stopped(block_id);
645 crate::backend::container::credential::revoke_block(block_id);
646 let sessions = crate::identity::aws_broker::sessions::global();
649 if let Some(uid) = crate::backend::agent_resolve::uid_for_block(&state.mstore, block_id) {
650 sessions.revoke_agent(&uid);
651 }
652 if let Some(block) = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten() {
653 let agent = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
654 if !agent.is_empty() {
655 sessions.revoke_agent(&agent);
656 }
657 }
658 save_final_state(state, block_id);
660 publish_shutdown(state, block_id, "saved", "conversation saved".into(), ShutdownExtra::default());
661 publish_shutdown(state, block_id, "done", "closing".into(), ShutdownExtra::default());
662 tracing::info!(
663 block_id = %block_id,
664 controller_type = %controller_type,
665 outcome = outcome.as_str(),
666 elapsed_ms = started.elapsed().as_millis() as u64,
667 survivors = survivors.len(),
668 "agent_shutdown"
669 );
670 survivors
671}
672
673const MEMBERS_GRACE_MAX: std::time::Duration = std::time::Duration::from_secs(2);
676
677async fn terminate_members(state: &AppState, block_id: &str, deadline: std::time::Instant) {
682 let grace = deadline.saturating_duration_since(std::time::Instant::now()).min(MEMBERS_GRACE_MAX);
683 if grace.is_zero() {
684 return;
685 }
686 let registry = state.process_tracker.clone();
687 let id = block_id.to_string();
688 let count = move || {
689 let (r, id) = (registry.clone(), id.clone());
690 tokio::task::spawn_blocking(move || r.member_count(&id))
691 };
692 if count().await.unwrap_or(0) == 0 {
693 return;
694 }
695 let (r, id) = (state.process_tracker.clone(), block_id.to_string());
696 if !tokio::task::spawn_blocking(move || r.terminate(&id)).await.unwrap_or(false) {
697 return;
698 }
699 let until = std::time::Instant::now() + grace;
700 while std::time::Instant::now() < until {
701 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
702 if count().await.unwrap_or(0) == 0 {
703 return;
704 }
705 }
706}
707
708async fn escaped(block_id: &str, known: &[agent_resources::ProcessEntry]) -> Vec<agent_resources::ProcessEntry> {
712 let scan = |id: String| async move {
713 tokio::task::spawn_blocking(move || crate::backend::process_tracker::scan::tagged(&id))
714 .await
715 .unwrap_or_default()
716 };
717 let first = scan(block_id.to_string()).await;
718 if first.is_empty() {
719 return Vec::new();
720 }
721 tokio::time::sleep(ESCAPE_SETTLE).await;
722 scan(block_id.to_string())
723 .await
724 .into_iter()
725 .filter(|p| first.iter().any(|f| f.pid == p.pid && f.started_at_ms == p.started_at_ms))
726 .filter(|p| !known.iter().any(|k| k.pid == p.pid))
727 .map(|p| agent_resources::ProcessEntry { pid: p.pid, command: p.command, started_at_ms: p.started_at_ms })
728 .collect()
729}
730
731const ESCAPE_SETTLE: std::time::Duration = std::time::Duration::from_millis(300);
732
733const VERIFY_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);
736
737async fn verify_gone(before: &[agent_resources::ProcessEntry]) -> Vec<agent_resources::ProcessEntry> {
742 if before.is_empty() {
743 return Vec::new();
744 }
745 let mut left = wait_gone(before.to_vec()).await;
746 if left.is_empty() {
747 return left;
748 }
749 for p in &left {
750 tracing::warn!(pid = p.pid, command = %p.command, "agent_teardown: forcing a survivor");
751 let (pid, started) = (p.pid, p.started_at_ms);
752 let _ = tokio::task::spawn_blocking(move || agent_resources::force_kill_tree(pid, started)).await;
753 }
754 left = wait_gone(left).await;
755 left
756}
757
758async fn wait_gone(mut procs: Vec<agent_resources::ProcessEntry>) -> Vec<agent_resources::ProcessEntry> {
761 let until = std::time::Instant::now() + VERIFY_WAIT;
762 loop {
763 procs = tokio::task::spawn_blocking(move || agent_resources::survivors(&procs)).await.unwrap_or_default();
764 if procs.is_empty() || std::time::Instant::now() >= until {
765 return procs;
766 }
767 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
768 }
769}
770
771async fn release_claims_and_list_crons(state: &AppState, who: &AgentIdentity, reason: &'static str) -> (usize, Vec<String>) {
776 let (identity_store, jobs_store) = (state.work_store.clone(), crate::server::cron::jobs_store(state));
777 let (a, u) = (who.agent_id.clone(), who.uid.clone());
778 let result = tokio::task::spawn_blocking(move || {
779 let released = release_claims(&identity_store, &a, u.as_deref(), reason, agentmux_common::time::now_ms());
780 let crons = jobs_store
781 .and_then(|s| s.cron_list().ok())
782 .map(|jobs| agent_resources::crons_targeting(&jobs, &a, u.as_deref()))
783 .unwrap_or_default();
784 (released, crons)
785 })
786 .await
787 .unwrap_or_default();
788 if result.0 > 0 {
789 crate::server::work_queue::publish_changed(state);
790 }
791 result
792}
793
794#[cfg(test)]
795mod tests {
796 use super::*;
797
798 #[test]
801 fn release_claims_returns_one_agents_tasks_with_the_reason_and_counts_the_attempt() {
802 use crate::backend::storage::work_queue::{work_state, ClaimFilter, WorkItem};
803 let dir = tempfile::tempdir().unwrap();
804 let store = crate::backend::storage::store::Store::open_identity_store(&dir.path().join("identity-store.db")).unwrap();
805 for id in ["w1", "w2"] {
806 let item = WorkItem {
807 id: id.into(),
808 title: "t".into(),
809 payload: "p".into(),
810 kind: String::new(),
811 target_agent: String::new(),
812 target_group: String::new(),
813 priority: 0,
814 state: work_state::OPEN.into(),
815 claimed_by: String::new(),
816 target_agent_uid: String::new(),
817 claimed_by_uid: String::new(),
818 claim_expires: None,
819 attempts: 0,
820 max_attempts: 3,
821 created_by: "tester".into(),
822 created_by_uid: String::new(),
823 created_at: 1000,
824 updated_at: 1000,
825 not_before: None,
826 result: String::new(),
827 };
828 store.work_queue_enqueue(&item).unwrap();
829 }
830 let claim_as = |agent: &str, uid: &str| {
831 let f = ClaimFilter { kind: None, agent_id: agent.into(), agent_uid: uid.into(), groups: vec![] };
832 store.work_queue_claim(&f, 2000, 120_000).unwrap().expect("an open item")
833 };
834 let lark = claim_as("Lark", "uid-lark");
835 let korp = claim_as("Korp", "uid-korp");
836
837 let reason = "stopped by the watchdog after 4 h";
838 assert_eq!(release_claims(&store, "Lark", Some("uid-lark"), reason, 3000), 1);
839 let back = store.work_queue_get(&lark.id).unwrap().unwrap();
840 assert_eq!((back.state.as_str(), back.attempts, back.result.as_str()), (work_state::OPEN, 1, reason));
841 assert_eq!(store.work_queue_get(&korp.id).unwrap().unwrap().state, work_state::CLAIMED, "another agent's claim stays");
842 assert_eq!(release_claims(&store, "Lark", Some("uid-lark"), reason, 3000), 0, "nothing left to release");
843 }
844
845 #[test]
846 fn policies_encode_todays_scopes() {
847 assert_eq!(Policy::close(), Policy { cli: CliStop::Graceful, release_claims: false, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false });
848 assert_eq!(Policy::quit(), Policy { cli: CliStop::Graceful, release_claims: true, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false });
849 assert_eq!(Policy::stop(false, false).cli, CliStop::StopOnly { graceful: false });
850 assert!(Policy::stop(true, false).release_claims && !Policy::stop(true, false).stop_shell_sessions);
852 assert!(Policy::stop(true, true).stop_background && !Policy::stop(true, false).stop_background);
853 assert!(Policy::close().stop_container && Policy::quit().stop_container && Policy::app_exit().stop_container);
855 assert!(!Policy::stop(true, true).stop_container && !Policy::replace().stop_container);
856 let w = Policy::stop_cli_only(true);
858 assert!(!w.release_claims && !w.stop_shell_sessions && !w.stop_background);
859 assert_eq!(Policy::replace(), Policy { cli: CliStop::Replace, release_claims: false, stop_shell_sessions: false, stop_background: false, stop_container: false, dock_floaters: false });
860 assert_eq!(Policy::app_exit(), Policy { cli: CliStop::Graceful, release_claims: false, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false });
861 assert!(Policy::stop(true, false).dock_floaters && !Policy::stop_cli_only(true).dock_floaters && !Policy::close().dock_floaters && !Policy::quit().dock_floaters);
863 assert!(APP_EXIT_CAP.saturating_sub(SHELL_SWEEP_GRACE) > blockcontroller::SHUTDOWN_GRACE);
865 }
866
867 #[test]
870 fn nothing_else_stops_an_agent() {
871 const ALLOWED: &[(&str, &str)] = &[
874 ("sagas/agent_teardown.rs", "the one path"),
875 ("backend/blockcontroller/mod.rs", "defines release_block_processes and delete_controller"),
876 ("backend/blockcontroller/persistent/", "the controller's own shutdown internals"),
877 ("backend/blockcontroller/shell/", "the controller's own stop internals"),
878 ("backend/process_tracker/", "the tracker itself"),
879 ("backend/shell_node.rs", "ShellSessionRegistry's own stop/stop_all"),
880 ("server/http_shell.rs", "the ShellStop tool: the agent stopping one shell on purpose"),
881 ("server/vault_rotate.rs", "a Vault rotation stopping its own set or verify command that ran past its time"),
882 ];
883 const PATTERNS: &[&str] = &[
884 "release_block_processes(",
885 "shell_sessions.stop(",
886 ".stop_all()",
887 ".shutdown(deadline",
888 "ctrl.stop(",
889 ".stop_for_replace(",
890 "delete_controller(",
891 ];
892 let mut offenders = Vec::new();
893 for root in crate::test_support::server_src_roots() {
894 let mut stack = vec![root.clone()];
895 while let Some(dir) = stack.pop() {
896 for entry in std::fs::read_dir(&dir).unwrap() {
897 let path = entry.unwrap().path();
898 if path.is_dir() {
899 stack.push(path);
900 continue;
901 }
902 if path.extension().and_then(|e| e.to_str()) != Some("rs") {
903 continue;
904 }
905 let rel = path.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/");
906 let is_test_file = rel.ends_with("tests.rs") || rel.contains("/tests/");
908 if is_test_file || ALLOWED.iter().any(|(a, _)| rel.starts_with(a) || rel == *a) {
909 continue;
910 }
911 let text = std::fs::read_to_string(&path).unwrap();
912 let cut = ["#[cfg(test)]", "#[cfg(any(test, feature = \"test-support\"))]"].iter().filter_map(|m| text.find(m)).min();
915 let code = &text[..cut.unwrap_or(text.len())];
916 for (i, line) in code.lines().enumerate() {
917 let t = line.trim_start();
918 if t.starts_with("//") {
919 continue;
920 }
921 if let Some(p) = PATTERNS.iter().find(|p| line.contains(*p)) {
922 offenders.push(format!("{rel}:{}: `{p}`", i + 1));
923 }
924 }
925 }
926 }
927 }
928 assert!(
929 offenders.is_empty(),
930 "an agent's processes are stopped only by sagas::agent_teardown (spec SPEC_AGENT_TEARDOWN_SINGLE_PATH §3 G1); \
931 route these through it:\n{}",
932 offenders.join("\n")
933 );
934 }
935
936 #[test]
937 fn the_agents_with_a_turn_in_flight_are_listed_once_and_a_pane_with_no_agent_is_left_out() {
938 let ids = ["b", " a ", "", "b", " "].map(String::from);
939 assert_eq!(distinct_agents(ids), vec!["a".to_string(), "b".to_string()]);
940 assert!(distinct_agents(Vec::new()).is_empty());
941 }
942}