Skip to main content

agentmux_srv/server/
restart_resume.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Restart resume (SPEC_ALWAYS_AVAILABLE_AGENTS_2026_10_27.md D7). An agent that is running when srv stops
5//! has a process only while srv lives. A pane in a tab is brought back by the window that shows it
6//! (`controller_backstop` covers the ones no window opens); an agent with no pane has no window at all, so
7//! this resumes it: the parked blocks whose agent was wanted running and was active within its idle window.
8//!
9//! An agent that was running when srv exited is resumed whatever its recorded desired state says: a
10//! live process with `desired=stopped` means something started it without recording that
11//! (`desired=running` is written by `start_agent`, and an explicit stop ends the process too), so the
12//! record is the stale half. Without this a restart left such an agent stopped.
13//!
14//! It resumes the most recently active first, one start at a time with a pause between, through
15//! `start_agent`: the same spawn gate, per-account warm-up slot and start limit as any other start. It
16//! stops at the cap instead of making room (`start_agent_without_eviction`), so a long list does not stop the
17//! agents it just resumed. Left stopped, and started by their first message or by being opened: an agent
18//! with no session to resume (it starts lazily anyway), one the user stopped, one that was idle past its
19//! window, one signed out or out of quota, and one a terminal view starts.
20
21use 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
34/// How long after startup the resume runs: long enough for srv to be up and the first windows to ask
35/// for their panes. It does not wait for the windows to finish: a window that shows an agent first is
36/// seen by the check right before each start (`still_wanted`), and a window that attaches to an agent
37/// already started finds its process running.
38const DELAY: Duration = Duration::from_secs(10);
39/// Between two starts, so a long list does not start in one burst (`start_agent` has its own gates too).
40const GAP: Duration = Duration::from_secs(2);
41/// A start that takes longer than this is logged once, naming the agent. The starts run one at a time, so
42/// one that never returns holds back every agent after it, and until now left no line saying so (narko's
43/// 0.60.9 to 0.60.10 restart wrote no closing line for eight minutes).
44const SLOW_START: Duration = Duration::from_secs(60);
45
46/// The parked agents that were running when srv last exited, in the channel folder
47/// ([`record_running_at_exit`]).
48const RUNNING_FILE: &str = "agentmux-running-at-exit.json";
49
50/// The agents the last exit left running that this start has not resumed yet: a second exit before
51/// the resume ran carries them into its own list.
52static PENDING: Mutex<Vec<String>> = Mutex::new(Vec::new());
53
54/// At app exit, before the agents are closed: keep which parked agents (no pane; a window
55/// brings its own panes back) have a running process, by definition id. The next start
56/// resumes these whatever their last turn was: an agent the idle sweep keeps running
57/// (it holds a claimed task) must not be dropped by a restart for having been quiet.
58/// Replaces the last list; none removes it.
59pub(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
84/// Whether the agent in `block` is up, as the Agents list shows it: a persistent agent has a running process,
85/// and a container agent has its controller, which holds no process between turns (each turn is a `docker exec`,
86/// so its status stays `init` or `done` while the agent waits for its next message). Without the second half a
87/// restart left every idle container agent off the exit list, "wanted running" and stopped, with nothing to start
88/// it (task #2283). A stop leaves the container agent's controller registered at `done` too, so the controller
89/// alone says nothing: it must also be wanted running, and not stopped in this run.
90fn 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
98/// The `pending` agents (definition ids) minus the ones stopped in this run: the stop is remembered in
99/// memory only, so an exit before the resume ran would otherwise carry the agent into the next start's
100/// list and lose the stop. BLOCKING (store reads).
101fn 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
111/// `running` and the `pending` ones too, each once, in order. An agent on the list is resumed whatever
112/// its recorded desired state says, but not when it was stopped in this run, so carrying one along does
113/// no harm.
114fn 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
137/// The agents the last exit left running. The file stays until the resume has run ([`clear_running`]),
138/// so a crash during the wait does not lose them.
139fn 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
143/// The resume has run: the list is spent.
144fn clear_running(dir: &Path) {
145    let _ = std::fs::remove_file(dir.join(RUNNING_FILE));
146}
147
148/// Whether this run's exit has already written its own list. Held while the file is written or
149/// removed, so the resume's cleanup and an exit's write never interleave.
150static EXIT_SNAPSHOT: Mutex<bool> = Mutex::new(false);
151
152/// An exit's list: written, and from now on the resume's cleanup leaves the file alone (an exit that
153/// overlaps the delayed resume would otherwise lose the list it just saved).
154fn 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
160/// The resume has run, so the list this start read is spent: removed unless an exit has written
161/// its own list since, which is the next start's.
162fn 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
169/// Resume once, [`DELAY`] after startup.
170pub(crate) fn install(state: &AppState) {
171    let state = state.clone();
172    // Read now, and kept until the resume has run: an exit before then carries these agents into its own list.
173    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        // Always one line: a start that logs nothing cannot be told from a resume that never ran.
185        tracing::info!(resumed = n, on_exit_list = running_at_exit.len(), "restart resume: started the parked agents that were running");
186    });
187}
188
189/// A parked agent that should come back: its definition id and its block.
190#[derive(Debug, PartialEq)]
191struct Candidate {
192    uid: String,
193    block_id: String,
194    last_active_ms: u64,
195    /// It had a running process when srv exited and has not been stopped in this run, so a recorded
196    /// `desired=stopped` (read from the database, possibly stale) does not hold it back.
197    was_running: bool,
198}
199
200/// Whether an agent last active at `last_active_ms` is within `window` of `now` (`None`: no window, so
201/// any agent that ran is).
202fn 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
206/// The latest write time (ms) of the transcript files `sources` name (a store and a zone each).
207fn 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
211/// When the agent's transcript was last written (ms): its last turn. `None` when it has none. A turn is
212/// appended to the agent's zone in the global transcript store and, unless that took it, to the block's
213/// own zone in this channel's store (an older layout kept the agent's zone there too): the newest of
214/// them. The controller names the agent's zone by the block's `agentId` meta, which for a block launched
215/// from a template is the template's id; the bound instance's id (`uid`) names the other.
216pub(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
235/// Whether `block_id` is the block `start_agent` runs for the agent `uid`, parked. Old layouts can hold
236/// several blocks for one agent and a start picks one by its own rule (a live process, then a pane over
237/// a parked block, then the lowest id): the checks for resuming have to be made on that block.
238fn 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
245/// Whether `c` is still to be resumed now: stopped agents and agents a window or a message started in the
246/// meantime are not. The wait between two starts is long enough for either.
247fn 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    // An agent on the exit list is resumed over a recorded `stopped` read from the database, but not
252    // over a stop decided in this run: that one is the user's.
253    (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
258/// Whether the agent `uid` was stopped in this run (BLOCKING: a store read).
259fn 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/// The parked agent blocks to resume, most recently active first.
267#[cfg(test)]
268fn candidates(state: &AppState) -> Vec<Candidate> {
269    candidates_with(state, &HashSet::new())
270}
271
272/// [`candidates`], and every agent in `running_at_exit` (definition ids) whatever its last turn: it was
273/// running when srv exited. One the idle sweep keeps running (a claimed task, a held message, the build
274/// slot) counts as recent too, so a crash, which leaves no list, does not drop it either.
275fn 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    // Each agent on the list that no block resumes, once, with the reason.
328    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    // One start per agent, the most recently active of its blocks: the list is in that order.
341    let mut seen = std::collections::HashSet::new();
342    found.retain(|c| seen.insert(c.uid.clone()));
343    found
344}
345
346/// The person went ahead with every pair that held parked agent `uid` (its block `block_id`) stopped at restart: it
347/// comes back as restart resume would have started it, unless something started or stopped it since.
348pub(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/// Resume the agents [`candidates`] names. Returns how many started.
360#[cfg(test)]
361pub(crate) async fn run_once(state: &AppState) -> usize {
362    run_once_with(state, &HashSet::new()).await
363}
364
365/// [`run_once`] with the agents the last exit left running ([`candidates_with`]).
366pub(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        // It may have been stopped, or started by a message or a window, while this ran.
376        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;