Skip to main content

agentmux_launcher/
upgrade_restart.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! "Upgrade & restart" (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md`
5//! §4.1, phases 3b, 3c and 3d): restart a Windows portable into the newer
6//! release srv downloaded, verified and unpacked next to it, run the newer
7//! release's installer on a `setup.exe` install, or replace a macOS
8//! `AgentMux.app` from the release's `.dmg` (`upgrade_macos`;
9//! `backend/update/download.rs`).
10//!
11//! srv asks with an `AGENTMUXSRV-UPGRADE` line on its stderr
12//! (`agentmux_common::srv_stderr`); the reader in `srv_spawner` hands it here.
13//! The supervisor then:
14//! 1. checks what srv names again ([`staged`]): an AgentMux portable of
15//!    exactly that version, newer than this one, beside a portable; or that
16//!    version's installer, with the release's digest, in this version's own
17//!    `updates/<v>/`, on a `setup.exe` install;
18//! 2. goes ahead when srv marks the request confirmed (the restart was decided
19//!    in the app: the user's own click or turn, or an approved request's in-app
20//!    countdown with no veto); a request without the mark, from an older srv, is
21//!    asked with a native dialog ([`confirm`]), which no page or agent tool in
22//!    AgentMux can click;
23//! 3. quits the host the way the tray's Quit does, which closes the windows and
24//!    saves the session;
25//! 4. after srv has stopped (so the new version copies complete data,
26//!    `srv/src/migrations/carry_forward.rs`), starts the new launcher, or a
27//!    hidden PowerShell that waits for this launcher to be gone, runs the
28//!    installer silently and starts AgentMux again ([`relaunch`]), and exits.
29
30use std::path::{Path, PathBuf};
31use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
32use std::sync::Mutex;
33use std::time::{Duration, Instant};
34
35use agentmux_common::srv_stderr::{UpgradeRequest, UpgradeTarget};
36use tokio::sync::mpsc;
37
38/// A confirmed restart that hasn't happened within this long (the host
39/// never quit) no longer restarts into the new version on a later quit.
40pub const CONFIRMED_FOR: Duration = Duration::from_secs(5 * 60);
41
42static REQUESTS: Mutex<Option<mpsc::UnboundedSender<UpgradeRequest>>> = Mutex::new(None);
43/// A Yes counts only this long after its dialog opened (the dialog itself
44/// can't time out). Shorter than srv's wait (`RESTART_GRACE`, 3 minutes in
45/// `srv/src/backend/update/restart.rs`), so by the time the panel says the
46/// restart didn't happen, no open dialog can still start one.
47pub const ANSWER_WITHIN: Duration = Duration::from_secs(150);
48
49/// The latest request asked about: only its dialog's Yes counts.
50static LATEST_ASK: AtomicU64 = AtomicU64::new(0);
51/// The thread showing the open dialog, 0 when none (Windows).
52static DIALOG_THREAD: AtomicU32 = AtomicU32::new(0);
53
54const DIALOG_TITLE: &str = "Upgrade AgentMux";
55
56/// The supervisor's end of srv's upgrade requests. One per process: it lasts
57/// across srv respawns, since the reader of each new srv sends here too.
58pub fn requests() -> mpsc::UnboundedReceiver<UpgradeRequest> {
59    let (tx, rx) = mpsc::unbounded_channel();
60    *REQUESTS.lock().unwrap_or_else(|e| e.into_inner()) = Some(tx);
61    rx
62}
63
64/// From the srv stderr reader.
65pub fn forward(req: UpgradeRequest) {
66    if let Some(tx) = REQUESTS.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
67        let _ = tx.send(req);
68    }
69}
70
71/// `major.minor.patch`, or `None`.
72fn version_core(v: &str) -> Option<(u64, u64, u64)> {
73    let core = v.trim().trim_start_matches('v').split(['+', '-']).next()?;
74    let mut parts = core.split('.').map(|p| p.parse::<u64>().ok());
75    let version = (parts.next()??, parts.next()??, parts.next()??);
76    parts.next().is_none().then_some(version)
77}
78
79/// Whether `dir` holds Inno Setup's uninstaller (`unins000.exe`, …): a
80/// `setup.exe` install.
81pub(crate) fn has_uninstaller(dir: &Path) -> bool {
82    std::fs::read_dir(dir).is_ok_and(|entries| {
83        entries.filter_map(|e| e.ok()).any(|e| {
84            let name = e.file_name().to_string_lossy().to_ascii_lowercase();
85            name.starts_with("unins") && name.ends_with(".exe")
86        })
87    })
88}
89
90/// A portable folder. `setup.exe` installs the same `runtime/`, marker and
91/// all, so a folder with Inno Setup's uninstaller isn't one.
92fn is_portable(folder: &Path) -> bool {
93    folder.join("runtime").join("agentmux-portable.marker").is_file() && !has_uninstaller(folder)
94}
95
96/// What a confirmed upgrade restarts into.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum Staged {
99    /// A portable's new folder: start its launcher.
100    Launcher(PathBuf),
101    /// A `setup.exe` install: run this installer, then start `own_dir`
102    /// again. The installer keeps the install's own mode (all users or the
103    /// current one): Inno Setup's default `UsePreviousPrivileges` reads it
104    /// from the previous install, which the folder alone can't tell.
105    /// `sha256` is the release's digest, checked again as it runs. `version`
106    /// is the release, for the "Updating to <version>" window that is on
107    /// screen while the installer runs ([`crate::updating_window`]).
108    Installer { installer: PathBuf, sha256: String, own_dir: PathBuf, version: String },
109    /// A macOS `.app`: replace it from the release's `.dmg` once this
110    /// launcher has exited (`upgrade_macos`).
111    MacDmg(crate::upgrade_macos::MacUpgrade),
112    /// A Linux `.deb` or `.rpm` install: the password was asked for and the
113    /// install helper is waiting for this launcher to quit
114    /// ([`crate::upgrade_package`]). Nothing is started after this exits: the
115    /// helper installs and its waiter starts AgentMux.
116    #[cfg(target_os = "linux")]
117    Package(crate::upgrade_package::PackageUpgrade),
118}
119
120impl std::fmt::Display for Staged {
121    /// The path the user would recognise: the new launcher, or the installer.
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        match self {
124            Staged::Launcher(launcher) => write!(f, "{}", launcher.display()),
125            Staged::Installer { installer, .. } => write!(f, "{}", installer.display()),
126            Staged::MacDmg(up) => write!(f, "{}", up.dmg.display()),
127            #[cfg(target_os = "linux")]
128            Staged::Package(up) => write!(f, "{}", up.installer.display()),
129        }
130    }
131}
132
133/// 64 lowercase hex digits: all that is ever put in the script.
134pub(crate) fn is_sha256_hex(s: &str) -> bool {
135    s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
136}
137
138/// The file's SHA-256 in lowercase hex, or `None` if it can't be read.
139pub(crate) fn file_sha256(path: &Path) -> Option<String> {
140    use sha2::{Digest, Sha256};
141    let mut hasher = Sha256::new();
142    std::io::copy(&mut std::fs::File::open(path).ok()?, &mut hasher).ok()?;
143    Some(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
144}
145
146/// What to restart into, if `req` names a newer release than `own_version`
147/// that fits this install (in `own_dir`, with its data in `data_dir` and its
148/// channel in `channel_dir`): a portable of exactly that version beside a
149/// portable (or, on Linux, where srv unpacked it, `upgrade_linux`), or that version's
150/// installer in this version's own `updates/<v>/` on a `setup.exe` install.
151pub fn staged(req: &UpgradeRequest, own_dir: &Path, data_dir: &Path, channel_dir: &Path, own_version: &str) -> Result<Staged, String> {
152    match (version_core(&req.version), version_core(own_version)) {
153        (Some(new), Some(own)) if new > own => {}
154        _ => return Err(format!("{} isn't newer than {own_version}", req.version)),
155    }
156    match &req.target {
157        // macOS: the release's `.dmg`, which replaces this `.app` (`upgrade_macos`).
158        UpgradeTarget::Installer { installer, sha256 } if cfg!(target_os = "macos") => {
159            crate::upgrade_macos::check_dmg(installer, sha256, &req.version, own_dir, data_dir, channel_dir).map(Staged::MacDmg)
160        }
161        // Linux `.deb`/`.rpm`: the package, installed by its helper (`upgrade_package`).
162        UpgradeTarget::Installer { installer, sha256 } if cfg!(target_os = "linux") => {
163            check_package(installer, sha256, &req.version, own_dir, data_dir)
164        }
165        UpgradeTarget::Launcher(launcher) if cfg!(target_os = "macos") => {
166            Err(format!("{} isn't how a macOS install upgrades (it takes the release's .dmg)", launcher.display()))
167        }
168        // Linux: a portable's `agentmux.sh`, or an AppImage (`upgrade_linux`).
169        UpgradeTarget::Launcher(launcher) if !cfg!(windows) => {
170            let own_appimage = std::env::current_exe()
171                .ok()
172                .and_then(|exe| agentmux_common::runtime_mode::running_appimage(&exe));
173            let own_root = crate::upgrade_linux::portable_root(own_dir);
174            crate::upgrade_linux::check_target(launcher, &req.version, own_root.as_deref(), own_appimage.as_deref(), data_dir, channel_dir)?;
175            Ok(Staged::Launcher(launcher.clone()))
176        }
177        UpgradeTarget::Launcher(launcher) => {
178            let named_right = launcher.file_name().is_some_and(|n| n.eq_ignore_ascii_case("agentmux.exe"));
179            if !launcher.is_absolute() || !named_right || !launcher.is_file() {
180                return Err(format!("{} isn't an AgentMux launcher", launcher.display()));
181            }
182            let folder = launcher.parent().ok_or("the launcher has no folder")?;
183            if !is_portable(own_dir) {
184                return Err("this AgentMux isn't a portable install".into());
185            }
186            if !is_portable(folder) || !folder.join("runtime").join(format!("agentmux-{}.exe", req.version)).is_file() {
187                return Err(format!("{} isn't an AgentMux {} portable", folder.display(), req.version));
188            }
189            if folder == own_dir {
190                return Err("that is the running AgentMux".into());
191            }
192            Ok(Staged::Launcher(launcher.clone()))
193        }
194        UpgradeTarget::Installer { installer, sha256 } => {
195            let name = format!("AgentMux-{}-x64-setup.exe", req.version);
196            let named_right = installer.file_name().is_some_and(|n| n.eq_ignore_ascii_case(name.as_str()));
197            let in_updates = installer.parent() == Some(data_dir.join("updates").join(&req.version).as_path());
198            if !installer.is_absolute() || !named_right || !in_updates || !installer.is_file() {
199                return Err(format!("{} isn't the AgentMux {} installer AgentMux downloaded", installer.display(), req.version));
200            }
201            if !has_uninstaller(own_dir) || !own_dir.join("agentmux.exe").is_file() {
202                return Err("this AgentMux isn't a setup.exe install".into());
203            }
204            // Before asking: a file changed since srv checked it fails here,
205            // with a reason. The check that binds is the script's
206            // ([`installer_script`]), on the file as it runs.
207            if !is_sha256_hex(sha256) || file_sha256(installer).as_deref() != Some(sha256.as_str()) {
208                return Err(format!("{} isn't the AgentMux {} release; download it again", installer.display(), req.version));
209            }
210            Ok(Staged::Installer { installer: installer.clone(), sha256: sha256.clone(), own_dir: own_dir.to_path_buf(), version: req.version.clone() })
211        }
212    }
213}
214
215#[cfg(target_os = "linux")]
216fn check_package(installer: &Path, sha256: &str, version: &str, own_dir: &Path, data_dir: &Path) -> Result<Staged, String> {
217    crate::upgrade_package::check(installer, sha256, version, own_dir, data_dir, Path::new(crate::upgrade_package::INSTALL_BIN))
218        .map(Staged::Package)
219}
220
221#[cfg(not(target_os = "linux"))]
222fn check_package(_: &Path, _: &str, _: &str, _: &Path, _: &Path) -> Result<Staged, String> {
223    Err("this AgentMux doesn't install .deb or .rpm packages".into())
224}
225
226/// Restart as srv asked, on a thread of its own. When the restart is `confirmed` (srv's line says so: the user's
227/// own click or turn, or an approved request whose in-app countdown ran out with no veto) nothing more is asked:
228/// no native dialog, so a computer nobody sits at restarts. The staged file was checked again before this
229/// ([`staged`]), and on a `.deb` or `.rpm` install the OS's own permission prompt still stands: that one is the
230/// system's, not a question of ours. A request that does not say it is confirmed is asked about, and `on_yes`
231/// is called only for an
232/// explicit Yes that still counts ([`answer_counts`]): one given within
233/// [`ANSWER_WITHIN`], to the latest request. One dialog at a time: a newer
234/// request closes the open one, and a dialog closes itself (as No) once its
235/// time is up. A Yes that slips past either is told it expired.
236/// `stopping` lists what agents left running that the restart stops
237/// ([`stopping_note`]); the dialog names it. `host_pid` is the host's process
238/// id: on Windows the dialog sits over the host's window, so it comes up in
239/// front of the person instead of waiting on the taskbar.
240pub fn ask_then(
241    version: String,
242    staged: Staged,
243    stopping: Vec<String>,
244    data_dir: PathBuf,
245    host_pid: Option<u32>,
246    confirmed: bool,
247    on_yes: impl FnOnce(Staged) + Send + 'static,
248) {
249    let ask = LATEST_ASK.fetch_add(1, Ordering::SeqCst) + 1;
250    dismiss(DIALOG_THREAD.load(Ordering::SeqCst));
251    std::thread::spawn(move || {
252        let opened = Instant::now();
253        if confirmed {
254            let ok = confirmed_go(&staged);
255            let outcome = confirmed_outcome(ok, opened.elapsed());
256            crate::log(&outcome.log_line(opened.elapsed()));
257            if outcome == DialogOutcome::Confirmed {
258                on_yes(staged);
259            } else if let Some(why) = outcome.declined() {
260                write_declined(&data_dir, &version, why);
261            }
262            return;
263        }
264        let thread = current_thread();
265        DIALOG_THREAD.store(thread, Ordering::SeqCst);
266        // Set by the timer below just before it closes the dialog: a close by time is told from a No by it.
267        let timed_out = std::sync::Arc::new(AtomicBool::new(false));
268        let timer_closed = timed_out.clone();
269        std::thread::spawn(move || {
270            std::thread::sleep(ANSWER_WITHIN);
271            if DIALOG_THREAD.load(Ordering::SeqCst) == thread {
272                timer_closed.store(true, Ordering::SeqCst);
273                dismiss(thread);
274            }
275        });
276        let yes = confirm(&version, &staged, &stopping, host_pid);
277        let _ = DIALOG_THREAD.compare_exchange(thread, 0, Ordering::SeqCst, Ordering::SeqCst);
278        let latest = LATEST_ASK.load(Ordering::SeqCst);
279        let waited = opened.elapsed();
280        let outcome = dialog_outcome(yes, timed_out.load(Ordering::SeqCst), ask, latest, waited);
281        crate::log(&outcome.log_line(waited));
282        match outcome {
283            DialogOutcome::Yes => on_yes(staged),
284            // A newer request closed this one: that request's own answer is still to come.
285            DialogOutcome::Superseded | DialogOutcome::Confirmed => {}
286            DialogOutcome::No | DialogOutcome::TimedOut | DialogOutcome::TooLate => {
287                // Not when the question was an older one: only the latest is waited for.
288                if ask == latest {
289                    if let Some(why) = outcome.declined() {
290                        write_declined(&data_dir, &version, why);
291                    }
292                }
293                if outcome == DialogOutcome::TooLate {
294                    crate::show_fatal_dialog(
295                        "AgentMux upgrade",
296                        "This upgrade request expired, so AgentMux didn't restart.\n\nStart it again from the version panel.",
297                    );
298                }
299            }
300        }
301    });
302}
303
304/// How the restart question ended.
305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306enum DialogOutcome {
307    /// An explicit Yes that still counts.
308    Yes,
309    /// The user answered No.
310    No,
311    /// Nobody answered: the dialog closed itself after [`ANSWER_WITHIN`], which counts as a No.
312    TimedOut,
313    /// A Yes that came too late, or to an older request: ignored.
314    TooLate,
315    /// A newer request closed this dialog.
316    Superseded,
317    /// srv said the restart is decided, so nothing was asked (and nothing more was needed).
318    Confirmed,
319}
320
321/// Whether to go on with a restart srv says is decided: always, except on a `.deb` or `.rpm` install, where the OS's
322/// own permission prompt for the install is asked here and may be refused or go unanswered.
323#[cfg(target_os = "linux")]
324fn confirmed_go(staged: &Staged) -> bool {
325    match staged {
326        Staged::Package(up) => crate::upgrade_package::authorize(up, std::process::id(), ANSWER_WITHIN),
327        _ => true,
328    }
329}
330
331#[cfg(not(target_os = "linux"))]
332fn confirmed_go(_staged: &Staged) -> bool {
333    true
334}
335
336/// How a decided restart went: on, or (the permission prompt of a package install said no, or was not answered within
337/// [`ANSWER_WITHIN`]) not.
338fn confirmed_outcome(go: bool, waited: Duration) -> DialogOutcome {
339    match (go, waited >= ANSWER_WITHIN) {
340        (true, _) => DialogOutcome::Confirmed,
341        (false, true) => DialogOutcome::TimedOut,
342        (false, false) => DialogOutcome::No,
343    }
344}
345
346/// What became of the question: `yes` is the dialog's answer, `timed_out` that the timer closed it,
347/// `ask` this request's number and `latest` the newest one's, `waited` how long it was open.
348fn dialog_outcome(yes: bool, timed_out: bool, ask: u64, latest: u64, waited: Duration) -> DialogOutcome {
349    match (yes, timed_out) {
350        (true, _) if answer_counts(ask, latest, waited) => DialogOutcome::Yes,
351        (true, _) => DialogOutcome::TooLate,
352        (false, _) if ask != latest => DialogOutcome::Superseded,
353        (false, true) => DialogOutcome::TimedOut,
354        (false, false) => DialogOutcome::No,
355    }
356}
357
358impl DialogOutcome {
359    /// The launcher log's line for it: every outcome says so, with how long the dialog was open.
360    fn log_line(self, waited: Duration) -> String {
361        let s = waited.as_secs();
362        match self {
363            DialogOutcome::Yes => format!("upgrade: the dialog was answered Yes after {s}s"),
364            DialogOutcome::No => format!("upgrade: the dialog was answered No after {s}s"),
365            DialogOutcome::TimedOut => format!("upgrade: nobody answered the dialog within {s}s; it closed itself, which counts as No"),
366            DialogOutcome::TooLate => format!("upgrade: a Yes {s}s after asking, or to an older request, was ignored"),
367            DialogOutcome::Superseded => format!("upgrade: a newer request closed the dialog after {s}s"),
368            DialogOutcome::Confirmed => format!("upgrade: the restart is already confirmed (the user's own click or turn, or an approved request's countdown); no dialog, going on after {s}s"),
369        }
370    }
371
372    /// What srv is told when this ends the question without a restart.
373    fn declined(self) -> Option<agentmux_common::srv_stderr::Declined> {
374        use agentmux_common::srv_stderr::Declined;
375        match self {
376            DialogOutcome::No => Some(Declined::No),
377            DialogOutcome::TimedOut => Some(Declined::TimedOut),
378            DialogOutcome::TooLate => Some(Declined::TooLate),
379            DialogOutcome::Yes | DialogOutcome::Superseded | DialogOutcome::Confirmed => None,
380        }
381    }
382}
383
384/// Tell srv the restart it asked for won't happen, and why
385/// ([`agentmux_common::srv_stderr::UPGRADE_DECLINED_FILE`]): it is waiting on
386/// this launcher and would otherwise say "Restarting" for minutes after a No.
387fn write_declined(data_dir: &Path, version: &str, why: agentmux_common::srv_stderr::Declined) {
388    let dir = data_dir.join("updates");
389    let _ = std::fs::create_dir_all(&dir);
390    let file = dir.join(agentmux_common::srv_stderr::UPGRADE_DECLINED_FILE);
391    if let Err(e) = std::fs::write(&file, agentmux_common::srv_stderr::declined_text(version, why)) {
392        crate::log(&format!("upgrade: couldn't leave {} for srv: {e}", file.display()));
393    }
394}
395
396/// Whether a Yes to request `ask`, given `waited` after its dialog opened,
397/// still counts when `latest` is the newest request.
398fn answer_counts(ask: u64, latest: u64, waited: Duration) -> bool {
399    ask == latest && waited < ANSWER_WITHIN
400}
401
402#[cfg(target_os = "windows")]
403fn current_thread() -> u32 {
404    unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }
405}
406
407/// Off Windows, an id of its own for each dialog, so a superseded dialog's
408/// timer never closes a newer one.
409#[cfg(not(target_os = "windows"))]
410fn current_thread() -> u32 {
411    static NEXT: AtomicU32 = AtomicU32::new(1);
412    NEXT.fetch_add(1, Ordering::SeqCst)
413}
414
415/// Close the dialog shown on `thread` by clicking its No button.
416#[cfg(target_os = "windows")]
417fn dismiss(thread: u32) {
418    use windows_sys::Win32::Foundation::{BOOL, HWND, LPARAM};
419    use windows_sys::Win32::UI::WindowsAndMessaging::{
420        EnumThreadWindows, GetDlgItem, GetWindowTextW, SendMessageW, BM_CLICK, IDNO,
421    };
422    unsafe extern "system" fn click_no(hwnd: HWND, _: LPARAM) -> BOOL {
423        let mut title = [0u16; 64];
424        let len = GetWindowTextW(hwnd, title.as_mut_ptr(), title.len() as i32).max(0) as usize;
425        if String::from_utf16_lossy(&title[..len]) == DIALOG_TITLE {
426            let no = GetDlgItem(hwnd, IDNO);
427            if !no.is_null() {
428                SendMessageW(no, BM_CLICK, 0, 0);
429            }
430            return 0;
431        }
432        1
433    }
434    if thread != 0 {
435        unsafe { EnumThreadWindows(thread, Some(click_no), 0) };
436    }
437}
438
439/// Close the open dialog; the callers check `thread` is its.
440#[cfg(target_os = "linux")]
441fn dismiss(thread: u32) {
442    if thread != 0 {
443        crate::upgrade_linux::dismiss();
444        crate::upgrade_package::dismiss();
445    }
446}
447
448#[cfg(target_os = "macos")]
449fn dismiss(thread: u32) {
450    if thread != 0 {
451        crate::upgrade_macos::dismiss();
452    }
453}
454
455#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
456fn dismiss(_thread: u32) {}
457
458/// The question for a restart into the new version at `from`.
459#[cfg_attr(not(any(target_os = "windows", target_os = "linux", target_os = "macos")), allow(dead_code))]
460fn restart_question(version: &str, from: &Path, stopping: &[String]) -> String {
461    format!(
462        "Restart AgentMux to upgrade to {version}?\n\n\
463         Every window closes and every agent stops, then AgentMux {version} opens \
464         from:\n{}\n\nYour tabs come back and agents resume their conversations.{}",
465        from.display(),
466        stopping_paragraph(stopping)
467    )
468}
469
470/// The list srv leaves beside the staged update (`updates/stopping.txt` in
471/// this version's data folder; srv's `background_work`) of what agents left
472/// running that the restart stops: a dev server, another AgentMux. One
473/// written more than 15 minutes ago is from an earlier attempt and ignored.
474pub fn stopping_note(data_dir: &Path) -> Vec<String> {
475    let path = data_dir.join("updates").join("stopping.txt");
476    let fresh = std::fs::metadata(&path)
477        .and_then(|m| m.modified())
478        .ok()
479        .and_then(|t| t.elapsed().ok())
480        .is_some_and(|age| age < Duration::from_secs(15 * 60));
481    if !fresh {
482        return Vec::new();
483    }
484    std::fs::read_to_string(&path)
485        .unwrap_or_default()
486        .lines()
487        .map(str::trim)
488        .filter(|l| !l.is_empty())
489        .take(8)
490        .map(|l| l.chars().take(160).collect())
491        .collect()
492}
493
494/// The dialog's paragraph naming what the restart stops, or nothing.
495fn stopping_paragraph(stopping: &[String]) -> String {
496    if stopping.is_empty() {
497        return String::new();
498    }
499    let lines: Vec<String> = stopping.iter().map(|l| format!("- {l}")).collect();
500    format!(
501        "\n\nThis also stops what agents left running in the background; each agent is told afterwards:\n{}",
502        lines.join("\n")
503    )
504}
505
506#[cfg(target_os = "windows")]
507fn confirm(version: &str, staged: &Staged, stopping: &[String], host_pid: Option<u32>) -> bool {
508    use std::os::windows::ffi::OsStrExt;
509    use windows_sys::Win32::UI::WindowsAndMessaging::{
510        MessageBoxW, IDYES, MB_DEFBUTTON2, MB_ICONQUESTION, MB_SETFOREGROUND, MB_TOPMOST, MB_YESNO,
511    };
512    let body = match staged {
513        Staged::Launcher(launcher) => restart_question(version, launcher.parent().unwrap_or(launcher), stopping),
514        Staged::Installer { .. } => format!(
515            "Restart AgentMux to upgrade to {version}?\n\n\
516             Every window closes and every agent stops, then the AgentMux {version} installer \
517             runs (Windows may ask for permission, if AgentMux is installed for all users) \
518             and AgentMux opens again.\n\nYour tabs come back and agents resume their conversations.{}",
519            stopping_paragraph(stopping)
520        ),
521        Staged::MacDmg(up) => crate::upgrade_macos::question(up, &stopping_paragraph(stopping)),
522    };
523    let wide = |s: &str| std::ffi::OsStr::new(s).encode_wide().chain(Some(0)).collect::<Vec<u16>>();
524    let (title, body) = (wide(DIALOG_TITLE), wide(&body));
525    // Over the host's window, so it comes up in front (upgrade_window.rs). Nothing a page or an
526    // agent can reach answers it: it is a window of this process, answered by the person.
527    let owner = host_pid.and_then(crate::upgrade_window::host_window);
528    crate::log(&format!("upgrade: asking over {}", owner.map_or("no window".to_string(), |h| format!("host window {h:#x}"))));
529    let answer = unsafe {
530        MessageBoxW(
531            owner.map_or(std::ptr::null_mut(), |h| h as _),
532            body.as_ptr(),
533            title.as_ptr(),
534            MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2 | MB_SETFOREGROUND | MB_TOPMOST,
535        )
536    };
537    answer == IDYES
538}
539
540/// Linux: zenity or kdialog (`upgrade_linux::confirm`). Shows the AppImage,
541/// or the portable's folder. For a `.deb` or `.rpm`, a Yes is followed by the
542/// desktop's password prompt (`upgrade_package::authorize`), and counts only
543/// once the install helper has accepted the file and is waiting for this
544/// launcher to quit.
545#[cfg(target_os = "linux")]
546fn confirm(version: &str, staged: &Staged, stopping: &[String], _host_pid: Option<u32>) -> bool {
547    let asked = Instant::now();
548    let shown = match staged {
549        Staged::Launcher(p) if p.file_name().is_some_and(|n| n == "agentmux.sh") => p.parent().unwrap_or(p),
550        Staged::Launcher(p) | Staged::Installer { installer: p, .. } => p.as_path(),
551        Staged::MacDmg(up) => up.dmg.as_path(),
552        Staged::Package(up) => {
553            let question = crate::upgrade_package::question(up, &stopping_paragraph(stopping));
554            if !crate::upgrade_linux::confirm(DIALOG_TITLE, &question) {
555                return false;
556            }
557            // The answer counts for ANSWER_WITHIN from the question: leave the password prompt the rest.
558            let within = ANSWER_WITHIN.saturating_sub(asked.elapsed() + Duration::from_secs(5));
559            return crate::upgrade_package::authorize(up, std::process::id(), within);
560        }
561    };
562    crate::upgrade_linux::confirm(DIALOG_TITLE, &restart_question(version, shown, stopping))
563}
564
565/// macOS: a native dialog through `osascript` (`upgrade_macos::confirm`).
566#[cfg(target_os = "macos")]
567fn confirm(version: &str, staged: &Staged, stopping: &[String], _host_pid: Option<u32>) -> bool {
568    let body = match staged {
569        Staged::MacDmg(up) => crate::upgrade_macos::question(up, &stopping_paragraph(stopping)),
570        Staged::Launcher(p) | Staged::Installer { installer: p, .. } => restart_question(version, p, stopping),
571    };
572    crate::upgrade_macos::confirm(DIALOG_TITLE, &body)
573}
574
575#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
576fn confirm(_version: &str, _staged: &Staged, _stopping: &[String], _host_pid: Option<u32>) -> bool {
577    false
578}
579
580/// Whether a restart confirmed at `at` still stands.
581pub fn still_confirmed(at: Instant) -> bool {
582    at.elapsed() < CONFIRMED_FOR
583}
584
585/// `path` as a PowerShell single-quoted string: nothing in it is expanded
586/// (no `$`, no `%VAR%`). Every character PowerShell takes as a single quote
587/// is written twice: `'` and the typographic ones (U+2018 to U+201B), which
588/// a user name can hold.
589fn ps_quote(path: &Path) -> String {
590    let mut out = String::from("'");
591    for c in path.display().to_string().chars() {
592        if matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}') {
593            out.push(c);
594        }
595        out.push(c);
596    }
597    out.push('\'');
598    out
599}
600
601/// The hidden PowerShell that upgrades a `setup.exe` install: wait a few
602/// seconds for this launcher to be gone (its files are replaced), run the
603/// installer silently, then start AgentMux again whatever the installer did,
604/// so a failed or declined install leaves the old version running, not none.
605///
606/// The installer sits in the user's own data folder, which any process of
607/// theirs can write, and on an all-users install Windows runs it elevated.
608/// So the script opens it allowing others only to read, which blocks any
609/// write, rename or delete; hashes it through that handle; and runs it only
610/// if it is `sha256`, holding the handle until the installer exits. The file
611/// that runs is the file that was checked.
612///
613/// An install that did not succeed (the installer's exit code was not 0, or it
614/// was not the file that was checked) leaves `failed_marker` before AgentMux
615/// starts again, so the "Updating to <version>" window can say so
616/// ([`crate::updating_window`]). Writing it is best effort and changes nothing else.
617fn installer_script(installer: &Path, sha256: &str, own_dir: &Path, failed_marker: &Path) -> String {
618    debug_assert!(is_sha256_hex(sha256));
619    let installer = ps_quote(installer);
620    format!(
621        "Start-Sleep -Seconds 3; \
622         $ok = $false; \
623         $f = $null; \
624         try {{ \
625         $f = [System.IO.File]::Open({installer}, 'Open', 'Read', 'Read'); \
626         $h = [System.BitConverter]::ToString([System.Security.Cryptography.SHA256]::Create().ComputeHash($f)).Replace('-', ''); \
627         if ($h -eq '{sha256}') {{ \
628         $p = Start-Process -FilePath {installer} -ArgumentList '/VERYSILENT','/SUPPRESSMSGBOXES','/NORESTART','/SP-' -Wait -PassThru; \
629         if ($p.ExitCode -eq 0) {{ $ok = $true }} \
630         }} \
631         }} catch {{ }} finally {{ if ($f) {{ $f.Dispose() }} }}; \
632         if (-not $ok) {{ try {{ New-Item -ItemType File -Force -Path {marker} | Out-Null }} catch {{ }} }}; \
633         Start-Process -FilePath {restart}",
634        marker = ps_quote(failed_marker),
635        restart = ps_quote(&own_dir.join("agentmux.exe")),
636    )
637}
638
639/// `-EncodedCommand`'s form of `script` (base64 of UTF-16LE): the paths in
640/// it reach PowerShell as they are, through no shell's parsing.
641fn encoded_command(script: &str) -> String {
642    use base64::Engine;
643    let utf16: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
644    base64::engine::general_purpose::STANDARD.encode(utf16)
645}
646
647/// Windows PowerShell by its full path, never whatever is first on `PATH`.
648fn powershell_exe() -> PathBuf {
649    let root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
650    PathBuf::from(root).join("System32").join("WindowsPowerShell").join("v1.0").join("powershell.exe")
651}
652
653/// The variables that say WHICH data the launcher uses: the root, the config
654/// folder and the channel. The restart keeps them: an instance a person pointed
655/// at a root of its own (a test, a second profile) must come back on that root,
656/// not on the machine's real channel, which the next version would then migrate.
657const KEPT_ENV: [&str; 4] = ["AGENTMUX_HOME_OVERRIDE", "AGENTMUX_DATA_HOME", "AGENTMUX_CONFIG_HOME", "AGENTMUX_CHANNEL"];
658
659/// The variables of `vars` the restart strips: `AGENTMUX` would make the next
660/// launcher think it was started from a pane, and the other `AGENTMUX_*` this
661/// launcher (or a parent) set (background service, tray) would override the next
662/// one's settings. [`KEPT_ENV`] stays.
663fn env_to_strip(vars: impl IntoIterator<Item = std::ffi::OsString>) -> Vec<std::ffi::OsString> {
664    vars.into_iter()
665        .filter(|key| {
666            let k = key.to_string_lossy();
667            (k == "AGENTMUX" || k.starts_with("AGENTMUX_")) && !KEPT_ENV.contains(&k.as_ref())
668        })
669        .collect()
670}
671
672/// What a process started to bring AgentMux back up gets for an environment:
673/// `vars` (this process's), less what the next version must not inherit
674/// ([`env_to_strip`], [`crate::upgrade_linux::NOT_INHERITED`]), and on Unix
675/// AppImageLauncher off.
676pub(crate) fn restart_env(cmd: &mut std::process::Command, vars: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>) {
677    let inherited: Vec<_> = vars.into_iter().collect();
678    // What the child starts with is this process's environment, less the
679    // stripped; setting the given variables first makes that explicit.
680    cmd.envs(inherited.iter().map(|(k, v)| (k, v)));
681    for key in env_to_strip(inherited.iter().map(|(k, _)| k.clone())) {
682        cmd.env_remove(key);
683    }
684    #[cfg(unix)]
685    {
686        for key in crate::upgrade_linux::NOT_INHERITED {
687            cmd.env_remove(key);
688        }
689        let (key, value) = crate::upgrade_linux::APPIMAGELAUNCHER_OFF;
690        cmd.env(key, value);
691    }
692}
693
694/// Restart into `staged`, detached, without this AgentMux's own environment
695/// except where it keeps its data ([`KEPT_ENV`]).
696///
697/// Not on macOS: its swap script starts the new app with `open`, which gives it
698/// LaunchServices' environment, not the script's, so an isolated instance still
699/// comes back on the machine's real channel there. (Not tried on a Mac; `open
700/// --env` would carry them.)
701pub fn relaunch(staged: &Staged) -> std::io::Result<()> {
702    relaunch_with_env(staged, std::env::vars_os())
703}
704
705/// [`relaunch`] with the environment it was started in given, so a test can say
706/// what the old launcher had without changing this process's.
707fn relaunch_with_env(staged: &Staged, inherited: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>) -> std::io::Result<()> {
708    use agentmux_common::win32::NoWindow;
709    let mut cmd = match staged {
710        Staged::Launcher(launcher) => {
711            let mut c = std::process::Command::new(launcher);
712            if let Some(folder) = launcher.parent() {
713                c.current_dir(folder);
714            }
715            c
716        }
717        // The swap runs after this launcher exits; it opens the new app itself.
718        Staged::MacDmg(up) => crate::upgrade_macos::apply_command(up, std::process::id()),
719        Staged::Installer { installer, sha256, own_dir, .. } => {
720            let marker = crate::updating_window::failed_marker(&crate::updating_window::dir());
721            let mut c = std::process::Command::new(powershell_exe());
722            c.args(["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-EncodedCommand"])
723                .arg(encoded_command(&installer_script(installer, sha256, own_dir, &marker)));
724            c
725        }
726        // Already running: the install helper's waiter, started when the user agreed, starts AgentMux.
727        #[cfg(target_os = "linux")]
728        Staged::Package(_) => return Ok(()),
729    };
730    restart_env(&mut cmd, inherited);
731    #[cfg(unix)]
732    {
733        use std::os::unix::process::CommandExt;
734        // Its own process group: it outlives this launcher, and a signal to
735        // this one's group never reaches it.
736        cmd.process_group(0);
737    }
738    let child = cmd
739        .stdin(std::process::Stdio::null())
740        .stdout(std::process::Stdio::null())
741        .stderr(std::process::Stdio::null())
742        .no_window()
743        .spawn()?;
744    // A `setup.exe` install: nothing of AgentMux is on screen while the script waits for this launcher to be
745    // gone and runs the installer, so a window says which version is coming. The upgrade doesn't depend on it.
746    #[cfg(windows)]
747    if let Staged::Installer { version, .. } = staged {
748        if let Err(e) = crate::updating_window::start(version, child.id(), &crate::updating_window::dir()) {
749            crate::log(&format!("upgrade: no updating window ({e}); the upgrade goes on without it"));
750        }
751    }
752    // A macOS `.dmg` install: the same gap, from this launcher's exit to the swap script opening the new app, with
753    // a window from a clone of this app (the app itself is about to be replaced).
754    #[cfg(target_os = "macos")]
755    if let Staged::MacDmg(up) = staged {
756        if let Err(e) = crate::updating_window::start(&up.version, child.id(), &up.app, &crate::updating_window::dir()) {
757            crate::log(&format!("upgrade: no updating window ({e}); the upgrade goes on without it"));
758        }
759    }
760    #[cfg(not(any(windows, target_os = "macos")))]
761    let _ = child;
762    Ok(())
763}
764
765#[cfg(test)]
766mod tests {
767    use super::*;
768
769    #[cfg_attr(not(windows), allow(dead_code))]
770    fn portable(dir: &Path, version: &str) -> PathBuf {
771        std::fs::create_dir_all(dir.join("runtime")).unwrap();
772        std::fs::write(dir.join("runtime/agentmux-portable.marker"), b"").unwrap();
773        std::fs::write(dir.join(format!("runtime/agentmux-{version}.exe")), b"").unwrap();
774        std::fs::write(dir.join("agentmux.exe"), b"").unwrap();
775        dir.join("agentmux.exe")
776    }
777
778    #[cfg(windows)]
779    fn req(version: &str, launcher: &Path) -> UpgradeRequest {
780        UpgradeRequest { version: version.into(), target: UpgradeTarget::Launcher(launcher.to_path_buf()), confirmed: false }
781    }
782
783    #[test]
784    fn a_restart_keeps_where_the_data_is_and_strips_the_rest() {
785        let os = |s: &str| std::ffi::OsString::from(s);
786        let vars = [
787            "AGENTMUX_HOME_OVERRIDE",
788            "AGENTMUX_DATA_HOME",
789            "AGENTMUX_CONFIG_HOME",
790            "AGENTMUX_CHANNEL",
791            "AGENTMUX",
792            "AGENTMUX_BACKGROUND_SERVICE",
793            "AGENTMUX_TRAY",
794            "AGENTMUX_DATA_DIR",
795            "AGENTMUX_INSTANCE_DIR",
796            "PATH",
797            "AGENTMUXED",
798        ];
799        let stripped: Vec<String> =
800            env_to_strip(vars.iter().map(|v| os(v))).iter().map(|k| k.to_string_lossy().into_owned()).collect();
801        assert_eq!(
802            stripped,
803            ["AGENTMUX", "AGENTMUX_BACKGROUND_SERVICE", "AGENTMUX_TRAY", "AGENTMUX_DATA_DIR", "AGENTMUX_INSTANCE_DIR"],
804        );
805    }
806
807    // An instance run on a root of its own comes back on that root: the next
808    // launcher really receives the root variables and not the stripped ones.
809    #[test]
810    fn an_isolated_launcher_restarts_into_the_same_root() {
811        let dir = tempfile::tempdir().unwrap();
812        let out = dir.path().join("env.txt");
813        let (script, body) = if cfg!(windows) {
814            (
815                dir.path().join("agentmux.cmd"),
816                format!(
817                    "@echo off
818(echo ROOT=%AGENTMUX_HOME_OVERRIDE%& echo DATA=%AGENTMUX_DATA_HOME%& echo PROBE=%AGENTMUX_QTEST_PROBE%) > \"{}\"
819",
820                    out.display()
821                ),
822            )
823        } else {
824            (
825                dir.path().join("agentmux.sh"),
826                format!(
827                    "#!/bin/sh
828echo \"ROOT=$AGENTMUX_HOME_OVERRIDE\" > '{0}'
829echo \"DATA=$AGENTMUX_DATA_HOME\" >> '{0}'
830echo \"PROBE=$AGENTMUX_QTEST_PROBE\" >> '{0}'
831",
832                    out.display()
833                ),
834            )
835        };
836        std::fs::write(&script, body).unwrap();
837        #[cfg(unix)]
838        {
839            use std::os::unix::fs::PermissionsExt;
840            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
841        }
842        // The old launcher had a root of its own, plus a variable the restart
843        // must strip.
844        let os = |s: &str| std::ffi::OsString::from(s);
845        let old = [
846            (os("AGENTMUX_HOME_OVERRIDE"), os("/iso/root")),
847            (os("AGENTMUX_DATA_HOME"), os("/iso/data")),
848            (os("AGENTMUX_QTEST_PROBE"), os("1")),
849        ];
850        relaunch_with_env(&Staged::Launcher(script), old).unwrap();
851        let mut seen = String::new();
852        for _ in 0..100 {
853            seen = std::fs::read_to_string(&out).unwrap_or_default();
854            if seen.lines().count() >= 3 {
855                break;
856            }
857            std::thread::sleep(std::time::Duration::from_millis(100));
858        }
859        assert!(seen.contains("ROOT=/iso/root"), "{seen}");
860        assert!(seen.contains("DATA=/iso/data"), "{seen}");
861        assert!(!seen.contains("PROBE=1"), "{seen}");
862    }
863
864    /// SHA-256 of the empty file, which the tests' installers are.
865    const EMPTY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
866
867    #[cfg_attr(target_os = "macos", allow(dead_code))]
868    fn setup_req(version: &str, installer: &Path) -> UpgradeRequest {
869        let target = UpgradeTarget::Installer { installer: installer.to_path_buf(), sha256: EMPTY_SHA256.into() };
870        UpgradeRequest { version: version.into(), target, confirmed: false }
871    }
872
873    // A Windows portable; Linux's targets are `upgrade_linux`'s tests.
874    #[cfg(windows)]
875    #[test]
876    fn only_a_newer_portable_beside_a_portable_is_restarted_into() {
877        let root = tempfile::tempdir().unwrap();
878        let data = root.path().join("data");
879        let own = root.path().join("agentmux-0.59.26-x64-portable");
880        portable(&own, "0.59.26");
881        let new = portable(&root.path().join("agentmux-0.59.27-x64-portable"), "0.59.27");
882        assert_eq!(staged(&req("0.59.27", &new), &own, &data, &data, "0.59.26").unwrap(), Staged::Launcher(new.clone()));
883
884        // Not newer, or not the version it claims.
885        assert!(staged(&req("0.59.27", &new), &own, &data, &data, "0.59.27").is_err());
886        assert!(staged(&req("0.59.28", &new), &own, &data, &data, "0.59.26").is_err());
887        // Not a launcher, or not absolute.
888        let other = root.path().join("agentmux-0.59.27-x64-portable/runtime/agentmux-0.59.27.exe");
889        assert!(staged(&req("0.59.27", &other), &own, &data, &data, "0.59.26").is_err());
890        assert!(staged(&req("0.59.27", Path::new("agentmux.exe")), &own, &data, &data, "0.59.26").is_err());
891        // This AgentMux isn't a portable, including a setup.exe install,
892        // which has the portable's runtime/ and marker too.
893        let installed = root.path().join("Programs/AgentMux");
894        portable(&installed, "0.59.26");
895        std::fs::write(installed.join("unins000.exe"), b"").unwrap();
896        assert!(staged(&req("0.59.27", &new), &installed, &data, &data, "0.59.26").is_err());
897    }
898
899    // On macOS an installer is the release's .dmg (upgrade_macos's tests), on
900    // Linux the .deb or .rpm (upgrade_package's).
901    #[cfg(windows)]
902    #[test]
903    fn only_that_versions_installer_in_this_versions_updates_runs_on_a_setup_install() {
904        let root = tempfile::tempdir().unwrap();
905        let data = root.path().join("data");
906        let own = root.path().join("Programs/AgentMux");
907        portable(&own, "0.59.26");
908        std::fs::write(own.join("unins000.exe"), b"").unwrap();
909        let updates = data.join("updates/0.59.27");
910        std::fs::create_dir_all(&updates).unwrap();
911        let installer = updates.join("AgentMux-0.59.27-x64-setup.exe");
912        std::fs::write(&installer, b"").unwrap();
913        let Staged::Installer { installer: got, sha256, own_dir, version } =
914            staged(&setup_req("0.59.27", &installer), &own, &data, &data, "0.59.26").unwrap()
915        else {
916            panic!("expected the installer")
917        };
918        assert_eq!((got, sha256.as_str(), own_dir, version.as_str()), (installer.clone(), EMPTY_SHA256, own.clone(), "0.59.27"));
919
920        // Changed since srv checked it, or no proper digest to check against.
921        std::fs::write(&installer, b"not the release").unwrap();
922        let err = staged(&setup_req("0.59.27", &installer), &own, &data, &data, "0.59.26").unwrap_err();
923        assert!(err.contains("download it again"), "{err}");
924        std::fs::write(&installer, b"").unwrap();
925        let mut upper = setup_req("0.59.27", &installer);
926        upper.target = UpgradeTarget::Installer { installer: installer.clone(), sha256: EMPTY_SHA256.to_uppercase() };
927        assert!(staged(&upper, &own, &data, &data, "0.59.26").is_err());
928
929        // Not that version's name, not in this version's updates, or older.
930        let renamed = updates.join("setup.exe");
931        std::fs::write(&renamed, b"").unwrap();
932        assert!(staged(&setup_req("0.59.27", &renamed), &own, &data, &data, "0.59.26").is_err());
933        let elsewhere = root.path().join("AgentMux-0.59.27-x64-setup.exe");
934        std::fs::write(&elsewhere, b"").unwrap();
935        assert!(staged(&setup_req("0.59.27", &elsewhere), &own, &data, &data, "0.59.26").is_err());
936        assert!(staged(&setup_req("0.59.27", &installer), &own, &data, &data, "0.59.27").is_err());
937        // A portable never runs an installer.
938        let portable_dir = root.path().join("agentmux-0.59.26-x64-portable");
939        portable(&portable_dir, "0.59.26");
940        assert!(staged(&setup_req("0.59.27", &installer), &portable_dir, &data, &data, "0.59.26").is_err());
941    }
942
943    #[cfg(target_os = "linux")]
944    #[test]
945    fn a_package_is_only_installed_over_the_package_install() {
946        let root = tempfile::tempdir().unwrap();
947        let data = root.path().join("data");
948        let updates = data.join("updates/0.59.27");
949        std::fs::create_dir_all(&updates).unwrap();
950        let installer = updates.join("AgentMux_0.59.27_amd64.deb");
951        std::fs::write(&installer, b"").unwrap();
952        // This launcher isn't in /opt/agentmux/bin (a portable, an AppImage, a dev build).
953        let err = staged(&setup_req("0.59.27", &installer), root.path(), &data, &data, "0.59.26").unwrap_err();
954        assert!(err.contains("isn't a .deb or .rpm install"), "{err}");
955        // Not newer: refused before anything else.
956        assert!(staged(&setup_req("0.59.27", &installer), root.path(), &data, &data, "0.59.27").is_err());
957    }
958
959    #[test]
960    fn the_installer_script_runs_silently_then_always_starts_agentmux_again() {
961        let path = "C:/Users/A %TEMP% $x/AgentMux-0.59.27-x64-setup.exe";
962        let marker = "C:/Users/A %TEMP%/agentmux-updating-1/failed";
963        let script = installer_script(Path::new(path), EMPTY_SHA256, Path::new("C:/Apps/O'Neil"), Path::new(marker));
964        assert!(script.starts_with("Start-Sleep -Seconds 3; "), "{script}");
965        // The updating window is told when the install did not succeed: only a zero exit code of the checked
966        // installer is a success, and the marker is written after the install and before AgentMux starts again.
967        let ok = script.find("if ($p.ExitCode -eq 0) { $ok = $true }").expect(&script);
968        let leave = script.find(&format!("if (-not $ok) {{ try {{ New-Item -ItemType File -Force -Path '{marker}'")).expect(&script);
969        assert!(script.find("$ok = $false").unwrap() < ok && ok < leave, "{script}");
970        // Opened so nothing else can change it, hashed through that handle,
971        // and run only on a match, before the handle is let go.
972        let open = script.find(&format!("[System.IO.File]::Open('{path}', 'Open', 'Read', 'Read')")).expect(&script);
973        let check = script.find(&format!("if ($h -eq '{EMPTY_SHA256}')")).expect(&script);
974        // Single-quoted: neither %TEMP% nor $x is expanded; a ' is doubled.
975        let run = script
976            .find(&format!("Start-Process -FilePath '{path}' -ArgumentList '/VERYSILENT','/SUPPRESSMSGBOXES','/NORESTART','/SP-' -Wait"))
977            .expect(&script);
978        let release = script.find("$f.Dispose()").expect(&script);
979        assert!(open < check && check < run && run < release, "{script}");
980        // AgentMux starts again whatever happened, last.
981        let restart = script.rfind("Start-Process -FilePath 'C:/Apps/O''Neil").expect(&script);
982        assert!(restart > release && restart > leave, "{script}");
983        // Typographic quotes close a PowerShell string too: doubled as well.
984        assert_eq!(ps_quote(Path::new("C:/Users/O\u{2019}Neil")), "'C:/Users/O\u{2019}\u{2019}Neil'");
985        assert_eq!(ps_quote(Path::new("a\u{2018}b\u{201A}c\u{201B}")), "'a\u{2018}\u{2018}b\u{201A}\u{201A}c\u{201B}\u{201B}'");
986        // The install keeps its own mode (UsePreviousPrivileges).
987        assert!(!script.contains("ALLUSERS") && !script.contains("CURRENTUSER"));
988    }
989
990    #[test]
991    fn the_script_reaches_powershell_as_utf16_base64() {
992        use base64::Engine;
993        let bytes = base64::engine::general_purpose::STANDARD.decode(encoded_command("Start-Process 'é'")).unwrap();
994        let units: Vec<u16> = bytes.chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
995        assert_eq!(String::from_utf16(&units).unwrap(), "Start-Process 'é'");
996    }
997
998    #[test]
999    fn a_late_or_superseded_yes_does_not_count() {
1000        assert!(answer_counts(3, 3, Duration::from_secs(10)));
1001        assert!(!answer_counts(3, 3, ANSWER_WITHIN));
1002        assert!(!answer_counts(2, 3, Duration::from_secs(10)));
1003        // The dialog must stop counting before srv gives up (3 minutes).
1004        assert!(ANSWER_WITHIN < Duration::from_secs(3 * 60));
1005    }
1006
1007    #[test]
1008    fn a_confirmation_lapses() {
1009        assert!(still_confirmed(Instant::now()));
1010        if let Some(long_ago) = Instant::now().checked_sub(CONFIRMED_FOR + Duration::from_secs(1)) {
1011            assert!(!still_confirmed(long_ago));
1012        }
1013    }
1014
1015    #[test]
1016    fn the_dialog_names_what_agents_left_running() {
1017        let dir = tempfile::tempdir().unwrap();
1018        assert!(stopping_note(dir.path()).is_empty(), "no list: nothing to say");
1019        std::fs::create_dir_all(dir.path().join("updates")).unwrap();
1020        std::fs::write(
1021            dir.path().join("updates").join("stopping.txt"),
1022            "Korp: an AgentMux instance (`task dev`), running 9 h
1023
1024Naki-2: `node server.js`
1025",
1026        )
1027        .unwrap();
1028        let note = stopping_note(dir.path());
1029        assert_eq!(note, ["Korp: an AgentMux instance (`task dev`), running 9 h", "Naki-2: `node server.js`"]);
1030        let question = restart_question("0.59.33", Path::new("C:/apps/agentmux-0.59.33"), &note);
1031        assert!(question.contains("also stops what agents left running"), "{question}");
1032        assert!(question.ends_with("- Naki-2: `node server.js`"), "{question}");
1033        assert!(!restart_question("0.59.33", Path::new("C:/x"), &[]).contains("also stops"));
1034    }
1035
1036    #[test]
1037    fn a_confirmed_restart_goes_ahead_with_no_dialog_and_leaves_nothing_for_srv_to_read_as_a_no() {
1038        let data = tempfile::tempdir().unwrap();
1039        let launcher = data.path().join("agentmux-0.60.35").join(if cfg!(windows) { "agentmux.exe" } else { "agentmux.sh" });
1040        let (tx, rx) = std::sync::mpsc::channel();
1041        ask_then("0.60.35".into(), Staged::Launcher(launcher.clone()), Vec::new(), data.path().to_path_buf(), None, true, move |s| {
1042            let _ = tx.send(s);
1043        });
1044        // The answer is Yes without anyone: it arrives at once (a dialog would wait for a person, and none can be shown here).
1045        let staged = rx.recv_timeout(Duration::from_secs(10)).expect("a confirmed restart goes ahead without a dialog");
1046        assert_eq!(staged, Staged::Launcher(launcher));
1047        assert!(!data.path().join("updates").join(agentmux_common::srv_stderr::UPGRADE_DECLINED_FILE).exists(), "no decline was left");
1048        // Only an install's own permission prompt can still refuse a decided restart (Linux .deb/.rpm), and when it does the
1049        // reason is told apart: refused (No) or not answered in time.
1050        assert_eq!(confirmed_outcome(true, Duration::ZERO), DialogOutcome::Confirmed);
1051        assert_eq!(confirmed_outcome(true, ANSWER_WITHIN), DialogOutcome::Confirmed);
1052        assert_eq!(confirmed_outcome(false, Duration::from_secs(3)), DialogOutcome::No);
1053        assert_eq!(confirmed_outcome(false, ANSWER_WITHIN), DialogOutcome::TimedOut);
1054    }
1055
1056    #[test]
1057    fn a_no_is_left_for_srv_under_the_name_it_reads() {
1058        let data = tempfile::tempdir().unwrap();
1059        // The updates folder may not exist yet.
1060        write_declined(data.path(), "0.59.37", agentmux_common::srv_stderr::Declined::TimedOut);
1061        let file = data.path().join("updates").join(agentmux_common::srv_stderr::UPGRADE_DECLINED_FILE);
1062        let text = std::fs::read_to_string(file).unwrap();
1063        assert_eq!(agentmux_common::srv_stderr::parse_declined(&text), ("0.59.37", Some(agentmux_common::srv_stderr::Declined::TimedOut)));
1064    }
1065
1066    #[test]
1067    fn every_way_the_question_can_end_is_told_apart_and_logged() {
1068        use agentmux_common::srv_stderr::Declined;
1069        let quick = Duration::from_secs(2);
1070        // Yes, within the time, to the latest request.
1071        assert_eq!(dialog_outcome(true, false, 3, 3, quick), DialogOutcome::Yes);
1072        // A Yes at or after the time, or to an older request, is ignored.
1073        assert_eq!(dialog_outcome(true, false, 3, 3, ANSWER_WITHIN), DialogOutcome::TooLate);
1074        assert_eq!(dialog_outcome(true, false, 2, 3, quick), DialogOutcome::TooLate);
1075        // No: an answer; a timeout: the timer closed the dialog; both end as a decline, with different reasons.
1076        assert_eq!(dialog_outcome(false, false, 3, 3, quick), DialogOutcome::No);
1077        assert_eq!(dialog_outcome(false, true, 3, 3, ANSWER_WITHIN), DialogOutcome::TimedOut);
1078        // A newer request closed it: neither, and srv is told nothing.
1079        assert_eq!(dialog_outcome(false, false, 2, 3, quick), DialogOutcome::Superseded);
1080        assert_eq!(dialog_outcome(false, true, 2, 3, ANSWER_WITHIN), DialogOutcome::Superseded);
1081        assert_eq!(DialogOutcome::No.declined(), Some(Declined::No));
1082        assert_eq!(DialogOutcome::TimedOut.declined(), Some(Declined::TimedOut));
1083        assert_eq!(DialogOutcome::TooLate.declined(), Some(Declined::TooLate));
1084        assert_eq!((DialogOutcome::Yes.declined(), DialogOutcome::Superseded.declined(), DialogOutcome::Confirmed.declined()), (None, None, None));
1085        // Every outcome has a line, and the line says how long the dialog was open.
1086        let lines: Vec<String> =
1087            [DialogOutcome::Yes, DialogOutcome::No, DialogOutcome::TimedOut, DialogOutcome::TooLate, DialogOutcome::Superseded, DialogOutcome::Confirmed]
1088                .iter()
1089                .map(|o| o.log_line(Duration::from_secs(150)))
1090                .collect();
1091        assert!(lines.iter().all(|l| l.starts_with("upgrade: ") && l.contains("150s")), "{lines:?}");
1092        assert_eq!(lines.iter().collect::<std::collections::HashSet<_>>().len(), 6, "each outcome reads differently");
1093    }
1094}