1use std::collections::BTreeMap;
18use std::sync::{Arc, Mutex};
19use std::time::{Duration, Instant};
20
21use tokio::sync::oneshot;
22
23use agentmux_procstats::{ProcInfo, ProcKey};
24
25const PROBE_MAX: Duration = Duration::from_secs(30);
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub(crate) enum Verdict {
32 Probing,
34 Busy,
36 Stuck,
38}
39
40pub(crate) struct IdleGate {
41 root: Option<u32>,
42 window: Duration,
43 probe: Option<(Instant, Option<TreeSample>)>,
44}
45
46impl IdleGate {
47 pub(crate) fn new(root: Option<u32>, idle_timeout: Duration) -> Self {
49 Self { root, window: PROBE_MAX.min(idle_timeout / 2), probe: None }
50 }
51
52 pub(crate) fn reset(&mut self) {
54 self.probe = None;
55 }
56
57 pub(crate) fn stuck(&mut self, last_activity: &mut Instant) -> bool {
61 match self.check() {
62 Verdict::Probing => false,
63 Verdict::Busy => {
64 tracing::info!(target: "bashwrap", "silent for the idle timeout but busy (CPU or new processes); not killing");
65 *last_activity = Instant::now();
66 false
67 }
68 Verdict::Stuck => true,
69 }
70 }
71
72 pub(crate) fn check(&mut self) -> Verdict {
75 let Some((since, before)) = &self.probe else {
76 self.probe = Some((Instant::now(), self.root.and_then(sample)));
77 return Verdict::Probing;
78 };
79 if since.elapsed() < self.window {
80 return Verdict::Probing;
81 }
82 let after = self.root.and_then(sample);
83 let verdict = match (before, &after) {
84 (Some(b), Some(a)) if busy(b, a, self.window) => Verdict::Busy,
85 _ => Verdict::Stuck,
86 };
87 self.probe = None;
88 verdict
89 }
90}
91
92pub(crate) async fn watch(
97 activity: Arc<Mutex<Instant>>,
98 root: Option<u32>,
99 idle_timeout: Duration,
100 idle_tx: oneshot::Sender<()>,
101) {
102 let mut gate = Some(IdleGate::new(root, idle_timeout));
103 loop {
104 tokio::time::sleep(Duration::from_millis(200)).await;
105 let mut last = *activity.lock().unwrap_or_else(|e| e.into_inner());
106 let Some(mut g) = gate.take() else { return };
107 if last.elapsed() < idle_timeout {
108 g.reset();
109 gate = Some(g);
110 continue;
111 }
112 let Ok((stuck, g, last)) = tokio::task::spawn_blocking(move || (g.stuck(&mut last), g, last)).await else {
113 let _ = idle_tx.send(());
114 return;
115 };
116 if stuck {
117 let _ = idle_tx.send(());
118 return;
119 }
120 *activity.lock().unwrap_or_else(|e| e.into_inner()) = last;
121 gate = Some(g);
122 }
123}
124
125#[derive(Debug, Clone, Default, PartialEq, Eq)]
127pub(crate) struct TreeSample(BTreeMap<ProcKey, u64>);
128
129fn sample(root: u32) -> Option<TreeSample> {
130 let procs = agentmux_procstats::snapshot().ok()?;
131 Some(tree_sample(&procs, root))
132}
133
134fn tree_sample(procs: &[ProcInfo], root: u32) -> TreeSample {
136 let mut out = BTreeMap::new();
137 let Some(top) = procs.iter().find(|p| p.pid == root) else { return TreeSample(out) };
138 let mut stack = vec![top];
139 while let Some(p) = stack.pop() {
140 if out.insert(p.key(), p.cpu_ns.unwrap_or(0)).is_some() {
141 continue;
142 }
143 stack.extend(procs.iter().filter(|c| c.is_child_of(p)));
144 }
145 TreeSample(out)
146}
147
148fn busy(before: &TreeSample, after: &TreeSample, window: Duration) -> bool {
151 let threshold = (window.as_nanos() / 100).max(10_000_000) as u64;
152 after.0.iter().any(|(key, &cpu)| match before.0.get(key) {
153 None => true,
154 Some(&was) => cpu.saturating_sub(was) >= threshold,
155 })
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 fn proc(pid: u32, ppid: Option<u32>, cpu_ms: u64) -> ProcInfo {
163 ProcInfo {
164 pid,
165 ppid,
166 start_key: pid as u64,
167 started_at_ms: Some(pid as u64),
168 name: format!("p{pid}"),
169 cpu_ns: Some(cpu_ms * 1_000_000),
170 mem_private: None,
171 mem_resident: None,
172 mem_commit: None,
173 }
174 }
175
176 #[test]
177 fn the_tree_is_the_root_and_its_descendants_only() {
178 let procs = [proc(10, Some(1), 0), proc(11, Some(10), 0), proc(12, Some(11), 0), proc(20, Some(1), 0)];
179 let pids: Vec<u32> = tree_sample(&procs, 10).0.keys().map(|k| k.pid).collect();
180 assert_eq!(pids, vec![10, 11, 12]);
181 assert!(tree_sample(&procs, 99).0.is_empty(), "a root that's gone has no tree");
182 }
183
184 #[test]
185 fn cpu_or_a_new_process_is_busy_and_nothing_is_stuck() {
186 let window = Duration::from_secs(30);
187 let before = tree_sample(&[proc(10, None, 100), proc(11, Some(10), 0)], 10);
188 assert!(!busy(&before, &tree_sample(&[proc(10, None, 100), proc(11, Some(10), 0)], 10), window));
190 assert!(!busy(&before, &tree_sample(&[proc(10, None, 100), proc(11, Some(10), 200)], 10), window));
192 assert!(busy(&before, &tree_sample(&[proc(10, None, 100), proc(11, Some(10), 5_000)], 10), window));
194 assert!(busy(&before, &tree_sample(&[proc(10, None, 100), proc(12, Some(10), 0)], 10), window));
196 }
197
198 #[test]
199 fn the_gate_probes_once_then_decides() {
200 let mut gate = IdleGate::new(None, Duration::from_millis(40));
202 assert_eq!(gate.check(), Verdict::Probing);
203 assert_eq!(gate.check(), Verdict::Probing, "inside the window");
204 std::thread::sleep(Duration::from_millis(25));
205 assert_eq!(gate.check(), Verdict::Stuck);
206 assert_eq!(gate.check(), Verdict::Probing);
208 gate.reset();
209 assert_eq!(gate.check(), Verdict::Probing);
210 }
211
212 #[test]
213 fn the_probe_window_is_at_most_half_the_timeout() {
214 assert_eq!(IdleGate::new(None, Duration::from_secs(600)).window, PROBE_MAX);
215 assert_eq!(IdleGate::new(None, Duration::from_secs(1)).window, Duration::from_millis(500));
216 }
217
218 mod end_to_end {
222 use crate::bash_wrap::{locate_bash, run_via_pipes, run_via_pty, Args};
223 use crate::cwd_state::CWD_STATE_FILE_OVERRIDE_ENV;
224 use crate::test_env_lock::{unique_temp_dir, EnvVarGuard, ENV_LOCK};
225 use std::sync::Arc;
226 use std::time::Duration;
227
228 const BUSY_AND_SILENT: &str = "end=$((SECONDS+4)); while [ $SECONDS -lt $end ]; do :; done; echo finished";
229
230 fn args(tool: &str) -> Args {
231 Args { tool_id: tool.into(), b64_cmd: String::new(), block_id: None, declared_background: false, agent: None, agent_unknown: false }
232 }
233
234 #[tokio::test]
235 async fn a_silent_but_busy_command_finishes_through_pipes() {
236 let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
237 let scratch = unique_temp_dir("idle-busy-pipes");
238 let _state = EnvVarGuard::set(CWD_STATE_FILE_OVERRIDE_ENV, scratch.join("s.cwd").to_str().unwrap());
239 let _idle = EnvVarGuard::set("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", "1");
240 let bash = locate_bash().expect("bash");
241 let buffered = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
242 let code = tokio::time::timeout(
243 Duration::from_secs(30),
244 run_via_pipes(&args("idle-busy-pipes"), BUSY_AND_SILENT, None, buffered.clone(), &bash),
245 )
246 .await
247 .expect("finishes")
248 .expect("runs");
249 let out = String::from_utf8_lossy(&buffered.lock().await).into_owned();
250 let _ = std::fs::remove_dir_all(&scratch);
251 assert_eq!(code, 0, "{out}");
252 assert!(out.contains("finished"), "{out}");
253 assert!(!out.contains("idle timeout"), "{out}");
254 }
255
256 #[tokio::test]
257 async fn a_silent_but_busy_command_finishes_in_a_pty() {
258 let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
259 let scratch = unique_temp_dir("idle-busy-pty");
260 let _state = EnvVarGuard::set(CWD_STATE_FILE_OVERRIDE_ENV, scratch.join("s.cwd").to_str().unwrap());
261 let _idle = EnvVarGuard::set("AGENTMUX_BASHWRAP_IDLE_TIMEOUT_SECS", "1");
262 let bash = locate_bash().expect("bash");
263 let size = portable_pty::PtySize { rows: 24, cols: 80, pixel_width: 0, pixel_height: 0 };
264 let Ok(pair) = portable_pty::native_pty_system().openpty(size) else {
265 eprintln!("skipping: PTY unavailable in this environment");
266 return;
267 };
268 let buffered = Arc::new(tokio::sync::Mutex::new(Vec::<u8>::new()));
269 let code = tokio::time::timeout(
270 Duration::from_secs(30),
271 run_via_pty(&args("idle-busy-pty"), BUSY_AND_SILENT, None, buffered.clone(), &bash, pair),
272 )
273 .await
274 .expect("finishes")
275 .expect("runs");
276 let out = String::from_utf8_lossy(&buffered.lock().await).into_owned();
277 let _ = std::fs::remove_dir_all(&scratch);
278 assert_eq!(code, 0, "{out}");
279 assert!(out.contains("finished"), "{out}");
280 assert!(!out.contains("idle timeout"), "{out}");
281 }
282 }
283}