Skip to main content

agentmux_launcher/
stale_srv.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Reclaim the data dir from an srv that an earlier launcher left behind.
5//!
6//! srv takes an exclusive `flock` on `<data_dir>/srv.lock` and writes its PID
7//! into it (`crates/srv-core/src/backend/base.rs`, `acquire_data_dir_lock`). If an
8//! srv outlives its launcher, every later launch's srv fails on that lock and
9//! the app cannot be opened (2026-10-11: macOS "Quit & Reopen" left one
10//! behind). An srv still holding the lock whose launcher is gone (it was
11//! reparented to launchd/init) is stale: stop it, and start fresh.
12//!
13//! Only a process that is an `agentmux-srv` binary is stopped, and never one
14//! started headless (`--headless` / `AGENTMUX_HEADLESS=1`), which runs on its
15//! own by design (the caller is told, [`Reclaim::HeadlessRunning`], so it can say so
16//! and not try to start a second srv on the same folder), and never one whose parent is still an AgentMux launcher:
17//! winning the single-instance socket isn't proof enough on its own, since two
18//! local builds of one checkout can share a data dir with different sockets.
19
20use std::os::unix::io::AsRawFd;
21use std::path::Path;
22use std::time::{Duration, Instant};
23
24/// Name of srv's data-dir lock file. Mirrors `SRV_DATA_LOCK_FILE` in
25/// `crates/srv-core/src/backend/base.rs`.
26const SRV_LOCK_FILE: &str = "srv.lock";
27
28/// How long a stale srv gets to exit after SIGTERM (it closes its agents
29/// first) before its whole process group is killed.
30const TERM_GRACE: Duration = Duration::from_secs(10);
31
32/// What [`reclaim_stale_srv_lock`] found.
33#[derive(Debug, PartialEq, Eq)]
34pub enum Reclaim {
35    /// Nobody holds the lock, or a stale srv was stopped: the srv spawn that follows can take it.
36    Free,
37    /// An srv started headless holds it (process `pid`). It runs on its own by design and is not stopped; a second srv
38    /// on this folder would fail on the lock.
39    HeadlessRunning { pid: i32 },
40    /// Something holds the lock that is not stopped (another instance's srv, another program, one that would not stop):
41    /// the srv spawn that follows fails on the lock and says so.
42    Left,
43}
44
45/// The title and the words for a person who opens AgentMux while an srv started headless holds its folder: it is running,
46/// without a window; here is how to use it, and how to get the app window instead. Not the splash's bare "interrupted".
47pub fn headless_running_words(pid: i32) -> (&'static str, String) {
48    (
49        "AgentMux is already running",
50        format!(
51            "AgentMux is already running without a window on this computer (process {pid}).\n\nOpen it in your browser with `agentmux open` in a terminal.\n\nTo use the app window instead, stop it with `agentmux stop`, then open AgentMux again."
52        ),
53    )
54}
55
56/// [`reclaim_stale_srv_lock`], and when a server started headless runs this folder: say what is running and how to use it
57/// or replace it, and stop. A second srv would fail on the folder's lock, and the splash would end on a bare "interrupted".
58pub fn reclaim_or_say_headless_running(data_dir: &Path) {
59    if let Reclaim::HeadlessRunning { pid } = reclaim_stale_srv_lock(data_dir) {
60        let (title, body) = headless_running_words(pid);
61        crate::log(&format!("a headless srv (pid {pid}) holds the data dir; told the person and exiting"));
62        tell_the_person(title, &body);
63        std::process::exit(0);
64    }
65}
66
67/// Print the words, and on macOS show them in a native alert too: a launcher started from the Finder has no terminal to print
68/// to. The text goes to `osascript` as arguments, never into the script, so nothing in it is parsed. Not
69/// `show_fatal_dialog`, whose other callers (out of memory, an expired upgrade) do not wait on a button.
70fn tell_the_person(title: &str, body: &str) {
71    eprintln!("{body}");
72    #[cfg(target_os = "macos")]
73    {
74        let _ = std::process::Command::new("/usr/bin/osascript")
75            .args([
76                "-e",
77                "on run argv",
78                "-e",
79                "display dialog (item 2 of argv) with title (item 1 of argv) buttons {\"OK\"} default button \"OK\" with icon caution",
80                "-e",
81                "end run",
82            ])
83            .arg(title)
84            .arg(body)
85            .stdin(std::process::Stdio::null())
86            .output();
87    }
88    #[cfg(not(target_os = "macos"))]
89    let _ = title;
90}
91
92/// Whether an `agentmux-srv` was started headless, from its arguments and its arguments with its environment
93/// (`ps` without and with `e`); either one that could not be read counts as not.
94fn started_headless(args: Option<&str>, with_env: Option<&str>) -> bool {
95    let env = with_env.is_some_and(|c| c.split_whitespace().any(|w| w == "AGENTMUX_HEADLESS=1" || w == "AGENTMUX_HEADLESS=true"));
96    let arg = args.is_some_and(|c| c.split_whitespace().any(|a| a == "--headless"));
97    env || arg
98}
99
100/// If `<data_dir>/srv.lock` is held, stop the stale srv holding it. Returns
101/// once the lock is free, or the holder can't be stopped (the srv spawn that
102/// follows then fails and reports it as before), or says that a headless srv
103/// holds it.
104pub fn reclaim_stale_srv_lock(data_dir: &Path) -> Reclaim {
105    let lock_path = data_dir.join(SRV_LOCK_FILE);
106    if lock_is_free(&lock_path) {
107        return Reclaim::Free;
108    }
109    // srv records its PID in the lock file; one from a release before that
110    // left it empty, so fall back to asking lsof who has the file open.
111    let recorded = std::fs::read_to_string(&lock_path)
112        .ok()
113        .and_then(|s| s.trim().parse::<i32>().ok())
114        .filter(|pid| *pid > 1);
115    let Some(pid) = recorded.or_else(|| lock_holder_via_lsof(&lock_path)) else {
116        crate::log(&format!(
117            "stale-srv: {} is held but its holder can't be identified; leaving it",
118            lock_path.display()
119        ));
120        return Reclaim::Left;
121    };
122    // `comm` is the executable as one field (a full path on macOS, which can
123    // hold spaces: `/Volumes/AgentMux 3/...`; the first 15 characters of the
124    // name on Linux). Only its file name ever goes into the log: another
125    // process' arguments and environment can hold secrets.
126    let Some(comm) = ps_field(pid, "comm=", false) else {
127        crate::log(&format!("stale-srv: lock names pid {pid}, which isn't running; leaving it"));
128        return Reclaim::Left;
129    };
130    let exe_name = Path::new(&comm)
131        .file_name()
132        .map(|n| n.to_string_lossy().into_owned())
133        .unwrap_or_default();
134    if !exe_name.starts_with("agentmux-srv") {
135        crate::log(&format!("stale-srv: lock names pid {pid} ({exe_name}), which isn't agentmux-srv; leaving it"));
136        return Reclaim::Left;
137    }
138    if started_headless(ps_field(pid, "command=", false).as_deref(), ps_field(pid, "command=", true).as_deref()) {
139        crate::log(&format!("stale-srv: pid {pid} is a headless srv using this data dir; leaving it"));
140        return Reclaim::HeadlessRunning { pid };
141    }
142
143    // Only an srv whose launcher is really gone: winning this launcher's
144    // single-instance socket doesn't prove nobody else owns the data dir (two
145    // local builds of one checkout have different socket hashes but the same
146    // data dir). An orphan is reparented to launchd/init (PPID 1); one whose
147    // parent is still an AgentMux process belongs to a running app.
148    let ppid = ps_field(pid, "ppid=", false).and_then(|p| p.trim().parse::<i32>().ok());
149    if let Some(ppid) = ppid.filter(|p| *p > 1) {
150        let parent = ps_field(ppid, "comm=", false)
151            .and_then(|c| Path::new(&c).file_name().map(|n| n.to_string_lossy().into_owned()))
152            .unwrap_or_default();
153        if parent.to_ascii_lowercase().contains("agentmux") {
154            crate::log(&format!(
155                "stale-srv: srv pid {pid} still has its launcher (pid {ppid}, {parent}); another instance owns this data dir, leaving it"
156            ));
157            return Reclaim::Left;
158        }
159    }
160
161    crate::log(&format!(
162        "stale-srv: srv pid {pid} still holds {} with no launcher; stopping it so this launch can start",
163        lock_path.display()
164    ));
165    unsafe { libc::kill(pid, libc::SIGTERM) };
166    if wait_for_free(&lock_path, TERM_GRACE) {
167        crate::log(&format!("stale-srv: pid {pid} exited after SIGTERM; lock is free"));
168        kill_orphaned_agents(data_dir, pid);
169        return Reclaim::Free;
170    }
171    // srv leads its own process group (srv_spawner's process_group(0)); take
172    // what else is in it down with it.
173    let target = if unsafe { libc::getpgid(pid) } == pid { -pid } else { pid };
174    unsafe { libc::kill(target, libc::SIGKILL) };
175    if wait_for_free(&lock_path, Duration::from_secs(3)) {
176        crate::log(&format!("stale-srv: pid {pid} killed; lock is free"));
177        kill_orphaned_agents(data_dir, pid);
178        Reclaim::Free
179    } else {
180        crate::log(&format!("stale-srv: lock still held after killing pid {pid}"));
181        Reclaim::Left
182    }
183}
184
185/// The stale srv is gone; its agent CLIs lead their own process groups and
186/// are still running unless it closed them. End them (`agent_roots`).
187fn kill_orphaned_agents(data_dir: &Path, pid: i32) {
188    let Ok(pid) = u32::try_from(pid) else { return };
189    if let Some(done) = agentmux_common::agent_roots::kill_orphans(data_dir, pid) {
190        crate::log(&format!(
191            "stale-srv: ended its agent CLIs: {} agent cgroup(s), {} CLI process group(s); {} had already exited",
192            done.cgroups, done.groups, done.gone
193        ));
194    }
195}
196
197/// True when nobody holds the lock (or the file doesn't exist). Takes and
198/// immediately releases the lock; the srv spawned next takes it for real.
199fn lock_is_free(lock_path: &Path) -> bool {
200    let Ok(file) = std::fs::OpenOptions::new().read(true).open(lock_path) else {
201        return true;
202    };
203    let fd = file.as_raw_fd();
204    if unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) } == 0 {
205        unsafe { libc::flock(fd, libc::LOCK_UN) };
206        true
207    } else {
208        false
209    }
210}
211
212fn wait_for_free(lock_path: &Path, within: Duration) -> bool {
213    let deadline = Instant::now() + within;
214    while Instant::now() < deadline {
215        if lock_is_free(lock_path) {
216            return true;
217        }
218        std::thread::sleep(Duration::from_millis(100));
219    }
220    lock_is_free(lock_path)
221}
222
223/// The process that has `lock_path` open, for a lock file without a recorded
224/// PID: an agentmux-srv among the holders if there is one, else the first.
225/// The checks in [`reclaim_stale_srv_lock`] still apply to it.
226fn lock_holder_via_lsof(lock_path: &Path) -> Option<i32> {
227    let pids: Vec<i32> = processes_with_file_open(lock_path)
228        .into_iter()
229        .filter(|pid| *pid > 1 && *pid != std::process::id() as i32)
230        .collect();
231    pids.iter()
232        .copied()
233        .find(|pid| {
234            ps_field(*pid, "comm=", false)
235                .and_then(|c| Path::new(&c).file_name().map(|n| n.to_string_lossy().starts_with("agentmux-srv")))
236                .unwrap_or(false)
237        })
238        .or_else(|| pids.first().copied())
239}
240
241/// PIDs with `path` open. macOS: `lsof -t`, part of the base system.
242#[cfg(not(target_os = "linux"))]
243fn processes_with_file_open(path: &Path) -> Vec<i32> {
244    let Ok(out) = std::process::Command::new("/usr/sbin/lsof")
245        .arg("-t")
246        .arg("--")
247        .arg(path)
248        .output()
249    else {
250        return Vec::new();
251    };
252    String::from_utf8_lossy(&out.stdout)
253        .lines()
254        .filter_map(|l| l.trim().parse::<i32>().ok())
255        .collect()
256}
257
258/// PIDs with `path` open. Linux: read `/proc/<pid>/fd` directly, since
259/// `lsof` isn't installed everywhere (the AppImage doesn't bundle it and the
260/// packages declare no dependencies). Only this user's processes are
261/// readable, which is all an srv we could stop can be.
262#[cfg(target_os = "linux")]
263fn processes_with_file_open(path: &Path) -> Vec<i32> {
264    let Ok(target) = std::fs::canonicalize(path) else {
265        return Vec::new();
266    };
267    let Ok(procs) = std::fs::read_dir("/proc") else {
268        return Vec::new();
269    };
270    procs
271        .flatten()
272        .filter_map(|entry| entry.file_name().to_str()?.parse::<i32>().ok())
273        .filter(|pid| {
274            std::fs::read_dir(format!("/proc/{pid}/fd"))
275                .map(|fds| fds.flatten().any(|fd| std::fs::read_link(fd.path()).is_ok_and(|l| l == target)))
276                .unwrap_or(false)
277        })
278        .collect()
279}
280
281/// One `ps` field for `pid` (`ww`: untruncated; `with_env`: append the
282/// process' environment, `ps e`), or `None` if it isn't running. Never log
283/// the result: it can hold another process' secrets.
284fn ps_field(pid: i32, field: &str, with_env: bool) -> Option<String> {
285    let flags = if with_env { "eww" } else { "ww" };
286    let out = std::process::Command::new("/bin/ps")
287        .args([flags, "-o", field, "-p", &pid.to_string()])
288        .output()
289        .ok()?;
290    let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
291    (out.status.success() && !s.is_empty()).then_some(s)
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn a_missing_or_unheld_lock_is_free() {
300        let dir = tempfile::tempdir().unwrap();
301        let lock = dir.path().join(SRV_LOCK_FILE);
302        assert!(lock_is_free(&lock), "missing file");
303        std::fs::write(&lock, "12345").unwrap();
304        assert!(lock_is_free(&lock), "file nobody holds");
305    }
306
307    #[test]
308    fn a_held_lock_is_not_free_and_is_left_alone_without_a_live_srv() {
309        let dir = tempfile::tempdir().unwrap();
310        let lock = dir.path().join(SRV_LOCK_FILE);
311        let holder = std::fs::OpenOptions::new()
312            .create(true)
313            .write(true)
314            .open(&lock)
315            .unwrap();
316        assert_eq!(unsafe { libc::flock(holder.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 0);
317        assert!(!lock_is_free(&lock));
318
319        // The lock names this test process, which isn't agentmux-srv: nothing
320        // may be signalled, and the lock stays held.
321        std::fs::write(&lock, std::process::id().to_string()).unwrap();
322        assert_eq!(reclaim_stale_srv_lock(dir.path()), Reclaim::Left);
323        assert!(!lock_is_free(&lock));
324    }
325
326    #[test]
327    fn a_free_lock_is_free() {
328        let dir = tempfile::tempdir().unwrap();
329        assert_eq!(reclaim_stale_srv_lock(dir.path()), Reclaim::Free);
330    }
331
332    #[test]
333    fn an_srv_started_headless_is_told_from_either_its_arguments_or_its_environment() {
334        assert!(started_headless(Some("/x/agentmux-srv --headless --web-port 7380"), None));
335        assert!(started_headless(None, Some("/x/agentmux-srv HOME=/h AGENTMUX_HEADLESS=1 PATH=/bin")));
336        assert!(started_headless(None, Some("/x/agentmux-srv AGENTMUX_HEADLESS=true")));
337        assert!(!started_headless(Some("/x/agentmux-srv --wavedata /d"), Some("/x/agentmux-srv HOME=/h AGENTMUX_HEADLESS=0")));
338        assert!(!started_headless(None, None), "nothing read is not headless");
339    }
340
341    #[test]
342    fn the_words_for_a_running_headless_srv_say_what_it_is_and_what_to_do() {
343        let (title, body) = headless_running_words(4242);
344        assert_eq!(title, "AgentMux is already running");
345        assert!(body.contains("without a window") && body.contains("4242"), "{body}");
346        assert!(body.contains("`agentmux open`") && body.contains("`agentmux stop`"), "{body}");
347        assert!(!body.to_lowercase().contains("interrupted"));
348    }
349}