Skip to main content

agentmux_launcher/
upgrade_macos.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The macOS side of "Upgrade & restart"
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` ยง4.2, phase
6//! 3c), for `upgrade_restart`: checking the `.dmg` srv downloaded and verified,
7//! asking the user with a native dialog (`osascript`), and the script that
8//! replaces `AgentMux.app` once this launcher has exited.
9//!
10//! The app can't replace itself while it runs (its own launcher is inside
11//! it), so the swap is a small `/bin/sh` script started detached just before
12//! the launcher exits ([`apply_command`]). It works on a private copy of the
13//! `.dmg`, checks it again against the release's SHA-256, mounts it read-only,
14//! checks the new app's code signature (and, when this app passes Gatekeeper,
15//! that the new one does too, from the same team), copies it into a private
16//! folder it creates beside the running one (a folder only this user, root or
17//! `admin` can change, all the way up) and swaps the two, holding a
18//! lock on the app so two launchers (two channels can run one `.app`) never
19//! swap it at once. This version goes to the Trash, so it can still be put
20//! back. Whatever fails, the script opens an AgentMux again: the
21//! new one, or this one, still in place.
22//!
23//! The pure parts (paths, checks, the dialog's answer, the script's
24//! arguments) build and are tested on every platform; only showing the
25//! dialog is macOS-only.
26
27use std::path::{Path, PathBuf};
28
29/// The release file a macOS install upgrades with, as
30/// `.github/workflows/build-macos.yml` names it (srv's `update::install`).
31pub fn dmg_name(version: &str) -> String {
32    format!("AgentMux_{version}_arm64.dmg")
33}
34
35/// The `.app` this launcher (in `AgentMux.app/Contents/MacOS/`) belongs to,
36/// by the bundle layout (`runtime_mode::app_bundle_of`).
37pub fn app_of(path: &Path) -> Option<PathBuf> {
38    agentmux_common::runtime_mode::app_bundle_of(path)
39}
40
41/// Why `app` can't be replaced where it is, or `None` when it can: macOS runs
42/// a quarantined app from a read-only copy (App Translocation), an app opened
43/// straight from its mounted `.dmg` is on a read-only volume, and the folder
44/// that holds it must be one this user can write.
45pub fn not_replaceable(app: &Path) -> Option<String> {
46    if app.to_string_lossy().contains("/AppTranslocation/") {
47        return Some(format!(
48            "macOS runs this AgentMux from a temporary read-only copy (App Translocation); move {} to Applications and open it from there",
49            app.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
50        ));
51    }
52    let Some(parent) = app.parent() else {
53        return Some(format!("{} has no folder", app.display()));
54    };
55    if let Some(who) = agentmux_common::runtime_mode::folder_others_can_change(parent) {
56        return Some(format!("{who}, so AgentMux isn't replaced there; move it to Applications to upgrade it in place"));
57    }
58    if !can_write_in(parent) {
59        return Some(format!(
60            "{} can't be written (a mounted .dmg, or a folder this user can't change); move AgentMux to Applications to upgrade it in place",
61            parent.display()
62        ));
63    }
64    None
65}
66
67/// Whether this user can create and remove entries in `dir`, asked without
68/// writing anything there (`access(2)`, which also says no on a read-only
69/// volume): a probe file at a predictable name could follow a link someone
70/// else planted.
71#[cfg(unix)]
72fn can_write_in(dir: &Path) -> bool {
73    use std::os::unix::ffi::OsStrExt;
74    std::ffi::CString::new(dir.as_os_str().as_bytes())
75        // SAFETY: `c` is a NUL-terminated path; `access` only reads it.
76        .is_ok_and(|c| unsafe { libc::access(c.as_ptr(), libc::W_OK | libc::X_OK) } == 0)
77}
78
79#[cfg(not(unix))]
80fn can_write_in(_dir: &Path) -> bool {
81    true
82}
83
84/// What a confirmed macOS upgrade needs: the verified `.dmg`, its digest, the
85/// app it replaces, the data channel to keep, and where the script logs.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct MacUpgrade {
88    pub dmg: PathBuf,
89    pub sha256: String,
90    pub version: String,
91    pub app: PathBuf,
92    pub channel: String,
93}
94
95impl MacUpgrade {
96    /// `updates/<v>/apply.log` beside the `.dmg`: what the script did.
97    pub fn log(&self) -> PathBuf {
98        self.dmg.with_file_name("apply.log")
99    }
100}
101
102/// Check what srv names for a macOS upgrade to `version`: that version's
103/// `.dmg`, in this version's own `updates/<v>/`, whole by the release's
104/// `sha256`, and an app here that can be replaced. `own_dir` is the
105/// launcher's folder (`AgentMux.app/Contents/MacOS`), `channel_dir` this
106/// channel's data folder, whose name is the channel the new version keeps.
107pub fn check_dmg(
108    dmg: &Path,
109    sha256: &str,
110    version: &str,
111    own_dir: &Path,
112    data_dir: &Path,
113    channel_dir: &Path,
114) -> Result<MacUpgrade, String> {
115    let named_right = dmg.file_name().is_some_and(|n| n == dmg_name(version).as_str());
116    let in_updates = dmg.parent() == Some(data_dir.join("updates").join(version).as_path());
117    if !dmg.is_absolute() || !named_right || !in_updates || !dmg.is_file() {
118        return Err(format!("{} isn't the AgentMux {version} disk image AgentMux downloaded", dmg.display()));
119    }
120    let app = app_of(own_dir).ok_or("this AgentMux isn't running from an .app")?;
121    if let Some(why) = not_replaceable(&app) {
122        return Err(why);
123    }
124    // Before asking: a file changed since srv checked it fails here. The
125    // check that binds is the script's, on its own private copy.
126    if !crate::upgrade_restart::is_sha256_hex(sha256) || crate::upgrade_restart::file_sha256(dmg).as_deref() != Some(sha256) {
127        return Err(format!("{} isn't the AgentMux {version} release; download it again", dmg.display()));
128    }
129    let channel = channel_dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
130    Ok(MacUpgrade { dmg: dmg.to_path_buf(), sha256: sha256.to_string(), version: version.to_string(), app, channel })
131}
132
133/// The dialog's question.
134pub fn question(up: &MacUpgrade, stopping_paragraph: &str) -> String {
135    format!(
136        "Restart AgentMux to upgrade to {v}?\n\n\
137         Every window closes and every agent stops, then AgentMux {v} replaces\n{}\nand opens. \
138         This version goes to the Trash.\n\n\
139         Your tabs come back and agents resume their conversations. macOS may ask again for \
140         permissions it gave this version.{stopping_paragraph}",
141        up.app.display(),
142        v = up.version
143    )
144}
145
146/// The label of the dialog's Yes.
147const YES: &str = "Upgrade & restart";
148
149/// Whether `osascript`'s output for the dialog is an explicit Yes: the button,
150/// and not given up (the dialog closes itself, as No, when its time is up).
151pub fn said_yes(stdout: &str) -> bool {
152    stdout.contains(&format!("button returned:{YES}")) && !stdout.contains("gave up:true")
153}
154
155/// The dialog's open `osascript`, 0 when none.
156#[cfg(target_os = "macos")]
157static DIALOG_PID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
158
159/// Ask with a native dialog, which no page or agent tool in AgentMux can
160/// click. "Not now" is the default button. The text goes to `osascript` as
161/// arguments, never into the script, so nothing in it is parsed. It closes
162/// itself after `upgrade_restart::ANSWER_WITHIN`.
163#[cfg(target_os = "macos")]
164pub fn confirm(title: &str, body: &str) -> bool {
165    use std::sync::atomic::Ordering;
166    let within = crate::upgrade_restart::ANSWER_WITHIN.as_secs();
167    let script = format!(
168        "on run argv\n\
169         display dialog (item 1 of argv) with title (item 2 of argv) buttons {{\"Not now\", \"{YES}\"}} \
170         default button \"Not now\" cancel button \"Not now\" with icon note giving up after {within}\n\
171         end run"
172    );
173    let child = std::process::Command::new("/usr/bin/osascript")
174        .arg("-e")
175        .arg(script)
176        .arg(body)
177        .arg(title)
178        .stdin(std::process::Stdio::null())
179        .stdout(std::process::Stdio::piped())
180        .stderr(std::process::Stdio::null())
181        .spawn();
182    let child = match child {
183        Ok(c) => c,
184        Err(e) => {
185            crate::log(&format!("upgrade: couldn't open osascript to ask: {e}"));
186            return false;
187        }
188    };
189    let pid = child.id();
190    DIALOG_PID.store(pid, Ordering::SeqCst);
191    let answer = child.wait_with_output();
192    let _ = DIALOG_PID.compare_exchange(pid, 0, Ordering::SeqCst, Ordering::SeqCst);
193    answer.is_ok_and(|out| out.status.success() && said_yes(&String::from_utf8_lossy(&out.stdout)))
194}
195
196/// Close the open dialog (as "Not now").
197#[cfg(target_os = "macos")]
198pub fn dismiss() {
199    let pid = DIALOG_PID.swap(0, std::sync::atomic::Ordering::SeqCst);
200    if pid != 0 {
201        // SAFETY: signals the dialog this launcher started and still waits on.
202        unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) };
203    }
204}
205
206/// The swap, run by `/bin/sh` once this launcher (`$1`) has exited. Every
207/// path is an argument, never part of the script, so nothing in one is
208/// parsed. Arguments: launcher pid, `.dmg`, SHA-256, version, the app to
209/// replace, the channel to record beside it (may be empty), the log, the file
210/// to leave when the upgrade failed ([`crate::updating_window::failed_marker`]).
211const APPLY_SCRIPT: &str = r#"
212pid="$1"; dmg="$2"; sha="$3"; ver="$4"; app="$5"; channel="$6"; log="$7"; marker="$8"
213exec >>"$log" 2>&1
214say() { echo "$(/bin/date -u +%Y-%m-%dT%H:%M:%SZ) $*"; }
215work=""; mnt=""; staging=""
216cleanup() {
217  [ -n "$mnt" ] && { /usr/bin/hdiutil detach -quiet "$mnt" || /usr/bin/hdiutil detach -quiet -force "$mnt"; }
218  [ -n "$staging" ] && /bin/rm -rf "$staging"
219  [ -n "$work" ] && /bin/rm -rf "$work"
220  [ -n "$locked" ] && /bin/rm -rf "$lock"
221}
222# The "Updating to <version>" window (updating_window) says the update failed when this file is there. The
223# folder is the window's own: with no window it isn't there and touch fails quietly (an external command, so a
224# failed redirect can't end this shell, as one on a special builtin would).
225mark_failed() { [ -n "$marker" ] && /usr/bin/touch "$marker" 2>/dev/null; return 0; }
226fail() { say "failed: $*; opening the AgentMux that is in place"; mark_failed; cleanup; /usr/bin/open "$app"; exit 1; }
227team_of() { /usr/bin/codesign -dv "$1" 2>&1 | /usr/bin/sed -n 's/^TeamIdentifier=//p'; }
228parent=$(/usr/bin/dirname "$app"); base=$(/usr/bin/basename "$app")
229lock="$parent/.$base.upgrade-lock"; locked=""
230say "upgrade to $ver: waiting for the launcher ($pid) to exit"
231i=0
232while /bin/kill -0 "$pid" 2>/dev/null; do
233  i=$((i+1)); [ "$i" -gt 600 ] && { say "the launcher is still running after 60 s; nothing changed"; mark_failed; /usr/bin/open "$app"; exit 1; }
234  /bin/sleep 0.1
235done
236# One swap of this app at a time: two launchers on different channels can
237# run the same .app. A lock left by a script that is gone is taken over.
238if ! /bin/mkdir "$lock" 2>/dev/null; then
239  other=$(/bin/cat "$lock/pid" 2>/dev/null)
240  if [ -n "$other" ] && /bin/kill -0 "$other" 2>/dev/null; then
241    # That swap opens the app when it is done.
242    say "another upgrade of $app is running ($other); nothing changed"; exit 1
243  fi
244  /bin/rm -rf "$lock"; /bin/mkdir "$lock" 2>/dev/null || { say "couldn't take the upgrade lock; nothing changed"; mark_failed; /usr/bin/open "$app"; exit 1; }
245fi
246locked=1; echo "$$" > "$lock/pid"
247work=$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/agentmux-upgrade.XXXXXX") || fail "no temporary folder"
248/bin/cp "$dmg" "$work/u.dmg" || fail "couldn't copy the disk image"
249got=$(/usr/bin/shasum -a 256 "$work/u.dmg" | /usr/bin/awk '{print $1}')
250[ "$got" = "$sha" ] || fail "the disk image isn't the release (sha256 $got)"
251mnt="$work/mnt"; /bin/mkdir "$mnt" || fail "no mount point"
252/usr/bin/hdiutil attach -quiet -nobrowse -noautoopen -readonly -mountpoint "$mnt" "$work/u.dmg" || { mnt=""; fail "couldn't mount the disk image"; }
253new="$mnt/AgentMux.app"
254[ -d "$new" ] || new=$(/bin/ls -d "$mnt"/*.app 2>/dev/null | /usr/bin/head -n 1)
255[ -n "$new" ] && [ -d "$new" ] || fail "no app in the disk image"
256got_ver=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "$new/Contents/Info.plist" 2>/dev/null)
257[ "$got_ver" = "$ver" ] || fail "the disk image holds version '$got_ver', not $ver"
258/usr/bin/codesign --verify --deep --strict "$new" || fail "the new app's code signature doesn't verify"
259old_team=$(team_of "$app")
260if [ -n "$old_team" ] && [ "$old_team" != "not set" ]; then
261  [ "$(team_of "$new")" = "$old_team" ] || fail "the new app isn't signed by this app's team ($old_team)"
262fi
263if /usr/sbin/spctl -a -t exec "$app" 2>/dev/null; then
264  /usr/sbin/spctl -a -t exec "$new" || fail "Gatekeeper doesn't accept the new app"
265fi
266# A folder of our own beside the app (created new, unpredictable name), so
267# nothing another account placed there is followed or overwritten.
268staging=$(/usr/bin/mktemp -d "$parent/.$base.upgrading.XXXXXX") || fail "couldn't make a folder beside the app"
269/usr/bin/ditto "$new" "$staging/$base" || fail "couldn't copy the new app beside this one"
270/usr/bin/codesign --verify --deep --strict "$staging/$base" || fail "the copied app's code signature doesn't verify"
271/usr/bin/hdiutil detach -quiet "$mnt" || /usr/bin/hdiutil detach -quiet -force "$mnt"; mnt=""
272old_ver=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "$app/Contents/Info.plist" 2>/dev/null)
273trash="$HOME/.Trash/${base%.app} $old_ver $(/bin/date +%Y%m%d-%H%M%S).app"
274/bin/mv "$app" "$trash" || fail "couldn't move this version to the Trash"
275if ! /bin/mv "$staging/$base" "$app"; then
276  /bin/mv "$trash" "$app"
277  fail "couldn't put the new app in place; this version is back"
278fi
279if [ -n "$channel" ]; then
280  # Written to a new file of our own, then renamed over the record: a rename
281  # replaces whatever is at that name and never follows it.
282  record="$parent/.$base.agentmux-channel"
283  tmp=$(/usr/bin/mktemp "$parent/.$base.agentmux-channel.XXXXXX") &&
284    printf '%s\n' "$channel" > "$tmp" && /bin/mv "$tmp" "$record" || { [ -n "$tmp" ] && /bin/rm -f "$tmp"; say "couldn't record the channel beside the app"; }
285fi
286cleanup
287say "replaced $app with $ver; this version is in the Trash as $trash"
288/usr/bin/open "$app" || say "couldn't open the new app"
289"#;
290
291/// The detached `/bin/sh` that swaps the app once launcher `launcher_pid` is
292/// gone. `upgrade_restart::relaunch` adds the environment and process group.
293pub fn apply_command(up: &MacUpgrade, launcher_pid: u32) -> std::process::Command {
294    let mut cmd = std::process::Command::new("/bin/sh");
295    cmd.arg("-c")
296        .arg(APPLY_SCRIPT)
297        .arg("agentmux-upgrade")
298        .arg(launcher_pid.to_string())
299        .arg(&up.dmg)
300        .arg(&up.sha256)
301        .arg(&up.version)
302        .arg(&up.app)
303        .arg(&up.channel)
304        .arg(up.log())
305        .arg(crate::updating_window::failed_marker(&crate::updating_window::dir()));
306    cmd
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    #[test]
314    fn the_app_the_launcher_is_in_is_the_one_replaced() {
315        let srv = Path::new("/Applications/AgentMux.app/Contents/Helpers/AgentMux Server.app/Contents/MacOS/srv");
316        assert_eq!(app_of(srv).as_deref(), Some(Path::new("/Applications/AgentMux.app")));
317        let launcher = Path::new("/Users/u/Apps/AgentMux 2.app/Contents/MacOS");
318        assert_eq!(app_of(launcher).as_deref(), Some(Path::new("/Users/u/Apps/AgentMux 2.app")));
319        // Never a folder around the install that only ends in .app.
320        let archived = Path::new("/Users/u/Old.app/AgentMux.app/Contents/MacOS");
321        assert_eq!(app_of(archived).as_deref(), Some(Path::new("/Users/u/Old.app/AgentMux.app")));
322        assert_eq!(app_of(Path::new("/opt/agentmux/bin")), None);
323    }
324
325    #[test]
326    fn a_translocated_or_unwritable_app_is_not_replaced() {
327        let translocated = Path::new("/private/var/folders/x/T/AppTranslocation/ABC/d/AgentMux.app");
328        assert!(not_replaceable(translocated).unwrap().contains("App Translocation"));
329        // The folder checks are Unix's (the module only runs on macOS).
330        #[cfg(unix)]
331        {
332            let missing = not_replaceable(Path::new("/no/such/folder/AgentMux.app")).unwrap();
333            assert!(missing.contains("can't be read") || missing.contains("can't be written"), "{missing}");
334        }
335        let dir = tempfile::tempdir().unwrap();
336        assert_eq!(not_replaceable(&dir.path().join("AgentMux.app")), None);
337    }
338
339    #[cfg(unix)]
340    #[test]
341    fn an_app_in_a_folder_every_account_can_write_is_not_replaced() {
342        use std::os::unix::fs::PermissionsExt;
343        let dir = tempfile::tempdir().unwrap();
344        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o1777)).unwrap();
345        assert!(not_replaceable(&dir.path().join("AgentMux.app")).unwrap().contains("every account"));
346        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
347        assert_eq!(not_replaceable(&dir.path().join("AgentMux.app")), None);
348    }
349
350    fn layout(root: &Path, version: &str) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
351        let own_dir = root.join("Apps/AgentMux.app/Contents/MacOS");
352        std::fs::create_dir_all(&own_dir).unwrap();
353        let channel_dir = root.join("channels/stable");
354        let data_dir = channel_dir.join("versions/0.59.35");
355        let updates = data_dir.join("updates").join(version);
356        std::fs::create_dir_all(&updates).unwrap();
357        let dmg = updates.join(dmg_name(version));
358        std::fs::write(&dmg, b"dmg").unwrap();
359        (own_dir, data_dir, channel_dir, dmg)
360    }
361
362    #[test]
363    fn only_the_downloaded_release_dmg_is_accepted() {
364        let root = tempfile::tempdir().unwrap();
365        let (own_dir, data_dir, channel_dir, dmg) = layout(root.path(), "0.59.36");
366        let sha = crate::upgrade_restart::file_sha256(&dmg).unwrap();
367        let up = check_dmg(&dmg, &sha, "0.59.36", &own_dir, &data_dir, &channel_dir).unwrap();
368        assert_eq!(up.app, root.path().join("Apps/AgentMux.app"));
369        assert_eq!(up.channel, "stable");
370        assert_eq!(up.log(), dmg.with_file_name("apply.log"));
371
372        // Another version's name, a wrong digest, or a file outside updates/<v>/.
373        assert!(check_dmg(&dmg, &sha, "0.59.37", &own_dir, &data_dir, &channel_dir).is_err());
374        assert!(check_dmg(&dmg, &"0".repeat(64), "0.59.36", &own_dir, &data_dir, &channel_dir).is_err());
375        let elsewhere = root.path().join(dmg_name("0.59.36"));
376        std::fs::write(&elsewhere, b"dmg").unwrap();
377        assert!(check_dmg(&elsewhere, &sha, "0.59.36", &own_dir, &data_dir, &channel_dir).is_err());
378        // Not running from an .app.
379        assert!(check_dmg(&dmg, &sha, "0.59.36", root.path(), &data_dir, &channel_dir).is_err());
380    }
381
382    #[test]
383    fn only_an_explicit_yes_in_time_counts() {
384        assert!(said_yes("button returned:Upgrade & restart, gave up:false\n"));
385        assert!(!said_yes("button returned:, gave up:true\n"));
386        assert!(!said_yes("button returned:Not now, gave up:false\n"));
387        assert!(!said_yes(""));
388    }
389
390    #[test]
391    fn the_script_gets_every_path_as_an_argument() {
392        let up = MacUpgrade {
393            dmg: PathBuf::from("/Users/u/.agentmux/channels/stable/versions/0.59.35/updates/0.59.36/AgentMux_0.59.36_arm64.dmg"),
394            sha256: "a".repeat(64),
395            version: "0.59.36".into(),
396            app: PathBuf::from("/Users/u/My Apps/AgentMux.app"),
397            channel: "stable".into(),
398        };
399        let cmd = apply_command(&up, 4242);
400        let args: Vec<String> = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect();
401        assert_eq!(cmd.get_program(), "/bin/sh");
402        assert_eq!(args[0], "-c");
403        assert!(!args[1].contains("My Apps"), "no path is inside the script");
404        // The record the script writes is the one the next version reads.
405        let record = agentmux_common::runtime_mode::mac_app_channel_file(&up.app);
406        assert_eq!(record, Path::new("/Users/u/My Apps/.AgentMux.app.agentmux-channel"));
407        assert!(args[1].contains(r#"record="$parent/.$base.agentmux-channel""#));
408        assert!(args[1].contains("mkdir \"$lock\""), "the swap holds a lock on the app");
409        // Every way the swap fails leaves the marker the "Updating" window reads, before the old app is opened.
410        assert!(args[1].contains("mark_failed; cleanup; /usr/bin/open"), "fail() marks the failure");
411        assert_eq!(args[1].matches("mark_failed;").count(), 3, "fail(), the launcher that never exited, the lock");
412        assert_eq!(
413            &args[2..],
414            &[
415                "agentmux-upgrade",
416                "4242",
417                &up.dmg.display().to_string(),
418                &up.sha256,
419                "0.59.36",
420                "/Users/u/My Apps/AgentMux.app",
421                "stable",
422                &up.log().display().to_string(),
423                &crate::updating_window::failed_marker(&crate::updating_window::dir()).display().to_string(),
424            ]
425        );
426    }
427
428    /// Run the real script against a disk image that isn't there: it fails at its first step, which must leave the
429    /// marker the "Updating to <version>" window reads, and end with status 1 whether or not the window's folder
430    /// exists (no window: the marker can't be written, which must not end the script early or differently).
431    #[cfg(target_os = "macos")]
432    #[test]
433    fn a_failed_swap_leaves_the_marker_for_the_updating_window() {
434        let root = tempfile::tempdir().unwrap();
435        // A launcher pid that is already gone, so the script goes straight on.
436        let mut gone = std::process::Command::new("/usr/bin/true").spawn().unwrap();
437        let pid = gone.id();
438        gone.wait().unwrap();
439        let apps = root.path().join("Apps");
440        std::fs::create_dir(&apps).unwrap();
441        let run = |marker: &Path| {
442            let log = root.path().join("apply.log");
443            let st = std::process::Command::new("/bin/sh")
444                .arg("-c")
445                .arg(APPLY_SCRIPT)
446                .arg("agentmux-upgrade")
447                .arg(pid.to_string())
448                .arg(root.path().join("missing.dmg"))
449                .arg("0".repeat(64))
450                .arg("0.60.36")
451                // Not an app, so the script's `open` of it opens nothing.
452                .arg(apps.join("NoSuchAgentMux.app"))
453                .arg("stable")
454                .arg(&log)
455                .arg(marker)
456                .env("TMPDIR", root.path())
457                .status()
458                .unwrap();
459            (st.code(), std::fs::read_to_string(&log).unwrap_or_default())
460        };
461        let window_dir = root.path().join("agentmux-updating-1");
462        std::fs::create_dir(&window_dir).unwrap();
463        let marker = crate::updating_window::failed_marker(&window_dir);
464        let (code, log) = run(&marker);
465        assert_eq!(code, Some(1), "{log}");
466        assert!(log.contains("failed: couldn't copy the disk image"), "{log}");
467        assert!(marker.exists(), "the window is told the update failed");
468        // No window folder: the failure is the same, nothing else breaks.
469        let (code, log) = run(&root.path().join("no-such-folder/failed"));
470        assert_eq!(code, Some(1), "{log}");
471        assert!(log.contains("failed: couldn't copy the disk image"), "{log}");
472    }
473
474    #[cfg(unix)]
475    #[test]
476    fn the_script_parses() {
477        let out = std::process::Command::new("/bin/sh").arg("-n").arg("-c").arg(APPLY_SCRIPT).output().unwrap();
478        assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
479    }
480}