agentmux_srv_core/backend/reactive/
activity_watcher.rs1use std::collections::{HashMap, HashSet};
44use std::sync::atomic::{AtomicU64, Ordering};
45use std::sync::{Arc, Mutex};
46use std::time::Duration;
47
48use tokio::time::interval;
49
50use crate::ambient::digest;
51use crate::ambient::tasks::Recovery;
52use crate::ambient::title::{store_title, Replace, META_TITLE};
53use crate::ambient::validate::is_usable_title;
54use crate::backend::blockcontroller::core::broadcast_block_update;
55use crate::backend::blockcontroller::{get_block_controller_status, STATUS_RUNNING};
56use crate::backend::eventbus::EventBus;
57use crate::backend::obj::{self, Block};
58use crate::backend::storage::filestore::FileStore;
59use crate::backend::storage::store::Store;
60
61use super::get_global_handler;
62
63const SWEEP_INTERVAL_SECS: u64 = 20;
65
66pub(crate) const MAX_ATTEMPTS: u32 = 3;
69
70const WORD_TARGET: u32 = 8;
73
74#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
76pub(crate) struct Attempts {
77 pub count: u32,
79 pub last_size: Option<i64>,
81 pub failures: u32,
83 pub retry_at_tick: u64,
85}
86
87impl Attempts {
88 fn failed(&mut self, tick: u64) {
90 self.failures += 1;
91 self.retry_at_tick = tick + backoff_ticks(self.failures);
92 }
93
94 fn completed(&mut self, size: i64) -> u32 {
96 self.count += 1;
97 self.last_size = Some(size);
98 self.failures = 0;
99 self.retry_at_tick = 0;
100 self.count
101 }
102}
103
104pub(crate) fn backoff_ticks(failures: u32) -> u64 {
106 if failures == 0 {
107 return 0;
108 }
109 (3u64 << (failures - 1).min(5)).min(90)
110}
111
112fn record_failure(attempts: &Mutex<HashMap<String, Attempts>>, block_id: &str, clock: &AtomicU64) {
114 let now = clock.load(Ordering::Relaxed);
115 attempts.lock().unwrap().entry(block_id.to_string()).or_default().failed(now);
116}
117
118pub(crate) fn skip_reason(has_title: bool, attempts: Attempts, output_size: i64, tick: u64) -> Option<&'static str> {
121 if has_title {
122 return Some("has a title");
123 }
124 if attempts.count >= MAX_ATTEMPTS {
125 return Some("attempts exhausted");
126 }
127 if tick < attempts.retry_at_tick {
128 return Some("backing off after a failed call");
129 }
130 if attempts.last_size == Some(output_size) {
131 return Some("no new output");
132 }
133 None
134}
135
136pub async fn run_agent_summary_loop(mstore: Arc<Store>, filestore: Arc<FileStore>, event_bus: Arc<EventBus>) {
138 let mut ticker = interval(Duration::from_secs(SWEEP_INTERVAL_SECS));
139 let attempts: Arc<Mutex<HashMap<String, Attempts>>> = Arc::new(Mutex::new(HashMap::new()));
140 let in_flight: Arc<Mutex<HashSet<String>>> = Arc::new(Mutex::new(HashSet::new()));
143 let clock = Arc::new(AtomicU64::new(0));
145
146 loop {
147 ticker.tick().await;
148 let tick = clock.fetch_add(1, Ordering::Relaxed) + 1;
149
150 let agents = get_global_handler().list_agents();
151 let registered: HashSet<String> = agents.iter().map(|a| a.block_id.clone()).collect();
152 attempts.lock().unwrap().retain(|block_id, _| registered.contains(block_id));
153
154 for agent in agents {
155 let block_id = agent.block_id.clone();
156
157 let Some(status) = get_block_controller_status(&block_id) else {
158 continue;
159 };
160 if status.shellprocstatus != STATUS_RUNNING || !status.is_agent_pane {
161 continue;
162 }
163 let Ok(Some(block)) = mstore.get::<Block>(&block_id) else {
164 continue;
165 };
166 let has_title = is_usable_title(&obj::meta_get_string(&block.meta, META_TITLE, ""));
167 if has_title {
168 attempts.lock().unwrap().remove(&block_id);
170 continue;
171 }
172 let readable = digest::reads_output_format(&obj::meta_get_string(&block.meta, "agentOutputFormat", ""));
174 if !readable || crate::ambient::cli::recovery_skips(&block.meta) {
175 continue;
176 }
177 let Some((output_size, _)) =
180 crate::backend::transcript::source::TranscriptSource::resolve(&filestore, &mstore, &block_id).stat()
181 else {
182 continue;
183 };
184 let state = attempts.lock().unwrap().get(&block_id).copied().unwrap_or_default();
185 if skip_reason(false, state, output_size, tick).is_some() {
186 continue;
187 }
188 if !in_flight.lock().unwrap().insert(block_id.clone()) {
189 continue;
190 }
191
192 let mstore = mstore.clone();
193 let filestore = filestore.clone();
194 let event_bus = event_bus.clone();
195 let (attempts, in_flight, clock) = (attempts.clone(), in_flight.clone(), clock.clone());
196
197 tokio::spawn(async move {
198 let result =
199 crate::ambient::tasks::generate_recovered_title(&mstore, &filestore, &block_id, tick, WORD_TARGET)
200 .await;
201 in_flight.lock().unwrap().remove(&block_id);
202
203 let generated = match result {
206 Recovery::NotRun => return,
207 Recovery::Failed => return record_failure(&attempts, &block_id, &clock),
208 Recovery::Done(generated) => generated,
209 };
210 let attempt = attempts.lock().unwrap().entry(block_id.clone()).or_default().completed(output_size);
211
212 let Some(title) = generated.text else {
213 tracing::info!(
214 block_id = %block_id,
215 attempt,
216 max = MAX_ATTEMPTS,
217 "ambient: title recovery produced nothing usable (abstained or rejected)"
218 );
219 return;
220 };
221 match store_title(&mstore, &block_id, &title, Replace::IfEmpty, None, || true) {
223 Ok(true) => {
224 tracing::info!(block_id = %block_id, attempt, title = %title, "ambient: recovered a missing session title");
225 broadcast_block_update(&mstore, &event_bus, &block_id);
226 }
227 Ok(false) => {
228 tracing::debug!(block_id = %block_id, "ambient: a title appeared while recovery ran; kept it");
229 }
230 Err(e) => {
231 tracing::warn!(block_id = %block_id, error = %e, "ambient: could not store a recovered title");
232 }
233 }
234 });
235 }
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242
243 fn tried(count: u32, last_size: i64) -> Attempts {
244 Attempts { count, last_size: Some(last_size), ..Attempts::default() }
245 }
246
247 #[test]
248 fn an_agent_with_a_title_costs_nothing() {
249 assert_eq!(skip_reason(true, Attempts::default(), 100, 1), Some("has a title"));
250 }
251
252 #[test]
253 fn an_untitled_agent_is_tried_once_per_growth_of_its_output() {
254 assert_eq!(skip_reason(false, Attempts::default(), 100, 1), None, "first try");
255 assert_eq!(skip_reason(false, tried(1, 100), 100, 1), Some("no new output"));
256 assert_eq!(skip_reason(false, tried(1, 100), 250, 1), None, "new output, try again");
257 }
258
259 #[test]
260 fn attempts_are_bounded_while_the_title_stays_empty() {
261 assert_eq!(skip_reason(false, tried(MAX_ATTEMPTS - 1, 1), 2, 1), None);
262 assert_eq!(skip_reason(false, tried(MAX_ATTEMPTS, 1), 2, 1), Some("attempts exhausted"));
263 }
264
265 #[test]
266 fn a_failed_call_waits_longer_each_time_up_to_half_an_hour() {
267 let waits: Vec<u64> = (0..9).map(backoff_ticks).collect();
268 assert_eq!(waits, vec![0, 3, 6, 12, 24, 48, 90, 90, 90]);
269 assert_eq!(backoff_ticks(u32::MAX), 90, "a long streak does not overflow");
270 }
271
272 #[test]
273 fn a_block_whose_call_failed_is_not_tried_again_until_its_wait_is_over() {
274 let failed = Attempts { failures: 1, retry_at_tick: 10 + backoff_ticks(1), ..Attempts::default() };
275 assert_eq!(skip_reason(false, failed, 100, 11), Some("backing off after a failed call"));
276 assert_eq!(skip_reason(false, failed, 100, 12), Some("backing off after a failed call"));
277 assert_eq!(skip_reason(false, failed, 100, 13), None, "three ticks (a minute) later");
278 assert_eq!(skip_reason(false, failed, 9_999, 11), Some("backing off after a failed call"));
280 }
281
282 #[test]
283 fn the_wait_starts_when_the_failed_call_ends_not_when_it_was_dispatched() {
284 let attempts = Mutex::new(HashMap::new());
285 let clock = AtomicU64::new(10);
287 clock.store(14, Ordering::Relaxed);
288 record_failure(&attempts, "b", &clock);
289 let state = attempts.lock().unwrap().get("b").copied().unwrap();
290 assert_eq!(state.failures, 1);
291 assert_eq!(state.retry_at_tick, 14 + backoff_ticks(1));
292 assert_eq!(skip_reason(false, state, 100, 15), Some("backing off after a failed call"));
294 assert_eq!(skip_reason(false, state, 100, 16), Some("backing off after a failed call"));
295 assert_eq!(skip_reason(false, state, 100, 17), None);
296 clock.store(30, Ordering::Relaxed);
298 record_failure(&attempts, "b", &clock);
299 assert_eq!(attempts.lock().unwrap().get("b").unwrap().retry_at_tick, 30 + backoff_ticks(2));
300 }
301}