Skip to main content

agentmux_srv_core/backend/
upgrade_request.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent asking to upgrade AgentMux: `RequestUpgrade`
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` §5.1, phase 4).
6//!
7//! A restart stops every agent and interrupts the user, and an agent can be
8//! prompt-injected, so an agent's word alone never starts one:
9//! - the user's own turn asked for it (`self_quit::gate_upgrade`: as for
10//!   `QuitSelf`, but a Swarm broadcast doesn't count):
11//!   the upgrade starts — the release is downloaded if it isn't yet, then
12//!   AgentMux restarts once every agent has finished its turn;
13//! - anything else is a sensitive request (`server/sensitive_handlers.rs`): the
14//!   super agent decides, the person can veto the countdown, and the agent is
15//!   told each step as an `[AgentMux]` note. When the countdown ends,
16//!   `sagas/sensitive_runners.rs` starts the same upgrade.
17//!
18//! The prompt every window used to show for the second case is gone; `answer`,
19//! `list` and `UpgradeRequest` below only serve any left from before.
20//!
21//! Either way the restart is already decided by then, so the launcher asks
22//! nothing more (`crates/launcher/src/upgrade_restart.rs`), and only a release
23//! the update check found, verified against GitHub's checksum, is installed:
24//! the agent can't name a file or a URL.
25
26use std::sync::{Arc, Mutex};
27use std::time::Duration;
28
29use serde::{Deserialize, Serialize};
30
31use crate::backend::mps::Broker;
32use crate::backend::storage::store::Store;
33use crate::backend::update::check::{self, AppUpdateStatus};
34
35/// How long the flow waits for the download before giving up.
36const DOWNLOAD_WAIT: Duration = Duration::from_secs(15 * 60);
37
38/// An agent's request waiting for the user.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
40#[ts(export, export_to = "../../../frontend/types/rpc/")]
41pub struct UpgradeRequest {
42    pub id: String,
43    /// The agent that asked, by name.
44    pub agent: String,
45    pub reason: String,
46    /// The release it would install.
47    pub version: String,
48    #[ts(type = "number")]
49    pub asked_ms: u64,
50    /// The asking agent's pane, to tell it the answer.
51    #[serde(skip)]
52    #[ts(skip)]
53    pub block_id: String,
54}
55
56/// `app:upgraderequests`: the agents' upgrade requests waiting for the user.
57#[derive(Debug, Clone, Serialize, ts_rs::TS)]
58#[ts(export, export_to = "../../../frontend/types/rpc/")]
59pub struct UpgradeRequestsEvent {
60    pub requests: Vec<UpgradeRequest>,
61}
62
63/// The user's answer, relayed by the host (`POST /api/v1/host/upgrade_request`).
64#[derive(Debug, Clone, Deserialize)]
65pub struct UpgradeRequestAnswer {
66    pub id: String,
67    /// The release the prompt showed: Upgrade now installs only that one.
68    pub version: String,
69    /// Upgrade now (true) or Later (false).
70    pub accept: bool,
71}
72
73/// What `RequestUpgrade` answers the agent.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
75#[serde(tag = "status", rename_all = "snake_case")]
76pub enum Outcome {
77    /// The user's own turn asked: the upgrade is under way. `stopping`: what
78    /// agents left running that the restart stops (`background_work`).
79    Started {
80        version: String,
81        #[serde(skip_serializing_if = "Vec::is_empty")]
82        stopping: Vec<String>,
83    },
84    /// Asked for like any sensitive operation (`Sensitive`): the super agent decides, the person
85    /// can veto the countdown. `review` says whom it went to; the agent hears the rest as notes.
86    Requested { version: String, id: String, review: String },
87    UpToDate { current: String },
88    /// Nothing this AgentMux can install itself; `url` is where the user can.
89    Unavailable { message: String, #[serde(skip_serializing_if = "Option::is_none")] url: Option<String> },
90}
91
92/// The release a request may install, or why there is none. `wanted` is the
93/// version the agent named, if any: only the latest release can be installed.
94pub fn installable(status: &AppUpdateStatus, wanted: Option<&str>) -> Result<String, Outcome> {
95    match status.state.as_str() {
96        "available" => {}
97        "up-to-date" => return Err(Outcome::UpToDate { current: status.current.clone() }),
98        "local-build" => {
99            return Err(Outcome::Unavailable {
100                message: "this is a development build (`task dev`), which runs from source; it doesn't upgrade itself".into(),
101                url: status.url.clone(),
102            })
103        }
104        _ => {
105            return Err(Outcome::Unavailable {
106                message: "AgentMux couldn't learn which release is the latest (GitHub didn't answer); try again in a few minutes".into(),
107                url: None,
108            })
109        }
110    }
111    let latest = status.latest.clone().unwrap_or_default();
112    // The rule the rest of the path rests on, stated here too: a release at or below this build is
113    // not an upgrade, whoever built the status (a feed can name one after a pull, a stale copy or a
114    // channel change). Only a person's explicit rollback replaces an install with an older one, and
115    // an agent's request is not that (task #49105).
116    if !crate::backend::update::check::is_newer(&latest, &status.current) {
117        tracing::info!(
118            offered = %latest,
119            running = %status.current,
120            "upgrade request: {latest} is not newer than {}; not installing it",
121            status.current
122        );
123        return Err(Outcome::UpToDate { current: status.current.clone() });
124    }
125    if let Some(floor) = &status.install_first {
126        return Err(Outcome::Unavailable {
127            message: format!(
128                "this AgentMux ({}) is older than {latest} can upgrade from; the user installs {floor} first, then upgrades",
129                status.current
130            ),
131            url: Some(format!("https://github.com/agentmuxai/agentmux/releases/tag/v{floor}")),
132        });
133    }
134    // A restart into an earlier release is under way (the check found a
135    // newer one since): that one goes first.
136    if let Some(d) = status.download.as_ref().filter(|d| matches!(d.state.as_str(), "waiting" | "restarting")) {
137        if d.version != latest {
138            return Err(Outcome::Unavailable {
139                message: format!("AgentMux is already restarting into {}; ask again once it has", d.version),
140                url: None,
141            });
142        }
143    }
144    if let Some(w) = wanted.map(|w| w.trim().trim_start_matches('v')).filter(|w| !w.is_empty()) {
145        if w != latest {
146            return Err(Outcome::Unavailable {
147                message: format!("only the latest release, {latest}, can be installed"),
148                url: status.url.clone(),
149            });
150        }
151    }
152    if !status.can_download {
153        return Err(Outcome::Unavailable {
154            message: format!(
155                "this AgentMux ({}) can't upgrade itself to {latest} yet; the user can download it from the release page",
156                status.install
157            ),
158            url: status.url.clone(),
159        });
160    }
161    Ok(latest)
162}
163
164static PENDING: Mutex<Vec<UpgradeRequest>> = Mutex::new(Vec::new());
165static ASKING: Mutex<Option<crate::backend::user_attention::Asking>> = Mutex::new(None);
166
167fn pending() -> std::sync::MutexGuard<'static, Vec<UpgradeRequest>> {
168    PENDING.lock().unwrap_or_else(|e| e.into_inner())
169}
170
171/// The requests waiting for the user (`app.upgrade-requests`).
172pub fn list() -> Vec<UpgradeRequest> {
173    pending().clone()
174}
175
176fn publish(broker: &Arc<Broker>, mstore: &Arc<Store>) {
177    let requests = list();
178    let mut asking = ASKING.lock().unwrap_or_else(|e| e.into_inner());
179    *asking = requests.first().map(|r| {
180        crate::backend::user_attention::Asking::start(
181            broker,
182            mstore,
183            "",
184            "upgrade",
185            &format!("{} asks to upgrade AgentMux to {}", r.agent, r.version),
186        )
187    });
188    drop(asking);
189    broker
190        .publish_event::<crate::backend::mps_events::AppUpgradeRequests>(&UpgradeRequestsEvent { requests }, vec![], 0);
191}
192
193/// Tell the agent in `block_id` something, as an `[AgentMux]` note.
194pub(crate) fn tell(block_id: &str, text: &str) {
195    let handler = crate::backend::reactive::get_global_handler();
196    let Some(target) = handler
197        .list_agents()
198        .into_iter()
199        .find(|r| r.block_id == block_id)
200        .map(|r| r.uid.unwrap_or(r.agent_id))
201    else {
202        tracing::info!(block_id, "upgrade request: the asking agent isn't running to be told");
203        return;
204    };
205    if let Err(e) = handler.deliver_system_note(&target, text) {
206        tracing::info!(block_id, error = %e, "upgrade request: note not delivered");
207    }
208}
209
210/// The user's answer to request `id`, for the release the prompt showed
211/// (relayed by the host: `POST /api/v1/host/upgrade_request`). Upgrade now
212/// answers every request for that release, since there is one AgentMux to
213/// upgrade; if the update check has found a newer release since, it installs
214/// nothing and the agent is told to ask again.
215pub fn answer(broker: &Arc<Broker>, mstore: &Arc<Store>, id: &str, version: &str, accept: bool) -> Result<(), String> {
216    let latest = check::current_status().latest.unwrap_or_default();
217    let (answered, stale): (Vec<UpgradeRequest>, bool) = {
218        let mut p = pending();
219        let Some(pos) = p.iter().position(|r| r.id == id && r.version == version) else {
220            return Err("that upgrade request was already answered".into());
221        };
222        if accept && version == latest {
223            let (same, other): (Vec<_>, Vec<_>) = std::mem::take(&mut *p).into_iter().partition(|r| r.version == version);
224            *p = other;
225            (same, false)
226        } else {
227            (vec![p.remove(pos)], accept)
228        }
229    };
230    publish(broker, mstore);
231    if stale {
232        for r in &answered {
233            tell(
234                &r.block_id,
235                &format!(
236                    "[AgentMux] AgentMux has learned of a newer release ({latest}) since you asked to upgrade to {}; nothing was installed. Ask again if it's still wanted.",
237                    r.version
238                ),
239            );
240        }
241        return Err(format!("a newer release, {latest}, came out since this request; nothing was installed"));
242    }
243    for r in &answered {
244        let text = if accept {
245            format!(
246                "[AgentMux] The user approved upgrading AgentMux to {}. It downloads now, then AgentMux restarts after every agent finishes its turn; your session resumes afterwards.",
247                r.version
248            )
249        } else {
250            format!("[AgentMux] The user chose not to upgrade AgentMux to {} for now.", r.version)
251        };
252        tell(&r.block_id, &text);
253    }
254    if accept {
255        start_upgrade(version.to_string(), answered.into_iter().map(|r| r.block_id).collect());
256    }
257    Ok(())
258}
259
260/// The user's own turn started the upgrade to `version`: requests for it
261/// that were waiting are answered by that, and their agents told so.
262pub fn resolve_started(broker: &Arc<Broker>, mstore: &Arc<Store>, version: &str) -> Vec<String> {
263    let resolved: Vec<UpgradeRequest> = {
264        let mut p = pending();
265        let (same, other): (Vec<_>, Vec<_>) = std::mem::take(&mut *p).into_iter().partition(|r| r.version == version);
266        *p = other;
267        same
268    };
269    if resolved.is_empty() {
270        return Vec::new();
271    }
272    publish(broker, mstore);
273    for r in &resolved {
274        tell(
275            &r.block_id,
276            &format!("[AgentMux] The user asked for the upgrade to {version} themselves; it is under way. Your request is answered by that."),
277        );
278    }
279    resolved.into_iter().map(|r| r.block_id).collect()
280}
281
282/// Download `version` if it isn't yet, then restart once every agent has
283/// finished its turn (the restart is already decided, so the launcher asks
284/// nothing more). Only while
285/// `version` is still the latest release: the download and restart take the
286/// latest, so a newer one appearing meanwhile stops the flow. The agents in
287/// `askers` (their panes) are told if it stops short, and why.
288pub fn start_upgrade(version: String, askers: Vec<String>) {
289    tokio::spawn(async move {
290        let stop = |why: &str| {
291            tracing::info!(version = %version, why, "upgrade request: stopped");
292            for block_id in &askers {
293                tell(block_id, &format!("[AgentMux] The upgrade to {version} stopped: {why}. Ask again if it's still wanted."));
294            }
295        };
296        let still_latest = |s: &AppUpdateStatus| s.latest.as_deref() == Some(version.as_str());
297        let ready = |s: &AppUpdateStatus| {
298            s.download.as_ref().is_some_and(|d| d.version == version && d.state == "ready")
299        };
300        let busy = |s: &AppUpdateStatus| {
301            s.download.as_ref().is_some_and(|d| matches!(d.state.as_str(), "waiting" | "restarting"))
302        };
303        let status = check::current_status();
304        if let Some(d) = status.download.as_ref().filter(|_| busy(&status)) {
305            // This release's restart is already under way; another's goes first.
306            if d.version != version {
307                stop(&format!("AgentMux is already restarting into {}", d.version));
308            }
309            return;
310        }
311        let newer = |s: &AppUpdateStatus| format!("a newer release, {}, came out", s.latest.clone().unwrap_or_default());
312        if !still_latest(&status) {
313            return stop(&newer(&status));
314        }
315        if !ready(&status) {
316            if let Err(e) = crate::backend::update::download::start() {
317                return stop(&format!("the download couldn't start ({e})"));
318            }
319            let deadline = tokio::time::Instant::now() + DOWNLOAD_WAIT;
320            loop {
321                tokio::time::sleep(Duration::from_secs(1)).await;
322                let s = check::current_status();
323                if !still_latest(&s) {
324                    return stop(&newer(&s));
325                }
326                if ready(&s) {
327                    break;
328                }
329                if let Some(d) = s.download.as_ref().filter(|d| d.state == "failed") {
330                    return stop(&format!("the download failed ({})", d.error.clone().unwrap_or_default()));
331                }
332                if s.download.is_none() || tokio::time::Instant::now() >= deadline {
333                    return stop("the download didn't finish");
334                }
335            }
336        }
337        let s = check::current_status();
338        if !still_latest(&s) {
339            return stop(&newer(&s));
340        }
341        if let Err(e) = crate::backend::update::restart::start(false, askers.clone()) {
342            stop(&format!("the restart couldn't start ({e})"));
343        }
344    });
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    fn status(state: &str, can_download: bool) -> AppUpdateStatus {
352        AppUpdateStatus {
353            state: state.into(),
354            current: "0.59.26".into(),
355            latest: Some("0.59.27".into()),
356            url: Some("https://github.com/agentmuxai/agentmux/releases/tag/v0.59.27".into()),
357            notes: None,
358            published_at: None,
359            checked_ms: 1,
360            install: if can_download { "windows-portable" } else { "windows-setup" }.into(),
361            asset: None,
362            can_download,
363            download_blocked: None,
364            download: None,
365            install_first: None,
366            rev: 0,
367        }
368    }
369
370    #[test]
371    fn only_the_latest_release_an_install_can_take_is_installable() {
372        assert_eq!(installable(&status("available", true), None), Ok("0.59.27".into()));
373        assert_eq!(installable(&status("available", true), Some("v0.59.27")), Ok("0.59.27".into()));
374        assert!(matches!(
375            installable(&status("available", true), Some("0.59.25")),
376            Err(Outcome::Unavailable { .. })
377        ));
378        assert_eq!(installable(&status("up-to-date", true), None), Err(Outcome::UpToDate { current: "0.59.26".into() }));
379        // An install AgentMux can't upgrade itself gets the release page.
380        let Err(Outcome::Unavailable { message, url }) = installable(&status("available", false), None) else {
381            panic!("expected unavailable")
382        };
383        assert!(message.contains("windows-setup"), "{message}");
384        assert!(url.unwrap().ends_with("v0.59.27"));
385        for state in ["local-build", "unknown"] {
386            assert!(matches!(installable(&status(state, true), None), Err(Outcome::Unavailable { .. })), "{state}");
387        }
388        // A restart into an earlier release is under way: that one goes first.
389        let mut busy = status("available", true);
390        busy.download = Some(crate::backend::update::check::DownloadStatus {
391            version: "0.59.26".into(),
392            state: "restarting".into(),
393            received: 1,
394            total: 1,
395            error: None,
396            folder: None,
397            installer: None,
398            waiting_for: 0,
399            waiting_on: Vec::new(),
400            stopping: Vec::new(),
401            not_confirmed_at: None,
402            not_confirmed: None,
403        });
404        let Err(Outcome::Unavailable { message, .. }) = installable(&busy, None) else { panic!("expected unavailable") };
405        assert!(message.contains("already restarting into 0.59.26"), "{message}");
406        // Older than the release upgrades from: the floor version first.
407        let mut old = status("available", false);
408        old.install_first = Some("0.58.0".into());
409        let Err(Outcome::Unavailable { message, url }) = installable(&old, None) else { panic!("expected unavailable") };
410        assert!(message.contains("installs 0.58.0 first"), "{message}");
411        assert!(url.unwrap().ends_with("/v0.58.0"));
412    }
413
414    #[test]
415    fn a_request_for_an_older_or_equal_release_is_refused_whatever_the_status_says() {
416        // A status whose state says "available" but whose release isn't newer (a stale status, or a
417        // feed that named an older release): the request must not become an install.
418        for (current, latest) in [("0.59.27", "0.59.26"), ("0.59.27", "0.59.27"), ("0.60.10", "0.60.10-rc1")] {
419            let mut s = status("available", true);
420            s.current = current.into();
421            s.latest = Some(latest.into());
422            assert_eq!(
423                installable(&s, None),
424                Err(Outcome::UpToDate { current: current.into() }),
425                "{latest} vs {current}"
426            );
427            assert_eq!(
428                installable(&s, Some(latest)),
429                Err(Outcome::UpToDate { current: current.into() }),
430                "{latest} vs {current}, asked by name"
431            );
432        }
433    }
434
435    #[test]
436    fn outcomes_read_as_the_tool_expects() {
437        let r = serde_json::to_value(Outcome::Requested { version: "0.59.27".into(), id: "r2".into(), review: "the super agent has been asked".into() }).unwrap();
438        assert_eq!(r, serde_json::json!({ "status": "requested", "version": "0.59.27", "id": "r2", "review": "the super agent has been asked" }));
439        let v = serde_json::to_value(Outcome::Unavailable { message: "m".into(), url: None }).unwrap();
440        assert_eq!(v, serde_json::json!({ "status": "unavailable", "message": "m" }));
441    }
442}