1use std::path::{Path, PathBuf};
35use std::sync::Mutex;
36use std::time::Duration;
37
38use agentmux_common::srv_stderr::{UpgradeTarget, INSTALL_RESULT_FILE, UPGRADE_DECLINED_FILE};
39
40use crate::backend::blockcontroller::{BlockControllerRuntimeStatus, STATUS_DONE};
41use crate::backend::update::check::{self, AppUpdateStatus, DownloadStatus, WaitingOn};
42
43const POLL: Duration = Duration::from_secs(2);
44const RESTART_GRACE: Duration = Duration::from_secs(3 * 60);
48
49static RUN: Mutex<u64> = Mutex::new(0);
52
53fn run_lock() -> std::sync::MutexGuard<'static, u64> {
54 RUN.lock().unwrap_or_else(|e| e.into_inner())
55}
56
57fn if_current(run: u64, f: impl FnOnce()) -> bool {
59 let current = run_lock();
60 if *current != run {
61 return false;
62 }
63 f();
64 true
65}
66
67fn set(d: &DownloadStatus, state: &str, waiting_on: Vec<WaitingOn>, error: Option<String>, stopping: Vec<String>) {
72 let stopping = if matches!(state, "waiting" | "restarting") { stopping } else { Vec::new() };
73 crate::backend::background_work::write_for_launcher(&stopping);
74 check::set_download(Some(with_wait(d, state, waiting_on, error, stopping)));
75}
76
77fn with_wait(d: &DownloadStatus, state: &str, waiting_on: Vec<WaitingOn>, error: Option<String>, stopping: Vec<String>) -> DownloadStatus {
80 let waiting_on = if state == "waiting" { waiting_on } else { Vec::new() };
81 let state = if state == "waiting" && waiting_on.is_empty() { "restarting" } else { state };
82 DownloadStatus {
84 state: state.to_string(),
85 waiting_for: waiting_on.len() as u32,
86 waiting_on,
87 error,
88 stopping,
89 not_confirmed_at: None,
90 not_confirmed: None,
91 ..d.clone()
92 }
93}
94
95const UNANSWERED: &str = "unanswered";
97
98fn why_words(why: &str) -> &'static str {
100 match why {
101 "no" => "the user answered No",
102 "timed_out" => "nobody answered the prompt before it closed itself",
103 "too_late" => "an answer came after the prompt had lapsed",
104 UNANSWERED => "the launcher didn't restart AgentMux in time (it may have refused the file, or this AgentMux can't restart itself)",
105 _ => "the restart was declined",
106 }
107}
108
109fn clock(ms: u64) -> String {
111 chrono::DateTime::from_timestamp_millis(ms as i64).map_or_else(|| "an unknown time".into(), |t| t.format("%H:%M UTC").to_string())
112}
113
114fn not_confirmed_line(why: &str, at_ms: u64) -> String {
116 format!(
117 "The restart didn't go ahead at {}: {}. The release is downloaded; start the upgrade again from the version panel.",
118 clock(at_ms),
119 why_words(why)
120 )
121}
122
123fn not_confirmed_note(version: &str, why: &str, at_ms: u64) -> String {
125 format!(
126 "[AgentMux] The upgrade to {version} did not happen: the restart didn't go ahead at {}: {}. The release is downloaded and waiting. Ask again if it's still wanted.",
127 clock(at_ms),
128 why_words(why)
129 )
130}
131
132fn not_confirmed(run: u64, d: &DownloadStatus, why: &str, askers: &[String]) {
135 let at = agentmux_common::time::now_ms_u64();
136 let line = not_confirmed_line(why, at);
137 let marked = if_current(run, || {
138 crate::backend::background_work::write_for_launcher(&[]);
139 check::set_download(Some(DownloadStatus {
140 not_confirmed_at: Some(at),
141 not_confirmed: Some(why.to_string()),
142 ..with_wait(d, "ready", Vec::new(), Some(line.clone()), Vec::new())
143 }));
144 });
145 if !marked {
146 return;
147 }
148 tracing::info!(version = %d.version, why, "upgrade: the restart wasn't confirmed");
149 let note = not_confirmed_note(&d.version, why, at);
150 for block_id in askers {
151 crate::backend::upgrade_request::tell(block_id, ¬e);
152 }
153}
154
155pub async fn stopping_now() -> Vec<String> {
157 tokio::task::spawn_blocking(stopping).await.unwrap_or_default()
158}
159
160pub(crate) fn stopping() -> Vec<String> {
162 let now = agentmux_common::time::now_ms_u64();
163 crate::backend::background_work::running().iter().map(|w| crate::backend::background_work::describe(w, now)).collect()
164}
165
166#[derive(Debug, Clone, Default)]
168struct Seen {
169 block: String,
170 kind: String,
171 status: BlockControllerRuntimeStatus,
172 agent: String,
174 retry: Option<Option<u16>>,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
181struct Busy {
182 on: WaitingOn,
183 log: String,
184}
185
186fn busy_controllers(controllers: &[Seen]) -> Vec<Busy> {
193 controllers
194 .iter()
195 .filter(|c| c.status.turn_active && c.status.shellprocstatus != STATUS_DONE)
196 .map(|c| {
197 let (why, held_up) = match c.retry {
198 None => ("turn", ""),
199 Some(None) => ("network_retry", ", retrying after no answer from the API"),
200 Some(Some(_)) => ("api_retry", ", retrying after an API error"),
201 };
202 Busy {
203 on: WaitingOn { agent: c.agent.clone(), why: why.to_string() },
204 log: format!("{} ({}, {}{held_up})", c.block, c.kind, c.status.shellprocstatus),
205 }
206 })
207 .collect()
208}
209
210fn busy_now() -> Vec<Busy> {
212 let names: std::collections::HashMap<String, String> =
213 crate::backend::reactive::get_global_handler().list_agents().into_iter().map(|a| (a.block_id, a.agent_id)).collect();
214 let seen: Vec<Seen> = crate::backend::blockcontroller::get_all_controllers()
215 .iter()
216 .map(|(block, c)| Seen {
217 block: block.clone(),
218 kind: c.controller_type().to_string(),
219 status: c.get_runtime_status(),
220 agent: names.get(block).cloned().unwrap_or_default(),
221 retry: crate::backend::agent_api_retry::current_api_retry(block).retry.map(|r| r.error_status),
222 })
223 .collect();
224 busy_controllers(&seen)
225}
226
227fn waited_for(busy: &[Busy]) -> Vec<WaitingOn> {
228 busy.iter().map(|b| b.on.clone()).collect()
229}
230
231fn staged(status: &AppUpdateStatus) -> Result<(DownloadStatus, UpgradeTarget), String> {
233 let d = status
234 .download
235 .clone()
236 .filter(|d| status.latest.as_deref() == Some(d.version.as_str()))
237 .ok_or("download the new version first")?;
238 if !matches!(d.state.as_str(), "ready" | "waiting") {
239 return Err("the new version isn't ready yet".into());
240 }
241 if !crate::backend::update::check::is_newer(&d.version, &status.current) {
245 tracing::info!(
246 offered = %d.version,
247 running = %status.current,
248 "update: {} is not newer than {}; not restarting into it",
249 d.version,
250 status.current
251 );
252 return Err(format!("{} isn't newer than {}; not restarting into it", d.version, status.current));
253 }
254 if let Some(folder) = d.folder.as_deref().map(PathBuf::from) {
257 if !crate::backend::update::download::is_staged_portable(&folder, &d.version) {
258 return Err(format!("{} is gone; download the new version again", folder.display()));
259 }
260 let launcher = folder.join(if cfg!(windows) { "agentmux.exe" } else { "agentmux.sh" });
263 return Ok((d, UpgradeTarget::Launcher(launcher)));
264 }
265 let installer = PathBuf::from(d.installer.as_deref().ok_or("the new version isn't ready yet")?);
266 if !installer.is_file() {
267 return Err(format!("{} is gone; download the new version again", installer.display()));
268 }
269 if status.install == "linux-appimage" {
271 return Ok((d, UpgradeTarget::Launcher(installer)));
272 }
273 let sha256 = status
275 .asset
276 .as_ref()
277 .filter(|a| installer.file_name().is_some_and(|n| n == a.name.as_str()))
278 .map(|a| a.sha256.to_ascii_lowercase())
279 .ok_or("the new version's checksum is unknown; check for updates again")?;
280 Ok((d, UpgradeTarget::Installer { installer, sha256 }))
281}
282
283pub fn start(now: bool, askers: Vec<String>) -> Result<AppUpdateStatus, String> {
286 let mut current = run_lock();
287 let (d, target) = staged(&check::current_status())?;
288 *current += 1;
289 let run_id = *current;
290 set(&d, "waiting", if now { Vec::new() } else { waited_for(&busy_now()) }, None, Vec::new());
293 drop(current);
294 tokio::spawn(run(run_id, d, target, now, askers));
295 Ok(check::current_status())
296}
297
298pub fn cancel() -> Result<AppUpdateStatus, String> {
301 let mut current = run_lock();
302 let status = check::current_status();
303 match status.download.as_ref() {
304 Some(d) if d.state == "restarting" => {
305 Err("AgentMux has started to restart into the new version; it can't be cancelled now".into())
306 }
307 Some(d) if d.state == "waiting" => {
308 *current += 1;
309 set(d, "ready", Vec::new(), None, Vec::new());
310 Ok(check::current_status())
311 }
312 _ => Ok(status),
313 }
314}
315
316fn declined_file() -> Option<PathBuf> {
318 std::env::var_os("AGENTMUX_DATA_DIR")
319 .filter(|d| !d.is_empty())
320 .map(|d| PathBuf::from(d).join("updates").join(UPGRADE_DECLINED_FILE))
321}
322
323pub(crate) fn take_install_failure(updates: &Path, version: &str) -> Option<String> {
329 let file = updates.join(version).join(INSTALL_RESULT_FILE);
330 let fresh = std::fs::metadata(&file)
331 .and_then(|m| m.modified())
332 .ok()
333 .and_then(|t| t.elapsed().ok())
334 .is_some_and(|age| age < Duration::from_secs(24 * 60 * 60));
335 let text = std::fs::read_to_string(&file).ok()?;
336 let _ = std::fs::remove_file(&file);
337 let json: serde_json::Value = serde_json::from_str(&text).ok()?;
338 let error: String = json.get("error")?.as_str()?.lines().next().unwrap_or("").trim().chars().take(300).collect();
340 (fresh && json.get("version")?.as_str()? == version && !error.is_empty()).then(|| format!("The install didn't finish: {error}"))
341}
342
343fn take_declined(file: &Path, version: &str) -> Option<&'static str> {
348 let text = std::fs::read_to_string(file).ok()?;
349 let (named, why) = agentmux_common::srv_stderr::parse_declined(&text);
350 if named != version {
351 return None;
352 }
353 let _ = std::fs::remove_file(file);
354 Some(why.map_or("declined", |w| w.as_str()))
355}
356
357async fn run(run_id: u64, d: DownloadStatus, target: UpgradeTarget, now: bool, askers: Vec<String>) {
358 let mut last_busy: Option<Vec<String>> = None;
362 loop {
363 let busy = if now { Vec::new() } else { busy_now() };
364 if busy.is_empty() {
365 break;
366 }
367 let lines: Vec<String> = busy.iter().map(|b| b.log.clone()).collect();
368 if last_busy.as_ref() != Some(&lines) {
369 tracing::info!(version = %d.version, busy = ?lines, "upgrade: waiting for agents to finish their turn");
370 last_busy = Some(lines);
371 }
372 let listed = stopping_now().await;
373 if !if_current(run_id, || set(&d, "waiting", waited_for(&busy), None, listed)) {
374 return;
375 }
376 tokio::time::sleep(POLL).await;
377 }
378 let listed = stopping_now().await;
379 let declined = declined_file();
380 let asked = if_current(run_id, || {
381 if let Some(file) = declined.as_deref() {
385 let _ = std::fs::remove_file(file);
386 }
387 set(&d, "restarting", Vec::new(), None, listed);
388 tracing::info!(version = %d.version, target = ?target, "upgrade: asking the launcher to restart");
389 eprintln!("{}", agentmux_common::srv_stderr::upgrade_line(&d.version, &target, true));
392 });
393 if !asked {
394 return;
395 }
396 let grace_ends = tokio::time::Instant::now() + RESTART_GRACE;
401 while tokio::time::Instant::now() < grace_ends {
402 tokio::time::sleep(POLL).await;
403 if !if_current(run_id, || {}) {
404 return;
405 }
406 if let Some(why) = take_install_failure(&crate::backend::update::download::updates_root(), &d.version) {
408 tracing::info!(version = %d.version, %why, "upgrade: the package install didn't start");
409 if_current(run_id, || set(&d, "ready", Vec::new(), Some(why), Vec::new()));
410 return;
411 }
412 if let Some(why) = declined.as_deref().and_then(|f| take_declined(f, &d.version)) {
413 tracing::info!(version = %d.version, why, "upgrade: the restart was declined");
414 not_confirmed(run_id, &d, why, &askers);
415 return;
416 }
417 }
418 not_confirmed(run_id, &d, UNANSWERED, &askers);
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425 use agentmux_common::srv_stderr::{declined_text, Declined};
426
427 fn controller(turn_active: bool, process: &str) -> BlockControllerRuntimeStatus {
428 BlockControllerRuntimeStatus { turn_active, shellprocstatus: process.to_string(), ..Default::default() }
429 }
430
431 fn seen(list: &[(&str, &str, BlockControllerRuntimeStatus)]) -> Vec<Seen> {
432 list.iter()
433 .map(|(block, kind, status)| Seen { block: block.to_string(), kind: kind.to_string(), status: status.clone(), ..Default::default() })
434 .collect()
435 }
436
437 fn busy(list: &[(&str, &str, BlockControllerRuntimeStatus)]) -> Vec<String> {
439 busy_controllers(&seen(list)).into_iter().map(|b| b.log).collect()
440 }
441
442 fn agent(name: &str, turn_active: bool, retry: Option<Option<u16>>) -> Seen {
443 Seen { block: format!("b-{name}"), kind: "persistent".into(), status: controller(turn_active, "running"), agent: name.into(), retry }
444 }
445
446 fn on(agent: &str, why: &str) -> WaitingOn {
447 WaitingOn { agent: agent.into(), why: why.into() }
448 }
449
450 #[test]
451 fn an_agent_retrying_a_request_is_waited_for_and_says_what_holds_it_up() {
452 let list = [
453 agent("Vmer", true, Some(None)),
454 agent("Deke", true, Some(Some(529))),
455 agent("Posa", true, None),
456 agent("Idle", false, Some(None)),
458 ];
459 let busy = busy_controllers(&list);
460 assert_eq!(waited_for(&busy), [on("Vmer", "network_retry"), on("Deke", "api_retry"), on("Posa", "turn")]);
461 assert_eq!(busy[0].log, "b-Vmer (persistent, running, retrying after no answer from the API)");
462 assert_eq!(busy[1].log, "b-Deke (persistent, running, retrying after an API error)");
463 assert_eq!(busy[2].log, "b-Posa (persistent, running)");
464 let mut gone = agent("Vmer", true, Some(None));
466 gone.status.shellprocstatus = "done".into();
467 assert!(busy_controllers(&[gone]).is_empty());
468 }
469
470 #[test]
471 fn a_wait_always_names_someone_and_a_wait_for_nobody_is_the_restart() {
472 let d = download("ready", None);
473 let waiting = with_wait(&d, "waiting", vec![on("Vmer", "turn"), on("Deke", "network_retry")], None, vec!["Vmer: `task dev`".into()]);
474 assert_eq!((waiting.state.as_str(), waiting.waiting_for), ("waiting", 2));
475 assert_eq!(waiting.waiting_on, [on("Vmer", "turn"), on("Deke", "network_retry")]);
476 assert_eq!(waiting.stopping, ["Vmer: `task dev`"]);
477 let nobody = with_wait(&d, "waiting", Vec::new(), None, Vec::new());
479 assert_eq!((nobody.state.as_str(), nobody.waiting_for, nobody.waiting_on.len()), ("restarting", 0, 0));
480 for state in ["restarting", "ready"] {
482 let after = with_wait(&waiting, state, vec![on("Vmer", "turn")], None, Vec::new());
483 assert_eq!((after.state.as_str(), after.waiting_for, after.waiting_on.len()), (state, 0, 0));
484 }
485 }
486
487 #[test]
488 fn only_a_controller_with_a_live_process_in_a_turn_is_waited_for() {
489 let list = [
490 ("b-working", "persistent", controller(true, "running")),
491 ("b-starting", "acp", controller(true, "init")),
492 ("b-idle", "persistent", controller(false, "running")),
493 ("b-stuck", "persistent", controller(true, "done")),
495 ];
496 assert_eq!(busy(&list), ["b-working (persistent, running)", "b-starting (acp, init)"]);
497 }
498
499 #[test]
500 fn nobody_in_a_turn_means_nothing_to_wait_for() {
501 let list = [("b-idle", "persistent", controller(false, "running")), ("b-done", "subprocess", controller(false, "done"))];
502 assert!(busy(&list).is_empty());
503 assert!(busy(&[]).is_empty());
504 }
505
506 #[test]
507 fn the_count_follows_the_controllers_each_time_it_is_asked() {
508 let mut list = vec![("b1", "persistent", controller(true, "running")), ("b2", "persistent", controller(true, "running"))];
509 assert_eq!(busy(&list).len(), 2);
510 list[0].2.turn_active = false;
511 assert_eq!(busy(&list), ["b2 (persistent, running)"]);
512 list[1].2.shellprocstatus = "done".into();
513 assert!(busy(&list).is_empty(), "an agent whose process ended is no longer waited for");
514 }
515
516 fn status(download: Option<DownloadStatus>) -> AppUpdateStatus {
517 AppUpdateStatus {
518 state: "available".into(),
519 current: "0.59.26".into(),
520 latest: Some("0.59.27".into()),
521 url: None,
522 notes: None,
523 published_at: None,
524 checked_ms: 0,
525 install: "windows-portable".into(),
526 asset: None,
527 can_download: true,
528 download_blocked: None,
529 download,
530 install_first: None,
531 rev: 0,
532 }
533 }
534
535 fn download(state: &str, folder: Option<&std::path::Path>) -> DownloadStatus {
536 DownloadStatus {
537 version: "0.59.27".into(),
538 state: state.into(),
539 received: 1,
540 total: 1,
541 error: None,
542 folder: folder.map(|f| f.display().to_string()),
543 installer: None,
544 waiting_for: 0,
545 waiting_on: Vec::new(),
546 stopping: Vec::new(),
547 not_confirmed_at: None,
548 not_confirmed: None,
549 }
550 }
551
552 #[test]
553 fn an_install_failure_is_read_once_for_its_version_and_says_why() {
554 let dir = tempfile::tempdir().unwrap();
555 let folder = dir.path().join("0.60.2");
556 std::fs::create_dir_all(&folder).unwrap();
557 let file = folder.join(INSTALL_RESULT_FILE);
558 assert_eq!(take_install_failure(dir.path(), "0.60.2"), None, "nothing left");
559 std::fs::write(&file, r#"{"version": "0.60.2", "error": "dnf couldn't install the package"}"#).unwrap();
560 assert_eq!(take_install_failure(dir.path(), "0.60.1"), None, "another version has no folder");
561 assert_eq!(
562 take_install_failure(dir.path(), "0.60.2").as_deref(),
563 Some("The install didn't finish: dnf couldn't install the package")
564 );
565 assert!(!file.exists(), "taken out as it is read");
566 std::fs::write(&file, r#"{"version": "0.60.9", "error": "x"}"#).unwrap();
568 assert_eq!(take_install_failure(dir.path(), "0.60.2"), None);
569 std::fs::write(&file, r#"{"version": "0.60.2", "error": " "}"#).unwrap();
570 assert_eq!(take_install_failure(dir.path(), "0.60.2"), None);
571 std::fs::write(&file, "not json").unwrap();
572 assert_eq!(take_install_failure(dir.path(), "0.60.2"), None);
573 let long = format!("{}\nsecond line", "x".repeat(500));
575 std::fs::write(&file, serde_json::json!({ "version": "0.60.2", "error": long }).to_string()).unwrap();
576 let said = take_install_failure(dir.path(), "0.60.2").unwrap();
577 assert_eq!(said, format!("The install didn't finish: {}", "x".repeat(300)));
578 }
579
580 #[test]
581 fn a_no_is_taken_once_and_only_for_the_version_asked() {
582 let dir = tempfile::tempdir().unwrap();
583 let file = dir.path().join(UPGRADE_DECLINED_FILE);
584 assert_eq!(take_declined(&file, "0.59.37"), None, "no answer yet");
585 std::fs::write(&file, "0.59.36\n").unwrap();
586 assert_eq!(take_declined(&file, "0.59.37"), None, "an answer about another version");
587 assert!(file.exists(), "...is left alone");
588 std::fs::write(&file, "0.59.37\n").unwrap();
590 assert_eq!(take_declined(&file, "0.59.37"), Some("declined"));
591 assert!(!file.exists(), "taken out as it is read");
592 assert_eq!(take_declined(&file, "0.59.37"), None, "so it can't answer a second question");
593 for why in [Declined::No, Declined::TimedOut, Declined::TooLate] {
595 std::fs::write(&file, declined_text("0.59.37", why)).unwrap();
596 assert_eq!(take_declined(&file, "0.59.37"), Some(why.as_str()));
597 }
598 }
599
600 #[test]
601 fn a_restart_nobody_confirmed_says_so_with_why_and_when_and_clears_with_the_next_attempt() {
602 let at = 1_795_106_021_000u64;
604 for (why, words) in [
605 ("no", "answered No"),
606 ("timed_out", "nobody answered"),
607 ("too_late", "had lapsed"),
608 (UNANSWERED, "didn't restart AgentMux in time"),
609 ("declined", "was declined"),
610 ] {
611 let line = not_confirmed_line(why, at);
612 assert!(line.contains("16:33 UTC") && line.contains(words) && !line.contains("150"), "{why}: {line}");
613 let note = not_confirmed_note("0.59.35", why, at);
614 assert!(note.starts_with("[AgentMux] The upgrade to 0.59.35 did not happen") && note.contains("16:33 UTC") && note.contains(words) && !note.contains("150"), "{why}: {note}");
615 }
616 let d = download("ready", None);
618 assert_eq!((d.not_confirmed_at, d.not_confirmed.clone()), (None, None));
619 let marked = DownloadStatus { not_confirmed_at: Some(at), not_confirmed: Some("timed_out".into()), ..d.clone() };
620 for state in ["waiting", "restarting", "ready"] {
621 let next = with_wait(&marked, state, vec![on("Vmer", "turn")], None, Vec::new());
622 assert_eq!((next.not_confirmed_at, next.not_confirmed), (None, None), "{state}");
623 }
624 }
625
626 #[test]
627 fn a_cancelled_run_changes_nothing() {
628 let run_id = {
629 let mut current = run_lock();
630 *current += 1;
631 *current
632 };
633 let mut ran = false;
634 assert!(if_current(run_id, || ran = true));
635 assert!(ran);
636 *run_lock() += 1; assert!(!if_current(run_id, || panic!("a stale run changed the state")));
638 }
639
640 #[test]
641 fn a_staged_release_that_is_not_newer_than_this_install_is_not_restarted_into() {
642 for (current, latest) in [("0.59.28", "0.59.27"), ("0.59.27", "0.59.27")] {
644 let mut s = status(Some(download("ready", None)));
645 s.current = current.into();
646 s.latest = Some(latest.into());
647 let err = staged(&s).unwrap_err();
648 assert!(err.contains("isn't newer than"), "{latest} vs {current}: {err}");
649 }
650 }
651
652 #[test]
653 fn only_a_staged_release_that_is_still_there_can_be_restarted_into() {
654 let dir = tempfile::tempdir().unwrap();
655 let folder = dir.path().join("agentmux-0.59.27-x64-portable");
656 assert!(staged(&status(None)).is_err());
657 assert!(staged(&status(Some(download("downloading", None)))).is_err());
658 let err = staged(&status(Some(download("ready", Some(&folder))))).unwrap_err();
660 assert!(err.contains("download the new version again"), "{err}");
661
662 crate::backend::update::download::fake_portable(&folder, "0.59.27");
663 let (d, t) = staged(&status(Some(download("ready", Some(&folder))))).unwrap();
664 let launcher = folder.join(if cfg!(windows) { "agentmux.exe" } else { "agentmux.sh" });
665 assert_eq!((d.version.as_str(), t), ("0.59.27", UpgradeTarget::Launcher(launcher)));
666
667 let installer = dir.path().join("AgentMux-0.59.27-x64-setup.exe");
669 let mut setup = download("ready", None);
670 setup.installer = Some(installer.display().to_string());
671 assert!(staged(&status(Some(setup.clone()))).unwrap_err().contains("download the new version again"));
672 std::fs::write(&installer, b"x").unwrap();
673 assert!(staged(&status(Some(setup.clone()))).unwrap_err().contains("checksum"));
675 let mut with_asset = status(Some(setup));
676 with_asset.asset = Some(crate::backend::update::check::ReleaseAsset {
677 name: "AgentMux-0.59.27-x64-setup.exe".into(),
678 size: 1,
679 url: String::new(),
680 sha256: "AB".repeat(32),
681 });
682 assert_eq!(staged(&with_asset).unwrap().1, UpgradeTarget::Installer { installer: installer.clone(), sha256: "ab".repeat(32) });
683 let mut appimage = with_asset.clone();
685 appimage.install = "linux-appimage".into();
686 assert_eq!(staged(&appimage).unwrap().1, UpgradeTarget::Launcher(installer));
687 let dmg = dir.path().join("AgentMux_0.59.27_arm64.dmg");
689 std::fs::write(&dmg, b"x").unwrap();
690 let mut mac = download("ready", None);
691 mac.installer = Some(dmg.display().to_string());
692 let mut mac = status(Some(mac));
693 mac.install = "macos-app".into();
694 assert!(staged(&mac).unwrap_err().contains("checksum"));
695 mac.asset = Some(crate::backend::update::check::ReleaseAsset {
696 name: "AgentMux_0.59.27_arm64.dmg".into(),
697 size: 1,
698 url: String::new(),
699 sha256: "CD".repeat(32),
700 });
701 let (d, target) = staged(&mac).unwrap();
702 assert_eq!(target, UpgradeTarget::Installer { installer: dmg.clone(), sha256: "cd".repeat(32) });
703 assert_eq!(
704 agentmux_common::srv_stderr::upgrade_line(&d.version, &target, true),
705 format!("AGENTMUXSRV-UPGRADE version:0.59.27 confirmed:1 sha256:{} installer:{}", "cd".repeat(32), dmg.display())
706 );
707 let mut newer = status(Some(download("ready", Some(&folder))));
709 newer.latest = Some("0.59.28".into());
710 assert!(staged(&newer).is_err());
711 }
712}