Skip to main content

agentmux_srv_core/backend/
background_work.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What agents left running in the background, and what a quit does about it
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` §6.2).
6//!
7//! Everything an agent starts runs in its pane's process tracker (a Windows
8//! job object, a Linux cgroup), which nothing can leave, `Start-Process`
9//! included; a quit closes the panes and the trackers with them, so it stops
10//! a dev server or a whole `task dev` AgentMux an agent started. That stays
11//! so (letting processes escape a pane was rejected on purpose:
12//! `SPEC_BACKGROUND_TASK_TEARDOWN_SURVIVAL_2026_08_20.md` §0). What changes is
13//! that it no longer happens without a word:
14//!
15//! - **Before:** [`running`] lists it, by agent ([`describe`]): the version
16//!   panel shows the list while an upgrade waits to restart, the launcher's
17//!   dialog (`updates/stopping.txt`, [`write_for_launcher`]) and an agent
18//!   asking for the upgrade are told.
19//! - **At the quit** ([`at_quit`], from the quit's session save): it is
20//!   recorded, and on Windows another AgentMux among it is told the session
21//!   is ending (`WM_QUERYENDSESSION`), so it saves all its windows as at an
22//!   OS shutdown before its tracker stops it. Its windows aren't closed: a
23//!   close deletes the window's workspace, and stopped as it is, its windows
24//!   all come back on its next start. Elsewhere it is stopped with its pane
25//!   as before, which keeps its windows the same way.
26//! - **After:** each agent that resumes is told what of its own was stopped
27//!   ([`on_registered`]), once, with its next turn, so it can start it again.
28
29use std::collections::{HashMap, HashSet};
30use std::path::{Path, PathBuf};
31use std::sync::{Mutex, OnceLock};
32use std::time::Duration;
33
34use serde::{Deserialize, Serialize};
35
36use crate::backend::process_tracker::TrackedProcess;
37
38/// The record of what the last quit stopped, in the channel folder (beside
39/// `upgrade_notice`'s): a version's own data folder is new after an upgrade.
40pub const RECORD_FILE: &str = "agentmux-stopped-at-quit.json";
41/// How long after a quit resumed agents are still told.
42const TELL_FOR: Duration = Duration::from_secs(60 * 60);
43/// How long another AgentMux has to save its windows, within the host's
44/// 1.5 s for the whole quit save.
45const SAVE_WAIT_MS: u32 = 900;
46/// The longest command shown for one item.
47const MAX_LABEL: usize = 90;
48
49/// Executables of an AgentMux instance: its launcher, host and srv. An
50/// agent's own `agentmux-mcp` and `agentmux-bashwrap` are plumbing, not one.
51const AGENTMUX_IMAGES: [&str; 4] = ["agentmux", "agentmux-launcher", "agentmux-cef", "agentmux-srv"];
52/// The AgentMux process that owns the windows.
53const HOST_IMAGE: &str = "agentmux-cef";
54
55/// One process tree an agent left running.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct Work {
58    /// The agent's name, as it is addressed.
59    pub agent: String,
60    /// Its id for the note (the registry uid, or the name).
61    pub key: String,
62    /// The tree's root command, shortened.
63    pub label: String,
64    /// The tree holds another AgentMux.
65    pub agentmux: bool,
66    /// When its root started (unix ms), 0 if unknown.
67    pub started_at_ms: u64,
68    /// Its AgentMux host process, asked to save its windows at a quit.
69    #[serde(skip)]
70    pub hosts: Vec<u32>,
71}
72
73/// Lowercased executable name without directory or `.exe`.
74fn image(p: &TrackedProcess) -> String {
75    let path = if p.exe.is_empty() { p.command.split_whitespace().next().unwrap_or("") } else { &p.exe };
76    let base = path.trim_matches('"').rsplit(['\\', '/']).next().unwrap_or(path).to_ascii_lowercase();
77    base.strip_suffix(".exe").map(str::to_string).unwrap_or(base)
78}
79
80/// `command` cut to [`MAX_LABEL`] characters, on one line.
81fn shorten(command: &str) -> String {
82    let one_line = command.split_whitespace().collect::<Vec<_>>().join(" ");
83    if one_line.chars().count() <= MAX_LABEL {
84        return one_line;
85    }
86    let mut cut: String = one_line.chars().take(MAX_LABEL - 1).collect();
87    cut.push('…');
88    cut
89}
90
91/// The process trees among `members` (what an agent started: the tracker's
92/// `list_block`), one [`Work`] per tree: a root is a member whose parent
93/// isn't one.
94pub fn trees(agent: &str, key: &str, members: &[TrackedProcess]) -> Vec<Work> {
95    let pids: HashSet<u32> = members.iter().map(|p| p.pid).collect();
96    let mut children: HashMap<u32, Vec<&TrackedProcess>> = HashMap::new();
97    for p in members {
98        if let Some(parent) = p.parent_pid.filter(|pp| pids.contains(pp) && *pp != p.pid) {
99            children.entry(parent).or_default().push(p);
100        }
101    }
102    let mut out: Vec<Work> = members
103        .iter()
104        .filter(|p| p.parent_pid.is_none_or(|pp| !pids.contains(&pp) || pp == p.pid))
105        .map(|root| {
106            let mut tree = vec![root];
107            let mut seen = HashSet::from([root.pid]);
108            let mut i = 0;
109            while i < tree.len() {
110                for c in children.get(&tree[i].pid).into_iter().flatten() {
111                    if seen.insert(c.pid) {
112                        tree.push(c);
113                    }
114                }
115                i += 1;
116            }
117            let images: Vec<String> = tree.iter().map(|p| image(p)).collect();
118            Work {
119                agent: agent.to_string(),
120                key: key.to_string(),
121                label: shorten(if root.command.is_empty() { &root.exe } else { &root.command }),
122                agentmux: images.iter().any(|i| AGENTMUX_IMAGES.contains(&i.as_str())),
123                started_at_ms: root.started_at_ms,
124                hosts: tree
125                    .iter()
126                    .zip(&images)
127                    .filter(|(p, i)| {
128                        // The host itself, not its CEF helpers (renderer, GPU):
129                        // they have a `--type=` and a host for a parent.
130                        let parent_is_host =
131                            tree.iter().zip(&images).any(|(q, qi)| Some(q.pid) == p.parent_pid && *qi == HOST_IMAGE);
132                        *i == HOST_IMAGE && !p.command.contains("--type=") && !parent_is_host
133                    })
134                    .map(|(p, _)| p.pid)
135                    .collect(),
136            }
137        })
138        .collect();
139    out.sort_by_key(|w| (!w.agentmux, w.started_at_ms));
140    out
141}
142
143/// What every running agent left running now, by agent.
144pub fn running() -> Vec<Work> {
145    let Some(registry) = crate::backend::process_tracker::registry::global() else { return Vec::new() };
146    let handler = crate::backend::reactive::get_global_handler();
147    let mut out = Vec::new();
148    for r in handler.list_agents() {
149        let members = registry.list_block(&r.block_id);
150        if members.is_empty() {
151            continue;
152        }
153        let key = r.uid.clone().unwrap_or_else(|| r.agent_id.clone());
154        out.extend(trees(&r.agent_id, &key, &members));
155    }
156    out
157}
158
159/// "2 h", "35 min", "a moment", for how long something ran.
160fn ran_for(started_at_ms: u64, now_ms: u64) -> Option<String> {
161    if started_at_ms == 0 || now_ms <= started_at_ms {
162        return None;
163    }
164    let mins = (now_ms - started_at_ms) / 60_000;
165    Some(match mins {
166        0 => "a moment".to_string(),
167        1..=59 => format!("{mins} min"),
168        _ => format!("{} h", mins / 60),
169    })
170}
171
172/// One line for the user: "Agent-1: an AgentMux instance (`task dev`), running 9 h".
173pub fn describe(w: &Work, now_ms: u64) -> String {
174    let what = if w.agentmux { format!("an AgentMux instance (`{}`)", w.label) } else { format!("`{}`", w.label) };
175    match ran_for(w.started_at_ms, now_ms) {
176        Some(t) => format!("{}: {what}, running {t}", w.agent),
177        None => format!("{}: {what}", w.agent),
178    }
179}
180
181/// Where the launcher reads the list for its dialog: beside the staged
182/// update (`updates/` in this version's data folder).
183pub fn launcher_file() -> Option<PathBuf> {
184    std::env::var_os("AGENTMUX_DATA_DIR").filter(|d| !d.is_empty()).map(|d| PathBuf::from(d).join("updates").join("stopping.txt"))
185}
186
187/// Write `lines` for the launcher's dialog (an empty list removes the file).
188pub fn write_for_launcher(lines: &[String]) {
189    let Some(path) = launcher_file() else { return };
190    if lines.is_empty() {
191        let _ = std::fs::remove_file(&path);
192        return;
193    }
194    let written = path.parent().map_or(Ok(()), std::fs::create_dir_all).and_then(|()| std::fs::write(&path, lines.join("\n")));
195    if let Err(e) = written {
196        tracing::warn!(path = %path.display(), error = %e, "background work: couldn't write the list for the launcher");
197    }
198}
199
200// ── At the quit ─────────────────────────────────────────────────────────────
201
202#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
203struct Record {
204    at_ms: i64,
205    items: Vec<Work>,
206}
207
208fn record_path(dir: &Path) -> PathBuf {
209    dir.join(RECORD_FILE)
210}
211
212fn read(dir: &Path) -> Option<Record> {
213    std::fs::read(record_path(dir)).ok().and_then(|b| serde_json::from_slice(&b).ok())
214}
215
216fn write(dir: &Path, record: &Record) {
217    let path = record_path(dir);
218    if record.items.is_empty() {
219        let _ = std::fs::remove_file(&path);
220        return;
221    }
222    let tmp = path.with_extension("json.tmp");
223    let written = serde_json::to_vec_pretty(record)
224        .map_err(|e| e.to_string())
225        .and_then(|b| std::fs::write(&tmp, b).map_err(|e| e.to_string()))
226        .and_then(|()| std::fs::rename(&tmp, &path).map_err(|e| e.to_string()));
227    if let Err(e) = written {
228        tracing::warn!(path = %path.display(), error = %e, "background work: couldn't save what the quit stopped");
229    }
230}
231
232/// The channel folder the record lives in.
233fn channel_dir() -> Option<PathBuf> {
234    agentmux_common::DataPaths::from_env().map(|p| p.instance_dir)
235}
236
237/// A quit is about to close every pane (`SaveSessionSnapshot` with
238/// `for_quit`): record what agents left running, for their note after the
239/// next start, and on Windows tell another AgentMux among it that the
240/// session is ending, so it saves its windows before its tracker stops it.
241pub async fn at_quit() {
242    let work = tokio::task::spawn_blocking(running).await.unwrap_or_default();
243    if work.is_empty() {
244        return;
245    }
246    let now = agentmux_common::time::now_ms_u64();
247    tracing::info!(stopping = ?work.iter().map(|w| describe(w, now)).collect::<Vec<_>>(), "background work: the quit stops what agents left running");
248    if let Some(dir) = channel_dir() {
249        write(&dir, &Record { at_ms: now as i64, items: work.clone() });
250    }
251    let hosts: Vec<u32> = work.iter().flat_map(|w| w.hosts.iter().copied()).collect();
252    if !hosts.is_empty() {
253        // All at once, so several instances still answer within the one wait.
254        let _ = tokio::task::spawn_blocking(move || {
255            std::thread::scope(|s| {
256                for pid in &hosts {
257                    s.spawn(move || save_windows_of(*pid));
258                }
259            })
260        })
261        .await;
262    }
263}
264
265/// Tell host process `pid` the session is ending, as Windows does at a
266/// shutdown: `WM_QUERYENDSESSION` to one of its visible windows, which saves
267/// every window (`client/wndproc.rs`'s session-end flush), and waits for the
268/// answer up to [`SAVE_WAIT_MS`]. Nothing is closed.
269#[cfg(windows)]
270fn save_windows_of(pid: u32) {
271    use windows_sys::Win32::Foundation::{BOOL, HWND, LPARAM, TRUE};
272    use windows_sys::Win32::UI::WindowsAndMessaging::{
273        EnumWindows, GetWindowThreadProcessId, IsWindowVisible, SendMessageTimeoutW, SMTO_ABORTIFHUNG,
274        WM_QUERYENDSESSION,
275    };
276    struct Find {
277        pid: u32,
278        found: HWND,
279    }
280    unsafe extern "system" fn each(hwnd: HWND, lparam: LPARAM) -> BOOL {
281        // SAFETY: lparam is the `Find` passed below, alive for the whole call.
282        let find = unsafe { &mut *(lparam as *mut Find) };
283        let mut owner = 0u32;
284        // SAFETY: hwnd comes from EnumWindows; owner is a valid out pointer.
285        unsafe { GetWindowThreadProcessId(hwnd, &mut owner) };
286        if owner == find.pid && unsafe { IsWindowVisible(hwnd) } != 0 {
287            find.found = hwnd;
288            return 0;
289        }
290        TRUE
291    }
292    let mut find = Find { pid, found: std::ptr::null_mut() };
293    // SAFETY: the callback only reads its window and writes `find`.
294    unsafe { EnumWindows(Some(each), &mut find as *mut Find as LPARAM) };
295    if find.found.is_null() {
296        return;
297    }
298    let mut answer = 0usize;
299    // SAFETY: a message to a window handle; the timeout bounds the wait.
300    unsafe { SendMessageTimeoutW(find.found, WM_QUERYENDSESSION, 0, 0, SMTO_ABORTIFHUNG, SAVE_WAIT_MS, &mut answer) };
301    tracing::info!(pid, "background work: told another AgentMux to save its windows");
302}
303
304/// Off Windows nothing is sent: stopped with its pane, another AgentMux keeps
305/// its windows for its next start.
306#[cfg(not(windows))]
307fn save_windows_of(_pid: u32) {}
308
309// ── After the next start ────────────────────────────────────────────────────
310
311struct State {
312    dir: PathBuf,
313    record: Mutex<Record>,
314    /// Agents a note is on its way to.
315    telling: Mutex<HashSet<String>>,
316}
317
318static STATE: OnceLock<Option<State>> = OnceLock::new();
319
320/// At srv start: what the last quit stopped, if it was recent.
321pub fn init() {
322    let state = channel_dir().and_then(|dir| {
323        let record = read(&dir)?;
324        let fresh = agentmux_common::time::now_ms() - record.at_ms < TELL_FOR.as_millis() as i64;
325        if !fresh {
326            write(&dir, &Record::default());
327            return None;
328        }
329        tracing::info!(items = record.items.len(), "background work: agents will be told what the last quit stopped");
330        Some(State { dir, record: Mutex::new(record), telling: Mutex::new(HashSet::new()) })
331    });
332    let _ = STATE.set(state);
333}
334
335/// The note for `items`, all of one agent's, stopped by the quit at `at_ms`.
336pub fn note_text(items: &[Work], at_ms: i64) -> String {
337    let at = chrono::DateTime::from_timestamp_millis(at_ms)
338        .map(|t| t.with_timezone(&chrono::Local).format(" at %H:%M").to_string())
339        .unwrap_or_default();
340    let list: Vec<String> = items
341        .iter()
342        .map(|w| {
343            let started = chrono::DateTime::from_timestamp_millis(w.started_at_ms as i64)
344                .filter(|_| w.started_at_ms > 0)
345                .map(|t| t.with_timezone(&chrono::Local).format(", started %H:%M").to_string())
346                .unwrap_or_default();
347            if w.agentmux {
348                format!("an AgentMux instance (`{}`{started})", w.label)
349            } else {
350                format!("`{}`{started}", w.label)
351            }
352        })
353        .collect();
354    format!(
355        "[AgentMux] When AgentMux quit{at}, it stopped what you had running in the background: {}. Start it again if you still need it.",
356        list.join("; ")
357    )
358}
359
360/// An agent registered in `block_id`: if the last quit stopped something of
361/// its own, tell it once. Called under the handler lock, so the agent is
362/// looked up, and told, from a task of its own.
363pub fn on_registered(block_id: &str) {
364    let Some(Some(state)) = STATE.get() else { return };
365    {
366        let record = state.record.lock().unwrap_or_else(|e| e.into_inner());
367        // Told only within the hour after the quit, however long srv has run.
368        if record.items.is_empty() || agentmux_common::time::now_ms() - record.at_ms >= TELL_FOR.as_millis() as i64 {
369            return;
370        }
371    }
372    let block_id = block_id.to_string();
373    tokio::spawn(async move {
374        let Some(Some(state)) = STATE.get() else { return };
375        let handler = crate::backend::reactive::get_global_handler();
376        let Some(key) = handler
377            .list_agents()
378            .into_iter()
379            .find(|r| r.block_id == block_id)
380            .map(|r| r.uid.unwrap_or(r.agent_id))
381        else {
382            return;
383        };
384        let (items, at_ms) = {
385            let record = state.record.lock().unwrap_or_else(|e| e.into_inner());
386            (record.items.iter().filter(|w| w.key == key).cloned().collect::<Vec<_>>(), record.at_ms)
387        };
388        if items.is_empty() || !state.telling.lock().unwrap_or_else(|e| e.into_inner()).insert(key.clone()) {
389            return;
390        }
391        let text = note_text(&items, at_ms);
392        use crate::backend::upgrade_notice::{deliver_with_retry, Undelivered, RETRIES, RETRY_GAP};
393        let delivered = deliver_with_retry(
394            || {
395                let target = handler
396                    .list_agents()
397                    .into_iter()
398                    .find(|r| r.block_id == block_id)
399                    .map(|r| r.uid.unwrap_or(r.agent_id))
400                    .ok_or_else(|| Undelivered::Gone("not registered any more".into()))?;
401                handler.hold_system_note(&target, "background-work", &text).map_err(Undelivered::Retry)
402            },
403            RETRIES,
404            RETRY_GAP,
405        )
406        .await;
407        match delivered {
408            Ok(()) => {
409                // Held, not sent: a note never starts a turn, it goes with the agent's next message.
410                tracing::info!(agent = %key, items = items.len(), "background work: the note on what the quit stopped is held for the agent's next message");
411                let mut record = state.record.lock().unwrap_or_else(|e| e.into_inner());
412                record.items.retain(|w| w.key != key);
413                write(&state.dir, &record);
414            }
415            Err(e) => {
416                tracing::info!(agent = %key, error = %e, "background work: note not delivered; the next registration tries again");
417                state.telling.lock().unwrap_or_else(|e| e.into_inner()).remove(&key);
418            }
419        }
420    });
421}
422
423#[cfg(test)]
424#[path = "background_work_tests.rs"]
425mod tests;