Skip to main content

agentmux_srv_core/backend/update/
restart.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! "Upgrade & restart", srv's half
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` §4.1, §8.2,
6//! phase 3b).
7//!
8//! Once a release is staged (`update::download`), a restart that is decided (the user's click or own turn, or
9//! an approved request whose in-app countdown ran out with no veto) waits for
10//! every agent to finish its turn (for as long as that takes, with who is
11//! waited for read again every pass; "Now" skips the wait, and Cancel stops
12//! it), then srv asks the launcher to restart into the new
13//! version with an `AGENTMUXSRV-UPGRADE ... confirmed:1` line on its stderr. The launcher
14//! checks the folder and the release's digest again and, the restart being decided, restarts
15//! without asking again (`crates/launcher/src/upgrade_restart.rs`); `restarting` can't be
16//! cancelled from here. If nothing has happened three
17//! minutes later (the launcher refused the file, or an AgentMux that can't restart itself, or a
18//! prompt it still had to show was declined), the
19//! status goes back to ready and says so: when and why the restart wasn't
20//! confirmed (`not_confirmed_at`, `not_confirmed`), and the agents that asked
21//! are told. The launcher says why in its answer file and its own log.
22//!
23//! What the wait is for, and nothing else: an agent whose process is alive
24//! and which is in the middle of a turn ([`busy_controllers`]). A turn held
25//! up by a request that is being retried is still a turn, and the status says
26//! so, since such a wait can be long. What agents left running in the
27//! background is not waited for: it is listed, and the restart stops it.
28//! With nobody to wait for the state is `restarting` at once: `waiting`
29//! always names at least one agent.
30//!
31//! Every change of state happens under [`RUN`], checked against the run it
32//! belongs to, so a Cancel can never be overtaken by a run it stopped.
33
34use 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);
44/// How long the launcher has to quit and restart (or, for a prompt it still has to show, to ask the user). Longer
45/// than the launcher counts a Yes (`ANSWER_WITHIN`, 150 s in `crates/launcher/src/upgrade_restart.rs`), so once
46/// this says the restart didn't happen, no open prompt can still start one.
47const RESTART_GRACE: Duration = Duration::from_secs(3 * 60);
48
49/// The current run, bumped by every start and cancel. Held across each
50/// change of state, so a run that was cancelled changes nothing.
51static 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
57/// Do `f` only if `run` is still the current run.
58fn 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
67/// While the restart waits or is asked for, `stopping` (what agents left
68/// running that it stops, [`stopping`]) is listed with it; the launcher's
69/// dialog lists it too. Gathered by the caller, outside [`RUN`]: it scans
70/// every agent pane's processes.
71fn 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
77/// `d` in `state`. Only `waiting` says who is waited for, and it always names someone: a wait for nobody is not a
78/// wait, so it is said as `restarting`, which is what comes next.
79fn 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    // A new wait, restart or ready state is not the last attempt's "not confirmed": it goes with it.
83    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
95/// The reason word a restart that nothing answered carries (no launcher answer in time).
96const UNANSWERED: &str = "unanswered";
97
98/// What happened, in words, for `why` (a `not_confirmed` word).
99fn 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
109/// `ms` (Unix) as "16:33 UTC".
110fn 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
114/// What the version panel and the status say after a restart that was not confirmed.
115fn 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
123/// What an agent that asked for the upgrade is told.
124fn 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
132/// The restart the launcher was asked for did not happen: back to `ready`, with why and when, and the agents that
133/// asked told. Only if `run` is still the current run.
134fn 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, &note);
152    }
153}
154
155/// [`stopping`] off the async threads.
156pub async fn stopping_now() -> Vec<String> {
157    tokio::task::spawn_blocking(stopping).await.unwrap_or_default()
158}
159
160/// What agents left running now, a line each.
161pub(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/// A pane's controller, as the wait reads it.
167#[derive(Debug, Clone, Default)]
168struct Seen {
169    block: String,
170    kind: String,
171    status: BlockControllerRuntimeStatus,
172    /// The agent's name; empty for a pane that has none.
173    agent: String,
174    /// Its CLI is trying a request to the model again now: `Some(None)` when the request got no answer (the
175    /// network), `Some(Some(status))` when the API answered with that HTTP status.
176    retry: Option<Option<u16>>,
177}
178
179/// One agent the restart waits for: what a window is told, and its line for the log (block id, kind, process state).
180#[derive(Debug, Clone, PartialEq, Eq)]
181struct Busy {
182    on: WaitingOn,
183    log: String,
184}
185
186/// The controllers in the middle of a turn.
187///
188/// A controller whose process has ended can't be in a turn: a `turn_active` left behind by an agent that stopped
189/// or errored mid-turn is not counted, or the restart would wait for something that will never finish. An agent
190/// whose request is being retried is still in its turn and is waited for; it says why, since the retries of a
191/// request that gets no answer can go on for minutes.
192fn 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
210/// Agents in the middle of a turn, read now each time it is asked and never kept.
211fn 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
231/// The staged release of the latest version, if it is still on disk.
232fn 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    // A ready download of an older or equal version (a stale status, or a release pulled between
242    // the check and this click) is not a restart into a new version: only a person's explicit
243    // rollback replaces an install with an older one, and it is not this button (task #49105).
244    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    // A portable's new folder, a setup.exe install's installer, or an
255    // AppImage's next one.
256    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        // On Linux the tarball's script, which sets the library path for the
261        // new folder's binaries before it starts the launcher.
262        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    // An AppImage is started as it is, like a portable's launcher.
270    if status.install == "linux-appimage" {
271        return Ok((d, UpgradeTarget::Launcher(installer)));
272    }
273    // The release's digest goes with it: the launcher checks the file it runs.
274    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
283/// Start "Upgrade & restart". `askers` are the panes of the agents that asked for it: they are told if the restart
284/// is not confirmed (the user's own click has none).
285pub 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    // With nobody to wait for (or "Now") this says `restarting` at once: the launcher is asked a moment later.
291    // What the restart stops follows from `run`, off the async threads.
292    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
298/// Stop waiting (the user's Cancel, through the host). Once the launcher is asked, the restart has started and
299/// can't be cancelled here.
300pub 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
316/// Where the launcher leaves a No (`updates/` of this version's data folder).
317fn 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
323/// Why a `.deb`/`.rpm` upgrade to `version` didn't happen, as the launcher
324/// left it in `updates/<version>/` ([`INSTALL_RESULT_FILE`]): the password was
325/// refused or couldn't be asked for, the file failed its checks, or the install
326/// failed. Taken out as it is read, and ignored when it is for another version
327/// or a day old, so an old attempt can't speak for a new one.
328pub(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    // The file is the user's to write: one line, so a stray process can't put a paragraph in the panel.
339    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
343/// Why the launcher answered No (or the question lapsed) for `version`, as a `not_confirmed` word, if `file` names
344/// it. Each request clears the file before it asks and each answer is taken out as it is read, so one left by an
345/// earlier attempt can't answer a new question, however soon the user tries again. A file from a launcher that
346/// gives no reason says `declined`.
347fn 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    // Waits for every agent to finish its turn for as long as that takes. It ends when nobody is in one, with
359    // "Now", or when the user cancels (which supersedes this run). Who is waited for is read again each pass,
360    // and logged whenever that changes, so a wait that doesn't end can be explained.
361    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        // In the same guarded step that asks, so a run that was superseded while it
382        // listed what it stops can't remove a newer run's answer. Before the
383        // launcher is asked: an answer from an earlier attempt isn't this one's.
384        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        // Asked only once the restart is decided: the user's own click or turn, or an approved request's in-app
390        // countdown that ran out with no veto. The launcher asks nothing more.
391        eprintln!("{}", agentmux_common::srv_stderr::upgrade_line(&d.version, &target, true));
392    });
393    if !asked {
394        return;
395    }
396    // The launcher is told to go ahead. It asks only about a file it refuses or a
397    // package install's own permission prompt; a No to that (or a question that
398    // lapsed) comes back as a file, so the panel stops saying "Restarting" at
399    // once; with no answer at all the grace runs out.
400    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        // A `.deb`/`.rpm` upgrade the launcher couldn't start: it says why.
407        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    // Nothing came back: say so the same way, with its own reason.
419    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    /// The log's lines for who is waited for.
438    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            // A retry left from a turn that has ended holds nothing up.
457            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        // Its process ended mid-retry: nothing is left to finish.
465        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        // Nobody in a turn, or "Now": never `waiting` with a count of 0.
478        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        // Who was waited for is not carried into the states after the wait.
481        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            // A turn flag left behind by an agent that stopped or errored mid-turn.
494            ("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        // For another version than its folder's, or without a reason: nothing to say.
567        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        // The file is the user's to write: the panel gets one short line of it.
574        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        // From a launcher that gives no reason.
589        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        // With the reason the launcher left.
594        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        // 2026-11-19 16:33:41 UTC.
603        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        // It is on the status as a word and a time (what a remote answer carries), and goes with the next wait or restart.
617        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; // a Cancel, or a newer start
637        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        // A stale status, or a release pulled between the check and the click: ready, but not new.
643        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        // Ready, but the folder was deleted since.
659        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        // A setup.exe install restarts through its downloaded installer.
668        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        // Not without the release's digest to check it against.
674        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        // An AppImage's next one is started as it is.
684        let mut appimage = with_asset.clone();
685        appimage.install = "linux-appimage".into();
686        assert_eq!(staged(&appimage).unwrap().1, UpgradeTarget::Launcher(installer));
687        // A macOS app restarts through its staged .dmg, with the release's digest.
688        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        // A download of an older release than the latest doesn't count.
708        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}