Skip to main content

agentmux_launcher/
upgrade_linux.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Linux side of "Upgrade & restart"
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` §4.2, phase
6//! 3e), for `upgrade_restart`: checking what srv names to start (a portable's
7//! `AgentMux/agentmux.sh`, or an AppImage), asking the user with `zenity` or
8//! `kdialog`, and what the new version must not inherit.
9
10use std::path::{Path, PathBuf};
11
12/// What this version's own start set for its own files, which the new
13/// version must not inherit: `agentmux.sh` and AppRun point `LD_LIBRARY_PATH`
14/// at this version's `usr/bin` (the new launcher would load this `libcef.so`),
15/// and AppRun's `APPIMAGE`… would make it think it is this AppImage. Both set
16/// their own again when the new version starts.
17#[cfg_attr(windows, allow(dead_code))]
18pub const NOT_INHERITED: &[&str] = &["LD_LIBRARY_PATH", "APPIMAGE", "APPDIR", "OWD", "ARGV0"];
19
20/// Set on the new version: AppImageLauncher, when installed, otherwise stops a
21/// freshly downloaded AppImage at its "integrate?" window until someone answers.
22#[cfg_attr(windows, allow(dead_code))]
23pub const APPIMAGELAUNCHER_OFF: (&str, &str) = ("APPIMAGELAUNCHER_DISABLE", "1");
24
25/// The Linux portable folder (`AgentMux/`, holding `agentmux.sh`) the launcher
26/// in `exe_dir` (its `usr/bin/`) belongs to.
27pub fn portable_root(exe_dir: &Path) -> Option<PathBuf> {
28    if !exe_dir.ends_with("usr/bin") {
29        return None;
30    }
31    let root = exe_dir.parent()?.parent()?;
32    root.join("agentmux.sh").is_file().then(|| root.to_path_buf())
33}
34
35/// Whether `name` is the release's AppImage for `version`
36/// (`AgentMux_<v>_amd64.AppImage`), or the copy srv makes beside one recorded
37/// for another channel (`AgentMux_<v>_amd64-2.AppImage`).
38fn is_appimage_name(name: &str, version: &str) -> bool {
39    name.strip_prefix(&format!("AgentMux_{version}_amd64"))
40        .and_then(|rest| rest.strip_suffix(".AppImage"))
41        .is_some_and(|n| n.is_empty() || n.strip_prefix('-').is_some_and(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit())))
42}
43
44fn is_executable(path: &Path) -> bool {
45    #[cfg(unix)]
46    {
47        use std::os::unix::fs::PermissionsExt;
48        std::fs::metadata(path).is_ok_and(|m| m.permissions().mode() & 0o111 != 0)
49    }
50    #[cfg(not(unix))]
51    {
52        path.is_file()
53    }
54}
55
56/// Check the new version srv names at `target` against this install. This
57/// install is a portable in `own_root`, or the AppImage `own_appimage`; the
58/// new version, of `version`, is where srv puts it: beside this one, or in
59/// `updates/<v>/` of the channel (`channel_dir`) or of this version's
60/// `data_dir`.
61/// - A portable: `agentmux.sh` of a folder whose `usr/share/agentmux/VERSION`
62///   says `version` and which holds that version's srv.
63/// - An AppImage: that version's release file, executable.
64pub fn check_target(
65    target: &Path,
66    version: &str,
67    own_root: Option<&Path>,
68    own_appimage: Option<&Path>,
69    data_dir: &Path,
70    channel_dir: &Path,
71) -> Result<(), String> {
72    if !target.is_absolute() || !target.is_file() {
73        return Err(format!("{} isn't an AgentMux {version}", target.display()));
74    }
75    let dir = target.parent().ok_or("the new version has no folder")?;
76    let updates = [data_dir, channel_dir].map(|d| d.join("updates").join(version));
77    let in_updates = |d: Option<&Path>| d.is_some_and(|d| updates.iter().any(|u| u == d));
78    let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
79    if name == "agentmux.sh" {
80        let own = own_root.ok_or("this AgentMux isn't a Linux portable")?;
81        let says = std::fs::read_to_string(dir.join("usr/share/agentmux/VERSION")).unwrap_or_default();
82        if says.trim() != version || !dir.join("usr/bin").join(format!("agentmux-srv-{version}-linux.x64")).is_file() {
83            return Err(format!("{} isn't an AgentMux {version} portable", dir.display()));
84        }
85        if dir == own {
86            return Err("that is the running AgentMux".into());
87        }
88        if dir.parent() != own.parent() && !in_updates(dir.parent()) {
89            return Err(format!("{} isn't where AgentMux put the new version", dir.display()));
90        }
91        return Ok(());
92    }
93    let own = own_appimage.ok_or("this AgentMux isn't an AppImage")?;
94    if !is_appimage_name(&name, version) || !is_executable(target) {
95        return Err(format!("{} isn't the AgentMux {version} AppImage", target.display()));
96    }
97    if target == own {
98        return Err("that is the running AgentMux".into());
99    }
100    if Some(dir) != own.parent() && !in_updates(Some(dir)) {
101        return Err(format!("{} isn't where AgentMux put the new version", target.display()));
102    }
103    Ok(())
104}
105
106/// `text` for zenity's `--text`, which reads Pango markup: a path's `&`, `<`
107/// or `>` shown as they are.
108#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
109pub(crate) fn pango_escape(text: &str) -> String {
110    text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
111}
112
113/// The dialog's process while it is open (0 when none).
114#[cfg(target_os = "linux")]
115static DIALOG_PID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
116
117/// Ask the user `body` in a native dialog, `zenity` (GNOME and most desktops)
118/// or else `kdialog` (KDE): a separate program no page or agent in AgentMux
119/// can click. `true` only for an explicit "Upgrade & restart". With neither
120/// installed, nothing restarts: the new version is staged, and the user can
121/// start it.
122#[cfg(target_os = "linux")]
123pub fn confirm(title: &str, body: &str) -> bool {
124    confirm_labelled(title, body, "Upgrade & restart")
125}
126
127/// [`confirm`] with its own name for the Yes button (the other is "Not now").
128#[cfg(target_os = "linux")]
129pub fn confirm_labelled(title: &str, body: &str, yes: &str) -> bool {
130    use std::sync::atomic::Ordering;
131    let markup = pango_escape(body);
132    let zenity_title = format!("--title={title}");
133    let zenity_text = format!("--text={markup}");
134    let zenity_ok = format!("--ok-label={yes}");
135    let dialogs: [(&str, Vec<&str>); 2] = [
136        ("zenity", vec!["--question", &zenity_title, &zenity_text, &zenity_ok, "--cancel-label=Not now", "--width=460"]),
137        ("kdialog", vec!["--title", title, "--yes-label", yes, "--no-label", "Not now", "--yesno", body]),
138    ];
139    for (program, args) in dialogs {
140        let mut cmd = std::process::Command::new(program);
141        cmd.args(&args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null());
142        // Not this version's libraries: they could break the dialog's own.
143        for key in NOT_INHERITED {
144            cmd.env_remove(key);
145        }
146        match cmd.spawn() {
147            Ok(mut child) => {
148                let pid = child.id();
149                DIALOG_PID.store(pid, Ordering::SeqCst);
150                let yes = child.wait().is_ok_and(|s| s.success());
151                // Only if it's still ours: a newer dialog may have opened
152                // after this one was closed.
153                let _ = DIALOG_PID.compare_exchange(pid, 0, Ordering::SeqCst, Ordering::SeqCst);
154                return yes;
155            }
156            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
157            Err(e) => {
158                crate::log(&format!("upgrade: couldn't open {program} to ask: {e}"));
159                return false;
160            }
161        }
162    }
163    crate::log("upgrade: neither zenity nor kdialog is installed to ask with; the new version is staged, start it yourself");
164    false
165}
166
167/// Tell the user `body` in a native dialog (`zenity` or `kdialog`), and wait for
168/// the OK; with neither installed, it only goes to the log.
169#[cfg(target_os = "linux")]
170pub fn notify(title: &str, body: &str) {
171    crate::log(&format!("{title}: {body}"));
172    let zenity_title = format!("--title={title}");
173    let zenity_text = format!("--text={}", pango_escape(body));
174    let dialogs: [(&str, Vec<&str>); 2] = [
175        ("zenity", vec!["--info", &zenity_title, &zenity_text, "--width=460"]),
176        ("kdialog", vec!["--title", title, "--msgbox", body]),
177    ];
178    for (program, args) in dialogs {
179        let mut cmd = std::process::Command::new(program);
180        cmd.args(&args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null());
181        for key in NOT_INHERITED {
182            cmd.env_remove(key);
183        }
184        match cmd.status() {
185            Ok(_) => return,
186            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
187            Err(_) => return,
188        }
189    }
190}
191
192/// Close the open dialog (as "Not now").
193#[cfg(target_os = "linux")]
194pub fn dismiss() {
195    let pid = DIALOG_PID.swap(0, std::sync::atomic::Ordering::SeqCst);
196    if pid != 0 {
197        // SAFETY: signals the dialog this launcher started and still waits on.
198        unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) };
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn appimage_names_are_the_release_s_or_srv_s_copy() {
208        assert!(is_appimage_name("AgentMux_0.59.30_amd64.AppImage", "0.59.30"));
209        assert!(is_appimage_name("AgentMux_0.59.30_amd64-2.AppImage", "0.59.30"));
210        assert!(!is_appimage_name("AgentMux_0.59.31_amd64.AppImage", "0.59.30"));
211        assert!(!is_appimage_name("AgentMux_0.59.30_amd64-x.AppImage", "0.59.30"));
212        assert!(!is_appimage_name("AgentMux_0.59.30_amd64.AppImage.part", "0.59.30"));
213    }
214
215    #[test]
216    fn paths_show_as_they_are_in_zenity() {
217        assert_eq!(pango_escape("/home/a&b/<x>"), "/home/a&amp;b/&lt;x&gt;");
218    }
219
220    fn portable(at: &Path, version: &str) -> PathBuf {
221        std::fs::create_dir_all(at.join("usr/bin")).unwrap();
222        std::fs::create_dir_all(at.join("usr/share/agentmux")).unwrap();
223        std::fs::write(at.join("agentmux.sh"), b"").unwrap();
224        std::fs::write(at.join("usr/share/agentmux/VERSION"), format!("{version}\n")).unwrap();
225        std::fs::write(at.join("usr/bin").join(format!("agentmux-srv-{version}-linux.x64")), b"").unwrap();
226        at.join("agentmux.sh")
227    }
228
229    #[test]
230    fn only_that_versions_portable_beside_this_one_or_in_updates_starts() {
231        let root = tempfile::tempdir().unwrap();
232        let data = root.path().join("data");
233        let chan = root.path().join("channel");
234        let own = root.path().join("AgentMux");
235        portable(&own, "0.59.29");
236        assert_eq!(portable_root(&own.join("usr/bin")).as_deref(), Some(own.as_path()));
237        assert_eq!(portable_root(&own.join("usr/lib")), None);
238        let new = portable(&root.path().join("AgentMux-0.59.30"), "0.59.30");
239        assert!(check_target(&new, "0.59.30", Some(&own), None, &data, &chan).is_ok());
240        let staged = portable(&data.join("updates/0.59.30/AgentMux-0.59.30"), "0.59.30");
241        assert!(check_target(&staged, "0.59.30", Some(&own), None, &data, &chan).is_ok());
242        // srv's fallback when the folder beside this one can't be written.
243        let in_channel = portable(&chan.join("updates/0.59.30/AgentMux-0.59.30"), "0.59.30");
244        assert!(check_target(&in_channel, "0.59.30", Some(&own), None, &data, &chan).is_ok());
245        assert!(check_target(&in_channel, "0.59.30", Some(&own), None, &data, &root.path().join("other")).is_err());
246        // Not that version, not this install's kind, the running one, or elsewhere.
247        assert!(check_target(&new, "0.59.31", Some(&own), None, &data, &chan).is_err());
248        assert!(check_target(&new, "0.59.30", None, Some(Path::new("/x.AppImage")), &data, &chan).is_err());
249        assert!(check_target(&own.join("agentmux.sh"), "0.59.29", Some(&own), None, &data, &chan).is_err());
250        let far = portable(&root.path().join("elsewhere/AgentMux-0.59.30"), "0.59.30");
251        assert!(check_target(&far, "0.59.30", Some(&own), None, &data, &chan).is_err());
252        assert!(check_target(Path::new("agentmux.sh"), "0.59.30", Some(&own), None, &data, &chan).is_err());
253    }
254
255    #[cfg(unix)]
256    #[test]
257    fn only_that_versions_executable_appimage_beside_this_one_starts() {
258        use std::os::unix::fs::PermissionsExt;
259        let root = tempfile::tempdir().unwrap();
260        let data = root.path().join("data");
261        let chan = root.path().join("channel");
262        let own = root.path().join("AgentMux_0.59.29_amd64.AppImage");
263        std::fs::write(&own, b"").unwrap();
264        let new = root.path().join("AgentMux_0.59.30_amd64.AppImage");
265        std::fs::write(&new, b"").unwrap();
266        assert!(check_target(&new, "0.59.30", None, Some(&own), &data, &chan).is_err(), "not executable yet");
267        std::fs::set_permissions(&new, std::fs::Permissions::from_mode(0o755)).unwrap();
268        assert!(check_target(&new, "0.59.30", None, Some(&own), &data, &chan).is_ok());
269        // srv's fallback when the folder beside this one can't be written.
270        std::fs::create_dir_all(chan.join("updates/0.59.30")).unwrap();
271        let in_channel = chan.join("updates/0.59.30/AgentMux_0.59.30_amd64.AppImage");
272        std::fs::copy(&new, &in_channel).unwrap();
273        assert!(check_target(&in_channel, "0.59.30", None, Some(&own), &data, &chan).is_ok());
274        assert!(check_target(&new, "0.59.30", Some(root.path()), None, &data, &chan).is_err(), "not an AppImage install");
275        assert!(check_target(&new, "0.59.31", None, Some(&own), &data, &chan).is_err());
276    }
277}