1use 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
38pub const CONFIRMED_FOR: Duration = Duration::from_secs(5 * 60);
41
42static REQUESTS: Mutex<Option<mpsc::UnboundedSender<UpgradeRequest>>> = Mutex::new(None);
43pub const ANSWER_WITHIN: Duration = Duration::from_secs(150);
48
49static LATEST_ASK: AtomicU64 = AtomicU64::new(0);
51static DIALOG_THREAD: AtomicU32 = AtomicU32::new(0);
53
54const DIALOG_TITLE: &str = "Upgrade AgentMux";
55
56pub 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
64pub 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
71fn 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
79pub(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
90fn is_portable(folder: &Path) -> bool {
93 folder.join("runtime").join("agentmux-portable.marker").is_file() && !has_uninstaller(folder)
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum Staged {
99 Launcher(PathBuf),
101 Installer { installer: PathBuf, sha256: String, own_dir: PathBuf, version: String },
109 MacDmg(crate::upgrade_macos::MacUpgrade),
112 #[cfg(target_os = "linux")]
117 Package(crate::upgrade_package::PackageUpgrade),
118}
119
120impl std::fmt::Display for Staged {
121 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
133pub(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
138pub(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
146pub 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 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 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 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 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
226pub 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 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 DialogOutcome::Superseded | DialogOutcome::Confirmed => {}
286 DialogOutcome::No | DialogOutcome::TimedOut | DialogOutcome::TooLate => {
287 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306enum DialogOutcome {
307 Yes,
309 No,
311 TimedOut,
313 TooLate,
315 Superseded,
317 Confirmed,
319}
320
321#[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
336fn 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
346fn 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 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 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
384fn 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
396fn 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#[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#[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#[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#[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
470pub 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
494fn 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 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#[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 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#[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
580pub fn still_confirmed(at: Instant) -> bool {
582 at.elapsed() < CONFIRMED_FOR
583}
584
585fn 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
601fn 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
639fn 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
647fn 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
653const KEPT_ENV: [&str; 4] = ["AGENTMUX_HOME_OVERRIDE", "AGENTMUX_DATA_HOME", "AGENTMUX_CONFIG_HOME", "AGENTMUX_CHANNEL"];
658
659fn 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
672pub(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 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
694pub fn relaunch(staged: &Staged) -> std::io::Result<()> {
702 relaunch_with_env(staged, std::env::vars_os())
703}
704
705fn 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 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 #[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 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 #[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 #[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 #[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 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 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 #[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 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 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 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 #[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 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 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 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 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 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 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 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 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 let restart = script.rfind("Start-Process -FilePath 'C:/Apps/O''Neil").expect(&script);
982 assert!(restart > release && restart > leave, "{script}");
983 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 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 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"), ¬e);
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 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 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 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 assert_eq!(dialog_outcome(true, false, 3, 3, quick), DialogOutcome::Yes);
1072 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 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 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 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}