1#![cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))]
32
33use std::path::{Path, PathBuf};
34use std::time::Duration;
35
36pub const ARG: &str = "--updating-window";
38
39pub const SLOW_AFTER: Duration = Duration::from_secs(90);
41pub const HARD_CAP: Duration = Duration::from_secs(240);
43pub const QUIET_END: Duration = Duration::from_secs(8);
45pub const FAILED_HOLD: Duration = Duration::from_secs(5);
47
48const STALE_AFTER: Duration = Duration::from_secs(3600);
50
51const DIR_PREFIX: &str = "agentmux-updating-";
53
54pub fn dir() -> PathBuf {
56 std::env::temp_dir().join(format!("{DIR_PREFIX}{}", std::process::id()))
57}
58
59pub fn failed_marker(dir: &Path) -> PathBuf {
62 dir.join("failed")
63}
64
65#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
68pub fn new_splash_marker(dir: &Path) -> PathBuf {
69 dir.join("new-splash")
70}
71
72fn is_hand_off_dir_name(name: &str) -> bool {
74 name.strip_prefix(DIR_PREFIX).is_some_and(|pid| !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit()))
75}
76
77#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
80pub fn signal_new_splash_in(root: &Path) {
81 let Ok(entries) = std::fs::read_dir(root) else { return };
82 for e in entries.flatten() {
83 let is_dir = e.file_type().is_ok_and(|t| t.is_dir());
84 if is_dir && is_hand_off_dir_name(&e.file_name().to_string_lossy()) {
85 let _ = std::fs::OpenOptions::new().write(true).create_new(true).open(new_splash_marker(&e.path()));
86 }
87 }
88}
89
90pub fn remove_stale_in(root: &Path, older_than: Duration) -> usize {
93 let Ok(entries) = std::fs::read_dir(root) else { return 0 };
94 let mut removed = 0;
95 for e in entries.flatten() {
96 let old = is_hand_off_dir_name(&e.file_name().to_string_lossy())
97 && e.file_type().is_ok_and(|t| t.is_dir())
98 && e.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > older_than);
99 if old && std::fs::remove_dir_all(e.path()).is_ok() {
100 removed += 1;
101 }
102 }
103 removed
104}
105
106fn parse_request(args: &[String]) -> Option<Result<(String, u32, PathBuf), ()>> {
109 if args.get(1).map(String::as_str) != Some(ARG) {
110 return None;
111 }
112 let (Some(version), Some(pid), Some(dir)) = (args.get(2), args.get(3).and_then(|p| p.parse::<u32>().ok()), args.get(4)) else {
113 return Some(Err(()));
114 };
115 Some(if valid_version(version) { Ok((version.clone(), pid, PathBuf::from(dir))) } else { Err(()) })
116}
117
118#[cfg_attr(not(windows), allow(dead_code))]
120pub fn event_name() -> &'static str {
121 "Local\\AgentMuxUpdatingWindow"
122}
123
124pub fn valid_version(v: &str) -> bool {
127 !v.is_empty() && v.len() <= 32 && v.starts_with(|c: char| c.is_ascii_digit()) && v.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+'))
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum Phase {
133 Updating,
134 Slow,
135 Failed,
136 Close,
137}
138
139#[derive(Debug, Clone, Copy)]
141pub struct Inputs {
142 pub elapsed: Duration,
144 pub script_ended_for: Option<Duration>,
146 pub new_splash: bool,
148 pub failed: bool,
150}
151
152pub fn phase(i: &Inputs) -> Phase {
154 if i.elapsed >= HARD_CAP {
155 return Phase::Close;
156 }
157 if i.failed {
158 return match i.script_ended_for {
159 Some(after) if after >= FAILED_HOLD => Phase::Close,
160 _ => Phase::Failed,
161 };
162 }
163 if i.new_splash || i.script_ended_for.is_some_and(|after| after >= QUIET_END) {
164 return Phase::Close;
165 }
166 if i.elapsed >= SLOW_AFTER {
167 Phase::Slow
168 } else {
169 Phase::Updating
170 }
171}
172
173pub fn headline(p: Phase) -> &'static str {
175 match p {
176 Phase::Slow => "Still updating...",
177 Phase::Failed => "The update was not installed",
178 _ => "Updating AgentMux...",
179 }
180}
181
182#[cfg_attr(target_os = "macos", allow(dead_code))]
185pub fn footer(version: &str, p: Phase) -> Vec<String> {
186 match p {
187 Phase::Failed => vec![format!("Could not update to v{version}"), "Opening the version you had".into()],
188 Phase::Slow => vec![format!("Updating to v{version}"), "Taking longer than usual".into()],
189 _ => vec![format!("Updating to v{version}"), "AgentMux opens again by itself".into()],
190 }
191}
192
193#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
196pub fn footer_mac(version: &str, p: Phase) -> Vec<String> {
197 match p {
198 Phase::Failed => vec![format!("Update to v{version} failed"), "Opening your old version".into()],
199 Phase::Slow => vec![format!("Updating to v{version}"), "Taking longer than usual".into()],
200 _ => vec![format!("Updating to v{version}"), "Opens again by itself".into()],
201 }
202}
203
204#[cfg(windows)]
205mod win {
206 use super::*;
207 use agentmux_common::win32::NoWindow;
208
209 pub fn signal_new_splash() {
211 use windows_sys::Win32::Foundation::CloseHandle;
212 use windows_sys::Win32::System::Threading::{OpenEventW, SetEvent, EVENT_MODIFY_STATE};
213 let name: Vec<u16> = format!("{}\0", event_name()).encode_utf16().collect();
214 unsafe {
215 let ev = OpenEventW(EVENT_MODIFY_STATE, 0, name.as_ptr());
216 if !ev.is_null() {
217 SetEvent(ev);
218 CloseHandle(ev);
219 }
220 }
221 }
222
223 pub fn start(version: &str, script_pid: u32, dir: &Path) -> std::io::Result<()> {
226 if !valid_version(version) {
227 return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a release version"));
228 }
229 std::fs::create_dir_all(dir)?;
230 let copy = dir.join("agentmux-updating.exe");
231 std::fs::copy(std::env::current_exe()?, ©)?;
232 let mut cmd = std::process::Command::new(©);
233 cmd.arg(ARG).arg(version).arg(script_pid.to_string()).arg(dir).current_dir(dir);
234 crate::upgrade_restart::restart_env(&mut cmd, std::env::vars_os());
236 cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).no_window().spawn()?;
237 crate::log(&format!("upgrade: updating window started for v{version} (hand-off script pid {script_pid}, from {})", copy.display()));
238 Ok(())
239 }
240
241 fn run_if_requested(args: &[String]) -> Option<i32> {
243 match parse_request(args)? {
244 Ok((version, pid, dir)) => {
245 crate::splash::run_updating_window(&version, pid, &dir);
246 Some(0)
247 }
248 Err(()) => Some(2),
249 }
250 }
251
252 pub fn early(args: &[String]) -> Option<i32> {
256 if let Some(code) = run_if_requested(args) {
257 return Some(code);
258 }
259 remove_stale_in(&std::env::temp_dir(), STALE_AFTER);
260 None
261 }
262}
263
264#[cfg(windows)]
265pub use win::{early, signal_new_splash, start};
266
267#[cfg(target_os = "macos")]
268mod mac {
269 use super::*;
270 use std::os::unix::ffi::OsStrExt;
271 use std::os::unix::process::CommandExt;
272
273 pub fn signal_new_splash() {
276 signal_new_splash_in(&std::env::temp_dir());
277 }
278
279 pub(super) fn clone_tree(from: &Path, to: &Path) -> std::io::Result<()> {
284 let c = |p: &Path| std::ffi::CString::new(p.as_os_str().as_bytes()).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e));
285 let (src, dst) = (c(from)?, c(to)?);
286 if unsafe { libc::clonefile(src.as_ptr(), dst.as_ptr(), 1) } == 0 {
289 Ok(())
290 } else {
291 Err(std::io::Error::last_os_error())
292 }
293 }
294
295 pub(super) fn exe_in_clone(exe: &Path, app: &Path, clone: &Path) -> Option<PathBuf> {
297 exe.strip_prefix(app).ok().map(|rel| clone.join(rel))
298 }
299
300 pub fn start(version: &str, script_pid: u32, app: &Path, dir: &Path) -> std::io::Result<()> {
303 let invalid = |m: &str| std::io::Error::new(std::io::ErrorKind::InvalidInput, m.to_string());
304 if !valid_version(version) {
305 return Err(invalid("not a release version"));
306 }
307 let exe = std::env::current_exe()?;
308 let clone = dir.join(app.file_name().ok_or_else(|| invalid("the app has no name"))?);
309 let copy = exe_in_clone(&exe, app, &clone).ok_or_else(|| invalid("this launcher is not in the app"))?;
310 let _ = std::fs::remove_dir_all(dir);
312 std::fs::create_dir_all(dir)?;
313 std::fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?;
314 if let Err(e) = clone_tree(app, &clone) {
315 let _ = std::fs::remove_dir_all(dir);
316 return Err(e);
317 }
318 let mut cmd = std::process::Command::new(©);
319 cmd.arg(ARG).arg(version).arg(script_pid.to_string()).arg(dir).current_dir(dir);
320 crate::upgrade_restart::restart_env(&mut cmd, std::env::vars_os());
322 cmd.process_group(0).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
324 if let Err(e) = cmd.spawn() {
325 let _ = std::fs::remove_dir_all(dir);
326 return Err(e);
327 }
328 crate::log(&format!("upgrade: updating window started for v{version} (swap script pid {script_pid}, from {})", copy.display()));
329 Ok(())
330 }
331
332 fn owns(dir: &Path) -> bool {
335 let named = dir.file_name().is_some_and(|n| is_hand_off_dir_name(&n.to_string_lossy()));
336 let parent = dir.parent().and_then(|p| p.canonicalize().ok());
337 named && parent.is_some() && parent == std::env::temp_dir().canonicalize().ok()
338 }
339
340 pub fn early(args: &[String]) -> Option<i32> {
344 match parse_request(args) {
345 Some(Ok((version, pid, dir))) => {
346 crate::splash_mac::run_updating_window(&version, pid, &dir);
347 if owns(&dir) {
348 let _ = std::fs::remove_dir_all(&dir);
349 }
350 Some(0)
351 }
352 Some(Err(())) => Some(2),
353 None => {
354 remove_stale_in(&std::env::temp_dir(), STALE_AFTER);
355 None
356 }
357 }
358 }
359}
360
361#[cfg(target_os = "macos")]
362pub use mac::{early, signal_new_splash, start};
363
364#[cfg(not(any(windows, target_os = "macos")))]
366pub fn early(_args: &[String]) -> Option<i32> {
367 None
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 const S: fn(u64) -> Duration = Duration::from_secs;
375
376 fn at(elapsed: u64, ended: Option<u64>, new_splash: bool, failed: bool) -> Phase {
377 phase(&Inputs { elapsed: S(elapsed), script_ended_for: ended.map(S), new_splash, failed })
378 }
379
380 #[test]
381 fn it_shows_the_update_until_the_new_splash_is_up() {
382 assert_eq!(at(0, None, false, false), Phase::Updating);
383 assert_eq!(at(30, None, false, false), Phase::Updating);
384 assert_eq!(at(30, None, true, false), Phase::Close);
385 }
386
387 #[test]
388 fn a_long_install_says_it_is_taking_longer_and_never_outlives_the_cap() {
389 assert_eq!(at(89, None, false, false), Phase::Updating);
390 assert_eq!(at(90, None, false, false), Phase::Slow);
391 assert_eq!(at(239, None, false, false), Phase::Slow);
392 assert_eq!(at(240, None, false, false), Phase::Close);
393 assert_eq!(at(240, None, false, true), Phase::Close);
395 assert_eq!(at(400, Some(1), false, true), Phase::Close);
396 }
397
398 #[test]
399 fn it_leaves_quietly_when_the_script_ended_and_no_new_splash_came() {
400 assert_eq!(at(20, Some(0), false, false), Phase::Updating);
401 assert_eq!(at(25, Some(7), false, false), Phase::Updating);
402 assert_eq!(at(26, Some(8), false, false), Phase::Close);
403 assert_eq!(at(21, Some(1), true, false), Phase::Close);
405 }
406
407 #[test]
408 fn a_failed_install_is_said_for_a_few_seconds_even_when_the_version_it_had_is_already_up() {
409 assert_eq!(at(20, Some(0), false, true), Phase::Failed);
410 assert_eq!(at(22, Some(2), true, true), Phase::Failed);
412 assert_eq!(at(25, Some(5), true, true), Phase::Close);
413 assert_eq!(at(25, Some(5), false, true), Phase::Close);
414 }
415
416 #[test]
417 fn the_footer_names_the_version_coming_and_never_the_one_leaving() {
418 assert_eq!(footer("0.60.35", Phase::Updating), vec!["Updating to v0.60.35", "AgentMux opens again by itself"]);
419 assert_eq!(footer("0.60.35", Phase::Slow)[0], "Updating to v0.60.35");
420 assert_eq!(footer("0.60.35", Phase::Failed), vec!["Could not update to v0.60.35", "Opening the version you had"]);
421 for p in [Phase::Updating, Phase::Slow, Phase::Failed] {
422 assert!(headline(p).is_ascii() && footer("0.60.35", p).iter().all(|l| l.is_ascii()), "{p:?}");
423 }
424 }
425
426 #[test]
427 fn the_mac_footer_says_the_same_and_fits_the_card() {
428 for p in [Phase::Updating, Phase::Slow, Phase::Failed] {
429 let lines = footer_mac("0.60.35", p);
430 assert_eq!(lines.len(), 2);
431 assert!(lines.iter().all(|l| l.is_ascii() && l.len() <= 26), "{p:?}: {lines:?}");
432 assert!(lines[0].contains("v0.60.35"), "{p:?}");
433 }
434 assert_eq!(footer_mac("0.60.35", Phase::Updating)[0], footer("0.60.35", Phase::Updating)[0]);
435 assert!(footer_mac("0.60.35", Phase::Failed)[0].contains("failed"));
436 }
437
438 #[test]
439 fn only_a_release_version_is_drawn() {
440 for ok in ["0.60.35", "1.2.3-rc.1", "0.60.35+build5"] {
441 assert!(valid_version(ok), "{ok}");
442 }
443 for bad in ["", "v0.60.35", "0.60.35 DEV", "0.60.35\"", "0.60.35; calc", "..\\x", "1234567890123456789012345678901234567890"] {
444 assert!(!valid_version(bad), "{bad}");
445 }
446 }
447
448 #[test]
449 fn its_folder_and_marker_are_in_the_temp_directory_and_named_for_the_old_launcher() {
450 let d = dir();
451 assert!(d.starts_with(std::env::temp_dir()));
452 assert_eq!(d.file_name().unwrap().to_string_lossy(), format!("agentmux-updating-{}", std::process::id()));
453 assert_eq!(failed_marker(&d), d.join("failed"));
454 }
455
456 #[test]
457 fn the_new_splash_tells_every_window_folder_and_nothing_else() {
458 let root = tempfile::tempdir().unwrap();
459 let a = root.path().join("agentmux-updating-4242");
460 let b = root.path().join("agentmux-updating-77");
461 let not_ours = root.path().join("agentmux-updating-extra");
462 let file = root.path().join("agentmux-updating-9");
463 for d in [&a, &b, ¬_ours] {
464 std::fs::create_dir(d).unwrap();
465 }
466 std::fs::write(&file, b"").unwrap();
467 signal_new_splash_in(root.path());
468 assert!(new_splash_marker(&a).exists() && new_splash_marker(&b).exists());
469 assert!(!new_splash_marker(¬_ours).exists(), "only <prefix><pid> folders");
470 assert!(file.is_file(), "a file of that name is left alone");
471 signal_new_splash_in(root.path());
473 signal_new_splash_in(&root.path().join("missing"));
474 }
475
476 #[cfg(unix)]
477 #[test]
478 fn a_marker_is_never_written_through_a_link() {
479 let root = tempfile::tempdir().unwrap();
480 let dir = root.path().join("agentmux-updating-5");
481 std::fs::create_dir(&dir).unwrap();
482 let target = root.path().join("precious");
483 std::fs::write(&target, b"keep").unwrap();
484 std::os::unix::fs::symlink(&target, new_splash_marker(&dir)).unwrap();
485 signal_new_splash_in(root.path());
486 assert_eq!(std::fs::read(&target).unwrap(), b"keep");
487 }
488
489 #[test]
490 fn old_window_folders_are_removed_and_new_ones_kept() {
491 let root = tempfile::tempdir().unwrap();
492 let hand_off = root.path().join("agentmux-updating-100");
493 let other = root.path().join("something-else");
494 for d in [&hand_off, &other] {
495 std::fs::create_dir(d).unwrap();
496 std::fs::write(d.join("f"), b"x").unwrap();
497 }
498 assert_eq!(remove_stale_in(root.path(), Duration::from_secs(3600)), 0, "a fresh folder stays");
499 assert!(hand_off.exists());
500 std::thread::sleep(Duration::from_millis(30));
501 assert_eq!(remove_stale_in(root.path(), Duration::ZERO), 1);
502 assert!(!hand_off.exists());
503 assert!(other.exists(), "only a hand-off's folder is touched");
504 assert_eq!(remove_stale_in(&root.path().join("missing"), Duration::ZERO), 0);
505 }
506
507 #[test]
508 fn the_window_arguments_are_checked_before_anything_is_drawn() {
509 let a = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
510 assert!(parse_request(&a(&["agentmux"])).is_none());
511 assert!(parse_request(&a(&["agentmux", "--version"])).is_none());
512 let ok = parse_request(&a(&["agentmux", ARG, "0.60.36", "4242", "/tmp/agentmux-updating-1"])).unwrap().unwrap();
513 assert_eq!(ok, ("0.60.36".to_string(), 4242, PathBuf::from("/tmp/agentmux-updating-1")));
514 for bad in [
515 a(&["agentmux", ARG]),
516 a(&["agentmux", ARG, "0.60.36", "4242"]),
517 a(&["agentmux", ARG, "0.60.36", "not-a-pid", "/tmp/x"]),
518 a(&["agentmux", ARG, "0.60.36; rm", "4242", "/tmp/x"]),
519 ] {
520 assert!(parse_request(&bad).unwrap().is_err(), "{bad:?}");
521 }
522 }
523
524 #[test]
525 fn only_a_pid_named_folder_is_a_hand_off_folder() {
526 assert!(is_hand_off_dir_name("agentmux-updating-4242"));
527 for bad in ["agentmux-updating-", "agentmux-updating-x", "agentmux-updating-12a", "agentmux-updating", "other-4242", ""] {
528 assert!(!is_hand_off_dir_name(bad), "{bad}");
529 }
530 }
531
532 #[cfg(target_os = "macos")]
533 #[test]
534 fn the_clones_launcher_is_at_the_same_place_in_the_bundle() {
535 let exe = Path::new("/Applications/AgentMux.app/Contents/MacOS/agentmux-launcher");
536 let clone = Path::new("/var/folders/x/T/agentmux-updating-7/AgentMux.app");
537 assert_eq!(
538 mac::exe_in_clone(exe, Path::new("/Applications/AgentMux.app"), clone),
539 Some(clone.join("Contents/MacOS/agentmux-launcher"))
540 );
541 assert_eq!(mac::exe_in_clone(exe, Path::new("/Users/u/Other.app"), clone), None);
542 }
543
544 #[cfg(target_os = "macos")]
547 #[test]
548 fn the_app_is_cloned_whole_and_never_over_an_existing_folder() {
549 use std::os::unix::fs::PermissionsExt;
550 let root = tempfile::tempdir().unwrap();
551 let app = root.path().join("AgentMux.app");
552 std::fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
553 std::fs::write(app.join("Contents/Info.plist"), b"plist").unwrap();
554 std::fs::write(app.join("Contents/MacOS/agentmux-launcher"), b"exe").unwrap();
555 std::fs::set_permissions(app.join("Contents/MacOS/agentmux-launcher"), std::fs::Permissions::from_mode(0o755)).unwrap();
556 std::os::unix::fs::symlink("Contents/MacOS", app.join("link")).unwrap();
557 let clone = root.path().join("clone/AgentMux.app");
558 std::fs::create_dir(root.path().join("clone")).unwrap();
559 match mac::clone_tree(&app, &clone) {
560 Ok(()) => {}
561 Err(e) if matches!(e.raw_os_error(), Some(libc::ENOTSUP) | Some(libc::EXDEV)) => return,
563 Err(e) => panic!("{e}"),
564 }
565 assert_eq!(std::fs::read(clone.join("Contents/Info.plist")).unwrap(), b"plist");
566 assert_eq!(std::fs::metadata(clone.join("Contents/MacOS/agentmux-launcher")).unwrap().permissions().mode() & 0o777, 0o755);
567 assert_eq!(std::fs::read_link(clone.join("link")).unwrap(), Path::new("Contents/MacOS"));
568 assert!(mac::clone_tree(&app, &clone).is_err(), "an existing folder is never merged into");
569 }
570}