Skip to main content

agentmux_srv_core/backend/update/
check.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Whether a newer AgentMux release exists
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` §3).
6//!
7//! srv asks GitHub Releases for the latest release when asked: the user's
8//! **Check for update** in the version panel, or an agent's `App` `version` or
9//! `upgrade` ([`check_now`]), at most every 30 seconds between them; and by
10//! itself, a minute after start and every few hours, unless the user turned
11//! `update:auto` off (`update::auto`, which also downloads and stages the
12//! release; the operator reversed the 2026-10-18 "no request the user didn't
13//! ask for" rule for this check on 2026-11-03). Offline, a rate limit or any
14//! error keeps what the last check found.
15//!
16//! Which release is latest comes from the `releases/latest` web page's
17//! redirect, which GitHub's 60-an-hour anonymous API limit (shared by
18//! everything on the computer) doesn't touch. The API is asked only for the
19//! release's files and notes, when the page names a release this srv hasn't
20//! got yet (and, once held, with its ETag, which saves the download; an
21//! unauthenticated 304 still counts against the limit, as measured). When
22//! GitHub still refuses, the check says so and when it lifts, and a newer release is
23//! still reported. Its files and checksums then come from the release's signed
24//! manifest at its download address (`update::signed_source`), which the API's limit
25//! doesn't touch; where that gives no answer either, there is no download until the
26//! API answers.
27//!
28//! The answer is kept here, sent to every window as the `app:updatestatus`
29//! event when it changes, and read on demand with `app.update-status`. It
30//! names the release file for this install (`update::install`) with the
31//! SHA-256 GitHub lists for it, and that check's answer is what the rest
32//! installs: `update::download` fetches exactly that file, and
33//! `update::restart` verifies it against that checksum. A new check replaces
34//! the release on offer, except while a download or a restart into it is
35//! under way, which finishes first.
36//!
37//! Any portable or installed build upgrades to a newer release, a local
38//! `task package` build (`local-…` channel) included: it compares versions like
39//! a release. Only a `task dev` build (`dev-…` channel), which runs from source,
40//! never upgrades; it reports which release is latest.
41
42use std::sync::atomic::{AtomicI64, Ordering};
43use std::sync::{Arc, OnceLock};
44use std::time::Duration;
45
46use parking_lot::RwLock;
47use serde::{Deserialize, Serialize};
48
49use crate::backend::update::install::InstallKind;
50
51/// The event every window gets when the status changes.
52pub const EVENT_APP_UPDATE_STATUS: &str = "app:updatestatus";
53
54/// GitHub's latest-release endpoint for the public repo. Unauthenticated:
55/// 60 requests an hour per address, shared with everything else on the
56/// computer; see the module doc for how little this asks of it.
57const LATEST_RELEASE_URL: &str = "https://api.github.com/repos/agentmuxai/agentmux/releases/latest";
58/// The page GitHub redirects to the latest release's own page: the tag is in
59/// the redirect, and it isn't part of the API's anonymous quota.
60const LATEST_PAGE_URL: &str = "https://github.com/agentmuxai/agentmux/releases/latest";
61/// A release's page; the latest page redirects to one of these.
62const RELEASE_PAGE_PREFIX: &str = "https://github.com/agentmuxai/agentmux/releases/tag/";
63const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
64/// The shortest gap between two checks the user or an agent asks for: GitHub
65/// allows 60 unauthenticated requests an hour per address.
66const CHECK_NOW_EVERY: Duration = Duration::from_secs(30);
67/// Release notes kept for the panel, in bytes.
68const MAX_NOTES_BYTES: usize = 16 * 1024;
69
70/// What srv knows about releases, as every window shows it.
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
72#[ts(export, export_to = "../../../frontend/types/rpc/")]
73pub struct AppUpdateStatus {
74    /// `up-to-date`, `available` (a newer release exists), `local-build`
75    /// (this build isn't a release; `latest` says which release is) or
76    /// `unknown` (not checked yet).
77    pub state: String,
78    /// This build's version.
79    pub current: String,
80    /// The latest release's version, without the `v`.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    #[ts(optional)]
83    pub latest: Option<String>,
84    /// The latest release's page.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    #[ts(optional)]
87    pub url: Option<String>,
88    /// Its notes (the release body), at most 16 KB.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    #[ts(optional)]
91    pub notes: Option<String>,
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    #[ts(optional)]
94    pub published_at: Option<String>,
95    /// When the last check answered (unix ms), 0 before any. The status is
96    /// that check's answer until the next one.
97    #[ts(type = "number")]
98    pub checked_ms: i64,
99    /// How this AgentMux was installed (`update::install`): `windows-portable`,
100    /// `windows-setup`, `windows-store`, `macos-app`, `linux-appimage`,
101    /// `linux-portable`, `linux-package` or `unknown`.
102    #[serde(default)]
103    pub install: String,
104    /// The latest release's file for this install, when it has one.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    #[ts(optional)]
107    pub asset: Option<ReleaseAsset>,
108    /// Whether AgentMux can download and stage that file itself; otherwise
109    /// the release page (or the Store) is the way.
110    #[serde(default)]
111    pub can_download: bool,
112    /// When a newer release is on offer and this install could upgrade itself but can't now, why: a macOS app that
113    /// can't be replaced in place, a release known only by its tag (GitHub is limiting the check), or a release with
114    /// no file for this computer. The page says so beside the button that opens the download page.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    #[ts(optional)]
117    pub download_blocked: Option<String>,
118    /// A download of the latest release, once one was asked for.
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    #[ts(optional)]
121    pub download: Option<DownloadStatus>,
122    /// When this AgentMux is older than the latest release can upgrade from
123    /// (the release's upgrade floor, [`upgrade_floor`]): the version to
124    /// install first. The latest release then isn't offered for download.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    #[ts(optional)]
127    pub install_first: Option<String>,
128    /// Rises with every change srv makes to this status. The answer to a click and the event for a later change
129    /// reach a window in either order, so a window keeps the one with the higher `rev`. Unix ms, pushed up when
130    /// two changes share a millisecond; 0 from an srv that doesn't say.
131    #[serde(default, skip_serializing_if = "is_zero")]
132    #[ts(optional, as = "Option<f64>")]
133    pub rev: u64,
134}
135
136fn is_zero(n: &u64) -> bool {
137    *n == 0
138}
139
140/// A release file, as GitHub lists it.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
142#[ts(export, export_to = "../../../frontend/types/rpc/")]
143pub struct ReleaseAsset {
144    pub name: String,
145    #[ts(type = "number")]
146    pub size: u64,
147    pub url: String,
148    /// Lowercase hex.
149    pub sha256: String,
150}
151
152/// One agent a restart waits for (`update::restart`).
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
154#[ts(export, export_to = "../../../frontend/types/rpc/")]
155pub struct WaitingOn {
156    /// The agent's name, as it is addressed; empty for a pane that has none.
157    pub agent: String,
158    /// Why it is waited for. `turn`: it is in the middle of a turn. A turn that is held up says by what:
159    /// `network_retry` (its request to the model got no answer and is being tried again) or `api_retry` (the
160    /// model's API answered with an error and the request is being tried again).
161    pub why: String,
162}
163
164/// Where a download of a release stands.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
166#[ts(export, export_to = "../../../frontend/types/rpc/")]
167pub struct DownloadStatus {
168    /// The release being downloaded.
169    pub version: String,
170    /// `downloading`, `unpacking`, `ready` or `failed`; then, after "Upgrade
171    /// & restart", `waiting` (for agents to finish their turn) and
172    /// `restarting` (the launcher was asked).
173    pub state: String,
174    #[ts(type = "number")]
175    pub received: u64,
176    #[ts(type = "number")]
177    pub total: u64,
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    #[ts(optional)]
180    pub error: Option<String>,
181    /// When ready, on a portable: the folder the new version is in.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    #[ts(optional)]
184    pub folder: Option<String>,
185    /// When ready, on a `setup.exe` install: the new version's installer.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    #[ts(optional)]
188    pub installer: Option<String>,
189    /// While `waiting`: how many agents are still in a turn.
190    #[serde(default)]
191    pub waiting_for: u32,
192    /// While `waiting`: those agents, one entry each ([`WaitingOn`]). Never empty then: with nobody to wait
193    /// for, the state is `restarting`.
194    #[serde(default, skip_serializing_if = "Vec::is_empty")]
195    #[ts(optional, as = "Option<Vec<WaitingOn>>")]
196    pub waiting_on: Vec<WaitingOn>,
197    /// While `waiting` or `restarting`: what agents left running that the
198    /// restart stops, a line each ("Agent-1: an AgentMux instance (`task
199    /// dev`), running 9 h"; `background_work`).
200    #[serde(default)]
201    pub stopping: Vec<String>,
202    /// After a restart that was asked for and then not confirmed (the user said No, nobody answered the launcher's
203    /// dialog, or an answer came too late): when, in Unix milliseconds. Gone with the next restart or download.
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    #[ts(optional, type = "number")]
206    pub not_confirmed_at: Option<u64>,
207    /// Why, with `not_confirmed_at`: `no`, `timed_out`, `too_late`, or `unanswered` (nothing came back in time, so
208    /// the dialog may never have been shown). A word, not a sentence: it leaves the machine in a remote answer.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    #[ts(optional)]
211    pub not_confirmed: Option<String>,
212}
213
214impl AppUpdateStatus {
215    fn initial(current: &str) -> Self {
216        Self {
217            state: "unknown".to_string(),
218            current: current.to_string(),
219            latest: None,
220            url: None,
221            notes: None,
222            published_at: None,
223            checked_ms: 0,
224            install: install_kind().label().to_string(),
225            asset: None,
226            can_download: false,
227            download_blocked: None,
228            download: None,
229            install_first: None,
230            rev: 0,
231        }
232    }
233}
234
235/// Why a newer release is on offer but AgentMux can't download it itself, for an install that normally could: a
236/// macOS app that can't be replaced in place, a release known only by its tag (GitHub is limiting the check, so
237/// there is no file list or checksum yet), or a release with no file for this computer. `None` when it can, and
238/// for installs that never download (the Store, an unknown install): the release page is their way, not a fault.
239fn download_blocked(state: &str, kind: &InstallKind, release: &Release, has_asset: bool, below_floor: bool) -> Option<String> {
240    if state != "available" || below_floor {
241        return None;
242    }
243    // A macOS app that can't be replaced where it is finds its file in the release all the same, so this
244    // comes before the file is looked at.
245    if let Some(why) = kind.blocked_reason() {
246        return Some(format!("This install can't upgrade itself where it is: {why}."));
247    }
248    if has_asset || !kind.can_download() {
249        return None;
250    }
251    Some(if let Some(note) = &release.limit_note {
252        note.clone()
253    } else if release.assets.is_empty() {
254        "The release's file list isn't available yet.".to_string()
255    } else {
256        "This release has no file for this computer.".to_string()
257    })
258}
259
260/// The part of GitHub's release JSON this reads.
261#[derive(Debug, Clone, Deserialize)]
262pub(crate) struct Release {
263    tag_name: String,
264    html_url: String,
265    #[serde(default)]
266    body: Option<String>,
267    #[serde(default)]
268    published_at: Option<String>,
269    #[serde(default)]
270    draft: bool,
271    #[serde(default)]
272    prerelease: bool,
273    #[serde(default)]
274    assets: Vec<GithubAsset>,
275    /// Set only on a release known by its tag alone ([`release_from_tag`]): why there are no files.
276    #[serde(skip)]
277    limit_note: Option<String>,
278}
279
280impl Release {
281    /// A release whose file list was read from its signed manifest (`update::signed_source`) rather than from
282    /// GitHub's API: the file for this install, when the manifest has one, with the checksum the manifest
283    /// signs. The manifest has no notes, so the body carries only the upgrade floor this build knows.
284    pub(crate) fn from_signed(tag: &str, asset: Option<&ReleaseAsset>, floor: Option<&str>) -> Release {
285        Release {
286            body: floor.map(|f| format!("{FLOOR_MARKER}{f} -->")),
287            assets: asset
288                .map(|a| GithubAsset { name: a.name.clone(), size: a.size, browser_download_url: a.url.clone(), digest: Some(format!("sha256:{}", a.sha256)) })
289                .into_iter()
290                .collect(),
291            limit_note: asset.is_none().then(|| "This release has no file for this computer.".to_string()),
292            ..release_from_tag(tag, None)
293        }
294    }
295
296    /// The release with `floor` as its upgrade floor, in place of whatever its notes said: the one floor line the status reads
297    /// (`status_for`) is replaced, so the check and the download, which follow the status, see the same floor.
298    pub(crate) fn with_floor(mut self, floor: &str) -> Release {
299        let kept = self.body.as_deref().map(without_floor).filter(|b| !b.is_empty());
300        let line = format!("{FLOOR_MARKER}{floor} -->");
301        self.body = Some(match kept {
302            Some(b) => format!("{b}\n{line}"),
303            None => line,
304        });
305        self
306    }
307
308    /// The release with `body` as its notes (a test's way to set them).
309    #[cfg(test)]
310    pub(crate) fn with_body(mut self, body: &str) -> Release {
311        self.body = Some(body.to_string());
312        self
313    }
314
315    /// Whether it lists a file called `name`.
316    #[cfg(test)]
317    pub(crate) fn has_signed_file(&self, name: &str) -> bool {
318        self.assets.iter().any(|a| a.name == name)
319    }
320}
321
322/// A file attached to a GitHub release. `digest` is `sha256:<hex>`.
323#[derive(Debug, Clone, Deserialize)]
324pub(crate) struct GithubAsset {
325    name: String,
326    size: u64,
327    browser_download_url: String,
328    #[serde(default)]
329    digest: Option<String>,
330}
331
332/// The release file `name`, if the release lists it with a SHA-256 and it is
333/// served from AgentMux's own releases.
334fn find_asset(release: &Release, name: &str) -> Option<ReleaseAsset> {
335    let a = release.assets.iter().find(|a| a.name == name)?;
336    let sha256 = a.digest.as_deref()?.strip_prefix("sha256:")?.to_ascii_lowercase();
337    if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
338        return None;
339    }
340    if !a.browser_download_url.starts_with(crate::backend::update::download::RELEASE_DOWNLOAD_PREFIX) {
341        return None;
342    }
343    Some(ReleaseAsset { name: a.name.clone(), size: a.size, url: a.browser_download_url.clone(), sha256 })
344}
345
346pub(crate) use agentmux_common::update_manifest::version_core;
347
348/// Whether `offered` is a release this build may move to: both parse as `major.minor.patch`, and
349/// the offered one is above the running one. Equal is not an upgrade, and lower is a downgrade,
350/// which only a person's explicit rollback may do (there is no rollback action yet). The suffixes a
351/// release may carry (`-rc1`, `+build.5`) are not ordered releases: only the core triple decides,
352/// as everywhere else in the updater. This one rule is what the offer, the download, the restart
353/// and an agent's upgrade request all consult, so no path can install an older or equal build by
354/// itself (task #49105).
355pub(crate) fn is_newer(offered: &str, running: &str) -> bool {
356    match (version_core(offered), version_core(running)) {
357        (Some(offered), Some(running)) => offered > running,
358        _ => false,
359    }
360}
361
362/// The hidden line a release's notes carry with the oldest version it
363/// upgrades from in place (`scripts/extract-changelog.sh`, the repo's
364/// `UPGRADE_FLOOR`).
365const FLOOR_MARKER: &str = "<!-- agentmux:min-upgrade-from=";
366
367/// The release's upgrade floor, from its notes: an install older than this
368/// can't take its data forward in one start (its migrations no longer
369/// reach that far back) and installs the floor version first.
370pub(crate) fn upgrade_floor(body: &str) -> Option<String> {
371    let rest = &body[body.find(FLOOR_MARKER)? + FLOOR_MARKER.len()..];
372    let floor = rest[..rest.find("-->")?].trim();
373    version_core(floor).map(|_| floor.to_string())
374}
375
376/// `body` without the floor's line, for the notes the user reads.
377fn without_floor(body: &str) -> String {
378    body.lines().filter(|l| !l.trim_start().starts_with(FLOOR_MARKER)).collect::<Vec<_>>().join("\n").trim_end().to_string()
379}
380
381/// Whether `channel` is a `task dev` build, which runs from source and so
382/// never upgrades itself. A local `task package` build (`local-…`) is a
383/// portable like a release's, and upgrades like one.
384pub(crate) fn is_dev_build(channel: &str) -> bool {
385    channel.starts_with("dev-") || channel == "dev"
386}
387
388/// The status for a release GitHub reported, seen from `current` on `channel`
389/// for an install of `kind`.
390pub(crate) fn status_for(current: &str, channel: &str, release: &Release, now_ms: i64, kind: &InstallKind) -> AppUpdateStatus {
391    status_for_arch(current, channel, release, now_ms, kind, std::env::consts::ARCH)
392}
393
394/// [`status_for`] for a computer with CPU `arch` (`std::env::consts::ARCH`'s names), so a test of the file chosen for one arch
395/// gives the same answer on any runner (an Apple Silicon runner is `aarch64`, not `x86_64`).
396pub(crate) fn status_for_arch(current: &str, channel: &str, release: &Release, now_ms: i64, kind: &InstallKind, arch: &str) -> AppUpdateStatus {
397    let latest = release.tag_name.trim().trim_start_matches('v').to_string();
398    let state = if release.draft || release.prerelease {
399        // `releases/latest` never returns these; treat one as no news.
400        "up-to-date"
401    } else if is_dev_build(channel) {
402        "local-build"
403    } else {
404        match (version_core(&latest), version_core(current)) {
405            (Some(l), Some(c)) if l > c => "available",
406            // A feed can name a release at or below this build: one that was pulled, a stale copy
407            // served in its place, or a channel whose latest is behind where this install came
408            // from. It is not an upgrade, so it is never offered. The core triple is what is
409            // compared, so an `-rc` or a build of the running version lands here too.
410            (Some(l), Some(c)) => {
411                if l < c {
412                    tracing::info!(
413                        offered = %latest,
414                        running = %current,
415                        "update check: {latest} is older than {current}; not offering it"
416                    );
417                } else {
418                    tracing::debug!(
419                        offered = %latest,
420                        running = %current,
421                        "update check: {latest} is not newer than {current}"
422                    );
423                }
424                "up-to-date"
425            }
426            _ => "unknown",
427        }
428    };
429    let notes = release.body.as_deref().map(without_floor).map(|b| {
430        let mut end = b.len().min(MAX_NOTES_BYTES);
431        while !b.is_char_boundary(end) {
432            end -= 1;
433        }
434        b[..end].to_string()
435    });
436    let asset = kind.asset_name(&latest, arch).and_then(|n| find_asset(release, &n));
437    // Older than the release upgrades from: install the floor first.
438    let install_first = release
439        .body
440        .as_deref()
441        .and_then(upgrade_floor)
442        .filter(|floor| state == "available" && version_core(current) < version_core(floor));
443    AppUpdateStatus {
444        state: state.to_string(),
445        current: current.to_string(),
446        can_download: state == "available" && kind.can_download() && asset.is_some() && install_first.is_none(),
447        download_blocked: download_blocked(state, kind, release, asset.is_some(), install_first.is_some()),
448        install_first,
449        latest: Some(latest),
450        url: Some(release.html_url.clone()),
451        notes,
452        published_at: release.published_at.clone(),
453        checked_ms: now_ms,
454        install: kind.label().to_string(),
455        asset,
456        download: None,
457        rev: 0,
458    }
459}
460
461/// What a person is told when this install is older than the latest release can upgrade from: the one message the check
462/// and the download both give, naming the version to install first.
463pub(crate) fn install_first_message(current: &str, latest: &str, floor: &str) -> String {
464    agentmux_common::update_manifest::install_first_message(current, latest, floor)
465}
466
467static STATUS: OnceLock<RwLock<AppUpdateStatus>> = OnceLock::new();
468static EVENT_BUS: OnceLock<Arc<crate::backend::eventbus::EventBus>> = OnceLock::new();
469static INSTALL_KIND: OnceLock<InstallKind> = OnceLock::new();
470/// The client every check uses, made by [`init`].
471static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
472/// The same, but it doesn't follow redirects: the latest release page's
473/// redirect is the answer.
474static WEB_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
475/// When [`check_now`] last asked GitHub, and why it failed if it did; held
476/// while it asks, so clicks that arrive meanwhile wait for its answer.
477static LAST_CHECK_NOW: tokio::sync::Mutex<Option<(std::time::Instant, Option<String>)>> = tokio::sync::Mutex::const_new(None);
478
479/// How this AgentMux was installed, read once.
480pub(crate) fn install_kind() -> InstallKind {
481    INSTALL_KIND.get_or_init(crate::backend::update::install::detect).clone()
482}
483
484/// Record where a download stands and tell every window (`update::download`,
485/// `update::restart`). A download of a release no longer on offer (a check
486/// replaced it before the download's first step was recorded) isn't: `false`.
487/// Decided under the same lock a check's answer is, so a check and a
488/// download starting together can't each see the other's old state.
489pub(crate) fn set_download(download: Option<DownloadStatus>) -> bool {
490    let Some(bus) = EVENT_BUS.get() else { return false };
491    update(bus, |cur| with_download(cur, download))
492}
493
494/// `cur` with `download`, or `None` when it is for a release no longer on
495/// offer.
496fn with_download(cur: &AppUpdateStatus, download: Option<DownloadStatus>) -> Option<AppUpdateStatus> {
497    if download.as_ref().is_some_and(|d| cur.latest.as_deref() != Some(d.version.as_str())) {
498        return None;
499    }
500    Some(AppUpdateStatus { download, ..cur.clone() })
501}
502
503/// What srv knows now (`app.update-status`).
504pub fn current_status() -> AppUpdateStatus {
505    STATUS
506        .get()
507        .map(|s| s.read().clone())
508        .unwrap_or_else(|| AppUpdateStatus::initial(env!("CARGO_PKG_VERSION")))
509}
510
511/// The latest release's tag, from where `releases/latest` redirects to. Not
512/// the API, so not its limit.
513async fn latest_tag(web: &reqwest::Client) -> Result<String, String> {
514    let resp = web.head(LATEST_PAGE_URL).send().await.map_err(|e| e.to_string())?;
515    let location = resp
516        .headers()
517        .get(reqwest::header::LOCATION)
518        .and_then(|v| v.to_str().ok())
519        .ok_or_else(|| format!("GitHub answered {} without a redirect", resp.status()))?;
520    tag_from_location(location).ok_or_else(|| "GitHub's latest release page didn't name a release".to_string())
521}
522
523/// The release tag a redirect to `location` names: only AgentMux's own
524/// releases page, and only a tag that is a version.
525fn tag_from_location(location: &str) -> Option<String> {
526    let rest = location
527        .strip_prefix(RELEASE_PAGE_PREFIX)
528        .or_else(|| location.strip_prefix("/agentmuxai/agentmux/releases/tag/"))?;
529    let tag = rest.split(['?', '#']).next()?.trim_end_matches('/');
530    version_core(tag).map(|_| tag.to_string())
531}
532
533/// When GitHub's API said to stop (unix ms), 0 when it hasn't.
534static API_LIMITED_UNTIL_MS: AtomicI64 = AtomicI64::new(0);
535/// The release the API last gave, with its ETag.
536static RELEASE_CACHE: parking_lot::Mutex<Option<(Option<String>, Release)>> = parking_lot::Mutex::new(None);
537
538/// How a check gets the release's files and notes.
539#[derive(Debug, PartialEq, Eq)]
540enum Plan {
541    /// The release already held is the latest: ask nothing.
542    UseCache,
543    /// Ask the API, with this ETag when one is held.
544    Api(Option<String>),
545    /// The API is off limits until later: report the release by its tag.
546    Degraded,
547    /// Nothing to go on: the page didn't answer and the API is off limits.
548    Limited,
549}
550
551fn plan(tag: Option<&str>, cached: Option<&(Option<String>, Release)>, limited_until_ms: i64, now_ms: i64) -> Plan {
552    if let (Some(tag), Some((_, release))) = (tag, cached) {
553        if release.tag_name == tag {
554            return Plan::UseCache;
555        }
556    }
557    if now_ms < limited_until_ms {
558        return if tag.is_some() { Plan::Degraded } else { Plan::Limited };
559    }
560    Plan::Api(cached.and_then(|(etag, _)| etag.clone()))
561}
562
563/// When a refusal says the limit lifts (unix ms): `Retry-After`, else the
564/// rate-limit reset, else a guess; never sooner than a minute from now.
565/// `None` when the refusal isn't about a limit at all.
566fn limited_until(status: u16, headers: &reqwest::header::HeaderMap, now_ms: i64) -> Option<i64> {
567    let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).map(str::trim);
568    let retry_after_s = header("retry-after").and_then(|v| v.parse::<i64>().ok());
569    let out_of_calls = header("x-ratelimit-remaining") == Some("0");
570    if status != 429 && retry_after_s.is_none() && !out_of_calls {
571        return None;
572    }
573    let until = retry_after_s
574        .map(|s| now_ms + s * 1000)
575        .or_else(|| header("x-ratelimit-reset").and_then(|v| v.parse::<i64>().ok()).map(|s| s * 1000))
576        .unwrap_or(now_ms + 15 * 60_000);
577    Some(until.max(now_ms + 60_000))
578}
579
580/// How long GitHub's limit on this computer still has to run, when it is in force.
581pub(crate) fn limited_for() -> Option<std::time::Duration> {
582    let left = API_LIMITED_UNTIL_MS.load(Ordering::Relaxed) - agentmux_common::time::now_ms();
583    u64::try_from(left).ok().filter(|ms| *ms > 0).map(std::time::Duration::from_millis)
584}
585
586/// What the person is told while GitHub limits the check.
587fn limited_message(until_ms: i64) -> String {
588    let at = chrono::DateTime::from_timestamp_millis(until_ms)
589        .map(|t| t.with_timezone(&chrono::Local).format("%H:%M").to_string())
590        .unwrap_or_else(|| "later".to_string());
591    format!("GitHub is limiting update checks from this computer; try again after {at}")
592}
593
594/// A release known only by its tag.
595pub(crate) fn release_from_tag(tag: &str, note: Option<String>) -> Release {
596    Release {
597        tag_name: tag.to_string(),
598        html_url: format!("{RELEASE_PAGE_PREFIX}{tag}"),
599        body: note.clone(),
600        published_at: None,
601        draft: false,
602        prerelease: false,
603        assets: Vec::new(),
604        limit_note: note,
605    }
606}
607
608/// The note a release known only by its tag carries.
609fn degraded_note(until_ms: i64) -> String {
610    format!("{}. The download is offered once GitHub answers.", limited_message(until_ms))
611}
612
613enum ApiAnswer {
614    Fresh(Box<Release>, Option<String>),
615    NotModified,
616}
617
618enum ApiMiss {
619    /// Refused for a limit, until this time (unix ms).
620    Limited(i64),
621    Other(String),
622}
623
624async fn api_get(client: &reqwest::Client, etag: Option<&str>, now_ms: i64) -> Result<ApiAnswer, ApiMiss> {
625    let mut req = client.get(LATEST_RELEASE_URL).header(reqwest::header::ACCEPT, "application/vnd.github+json");
626    if let Some(etag) = etag {
627        req = req.header(reqwest::header::IF_NONE_MATCH, etag);
628    }
629    let resp = req.send().await.map_err(|e| ApiMiss::Other(e.to_string()))?;
630    let status = resp.status();
631    if status == reqwest::StatusCode::NOT_MODIFIED {
632        return Ok(ApiAnswer::NotModified);
633    }
634    if !status.is_success() {
635        if matches!(status.as_u16(), 403 | 429) {
636            if let Some(until) = limited_until(status.as_u16(), resp.headers(), now_ms) {
637                return Err(ApiMiss::Limited(until));
638            }
639        }
640        return Err(ApiMiss::Other(format!("GitHub answered {status}")));
641    }
642    let etag = resp.headers().get(reqwest::header::ETAG).and_then(|v| v.to_str().ok()).map(str::to_string);
643    let release = resp.json::<Release>().await.map_err(|e| ApiMiss::Other(e.to_string()))?;
644    Ok(ApiAnswer::Fresh(Box::new(release), etag))
645}
646
647/// The upgrade floor of the repo when this build was made (`UPGRADE_FLOOR`): a floor only rises, so no later
648/// release's is lower.
649const BUILD_FLOOR: &str = include_str!("../../../../../UPGRADE_FLOOR");
650
651/// [`BUILD_FLOOR`] when it is a version.
652pub(crate) fn build_floor() -> Option<&'static str> {
653    Some(BUILD_FLOOR.trim()).filter(|f| version_core(f).is_some())
654}
655
656/// The oldest version known to upgrade in place: this build's own floor, or a later one an answer from the API
657/// carried. A signed manifest doesn't carry one.
658fn known_floor() -> Option<String> {
659    let built = Some(BUILD_FLOOR.trim().to_string()).filter(|f| version_core(f).is_some());
660    let cached = RELEASE_CACHE.lock().as_ref().and_then(|(_, r)| r.body.as_deref().and_then(upgrade_floor));
661    [built, cached].into_iter().flatten().max_by_key(|f| version_core(f))
662}
663
664/// The release `tag` names, while the API gives no answer (it limits this computer or failed): its files and
665/// checksums from the signed manifest at its download address (`update::signed_source`). `None` when that
666/// gives no answer either: the release stays known by its tag.
667async fn release_without_api(client: &reqwest::Client, tag: &str, limited_until_ms: i64, now_ms: i64) -> Option<Release> {
668    use crate::backend::update::signed_source::{release_for, Got};
669    match release_for(client, tag, env!("CARGO_PKG_VERSION"), &install_kind(), known_floor().as_deref(), limited_until_ms, now_ms).await {
670        Got::Release(r) => Some(r),
671        Got::NothingNew => Some(release_from_tag(tag, None)),
672        Got::None => None,
673    }
674}
675
676/// The latest release as the check sees it: from GitHub ([`fetch_latest_from_github`]), with its upgrade floor taken from
677/// its signed manifest when that carries a usable one (`SPEC_UPGRADE_FLOOR_IN_SIGNED_MANIFEST`): the higher of the signed
678/// floor and this build's, with the notes' floor line not consulted. A release no newer than this build, or one whose
679/// manifest has no usable floor, is left as GitHub said.
680async fn fetch_latest(client: &reqwest::Client, web: &reqwest::Client) -> Result<Release, String> {
681    use crate::backend::update::signed_source::{newer_than, signed_floor_for, signed_floor_in_force};
682    let release = fetch_latest_from_github(client, web).await?;
683    let current = env!("CARGO_PKG_VERSION");
684    if !newer_than(&release.tag_name, current) {
685        return Ok(release);
686    }
687    let signed = signed_floor_for(client, &release.tag_name, agentmux_common::time::now_ms()).await;
688    Ok(match signed_floor_in_force(build_floor(), &signed) {
689        Some(floor) => release.with_floor(&floor),
690        None => release,
691    })
692}
693
694/// The latest release, with as few calls to GitHub's API as possible (see the
695/// module doc). The error is what the person is told.
696async fn fetch_latest_from_github(client: &reqwest::Client, web: &reqwest::Client) -> Result<Release, String> {
697    let now_ms = agentmux_common::time::now_ms();
698    let tag = match latest_tag(web).await {
699        Ok(t) => Some(t),
700        Err(e) => {
701            tracing::debug!(error = %e, "update check: the latest page didn't name a release; asking the API");
702            None
703        }
704    };
705    let cached = RELEASE_CACHE.lock().clone();
706    let limited = API_LIMITED_UNTIL_MS.load(Ordering::Relaxed);
707    match plan(tag.as_deref(), cached.as_ref(), limited, now_ms) {
708        Plan::UseCache => cached.map(|(_, r)| r).ok_or_else(|| "no release held".to_string()),
709        Plan::Degraded => {
710            let tag = tag.as_deref().unwrap_or_default();
711            Ok(release_without_api(client, tag, limited, now_ms).await.unwrap_or_else(|| release_from_tag(tag, Some(degraded_note(limited)))))
712        }
713        Plan::Limited => Err(limited_message(limited)),
714        Plan::Api(etag) => match api_get(client, etag.as_deref(), now_ms).await {
715            Ok(ApiAnswer::Fresh(release, etag)) => {
716                *RELEASE_CACHE.lock() = Some((etag, (*release).clone()));
717                Ok(*release)
718            }
719            Ok(ApiAnswer::NotModified) => cached.map(|(_, r)| r).ok_or_else(|| "GitHub said nothing changed".to_string()),
720            Err(ApiMiss::Limited(until)) => {
721                API_LIMITED_UNTIL_MS.store(until, Ordering::Relaxed);
722                tracing::info!(until_ms = until, "update check: GitHub's API is limiting this computer");
723                match tag {
724                    Some(tag) => Ok(release_without_api(client, &tag, until, now_ms).await.unwrap_or_else(|| release_from_tag(&tag, Some(degraded_note(until))))),
725                    None => Err(limited_message(until)),
726                }
727            }
728            Err(ApiMiss::Other(e)) => match tag {
729                Some(tag) => release_without_api(client, &tag, 0, now_ms).await.ok_or_else(|| format!("couldn't reach GitHub: {e}")),
730                None => Err(format!("couldn't reach GitHub: {e}")),
731            },
732        },
733    }
734}
735
736/// Get ready to check (`bootstrap::background`). Asks nothing itself: `update::auto` and the user ask.
737pub fn init(event_bus: Arc<crate::backend::eventbus::EventBus>) {
738    let current = env!("CARGO_PKG_VERSION");
739    let _ = STATUS.set(RwLock::new(AppUpdateStatus::initial(current)));
740    let _ = EVENT_BUS.set(event_bus);
741    match crate::http_client::builder()
742        .user_agent(format!("AgentMux/{current}"))
743        .timeout(REQUEST_TIMEOUT)
744        .build()
745    {
746        Ok(c) => {
747            let _ = CLIENT.set(c);
748        }
749        Err(e) => tracing::warn!(error = %e, "update check: no HTTP client, can't check"),
750    }
751    if let Ok(c) = crate::http_client::builder()
752        .user_agent(format!("AgentMux/{current}"))
753        .timeout(REQUEST_TIMEOUT)
754        .redirect(reqwest::redirect::Policy::none())
755        .build()
756    {
757        let _ = WEB_CLIENT.set(c);
758    }
759}
760
761/// Ask GitHub now, for the user's **Check for update** or an agent's `App`
762/// `version` or `upgrade`, and return what srv knows after. Asked again within
763/// [`CHECK_NOW_EVERY`], it answers what the last check found, its failure
764/// included; concurrent callers share one request.
765pub async fn check_now() -> Result<AppUpdateStatus, String> {
766    let (Some(client), Some(web), Some(bus)) = (CLIENT.get(), WEB_CLIENT.get(), EVENT_BUS.get()) else {
767        return Err("AgentMux isn't checking for updates yet; try again in a moment".into());
768    };
769    let mut last = LAST_CHECK_NOW.lock().await;
770    if let Some((_, failed)) = last.as_ref().filter(|(at, _)| at.elapsed() < CHECK_NOW_EVERY) {
771        return failed.clone().map_or_else(|| Ok(current_status()), Err);
772    }
773    let current = env!("CARGO_PKG_VERSION");
774    let channel = crate::backend::reactive::registry::local_channel_id();
775    let outcome = match fetch_latest(client, web).await {
776        Ok(release) => {
777            let next = status_for(current, &channel, &release, agentmux_common::time::now_ms(), &install_kind());
778            publish_check(bus, next);
779            Ok(current_status())
780        }
781        Err(e) => {
782            tracing::info!(error = %e, "update check: asked now, no answer");
783            Err(e)
784        }
785    };
786    *last = Some((std::time::Instant::now(), outcome.as_ref().err().cloned()));
787    outcome
788}
789
790/// The release a download or restart under way is installing, when `next`
791/// would replace it with another: that one finishes first, and a check after
792/// it offers the newer release.
793fn pinned_by_upgrade(cur: &AppUpdateStatus, next: &AppUpdateStatus) -> Option<String> {
794    let d = cur.download.as_ref()?;
795    let under_way = matches!(d.state.as_str(), "downloading" | "unpacking" | "waiting" | "restarting");
796    (under_way && next.latest.as_deref() != Some(d.version.as_str())).then(|| d.version.clone())
797}
798
799/// A check's answer: it replaces what srv knows, unless an upgrade under way
800/// pins the release on offer ([`pinned_by_upgrade`]). A new check keeps a
801/// download of the release it still reports.
802fn publish_check(event_bus: &crate::backend::eventbus::EventBus, next: AppUpdateStatus) {
803    // Read (and removed) once, here: the closure below may run more than once.
804    let install_failure = match (&next.latest, &next.asset, matches!(install_kind(), InstallKind::LinuxPackage { .. })) {
805        (Some(version), Some(asset), true) if next.state == "available" && next.download.is_none() => {
806            let updates = crate::backend::update::download::updates_root();
807            crate::backend::update::restart::take_install_failure(&updates, version).map(|error| {
808                // The release file is still there: the panel offers the restart again, with the
809                // reason above it (a "failed" download would say "Download failed" and fetch it again).
810                let staged = crate::backend::update::download::installer_path(&updates.join(version), asset);
811                let kept = crate::backend::update::download::is_staged_installer(&staged, asset);
812                DownloadStatus {
813                    version: version.clone(),
814                    state: if kept { "ready" } else { "failed" }.into(),
815                    received: if kept { asset.size } else { 0 },
816                    total: asset.size,
817                    error: Some(error),
818                    folder: None,
819                    installer: kept.then(|| staged.display().to_string()),
820                    waiting_for: 0,
821                    waiting_on: Vec::new(),
822                    stopping: Vec::new(),
823                    not_confirmed_at: None,
824                    not_confirmed: None,
825                }
826            })
827        }
828        _ => None,
829    };
830    update(event_bus, |cur| {
831        if let Some(version) = pinned_by_upgrade(cur, &next) {
832            tracing::info!(latest = ?next.latest, version, "update check: a newer release is out; the upgrade under way finishes first");
833            return None;
834        }
835        let mut next = next.clone();
836        if next.download.is_none() && next.latest.is_some() && next.latest == cur.latest {
837            next.download = cur.download.clone();
838        }
839        // A `.deb`/`.rpm` upgrade that didn't finish left its reason (the old version
840        // runs again): the panel says why, rather than offering it as if untried.
841        if next.download.is_none() {
842            next.download = install_failure.clone();
843        }
844        Some(next)
845    });
846}
847
848/// The `rev` of the change after the one numbered `last`, made at `now_ms`: the time, and always higher than `last`.
849fn rev_after(last: u64, now_ms: u64) -> u64 {
850    now_ms.max(last + 1)
851}
852
853/// Replace what srv knows with what `change` makes of it (`None`: leave it),
854/// in one step under the lock, and tell every window when it changed.
855/// Whether it was replaced.
856fn update(
857    event_bus: &crate::backend::eventbus::EventBus,
858    change: impl FnOnce(&AppUpdateStatus) -> Option<AppUpdateStatus>,
859) -> bool {
860    let Some(lock) = STATUS.get() else { return false };
861    let next = {
862        let mut cur = lock.write();
863        let Some(mut next) = change(&cur) else { return false };
864        // A new check time alone is news to every window: the panel shows
865        // when the last check was, whoever asked for it.
866        next.rev = cur.rev;
867        let same = next == *cur;
868        if !same {
869            next.rev = rev_after(cur.rev, agentmux_common::time::now_ms_u64());
870        }
871        // Download progress is news to a window, not to the log.
872        let step = |s: &AppUpdateStatus| (s.state.clone(), s.latest.clone(), s.download.as_ref().map(|d| d.state.clone()));
873        if step(&cur) != step(&next) {
874            tracing::info!(
875                state = %next.state,
876                latest = ?next.latest,
877                download = ?next.download.as_ref().map(|d| d.state.as_str()),
878                "update check: status changed"
879            );
880        }
881        *cur = next.clone();
882        (!same).then_some(next)
883    };
884    if let Some(next) = next {
885        event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<
886            crate::backend::mps_events::AppUpdateStatusChanged,
887        >(&next, String::new()));
888    }
889    true
890}
891
892#[cfg(test)]
893mod tests {
894    use super::*;
895
896    #[test]
897    fn every_change_gets_a_higher_rev_than_the_one_before() {
898        assert_eq!(rev_after(0, 1_000), 1_000);
899        assert_eq!(rev_after(1_000, 1_000), 1_001, "two changes in one millisecond");
900        assert_eq!(rev_after(1_001, 900), 1_002, "a clock that went back");
901    }
902
903    fn release(tag: &str) -> Release {
904        Release {
905            tag_name: tag.into(),
906            html_url: format!("https://github.com/agentmuxai/agentmux/releases/tag/{tag}"),
907            body: Some("- Sysinfo opens on a new Overview".into()),
908            published_at: Some("2026-10-15T10:28:48Z".into()),
909            draft: false,
910            prerelease: false,
911            assets: Vec::new(),
912            limit_note: None,
913        }
914    }
915
916    #[test]
917    fn only_a_version_tag_on_agentmuxs_own_releases_page_is_a_release() {
918        let ok = "https://github.com/agentmuxai/agentmux/releases/tag/v0.60.1";
919        assert_eq!(tag_from_location(ok).as_deref(), Some("v0.60.1"));
920        assert_eq!(tag_from_location("/agentmuxai/agentmux/releases/tag/v0.60.1").as_deref(), Some("v0.60.1"));
921        assert_eq!(tag_from_location(&format!("{ok}?x=1")).as_deref(), Some("v0.60.1"));
922        assert_eq!(tag_from_location("https://evil.example/agentmuxai/agentmux/releases/tag/v0.60.1"), None);
923        assert_eq!(tag_from_location("https://github.com/other/repo/releases/tag/v0.60.1"), None);
924        assert_eq!(tag_from_location("https://github.com/agentmuxai/agentmux/releases/tag/nightly"), None);
925        assert_eq!(tag_from_location("https://github.com/agentmuxai/agentmux/releases"), None);
926    }
927
928    #[test]
929    fn the_release_already_held_asks_nothing_and_a_new_tag_asks_the_api_with_the_etag() {
930        let held = (Some("\"abc\"".to_string()), release("v0.60.0"));
931        assert_eq!(plan(Some("v0.60.0"), Some(&held), 0, 1_000), Plan::UseCache);
932        assert_eq!(plan(Some("v0.60.1"), Some(&held), 0, 1_000), Plan::Api(Some("\"abc\"".into())));
933        assert_eq!(plan(None, Some(&held), 0, 1_000), Plan::Api(Some("\"abc\"".into())));
934        assert_eq!(plan(Some("v0.60.0"), None, 0, 1_000), Plan::Api(None));
935    }
936
937    #[test]
938    fn while_the_api_is_limited_a_known_tag_is_reported_and_nothing_is_asked() {
939        let held = (None, release("v0.60.0"));
940        assert_eq!(plan(Some("v0.60.1"), Some(&held), 5_000, 1_000), Plan::Degraded);
941        assert_eq!(plan(Some("v0.60.0"), Some(&held), 5_000, 1_000), Plan::UseCache, "held and current: no call at all");
942        assert_eq!(plan(None, None, 5_000, 1_000), Plan::Limited);
943        assert_eq!(plan(Some("v0.60.1"), None, 5_000, 6_000), Plan::Api(None), "the limit lifted");
944    }
945
946    #[test]
947    fn a_refusal_names_when_the_limit_lifts_and_a_plain_403_is_not_a_limit() {
948        use reqwest::header::{HeaderMap, HeaderValue};
949        let h = |pairs: &[(&'static str, String)]| {
950            let mut m = HeaderMap::new();
951            for (k, v) in pairs {
952                m.insert(*k, HeaderValue::from_str(v).unwrap());
953            }
954            m
955        };
956        let now = 1_000_000_000_000_i64;
957        let reset = (now / 1000 + 1800).to_string();
958        let out = h(&[("x-ratelimit-remaining", "0".into()), ("x-ratelimit-reset", reset)]);
959        assert_eq!(limited_until(403, &out, now), Some(now + 1_800_000));
960        assert_eq!(limited_until(429, &h(&[("retry-after", "120".into())]), now), Some(now + 120_000));
961        assert_eq!(limited_until(429, &h(&[]), now), Some(now + 15 * 60_000), "no header: a guess");
962        assert_eq!(limited_until(429, &h(&[("retry-after", "1".into())]), now), Some(now + 60_000), "never sooner than a minute");
963        assert_eq!(limited_until(403, &h(&[("x-ratelimit-remaining", "12".into())]), now), None, "403 with calls left is a refusal, not a limit");
964        assert_eq!(limited_until(403, &h(&[]), now), None);
965    }
966
967    #[test]
968    fn the_message_for_a_limit_says_what_is_happening_not_403() {
969        let m = limited_message(1_000_000_000_000);
970        assert!(m.starts_with("GitHub is limiting update checks from this computer; try again after "), "{m}");
971        assert!(!m.contains("403"), "{m}");
972    }
973
974    #[test]
975    fn a_release_known_only_by_its_tag_is_still_news_but_not_a_download() {
976        let r = release_from_tag("v99.0.0", Some(degraded_note(1_000_000_000_000)));
977        let st = status_for("0.59.41", "stable", &r, 1, &InstallKind::Unknown);
978        assert_eq!(st.state, "available");
979        assert_eq!(st.latest.as_deref(), Some("99.0.0"));
980        assert_eq!(st.url.as_deref(), Some("https://github.com/agentmuxai/agentmux/releases/tag/v99.0.0"));
981        assert!(!st.can_download && st.asset.is_none(), "nothing to download without the API's checksum");
982        assert!(st.notes.as_deref().is_some_and(|n| n.contains("limiting update checks")));
983    }
984
985    #[test]
986    fn a_release_that_cannot_be_downloaded_says_why_for_an_install_that_normally_could() {
987        let setup = InstallKind::WindowsSetup;
988        // Known only by its tag (GitHub limiting the check): the reason is the limit's own note.
989        let degraded = release_from_tag("v99.0.0", Some(degraded_note(1_000_000_000_000)));
990        let why = status_for("0.59.41", "stable", &degraded, 1, &setup).download_blocked.unwrap();
991        assert!(why.starts_with("GitHub is limiting update checks from this computer; try again after "), "{why}");
992        // No note at all: still a reason, never none.
993        assert!(status_for("0.59.41", "stable", &release_from_tag("v99.0.0", None), 1, &setup).download_blocked.is_some());
994        // A release with files, but none for this computer.
995        let other = with_asset(release("v99.0.0"), "agentmux-99.0.0-arm64.zip", Some("sha256:00"), "https://github.com/agentmuxai/agentmux/releases/download/v99.0.0/x");
996        assert_eq!(status_for("0.59.41", "stable", &other, 1, &setup).download_blocked.as_deref(), Some("This release has no file for this computer."));
997        // A macOS app that can't be replaced where it is names where and why.
998        let mac = InstallKind::MacApp { app: "/Applications/AgentMux.app".into(), blocked: Some("it is on a read-only volume".into()) };
999        let blocked = status_for("0.59.41", "stable", &release("v99.0.0"), 1, &mac).download_blocked.unwrap();
1000        assert_eq!(blocked, "This install can't upgrade itself where it is: it is on a read-only volume.");
1001        // ...also when the release does list its file (the usual case): the file is there, the app can't be replaced.
1002        // (Asked directly with the file found, so the test doesn't depend on the architecture it runs on.)
1003        let with_file = download_blocked("available", &mac, &release("v99.0.0"), true, false);
1004        assert_eq!(with_file.as_deref(), Some("This install can't upgrade itself where it is: it is on a read-only volume."));
1005        // An install that can replace itself, with its file found, has nothing to say.
1006        assert_eq!(download_blocked("available", &InstallKind::WindowsSetup, &release("v99.0.0"), true, false), None);
1007    }
1008
1009    #[test]
1010    fn a_release_whose_files_are_not_up_yet_never_shows_its_notes_as_the_reason() {
1011        // A real release with an empty file list and a changelog (and the floor line): the reason is the plain one.
1012        let notes = "- A long changelog line\n<!-- agentmux:min-upgrade-from=0.50.0 -->\n".repeat(2000);
1013        let not_up_yet = Release { body: Some(notes), ..release("v99.0.0") };
1014        let why = status_for("0.59.41", "stable", &not_up_yet, 1, &InstallKind::WindowsSetup).download_blocked.unwrap();
1015        assert_eq!(why, "The release's file list isn't available yet.");
1016    }
1017
1018    #[test]
1019    fn nothing_is_blocked_when_it_can_download_or_never_downloads_or_there_is_nothing_to_offer() {
1020        let degraded = release_from_tag("v99.0.0", Some(degraded_note(1_000_000_000_000)));
1021        // The Store and an unknown install never download in the app: the page is their way, not a fault.
1022        for kind in [InstallKind::WindowsStore, InstallKind::Unknown] {
1023            assert_eq!(status_for("0.59.41", "stable", &degraded, 1, &kind).download_blocked, None, "{kind:?}");
1024        }
1025        // Up to date, or older than the release upgrades from: not this.
1026        assert_eq!(status_for("99.0.0", "stable", &degraded, 1, &InstallKind::WindowsSetup).download_blocked, None);
1027        let floor = Release { body: Some("<!-- agentmux:min-upgrade-from=98.0.0 -->".into()), ..release_from_tag("v99.0.0", None) };
1028        let st = status_for("0.57.0", "stable", &floor, 1, &InstallKind::WindowsSetup);
1029        assert_eq!(st.install_first.as_deref(), Some("98.0.0"));
1030        assert_eq!(st.download_blocked, None);
1031        // The released status says nothing before any check.
1032        assert_eq!(AppUpdateStatus::initial("0.59.26").download_blocked, None);
1033    }
1034
1035    #[test]
1036    fn a_newer_release_is_available_on_a_release_build() {
1037        let s = status_for("0.59.26", "stable", &release("v0.59.27"), 5, &InstallKind::Unknown);
1038        assert_eq!(s.state, "available");
1039        assert_eq!(s.latest.as_deref(), Some("0.59.27"));
1040        assert_eq!(s.current, "0.59.26");
1041        assert!(s.url.unwrap().ends_with("/v0.59.27"));
1042        assert_eq!(s.checked_ms, 5);
1043        assert_eq!(s.notes.as_deref(), Some("- Sysinfo opens on a new Overview"));
1044    }
1045
1046    #[test]
1047    fn the_same_or_an_older_release_is_up_to_date() {
1048        assert_eq!(status_for("0.59.27", "stable", &release("v0.59.27"), 0, &InstallKind::Unknown).state, "up-to-date");
1049        assert_eq!(status_for("0.60.0", "stable", &release("v0.59.27"), 0, &InstallKind::Unknown).state, "up-to-date");
1050        // Numbers, not text: 0.59.100 is newer than 0.59.27.
1051        assert_eq!(status_for("0.59.27", "stable", &release("v0.59.100"), 0, &InstallKind::Unknown).state, "available");
1052        assert_eq!(status_for("0.59.100", "stable", &release("v0.59.27"), 0, &InstallKind::Unknown).state, "up-to-date");
1053    }
1054
1055    #[test]
1056    fn only_a_higher_core_version_is_an_upgrade_and_rc_or_build_suffixes_do_not_order_releases() {
1057        // 0.60.9 -> 0.60.10 is an upgrade; the reverse and the equal case are not.
1058        assert!(is_newer("0.60.10", "0.60.9"));
1059        assert!(!is_newer("0.60.9", "0.60.10"));
1060        assert!(!is_newer("0.60.10", "0.60.10"));
1061        // A leading `v`, as the releases API writes it.
1062        assert!(is_newer("v0.60.10", "0.60.9"));
1063        // The project's suffixes are not ordered releases: an `-rc` or `+build` of the running
1064        // version is that same release, and one of the next version is the next release.
1065        assert!(!is_newer("0.60.10-rc1", "0.60.10"));
1066        assert!(is_newer("0.60.10-rc1", "0.60.9"));
1067        assert!(!is_newer("0.60.10+build.5", "0.60.10"));
1068        assert!(is_newer("0.60.10+build.5", "0.60.9"));
1069        // Anything that isn't a plain core triple is not an upgrade this updater makes.
1070        assert!(!is_newer("nightly", "0.60.9"));
1071        assert!(!is_newer("0.60.10.1", "0.60.9"));
1072        assert!(!is_newer("0.60.10", "weird"));
1073    }
1074
1075    #[test]
1076    fn the_offer_never_names_an_older_or_equal_release_as_an_upgrade() {
1077        let unknown = InstallKind::Unknown;
1078        // A stale copy, a pulled release or a channel whose latest is behind: not an offer.
1079        assert_eq!(status_for("0.60.10", "stable", &release("v0.60.9"), 0, &unknown).state, "up-to-date");
1080        assert_eq!(status_for("0.60.10", "stable", &release("v0.60.10"), 0, &unknown).state, "up-to-date");
1081        // The suffixes the project uses do not turn the running version into an upgrade, and an
1082        // `-rc` of the next version is that next version.
1083        assert_eq!(status_for("0.60.10", "stable", &release("v0.60.10-rc1"), 0, &unknown).state, "up-to-date");
1084        assert_eq!(status_for("0.60.9", "stable", &release("v0.60.10-rc1"), 0, &unknown).state, "available");
1085    }
1086
1087    #[test]
1088    fn a_dev_build_only_reports_the_latest_release() {
1089        for channel in ["dev-qtest-x-38b2af", "dev"] {
1090            let s = status_for("0.59.26", channel, &release("v0.59.27"), 0, &InstallKind::Unknown);
1091            assert_eq!(s.state, "local-build", "{channel}");
1092            assert_eq!(s.latest.as_deref(), Some("0.59.27"));
1093        }
1094    }
1095
1096    #[test]
1097    fn a_local_package_build_upgrades_like_a_release() {
1098        let local = "local-main-b28b7a-f62415cd";
1099        assert_eq!(status_for("0.59.26", local, &release("v0.59.27"), 0, &InstallKind::Unknown).state, "available");
1100        // Built from main, ahead of the latest release: nothing to upgrade to.
1101        assert_eq!(status_for("0.59.28", local, &release("v0.59.27"), 0, &InstallKind::Unknown).state, "up-to-date");
1102    }
1103
1104    #[test]
1105    fn versions_that_dont_parse_are_never_called_newer() {
1106        assert_eq!(status_for("0.59.26", "stable", &release("nightly"), 0, &InstallKind::Unknown).state, "unknown");
1107        assert_eq!(status_for("weird", "stable", &release("v0.59.27"), 0, &InstallKind::Unknown).state, "unknown");
1108        let mut pre = release("v0.60.0-rc1");
1109        pre.prerelease = true;
1110        assert_eq!(status_for("0.59.26", "stable", &pre, 0, &InstallKind::Unknown).state, "up-to-date");
1111        assert_eq!(version_core("v0.59.27+g1a2b"), Some((0, 59, 27)));
1112        assert_eq!(version_core("0.59"), None);
1113        assert_eq!(version_core("0.59.27.1"), None);
1114    }
1115
1116    #[test]
1117    fn an_install_older_than_the_release_upgrades_from_installs_the_floor_first() {
1118        let kind = InstallKind::WindowsPortable { root: "C:/apps/agentmux".into() };
1119        let name = "agentmux-0.60.0-x64-portable.7z";
1120        let url = format!("https://github.com/agentmuxai/agentmux/releases/download/v0.60.0/{name}");
1121        let mut r = with_asset(release("v0.60.0"), name, Some(&format!("sha256:{}", "ab".repeat(32))), &url);
1122        r.body = Some("- Faster startup\n\n<!-- agentmux:min-upgrade-from=0.58.0 -->".into());
1123        let old = status_for("0.57.3", "stable", &r, 0, &kind);
1124        assert_eq!((old.state.as_str(), old.install_first.as_deref(), old.can_download), ("available", Some("0.58.0"), false));
1125        assert_eq!(old.notes.as_deref(), Some("- Faster startup"), "the floor's line isn't shown");
1126        // At or above the floor: as before.
1127        for current in ["0.58.0", "0.59.31"] {
1128            let s = status_for(current, "stable", &r, 0, &kind);
1129            assert_eq!(s.install_first, None, "{current}");
1130            assert_eq!(s.can_download, std::env::consts::ARCH == "x86_64", "{current}");
1131        }
1132        assert_eq!(upgrade_floor("notes\n<!-- agentmux:min-upgrade-from= 0.55.0 -->"), Some("0.55.0".into()));
1133        assert_eq!(upgrade_floor("<!-- agentmux:min-upgrade-from=soon -->"), None);
1134        assert_eq!(upgrade_floor("no floor"), None);
1135    }
1136
1137    #[test]
1138    fn long_notes_are_cut_on_a_character_boundary() {
1139        let mut r = release("v0.59.27");
1140        r.body = Some("é".repeat(MAX_NOTES_BYTES));
1141        let notes = status_for("0.59.26", "stable", &r, 0, &InstallKind::Unknown).notes.unwrap();
1142        assert!(notes.len() <= MAX_NOTES_BYTES);
1143        assert!(notes.chars().all(|c| c == 'é'));
1144    }
1145
1146    #[test]
1147    fn the_status_reads_as_the_ui_expects() {
1148        let s = status_for("0.59.26", "stable", &release("v0.59.27"), 7, &InstallKind::Unknown);
1149        let v = serde_json::to_value(&s).unwrap();
1150        assert_eq!(v["state"], "available");
1151        assert_eq!(v["checked_ms"], 7);
1152        let mut unchecked = serde_json::to_value(AppUpdateStatus::initial("0.59.26")).unwrap();
1153        unchecked.as_object_mut().unwrap().remove("install");
1154        assert_eq!(unchecked, serde_json::json!({ "state": "unknown", "current": "0.59.26", "checked_ms": 0, "can_download": false }));
1155    }
1156
1157    #[test]
1158    fn a_check_doesnt_replace_the_release_an_upgrade_is_installing() {
1159        let download = |state: &str| DownloadStatus {
1160            version: "0.59.27".into(),
1161            state: state.into(),
1162            received: 1,
1163            total: 2,
1164            error: None,
1165            folder: None,
1166            installer: None,
1167            waiting_for: 0,
1168            waiting_on: Vec::new(),
1169            stopping: Vec::new(),
1170            not_confirmed_at: None,
1171            not_confirmed: None,
1172        };
1173        let newer = status_for("0.59.26", "stable", &release("v0.59.28"), 9, &InstallKind::Unknown);
1174        let same = status_for("0.59.26", "stable", &release("v0.59.27"), 9, &InstallKind::Unknown);
1175        let mut cur = status_for("0.59.26", "stable", &release("v0.59.27"), 1, &InstallKind::Unknown);
1176        for state in ["downloading", "unpacking", "waiting", "restarting"] {
1177            cur.download = Some(download(state));
1178            assert_eq!(pinned_by_upgrade(&cur, &newer).as_deref(), Some("0.59.27"), "{state}");
1179            assert_eq!(pinned_by_upgrade(&cur, &same), None, "{state}: the same release is no change");
1180        }
1181        // Downloaded but not restarting, failed, or nothing asked: the newer one is offered.
1182        for state in ["ready", "failed"] {
1183            cur.download = Some(download(state));
1184            assert_eq!(pinned_by_upgrade(&cur, &newer), None, "{state}");
1185        }
1186        cur.download = None;
1187        assert_eq!(pinned_by_upgrade(&cur, &newer), None);
1188
1189        // A download of the release a check has since replaced isn't recorded.
1190        let mut d = download("downloading");
1191        assert!(with_download(&cur, Some(d.clone())).is_some_and(|s| s.download.is_some()));
1192        assert!(with_download(&newer, Some(d.clone())).is_none(), "0.59.27's download on a 0.59.28 offer");
1193        d.version = "0.59.28".into();
1194        assert!(with_download(&newer, Some(d)).is_some());
1195        assert!(with_download(&newer, None).is_some_and(|s| s.download.is_none()), "clearing is always allowed");
1196    }
1197
1198    fn with_asset(mut r: Release, name: &str, digest: Option<&str>, url: &str) -> Release {
1199        r.assets.push(GithubAsset {
1200            name: name.into(),
1201            size: 124_705_866,
1202            browser_download_url: url.into(),
1203            digest: digest.map(Into::into),
1204        });
1205        r
1206    }
1207
1208    #[test]
1209    fn a_portable_gets_its_release_file_with_github_s_checksum() {
1210        let name = "agentmux-0.59.27-x64-portable.7z";
1211        let url = format!("https://github.com/agentmuxai/agentmux/releases/download/v0.59.27/{name}");
1212        let sha = "DB750E1689752519AD21B730436F783493C63B59AD734677A433E413C9B47F2A";
1213        let kind = InstallKind::WindowsPortable { root: "C:/apps/agentmux".into() };
1214        let r = with_asset(release("v0.59.27"), name, Some(&format!("sha256:{sha}")), &url);
1215        let s = status_for("0.59.26", "stable", &r, 0, &kind);
1216        assert_eq!(s.install, "windows-portable");
1217        if std::env::consts::ARCH == "x86_64" {
1218            let asset = s.asset.clone().unwrap();
1219            assert_eq!(asset.sha256, sha.to_ascii_lowercase());
1220            assert_eq!((asset.name.as_str(), asset.size), (name, 124_705_866));
1221            assert!(s.can_download);
1222        }
1223        // Not newer: nothing to download.
1224        assert!(!status_for("0.59.27", "stable", &r, 0, &kind).can_download);
1225        // No checksum, or served from anywhere else: not offered.
1226        let unsigned = with_asset(release("v0.59.27"), name, None, &url);
1227        assert!(status_for("0.59.26", "stable", &unsigned, 0, &kind).asset.is_none());
1228        let elsewhere = with_asset(release("v0.59.27"), name, Some(&format!("sha256:{sha}")), "https://example.com/x.7z");
1229        assert!(status_for("0.59.26", "stable", &elsewhere, 0, &kind).asset.is_none());
1230        // A kind AgentMux can't install itself still learns of the release.
1231        let store = status_for("0.59.26", "stable", &r, 0, &InstallKind::WindowsStore);
1232        assert_eq!((store.state.as_str(), store.can_download), ("available", false));
1233    }
1234}