1use std::sync::Arc;
20use std::time::Duration;
21use tokio::time::interval;
22
23use crate::backend::mps::Broker;
24use crate::backend::notify::policy::NotifyKind;
25use crate::backend::storage::store::Store;
26use crate::backend::wconfig::ConfigState;
27use super::{get_all_controllers, STATUS_RUNNING};
28
29const WATCHDOG_INTERVAL_SECS: u64 = 60;
31
32#[derive(Debug, Clone, Copy, Default)]
34pub(crate) struct Limits {
35 pub max_runtime_hours: f64,
36 pub idle_timeout_mins: f64,
37}
38
39#[derive(Debug, Clone, Copy, Default)]
41pub(crate) struct AgentClock {
42 pub spawn_ms: Option<i64>,
43 pub last_output_ms: Option<i64>,
44 pub pass_started_ms: Option<i64>,
46 pub turn_active: bool,
47 pub awaiting_user: bool,
51 pub wait_ended_ms: Option<i64>,
55 pub is_shell: bool,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub(crate) enum StopReason {
62 MaxRuntime { elapsed_ms: i64 },
63 IdleOutput { idle_ms: i64 },
64}
65
66pub(crate) fn verdict(limits: Limits, now_ms: i64, agent: &AgentClock) -> Option<StopReason> {
68 if limits.max_runtime_hours > 0.0 {
69 if let Some(spawn_ms) = agent.spawn_ms {
70 let elapsed_ms = (now_ms - spawn_ms).max(0);
71 if elapsed_ms >= (limits.max_runtime_hours * 3_600_000.0) as i64 {
72 return Some(StopReason::MaxRuntime { elapsed_ms });
73 }
74 }
75 }
76 if limits.idle_timeout_mins > 0.0 {
77 let quiet_since = if agent.is_shell {
78 agent.last_output_ms
79 } else if agent.turn_active && !agent.awaiting_user {
80 [agent.last_output_ms, agent.pass_started_ms, agent.spawn_ms, agent.wait_ended_ms].into_iter().flatten().max()
83 } else {
84 None
85 };
86 if let Some(since) = quiet_since {
87 let idle_ms = (now_ms - since).max(0);
88 if idle_ms >= (limits.idle_timeout_mins * 60_000.0) as i64 {
89 return Some(StopReason::IdleOutput { idle_ms });
90 }
91 }
92 }
93 None
94}
95
96fn awaiting_user(store: &Store, block_id: &str) -> bool {
98 store
99 .get::<crate::backend::obj::Block>(block_id)
100 .ok()
101 .flatten()
102 .is_some_and(|b| {
103 crate::backend::obj::meta_get_bool(&b.meta, crate::backend::agent_state::META_AWAITING_USER, false)
104 })
105}
106
107pub(crate) fn limit_text(reason: StopReason, limits: Limits) -> String {
110 let hours = |h: f64| if h.fract() == 0.0 { format!("{h:.0} h") } else { format!("{h} h") };
111 match reason {
112 StopReason::MaxRuntime { .. } => hours(limits.max_runtime_hours),
113 StopReason::IdleOutput { .. } => {
114 let m = limits.idle_timeout_mins;
115 if m.fract() == 0.0 { format!("{m:.0} min without output") } else { format!("{m} min without output") }
116 }
117 }
118}
119
120fn after_stop(work_store: &Store, broker: &Arc<Broker>, block_id: &str, limit: &str, agent: Option<(String, Option<String>)>) {
126 let reason = format!("stopped by the watchdog after {limit}");
127 if let Some((agent_id, uid)) = agent {
128 let released = crate::backend::work_claims::release_claims(work_store, &agent_id, uid.as_deref(), &reason, agentmux_common::time::now_ms());
129 if released > 0 {
130 tracing::info!(block_id = %block_id, released, "watchdog: released the stopped agent's claimed tasks");
131 broker.publish_event::<crate::backend::mps_events::WorkQueueChanged>(&(), vec![], 0);
132 }
133 }
134 if let Some(router) = crate::backend::notify::router::get(broker) {
135 router.emit_fixed(NotifyKind::AgentCrashed, block_id, Some(format!("Stopped by the watchdog after {limit}.")));
136 }
137}
138
139pub async fn run_watchdog_loop(config: Arc<ConfigState>, store: Arc<Store>, work_store: Arc<Store>, broker: Arc<Broker>) {
141 let mut ticker = interval(Duration::from_secs(WATCHDOG_INTERVAL_SECS));
142 let mut seen_waiting: std::collections::HashMap<String, i64> = Default::default();
146 loop {
147 ticker.tick().await;
148 let settings = config.get_settings();
149 let limits = Limits {
150 max_runtime_hours: settings.term_agent_max_runtime_hours,
151 idle_timeout_mins: settings.term_agent_idle_timeout_mins,
152 };
153
154 if limits.max_runtime_hours <= 0.0 && limits.idle_timeout_mins <= 0.0 {
156 continue;
157 }
158
159 let now_ms = agentmux_common::time::now_ms();
160 let controllers = get_all_controllers();
161 seen_waiting.retain(|id, _| controllers.contains_key(id));
162
163 for (block_id, ctrl) in controllers {
164 let status = ctrl.get_runtime_status();
165 if status.shellprocstatus != STATUS_RUNNING {
166 continue;
167 }
168 let is_subprocess = ctrl.as_any().is::<super::subprocess::SubprocessController>();
172 if !status.is_agent_pane && !is_subprocess {
173 continue;
174 }
175 let shell = ctrl.as_any().downcast_ref::<super::shell::ShellController>();
176 let tracker = ctrl.turn_tracker();
177 let last_output_ms = match shell {
178 Some(shell) => shell.last_output_secs_ago().map(|secs| now_ms - secs as i64 * 1000),
179 None => ctrl.last_output_ms(),
180 };
181 let check_question = shell.is_none() && status.turn_active && limits.idle_timeout_mins > 0.0;
184 let awaiting = check_question && (ctrl.awaiting_user_reply() || awaiting_user(&store, &block_id));
185 if awaiting {
186 seen_waiting.insert(block_id.clone(), now_ms);
187 }
188 let replied_ms = tracker.as_ref().and_then(|t| t.last_user_reply_ms());
189 let agent = AgentClock {
190 spawn_ms: status.spawn_ts_ms.or_else(|| tracker.as_ref().and_then(|t| t.spawned_at_ms())),
191 last_output_ms,
192 pass_started_ms: tracker.as_ref().and_then(|t| t.pass_started_ms()),
193 turn_active: status.turn_active,
194 awaiting_user: awaiting,
195 wait_ended_ms: replied_ms.max(seen_waiting.get(&block_id).copied()),
196 is_shell: shell.is_some(),
197 };
198
199 let verdict = verdict(limits, now_ms, &agent);
200 match verdict {
201 Some(StopReason::MaxRuntime { elapsed_ms }) => {
202 tracing::warn!(
203 block_id = %block_id,
204 elapsed_hours = elapsed_ms / 3_600_000,
205 limit_hours = %limits.max_runtime_hours,
206 "watchdog: agent pane exceeded max-runtime, stopping"
207 );
208 }
209 Some(StopReason::IdleOutput { idle_ms }) => {
210 tracing::warn!(
211 block_id = %block_id,
212 idle_mins = idle_ms / 60_000,
213 limit_mins = %limits.idle_timeout_mins,
214 "watchdog: agent pane exceeded idle-output timeout, stopping"
215 );
216 }
217 None => continue,
218 }
219 let who = crate::backend::reactive::get_global_handler()
221 .list_agents()
222 .into_iter()
223 .find(|r| r.block_id == block_id)
224 .map(|r| (r.agent_id, r.uid));
225 if crate::backend::teardown_hooks::hooks().stop_now(&block_id, true).is_ok() && !agent.is_shell {
226 if let Some(reason) = verdict {
227 let (work_store, broker, block_id) = (work_store.clone(), broker.clone(), block_id.clone());
228 let limit = limit_text(reason, limits);
229 let _ = tokio::task::spawn_blocking(move || after_stop(&work_store, &broker, &block_id, &limit, who)).await;
230 }
231 }
232 }
233 }
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 const HOUR: i64 = 3_600_000;
241 const MIN: i64 = 60_000;
242 const NOW: i64 = 1_800_000_000_000;
243
244 fn limits(hours: f64, mins: f64) -> Limits {
245 Limits { max_runtime_hours: hours, idle_timeout_mins: mins }
246 }
247
248 fn mid_turn(age_ms: i64, quiet_ms: i64) -> AgentClock {
251 AgentClock {
252 spawn_ms: Some(NOW - age_ms),
253 last_output_ms: Some(NOW - quiet_ms),
254 pass_started_ms: Some(NOW - age_ms),
255 turn_active: true,
256 ..AgentClock::default()
257 }
258 }
259
260 #[test]
261 fn the_limit_is_named_in_the_unit_it_was_set_in() {
262 let l = limits(4.0, 30.0);
263 assert_eq!(limit_text(StopReason::MaxRuntime { elapsed_ms: 0 }, l), "4 h");
264 assert_eq!(limit_text(StopReason::IdleOutput { idle_ms: 0 }, l), "30 min without output");
265 assert_eq!(limit_text(StopReason::MaxRuntime { elapsed_ms: 0 }, limits(1.5, 0.0)), "1.5 h");
266 }
267
268 #[test]
269 fn disabled_limits_never_stop_anything() {
270 assert_eq!(verdict(limits(0.0, 0.0), NOW, &mid_turn(100 * HOUR, 100 * HOUR)), None);
271 }
272
273 #[test]
274 fn max_runtime_stops_any_agent_with_a_spawn_time() {
275 let over = AgentClock { spawn_ms: Some(NOW - 2 * HOUR), ..AgentClock::default() };
276 assert_eq!(verdict(limits(2.0, 0.0), NOW, &over), Some(StopReason::MaxRuntime { elapsed_ms: 2 * HOUR }));
277 let under = AgentClock { spawn_ms: Some(NOW - 2 * HOUR + 1), ..AgentClock::default() };
278 assert_eq!(verdict(limits(2.0, 0.0), NOW, &under), None);
279 assert_eq!(verdict(limits(2.0, 0.0), NOW, &AgentClock::default()), None, "no spawn time, no runtime");
280 }
281
282 #[test]
283 fn a_silent_turn_in_flight_is_idle() {
284 let agent = mid_turn(HOUR, 30 * MIN);
285 assert_eq!(verdict(limits(0.0, 30.0), NOW, &agent), Some(StopReason::IdleOutput { idle_ms: 30 * MIN }));
286 assert_eq!(verdict(limits(0.0, 31.0), NOW, &agent), None);
287 }
288
289 #[test]
290 fn an_agent_between_turns_waits_for_the_user_and_is_never_idle() {
291 let agent = AgentClock { turn_active: false, pass_started_ms: None, ..mid_turn(10 * HOUR, 10 * HOUR) };
292 assert_eq!(verdict(limits(0.0, 1.0), NOW, &agent), None);
293 }
294
295 #[test]
296 fn a_question_waiting_for_the_user_is_not_idle() {
297 let agent = AgentClock { awaiting_user: true, ..mid_turn(HOUR, HOUR) };
298 assert_eq!(verdict(limits(0.0, 1.0), NOW, &agent), None);
299 }
300
301 #[test]
302 fn a_new_turn_after_a_long_wait_starts_its_idle_clock_at_the_turn() {
303 let agent = AgentClock { pass_started_ms: Some(NOW - 2 * MIN), ..mid_turn(5 * HOUR, HOUR) };
305 assert_eq!(verdict(limits(0.0, 30.0), NOW, &agent), None);
306 assert_eq!(verdict(limits(0.0, 2.0), NOW, &agent), Some(StopReason::IdleOutput { idle_ms: 2 * MIN }));
307 }
308
309 #[test]
310 fn an_answered_wait_starts_the_idle_clock_at_the_answer() {
311 let agent = AgentClock { wait_ended_ms: Some(NOW - 2 * MIN), ..mid_turn(2 * HOUR, HOUR) };
313 assert_eq!(verdict(limits(0.0, 30.0), NOW, &agent), None);
314 assert_eq!(verdict(limits(0.0, 2.0), NOW, &agent), Some(StopReason::IdleOutput { idle_ms: 2 * MIN }));
315 }
316
317 #[test]
318 fn a_turn_with_no_output_yet_counts_from_its_start() {
319 let agent = AgentClock { last_output_ms: None, pass_started_ms: Some(NOW - 45 * MIN), ..mid_turn(HOUR, 0) };
320 assert_eq!(verdict(limits(0.0, 30.0), NOW, &agent), Some(StopReason::IdleOutput { idle_ms: 45 * MIN }));
321 }
322
323 #[test]
324 fn a_shell_pane_is_idle_whenever_its_pty_is_quiet() {
325 let shell = AgentClock { is_shell: true, last_output_ms: Some(NOW - 30 * MIN), ..AgentClock::default() };
326 assert_eq!(verdict(limits(0.0, 30.0), NOW, &shell), Some(StopReason::IdleOutput { idle_ms: 30 * MIN }));
327 let never_wrote = AgentClock { is_shell: true, ..AgentClock::default() };
328 assert_eq!(verdict(limits(0.0, 1.0), NOW, &never_wrote), None);
329 }
330
331 #[test]
332 fn max_runtime_wins_over_idle() {
333 let agent = mid_turn(3 * HOUR, 3 * HOUR);
334 assert!(matches!(verdict(limits(1.0, 1.0), NOW, &agent), Some(StopReason::MaxRuntime { .. })));
335 }
336}