Skip to main content

agentmux_launcher/
updating_window.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The "Updating to <version>" window of an in-app upgrade that has to stop the running launcher first: a
5//! `setup.exe` install on Windows, a `.dmg` install on macOS.
6//!
7//! The old launcher has to exit so the installer can replace its files, and the installer runs hidden
8//! (`upgrade_restart::installer_script`): from the moment the person confirms the restart until the new
9//! version's own splash appears, nothing of AgentMux is on screen. This window fills that gap. It looks like
10//! the splash (same logo, same card) and its footer says which version is coming.
11//!
12//! It is a copy of this launcher, started from a folder in the temp directory (the install folder's files are
13//! about to be replaced, and a running one cannot be), with `--updating-window <version> <script pid> <folder>`.
14//!
15//! On macOS the copy is of the whole `.app`, made with `clonefile(2)` (instant, and no disk space: the clone shares
16//! the original's blocks). A launcher copied out of its bundle on its own is killed by the kernel on current macOS
17//! (its signature covers the bundle's `Info.plist`, and `AppleSystemPolicy` refuses it); a clone of the bundle keeps
18//! the signature valid and notarized, so Gatekeeper accepts it, and it never carries the quarantine flag. Where the
19//! bundle can't be cloned (a volume without `clonefile`), there is no window and the upgrade goes on without one.
20//! The new launcher's splash tells the window it is up by creating [`new_splash_marker`] in the window's folder, and
21//! the hand-off script (the macOS one) leaves [`failed_marker`] when the swap failed.
22//! It shows nothing but that text and ends by itself, never by waiting on anything that may not come:
23//!
24//! - the new launcher's splash is on screen (it sets the event [`event_name`]): the normal end;
25//! - the hand-off script has ended and the new splash has not come within [`QUIET_END`]: gone quietly;
26//! - the script ended after an install that did not succeed (it leaves [`failed_marker`]): it says so for
27//!   [`FAILED_HOLD`], while the script starts the version the person had, then ends;
28//! - [`SLOW_AFTER`]: the text says it is taking longer; [`HARD_CAP`]: it ends whatever happens.
29//!
30//! The upgrade does not depend on it: if the copy cannot be made or started, the upgrade goes on without it.
31#![cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))]
32
33use std::path::{Path, PathBuf};
34use std::time::Duration;
35
36/// The argument that makes a launcher run only this window.
37pub const ARG: &str = "--updating-window";
38
39/// After this long with no end, the text says the update is taking longer than usual.
40pub const SLOW_AFTER: Duration = Duration::from_secs(90);
41/// The window never lives longer than this.
42pub const HARD_CAP: Duration = Duration::from_secs(240);
43/// How long after the hand-off script ended the window waits for the new splash before it leaves on its own.
44pub const QUIET_END: Duration = Duration::from_secs(8);
45/// How long a failed install's message stays after the script ended.
46pub const FAILED_HOLD: Duration = Duration::from_secs(5);
47
48/// A hand-off folder left this long ago is removed by the next start (the window removes its own on macOS).
49const STALE_AFTER: Duration = Duration::from_secs(3600);
50
51/// The folder (in the temp directory) a hand-off's window runs from: `agentmux-updating-<pid of the old launcher>`.
52const DIR_PREFIX: &str = "agentmux-updating-";
53
54/// The folder this launcher's hand-off window runs from; the script's marker is in it too.
55pub fn dir() -> PathBuf {
56    std::env::temp_dir().join(format!("{DIR_PREFIX}{}", std::process::id()))
57}
58
59/// The file the hand-off script leaves when the install did not succeed (the installer's exit code was not 0, or the
60/// installer was not the one checked): the window then says so.
61pub fn failed_marker(dir: &Path) -> PathBuf {
62    dir.join("failed")
63}
64
65/// The file the new launcher's splash leaves in the window's folder when it is on screen (macOS: the Windows window
66/// uses [`event_name`] instead).
67#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
68pub fn new_splash_marker(dir: &Path) -> PathBuf {
69    dir.join("new-splash")
70}
71
72/// Whether `name` is the folder name of a hand-off's window ([`dir`]).
73fn is_hand_off_dir_name(name: &str) -> bool {
74    name.strip_prefix(DIR_PREFIX).is_some_and(|pid| !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit()))
75}
76
77/// Tell every hand-off window with a folder in `root` that the new launcher's splash is on screen. Nothing happens
78/// when none is up (the usual case: it is one directory listing). A marker is created new, never over a link.
79#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
80pub fn signal_new_splash_in(root: &Path) {
81    let Ok(entries) = std::fs::read_dir(root) else { return };
82    for e in entries.flatten() {
83        let is_dir = e.file_type().is_ok_and(|t| t.is_dir());
84        if is_dir && is_hand_off_dir_name(&e.file_name().to_string_lossy()) {
85            let _ = std::fs::OpenOptions::new().write(true).create_new(true).open(new_splash_marker(&e.path()));
86        }
87    }
88}
89
90/// Remove the folders of hand-offs long over from `root`: those last changed more than `older_than` ago. A running
91/// copy can't delete itself on Windows, so each start tidies the earlier ones. Returns how many it removed.
92pub fn remove_stale_in(root: &Path, older_than: Duration) -> usize {
93    let Ok(entries) = std::fs::read_dir(root) else { return 0 };
94    let mut removed = 0;
95    for e in entries.flatten() {
96        let old = is_hand_off_dir_name(&e.file_name().to_string_lossy())
97            && e.file_type().is_ok_and(|t| t.is_dir())
98            && e.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > older_than);
99        if old && std::fs::remove_dir_all(e.path()).is_ok() {
100            removed += 1;
101        }
102    }
103    removed
104}
105
106/// What `--updating-window` was given: the version to show, the hand-off script's pid, the folder. `None` when the
107/// arguments are not a request for the window; `Some(Err(()))` when they are but are not usable.
108fn parse_request(args: &[String]) -> Option<Result<(String, u32, PathBuf), ()>> {
109    if args.get(1).map(String::as_str) != Some(ARG) {
110        return None;
111    }
112    let (Some(version), Some(pid), Some(dir)) = (args.get(2), args.get(3).and_then(|p| p.parse::<u32>().ok()), args.get(4)) else {
113        return Some(Err(()));
114    };
115    Some(if valid_version(version) { Ok((version.clone(), pid, PathBuf::from(dir))) } else { Err(()) })
116}
117
118/// The name of the event the new launcher's splash sets when it is on screen (the session's own namespace).
119#[cfg_attr(not(windows), allow(dead_code))]
120pub fn event_name() -> &'static str {
121    "Local\\AgentMuxUpdatingWindow"
122}
123
124/// A version the window will show: what a release is called (digits, dots, and a `-`/`+` suffix), and no longer than
125/// that. Anything else is not drawn: this process is started with it as an argument.
126pub fn valid_version(v: &str) -> bool {
127    !v.is_empty() && v.len() <= 32 && v.starts_with(|c: char| c.is_ascii_digit()) && v.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+'))
128}
129
130/// What the window shows.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum Phase {
133    Updating,
134    Slow,
135    Failed,
136    Close,
137}
138
139/// What the window knows each moment.
140#[derive(Debug, Clone, Copy)]
141pub struct Inputs {
142    /// Since the window started.
143    pub elapsed: Duration,
144    /// Since the hand-off script ended, once it has.
145    pub script_ended_for: Option<Duration>,
146    /// The new launcher's splash is on screen.
147    pub new_splash: bool,
148    /// The script ended and left [`failed_marker`].
149    pub failed: bool,
150}
151
152/// What to show now, or that the window is done.
153pub fn phase(i: &Inputs) -> Phase {
154    if i.elapsed >= HARD_CAP {
155        return Phase::Close;
156    }
157    if i.failed {
158        return match i.script_ended_for {
159            Some(after) if after >= FAILED_HOLD => Phase::Close,
160            _ => Phase::Failed,
161        };
162    }
163    if i.new_splash || i.script_ended_for.is_some_and(|after| after >= QUIET_END) {
164        return Phase::Close;
165    }
166    if i.elapsed >= SLOW_AFTER {
167        Phase::Slow
168    } else {
169        Phase::Updating
170    }
171}
172
173/// The line in the splash's stage area. ASCII only: the splash font has no more.
174pub fn headline(p: Phase) -> &'static str {
175    match p {
176        Phase::Slow => "Still updating...",
177        Phase::Failed => "The update was not installed",
178        _ => "Updating AgentMux...",
179    }
180}
181
182/// The footer's two lines, in place of `user@host` and the version: the version shown is the one coming, never the
183/// one that is leaving.
184#[cfg_attr(target_os = "macos", allow(dead_code))]
185pub fn footer(version: &str, p: Phase) -> Vec<String> {
186    match p {
187        Phase::Failed => vec![format!("Could not update to v{version}"), "Opening the version you had".into()],
188        Phase::Slow => vec![format!("Updating to v{version}"), "Taking longer than usual".into()],
189        _ => vec![format!("Updating to v{version}"), "AgentMux opens again by itself".into()],
190    }
191}
192
193/// [`footer`] for the macOS card: its footer is 13 pt fixed-pitch text on a 220 pt card, 26 characters at most, so
194/// the lines are shorter. Same meaning, ASCII only.
195#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
196pub fn footer_mac(version: &str, p: Phase) -> Vec<String> {
197    match p {
198        Phase::Failed => vec![format!("Update to v{version} failed"), "Opening your old version".into()],
199        Phase::Slow => vec![format!("Updating to v{version}"), "Taking longer than usual".into()],
200        _ => vec![format!("Updating to v{version}"), "Opens again by itself".into()],
201    }
202}
203
204#[cfg(windows)]
205mod win {
206    use super::*;
207    use agentmux_common::win32::NoWindow;
208
209    /// Called by the new launcher once its splash is on screen: ends the window, if one is up.
210    pub fn signal_new_splash() {
211        use windows_sys::Win32::Foundation::CloseHandle;
212        use windows_sys::Win32::System::Threading::{OpenEventW, SetEvent, EVENT_MODIFY_STATE};
213        let name: Vec<u16> = format!("{}\0", event_name()).encode_utf16().collect();
214        unsafe {
215            let ev = OpenEventW(EVENT_MODIFY_STATE, 0, name.as_ptr());
216            if !ev.is_null() {
217                SetEvent(ev);
218                CloseHandle(ev);
219            }
220        }
221    }
222
223    /// Copy this launcher into `dir` and start the window from the copy. `script_pid` is the hand-off script, whose
224    /// end the window watches. Not needed by the upgrade: an error only means no window.
225    pub fn start(version: &str, script_pid: u32, dir: &Path) -> std::io::Result<()> {
226        if !valid_version(version) {
227            return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a release version"));
228        }
229        std::fs::create_dir_all(dir)?;
230        let copy = dir.join("agentmux-updating.exe");
231        std::fs::copy(std::env::current_exe()?, &copy)?;
232        let mut cmd = std::process::Command::new(&copy);
233        cmd.arg(ARG).arg(version).arg(script_pid.to_string()).arg(dir).current_dir(dir);
234        // Like the script: what the next version must not inherit of this one's AgentMux environment stays out.
235        crate::upgrade_restart::restart_env(&mut cmd, std::env::vars_os());
236        cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).no_window().spawn()?;
237        crate::log(&format!("upgrade: updating window started for v{version} (hand-off script pid {script_pid}, from {})", copy.display()));
238        Ok(())
239    }
240
241    /// This launcher is the window's copy: `Some(exit code)` when it was.
242    fn run_if_requested(args: &[String]) -> Option<i32> {
243        match parse_request(args)? {
244            Ok((version, pid, dir)) => {
245                crate::splash::run_updating_window(&version, pid, &dir);
246                Some(0)
247            }
248            Err(()) => Some(2),
249        }
250    }
251
252    /// `main`'s first look at the arguments: `Some(exit code)` when this launcher is the window's copy, which shows
253    /// the window and nothing else; otherwise the folders of earlier upgrades' windows are tidied (a running copy
254    /// can't delete its own folder) and the start goes on.
255    pub fn early(args: &[String]) -> Option<i32> {
256        if let Some(code) = run_if_requested(args) {
257            return Some(code);
258        }
259        remove_stale_in(&std::env::temp_dir(), STALE_AFTER);
260        None
261    }
262}
263
264#[cfg(windows)]
265pub use win::{early, signal_new_splash, start};
266
267#[cfg(target_os = "macos")]
268mod mac {
269    use super::*;
270    use std::os::unix::ffi::OsStrExt;
271    use std::os::unix::process::CommandExt;
272
273    /// Called by the new launcher once its splash (or, with the splash off, its menu-bar item) is up: ends the
274    /// window, if one is up.
275    pub fn signal_new_splash() {
276        signal_new_splash_in(&std::env::temp_dir());
277    }
278
279    /// `to` as a clone of the directory tree `from`: `clonefile(2)`, which shares the blocks (nothing is read or
280    /// written, so it takes well under a second for the whole app and uses no disk) and keeps every link and
281    /// attribute as it is, so the bundle's signature still verifies. It fails, and changes nothing, where the two
282    /// are not on one volume that can clone.
283    pub(super) fn clone_tree(from: &Path, to: &Path) -> std::io::Result<()> {
284        let c = |p: &Path| std::ffi::CString::new(p.as_os_str().as_bytes()).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e));
285        let (src, dst) = (c(from)?, c(to)?);
286        // CLONE_NOFOLLOW (1): a link at `from` itself is not followed.
287        // SAFETY: both are NUL-terminated paths that outlive the call; `clonefile` only reads them.
288        if unsafe { libc::clonefile(src.as_ptr(), dst.as_ptr(), 1) } == 0 {
289            Ok(())
290        } else {
291            Err(std::io::Error::last_os_error())
292        }
293    }
294
295    /// Where this launcher's copy lives inside a clone of `app` made at `clone`: the same path under it.
296    pub(super) fn exe_in_clone(exe: &Path, app: &Path, clone: &Path) -> Option<PathBuf> {
297        exe.strip_prefix(app).ok().map(|rel| clone.join(rel))
298    }
299
300    /// Clone the `.app` this launcher is in to `dir` and start the window from the clone. `script_pid` is the swap
301    /// script, whose end the window watches. Not needed by the upgrade: an error only means no window.
302    pub fn start(version: &str, script_pid: u32, app: &Path, dir: &Path) -> std::io::Result<()> {
303        let invalid = |m: &str| std::io::Error::new(std::io::ErrorKind::InvalidInput, m.to_string());
304        if !valid_version(version) {
305            return Err(invalid("not a release version"));
306        }
307        let exe = std::env::current_exe()?;
308        let clone = dir.join(app.file_name().ok_or_else(|| invalid("the app has no name"))?);
309        let copy = exe_in_clone(&exe, app, &clone).ok_or_else(|| invalid("this launcher is not in the app"))?;
310        // Only this user: the folder holds the failed marker the swap script writes.
311        let _ = std::fs::remove_dir_all(dir);
312        std::fs::create_dir_all(dir)?;
313        std::fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?;
314        if let Err(e) = clone_tree(app, &clone) {
315            let _ = std::fs::remove_dir_all(dir);
316            return Err(e);
317        }
318        let mut cmd = std::process::Command::new(&copy);
319        cmd.arg(ARG).arg(version).arg(script_pid.to_string()).arg(dir).current_dir(dir);
320        // Like the script: what the next version must not inherit of this one's AgentMux environment stays out.
321        crate::upgrade_restart::restart_env(&mut cmd, std::env::vars_os());
322        // Its own process group, like the script: it outlives this launcher.
323        cmd.process_group(0).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
324        if let Err(e) = cmd.spawn() {
325            let _ = std::fs::remove_dir_all(dir);
326            return Err(e);
327        }
328        crate::log(&format!("upgrade: updating window started for v{version} (swap script pid {script_pid}, from {})", copy.display()));
329        Ok(())
330    }
331
332    /// `dir` is a hand-off window's folder in this user's temp directory, and so safe for the window to delete when
333    /// it is done (it is given as an argument, so it is checked, not trusted).
334    fn owns(dir: &Path) -> bool {
335        let named = dir.file_name().is_some_and(|n| is_hand_off_dir_name(&n.to_string_lossy()));
336        let parent = dir.parent().and_then(|p| p.canonicalize().ok());
337        named && parent.is_some() && parent == std::env::temp_dir().canonicalize().ok()
338    }
339
340    /// `main`'s first look at the arguments: `Some(exit code)` when this launcher is the window's clone, which shows
341    /// the window, removes its folder (the clone, the markers) and nothing else; otherwise the folders of earlier
342    /// upgrades' windows are tidied and the start goes on.
343    pub fn early(args: &[String]) -> Option<i32> {
344        match parse_request(args) {
345            Some(Ok((version, pid, dir))) => {
346                crate::splash_mac::run_updating_window(&version, pid, &dir);
347                if owns(&dir) {
348                    let _ = std::fs::remove_dir_all(&dir);
349                }
350                Some(0)
351            }
352            Some(Err(())) => Some(2),
353            None => {
354                remove_stale_in(&std::env::temp_dir(), STALE_AFTER);
355                None
356            }
357        }
358    }
359}
360
361#[cfg(target_os = "macos")]
362pub use mac::{early, signal_new_splash, start};
363
364/// Nothing to do on Linux.
365#[cfg(not(any(windows, target_os = "macos")))]
366pub fn early(_args: &[String]) -> Option<i32> {
367    None
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    const S: fn(u64) -> Duration = Duration::from_secs;
375
376    fn at(elapsed: u64, ended: Option<u64>, new_splash: bool, failed: bool) -> Phase {
377        phase(&Inputs { elapsed: S(elapsed), script_ended_for: ended.map(S), new_splash, failed })
378    }
379
380    #[test]
381    fn it_shows_the_update_until_the_new_splash_is_up() {
382        assert_eq!(at(0, None, false, false), Phase::Updating);
383        assert_eq!(at(30, None, false, false), Phase::Updating);
384        assert_eq!(at(30, None, true, false), Phase::Close);
385    }
386
387    #[test]
388    fn a_long_install_says_it_is_taking_longer_and_never_outlives_the_cap() {
389        assert_eq!(at(89, None, false, false), Phase::Updating);
390        assert_eq!(at(90, None, false, false), Phase::Slow);
391        assert_eq!(at(239, None, false, false), Phase::Slow);
392        assert_eq!(at(240, None, false, false), Phase::Close);
393        // The cap holds against everything else.
394        assert_eq!(at(240, None, false, true), Phase::Close);
395        assert_eq!(at(400, Some(1), false, true), Phase::Close);
396    }
397
398    #[test]
399    fn it_leaves_quietly_when_the_script_ended_and_no_new_splash_came() {
400        assert_eq!(at(20, Some(0), false, false), Phase::Updating);
401        assert_eq!(at(25, Some(7), false, false), Phase::Updating);
402        assert_eq!(at(26, Some(8), false, false), Phase::Close);
403        // A splash that came after the script ended closes it at once.
404        assert_eq!(at(21, Some(1), true, false), Phase::Close);
405    }
406
407    #[test]
408    fn a_failed_install_is_said_for_a_few_seconds_even_when_the_version_it_had_is_already_up() {
409        assert_eq!(at(20, Some(0), false, true), Phase::Failed);
410        // The old version's own splash is up (it sets the event too): the message stays its time.
411        assert_eq!(at(22, Some(2), true, true), Phase::Failed);
412        assert_eq!(at(25, Some(5), true, true), Phase::Close);
413        assert_eq!(at(25, Some(5), false, true), Phase::Close);
414    }
415
416    #[test]
417    fn the_footer_names_the_version_coming_and_never_the_one_leaving() {
418        assert_eq!(footer("0.60.35", Phase::Updating), vec!["Updating to v0.60.35", "AgentMux opens again by itself"]);
419        assert_eq!(footer("0.60.35", Phase::Slow)[0], "Updating to v0.60.35");
420        assert_eq!(footer("0.60.35", Phase::Failed), vec!["Could not update to v0.60.35", "Opening the version you had"]);
421        for p in [Phase::Updating, Phase::Slow, Phase::Failed] {
422            assert!(headline(p).is_ascii() && footer("0.60.35", p).iter().all(|l| l.is_ascii()), "{p:?}");
423        }
424    }
425
426    #[test]
427    fn the_mac_footer_says_the_same_and_fits_the_card() {
428        for p in [Phase::Updating, Phase::Slow, Phase::Failed] {
429            let lines = footer_mac("0.60.35", p);
430            assert_eq!(lines.len(), 2);
431            assert!(lines.iter().all(|l| l.is_ascii() && l.len() <= 26), "{p:?}: {lines:?}");
432            assert!(lines[0].contains("v0.60.35"), "{p:?}");
433        }
434        assert_eq!(footer_mac("0.60.35", Phase::Updating)[0], footer("0.60.35", Phase::Updating)[0]);
435        assert!(footer_mac("0.60.35", Phase::Failed)[0].contains("failed"));
436    }
437
438    #[test]
439    fn only_a_release_version_is_drawn() {
440        for ok in ["0.60.35", "1.2.3-rc.1", "0.60.35+build5"] {
441            assert!(valid_version(ok), "{ok}");
442        }
443        for bad in ["", "v0.60.35", "0.60.35 DEV", "0.60.35\"", "0.60.35; calc", "..\\x", "1234567890123456789012345678901234567890"] {
444            assert!(!valid_version(bad), "{bad}");
445        }
446    }
447
448    #[test]
449    fn its_folder_and_marker_are_in_the_temp_directory_and_named_for_the_old_launcher() {
450        let d = dir();
451        assert!(d.starts_with(std::env::temp_dir()));
452        assert_eq!(d.file_name().unwrap().to_string_lossy(), format!("agentmux-updating-{}", std::process::id()));
453        assert_eq!(failed_marker(&d), d.join("failed"));
454    }
455
456    #[test]
457    fn the_new_splash_tells_every_window_folder_and_nothing_else() {
458        let root = tempfile::tempdir().unwrap();
459        let a = root.path().join("agentmux-updating-4242");
460        let b = root.path().join("agentmux-updating-77");
461        let not_ours = root.path().join("agentmux-updating-extra");
462        let file = root.path().join("agentmux-updating-9");
463        for d in [&a, &b, &not_ours] {
464            std::fs::create_dir(d).unwrap();
465        }
466        std::fs::write(&file, b"").unwrap();
467        signal_new_splash_in(root.path());
468        assert!(new_splash_marker(&a).exists() && new_splash_marker(&b).exists());
469        assert!(!new_splash_marker(&not_ours).exists(), "only <prefix><pid> folders");
470        assert!(file.is_file(), "a file of that name is left alone");
471        // Again, and with no window up: nothing breaks.
472        signal_new_splash_in(root.path());
473        signal_new_splash_in(&root.path().join("missing"));
474    }
475
476    #[cfg(unix)]
477    #[test]
478    fn a_marker_is_never_written_through_a_link() {
479        let root = tempfile::tempdir().unwrap();
480        let dir = root.path().join("agentmux-updating-5");
481        std::fs::create_dir(&dir).unwrap();
482        let target = root.path().join("precious");
483        std::fs::write(&target, b"keep").unwrap();
484        std::os::unix::fs::symlink(&target, new_splash_marker(&dir)).unwrap();
485        signal_new_splash_in(root.path());
486        assert_eq!(std::fs::read(&target).unwrap(), b"keep");
487    }
488
489    #[test]
490    fn old_window_folders_are_removed_and_new_ones_kept() {
491        let root = tempfile::tempdir().unwrap();
492        let hand_off = root.path().join("agentmux-updating-100");
493        let other = root.path().join("something-else");
494        for d in [&hand_off, &other] {
495            std::fs::create_dir(d).unwrap();
496            std::fs::write(d.join("f"), b"x").unwrap();
497        }
498        assert_eq!(remove_stale_in(root.path(), Duration::from_secs(3600)), 0, "a fresh folder stays");
499        assert!(hand_off.exists());
500        std::thread::sleep(Duration::from_millis(30));
501        assert_eq!(remove_stale_in(root.path(), Duration::ZERO), 1);
502        assert!(!hand_off.exists());
503        assert!(other.exists(), "only a hand-off's folder is touched");
504        assert_eq!(remove_stale_in(&root.path().join("missing"), Duration::ZERO), 0);
505    }
506
507    #[test]
508    fn the_window_arguments_are_checked_before_anything_is_drawn() {
509        let a = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
510        assert!(parse_request(&a(&["agentmux"])).is_none());
511        assert!(parse_request(&a(&["agentmux", "--version"])).is_none());
512        let ok = parse_request(&a(&["agentmux", ARG, "0.60.36", "4242", "/tmp/agentmux-updating-1"])).unwrap().unwrap();
513        assert_eq!(ok, ("0.60.36".to_string(), 4242, PathBuf::from("/tmp/agentmux-updating-1")));
514        for bad in [
515            a(&["agentmux", ARG]),
516            a(&["agentmux", ARG, "0.60.36", "4242"]),
517            a(&["agentmux", ARG, "0.60.36", "not-a-pid", "/tmp/x"]),
518            a(&["agentmux", ARG, "0.60.36; rm", "4242", "/tmp/x"]),
519        ] {
520            assert!(parse_request(&bad).unwrap().is_err(), "{bad:?}");
521        }
522    }
523
524    #[test]
525    fn only_a_pid_named_folder_is_a_hand_off_folder() {
526        assert!(is_hand_off_dir_name("agentmux-updating-4242"));
527        for bad in ["agentmux-updating-", "agentmux-updating-x", "agentmux-updating-12a", "agentmux-updating", "other-4242", ""] {
528            assert!(!is_hand_off_dir_name(bad), "{bad}");
529        }
530    }
531
532    #[cfg(target_os = "macos")]
533    #[test]
534    fn the_clones_launcher_is_at_the_same_place_in_the_bundle() {
535        let exe = Path::new("/Applications/AgentMux.app/Contents/MacOS/agentmux-launcher");
536        let clone = Path::new("/var/folders/x/T/agentmux-updating-7/AgentMux.app");
537        assert_eq!(
538            mac::exe_in_clone(exe, Path::new("/Applications/AgentMux.app"), clone),
539            Some(clone.join("Contents/MacOS/agentmux-launcher"))
540        );
541        assert_eq!(mac::exe_in_clone(exe, Path::new("/Users/u/Other.app"), clone), None);
542    }
543
544    /// The clone the window runs from is a whole bundle made without copying a byte: files, links and modes as they
545    /// were, and a second one refused rather than merged over the first.
546    #[cfg(target_os = "macos")]
547    #[test]
548    fn the_app_is_cloned_whole_and_never_over_an_existing_folder() {
549        use std::os::unix::fs::PermissionsExt;
550        let root = tempfile::tempdir().unwrap();
551        let app = root.path().join("AgentMux.app");
552        std::fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
553        std::fs::write(app.join("Contents/Info.plist"), b"plist").unwrap();
554        std::fs::write(app.join("Contents/MacOS/agentmux-launcher"), b"exe").unwrap();
555        std::fs::set_permissions(app.join("Contents/MacOS/agentmux-launcher"), std::fs::Permissions::from_mode(0o755)).unwrap();
556        std::os::unix::fs::symlink("Contents/MacOS", app.join("link")).unwrap();
557        let clone = root.path().join("clone/AgentMux.app");
558        std::fs::create_dir(root.path().join("clone")).unwrap();
559        match mac::clone_tree(&app, &clone) {
560            Ok(()) => {}
561            // A volume that can't clone: the real start then makes no window, which is the designed fallback.
562            Err(e) if matches!(e.raw_os_error(), Some(libc::ENOTSUP) | Some(libc::EXDEV)) => return,
563            Err(e) => panic!("{e}"),
564        }
565        assert_eq!(std::fs::read(clone.join("Contents/Info.plist")).unwrap(), b"plist");
566        assert_eq!(std::fs::metadata(clone.join("Contents/MacOS/agentmux-launcher")).unwrap().permissions().mode() & 0o777, 0o755);
567        assert_eq!(std::fs::read_link(clone.join("link")).unwrap(), Path::new("Contents/MacOS"));
568        assert!(mac::clone_tree(&app, &clone).is_err(), "an existing folder is never merged into");
569    }
570}