Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): resolve latest release without the rate-limited REST API (#4757)

Francesco Bonaccia2b3182eac98
diff --git a/docs/content/docs/cua-driver/guides/operate.mdx b/docs/content/docs/cua-driver/guides/operate.mdx
index ce968a5684..d201c01135 100644
--- a/docs/content/docs/cua-driver/guides/operate.mdx
+++ b/docs/content/docs/cua-driver/guides/operate.mdx
@@ -157,11 +157,17 @@ cua-driver update --apply
```
`check-update` only checks (`--json` for scripts, `--no-cache` to skip the
-20-hour cache); `update --apply` runs the canonical installer. Then restart the
+1-hour cache); `update --apply` runs the canonical installer. Then restart the
daemon with your usual start command (`open -n -g -a CuaDriver --args serve`,
`cua-driver autostart kick`, or `cua-driver serve`), keeping any mode flags. The
same check is the `check_for_update` MCP tool.
+The check reads the version the installer itself would install, so it agrees
+with `curl -fsSL https://cua.ai/driver/install.sh | bash`, and it does not spend
+GitHub's REST API quota for stable releases. When GitHub's API does answer with
+a rate limit (nightly lookups and fallbacks), the message says so and shows when
+the limit resets; set `GITHUB_TOKEN` or `GH_TOKEN` to use your own quota.
+
```bash test="cli-shape" id="cua-driver-update-2"
if cua-driver check-update --json | jq -e '.update_available' > /dev/null; then
cua-driver update --apply
diff --git a/docs/content/docs/cua-driver/reference/cli/updates.mdx b/docs/content/docs/cua-driver/reference/cli/updates.mdx
index 73500b9edd..3b935a7c4a 100644
--- a/docs/content/docs/cua-driver/reference/cli/updates.mdx
+++ b/docs/content/docs/cua-driver/reference/cli/updates.mdx
@@ -33,7 +33,7 @@ cua-driver check-update [OPTIONS]
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
| <span id="cua-driver-check-update--json"></span>`--json` | boolean | `false` | Emit a machine-readable JSON payload. |
-| <span id="cua-driver-check-update--no-cache"></span>`--no-cache` | boolean | `false` | Skip the 20-hour on-disk cache and force a GitHub request. |
+| <span id="cua-driver-check-update--no-cache"></span>`--no-cache` | boolean | `false` | Skip the 1-hour on-disk cache and look up the latest release again. |
**Examples**
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index b439a1c2db..2bf67c3539 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -3224,9 +3224,9 @@ fn run_recording_render(args: &[String]) {
/// `cua-driver update [--apply]` — check for a newer release and optionally apply it.
///
-/// Shares the GitHub releases fetch with the startup banner via
+/// Shares the release lookup with the startup banner via
/// [`crate::version_check::fetch_latest_version`] so both code paths agree on
-/// tag filtering and HTTP semantics. `--apply` delegates to the canonical
+/// the source (the installer's own version pin, then GitHub) and tag filtering. `--apply` delegates to the canonical
/// installer script — see [`crate::updater`] for why we go through the script
/// instead of re-implementing the asset resolution + atomic swap + GC in Rust.
pub fn run_update_cmd(apply: bool, json: bool) {
@@ -3282,6 +3282,10 @@ pub fn run_update_cmd(apply: bool, json: bool) {
}
let latest = crate::version_check::fetch_latest_version();
+ if let Ok(v) = &latest {
+ // Keep the cache in step with what the user was just told.
+ crate::version_check::record_latest(selected_channel, v);
+ }
match latest {
Err(e) => {
crate::telemetry::capture_update_checked(
@@ -3299,12 +3303,11 @@ pub fn run_update_cmd(apply: bool, json: bool) {
apply_started_at.elapsed(),
);
}
- // The shared helper returns a human-readable error string for
- // the CLI surface — pass it through so the user can see why
- // (timeout, parse error, etc.) instead of just "unreachable".
- tracing::debug!(target: "cua_driver::update", "fetch failed: {e}");
+ // The error names the real cause: a GitHub API rate limit (with its
+ // reset time) is not a network failure, and vice versa.
+ tracing::debug!(target: "cua_driver::update", "fetch failed: {e:?}");
if !json {
- println!("Could not reach GitHub — check your connection and try again.");
+ println!("Could not check for updates: {e}");
}
process::exit(1);
}
@@ -3371,6 +3374,9 @@ pub fn run_update_cmd(apply: bool, json: bool) {
daemon_was_running,
apply_started_at.elapsed(),
);
+ // What was "latest" before this install says nothing about
+ // what is latest after it.
+ crate::version_check::invalidate_cache();
if !json {
println!("Installed cua-driver {v}.");
}
@@ -4435,7 +4441,7 @@ fn cli_docs_literal() -> serde_json::Value {
"options": no_options,
"flags": [
{"name":"json","short_name":null,"help":"Emit a machine-readable JSON payload.","default_value":false},
- {"name":"no-cache","short_name":null,"help":"Skip the 20-hour on-disk cache and force a GitHub request.","default_value":false}
+ {"name":"no-cache","short_name":null,"help":"Skip the 1-hour on-disk cache and look up the latest release again.","default_value":false}
],
"subcommands": no_subcommands
},
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
index 75ebb3fa45..b5460a98eb 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -32,6 +32,7 @@ mod perception_cli;
mod private_worker;
mod proxy;
mod release_channel;
+mod release_source;
mod responsibility;
mod sdk_adapter;
mod serve;
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/release_source.rs b/libs/cua-driver/rust/crates/cua-driver/src/release_source.rs
new file mode 100644
index 0000000000..a1094087f8
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/src/release_source.rs
@@ -0,0 +1,1051 @@
+//! Resolves "what is the latest Cua Driver release?" without depending on the
+//! rate-limited GitHub REST API.
+//!
+//! The installer (`https://cua.ai/driver/install.sh`, which delegates to
+//! `_install-rust.sh`) resolves the stable version from a constant it carries,
+//! `CUA_DRIVER_RS_BAKED_VERSION`. The release workflow advances that constant
+//! only after every release asset is public, so it names the newest release a
+//! user can actually install. Update discovery reads the same constant, which
+//! keeps `check-update` and the installer in agreement by construction.
+//!
+//! Source order:
+//!
+//! | channel | order |
+//! |---------|-------|
+//! | stable | installer's baked version, then the releases API, then the releases feed |
+//! | nightly | releases API, then the releases feed |
+//!
+//! The releases API call carries `GH_TOKEN` / `GITHUB_TOKEN` when one is set
+//! (same precedence as the installer) and only ever to `api.github.com`.
+//! The `releases.atom` feed lives on github.com and is not subject to the REST
+//! API quota, but it only lists the newest ten releases across every product in
+//! the monorepo, so it is a last resort rather than a primary source.
+//!
+//! Failures are classified so callers can tell the user the truth: a REST rate
+//! limit ([`FetchError::RateLimited`], with the reset time) is not a network
+//! failure ([`FetchError::Network`]).
+
+use std::fmt;
+use std::time::Duration;
+
+use crate::release_channel::ReleaseChannel;
+
+/// Installer script that carries the baked stable version.
+pub(crate) const INSTALLER_SCRIPT_URL: &str = "https://cua.ai/driver/_install-rust.sh";
+/// REST endpoint listing releases, newest first.
+pub(crate) const RELEASES_API_URL: &str = "https://api.github.com/repos/trycua/cua/releases";
+/// Atom feed of the newest releases. Served from github.com, not the REST API.
+pub(crate) const RELEASES_FEED_URL: &str = "https://github.com/trycua/cua/releases.atom";
+
+/// Pages of 100 releases to walk before giving up. The monorepo interleaves
+/// several products, so the newest `cua-driver-rs-v*` tag is not always on the
+/// first page. The installer uses the same bound.
+const MAX_API_PAGES: usize = 10;
+const API_PAGE_SIZE: usize = 100;
+
+const HTTP_TIMEOUT_SECONDS: u64 = 4;
+
+const BAKED_VERSION_KEY: &str = "CUA_DRIVER_RS_BAKED_VERSION=";
+const WITHDRAWN_VERSIONS_KEY: &str = "CUA_DRIVER_RS_WITHDRAWN_VERSIONS=";
+
+// ── Errors ───────────────────────────────────────────────────────────────
+
+/// Why a release lookup failed.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum FetchError {
+ /// The GitHub REST API refused the request because its quota is spent.
+ RateLimited {
+ /// Quota per hour (`x-ratelimit-limit`), when reported.
+ limit: Option<u64>,
+ /// Unix time at which the quota resets (`x-ratelimit-reset`, or
+ /// `retry-after` converted to an absolute time).
+ reset_unix: Option<u64>,
+ /// Whether the rejected request carried a token.
+ authenticated: bool,
+ },
+ /// A transport failure: DNS, connect, TLS or timeout.
+ Network { host: String, detail: String },
+ /// The server answered but the answer was unusable.
+ Other(String),
+}
+
+impl FetchError {
+ /// Human-readable description relative to `now` (unix seconds).
+ pub fn describe(&self, now: u64) -> String {
+ match self {
+ FetchError::RateLimited {
+ limit,
+ reset_unix,
+ authenticated,
+ } => {
+ let who = if *authenticated {
+ "authenticated"
+ } else {
+ "unauthenticated"
+ };
+ let quota = match limit {
+ Some(limit) => format!("{limit} requests/hour, {who}"),
+ None => who.to_owned(),
+ };
+ let reset = match reset_unix {
+ Some(reset) => format!(
+ "Resets at {} ({}).",
+ crate::version_check::iso8601(*reset),
+ relative_time(*reset, now)
+ ),
+ None => "The reset time was not reported.".to_owned(),
+ };
+ let advice = if *authenticated {
+ "Wait for the reset, or run the installer directly: \
+ curl -fsSL https://cua.ai/driver/install.sh | bash"
+ } else {
+ "Set GITHUB_TOKEN or GH_TOKEN to use your own quota."
+ };
+ format!("GitHub API rate limit exceeded ({quota}). {reset} {advice}")
+ }
+ FetchError::Network { host, detail } => format!(
+ "Could not reach {host}: {detail}. Check your network, DNS, proxy or TLS \
+ settings and try again."
+ ),
+ FetchError::Other(message) => message.clone(),
+ }
+ }
+}
+
+impl fmt::Display for FetchError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.describe(crate::version_check::unix_now()))
+ }
+}
+
+impl std::error::Error for FetchError {}
+
+fn relative_time(target: u64, now: u64) -> String {
+ if target <= now {
+ return "now".to_owned();
+ }
+ let secs = target - now;
+ if secs < 90 {
+ format!("in {secs} s")
+ } else if secs < 90 * 60 {
+ format!("in {} min", secs.div_ceil(60))
+ } else {
+ let minutes = secs.div_ceil(60);
+ format!("in {} h {} min", minutes / 60, minutes % 60)
+ }
+}
+
+// ── HTTP seam ────────────────────────────────────────────────────────────
+
+/// A completed HTTP exchange. Any status code is a response, not an error;
+/// only transport failures are `Err`.
+#[derive(Debug, Clone)]
+pub(crate) struct HttpResponse {
+ pub status: u16,
+ /// Header names are lowercased.
+ pub headers: Vec<(String, String)>,
+ pub body: String,
+}
+
+impl HttpResponse {
+ fn header(&self, name: &str) -> Option<&str> {
+ self.headers
+ .iter()
+ .find(|(key, _)| key == name)
+ .map(|(_, value)| value.as_str())
+ }
+}
+
+/// Transport failure detail, host-tagged by the caller.
+pub(crate) type TransportError = String;
+
+pub(crate) trait HttpClient {
+ /// GET `url`. `bearer` is sent as `Authorization: Bearer ...` when set.
+ fn get(
+ &self,
+ url: &str,
+ accept: &str,
+ bearer: Option<&str>,
+ ) -> Result<HttpResponse, TransportError>;
+}
+
+/// Production client backed by `ureq`.
+pub(crate) struct UreqClient {
+ agent: ureq::Agent,
+}
+
+impl UreqClient {
+ pub(crate) fn new() -> Self {
+ let agent = ureq::Agent::config_builder()
+ .timeout_global(Some(Duration::from_secs(HTTP_TIMEOUT_SECONDS)))
+ // 4xx/5xx are responses we classify ourselves (rate limits above all).
+ .http_status_as_error(false)
+ .build()
+ .new_agent();
+ Self { agent }
+ }
+}
+
+impl HttpClient for UreqClient {
+ fn get(
+ &self,
+ url: &str,
+ accept: &str,
+ bearer: Option<&str>,
+ ) -> Result<HttpResponse, TransportError> {
+ let mut request = self.agent.get(url).header("Accept", accept).header(
+ "User-Agent",
+ concat!("cua-driver-rs/", env!("CARGO_PKG_VERSION")),
+ );
+ if let Some(token) = bearer {
+ request = request.header("Authorization", &format!("Bearer {token}"));
+ }
+ let response = request.call().map_err(|error| error.to_string())?;
+ let status = response.status().as_u16();
+ let headers = response
+ .headers()
+ .iter()
+ .filter_map(|(name, value)| {
+ Some((
+ name.as_str().to_ascii_lowercase(),
+ value.to_str().ok()?.to_owned(),
+ ))
+ })
+ .collect();
+ let body = response
+ .into_body()
+ .read_to_string()
+ .map_err(|error| error.to_string())?;
+ Ok(HttpResponse {
+ status,
+ headers,
+ body,
+ })
+ }
+}
+
+/// Endpoints, overridable so tests can point at a local server.
+#[derive(Debug, Clone)]
+pub(crate) struct Endpoints {
+ pub installer_script: String,
+ pub releases_api: String,
+ pub releases_feed: String,
+}
+
+impl Default for Endpoints {
+ fn default() -> Self {
+ Self {
+ installer_script: INSTALLER_SCRIPT_URL.to_owned(),
+ releases_api: RELEASES_API_URL.to_owned(),
+ releases_feed: RELEASES_FEED_URL.to_owned(),
+ }
+ }
+}
+
+/// `GH_TOKEN` wins over `GITHUB_TOKEN`, matching the GitHub CLI and the
+/// installer. Empty values count as unset.
+pub(crate) fn token_from_env() -> Option<String> {
+ ["GH_TOKEN", "GITHUB_TOKEN"].iter().find_map(|name| {
+ std::env::var(name)
+ .ok()
+ .map(|value| value.trim().to_owned())
+ .filter(|value| !value.is_empty())
+ })
+}
+
+// ── Resolution ───────────────────────────────────────────────────────────
+
+/// Resolve the latest release version for `channel`, bare (no tag prefix).
+pub(crate) fn resolve_latest(
+ http: &dyn HttpClient,
+ endpoints: &Endpoints,
+ channel: ReleaseChannel,
+ token: Option<&str>,
+) -> Result<String, FetchError> {
+ let mut errors: Vec<FetchError> = Vec::new();
+ let mut withdrawn: Vec<String> = Vec::new();
+
+ if channel == ReleaseChannel::Stable {
+ match fetch_installer_pin(http, endpoints) {
+ Ok(pin) => {
+ withdrawn = pin.withdrawn;
+ // Same rule as the installer: a baked version that is not
+ // withdrawn is the latest stable release.
+ if let Some(baked) = pin.baked.filter(|baked| !withdrawn.contains(baked)) {
+ return Ok(baked);
+ }
+ }
+ Err(error) => {
+ tracing::debug!(target: "cua_driver::release_source",
+ "installer lookup failed: {error:?}");
+ errors.push(error);
+ }
+ }
+ }
+
+ match fetch_via_api(http, endpoints, channel, token, &withdrawn) {
+ Ok(Some(version)) => return Ok(version),
+ Ok(None) => errors.push(no_match_error(channel)),
+ Err(error) => {
+ tracing::debug!(target: "cua_driver::release_source",
+ "releases API lookup failed: {error:?}");
+ errors.push(error);
+ }
+ }
+
+ match fetch_via_feed(http, endpoints, channel, &withdrawn) {
+ Ok(Some(version)) => return Ok(version),
+ Ok(None) => errors.push(no_match_error(channel)),
+ Err(error) => {
+ tracing::debug!(target: "cua_driver::release_source",
+ "releases feed lookup failed: {error:?}");
+ errors.push(error);
+ }
+ }
+
+ Err(most_informative(errors, channel))
+}
+
+fn no_match_error(channel: ReleaseChannel) -> FetchError {
+ FetchError::Other(format!(
+ "no matching {}* release found",
+ crate::version_check::tag_prefix(channel)
+ ))
+}
+
+/// Pick the error that explains the failure best: a rate limit beats
+/// everything, a real answer ("no such release") beats a transport failure
+/// elsewhere, and a network error is reported only when nothing was reachable.
+fn most_informative(errors: Vec<FetchError>, channel: ReleaseChannel) -> FetchError {
+ if let Some(limited) = errors
+ .iter()
+ .find(|error| matches!(error, FetchError::RateLimited { .. }))
+ {
+ return limited.clone();
+ }
+ if let Some(other) = errors
+ .iter()
+ .find(|error| matches!(error, FetchError::Other(_)))
+ {
+ return other.clone();
+ }
+ errors
+ .into_iter()
+ .next()
+ .unwrap_or_else(|| no_match_error(channel))
+}
+
+fn host_of(url: &str) -> String {
+ url.split("://")
+ .nth(1)
+ .unwrap_or(url)
+ .split(['/', '?'])
+ .next()
+ .unwrap_or(url)
+ .to_owned()
+}
+
+fn transport(url: &str, detail: TransportError) -> FetchError {
+ FetchError::Network {
+ host: host_of(url),
+ detail,
+ }
+}
+
+// ── Installer pin ────────────────────────────────────────────────────────
+
+#[derive(Debug, Default, PartialEq, Eq)]
+struct InstallerPin {
+ baked: Option<String>,
+ withdrawn: Vec<String>,
+}
+
+fn fetch_installer_pin(
+ http: &dyn HttpClient,
+ endpoints: &Endpoints,
+) -> Result<InstallerPin, FetchError> {
+ let url = &endpoints.installer_script;
+ let response = http
+ .get(url, "text/plain", None)
+ .map_err(|detail| transport(url, detail))?;
+ if !(200..300).contains(&response.status) {
+ return Err(FetchError::Other(format!(
+ "{} returned HTTP {}",
+ host_of(url),
+ response.status
+ )));
+ }
+ Ok(parse_installer_pin(&response.body))
+}
+
+/// Read the two sentinel assignments out of `_install-rust.sh`:
+///
+/// ```text
+/// CUA_DRIVER_RS_BAKED_VERSION="0.34.0" # published-installer-version
+/// CUA_DRIVER_RS_WITHDRAWN_VERSIONS="0.28.3" # withdrawn-installer-versions
+/// ```
+fn parse_installer_pin(script: &str) -> InstallerPin {
+ let mut pin = InstallerPin::default();
+ for line in script.lines() {
+ // Only a bare assignment at the start of a line: uses such as
+ // `"${CUA_DRIVER_RS_BAKED_VERSION#v}"` and comments never match.
+ if let Some(rest) = line.strip_prefix(BAKED_VERSION_KEY) {
+ pin.baked = quoted_value(rest)
+ .map(|value| value.trim_start_matches('v').to_owned())
+ .filter(|value| is_plain_release(value));
+ } else if let Some(rest) = line.strip_prefix(WITHDRAWN_VERSIONS_KEY) {
+ pin.withdrawn = quoted_value(rest)
+ .map(|value| value.split_whitespace().map(str::to_owned).collect())
+ .unwrap_or_default();
+ }
+ }
+ pin
+}
+
+fn quoted_value(rest: &str) -> Option<&str> {
+ let rest = rest.strip_prefix('"')?;
+ Some(&rest[..rest.find('"')?])
+}
+
+/// Exact `x.y.z` with no pre-release or build suffix.
+fn is_plain_release(value: &str) -> bool {
+ semver::Version::parse(value)
+ .map(|version| version.pre.is_empty() && version.build.is_empty())
+ .unwrap_or(false)
+ && value.split('.').count() == 3
+}
+
+// ── Releases API ─────────────────────────────────────────────────────────
+
+fn fetch_via_api(
+ http: &dyn HttpClient,
+ endpoints: &Endpoints,
+ channel: ReleaseChannel,
+ token: Option<&str>,
+ withdrawn: &[String],
+) -> Result<Option<String>, FetchError> {
+ let mut token = token;
+ for page in 1..=MAX_API_PAGES {
+ let url = format!(
+ "{}?per_page={API_PAGE_SIZE}&page={page}",
+ endpoints.releases_api
+ );
+ let response = api_get(http, &url, &mut token)?;
+ let body: serde_json::Value = serde_json::from_str(&response.body)
+ .map_err(|error| FetchError::Other(format!("JSON parse error: {error}")))?;
+ let entries = body.as_array().map(Vec::len).unwrap_or(0);
+ if let Some(version) =
+ crate::version_check::pick_latest_release_excluding(&body, channel, withdrawn)
+ {
+ return Ok(Some(version));
+ }
+ if entries < API_PAGE_SIZE {
+ break;
+ }
+ }
+ Ok(None)
+}
+
+/// GET against the REST API, classifying rate limits. A rejected token (401)
+/// is retried once without it: a stale `GITHUB_TOKEN` in the environment must
+/// not make discovery worse than having none.
+fn api_get(
+ http: &dyn HttpClient,
+ url: &str,
+ token: &mut Option<&str>,
+) -> Result<HttpResponse, FetchError> {
+ const ACCEPT: &str = "application/vnd.github+json";
+ let mut response = http
+ .get(url, ACCEPT, *token)
+ .map_err(|detail| transport(url, detail))?;
+ if response.status == 401 && token.is_some() {
+ tracing::debug!(target: "cua_driver::release_source",
+ "GitHub rejected the token; retrying unauthenticated");
+ *token = None;
+ response = http
+ .get(url, ACCEPT, None)
+ .map_err(|detail| transport(url, detail))?;
+ }
+ if (200..300).contains(&response.status) {
+ return Ok(response);
+ }
+ if let Some(limited) = classify_rate_limit(&response, token.is_some()) {
+ return Err(limited);
+ }
+ Err(FetchError::Other(format!(
+ "GitHub API returned HTTP {}",
+ response.status
+ )))
+}
+
+/// A 429, or a 403 that says the quota is spent (`x-ratelimit-remaining: 0`,
+/// a `retry-after` for secondary limits, or a rate-limit message body).
+fn classify_rate_limit(response: &HttpResponse, authenticated: bool) -> Option<FetchError> {
+ let remaining_zero = response
+ .header("x-ratelimit-remaining")
+ .map(|value| value.trim() == "0")
+ .unwrap_or(false);
+ let retry_after = response
+ .header("retry-after")
+ .and_then(|value| value.trim().parse::<u64>().ok());
+ let limited = match response.status {
+ 429 => true,
+ 403 => {
+ remaining_zero
+ || retry_after.is_some()
+ || response.body.to_ascii_lowercase().contains("rate limit")
+ }
+ _ => false,
+ };
+ if !limited {
+ return None;
+ }
+ let reset_unix = response
+ .header("x-ratelimit-reset")
+ .and_then(|value| value.trim().parse::<u64>().ok())
+ .or_else(|| retry_after.map(|secs| crate::version_check::unix_now() + secs));
+ Some(FetchError::RateLimited {
+ limit: response
+ .header("x-ratelimit-limit")
+ .and_then(|value| value.trim().parse().ok()),
+ reset_unix,
+ authenticated,
+ })
+}
+
+// ── Releases feed ────────────────────────────────────────────────────────
+
+fn fetch_via_feed(
+ http: &dyn HttpClient,
+ endpoints: &Endpoints,
+ channel: ReleaseChannel,
+ withdrawn: &[String],
+) -> Result<Option<String>, FetchError> {
+ let url = &endpoints.releases_feed;
+ let response = http
+ .get(url, "application/atom+xml", None)
+ .map_err(|detail| transport(url, detail))?;
+ if !(200..300).contains(&response.status) {
+ return Err(FetchError::Other(format!(
+ "{} returned HTTP {}",
+ host_of(url),
+ response.status
+ )));
+ }
+ let releases: Vec<serde_json::Value> = feed_tags(&response.body)
+ .into_iter()
+ .map(|tag| serde_json::json!({ "tag_name": tag, "draft": false }))
+ .collect();
+ Ok(crate::version_check::pick_latest_release_excluding(
+ &serde_json::Value::Array(releases),
+ channel,
+ withdrawn,
+ ))
+}
+
+/// Tag names from `<link ... href=".../releases/tag/<tag>"/>` entries.
+fn feed_tags(feed: &str) -> Vec<String> {
+ const MARKER: &str = "/releases/tag/";
+ let mut tags = Vec::new();
+ let mut rest = feed;
+ while let Some(at) = rest.find(MARKER) {
+ let after = &rest[at + MARKER.len()..];
+ let end = after.find(['"', '\'', '<', '&']).unwrap_or(after.len());
+ let tag = &after[..end];
+ if !tag.is_empty() {
+ tags.push(tag.to_owned());
+ }
+ rest = &after[end..];
+ }
+ tags
+}
+
+// ── Tests ────────────────────────────────────────────────────────────────
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::cell::RefCell;
+ use std::collections::HashMap;
+
+ /// Scripted HTTP client. Responses are keyed by URL prefix; every call is
+ /// recorded with the bearer token it carried.
+ #[derive(Default)]
+ struct MockHttp {
+ routes: Vec<(String, Result<HttpResponse, TransportError>)>,
+ calls: RefCell<Vec<(String, Option<String>)>>,
+ }
+
+ impl MockHttp {
+ fn route(mut self, prefix: &str, response: Result<HttpResponse, TransportError>) -> Self {
+ self.routes.push((prefix.to_owned(), response));
+ self
+ }
+ fn calls_to(&self, prefix: &str) -> Vec<Option<String>> {
+ self.calls
+ .borrow()
+ .iter()
+ .filter(|(url, _)| url.starts_with(prefix))
+ .map(|(_, token)| token.clone())
+ .collect()
+ }
+ }
+
+ impl HttpClient for MockHttp {
+ fn get(
+ &self,
+ url: &str,
+ _accept: &str,
+ bearer: Option<&str>,
+ ) -> Result<HttpResponse, TransportError> {
+ self.calls
+ .borrow_mut()
+ .push((url.to_owned(), bearer.map(str::to_owned)));
+ self.routes
+ .iter()
+ .find(|(prefix, _)| url.starts_with(prefix))
+ .map(|(_, response)| response.clone())
+ .unwrap_or_else(|| Err(format!("no route for {url}")))
+ }
+ }
+
+ const SCRIPT: &str = "https://scripts.test/_install-rust.sh";
+ const API: &str = "https://api.test/repos/trycua/cua/releases";
+ const FEED: &str = "https://feed.test/releases.atom";
+
+ fn endpoints() -> Endpoints {
+ Endpoints {
+ installer_script: SCRIPT.to_owned(),
+ releases_api: API.to_owned(),
+ releases_feed: FEED.to_owned(),
+ }
+ }
+
+ fn ok(body: &str) -> Result<HttpResponse, TransportError> {
+ Ok(HttpResponse {
+ status: 200,
+ headers: vec![],
+ body: body.to_owned(),
+ })
+ }
+
+ fn status(
+ code: u16,
+ headers: &[(&str, &str)],
+ body: &str,
+ ) -> Result<HttpResponse, TransportError> {
+ Ok(HttpResponse {
+ status: code,
+ headers: headers
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect(),
+ body: body.to_owned(),
+ })
+ }
+
+ fn rate_limited() -> Result<HttpResponse, TransportError> {
+ status(
+ 403,
+ &[
+ ("x-ratelimit-limit", "60"),
+ ("x-ratelimit-remaining", "0"),
+ ("x-ratelimit-reset", "1791298445"),
+ ],
+ r#"{"message":"API rate limit exceeded for 1.2.3.4."}"#,
+ )
+ }
+
+ fn installer_script(baked: &str, withdrawn: &str) -> String {
+ format!(
+ "#!/bin/bash\n# prose mentioning CUA_DRIVER_RS_BAKED_VERSION=\"9.9.9\"\n\
+ # ~~~ BAKED_VERSION ~~~\n\
+ CUA_DRIVER_RS_BAKED_VERSION=\"{baked}\" # published-installer-version\n\
+ # ~~~ END ~~~\n\
+ CUA_DRIVER_RS_WITHDRAWN_VERSIONS=\"{withdrawn}\" # withdrawn-installer-versions\n\
+ TAG=\"${{TAG_PREFIX}}${{CUA_DRIVER_RS_BAKED_VERSION#v}}\"\n"
+ )
+ }
+
+ fn releases_json(tags: &[&str]) -> String {
+ serde_json::Value::Array(
+ tags.iter()
+ .map(|tag| serde_json::json!({"tag_name": tag, "draft": false, "prerelease": true}))
+ .collect(),
+ )
+ .to_string()
+ }
+
+ fn feed_xml(tags: &[&str]) -> String {
+ let entries: String = tags
+ .iter()
+ .map(|tag| {
+ format!(
+ "<entry><link rel=\"alternate\" type=\"text/html\" \
+ href=\"https://github.com/trycua/cua/releases/tag/{tag}\"/>\
+ <title>{tag}</title></entry>"
+ )
+ })
+ .collect();
+ format!("<feed>{entries}</feed>")
+ }
+
+ #[test]
+ fn stable_uses_the_installers_baked_version_without_touching_the_api() {
+ let http = MockHttp::default()
+ .route(SCRIPT, ok(&installer_script("0.34.0", "0.28.3")))
+ .route(API, rate_limited());
+ let latest = resolve_latest(&http, &endpoints(), ReleaseChannel::Stable, None).unwrap();
+ assert_eq!(latest, "0.34.0");
+ assert!(http.calls_to(API).is_empty(), "API must not be consulted");
+ }
+
+ #[test]
+ fn baked_version_wins_over_a_newer_api_release() {
+ // The installer would install 0.34.0; so must update discovery, even if
+ // the API already lists a tag whose assets are not all public yet.
+ let http = MockHttp::default()
+ .route(SCRIPT, ok(&installer_script("0.34.0", "")))
+ .route(API, ok(&releases_json(&["cua-driver-rs-v0.35.0"])));
+ let latest = resolve_latest(&http, &endpoints(), ReleaseChannel::Stable, None).unwrap();
+ assert_eq!(latest, "0.34.0");
+ }
+
+ #[test]
+ fn withdrawn_baked_version_falls_back_to_the_api_and_skips_withdrawn_tags() {
+ let http = MockHttp::default()
+ .route(SCRIPT, ok(&installer_script("0.28.3", "0.28.3 0.30.0")))
+ .route(
+ API,
+ ok(&releases_json(&[
+ "cua-driver-rs-v0.30.0",
+ "cua-driver-rs-v0.29.0",
+ "lume-v1.0.0",
+ ])),
+ );
+ let latest = resolve_latest(&http, &endpoints(), ReleaseChannel::Stable, None).unwrap();
+ assert_eq!(latest, "0.29.0");
+ }
+
+ #[test]
+ fn rate_limited_api_is_reported_with_the_reset_time_not_as_a_network_error() {
+ let http = MockHttp::default()
+ .route(SCRIPT, Err("connection refused".into()))
+ .route(API, rate_limited())
+ .route(FEED, Err("connection refused".into()));
+ let error = resolve_latest(&http, &endpoints(), ReleaseChannel::Stable, None).unwrap_err();
+ assert_eq!(
+ error,
+ FetchError::RateLimited {
+ limit: Some(60),
+ reset_unix: Some(1_791_298_445),
+ authenticated: false,
+ }
+ );
+ let message = error.describe(1_791_298_445 - 600);
+ assert!(message.contains("rate limit exceeded"), "{message}");
+ assert!(
+ message.contains("60 requests/hour, unauthenticated"),
+ "{message}"
+ );
+ assert!(
+ message.contains(&crate::version_check::iso8601(1_791_298_445)),
+ "{message}"
+ );
+ assert!(message.contains("in 10 min"), "{message}");
+ assert!(message.contains("GITHUB_TOKEN"), "{message}");
+ assert!(!message.contains("Could not reach"), "{message}");
+ }
+
+ #[test]
+ fn http_429_is_a_rate_limit_too() {
+ let http =
+ MockHttp::default().route(API, status(429, &[("retry-after", "30")], "slow down"));
+ let error =
+ fetch_via_api(&http, &endpoints(), ReleaseChannel::Nightly, None, &[]).unwrap_err();
+ assert!(
+ matches!(
+ error,
+ FetchError::RateLimited {
+ reset_unix: Some(_),
+ ..
+ }
+ ),
+ "{error:?}"
+ );
+ }
+
+ #[test]
+ fn plain_403_is_not_misreported_as_a_rate_limit() {
+ let http = MockHttp::default().route(
+ API,
+ status(403, &[("x-ratelimit-remaining", "42")], "forbidden"),
+ );
+ let error =
+ fetch_via_api(&http, &endpoints(), ReleaseChannel::Nightly, None, &[]).unwrap_err();
+ assert_eq!(
+ error,
+ FetchError::Other("GitHub API returned HTTP 403".into())
+ );
+ }
+
+ #[test]
+ fn real_network_failure_is_reported_as_could_not_reach() {
+ let http = MockHttp::default()
+ .route(SCRIPT, Err("dns error: no such host".into()))
+ .route(API, Err("dns error: no such host".into()))
+ .route(FEED, Err("tls handshake failed".into()));
+ let error = resolve_latest(&http, &endpoints(), ReleaseChannel::Stable, None).unwrap_err();
+ assert!(matches!(error, FetchError::Network { .. }), "{error:?}");
+ let message = error.describe(0);
+ assert!(message.starts_with("Could not reach "), "{message}");
+ assert!(message.contains("DNS"), "{message}");
+ assert!(!message.contains("rate limit"), "{message}");
+ }
+
+ #[test]
+ fn token_is_sent_to_the_api_only_and_authenticated_limits_say_so() {
+ let http = MockHttp::default()
+ .route(SCRIPT, ok(&installer_script("0.28.3", "0.28.3")))
+ .route(API, ok(&releases_json(&["cua-driver-rs-v0.34.0"])));
+ let latest = resolve_latest(
+ &http,
+ &endpoints(),
+ ReleaseChannel::Stable,
+ Some("ghp_secret"),
+ )
+ .unwrap();
+ assert_eq!(latest, "0.34.0");
+ assert_eq!(http.calls_to(API), vec![Some("ghp_secret".to_owned())]);
+ assert_eq!(
+ http.calls_to(SCRIPT),
+ vec![None],
+ "token must never leave api host"
+ );
+
+ let limited = MockHttp::default().route(API, rate_limited());
+ let error = fetch_via_api(
+ &limited,
+ &endpoints(),
+ ReleaseChannel::Nightly,
+ Some("ghp_secret"),
+ &[],
+ )
+ .unwrap_err();
+ assert!(
+ matches!(
+ error,
+ FetchError::RateLimited {
+ authenticated: true,
+ ..
+ }
+ ),
+ "{error:?}"
+ );
+ assert!(error.describe(0).contains("authenticated"));
+ }
+
+ #[test]
+ fn rejected_token_is_retried_without_it() {
+ let calls = RefCell::new(0);
+ struct Flaky<'a>(&'a RefCell<i32>, String);
+ impl HttpClient for Flaky<'_> {
+ fn get(
+ &self,
+ _url: &str,
+ _accept: &str,
+ bearer: Option<&str>,
+ ) -> Result<HttpResponse, TransportError> {
+ *self.0.borrow_mut() += 1;
+ if bearer.is_some() {
+ status(401, &[], "Bad credentials")
+ } else {
+ ok(&self.1)
+ }
+ }
+ }
+ let http = Flaky(&calls, releases_json(&["cua-driver-rs-v0.34.0"]));
+ let found = fetch_via_api(
+ &http,
+ &endpoints(),
+ ReleaseChannel::Stable,
+ Some("stale"),
+ &[],
+ )
+ .unwrap();
+ assert_eq!(found.as_deref(), Some("0.34.0"));
+ assert_eq!(*calls.borrow(), 2);
+ }
+
+ #[test]
+ fn feed_is_the_fallback_when_installer_and_api_are_unavailable() {
+ let http = MockHttp::default()
+ .route(SCRIPT, status(503, &[], ""))
+ .route(API, rate_limited())
+ .route(
+ FEED,
+ ok(&feed_xml(&[
+ "nightly-lume-v0.6.2-nightly.20261006.37415690828",
+ "cua-driver-rs-v0.34.0",
+ "cua-driver-rs-v0.33.4",
+ ])),
+ );
+ let latest = resolve_latest(&http, &endpoints(), ReleaseChannel::Stable, None).unwrap();
+ assert_eq!(latest, "0.34.0");
+ }
+
+ #[test]
+ fn nightly_never_reads_the_installer_pin() {
+ let http = MockHttp::default()
+ .route(SCRIPT, ok(&installer_script("0.34.0", "")))
+ .route(
+ API,
+ ok(&releases_json(&[
+ "nightly-cua-driver-rs-v0.34.1-nightly.20261006.7",
+ "cua-driver-rs-v0.34.0",
+ ])),
+ );
+ let latest = resolve_latest(&http, &endpoints(), ReleaseChannel::Nightly, None).unwrap();
+ assert_eq!(latest, "0.34.1-nightly.20261006.7");
+ assert!(http.calls_to(SCRIPT).is_empty());
+ }
+
+ #[test]
+ fn api_walks_further_pages_until_a_match_appears() {
+ let first_page: Vec<String> = (0..API_PAGE_SIZE)
+ .map(|i| format!("lume-v1.0.{i}"))
+ .collect();
+ let first_page: Vec<&str> = first_page.iter().map(String::as_str).collect();
+ let http = MockHttp::default()
+ .route(
+ &format!("{API}?per_page=100&page=1"),
+ ok(&releases_json(&first_page)),
+ )
+ .route(
+ &format!("{API}?per_page=100&page=2"),
+ ok(&releases_json(&["cua-driver-rs-v0.20.0"])),
+ );
+ let found = fetch_via_api(&http, &endpoints(), ReleaseChannel::Stable, None, &[]).unwrap();
+ assert_eq!(found.as_deref(), Some("0.20.0"));
+ }
+
+ #[test]
+ fn installer_pin_parser_ignores_comments_and_expansions() {
+ let pin = parse_installer_pin(&installer_script("0.34.0", "0.28.3 0.30.1"));
+ assert_eq!(pin.baked.as_deref(), Some("0.34.0"));
+ assert_eq!(pin.withdrawn, vec!["0.28.3", "0.30.1"]);
+ assert_eq!(
+ parse_installer_pin(&installer_script("0.34.0-rc.1", "")).baked,
+ None
+ );
+ assert_eq!(parse_installer_pin(&installer_script("", "")).baked, None);
+ assert_eq!(
+ parse_installer_pin("no sentinels here"),
+ InstallerPin::default()
+ );
+ }
+
+ /// Serve one canned HTTP response on localhost and return the base URL.
+ fn serve_once(response: &'static str) -> String {
+ use std::io::{Read, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ std::thread::spawn(move || {
+ if let Ok((mut stream, _)) = listener.accept() {
+ let mut buf = [0u8; 4096];
+ let _ = stream.read(&mut buf);
+ let _ = stream.write_all(response.as_bytes());
+ }
+ });
+ format!("http://{addr}")
+ }
+
+ #[test]
+ fn ureq_client_surfaces_a_403_with_its_rate_limit_headers() {
+ let base = serve_once(
+ "HTTP/1.1 403 Forbidden\r\ncontent-type: application/json\r\n\
+ x-ratelimit-limit: 60\r\nx-ratelimit-remaining: 0\r\n\
+ x-ratelimit-reset: 1791298445\r\ncontent-length: 44\r\n\r\n\
+ {\"message\":\"API rate limit exceeded for ip\"}",
+ );
+ let endpoints = Endpoints {
+ releases_api: format!("{base}/repos/trycua/cua/releases"),
+ ..endpoints()
+ };
+ let error = fetch_via_api(
+ &UreqClient::new(),
+ &endpoints,
+ ReleaseChannel::Nightly,
+ None,
+ &[],
+ )
+ .unwrap_err();
+ assert_eq!(
+ error,
+ FetchError::RateLimited {
+ limit: Some(60),
+ reset_unix: Some(1_791_298_445),
+ authenticated: false,
+ }
+ );
+ }
+
+ #[test]
+ fn ureq_client_reports_a_refused_connection_as_a_network_failure() {
+ // Bind then drop to get a port nothing listens on.
+ let port = std::net::TcpListener::bind("127.0.0.1:0")
+ .unwrap()
+ .local_addr()
+ .unwrap()
+ .port();
+ let endpoints = Endpoints {
+ installer_script: format!("http://127.0.0.1:{port}/_install-rust.sh"),
+ releases_api: format!("http://127.0.0.1:{port}/releases"),
+ releases_feed: format!("http://127.0.0.1:{port}/releases.atom"),
+ };
+ let error = resolve_latest(&UreqClient::new(), &endpoints, ReleaseChannel::Stable, None)
+ .unwrap_err();
+ assert!(matches!(error, FetchError::Network { .. }), "{error:?}");
+ assert!(error.describe(0).starts_with("Could not reach 127.0.0.1:"));
+ }
+
+ #[test]
+ fn relative_time_is_readable() {
+ assert_eq!(relative_time(100, 200), "now");
+ assert_eq!(relative_time(230, 200), "in 30 s");
+ assert_eq!(relative_time(200 + 600, 200), "in 10 min");
+ assert_eq!(relative_time(200 + 3 * 3600 + 60, 200), "in 3 h 1 min");
+ assert_eq!(relative_time(200 + 4 * 3600 - 10, 200), "in 4 h 0 min");
+ }
+
+ #[test]
+ fn token_env_prefers_gh_token_and_ignores_blank_values() {
+ let _guard = crate::version_check::ENV_LOCK
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ let saved: HashMap<&str, Option<std::ffi::OsString>> = ["GH_TOKEN", "GITHUB_TOKEN"]
+ .iter()
+ .map(|name| (*name, std::env::var_os(name)))
+ .collect();
+ unsafe {
+ std::env::set_var("GH_TOKEN", " ");
+ std::env::set_var("GITHUB_TOKEN", "from-github-token");
+ }
+ assert_eq!(token_from_env().as_deref(), Some("from-github-token"));
+ unsafe {
+ std::env::set_var("GH_TOKEN", "from-gh-token");
+ }
+ assert_eq!(token_from_env().as_deref(), Some("from-gh-token"));
+ unsafe {
+ std::env::remove_var("GH_TOKEN");
+ std::env::remove_var("GITHUB_TOKEN");
+ }
+ assert_eq!(token_from_env(), None);
+ for (name, value) in saved {
+ match value {
+ Some(value) => unsafe { std::env::set_var(name, value) },
+ None => unsafe { std::env::remove_var(name) },
+ }
+ }
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs b/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs
index f84ed194ad..b423fef21d 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs
@@ -1,9 +1,10 @@
//! Startup "new version available" banner.
//!
-//! On the interactive entry points (`mcp`, `serve`, `doctor`) we check the
-//! GitHub releases API for a newer `cua-driver-rs-v*` tag, cache the answer
-//! on disk for ~20 hours, and print a small two-line banner to **stderr**
-//! if a strictly-newer release exists and the user hasn't dismissed it.
+//! On the interactive entry points (`mcp`, `serve`, `doctor`) we resolve the
+//! latest release (see [`crate::release_source`]: the installer's own version
+//! pin first, GitHub's REST API only as a fallback), cache the answer on disk
+//! for an hour, and print a small two-line banner to **stderr** if a
+//! strictly-newer release exists and the user hasn't dismissed it.
//!
//! Design constraints:
//!
@@ -16,9 +17,12 @@
//! refusal-to-write-cache — everything is `tracing::debug!` only. Never
//! pollute the user's stderr with "couldn't check for updates" noise;
//! the next launch just retries.
-//! - **Cache-first.** A 20-hour-old cache short-circuits the network call
-//! entirely. This bounds outbound requests to roughly one per machine
-//! per day even on a hot reload loop.
+//! - **Cache-first, but never stale.** A cache younger than an hour
+//! short-circuits the network call, which bounds outbound requests on a hot
+//! reload loop. A cached answer is ignored when it was written by a
+//! different build (the binary was replaced since), or when it is older than
+//! the running version. Failed lookups are remembered for a few minutes so
+//! the background banner does not retry on every launch.
//! - **Opt-out at three layers.** Env var `CUA_DRIVER_RS_UPDATE_CHECK=false`
//! (single invocation), persisted config `update_check_enabled = false`
//! in `~/.cua-driver/config.json` (permanent), and an automatic skip when
@@ -49,14 +53,14 @@ const LEGACY_HOME_SUBDIRECTORY: &str = ".cua-driver-rs";
/// else (including unset) leaves it on.
const ENV_UPDATE_CHECK: &str = "CUA_DRIVER_RS_UPDATE_CHECK";
-/// Refresh threshold for the on-disk cache. A fresh cache short-circuits
-/// the network call so we hit the GitHub API at most ~1× per machine per
-/// day even when the daemon restarts repeatedly.
-const CACHE_REFRESH_SECONDS: u64 = 20 * 60 * 60; // 20 hours
+/// Refresh threshold for a cached *result*. Short enough that a release
+/// published today is visible within the hour; long enough to bound outbound
+/// requests when the daemon restarts repeatedly.
+const CACHE_REFRESH_SECONDS: u64 = 60 * 60; // 1 hour
-/// HTTP timeout for the releases API fetch. Kept tight so the background
-/// task can't linger past the daemon's normal startup window.
-const HTTP_TIMEOUT_SECONDS: u64 = 4;
+/// How long the background banner waits after a failed lookup before trying
+/// again. Explicit `check-update` / `update` calls ignore this.
+const ERROR_BACKOFF_SECONDS: u64 = 5 * 60;
/// Tag-name prefix used by the Rust-port releases on the trycua/cua repo.
/// Releases tagged with anything else (e.g. the Swift port's
@@ -64,11 +68,6 @@ const HTTP_TIMEOUT_SECONDS: u64 = 4;
pub const RELEASE_TAG_PREFIX: &str = "cua-driver-rs-v";
pub const NIGHTLY_RELEASE_TAG_PREFIX: &str = "nightly-cua-driver-rs-v";
-/// GitHub releases API endpoint. Paginates newest-first; 40 entries is
-/// plenty of headroom past the most recent stable release even when
-/// pre-releases are sprinkled in between.
-const RELEASES_URL: &str = "https://api.github.com/repos/trycua/cua/releases?per_page=40";
-
// ── Public API ───────────────────────────────────────────────────────────
/// Kick off a background "is there a newer release?" check.
@@ -94,7 +93,12 @@ pub fn maybe_announce_update() {
let current = env!("CARGO_PKG_VERSION").to_owned();
let task = move || {
- run_check_and_announce(&current, fetch_latest_version, std::io::stderr(), true);
+ run_check_and_announce(
+ &current,
+ || fetch_latest_version().map_err(|e| e.to_string()),
+ std::io::stderr(),
+ true,
+ );
};
if tokio::runtime::Handle::try_current().is_ok() {
@@ -186,8 +190,8 @@ fn install_one_liner() -> String {
///
/// Drives the same fetch + cache primitives the launch-time banner uses,
/// so the two paths never disagree on which tag is "latest". Respects the
-/// 20-hour `CACHE_REFRESH_SECONDS` unless `no_cache=true`, which forces a
-/// fresh GitHub round-trip (and rewrites the cache on success).
+/// 1-hour `CACHE_REFRESH_SECONDS` unless `no_cache=true`, which forces a
+/// fresh lookup (and rewrites the cache on success).
///
/// Never panics, never returns an error type — fetch failures land in
/// `UpdateState.error` with a non-empty `current_version` so consumers
@@ -239,17 +243,10 @@ pub(crate) fn check_update_state_with_ownership(no_cache: bool, managed: bool) -
};
let cached = read_cache().unwrap_or_default();
- let cache_fresh = cached
- .last_checked_unix
- .map(|t| now.saturating_sub(t) < CACHE_REFRESH_SECONDS)
- .unwrap_or(false);
// Honour the cache unless caller explicitly asked us to bypass it.
// Mirrors `npm outdated --no-cache` / `brew update --force` semantics.
- let cache_channel_matches =
- cached.channel.as_deref().unwrap_or("stable") == selected_channel.as_str();
- let use_cache =
- !no_cache && cache_fresh && cache_channel_matches && cached.latest_version.is_some();
+ let use_cache = !no_cache && cache_is_usable(&cached, now, &current, selected_channel);
let (latest, cache_hit, fetch_error) = if use_cache {
(cached.latest_version.clone(), true, None)
@@ -257,32 +254,23 @@ pub(crate) fn check_update_state_with_ownership(no_cache: bool, managed: bool) -
match fetch_latest_version_for(selected_channel) {
Ok(v) => {
// Persist on success so the next launch can reuse the answer.
- let new_cache = VersionCache {
- last_checked_unix: Some(now),
- last_checked_at: Some(checked_at.clone()),
- latest_version: Some(v.clone()),
- channel: Some(selected_channel.as_str().to_owned()),
- dismissed_versions: cached.dismissed_versions.clone(),
- };
- if let Err(e) = write_cache(&new_cache) {
- tracing::debug!(target: "cua_driver::version_check",
- "failed to write cache: {e}");
- }
+ persist_result(&cached, now, &current, selected_channel, &v);
(Some(v), false, None)
}
Err(e) => {
- // Network failure — fall back to whatever the cache holds
- // (better a slightly-stale answer than nothing). The error
- // surfaces only when no cache is available.
tracing::debug!(target: "cua_driver::version_check",
"fetch failed: {e}");
+ persist_error(&cached, now);
+ // Fall back to a cached answer we still trust (same build and
+ // channel, not behind the running version) — better a slightly
+ // old answer than none. The error surfaces only otherwise.
match cached
.latest_version
.clone()
- .filter(|_| cache_channel_matches)
+ .filter(|_| cache_is_trustworthy(&cached, &current, selected_channel))
{
Some(v) => (Some(v), true, None),
- None => (None, false, Some(e)),
+ None => (None, false, Some(e.to_string())),
}
}
}
@@ -321,6 +309,104 @@ pub(crate) fn check_update_state_with_ownership(no_cache: bool, managed: bool) -
}
}
+// ── Cache policy ─────────────────────────────────────────────────────────
+
+/// The cache may be consulted for this build and channel at all.
+///
+/// Rejects an answer that cannot be right: it names another channel, it was
+/// written by a different build (the binary was replaced since, so "latest"
+/// has likely moved), or it is older than the running version.
+fn cache_is_trustworthy(
+ cached: &VersionCache,
+ current: &str,
+ channel: crate::release_channel::ReleaseChannel,
+) -> bool {
+ let Some(latest) = cached.latest_version.as_deref() else {
+ return false;
+ };
+ let channel_matches = cached.channel.as_deref().unwrap_or("stable") == channel.as_str();
+ let same_build = cached.checked_by_version.as_deref() == Some(current);
+ let behind_installed = crate::release_channel::ReleaseChannel::from_version(current)
+ == Some(channel)
+ && is_newer(current, latest);
+ channel_matches && same_build && !behind_installed
+}
+
+/// The cache is trustworthy *and* young enough to skip the lookup.
+fn cache_is_usable(
+ cached: &VersionCache,
+ now: u64,
+ current: &str,
+ channel: crate::release_channel::ReleaseChannel,
+) -> bool {
+ let fresh = cached
+ .last_checked_unix
+ .map(|t| t <= now && now - t < CACHE_REFRESH_SECONDS)
+ .unwrap_or(false);
+ fresh && cache_is_trustworthy(cached, current, channel)
+}
+
+/// Record a successful lookup, keeping the user's dismissals.
+fn persist_result(
+ previous: &VersionCache,
+ now: u64,
+ current: &str,
+ channel: crate::release_channel::ReleaseChannel,
+ latest: &str,
+) {
+ let cache = VersionCache {
+ last_checked_unix: Some(now),
+ last_checked_at: Some(iso8601(now)),
+ latest_version: Some(latest.to_owned()),
+ channel: Some(channel.as_str().to_owned()),
+ checked_by_version: Some(current.to_owned()),
+ last_error_unix: None,
+ dismissed_versions: previous.dismissed_versions.clone(),
+ };
+ if let Err(e) = write_cache(&cache) {
+ tracing::debug!(target: "cua_driver::version_check", "failed to write cache: {e}");
+ }
+}
+
+/// Record a failed lookup without disturbing the last good result.
+fn persist_error(previous: &VersionCache, now: u64) {
+ let cache = VersionCache {
+ last_error_unix: Some(now),
+ ..previous.clone()
+ };
+ if let Err(e) = write_cache(&cache) {
+ tracing::debug!(target: "cua_driver::version_check", "failed to write cache: {e}");
+ }
+}
+
+/// Drop the cached result (keeping dismissals) so the next check looks again.
+///
+/// Called after a successful install: the answer that was true before the
+/// install says nothing about what is latest now.
+pub(crate) fn invalidate_cache() {
+ let Some(previous) = read_cache() else { return };
+ let cache = VersionCache {
+ dismissed_versions: previous.dismissed_versions,
+ ..Default::default()
+ };
+ if let Err(e) = write_cache(&cache) {
+ tracing::debug!(target: "cua_driver::version_check", "failed to invalidate cache: {e}");
+ }
+}
+
+/// Record the result of an explicit `cua-driver update` lookup so the cache
+/// reflects what the user was just told.
+pub(crate) fn record_latest(channel: crate::release_channel::ReleaseChannel, latest: &str) {
+ let previous = read_cache().unwrap_or_default();
+ persist_result(
+ &previous,
+ unix_now(),
+ env!("CARGO_PKG_VERSION"),
+ channel,
+ latest,
+ );
+}
+
// ── Core logic (testable seam) ───────────────────────────────────────────
/// Inner routine wired up by [`maybe_announce_update`].
@@ -361,54 +447,36 @@ fn run_check_and_announce_with_ownership<F, W>(
return;
};
- // Decide whether the cache is still fresh enough to skip the network.
+ // Decide whether the cache is still good enough to skip the network.
let cached = read_cache().unwrap_or_default();
- let cache_channel_matches =
- cached.channel.as_deref().unwrap_or("stable") == selected_channel.as_str();
- let needs_refresh = cached
- .last_checked_unix
- .map(|t| now.saturating_sub(t) >= CACHE_REFRESH_SECONDS)
- .unwrap_or(true)
- || !cache_channel_matches;
+ let trusted = cache_is_trustworthy(&cached, current, selected_channel);
+ let needs_refresh = !cache_is_usable(&cached, now, current, selected_channel);
+ let backing_off = cached
+ .last_error_unix
+ .map(|t| t <= now && now - t < ERROR_BACKOFF_SECONDS)
+ .unwrap_or(false);
- let (latest, cache_hit) = if needs_refresh {
+ let (latest, cache_hit) = if needs_refresh && !backing_off {
match fetch() {
Ok(v) => {
// Persist on success so the next launch re-uses the answer.
- let new_cache = VersionCache {
- last_checked_unix: Some(now),
- last_checked_at: Some(iso8601(now)),
- latest_version: Some(v.clone()),
- channel: Some(selected_channel.as_str().to_owned()),
- dismissed_versions: cached.dismissed_versions.clone(),
- };
- if let Err(e) = write_cache(&new_cache) {
- tracing::debug!(target: "cua_driver::version_check",
- "failed to write cache: {e}");
- }
+ persist_result(&cached, now, current, selected_channel, &v);
(v, false)
}
Err(e) => {
tracing::debug!(target: "cua_driver::version_check",
"fetch failed: {e}");
- // Fall back to the cached value if any — better an old
+ persist_error(&cached, now);
+ // Fall back to a trusted cached value if any — better an old
// banner than none on a brief network blip.
- match cached
- .latest_version
- .clone()
- .filter(|_| cache_channel_matches)
- {
+ match cached.latest_version.clone().filter(|_| trusted) {
Some(v) => (v, true),
None => return,
}
}
}
} else {
- match cached
- .latest_version
- .clone()
- .filter(|_| cache_channel_matches)
- {
+ match cached.latest_version.clone().filter(|_| trusted) {
Some(v) => (v, true),
None => return,
}
@@ -569,6 +637,14 @@ pub(crate) struct VersionCache {
pub latest_version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel: Option<String>,
+ /// Version of the cua-driver build that wrote `latest_version`. A cache
+ /// written by another build is not trusted: the binary was replaced since
+ /// (an install or update), which is exactly when "latest" has moved.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub checked_by_version: Option<String>,
+ /// When the last lookup failed. Lets the background banner back off.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last_error_unix: Option<u64>,
#[serde(default)]
pub dismissed_versions: Vec<String>,
}
@@ -660,64 +736,57 @@ fn migrate_legacy_cache() {
// ── HTTP fetch (shared with the `update` subcommand) ─────────────────────
-/// Fetch the highest `cua-driver-rs-v*` release tag from GitHub.
+/// Resolve the latest release for the saved channel.
///
-/// Uses `ureq` (already a dep via telemetry) so we don't shell out to
-/// `curl` from a background task and stay cross-platform. Filters out:
+/// Delegates to [`crate::release_source::resolve_latest`]: for stable, the
+/// version pinned in the installer (the source `install.sh` itself uses),
+/// then the GitHub releases API (with `GH_TOKEN` / `GITHUB_TOKEN` when set),
+/// then the releases feed. Tags that don't start with the channel's prefix
+/// (Swift port, lume, SDK releases) and drafts are ignored; stable accepts
+/// only plain `x.y.z`.
///
-/// - tags that don't start with `cua-driver-rs-v` (Swift port releases)
-/// - draft releases (`"draft": true`)
-///
-/// Pre-releases (`"prerelease": true`) are NOT filtered — cua-driver-rs
-/// is pre-1.0 and the CD pipeline marks every release `prerelease=true`
-/// by convention. Stripping them out left the check finding zero
-/// candidates.
-///
-/// Returns the bare version string (e.g. `"0.1.4"`) on success, or a
-/// human-readable error string on failure. The caller is expected to
-/// downgrade errors to `tracing::debug!`.
-pub fn fetch_latest_version() -> Result<String, String> {
- let channel = crate::release_channel::selected()?;
+/// Returns the bare version string (e.g. `"0.1.4"`) on success. The error
+/// distinguishes a GitHub API rate limit from a real network failure.
+pub fn fetch_latest_version() -> Result<String, crate::release_source::FetchError> {
+ let channel =
+ crate::release_channel::selected().map_err(crate::release_source::FetchError::Other)?;
fetch_latest_version_for(channel)
}
pub fn fetch_latest_version_for(
channel: crate::release_channel::ReleaseChannel,
-) -> Result<String, String> {
+) -> Result<String, crate::release_source::FetchError> {
if crate::updater::is_pacman_managed() {
- return Err(crate::updater::PACMAN_UPDATE_GUIDANCE.to_owned());
+ return Err(crate::release_source::FetchError::Other(
+ crate::updater::PACMAN_UPDATE_GUIDANCE.to_owned(),
+ ));
}
- let agent = ureq::Agent::config_builder()
- .timeout_global(Some(std::time::Duration::from_secs(HTTP_TIMEOUT_SECONDS)))
- .build()
- .new_agent();
-
- let response = agent
- .get(RELEASES_URL)
- .header("Accept", "application/vnd.github+json")
- .header(
- "User-Agent",
- concat!("cua-driver-rs/", env!("CARGO_PKG_VERSION")),
- )
- .call()
- .map_err(|e| format!("HTTP error: {e}"))?;
-
- let body: serde_json::Value = response
- .into_body()
- .read_json()
- .map_err(|e| format!("JSON parse error: {e}"))?;
-
- pick_latest_release(&body, channel)
- .ok_or_else(|| format!("no matching {}* release in response", tag_prefix(channel)))
+ crate::release_source::resolve_latest(
+ &crate::release_source::UreqClient::new(),
+ &crate::release_source::Endpoints::default(),
+ channel,
+ crate::release_source::token_from_env().as_deref(),
+ )
}
/// Pull the highest non-draft `cua-driver-rs-v*` tag out of the parsed
/// releases response. Split out so unit tests can feed in canned JSON
/// without hitting the network. Pre-release flag is intentionally
/// ignored — see `fetch_latest_version` doc-comment.
+#[cfg(test)]
pub(crate) fn pick_latest_release(
body: &serde_json::Value,
channel: crate::release_channel::ReleaseChannel,
+) -> Option<String> {
+ pick_latest_release_excluding(body, channel, &[])
+}
+
+/// [`pick_latest_release`] that also skips withdrawn versions (bare, e.g.
+/// `"0.28.3"`), as the installer does.
+pub(crate) fn pick_latest_release_excluding(
+ body: &serde_json::Value,
+ channel: crate::release_channel::ReleaseChannel,
+ withdrawn: &[String],
) -> Option<String> {
let releases = body.as_array()?;
let mut versions: Vec<semver::Version> = releases
@@ -729,6 +798,9 @@ pub(crate) fn pick_latest_release(
return None;
}
let version = semver::Version::parse(bare).ok()?;
+ if withdrawn.iter().any(|w| w == bare) {
+ return None;
+ }
match channel {
crate::release_channel::ReleaseChannel::Stable
if !version.pre.is_empty() || !version.build.is_empty() =>
@@ -749,7 +821,7 @@ pub(crate) fn pick_latest_release(
versions.last().map(|v| v.to_string())
}
-fn tag_prefix(channel: crate::release_channel::ReleaseChannel) -> &'static str {
+pub(crate) fn tag_prefix(channel: crate::release_channel::ReleaseChannel) -> &'static str {
match channel {
crate::release_channel::ReleaseChannel::Stable => RELEASE_TAG_PREFIX,
crate::release_channel::ReleaseChannel::Nightly => NIGHTLY_RELEASE_TAG_PREFIX,
@@ -768,7 +840,7 @@ fn is_canonical_nightly(version: &semver::Version) -> bool {
// ── Time helpers ─────────────────────────────────────────────────────────
-fn unix_now() -> u64 {
+pub(crate) fn unix_now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
@@ -778,7 +850,7 @@ fn unix_now() -> u64 {
/// Render a unix timestamp as `YYYY-MM-DDTHH:MM:SSZ`. Mirrors the
/// telemetry module's formatter so the on-disk cache file stays
/// human-readable without dragging in `chrono`.
-fn iso8601(unix_secs: u64) -> String {
+pub(crate) fn iso8601(unix_secs: u64) -> String {
let (year, month, day, hour, minute, second) = civil_from_unix(unix_secs);
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
}
@@ -806,6 +878,11 @@ fn civil_from_unix(unix_secs: u64) -> (i32, u32, u32, u32, u32, u32) {
// ── Tests ────────────────────────────────────────────────────────────────
+/// All env-mutating tests serialise on this lock — `std::env::set_var`
+/// is process-global, parallel tests would race.
+#[cfg(test)]
+pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
#[cfg(test)]
mod tests {
use super::*;
@@ -813,7 +890,7 @@ mod tests {
#[test]
fn pacman_managed_check_ignores_upstream_cache_and_channel() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
with_isolated_home(|home| {
write_cache(&VersionCache {
latest_version: Some("999.0.0".into()),
@@ -855,9 +932,7 @@ mod tests {
assert!(banner.is_empty());
}
- /// All env-mutating tests serialise on this lock — `std::env::set_var`
- /// is process-global, parallel tests would race.
- static ENV_LOCK: Mutex<()> = Mutex::new(());
+ use super::ENV_LOCK;
/// Redirect `HOME` / `USERPROFILE` to a fresh temp dir for the body
/// of `f`, then restore. Ensures the cache file lives in an isolated
@@ -977,13 +1052,15 @@ mod tests {
#[test]
fn cache_round_trips_through_tempdir() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
with_isolated_home(|_| {
let original = VersionCache {
last_checked_unix: Some(1_700_000_000),
last_checked_at: Some("2023-11-14T22:13:20Z".into()),
latest_version: Some("0.1.4".into()),
channel: Some("stable".into()),
+ checked_by_version: Some("0.1.3".into()),
+ last_error_unix: None,
dismissed_versions: vec!["0.1.3".into()],
};
write_cache(&original).expect("write_cache");
@@ -996,7 +1073,7 @@ mod tests {
#[test]
fn cache_lands_in_the_canonical_home() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
with_isolated_home(|home| {
write_cache(&VersionCache::default()).expect("write_cache");
assert!(home
@@ -1011,7 +1088,7 @@ mod tests {
#[test]
fn legacy_cache_is_migrated_and_its_home_removed() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
with_isolated_home(|home| {
let legacy_home = home.join(LEGACY_HOME_SUBDIRECTORY);
std::fs::create_dir_all(&legacy_home).unwrap();
@@ -1034,7 +1111,7 @@ mod tests {
#[test]
fn migration_leaves_a_legacy_home_that_still_holds_other_files() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
with_isolated_home(|home| {
let legacy_home = home.join(LEGACY_HOME_SUBDIRECTORY);
std::fs::create_dir_all(&legacy_home).unwrap();
@@ -1052,7 +1129,7 @@ mod tests {
#[test]
fn failed_migration_preserves_the_legacy_cache() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
with_isolated_home(|home| {
let legacy_home = home.join(LEGACY_HOME_SUBDIRECTORY);
let legacy_cache = legacy_home.join(CACHE_FILE_NAME);
@@ -1075,19 +1152,21 @@ mod tests {
});
}
- // ── 20h refresh threshold ───────────────────────────────────────────
+ // ── 1h refresh threshold ────────────────────────────────────────────
#[test]
fn cache_older_than_threshold_triggers_refresh() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
with_isolated_home(|_| {
- // Seed the cache 21 hours in the past.
+ // Seed the cache 2 hours in the past.
let now = unix_now();
let stale = VersionCache {
- last_checked_unix: Some(now.saturating_sub(21 * 60 * 60)),
- last_checked_at: Some(iso8601(now.saturating_sub(21 * 60 * 60))),
+ last_checked_unix: Some(now.saturating_sub(2 * 60 * 60)),
+ last_checked_at: Some(iso8601(now.saturating_sub(2 * 60 * 60))),
latest_version: Some("0.1.3".into()), // stale data
channel: Some("stable".into()),
+ checked_by_version: Some("0.1.3".into()),
+ last_error_unix: None,
dismissed_versions: vec![],
};
write_cache(&stale).unwrap();
@@ -1117,15 +1196,17 @@ mod tests {
#[test]
fn cache_younger_than_threshold_skips_network() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
with_isolated_home(|_| {
- // Seed the cache 1 hour in the past with a known-newer version.
+ // Seed the cache 30 minutes in the past with a known-newer version.
let now = unix_now();
let fresh = VersionCache {
- last_checked_unix: Some(now.saturating_sub(60 * 60)),
- last_checked_at: Some(iso8601(now.saturating_sub(60 * 60))),
+ last_checked_unix: Some(now.saturating_sub(30 * 60)),
+ last_checked_at: Some(iso8601(now.saturating_sub(30 * 60))),
latest_version: Some("0.1.4".into()),
channel: Some("stable".into()),
+ checked_by_version: Some("0.1.3".into()),
+ last_error_unix: None,
dismissed_versions: vec![],
};
write_cache(&fresh).unwrap();
@@ -1155,7 +1236,7 @@ mod tests {
#[test]
fn dismissed_latest_suppresses_banner() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
with_isolated_home(|_| {
// Cache is fresh and reports a newer version, but the user
// dismissed exactly that version — banner must stay silent.
@@ -1165,6 +1246,8 @@ mod tests {
last_checked_at: Some(iso8601(now)),
latest_version: Some("0.1.4".into()),
channel: Some("stable".into()),
+ checked_by_version: Some("0.1.3".into()),
+ last_error_unix: None,
dismissed_versions: vec!["0.1.4".into()],
};
write_cache(&cache).unwrap();
@@ -1175,11 +1258,187 @@ mod tests {
});
}
+ // ── Stale-cache invalidation ────────────────────────────────────────
+
+ fn seeded(now: u64, age: u64, latest: &str, built_by: Option<&str>) -> VersionCache {
+ VersionCache {
+ last_checked_unix: Some(now - age),
+ last_checked_at: Some(iso8601(now - age)),
+ latest_version: Some(latest.into()),
+ channel: Some("stable".into()),
+ checked_by_version: built_by.map(Into::into),
+ last_error_unix: None,
+ dismissed_versions: vec![],
+ }
+ }
+
+ #[test]
+ fn result_cache_is_usable_only_when_young_and_from_this_build() {
+ use crate::release_channel::ReleaseChannel::Stable;
+ let now = 1_800_000_000;
+ // Young, same build: usable.
+ assert!(cache_is_usable(
+ &seeded(now, 60, "0.34.0", Some("0.33.0")),
+ now,
+ "0.33.0",
+ Stable
+ ));
+ // Older than the 1h TTL: refresh (the 20h cache of #4755 is gone).
+ assert!(!cache_is_usable(
+ &seeded(now, 2 * 3600, "0.34.0", Some("0.33.0")),
+ now,
+ "0.33.0",
+ Stable
+ ));
+ // Written by another build, e.g. before an install replaced the binary.
+ assert!(!cache_is_usable(
+ &seeded(now, 60, "0.33.4", Some("0.33.0")),
+ now,
+ "0.34.0",
+ Stable
+ ));
+ // Legacy cache with no build recorded.
+ assert!(!cache_is_usable(
+ &seeded(now, 60, "0.33.4", None),
+ now,
+ "0.33.4",
+ Stable
+ ));
+ // Clearly stale: "latest" is older than the running version.
+ assert!(!cache_is_usable(
+ &seeded(now, 60, "0.33.4", Some("0.34.0")),
+ now,
+ "0.34.0",
+ Stable
+ ));
+ // Clock skew: a timestamp from the future is not fresh.
+ let mut future = seeded(now, 0, "0.34.0", Some("0.33.0"));
+ future.last_checked_unix = Some(now + 3600);
+ assert!(!cache_is_usable(&future, now, "0.33.0", Stable));
+ // Wrong channel.
+ assert!(!cache_is_usable(
+ &seeded(now, 60, "0.34.0", Some("0.33.0")),
+ now,
+ "0.33.0",
+ crate::release_channel::ReleaseChannel::Nightly
+ ));
+ }
+
+ #[test]
+ fn stale_cache_from_older_build_is_replaced_not_announced() {
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ with_isolated_home(|_| {
+ // The #4755 shape: a young cache saying 0.33.4, written by the
+ // 0.33.4 build, read by the 0.34.0 build that replaced it.
+ let now = unix_now();
+ write_cache(&seeded(now, 600, "0.33.4", Some("0.33.4"))).unwrap();
+ let fetches = std::sync::atomic::AtomicUsize::new(0);
+ let mut buf: Vec<u8> = Vec::new();
+ run_check_and_announce(
+ "0.34.0",
+ || {
+ fetches.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok("0.34.0".into())
+ },
+ &mut buf,
+ false,
+ );
+ assert_eq!(fetches.load(std::sync::atomic::Ordering::SeqCst), 1);
+ let refreshed = read_cache().unwrap();
+ assert_eq!(refreshed.latest_version.as_deref(), Some("0.34.0"));
+ assert_eq!(refreshed.checked_by_version.as_deref(), Some("0.34.0"));
+ });
+ }
+
+ #[test]
+ fn failed_lookup_backs_off_but_never_serves_an_untrusted_result() {
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ with_isolated_home(|_| {
+ let now = unix_now();
+ let fetches = std::sync::atomic::AtomicUsize::new(0);
+ let failing = || {
+ fetches.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Err("rate limited".to_owned())
+ };
+ let count = || fetches.load(std::sync::atomic::Ordering::SeqCst);
+
+ // Cache from another build: the lookup is attempted, fails, and the
+ // untrusted 0.33.4 is not shown as a fallback.
+ write_cache(&seeded(now, 2 * 3600, "0.99.0", Some("0.33.4"))).unwrap();
+ let mut buf: Vec<u8> = Vec::new();
+ run_check_and_announce("0.33.0", failing, &mut buf, false);
+ assert_eq!(count(), 1);
+ assert!(buf.is_empty(), "untrusted result must not be announced");
+
+ // Same build, expired result: lookup fails, the trusted result is
+ // still shown, and the failure is recorded.
+ write_cache(&seeded(now, 2 * 3600, "0.34.0", Some("0.33.0"))).unwrap();
+ let mut buf: Vec<u8> = Vec::new();
+ run_check_and_announce("0.33.0", failing, &mut buf, false);
+ assert_eq!(count(), 2);
+ assert!(String::from_utf8(buf)
+ .unwrap()
+ .contains("v0.34.0 is available"));
+ let after = read_cache().unwrap();
+ assert!(after.last_error_unix.is_some());
+ assert_eq!(
+ after.latest_version.as_deref(),
+ Some("0.34.0"),
+ "last good result kept"
+ );
+
+ // Within the backoff window the lookup is not retried.
+ let mut buf: Vec<u8> = Vec::new();
+ run_check_and_announce("0.33.0", failing, &mut buf, false);
+ assert_eq!(count(), 2, "backoff");
+ assert!(String::from_utf8(buf)
+ .unwrap()
+ .contains("v0.34.0 is available"));
+ });
+ }
+
+ #[test]
+ fn invalidate_cache_drops_the_result_and_keeps_dismissals() {
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ with_isolated_home(|_| {
+ let now = unix_now();
+ let mut cache = seeded(now, 60, "0.33.4", Some("0.33.4"));
+ cache.dismissed_versions = vec!["0.33.4".into()];
+ write_cache(&cache).unwrap();
+ invalidate_cache();
+ let after = read_cache().unwrap();
+ assert!(after.latest_version.is_none());
+ assert!(after.last_checked_unix.is_none());
+ assert!(after.checked_by_version.is_none());
+ assert_eq!(after.dismissed_versions, vec!["0.33.4".to_owned()]);
+ assert!(!cache_is_usable(
+ &after,
+ now,
+ "0.33.4",
+ crate::release_channel::ReleaseChannel::Stable
+ ));
+ });
+ }
+
+ #[test]
+ fn pick_latest_release_excluding_skips_withdrawn_versions() {
+ let body = serde_json::json!([
+ {"tag_name": "cua-driver-rs-v0.30.0", "draft": false},
+ {"tag_name": "cua-driver-rs-v0.29.0", "draft": false},
+ ]);
+ let latest = pick_latest_release_excluding(
+ &body,
+ crate::release_channel::ReleaseChannel::Stable,
+ &["0.30.0".to_owned()],
+ );
+ assert_eq!(latest.as_deref(), Some("0.29.0"));
+ }
+
// ── Opt-out paths ───────────────────────────────────────────────────
#[test]
fn env_opt_out_short_circuits_enabled_check() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let saved = std::env::var_os(ENV_UPDATE_CHECK);
unsafe {
@@ -1218,7 +1477,7 @@ mod tests {
#[test]
fn config_flag_disables_check() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let saved = std::env::var_os(ENV_UPDATE_CHECK);
unsafe {
std::env::remove_var(ENV_UPDATE_CHECK);
@@ -1255,7 +1514,7 @@ mod tests {
#[test]
fn config_flag_true_or_missing_leaves_check_on() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let saved = std::env::var_os(ENV_UPDATE_CHECK);
unsafe {
std::env::remove_var(ENV_UPDATE_CHECK);
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/release_channel_cli_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/release_channel_cli_test.rs
index e735cb221d..428daebcc6 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/release_channel_cli_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/release_channel_cli_test.rs
@@ -225,9 +225,21 @@ mod pacman {
);
let state: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(state["selected_channel"], "stable");
+ // A young cache written by this exact build is honoured; the cache is
+ // bound to the build that wrote it, so seed it as such.
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
std::fs::write(
root.path().join(".cua-driver/version_check.json"),
- r#"{"latest_version":"999.0.0","channel":"stable","last_checked_unix":9999999999}"#,
+ serde_json::json!({
+ "latest_version": "999.0.0",
+ "channel": "stable",
+ "last_checked_unix": now,
+ "checked_by_version": env!("CARGO_PKG_VERSION"),
+ })
+ .to_string(),
)
.unwrap();
let output = command(&executable, root.path(), &["check-update", "--json"]);
diff --git a/scripts/docs-generators/cli-specs/cua-driver.json b/scripts/docs-generators/cli-specs/cua-driver.json
index b76bbc9172..d812e0025e 100644
--- a/scripts/docs-generators/cli-specs/cua-driver.json
+++ b/scripts/docs-generators/cli-specs/cua-driver.json
@@ -1177,7 +1177,7 @@
},
{
"default_value": false,
- "help": "Skip the 20-hour on-disk cache and force a GitHub request.",
+ "help": "Skip the 1-hour on-disk cache and look up the latest release again.",
"name": "no-cache",
"short_name": null
}