Skip to main content

agentmux_srv_core/backend/update/
auto.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The background update: check for a newer release on a timer, and download,
5//! verify and stage it, with no click
6//! (`docs/specs/SPEC_BACKGROUND_UPDATES_ONE_CLICK_RESTART_2026_11_03.md` §4.1, §4.2).
7//!
8//! It only calls what a click calls: [`check::check_now`] and
9//! [`download::start`], so what is checked, downloaded, signed and staged is
10//! the same either way. Nothing is installed here: a staged release waits for
11//! the user's restart (the status bar's **Restart to update**, the tray, or
12//! the version panel).
13//!
14//! The first check is a minute after start (never during startup), then every
15//! six hours give or take a fifth, so a fleet doesn't ask GitHub together. A
16//! failed check backs off: 15 minutes, doubling, at most a day, and the next
17//! good one is back to six hours. `update:auto` off asks GitHub nothing;
18//! `update:autodownload` off checks but leaves the download to the click. A
19//! `task dev` build (it runs from source), a headless srv, a test harness
20//! (`AGENTMUX_DISABLE_CLOUD_SUBSCRIBER`) and `AGENTMUX_NO_AUTO_UPDATE` never
21//! check by themselves.
22
23use std::sync::Arc;
24use std::time::Duration;
25
26use crate::backend::update::check::{self, AppUpdateStatus};
27use crate::backend::update::download;
28use crate::backend::wconfig::ConfigState;
29
30/// The first check, after start.
31const FIRST_CHECK_AFTER: Duration = Duration::from_secs(60);
32/// Up to this much more, so installs started together don't check together.
33const FIRST_CHECK_JITTER: Duration = Duration::from_secs(30);
34/// Between two good checks.
35const CHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60);
36/// The first wait after a failed check; it doubles up to [`BACKOFF_MAX`].
37const BACKOFF_START: Duration = Duration::from_secs(15 * 60);
38const BACKOFF_MAX: Duration = Duration::from_secs(24 * 60 * 60);
39/// How often the switch is looked at while it is off.
40const OFF_RECHECK: Duration = Duration::from_secs(5 * 60);
41/// A release whose download failed is tried again at the next checks, this
42/// many times, then left to the user's click.
43const MAX_DOWNLOAD_TRIES: u32 = 3;
44
45/// The two switches, read from settings each round (absent = on).
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub(crate) struct Switches {
48    pub check: bool,
49    pub download: bool,
50}
51
52pub(crate) fn switches(config: &ConfigState) -> Switches {
53    let s = config.get_settings();
54    Switches { check: s.update_auto.unwrap_or(true), download: s.update_auto_download.unwrap_or(true) }
55}
56
57/// Start the timer. Call once, after [`check::init`].
58pub fn spawn(config: Arc<ConfigState>, headless: bool) {
59    if std::env::var_os("AGENTMUX_NO_AUTO_UPDATE").is_some_and(|v| !v.is_empty()) {
60        tracing::info!("update: background check off (AGENTMUX_NO_AUTO_UPDATE)");
61        return;
62    }
63    // A headless srv, or a test harness: neither updates an app.
64    if headless || std::env::var_os("AGENTMUX_DISABLE_CLOUD_SUBSCRIBER").is_some() {
65        return;
66    }
67    let channel = crate::backend::reactive::registry::local_channel_id();
68    if check::is_dev_build(&channel) {
69        return;
70    }
71    tokio::spawn(async move { run(config).await });
72}
73
74async fn run(config: Arc<ConfigState>) {
75    tokio::time::sleep(FIRST_CHECK_AFTER + FIRST_CHECK_JITTER.mul_f64(fraction())).await;
76    let mut failures = 0u32;
77    let mut tries = DownloadTries::default();
78    loop {
79        let on = switches(&config);
80        if !on.check {
81            tokio::time::sleep(OFF_RECHECK).await;
82            continue;
83        }
84        let wait = match check::check_now().await {
85            Ok(status) => {
86                failures = 0;
87                if on.download {
88                    maybe_download(&status, &mut tries);
89                }
90                wait_after_good_check(after_good_check(fraction()), check::limited_for())
91            }
92            Err(e) => {
93                failures = failures.saturating_add(1);
94                tracing::info!(error = %e, failures, "update: background check failed");
95                after_failure(failures)
96            }
97        };
98        tokio::time::sleep(wait).await;
99    }
100}
101
102/// Start the download of the release on offer when it is wanted and not tried
103/// out.
104fn maybe_download(status: &AppUpdateStatus, tries: &mut DownloadTries) {
105    if !wants_download(status, tries) {
106        return;
107    }
108    match download::start() {
109        Ok(_) => tracing::info!(latest = ?status.latest, "update: downloading in the background"),
110        Err(e) => tracing::info!(error = %e, "update: background download not started"),
111    }
112}
113
114/// How often a release's download was started here, so a download that keeps
115/// failing is left alone.
116#[derive(Debug, Default)]
117pub(crate) struct DownloadTries {
118    version: Option<String>,
119    started: u32,
120}
121
122/// Whether the background should start the download for `status` now, and
123/// count the start in `tries`: a newer release is on offer, this install can
124/// download it, nothing of it is under way or staged, and a failed download
125/// has not failed [`MAX_DOWNLOAD_TRIES`] times.
126pub(crate) fn wants_download(status: &AppUpdateStatus, tries: &mut DownloadTries) -> bool {
127    let Some(version) = status.latest.as_deref() else { return false };
128    if status.state != "available" || !status.can_download {
129        return false;
130    }
131    // A release at or below this build is not an upgrade, whatever a status says: this background
132    // path downloads by itself, so it holds the rule too (task #49105).
133    if !crate::backend::update::check::is_newer(version, &status.current) {
134        tracing::info!(
135            offered = %version,
136            running = %status.current,
137            "update: not downloading {version}; it isn't newer than {}",
138            status.current
139        );
140        return false;
141    }
142    if let Some(d) = &status.download {
143        // Under way, staged, or asked to restart: not ours to start again.
144        if d.version == version && d.state != "failed" {
145            return false;
146        }
147    }
148    if tries.version.as_deref() != Some(version) {
149        *tries = DownloadTries { version: Some(version.to_string()), started: 0 };
150    }
151    if tries.started >= MAX_DOWNLOAD_TRIES {
152        return false;
153    }
154    tries.started += 1;
155    true
156}
157
158/// The wait after a good check: [`CHECK_EVERY`], 80%..120% of it for `r` in 0..1.
159pub(crate) fn after_good_check(r: f64) -> Duration {
160    CHECK_EVERY.mul_f64(0.8 + 0.4 * r.clamp(0.0, 1.0))
161}
162
163/// A moment after GitHub's limit lifts, so the check that follows is not itself refused.
164const AFTER_LIMIT: Duration = Duration::from_secs(30);
165
166/// The wait after a good check, shortened to end just after GitHub's limit does: a release known only by its tag
167/// (no file list while the limit holds) is then checked again as soon as the download can be offered, not hours later.
168pub(crate) fn wait_after_good_check(base: Duration, limited_for: Option<Duration>) -> Duration {
169    limited_for.map_or(base, |left| base.min(left + AFTER_LIMIT))
170}
171
172/// The wait after the `failures`th failed check in a row: 15 minutes, doubling,
173/// at most a day.
174pub(crate) fn after_failure(failures: u32) -> Duration {
175    let doublings = failures.saturating_sub(1).min(16);
176    BACKOFF_START.saturating_mul(1u32 << doublings).min(BACKOFF_MAX)
177}
178
179/// A number in 0..1 from the clock and the process id: installs started together
180/// still spread out, and nothing here needs better.
181fn fraction() -> f64 {
182    let ms = agentmux_common::time::now_ms_u64();
183    let mixed = ms.wrapping_mul(2_654_435_761).wrapping_add(u64::from(std::process::id()));
184    (mixed % 1_000_000) as f64 / 1_000_000.0
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use crate::backend::update::check::DownloadStatus;
191
192    fn offered(latest: &str) -> AppUpdateStatus {
193        AppUpdateStatus {
194            state: "available".into(),
195            current: "0.60.1".into(),
196            latest: Some(latest.into()),
197            url: None,
198            notes: None,
199            published_at: None,
200            checked_ms: 1,
201            install: "windows-portable".into(),
202            asset: None,
203            can_download: true,
204            download_blocked: None,
205            download: None,
206            install_first: None,
207            rev: 0,
208        }
209    }
210
211    fn download_in(version: &str, state: &str) -> DownloadStatus {
212        DownloadStatus {
213            version: version.into(),
214            state: state.into(),
215            received: 0,
216            total: 0,
217            error: None,
218            folder: None,
219            installer: None,
220            waiting_for: 0,
221            waiting_on: Vec::new(),
222            stopping: Vec::new(),
223            not_confirmed_at: None,
224            not_confirmed: None,
225        }
226    }
227
228    #[test]
229    fn a_limit_shortens_the_wait_to_just_after_it_lifts_and_never_lengthens_it() {
230        let base = CHECK_EVERY;
231        assert_eq!(wait_after_good_check(base, None), base);
232        assert_eq!(wait_after_good_check(base, Some(Duration::from_secs(300))), Duration::from_secs(330));
233        // A limit longer than the usual wait changes nothing.
234        assert_eq!(wait_after_good_check(base, Some(base * 2)), base);
235    }
236
237    #[test]
238    fn a_good_check_waits_about_six_hours() {
239        assert_eq!(after_good_check(0.5), CHECK_EVERY);
240        assert_eq!(after_good_check(0.0), CHECK_EVERY.mul_f64(0.8));
241        assert_eq!(after_good_check(1.0), CHECK_EVERY.mul_f64(1.2));
242        // Out of range is held to the range.
243        assert_eq!(after_good_check(7.0), CHECK_EVERY.mul_f64(1.2));
244    }
245
246    #[test]
247    fn a_failed_check_backs_off_to_a_day() {
248        assert_eq!(after_failure(1), Duration::from_secs(15 * 60));
249        assert_eq!(after_failure(2), Duration::from_secs(30 * 60));
250        assert_eq!(after_failure(3), Duration::from_secs(60 * 60));
251        assert_eq!(after_failure(8), BACKOFF_MAX);
252        assert_eq!(after_failure(u32::MAX), BACKOFF_MAX);
253    }
254
255    #[test]
256    fn a_newer_release_is_downloaded_once_it_can_be() {
257        let mut tries = DownloadTries::default();
258        assert!(wants_download(&offered("0.60.2"), &mut tries));
259    }
260
261    #[test]
262    fn nothing_is_downloaded_that_the_install_cannot_download() {
263        let mut tries = DownloadTries::default();
264        let mut store = offered("0.60.2");
265        store.can_download = false;
266        assert!(!wants_download(&store, &mut tries), "a Store install updates through the Store");
267        let mut current = offered("0.60.1");
268        current.state = "up-to-date".into();
269        assert!(!wants_download(&current, &mut tries));
270        let mut unchecked = offered("0.60.2");
271        unchecked.latest = None;
272        assert!(!wants_download(&unchecked, &mut tries));
273    }
274
275    #[test]
276    fn an_older_or_equal_release_is_never_downloaded_by_itself() {
277        for latest in ["0.60.0", "0.60.1"] {
278            let mut tries = DownloadTries::default();
279            let s = offered(latest);
280            assert!(!wants_download(&s, &mut tries), "{latest} vs {}", s.current);
281        }
282    }
283
284    #[test]
285    fn a_download_under_way_or_staged_is_left_alone() {
286        for state in ["downloading", "unpacking", "ready", "waiting", "restarting"] {
287            let mut tries = DownloadTries::default();
288            let mut s = offered("0.60.2");
289            s.download = Some(download_in("0.60.2", state));
290            assert!(!wants_download(&s, &mut tries), "{state}");
291        }
292    }
293
294    #[test]
295    fn a_download_of_an_older_release_does_not_block_the_newer_one() {
296        let mut tries = DownloadTries::default();
297        let mut s = offered("0.60.3");
298        s.download = Some(download_in("0.60.2", "ready"));
299        assert!(wants_download(&s, &mut tries));
300    }
301
302    #[test]
303    fn a_failing_download_is_tried_three_times_then_left_to_the_click() {
304        let mut tries = DownloadTries::default();
305        let mut s = offered("0.60.2");
306        s.download = Some(download_in("0.60.2", "failed"));
307        for _ in 0..MAX_DOWNLOAD_TRIES {
308            assert!(wants_download(&s, &mut tries));
309        }
310        assert!(!wants_download(&s, &mut tries));
311        // A newer release starts over.
312        let mut newer = offered("0.60.3");
313        newer.download = Some(download_in("0.60.2", "failed"));
314        assert!(wants_download(&newer, &mut tries));
315    }
316}