Skip to main content

agentmux_launcher/
upgrade_package.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The launcher's half of upgrading a `.deb` or `.rpm` install from the app
5//! (`docs/specs/SPEC_LINUX_PACKAGE_UPGRADE_AND_REPOSITORY_2026_10_24.md` ยง3.1,
6//! phase 3g-1).
7//!
8//! Installing a package takes root, and AgentMux never runs as root. So instead
9//! of the usual "quit, then run the installer", the user is asked for permission
10//! first, while AgentMux is still open: `pkexec` starts the package's own helper
11//! (`/opt/agentmux/bin/agentmux-install-update`, `scripts/agentmux-install-update.sh`),
12//! the desktop shows its password prompt, and the helper checks the file itself
13//! and prints `READY`. Only then does the launcher quit; the helper waits for it
14//! to be gone, installs, and a small waiter, started before any of that and kept
15//! running after the launcher exits, starts AgentMux again whether the install
16//! worked or not, so the old version runs rather than none.
17//!
18//! If the password is refused, can't be asked for, or the file fails its checks,
19//! nothing quits: the reason is left for srv (`INSTALL_RESULT_FILE`) and the
20//! panel says it.
21
22use std::path::{Path, PathBuf};
23
24/// Where a package puts AgentMux's programs.
25pub const INSTALL_BIN: &str = "/opt/agentmux/bin";
26/// The helper's name in [`INSTALL_BIN`].
27pub const HELPER_NAME: &str = "agentmux-install-update";
28/// The command that starts the installed AgentMux (the package's wrapper).
29pub const START_COMMAND: &str = "/usr/bin/agentmux";
30
31/// The helper's record of the last upgrade it did (`from=` and `to=` lines), readable
32/// by anyone: what "go back" is offered from.
33pub const STATE_DIR: &str = "/var/lib/agentmux";
34/// How long after an upgrade going back is still offered: after that, what the new
35/// version did to its data is too much to leave behind.
36const GO_BACK_WITHIN: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 60 * 60);
37
38/// How long going back waits for the helper's `READY`: it prints that only once it has downloaded
39/// the old release (its download may take up to 900 s) and checked it, and the user's password
40/// prompt comes before all of that. Stopping the wait early would leave the helper without the waiter
41/// that starts AgentMux again.
42const GO_BACK_AUTHORIZE_WITHIN: std::time::Duration = std::time::Duration::from_secs(900 + 300);
43
44/// What to hand the helper in place of a file when it is to install the version
45/// the last upgrade replaced.
46const GO_BACK_ARG: &str = "--go-back";
47
48/// A package that the user's password can install.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct PackageUpgrade {
51    /// The release's `.deb` or `.rpm` in `updates/<version>/` of the data folder;
52    /// for going back, [`GO_BACK_ARG`] (the helper downloads the package itself).
53    pub installer: PathBuf,
54    pub version: String,
55    /// This version's data folder: where the result is left for srv.
56    pub data_dir: PathBuf,
57}
58
59/// The release's file for `version`, by package kind.
60pub fn package_file_name(version: &str, deb: bool) -> String {
61    if deb {
62        format!("AgentMux_{version}_amd64.deb")
63    } else {
64        format!("AgentMux-{version}-1.x86_64.rpm")
65    }
66}
67
68/// Check what srv names to install against this install: `installer` is the release's
69/// package for `version`, as downloaded into this version's `updates/<version>/`
70/// and whole by `sha256`, and this launcher is the installed one (`own_dir` is
71/// `bin_dir`) with the install helper beside it.
72pub fn check(installer: &Path, sha256: &str, version: &str, own_dir: &Path, data_dir: &Path, bin_dir: &Path) -> Result<PackageUpgrade, String> {
73    if own_dir != bin_dir || !bin_dir.join(HELPER_NAME).is_file() {
74        return Err("this AgentMux isn't a .deb or .rpm install that can install updates itself".into());
75    }
76    let named_right = installer
77        .file_name()
78        .is_some_and(|n| [true, false].iter().any(|deb| n.to_string_lossy() == package_file_name(version, *deb)));
79    let in_updates = installer.parent() == Some(data_dir.join("updates").join(version).as_path());
80    if !installer.is_absolute() || !named_right || !in_updates || !installer.is_file() {
81        return Err(format!("{} isn't the AgentMux {version} package AgentMux downloaded", installer.display()));
82    }
83    if !crate::upgrade_restart::is_sha256_hex(sha256) || crate::upgrade_restart::file_sha256(installer).as_deref() != Some(sha256) {
84        return Err(format!("{} isn't the AgentMux {version} release; download it again", installer.display()));
85    }
86    Ok(PackageUpgrade { installer: installer.to_path_buf(), version: version.to_string(), data_dir: data_dir.to_path_buf() })
87}
88
89/// Whether the last upgrade the helper did replaced `version` with `own_version` (the
90/// running one) not long before `now`: then going back to it is on offer.
91/// `record` is the helper's `last-upgrade` file: `from=` and `to=` lines.
92pub fn go_back_version(record: &Path, own_version: &str, now: std::time::SystemTime) -> Option<String> {
93    let age = now.duration_since(std::fs::metadata(record).and_then(|m| m.modified()).ok()?).unwrap_or_default();
94    let text = std::fs::read_to_string(record).ok()?;
95    let field = |key: &str| text.lines().find_map(|l| l.strip_prefix(key)).map(|v| v.trim().to_string());
96    let (from, to) = (field("from=")?, field("to=")?);
97    let plain = |v: &str| !v.is_empty() && v.bytes().all(|b| b.is_ascii_alphanumeric() || b"+~.-".contains(&b));
98    (to == own_version && plain(&from) && plain(&to) && from != to && age < GO_BACK_WITHIN).then_some(from)
99}
100
101impl PackageUpgrade {
102    /// Going back to `version`: the helper fetches and checks the package itself.
103    pub fn go_back(version: &str, data_dir: &Path) -> PackageUpgrade {
104        let up = PackageUpgrade { installer: PathBuf::from(GO_BACK_ARG), version: version.to_string(), data_dir: data_dir.to_path_buf() };
105        let _ = std::fs::create_dir_all(up.files().0.parent().unwrap_or(data_dir));
106        up
107    }
108
109    fn is_go_back(&self) -> bool {
110        self.installer.as_os_str() == GO_BACK_ARG
111    }
112
113    fn deb(&self) -> bool {
114        self.installer.extension().is_some_and(|e| e == "deb")
115    }
116
117    /// Where the waiter's output goes, and where the result is left.
118    fn files(&self) -> (PathBuf, PathBuf, PathBuf) {
119        let dir = self.data_dir.join("updates").join(&self.version);
120        (dir.join("install.out"), dir.join("install.err"), dir.join(agentmux_common::srv_stderr::INSTALL_RESULT_FILE))
121    }
122
123    /// The command that installs this file by hand: what the panel offers when no
124    /// password prompt can be shown.
125    pub fn manual_command(&self) -> String {
126        if self.is_go_back() {
127            return format!("download AgentMux {} from https://github.com/agentmuxai/agentmux/releases and install it with your package manager", self.version);
128        }
129        format!("sudo {} {}", if self.deb() { "apt install" } else { "dnf install" }, self.installer.display())
130    }
131}
132
133/// The reason an earlier try left (see [`leave_result`]).
134fn read_result(up: &PackageUpgrade) -> Option<String> {
135    let text = std::fs::read_to_string(up.files().2).ok()?;
136    serde_json::from_str::<serde_json::Value>(&text).ok()?.get("error")?.as_str().map(String::from)
137}
138
139/// Leave `error` for srv, which shows it in the version panel.
140fn leave_result(up: &PackageUpgrade, error: &str) {
141    let (_, _, result) = up.files();
142    let json = serde_json::json!({ "version": up.version, "error": error });
143    if let Err(e) = std::fs::write(&result, format!("{json}\n")) {
144        crate::log(&format!("upgrade: couldn't leave {} for srv: {e}", result.display()));
145    }
146}
147
148/// What the waiter runs: `pkexec <helper> <file> <version> <launcher pid>`, with the
149/// helper's output in files the launcher and the waiter read (the files are opened
150/// here, as the user, so root never needs a path in the user's folders).
151/// Arguments: pkexec, helper, file, version, launcher pid, out, err, result, the
152/// command that starts AgentMux.
153///
154/// Before the helper printed `READY` (password refused or unavailable, or the file
155/// failed a check) AgentMux is still running: the exit status tells the launcher
156/// what happened, and nothing else is done. After it, the waiter outlives the
157/// launcher: it leaves why the install failed (a success leaves nothing), waits for
158/// the launcher to be gone and starts AgentMux again, the old version or the new.
159const WAITER: &str = r#"pkexec="$1"; helper="$2"; file="$3"; ver="$4"; lpid="$5"; out="$6"; err="$7"; result="$8"; start="$9"
160"$pkexec" "$helper" "$file" "$ver" "$lpid" >"$out" 2>"$err" </dev/null
161rc=$?
162grep -qx READY "$out" 2>/dev/null || exit "$rc"
163if [ "$rc" -eq 0 ]; then
164    rm -f "$result"
165else
166    reason=$(sed -n 's/^agentmux-install-update: //p' "$err" | tail -n 1 | tr -d '"\\' | cut -c1-300)
167    [ -n "$reason" ] || reason="the installer stopped with status $rc"
168    printf '{"version":"%s","error":"%s"}\n' "$ver" "$reason" >"$result"
169fi
170# The launcher is on its way out (it was told to quit when the helper said READY):
171# start AgentMux once it has gone, whether or not the install worked.
172n=0
173while kill -0 "$lpid" 2>/dev/null; do
174    [ "$n" -lt 180 ] || exit "$rc"
175    sleep 1
176    n=$((n + 1))
177done
178exec "$start"
179"#;
180
181/// pkexec exits with this when the user dismissed the password prompt, and with
182/// [`NOT_AUTHORIZED`] when it couldn't authorise the command (no prompt to show, or
183/// not allowed).
184const DISMISSED: i32 = 126;
185const NOT_AUTHORIZED: i32 = 127;
186
187/// The waiter's process group while the password prompt is open (0 when none).
188static WAITER_GROUP: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
189
190/// What the dialog asks before the password is: the user agrees to quit, then
191/// the desktop asks for the password.
192pub fn question(up: &PackageUpgrade, stopping_paragraph: &str) -> String {
193    format!(
194        "Restart AgentMux to upgrade to {}?\n\n\
195         AgentMux asks your computer for permission to install the new {} package (you may be asked for your password), \
196         then every window closes and every agent stops, the new version is installed and AgentMux opens again.\n\n\
197         Your tabs come back and agents resume their conversations.{stopping_paragraph}",
198        up.version,
199        if up.deb() { ".deb" } else { ".rpm" },
200    )
201}
202
203/// What the dialog asks when the new version could not be kept running.
204pub fn go_back_question(from: &str, to: &str, why: &str) -> String {
205    format!(
206        "AgentMux {to} {why}.\n\n\
207         Go back to AgentMux {from}, the version before the last upgrade? Your computer asks for your password \
208         to install it, then AgentMux {from} opens. Your tabs from before the upgrade come back, but what you \
209         changed in {to} stays in {to}'s own data."
210    )
211}
212
213/// The new version could not be kept running (`why` finishes "AgentMux X ___"): offer to
214/// go back to the version the last upgrade replaced. `true` once the helper has
215/// accepted and is waiting for this launcher to exit: the caller exits, and the waiter
216/// starts the old version. Only for a `.deb`/`.rpm` install, one upgrade from the app
217/// ago (the helper's record), and the user's yes.
218pub fn offer_go_back(own_version: &str, own_dir: &Path, data_dir: &Path, why: &str) -> bool {
219    if own_dir != Path::new(INSTALL_BIN) || !own_dir.join(HELPER_NAME).is_file() {
220        return false;
221    }
222    let record = Path::new(STATE_DIR).join("last-upgrade");
223    let Some(from) = go_back_version(&record, own_version, std::time::SystemTime::now()) else { return false };
224    crate::log(&format!("upgrade: {own_version} {why}; offering to go back to {from}"));
225    if !crate::upgrade_linux::confirm_labelled("Go back to the previous AgentMux?", &go_back_question(&from, own_version, why), "Go back") {
226        return false;
227    }
228    let up = PackageUpgrade::go_back(&from, data_dir);
229    if authorize(&up, std::process::id(), GO_BACK_AUTHORIZE_WITHIN) {
230        return true;
231    }
232    // Nothing was installed: the reason is the result file's, if there is one (a cancelled prompt has none).
233    if let Some(error) = read_result(&up) {
234        crate::upgrade_linux::notify("AgentMux couldn't go back", &format!("The install didn't finish: {error}"));
235    }
236    false
237}
238
239/// Close the password prompt (and with it the waiter), as "Not now".
240pub fn dismiss() {
241    let group = WAITER_GROUP.swap(0, std::sync::atomic::Ordering::SeqCst);
242    if group != 0 {
243        let _ = agentmux_common::process::signal_process_group(group, libc::SIGTERM);
244    }
245}
246
247/// The last line the helper left on stderr, without its prefix.
248fn last_reason(err: &Path) -> Option<String> {
249    let text = std::fs::read_to_string(err).ok()?;
250    let line = text.lines().rev().map(str::trim).find(|l| !l.is_empty())?;
251    Some(line.strip_prefix("agentmux-install-update: ").unwrap_or(line).chars().take(300).collect())
252}
253
254/// Ask for permission to install `up` (the desktop's password prompt, through
255/// polkit) and have its helper check the file. `true` once the helper is waiting
256/// for AgentMux to quit: the waiter then carries on without the launcher.
257/// `false` (with the reason left for srv, unless the user simply said no) when
258/// nothing will be installed, so AgentMux keeps running.
259pub fn authorize(up: &PackageUpgrade, launcher_pid: u32, within: std::time::Duration) -> bool {
260    authorize_with(Path::new("/usr/bin/pkexec"), &Path::new(INSTALL_BIN).join(HELPER_NAME), Path::new(START_COMMAND), up, launcher_pid, within)
261}
262
263fn authorize_with(pkexec: &Path, helper: &Path, start: &Path, up: &PackageUpgrade, launcher_pid: u32, within: std::time::Duration) -> bool {
264    use std::os::unix::process::CommandExt;
265    let (out, err, result) = up.files();
266    let _ = std::fs::remove_file(&result);
267    if !pkexec.is_file() {
268        leave_result(up, &format!("this computer has no pkexec to ask for permission. Install it yourself: {}", up.manual_command()));
269        return false;
270    }
271    let _ = std::fs::remove_file(&out);
272    let mut cmd = std::process::Command::new("/bin/sh");
273    cmd.arg("-c")
274        .arg(WAITER)
275        .arg("agentmux-install-waiter")
276        .arg(pkexec)
277        .arg(helper)
278        .arg(&up.installer)
279        .arg(&up.version)
280        .arg(launcher_pid.to_string())
281        .arg(&out)
282        .arg(&err)
283        .arg(&result)
284        .arg(start)
285        .stdin(std::process::Stdio::null())
286        .stdout(std::process::Stdio::null())
287        .stderr(std::process::Stdio::null())
288        // Its own session: it outlives this launcher, and a signal to this one's group never reaches it.
289        .process_group(0);
290    crate::upgrade_restart::restart_env(&mut cmd, std::env::vars_os());
291    let mut child = match cmd.spawn() {
292        Ok(c) => c,
293        Err(e) => {
294            leave_result(up, &format!("couldn't start the installer: {e}"));
295            return false;
296        }
297    };
298    let group = child.id();
299    WAITER_GROUP.store(group, std::sync::atomic::Ordering::SeqCst);
300    let started = std::time::Instant::now();
301    let ready = loop {
302        if std::fs::read_to_string(&out).is_ok_and(|t| t.lines().any(|l| l == "READY")) {
303            break true;
304        }
305        match child.try_wait() {
306            Ok(Some(status)) => {
307                // It stopped before the helper was ready: the exit status says why.
308                match status.code() {
309                    Some(DISMISSED) | None => crate::log("upgrade: the password prompt was dismissed; nothing is installed"),
310                    Some(NOT_AUTHORIZED) => {
311                        crate::log("upgrade: polkit couldn't authorise the install (no password prompt here, or not allowed)");
312                        leave_result(up, &format!("no password prompt could be shown here. Install it yourself: {}", up.manual_command()));
313                    }
314                    Some(code) => {
315                        let why = last_reason(&err).unwrap_or_else(|| format!("the installer stopped with status {code}"));
316                        crate::log(&format!("upgrade: the package install didn't start: {why}"));
317                        leave_result(up, &why);
318                    }
319                }
320                break false;
321            }
322            Ok(None) if started.elapsed() > within => {
323                let _ = agentmux_common::process::signal_process_group(group, libc::SIGTERM);
324                crate::log("upgrade: no answer to the password prompt in time");
325                break false;
326            }
327            Ok(None) => std::thread::sleep(std::time::Duration::from_millis(150)),
328            Err(e) => {
329                crate::log(&format!("upgrade: lost the installer's waiter: {e}"));
330                break false;
331            }
332        }
333    };
334    // Still the waiter's only while this prompt is open; a dismiss after this can't reach it.
335    let _ = WAITER_GROUP.compare_exchange(group, 0, std::sync::atomic::Ordering::SeqCst, std::sync::atomic::Ordering::SeqCst);
336    if ready {
337        // Leave it running: it is the waiter that starts AgentMux again. Dropping the
338        // handle doesn't stop it.
339        drop(child);
340    }
341    ready
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347    use std::os::unix::fs::PermissionsExt;
348    use std::time::Duration;
349
350    const SHA: &str = "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"; // "foo"
351
352    /// A data folder with `updates/0.60.2/<name>` holding "foo", and a bin folder with the helper.
353    fn layout(name: &str) -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) {
354        let dir = tempfile::tempdir().unwrap();
355        let data = dir.path().join("data");
356        let updates = data.join("updates/0.60.2");
357        std::fs::create_dir_all(&updates).unwrap();
358        let installer = updates.join(name);
359        std::fs::write(&installer, "foo").unwrap();
360        let bin = dir.path().join("bin");
361        std::fs::create_dir_all(&bin).unwrap();
362        std::fs::write(bin.join(HELPER_NAME), "#!/bin/sh\n").unwrap();
363        (dir, installer, data, bin)
364    }
365
366    #[test]
367    fn only_the_releases_package_in_this_versions_updates_folder_passes() {
368        for name in ["AgentMux_0.60.2_amd64.deb", "AgentMux-0.60.2-1.x86_64.rpm"] {
369            let (_dir, installer, data, bin) = layout(name);
370            let up = check(&installer, SHA, "0.60.2", &bin, &data, &bin).unwrap();
371            assert_eq!(up.installer, installer);
372            assert_eq!(up.deb(), name.ends_with(".deb"));
373        }
374    }
375
376    #[test]
377    fn a_package_that_isnt_what_srv_downloaded_is_refused() {
378        let (dir, installer, data, bin) = layout("AgentMux_0.60.2_amd64.deb");
379        assert!(check(&installer, SHA, "0.60.3", &bin, &data, &bin).is_err(), "another version");
380        assert!(check(&installer, &SHA.replace('2', "3"), "0.60.2", &bin, &data, &bin).is_err(), "a changed file");
381        assert!(check(&installer, "zz", "0.60.2", &bin, &data, &bin).is_err(), "not a digest");
382        assert!(check(&installer, SHA, "0.60.2", &dir.path().join("elsewhere"), &data, &bin).is_err(), "not the installed launcher");
383        let wrong_name = installer.with_file_name("agentmux.deb");
384        std::fs::copy(&installer, &wrong_name).unwrap();
385        assert!(check(&wrong_name, SHA, "0.60.2", &bin, &data, &bin).is_err(), "the release's name only");
386        let outside = dir.path().join("AgentMux_0.60.2_amd64.deb");
387        std::fs::copy(&installer, &outside).unwrap();
388        assert!(check(&outside, SHA, "0.60.2", &bin, &data, &bin).is_err(), "only from this version's updates folder");
389        std::fs::remove_file(bin.join(HELPER_NAME)).unwrap();
390        assert!(check(&installer, SHA, "0.60.2", &bin, &data, &bin).is_err(), "a package from before the helper shipped");
391    }
392
393    #[test]
394    fn the_manual_command_names_the_package_manager_and_the_file() {
395        let (_dir, installer, data, bin) = layout("AgentMux_0.60.2_amd64.deb");
396        let up = check(&installer, SHA, "0.60.2", &bin, &data, &bin).unwrap();
397        assert_eq!(up.manual_command(), format!("sudo apt install {}", installer.display()));
398        let (_dir, installer, data, bin) = layout("AgentMux-0.60.2-1.x86_64.rpm");
399        let up = check(&installer, SHA, "0.60.2", &bin, &data, &bin).unwrap();
400        assert_eq!(up.manual_command(), format!("sudo dnf install {}", installer.display()));
401    }
402
403    /// An executable that stands in for pkexec: runs `body`, given the helper and its arguments.
404    fn fake_pkexec(dir: &Path, body: &str) -> PathBuf {
405        let path = dir.join("pkexec");
406        std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
407        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
408        path
409    }
410
411    fn result_error(up: &PackageUpgrade) -> Option<String> {
412        let text = std::fs::read_to_string(up.files().2).ok()?;
413        serde_json::from_str::<serde_json::Value>(&text).ok()?.get("error")?.as_str().map(String::from)
414    }
415
416    /// A script standing in for the command that starts AgentMux: it records that it ran.
417    fn start_script(dir: &Path) -> (PathBuf, PathBuf) {
418        let marker = dir.join("started");
419        let start = dir.join("start.sh");
420        std::fs::write(&start, format!("#!/bin/sh\necho started >> {}\n", marker.display())).unwrap();
421        std::fs::set_permissions(&start, std::fs::Permissions::from_mode(0o755)).unwrap();
422        (start, marker)
423    }
424
425    /// For the tests that never get as far as starting AgentMux.
426    fn no_start(dir: &Path) -> PathBuf {
427        start_script(dir).0
428    }
429
430    fn wait_for(what: impl Fn() -> bool) -> bool {
431        let started = std::time::Instant::now();
432        while !what() && started.elapsed() < Duration::from_secs(15) {
433            std::thread::sleep(Duration::from_millis(50));
434        }
435        what()
436    }
437
438    #[test]
439    fn a_failed_install_leaves_its_reason_and_the_waiter_starts_agentmux_once_the_launcher_is_gone() {
440        let (dir, installer, data, bin) = layout("AgentMux_0.60.2_amd64.deb");
441        let up = check(&installer, SHA, "0.60.2", &bin, &data, &bin).unwrap();
442        // Authorised: READY, then an install that fails with a reason on stderr.
443        let pkexec = fake_pkexec(dir.path(), "echo READY; echo 'agentmux-install-update: apt-get couldn'\\''t install it' >&2; exit 1");
444        let (start, marker) = start_script(dir.path());
445        // A process standing in for the launcher, which is still quitting.
446        let mut launcher = std::process::Command::new("sleep").arg("60").spawn().unwrap();
447        assert!(authorize_with(&pkexec, &bin.join(HELPER_NAME), &start, &up, launcher.id(), Duration::from_secs(10)));
448        assert!(wait_for(|| result_error(&up).is_some()));
449        assert_eq!(result_error(&up).as_deref(), Some("apt-get couldn't install it"));
450        std::thread::sleep(Duration::from_millis(1500));
451        assert!(!marker.exists(), "not while the launcher is still there");
452        launcher.kill().unwrap();
453        launcher.wait().unwrap();
454        assert!(wait_for(|| marker.exists()), "AgentMux is started again after a failed install");
455    }
456
457    #[test]
458    fn a_successful_install_leaves_no_failure_and_starts_agentmux() {
459        let (dir, installer, data, bin) = layout("AgentMux_0.60.2_amd64.deb");
460        let up = check(&installer, SHA, "0.60.2", &bin, &data, &bin).unwrap();
461        let (start, marker) = start_script(dir.path());
462        let pkexec = fake_pkexec(dir.path(), "echo READY; exit 0");
463        let (out, err, result) = up.files();
464        std::fs::write(&result, "old").unwrap();
465        // Run the waiter itself, with a launcher that is already gone.
466        let status = std::process::Command::new("/bin/sh")
467            .arg("-c")
468            .arg(WAITER)
469            .arg("waiter")
470            .arg(&pkexec)
471            .arg(bin.join(HELPER_NAME))
472            .arg(&installer)
473            .arg("0.60.2")
474            .arg("999999")
475            .arg(&out)
476            .arg(&err)
477            .arg(&result)
478            .arg(&start)
479            .status()
480            .unwrap();
481        assert!(status.success());
482        assert!(marker.exists(), "AgentMux is started once the install is done");
483        assert!(!result.exists(), "a successful install leaves no failure behind");
484    }
485
486    #[test]
487    fn going_back_is_offered_only_for_the_version_the_last_upgrade_installed() {
488        let dir = tempfile::tempdir().unwrap();
489        let record = dir.path().join("last-upgrade");
490        let now = std::time::SystemTime::now();
491        assert_eq!(go_back_version(&record, "0.60.2", now), None, "no upgrade done from the app");
492        std::fs::write(&record, "from=0.60.1\nto=0.60.2\n").unwrap();
493        assert_eq!(go_back_version(&record, "0.60.2", now).as_deref(), Some("0.60.1"));
494        assert_eq!(go_back_version(&record, "0.60.3", now), None, "a version the upgrade didn't install");
495        assert_eq!(go_back_version(&record, "0.60.2", now + GO_BACK_WITHIN + Duration::from_secs(60)), None, "too long ago");
496        for bad in ["from=\nto=0.60.2\n", "from=0.60.1 x\nto=0.60.2\n", "from=../x\nto=0.60.2\n", "from=0.60.2\nto=0.60.2\n", "to=0.60.2\n"] {
497            std::fs::write(&record, bad).unwrap();
498            assert_eq!(go_back_version(&record, "0.60.2", now), None, "{bad:?}");
499        }
500    }
501
502    #[test]
503    fn going_back_hands_the_helper_no_file_and_restarts_the_old_version() {
504        let (dir, _installer, data, _bin) = layout("AgentMux_0.60.2_amd64.deb");
505        let up = PackageUpgrade::go_back("0.60.1", &data);
506        assert!(up.is_go_back());
507        let args = dir.path().join("args");
508        let pkexec = fake_pkexec(dir.path(), &format!("printf '%s\\n' \"$@\" > {}; echo READY; exit 0", args.display()));
509        let (start, marker) = start_script(dir.path());
510        // A process standing in for the launcher, which exits once the helper says READY.
511        let mut launcher = std::process::Command::new("sleep").arg("60").spawn().unwrap();
512        let pid = launcher.id();
513        assert!(authorize_with(&pkexec, Path::new("/opt/agentmux/bin/agentmux-install-update"), &start, &up, pid, Duration::from_secs(10)));
514        launcher.kill().unwrap();
515        launcher.wait().unwrap();
516        assert!(wait_for(|| marker.exists()), "the old version is started once the launcher is gone");
517        let got = std::fs::read_to_string(&args).unwrap();
518        assert_eq!(got, format!("/opt/agentmux/bin/agentmux-install-update\n--go-back\n0.60.1\n{pid}\n"));
519        assert!(up.manual_command().contains("0.60.1"));
520    }
521
522    #[test]
523    fn a_dismissed_prompt_installs_nothing_and_says_nothing() {
524        let (dir, installer, data, bin) = layout("AgentMux_0.60.2_amd64.deb");
525        let up = check(&installer, SHA, "0.60.2", &bin, &data, &bin).unwrap();
526        let pkexec = fake_pkexec(dir.path(), "exit 126");
527        assert!(!authorize_with(&pkexec, &bin.join(HELPER_NAME), &no_start(dir.path()), &up, 1, Duration::from_secs(10)));
528        assert_eq!(result_error(&up), None, "the user said no: not an error");
529    }
530
531    #[test]
532    fn no_password_prompt_leaves_the_command_to_run_by_hand() {
533        let (dir, installer, data, bin) = layout("AgentMux_0.60.2_amd64.deb");
534        let up = check(&installer, SHA, "0.60.2", &bin, &data, &bin).unwrap();
535        let pkexec = fake_pkexec(dir.path(), "exit 127");
536        assert!(!authorize_with(&pkexec, &bin.join(HELPER_NAME), &no_start(dir.path()), &up, 1, Duration::from_secs(10)));
537        let error = result_error(&up).unwrap();
538        assert!(error.contains(&format!("sudo apt install {}", installer.display())), "{error}");
539        // No pkexec at all says the same.
540        assert!(!authorize_with(&dir.path().join("none"), &bin.join(HELPER_NAME), &no_start(dir.path()), &up, 1, Duration::from_secs(10)));
541        assert!(result_error(&up).unwrap().contains("no pkexec"));
542    }
543
544    #[test]
545    fn a_file_the_helper_refuses_leaves_its_reason_and_nothing_quits() {
546        let (dir, installer, data, bin) = layout("AgentMux_0.60.2_amd64.deb");
547        let up = check(&installer, SHA, "0.60.2", &bin, &data, &bin).unwrap();
548        let pkexec = fake_pkexec(dir.path(), "echo 'agentmux-install-update: the file doesn'\\''t match the checksum GitHub lists for it' >&2; exit 1");
549        assert!(!authorize_with(&pkexec, &bin.join(HELPER_NAME), &no_start(dir.path()), &up, 1, Duration::from_secs(10)));
550        assert_eq!(result_error(&up).as_deref(), Some("the file doesn't match the checksum GitHub lists for it"));
551    }
552
553    #[test]
554    fn a_prompt_left_unanswered_is_closed_when_time_is_up() {
555        let (dir, installer, data, bin) = layout("AgentMux_0.60.2_amd64.deb");
556        let up = check(&installer, SHA, "0.60.2", &bin, &data, &bin).unwrap();
557        let pkexec = fake_pkexec(dir.path(), "exec sleep 30");
558        let started = std::time::Instant::now();
559        assert!(!authorize_with(&pkexec, &bin.join(HELPER_NAME), &no_start(dir.path()), &up, 1, Duration::from_millis(600)));
560        assert!(started.elapsed() < Duration::from_secs(10));
561        assert_eq!(result_error(&up), None);
562    }
563}