Skip to main content

agentmux_srv_core/backend/update/
install.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How this AgentMux was installed, and which release file upgrades it
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` §4.2).
6//!
7//! Read from where the running srv binary is, so nothing has to be passed
8//! down from the launcher:
9//! - Windows portable: srv is in `<folder>/runtime/`, beside
10//!   `agentmux-portable.marker`, and `<folder>/agentmux.exe` is the launcher.
11//!   `setup.exe` installs the same `runtime/` (marker included), so a folder
12//!   with Inno Setup's uninstaller (`unins000.exe`) is a `setup.exe` install;
13//! - Microsoft Store: under `WindowsApps`; the Store updates it;
14//! - Windows `setup.exe`: any other Windows install;
15//! - macOS: inside an `.app` (srv runs nested in it, so the app is the
16//!   outermost one); it can only be upgraded in place from a folder the user
17//!   can write, not from the mounted `.dmg` or an App-Translocated copy;
18//! - Linux: an AppImage (`$APPIMAGE`), a portable folder (the marker), or a
19//!   `.deb`/`.rpm` (under `/usr` or `/opt`; dpkg's own file list says which
20//!   package manager owns it, and the packages' install helper says whether it can
21//!   upgrade itself: `docs/specs/SPEC_LINUX_PACKAGE_UPGRADE_AND_REPOSITORY_2026_10_24.md`).
22
23use std::path::{Path, PathBuf};
24
25const PORTABLE_MARKER: &str = "agentmux-portable.marker";
26
27/// What a `.deb` or `.rpm` ships to install its own updates as root, through
28/// polkit (`scripts/agentmux-install-update.sh`).
29pub const PACKAGE_HELPER: &str = "/opt/agentmux/bin/agentmux-install-update";
30
31/// dpkg's list of the files the package `agentmux` installed.
32const DPKG_FILE_LIST: &str = "/var/lib/dpkg/info/agentmux.list";
33
34/// How this AgentMux was installed.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub enum InstallKind {
37    /// A Windows portable folder; `root` holds `agentmux.exe`.
38    WindowsPortable { root: PathBuf },
39    WindowsSetup,
40    WindowsStore,
41    /// A macOS app: `app` is the outermost `.app` srv runs inside, and
42    /// `blocked` says why it can't be replaced in place (if it can't).
43    MacApp { app: PathBuf, blocked: Option<String> },
44    LinuxAppImage,
45    /// A Linux portable: the release tarball's `AgentMux/` folder, which holds
46    /// `agentmux.sh` above `usr/bin/` (or an older folder with the marker).
47    LinuxPortable { root: PathBuf },
48    /// A `.deb` (`debian`: dpkg owns it) or `.rpm` install.
49    LinuxPackage { debian: bool },
50    Unknown,
51}
52
53impl InstallKind {
54    /// The name the UI sees.
55    pub fn label(&self) -> &'static str {
56        match self {
57            Self::WindowsPortable { .. } => "windows-portable",
58            Self::WindowsSetup => "windows-setup",
59            Self::WindowsStore => "windows-store",
60            Self::MacApp { .. } => "macos-app",
61            Self::LinuxAppImage => "linux-appimage",
62            Self::LinuxPortable { .. } => "linux-portable",
63            Self::LinuxPackage { .. } => "linux-package",
64            Self::Unknown => "unknown",
65        }
66    }
67
68    /// Whether AgentMux can download and stage this kind's upgrade itself.
69    /// The others still open the release page (or the Store).
70    pub fn can_download(&self) -> bool {
71        self.can_download_with(Path::new(PACKAGE_HELPER).is_file())
72    }
73
74    /// [`Self::can_download`], given whether the package's install helper
75    /// ([`PACKAGE_HELPER`]) is there: a `.deb` or `.rpm` from before it shipped
76    /// can't install an update itself, and keeps the release page.
77    pub fn can_download_with(&self, package_helper: bool) -> bool {
78        match self {
79            Self::MacApp { blocked, .. } => blocked.is_none(),
80            Self::LinuxPackage { .. } => package_helper,
81            _ => matches!(
82                self,
83                Self::WindowsPortable { .. } | Self::WindowsSetup | Self::LinuxPortable { .. } | Self::LinuxAppImage
84            ),
85        }
86    }
87
88    /// Why this install could upgrade itself but can't here (a macOS app that can't be replaced in place), when it
89    /// can't: shown beside the button that opens the download page instead.
90    pub fn blocked_reason(&self) -> Option<&str> {
91        match self {
92            Self::MacApp { blocked, .. } => blocked.as_deref(),
93            _ => None,
94        }
95    }
96
97    /// The release file that upgrades this kind to `version` on `arch`
98    /// (`std::env::consts::ARCH`), as `.github/workflows/build-*.yml` name them.
99    pub fn asset_name(&self, version: &str, arch: &str) -> Option<String> {
100        let x64 = arch == "x86_64";
101        match self {
102            Self::WindowsPortable { .. } if x64 => Some(format!("agentmux-{version}-x64-portable.7z")),
103            Self::WindowsSetup if x64 => Some(format!("AgentMux-{version}-x64-setup.exe")),
104            Self::MacApp { .. } if arch == "aarch64" => Some(format!("AgentMux_{version}_arm64.dmg")),
105            Self::LinuxAppImage if x64 => Some(format!("AgentMux_{version}_amd64.AppImage")),
106            Self::LinuxPortable { .. } if x64 => Some(format!("AgentMux_{version}_amd64-portable.tar.xz")),
107            Self::LinuxPackage { debian: true } if x64 => Some(format!("AgentMux_{version}_amd64.deb")),
108            Self::LinuxPackage { debian: false } if x64 => Some(format!("AgentMux-{version}-1.x86_64.rpm")),
109            _ => None,
110        }
111    }
112}
113
114/// Whether `dir` holds Inno Setup's uninstaller (`unins000.exe`, or
115/// `unins001.exe`… when one was already there): a `setup.exe` install.
116pub fn has_uninstaller(dir: &Path) -> bool {
117    std::fs::read_dir(dir).is_ok_and(|entries| {
118        entries.filter_map(|e| e.ok()).any(|e| {
119            let name = e.file_name().to_string_lossy().to_ascii_lowercase();
120            name.starts_with("unins") && name.ends_with(".exe")
121        })
122    })
123}
124
125/// The kind for an srv binary at `exe` on `os` (`std::env::consts::OS`).
126fn detect_at(exe: &Path, os: &str, appimage: bool, debian: bool) -> InstallKind {
127    let dir = exe.parent();
128    let portable_root = dir
129        .filter(|d| d.join(PORTABLE_MARKER).is_file())
130        .and_then(|d| d.parent())
131        .map(Path::to_path_buf);
132    let text = exe.to_string_lossy().replace('\\', "/");
133    match os {
134        "windows" => {
135            if text.to_ascii_lowercase().contains("/windowsapps/") {
136                InstallKind::WindowsStore
137            } else if let Some(root) =
138                portable_root.filter(|r| r.join("agentmux.exe").is_file() && !has_uninstaller(r))
139            {
140                InstallKind::WindowsPortable { root }
141            } else if dir.and_then(Path::parent).is_some_and(|app| has_uninstaller(app) && app.join("agentmux.exe").is_file()) {
142                // srv is in `{app}\runtime\`; the launcher checks the same uninstaller.
143                InstallKind::WindowsSetup
144            } else {
145                InstallKind::Unknown
146            }
147        }
148        "macos" if text.contains(".app/Contents/") => mac_app(exe),
149        // The release tarball: `AgentMux/agentmux.sh` above srv's `usr/bin/`.
150        "linux" if dir.is_some_and(|d| d.ends_with("usr/bin")) && linux_portable_root(exe).is_some() => {
151            InstallKind::LinuxPortable { root: linux_portable_root(exe).unwrap_or_default() }
152        }
153        "linux" if appimage => InstallKind::LinuxAppImage,
154        "linux" => match portable_root {
155            Some(root) => InstallKind::LinuxPortable { root },
156            None if text.starts_with("/usr/") || text.starts_with("/opt/") => InstallKind::LinuxPackage { debian },
157            None => InstallKind::Unknown,
158        },
159        _ => InstallKind::Unknown,
160    }
161}
162
163/// The `.app` srv at `exe` belongs to, by the bundle layout: srv runs in a
164/// helper app nested in `AgentMux.app/Contents/Helpers/`
165/// (`runtime_mode::app_bundle_of`).
166pub fn outermost_app(exe: &Path) -> Option<PathBuf> {
167    agentmux_common::runtime_mode::app_bundle_of(exe)
168}
169
170/// Why `app` can't be replaced in place, if it can't. `read_only` is whether
171/// its volume is mounted read-only (a `.dmg` it was run straight from);
172/// `parent_writable` whether the user can write the folder that holds it.
173fn replace_blocker(app: &Path, read_only: bool, parent_writable: bool) -> Option<String> {
174    if read_only {
175        return Some(format!("{} is on a read-only volume (run from the .dmg?); drag it to Applications first", app.display()));
176    }
177    // Gatekeeper's App Translocation runs a quarantined app from a random
178    // read-only mount, so what's replaced there would not be the real app.
179    if app.to_string_lossy().contains("/AppTranslocation/") {
180        return Some(format!("{} is App-Translocated; move it to Applications and open it from there", app.display()));
181    }
182    if !parent_writable {
183        return Some(format!("the folder holding {} isn't writable by this user", app.display()));
184    }
185    None
186}
187
188/// Whether the volume holding `path` is mounted read-only.
189// `MNT_RDONLY` is BSD's (macOS included), not Linux's; only macOS asks.
190#[cfg(target_os = "macos")]
191fn on_read_only_volume(path: &Path) -> bool {
192    use std::os::unix::ffi::OsStrExt;
193    let Ok(c) = std::ffi::CString::new(path.as_os_str().as_bytes()) else { return true };
194    let mut st: libc::statfs = unsafe { std::mem::zeroed() };
195    // SAFETY: `c` is a NUL-terminated path and `st` a zeroed statfs the call fills.
196    if unsafe { libc::statfs(c.as_ptr(), &mut st) } != 0 {
197        return true;
198    }
199    (st.f_flags as u64) & (libc::MNT_RDONLY as u64) != 0
200}
201
202#[cfg(not(target_os = "macos"))]
203fn on_read_only_volume(_: &Path) -> bool {
204    false
205}
206
207/// Whether this user can create and remove entries in `dir`.
208#[cfg(unix)]
209fn writable_dir(dir: &Path) -> bool {
210    use std::os::unix::ffi::OsStrExt;
211    std::ffi::CString::new(dir.as_os_str().as_bytes())
212        // SAFETY: `c` is a NUL-terminated path.
213        .is_ok_and(|c| unsafe { libc::access(c.as_ptr(), libc::W_OK | libc::X_OK) } == 0)
214}
215
216#[cfg(not(unix))]
217fn writable_dir(_: &Path) -> bool {
218    true
219}
220
221/// The macOS app srv at `exe` runs in, and whether it can be replaced in place.
222fn mac_app(exe: &Path) -> InstallKind {
223    let app = outermost_app(exe).unwrap_or_else(|| exe.to_path_buf());
224    let parent = app.parent().unwrap_or(&app);
225    // Whoever else can rename entries beside the app could swap a checked
226    // bundle during the launcher's swap; the launcher refuses the same.
227    let blocked = replace_blocker(&app, on_read_only_volume(&app), writable_dir(parent)).or_else(|| {
228        agentmux_common::runtime_mode::folder_others_can_change(parent).map(|who| format!("{who}; drag AgentMux to Applications first"))
229    });
230    if let Some(reason) = &blocked {
231        tracing::info!(app = %app.display(), "update: this AgentMux can't upgrade itself in place: {reason}");
232    }
233    InstallKind::MacApp { app, blocked }
234}
235
236/// The Linux portable folder above srv at `exe` (`AgentMux/usr/bin/srv`):
237/// the one holding `agentmux.sh`.
238pub fn linux_portable_root(exe: &Path) -> Option<PathBuf> {
239    let root = exe.parent()?.parent()?.parent()?;
240    root.join("agentmux.sh").is_file().then(|| root.to_path_buf())
241}
242
243/// Whether dpkg installed the file at `exe`, by its file list for the package
244/// `agentmux`; otherwise it came from an `.rpm`. The package manager that owns
245/// the install is what upgrades it, not the distribution's name: an rpm can sit
246/// on a Debian system and the reverse.
247fn owned_by_dpkg(exe: &Path, file_list: &Path) -> bool {
248    std::fs::read_to_string(file_list).is_ok_and(|list| list.lines().any(|l| Path::new(l) == exe))
249}
250
251/// How the running AgentMux was installed.
252pub fn detect() -> InstallKind {
253    let Ok(exe) = std::env::current_exe() else { return InstallKind::Unknown };
254    detect_at(
255        &exe,
256        std::env::consts::OS,
257        agentmux_common::runtime_mode::running_appimage(&exe).is_some(),
258        owned_by_dpkg(&exe, Path::new(DPKG_FILE_LIST)),
259    )
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    fn portable(root: &Path) -> PathBuf {
267        let runtime = root.join("runtime");
268        std::fs::create_dir_all(&runtime).unwrap();
269        std::fs::write(runtime.join(PORTABLE_MARKER), b"").unwrap();
270        std::fs::write(root.join("agentmux.exe"), b"").unwrap();
271        runtime.join("agentmux-srv-0.59.26-windows.x64.exe")
272    }
273
274    #[test]
275    fn windows_installs_are_told_apart() {
276        let dir = tempfile::tempdir().unwrap();
277        let root = dir.path().join("agentmux-0.59.26-x64-portable");
278        let exe = portable(&root);
279        assert_eq!(detect_at(&exe, "windows", false, false), InstallKind::WindowsPortable { root });
280        let store = Path::new(r"C:\Program Files\WindowsApps\AgentMux.AgentMux_0.59.26.0_x64__vqr1k32tkfk4y\runtime\srv.exe");
281        assert_eq!(detect_at(store, "windows", false, false), InstallKind::WindowsStore);
282        // Neither a portable nor an install with the uninstaller: not one
283        // AgentMux knows how to upgrade (the launcher would refuse it).
284        let other = Path::new(r"C:\Users\u\AppData\Local\Programs\AgentMux\runtime\srv.exe");
285        assert_eq!(detect_at(other, "windows", false, false), InstallKind::Unknown);
286        // setup.exe ships the portable's runtime/, marker and all: its
287        // uninstaller is what tells the two apart.
288        let installed = dir.path().join("Programs/AgentMux");
289        let exe = portable(&installed);
290        std::fs::write(installed.join("unins000.exe"), b"").unwrap();
291        assert_eq!(detect_at(&exe, "windows", false, false), InstallKind::WindowsSetup);
292    }
293
294    #[test]
295    fn mac_and_linux_installs_are_told_apart() {
296        let app = Path::new("/Applications/AgentMux.app/Contents/Helpers/AgentMux Server.app/Contents/MacOS/srv");
297        assert!(matches!(detect_at(app, "macos", false, false), InstallKind::MacApp { app, .. } if app == Path::new("/Applications/AgentMux.app")));
298        let bin = Path::new("/tmp/.mount_AgentM/usr/bin/agentmux-srv");
299        assert_eq!(detect_at(bin, "linux", true, true), InstallKind::LinuxAppImage);
300        let deb = Path::new("/opt/AgentMux/agentmux-srv");
301        assert_eq!(detect_at(deb, "linux", false, true), InstallKind::LinuxPackage { debian: true });
302        let dir = tempfile::tempdir().unwrap();
303        let exe = portable(dir.path());
304        assert_eq!(detect_at(&exe, "linux", false, false), InstallKind::LinuxPortable { root: dir.path().to_path_buf() });
305        // The release tarball: `AgentMux/agentmux.sh` above `usr/bin/`, no
306        // marker. It wins over an `APPIMAGE` a pane passed down.
307        let tarball = tempfile::tempdir().unwrap();
308        let root = tarball.path().join("AgentMux");
309        std::fs::create_dir_all(root.join("usr/bin")).unwrap();
310        std::fs::write(root.join("agentmux.sh"), b"").unwrap();
311        let srv = root.join("usr/bin/agentmux-srv-0.59.30-linux.x64");
312        for appimage in [false, true] {
313            assert_eq!(detect_at(&srv, "linux", appimage, true), InstallKind::LinuxPortable { root: root.clone() });
314        }
315        assert!(InstallKind::LinuxPortable { root }.can_download() && InstallKind::LinuxAppImage.can_download());
316    }
317
318    #[test]
319    fn a_package_downloads_only_with_the_install_helper() {
320        let deb = InstallKind::LinuxPackage { debian: true };
321        assert!(deb.can_download_with(true));
322        assert!(!deb.can_download_with(false), "a package from before the helper shipped keeps the release page");
323        assert!(InstallKind::LinuxPackage { debian: false }.can_download_with(true));
324        assert!(InstallKind::LinuxAppImage.can_download_with(false), "the other kinds don't look for it");
325    }
326
327    #[test]
328    fn dpkg_owns_what_its_file_list_names() {
329        let dir = tempfile::tempdir().unwrap();
330        let list = dir.path().join("agentmux.list");
331        std::fs::write(&list, "/.\n/opt\n/opt/agentmux/bin/agentmux-srv-0.60.1-linux.x64\n/usr/bin/agentmux\n").unwrap();
332        assert!(owned_by_dpkg(Path::new("/opt/agentmux/bin/agentmux-srv-0.60.1-linux.x64"), &list));
333        // Another version's file, or no list at all (an rpm install, or no dpkg).
334        assert!(!owned_by_dpkg(Path::new("/opt/agentmux/bin/agentmux-srv-0.60.0-linux.x64"), &list));
335        assert!(!owned_by_dpkg(Path::new("/opt/agentmux/bin/agentmux-srv-0.60.1-linux.x64"), &dir.path().join("missing")));
336    }
337
338    #[test]
339    fn each_kind_names_the_release_file_ci_publishes() {
340        let p = InstallKind::WindowsPortable { root: PathBuf::new() };
341        assert_eq!(p.asset_name("0.59.27", "x86_64").as_deref(), Some("agentmux-0.59.27-x64-portable.7z"));
342        assert_eq!(p.asset_name("0.59.27", "aarch64"), None);
343        assert_eq!(InstallKind::MacApp { app: PathBuf::new(), blocked: None }.asset_name("0.59.27", "aarch64").as_deref(), Some("AgentMux_0.59.27_arm64.dmg"));
344        assert_eq!(InstallKind::WindowsStore.asset_name("0.59.27", "x86_64"), None);
345        assert_eq!(
346            InstallKind::LinuxPackage { debian: false }.asset_name("0.59.27", "x86_64").as_deref(),
347            Some("AgentMux-0.59.27-1.x86_64.rpm")
348        );
349        assert!(p.can_download());
350        assert!(InstallKind::WindowsSetup.can_download());
351        assert!(!InstallKind::WindowsStore.can_download());
352    }
353
354    const NESTED: &str = "AgentMux.app/Contents/Helpers/AgentMux Server.app/Contents/MacOS/srv";
355
356    #[test]
357    fn the_outermost_app_is_the_one_replaced() {
358        let exe = Path::new("/Applications").join(NESTED);
359        assert_eq!(outermost_app(&exe), Some(PathBuf::from("/Applications/AgentMux.app")));
360        // A volume or folder name with spaces, or `.app` inside a name, is no matter.
361        let dmg = Path::new("/Volumes/AgentMux 3").join(NESTED);
362        assert_eq!(outermost_app(&dmg), Some(PathBuf::from("/Volumes/AgentMux 3/AgentMux.app")));
363        let nested_in_app = Path::new("/Users/u/Foo.app/Resources").join(NESTED);
364        // A folder around the install that only ends in .app is never replaced.
365        assert_eq!(outermost_app(&nested_in_app), Some(PathBuf::from("/Users/u/Foo.app/Resources/AgentMux.app")));
366        assert_eq!(outermost_app(Path::new("/usr/local/bin/srv")), None);
367        // `.app` only counts at the end of a name.
368        assert_eq!(outermost_app(Path::new("/x/my.application/srv")), None);
369    }
370
371    #[test]
372    fn an_app_is_replaced_in_place_only_where_that_can_work() {
373        let app = Path::new("/Applications/AgentMux.app");
374        assert_eq!(replace_blocker(app, false, true), None);
375        // Run straight from the mounted .dmg.
376        let dmg = replace_blocker(Path::new("/Volumes/AgentMux 3/AgentMux.app"), true, true).unwrap();
377        assert!(dmg.contains("read-only volume"), "{dmg}");
378        let translocated = Path::new("/private/var/folders/ab/xyz/T/AppTranslocation/1234-5678/d/AgentMux.app");
379        assert!(replace_blocker(translocated, false, true).unwrap().contains("App-Translocated"));
380        assert!(replace_blocker(app, false, false).unwrap().contains("isn't writable"));
381        // Each reason alone is enough, and the read-only one is reported first.
382        assert!(replace_blocker(translocated, true, false).unwrap().contains("read-only"));
383    }
384
385    #[test]
386    fn a_mac_app_downloads_only_when_it_can_be_replaced() {
387        let kind = |blocked: Option<&str>| InstallKind::MacApp { app: PathBuf::from("/Applications/AgentMux.app"), blocked: blocked.map(String::from) };
388        assert!(kind(None).can_download());
389        assert!(!kind(Some("read-only")).can_download());
390        assert_eq!(kind(None).label(), "macos-app");
391    }
392
393    #[cfg(unix)]
394    #[test]
395    fn the_filesystem_checks_follow_the_real_folder() {
396        use std::os::unix::fs::PermissionsExt;
397        let dir = tempfile::tempdir().unwrap();
398        // `tempdir()` makes the folder 0777 & !umask: group-writable under a umask of 002 (charlie's), and
399        // an app beside a folder its group can change is refused on purpose. Set the mode, not the umask's.
400        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
401        assert!(writable_dir(dir.path()));
402        assert!(!on_read_only_volume(dir.path()));
403        // A bundle laid out like the release's, in a folder the user can write.
404        let exe = dir.path().join(NESTED);
405        std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
406        let kind = detect_at(&exe, "macos", false, false);
407        assert_eq!(kind, InstallKind::MacApp { app: dir.path().join("AgentMux.app"), blocked: None });
408        assert!(kind.can_download());
409        // The same bundle in a folder the user can't write (root ignores modes).
410        let locked = dir.path().join("locked");
411        std::fs::create_dir_all(&locked).unwrap();
412        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555)).unwrap();
413        let in_locked = locked.join(NESTED);
414        let blocked = detect_at(&in_locked, "macos", false, false);
415        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
416        // SAFETY: geteuid has no preconditions.
417        if unsafe { libc::geteuid() } != 0 {
418            assert!(!blocked.can_download(), "{blocked:?}");
419        }
420        assert!(!writable_dir(&dir.path().join("missing")));
421    }
422}