1use std::collections::HashSet;
22use std::path::Path;
23use std::sync::Mutex;
24use std::time::Duration;
25
26use crate::backend::agent_session::{agent_current_zone, agent_zone_for_block_meta, global_transcript_store, is_valid_definition_id, OUTPUT_FILE};
27use crate::backend::storage::filestore::FileStore;
28use crate::backend::blockcontroller;
29use crate::backend::obj;
30
31use super::app_api::agent_attach::{desired_of, stopped_this_run, DESIRED_RUNNING};
32use super::AppState;
33
34const DELAY: Duration = Duration::from_secs(10);
39const GAP: Duration = Duration::from_secs(2);
41const SLOW_START: Duration = Duration::from_secs(60);
45
46const RUNNING_FILE: &str = "agentmux-running-at-exit.json";
49
50static PENDING: Mutex<Vec<String>> = Mutex::new(Vec::new());
53
54pub(crate) async fn record_running_at_exit(state: &AppState, ids: &[String]) {
60 let st = state.clone();
61 let ids: HashSet<String> = ids.iter().cloned().collect();
62 let pending = PENDING.lock().unwrap_or_else(|e| e.into_inner()).clone();
63 let running = tokio::task::spawn_blocking(move || {
64 let Ok(blocks) = super::app_api::agent_block::blocks_in_tabs_or_parked(&st.mstore) else {
65 return Vec::new();
66 };
67 let pending = without_stopped(&st, pending);
68 let uids: Vec<String> = blocks
69 .into_iter()
70 .filter(|(block, tab)| tab.is_none() && ids.contains(&block.oid))
71 .filter(|(block, _)| is_up(block))
72 .filter(|(block, _)| crate::sagas::park_agents::is_parkable(&st, &block.oid))
73 .filter_map(|(block, _)| crate::sagas::park_agents::agent_of_block(&st, &block.oid, &block).map(|a| a.id))
74 .collect();
75 with_pending(uids, &pending)
76 })
77 .await
78 .unwrap_or_default();
79 if let Some(paths) = agentmux_common::DataPaths::from_env() {
80 save_exit_snapshot(&EXIT_SNAPSHOT, &paths.instance_dir, &running);
81 }
82}
83
84fn is_up(block: &obj::Block) -> bool {
91 let Some(controller) = blockcontroller::get_controller(&block.oid) else { return false };
92 controller.get_runtime_status().shellprocstatus == blockcontroller::STATUS_RUNNING
93 || (crate::backend::runtime_adapter::RuntimeKind::of_block_meta(&block.meta).is_container()
94 && desired_of(block).as_deref() == Some(DESIRED_RUNNING)
95 && !stopped_this_run(&block.oid))
96}
97
98fn without_stopped(state: &AppState, pending: Vec<String>) -> Vec<String> {
102 pending
103 .into_iter()
104 .filter(|uid| match super::app_api::agent_block::find_agent_block_by_uid(&state.mstore, uid) {
105 Ok(Some(found)) => !stopped_this_run(&found.block.oid),
106 _ => true,
107 })
108 .collect()
109}
110
111fn with_pending(mut running: Vec<String>, pending: &[String]) -> Vec<String> {
115 running.extend(pending.iter().cloned());
116 running.sort();
117 running.dedup();
118 running
119}
120
121fn write_running(dir: &Path, uids: &[String]) {
122 let path = dir.join(RUNNING_FILE);
123 if uids.is_empty() {
124 let _ = std::fs::remove_file(&path);
125 return;
126 }
127 let tmp = path.with_extension("json.tmp");
128 let written = serde_json::to_vec(uids)
129 .map_err(|e| e.to_string())
130 .and_then(|bytes| std::fs::write(&tmp, bytes).map_err(|e| e.to_string()))
131 .and_then(|()| std::fs::rename(&tmp, &path).map_err(|e| e.to_string()));
132 if let Err(e) = written {
133 tracing::warn!(path = %path.display(), error = %e, "restart resume: could not save the agents running at exit");
134 }
135}
136
137fn read_running(dir: &Path) -> Vec<String> {
140 std::fs::read(dir.join(RUNNING_FILE)).ok().and_then(|b| serde_json::from_slice::<Vec<String>>(&b).ok()).unwrap_or_default()
141}
142
143fn clear_running(dir: &Path) {
145 let _ = std::fs::remove_file(dir.join(RUNNING_FILE));
146}
147
148static EXIT_SNAPSHOT: Mutex<bool> = Mutex::new(false);
151
152fn save_exit_snapshot(recorded: &Mutex<bool>, dir: &Path, uids: &[String]) {
155 let mut recorded = recorded.lock().unwrap_or_else(|e| e.into_inner());
156 write_running(dir, uids);
157 *recorded = true;
158}
159
160fn spend_start_snapshot(recorded: &Mutex<bool>, dir: &Path) {
163 let recorded = recorded.lock().unwrap_or_else(|e| e.into_inner());
164 if !*recorded {
165 clear_running(dir);
166 }
167}
168
169pub(crate) fn install(state: &AppState) {
171 let state = state.clone();
172 let dir = agentmux_common::DataPaths::from_env().map(|p| p.instance_dir);
174 let running_at_exit = dir.as_deref().map(read_running).unwrap_or_default();
175 *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = running_at_exit.clone();
176 let running_at_exit: HashSet<String> = running_at_exit.into_iter().collect();
177 tokio::spawn(async move {
178 tokio::time::sleep(DELAY).await;
179 let n = run_once_with(&state, &running_at_exit).await;
180 PENDING.lock().unwrap_or_else(|e| e.into_inner()).clear();
181 if let Some(dir) = &dir {
182 spend_start_snapshot(&EXIT_SNAPSHOT, dir);
183 }
184 tracing::info!(resumed = n, on_exit_list = running_at_exit.len(), "restart resume: started the parked agents that were running");
186 });
187}
188
189#[derive(Debug, PartialEq)]
191struct Candidate {
192 uid: String,
193 block_id: String,
194 last_active_ms: u64,
195 was_running: bool,
198}
199
200fn active_within(last_active_ms: u64, now_ms: u64, window_ms: Option<u64>) -> bool {
203 window_ms.is_none_or(|w| now_ms.saturating_sub(last_active_ms) <= w)
204}
205
206fn latest_write_ms(sources: &[(&FileStore, &str)]) -> Option<u64> {
208 sources.iter().filter_map(|(store, zone)| store.stat(zone, OUTPUT_FILE).ok().flatten()).map(|f| f.modts.max(0) as u64).max()
209}
210
211pub(crate) fn last_active_ms(state: &AppState, uid: &str, block: &obj::Block) -> Option<u64> {
217 let mut zones: Vec<String> = agent_zone_for_block_meta(&block.meta).into_iter().collect();
218 if is_valid_definition_id(uid) {
219 zones.push(agent_current_zone(uid));
220 }
221 zones.dedup();
222 if zones.is_empty() {
223 return None;
224 }
225 let mut sources: Vec<(&FileStore, &str)> = vec![(state.filestore.as_ref(), block.oid.as_str())];
226 for zone in &zones {
227 sources.push((state.filestore.as_ref(), zone.as_str()));
228 if let Some(global) = global_transcript_store() {
229 sources.push((global.as_ref(), zone.as_str()));
230 }
231 }
232 latest_write_ms(&sources)
233}
234
235fn is_the_agents_block(state: &AppState, uid: &str, block_id: &str) -> bool {
239 matches!(
240 super::app_api::agent_block::find_agent_block_by_uid(&state.mstore, uid),
241 Ok(Some(found)) if found.block.oid == block_id && found.tab_id.is_none()
242 )
243}
244
245fn still_wanted(state: &AppState, c: &Candidate) -> bool {
248 let Ok(Some(block)) = state.mstore.get::<obj::Block>(&c.block_id) else {
249 return false;
250 };
251 (desired_of(&block).as_deref() == Some(DESIRED_RUNNING) || (c.was_running && !stopped_this_run(&c.block_id)))
254 && blockcontroller::get_controller(&c.block_id).is_none()
255 && is_the_agents_block(state, &c.uid, &c.block_id)
256}
257
258fn stopped_in_this_run(state: &AppState, uid: &str) -> bool {
260 matches!(
261 super::app_api::agent_block::find_agent_block_by_uid(&state.mstore, uid),
262 Ok(Some(found)) if stopped_this_run(&found.block.oid)
263 )
264}
265
266#[cfg(test)]
268fn candidates(state: &AppState) -> Vec<Candidate> {
269 candidates_with(state, &HashSet::new())
270}
271
272fn candidates_with(state: &AppState, running_at_exit: &HashSet<String>) -> Vec<Candidate> {
276 let Ok(blocks) = super::app_api::agent_block::blocks_in_tabs_or_parked(&state.mstore) else {
277 return Vec::new();
278 };
279 let now = agentmux_common::time::now_ms_u64();
280 let mut skipped: Vec<(String, &'static str)> = Vec::new();
281 let mut found: Vec<Candidate> = blocks
282 .into_iter()
283 .filter(|(_, tab)| tab.is_none())
284 .filter_map(|(block, _)| {
285 if !crate::sagas::park_agents::is_parkable(state, &block.oid) {
286 return None;
287 }
288 let uid = crate::sagas::park_agents::agent_of_block(state, &block.oid, &block)?.id;
289 let was_running = running_at_exit.contains(&uid) && !stopped_this_run(&block.oid);
290 let mut skip = |why: &'static str| {
291 if was_running {
292 skipped.push((uid.clone(), why));
293 }
294 };
295 if desired_of(&block).as_deref() != Some(DESIRED_RUNNING) && !was_running {
296 return None;
297 }
298 if obj::meta_get_string(&block.meta, "agent:sessionid", "").is_empty() {
299 skip("it has no session to resume");
300 return None;
301 }
302 if blockcontroller::get_controller(&block.oid).is_some() {
303 skip("it already has a controller");
304 return None;
305 }
306 if let Some(why) = super::controller_backstop::starts_no_controller(&block) {
307 skip(why);
308 return None;
309 }
310 if super::controller_backstop::failed_on_its_account(&block) {
311 skip("its account is signed out or out of quota");
312 return None;
313 }
314 if !is_the_agents_block(state, &uid, &block.oid) {
315 skip("it is not the block its agent starts");
316 return None;
317 }
318 let last_active_ms = last_active_ms(state, &uid, &block)?;
319 let window = super::agent_lifecycle::idle_window_of(state, &block);
320 let kept = was_running || {
321 let slug = state.mstore.agent_def_get(&uid).ok().flatten().map(|d| d.slug).filter(|s| !s.is_empty());
322 super::agent_lifecycle::exempt_agent(state, slug.as_deref().unwrap_or(&uid), &uid).is_some()
323 };
324 (kept || active_within(last_active_ms, now, window)).then_some(Candidate { uid, block_id: block.oid, last_active_ms, was_running })
325 })
326 .collect();
327 for uid in running_at_exit {
329 if found.iter().any(|c| &c.uid == uid) {
330 continue;
331 }
332 let why = match skipped.iter().find(|(s, _)| s == uid) {
333 Some((_, why)) => *why,
334 None if stopped_in_this_run(state, uid) => "it was stopped in this run",
335 None => "it has no parked block now (a window shows it, or it is not parkable), or no recorded turn",
336 };
337 tracing::info!(agent = %uid, "restart resume: not resumed although it was running at exit: {why}");
338 }
339 found.sort_by(|a, b| b.last_active_ms.cmp(&a.last_active_ms).then_with(|| a.uid.cmp(&b.uid)));
340 let mut seen = std::collections::HashSet::new();
342 found.retain(|c| seen.insert(c.uid.clone()));
343 found
344}
345
346pub(crate) async fn resume_after_go_ahead(state: &AppState, uid: &str, block_id: &str) {
349 let c = Candidate { uid: uid.to_string(), block_id: block_id.to_string(), last_active_ms: 0, was_running: true };
350 if !still_wanted(state, &c) {
351 return;
352 }
353 match super::app_api::agent_attach::start_agent_without_eviction(state, uid).await {
354 Ok(_) => tracing::info!(agent = %uid, "restart resume: started after the person's go-ahead"),
355 Err(e) => tracing::warn!(agent = %uid, "restart resume: could not start it after the person's go-ahead: {e}"),
356 }
357}
358
359#[cfg(test)]
361pub(crate) async fn run_once(state: &AppState) -> usize {
362 run_once_with(state, &HashSet::new()).await
363}
364
365pub(crate) async fn run_once_with(state: &AppState, running_at_exit: &HashSet<String>) -> usize {
367 if !crate::sagas::park_agents::enabled(state) {
368 return 0;
369 }
370 let mut started = 0;
371 let all = candidates_with(state, running_at_exit);
372 let last = all.len().saturating_sub(1);
373 tracing::info!(candidates = all.len(), "restart resume: starting the parked agents one after the other");
374 for (i, c) in all.into_iter().enumerate() {
375 if !still_wanted(state, &c) {
377 continue;
378 }
379 let start = super::app_api::agent_attach::start_agent_without_eviction(state, &c.uid);
380 tokio::pin!(start);
381 let result = tokio::select! {
382 r = &mut start => r,
383 () = tokio::time::sleep(SLOW_START) => {
384 tracing::warn!(agent = %c.uid, block_id = %c.block_id, secs = SLOW_START.as_secs(), position = i + 1, of = last + 1, "restart resume: still starting this agent; the ones after it wait");
385 start.await
386 }
387 };
388 match result {
389 Ok(_) => started += 1,
390 Err(e) if e.starts_with("capacity:") => {
391 tracing::info!("restart resume: {e}; the rest stay stopped and start on their first message");
392 break;
393 }
394 Err(e) if e.contains(crate::backend::folder_overlap::OPEN_REFUSAL_CODE) => {
395 tracing::warn!(agent = %c.uid, "restart resume: left stopped, it waits for the person's go-ahead for a shared folder");
396 super::app_api::folder_overlap::ask_for_resumed(state, &c.uid, &c.block_id);
397 }
398 Err(e) => tracing::warn!(agent = %c.uid, "restart resume: could not start it: {e}"),
399 }
400 if i < last {
401 tokio::time::sleep(GAP).await;
402 }
403 }
404 started
405}
406
407#[cfg(test)]
408mod tests;