hex/src/updater.rs
Dax 197ea1883c
Linux ARM64, .deb, and .rpm releases (#239)
* Linux ARM64, .deb, and .rpm releases

Both Linux architectures build natively on Ubuntu 24.04 runners (glibc 2.39
floor, Vulkan on both), publish linux-arm64 plus linux-<arch>-deb and -rpm
(hex.deb, hex.rpm) built with nfpm and installed on Ubuntu and Fedora in the
build job. hex-bin gains aarch64. Package installs report deb-<arch> or
rpm-<arch> through dpkg/rpm ownership and get the stable update command.

* build-linux.sh prints only the executable's path

* Linux releases link no system BLAS, as the Arch build shipped

* Linux build: keep libopenblas-dev for build.rs's dropped -lopenblas
2026-10-27 21:50:19 -04:00

892 lines
32 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Hex's in-app updater on every OS, a client of the Anomaly release service
//! (`docs/plans/release-service.md`). One worker polls the channel's manifest
//! 10 seconds after launch, then hourly or on "Check for updates", decides with the
//! protocol's client rules, and for a direct install downloads the target,
//! checks its size, SHA-256, and OS code signature, and stages it until the
//! user restarts. Versions are display text and never compared: whenever the
//! channel's current release is not the running build (its target SHA-256,
//! else its exact version), Hex takes it, and switching channels does so
//! after the user confirms. Package-managed installs only learn the command to run;
//! source builds, test builds, and installs whose administrator set
//! `DisableUpdates` never check. Manifests are not signed: HTTPS, the
//! manifest's SHA-256, and (macOS, Windows) the code signature are the
//! integrity checks.
#[cfg_attr(target_os = "linux", path = "updater/linux.rs")]
#[cfg_attr(target_os = "macos", path = "updater/macos.rs")]
#[cfg_attr(target_os = "windows", path = "updater/windows.rs")]
mod platform;
pub mod protocol;
mod transport;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;
use color_eyre::eyre::{Result, WrapErr, eyre};
use crate::app_settings::{AppSettings, UpdateChannel};
use crate::desktop_host::{DesktopAction, DesktopUpdateStatus};
use protocol::{Decision, Install};
use platform::Staged;
#[cfg(target_os = "macos")]
pub use platform::finish_on_launch;
const APP: &str = "hex";
const ARTIFACT: &str = "desktop";
const ORIGIN: &str = "https://anoma.ly/release";
const STARTUP_DELAY: Duration = Duration::from_secs(10);
const CHECK_INTERVAL: Duration = Duration::from_secs(60 * 60);
/// Dev builds land on every push to dev, so the Dev channel checks often.
const DEV_CHECK_INTERVAL: Duration = Duration::from_secs(10 * 60);
/// Opening or focusing the window checks the Dev channel at most this often.
const FOCUS_CHECK_GAP: Duration = Duration::from_secs(60);
const MAX_BACKOFF: Duration = Duration::from_secs(6 * 60 * 60);
/// How this install receives updates, which decides what the updater does.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Method {
/// Our installer's receipt (or, on macOS, a writable `Hex.app`): Hex
/// downloads and stages updates itself on this channel.
Direct { channel: String },
/// A direct install Hex cannot replace (macOS: a read-only or translocated
/// location); updates link to the download.
DownloadOnly,
/// A package manager (`aur`, `deb-x64`, `rpm-arm64`, `nix`, `brew`, …) updates
/// it; Hex shows its command once it serves a newer version.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
Package(&'static str),
/// Built from a checkout, which updates it.
Source,
/// Anything else, such as a downloaded executable run in place.
#[cfg_attr(target_os = "macos", allow(dead_code))]
Unknown,
}
impl Method {
fn distribution(&self) -> &str {
match self {
Self::Direct { .. } | Self::DownloadOnly => "direct",
Self::Package(kind) => kind,
Self::Source | Self::Unknown => "unknown",
}
}
fn channel(&self) -> &str {
match self {
Self::Direct { channel } => channel,
_ => "stable",
}
}
}
/// The channel the Release workflow published this build on, stamped at
/// build time beside its version (`HEX_BUILD_CHANNEL`).
const BUILD_CHANNEL: Option<&str> = option_env!("HEX_BUILD_CHANNEL");
/// The channel this build belongs to: the one it was published on, else
/// (builds from before the stamp) `dev` for a dev version, else the
/// install's own channel. Package managers follow `stable`.
fn home_channel(method: &Method, built: Option<&str>, version: &str) -> String {
if matches!(method, Method::Package(_)) {
return method.channel().into();
}
match built.filter(|channel| ["stable", "beta", "dev"].contains(channel)) {
Some(channel) => channel.into(),
None if is_dev_version(version) => UpdateChannel::Dev.name().into(),
None => method.channel().into(),
}
}
/// The channel to check: the `updates.channel` setting, else the build's
/// own. Package managers follow `stable`. A setting other than the build's
/// channel makes the decision a switch, which waits for the user.
fn channel(method: &Method, setting: Option<UpdateChannel>, home: &str) -> String {
match setting {
Some(channel) if !matches!(method, Method::Package(_)) => channel.name().into(),
_ => home.into(),
}
}
/// Dev builds are `0.0.0-dev-<run>` (`X.Y.Z-dev.N` before 2026-10-27).
fn is_dev_version(version: &str) -> bool {
version.contains("-dev")
}
/// The control that confirms a channel switch, e.g. "Switch to Stable 2.3.1".
pub fn switch_label(channel: &str, version: &str) -> String {
let channel = match channel {
"dev" => UpdateChannel::Dev.label(),
"stable" => UpdateChannel::Stable.label(),
other => other,
};
crate::desktop_i18n::tr_named(
"Switch to {channel} {version}",
&[
("channel", crate::desktop_i18n::tr(channel)),
("version", version),
],
)
}
/// The Update channel Settings shows when none is saved: this build's own.
pub fn build_channel() -> UpdateChannel {
let home = home_channel(&Method::Unknown, BUILD_CHANNEL, env!("CARGO_PKG_VERSION"));
if home == UpdateChannel::Dev.name() {
UpdateChannel::Dev
} else {
UpdateChannel::Stable
}
}
#[derive(Clone, Debug)]
enum State {
Disabled(DesktopUpdateStatus),
Checking,
Current,
Failed,
Downloading,
Ready(Staged),
/// Switched over; the restart is under way.
Applied,
/// A newer release this install cannot apply itself.
Download {
url: String,
},
/// The setting names another channel, whose current release waits for
/// the user to confirm the switch.
Switch {
channel: String,
version: String,
sha256: String,
},
/// The package manager serves another version.
Command {
command: String,
},
}
struct Shared {
state: Mutex<State>,
/// A package manager installed Hex, so "up to date" is its to say.
packaged: bool,
/// Set by "Check for updates" and `stop`; the worker waits on it between checks.
wake: Mutex<Wake>,
signal: Condvar,
/// The channel and start of the latest check.
last: Mutex<Option<(String, std::time::Instant)>>,
/// The SHA-256 of the other channel's release the user agreed to switch to.
confirmed: Mutex<Option<String>>,
}
#[derive(Default)]
struct Wake {
check: bool,
stop: bool,
}
#[derive(Clone)]
pub struct Updater {
shared: Arc<Shared>,
}
impl Updater {
pub fn start() -> Self {
let method = platform::method();
let disabled = if option_env!("HEX_TEST_BUILD") == Some("1") {
Some(DesktopUpdateStatus::Unavailable)
} else if managed_by_policy() {
Some(DesktopUpdateStatus::Managed)
} else if method == Method::Source {
Some(DesktopUpdateStatus::SourceBuild)
} else {
None
};
let checks = disabled.is_none();
let shared = Arc::new(Shared {
state: Mutex::new(match disabled {
Some(status) => State::Disabled(status),
None => State::Checking,
}),
packaged: matches!(method, Method::Package(_)),
wake: Mutex::new(Wake::default()),
signal: Condvar::new(),
last: Mutex::new(None),
confirmed: Mutex::new(None),
});
if checks {
let worker = shared.clone();
if let Err(error) = std::thread::Builder::new()
.name("updater".into())
.spawn(move || run(&worker, &method))
{
tracing::error!(%error, "could not start the updater");
*lock(&shared.state) = State::Failed;
}
}
Self { shared }
}
/// An updater with no worker in the Current state, for tests of when it
/// asks for a check.
#[cfg(test)]
fn idle_checking() -> Self {
Self {
shared: Arc::new(Shared {
state: Mutex::new(State::Current),
packaged: false,
wake: Mutex::new(Wake::default()),
signal: Condvar::new(),
last: Mutex::new(None),
confirmed: Mutex::new(None),
}),
}
}
/// An updater that never checks, for tests of the hosts that own one.
#[cfg(all(test, target_os = "linux"))]
pub fn idle() -> Self {
Self {
shared: Arc::new(Shared {
state: Mutex::new(State::Disabled(DesktopUpdateStatus::Unavailable)),
packaged: false,
wake: Mutex::new(Wake::default()),
signal: Condvar::new(),
last: Mutex::new(None),
confirmed: Mutex::new(None),
}),
}
}
/// Checks now instead of at the next interval. A staged update stays
/// ready until the restart.
pub fn check_now(&self) {
let mut state = lock(&self.shared.state);
if matches!(
&*state,
State::Disabled(_) | State::Ready(_) | State::Applied | State::Downloading
) {
return;
}
*state = State::Checking;
drop(state);
lock(&self.shared.wake).check = true;
self.shared.signal.notify_all();
}
/// The window opened or gained focus: on the Dev channel, check now
/// unless a check started within the last minute.
pub fn window_focused(&self) {
let recent = lock(&self.shared.last)
.as_ref()
.is_some_and(|(channel, at)| channel != "dev" || at.elapsed() < FOCUS_CHECK_GAP);
if !recent {
self.check_now();
}
}
pub fn stop(&self) {
lock(&self.shared.wake).stop = true;
self.shared.signal.notify_all();
}
pub fn status(&self) -> DesktopUpdateStatus {
match &*lock(&self.shared.state) {
State::Disabled(status) => status.clone(),
// A package manager updates Hex: its own checks only look for
// the manager's command, so they show nothing of their own.
State::Checking | State::Current | State::Failed if self.shared.packaged => {
DesktopUpdateStatus::PackageManager
}
State::Checking => DesktopUpdateStatus::Checking,
State::Current => DesktopUpdateStatus::Current,
State::Failed => DesktopUpdateStatus::Failed,
State::Downloading => DesktopUpdateStatus::Downloading,
State::Ready(_) | State::Applied => DesktopUpdateStatus::ReadyToRestart,
State::Download { .. } => DesktopUpdateStatus::Available,
State::Switch {
channel, version, ..
} => DesktopUpdateStatus::SwitchAvailable {
channel: channel.clone(),
version: version.clone(),
},
State::Command { command } => DesktopUpdateStatus::PackageUpdate {
command: command.clone(),
},
}
}
/// Carries out an update control: check now, open the download, or
/// switch to the staged update. True when Hex must now quit so the
/// update can start.
pub fn act(&self, action: &DesktopAction) -> Result<bool> {
match action {
DesktopAction::CheckForUpdates => self.check_now(),
DesktopAction::WindowFocused => self.window_focused(),
DesktopAction::OpenUpdate => self.open_download(),
DesktopAction::ConfirmUpdateSwitch => self.confirm_switch(),
DesktopAction::RestartIntoUpdate => {
self.restart_into_update()?;
return Ok(true);
}
_ => {}
}
Ok(false)
}
/// The action of a single "update" menu item, which follows the status.
#[cfg(target_os = "macos")]
pub fn menu_action(&self) -> DesktopAction {
match self.status() {
DesktopUpdateStatus::ReadyToRestart => DesktopAction::RestartIntoUpdate,
DesktopUpdateStatus::Available => DesktopAction::OpenUpdate,
DesktopUpdateStatus::SwitchAvailable { .. } => DesktopAction::ConfirmUpdateSwitch,
_ => DesktopAction::CheckForUpdates,
}
}
/// The user agreed to switch to the other channel's release on offer:
/// download and stage it now.
fn confirm_switch(&self) {
let State::Switch { sha256, .. } = lock(&self.shared.state).clone() else {
return;
};
*lock(&self.shared.confirmed) = Some(sha256);
self.check_now();
}
/// Opens the download an install that cannot update itself needs.
fn open_download(&self) {
let State::Download { url } = lock(&self.shared.state).clone() else {
return;
};
if let Err(error) = crate::commands::execute(crate::commands::Action::OpenUrl(url)) {
tracing::warn!(%error, "could not open the Hex download");
}
}
/// Quitting with an update ready installs it for the next launch; the
/// other platforms activate it when it is staged.
#[cfg(target_os = "macos")]
pub fn install_on_quit(&self) {
let mut state = lock(&self.shared.state);
if let State::Ready(staged) = &*state {
platform::install_on_quit(staged);
*state = State::Applied;
}
}
/// Switches to the staged update and starts it once this process exits;
/// the caller quits Hex afterwards.
fn restart_into_update(&self) -> Result<()> {
let mut state = lock(&self.shared.state);
let State::Ready(staged) = &*state else {
return Err(eyre!("no update is ready"));
};
platform::restart_into(staged)?;
*state = State::Applied;
Ok(())
}
}
/// Whether an administrator turned updates off (`DisableUpdates`), read
/// once per launch so a managed value applies at the next one.
pub fn managed_by_policy() -> bool {
static MANAGED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*MANAGED.get_or_init(platform::updates_disabled_by_policy)
}
/// Shown in place of update actions when an administrator turned them off.
#[cfg(target_os = "macos")]
pub const MANAGED_LABEL: &str = "Updates Managed by Your Organization";
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(|error| error.into_inner())
}
/// Waits `delay` or until woken; true when the updater should stop.
fn wait(shared: &Shared, delay: Duration) -> bool {
let mut wake = lock(&shared.wake);
let deadline = std::time::Instant::now() + delay;
while !wake.check && !wake.stop {
let now = std::time::Instant::now();
if now >= deadline {
break;
}
wake = shared
.signal
.wait_timeout(wake, deadline - now)
.unwrap_or_else(|error| error.into_inner())
.0;
}
wake.check = false;
wake.stop
}
/// How often a channel is checked: Dev every few minutes, others hourly.
fn check_interval(channel: &str) -> Duration {
if channel == "dev" {
DEV_CHECK_INTERVAL
} else {
CHECK_INTERVAL
}
}
fn run(shared: &Shared, method: &Method) {
let mut cache = transport::ManifestCache::default();
let mut failures = 0;
if wait(shared, STARTUP_DELAY) {
return;
}
loop {
*lock(&shared.state) = State::Checking;
let result = check(shared, method, &mut cache);
let interval = lock(&shared.last)
.as_ref()
.map_or(CHECK_INTERVAL, |(channel, _)| check_interval(channel));
let delay = match result {
Ok(next) => {
failures = 0;
*lock(&shared.state) = next;
interval
}
Err(error) => {
tracing::warn!(error = %format!("{error:#}"), "update check failed");
*lock(&shared.state) = State::Failed;
failures = (failures + 1).min(8);
(interval * 2u32.pow(failures)).min(MAX_BACKOFF)
}
};
if matches!(&*lock(&shared.state), State::Ready(_)) {
// A staged update waits for the restart; nothing further to check.
return;
}
if wait(shared, delay) {
return;
}
}
}
fn check(shared: &Shared, method: &Method, cache: &mut transport::ManifestCache) -> Result<State> {
let updates = updates_dir()?;
// Read each check, so a change from the window or `hex settings` applies
// at the next one.
let setting = AppSettings::saved_update_channel();
let home = home_channel(method, BUILD_CHANNEL, env!("CARGO_PKG_VERSION"));
let channel = channel(method, setting, &home);
*lock(&shared.last) = Some((channel.clone(), std::time::Instant::now()));
let manifest_url = manifest_url(&channel);
let manifest = cache.fetch(&manifest_url, &updates)?;
let install = Install {
version: env!("CARGO_PKG_VERSION").into(),
target: platform::TARGET.into(),
distribution: method.distribution().into(),
rollout_bucket: rollout_bucket(&crate::app_paths::support_dir()?)?,
sha256: match method {
Method::Direct { .. } => running_sha256(),
_ => None,
},
channel: (!matches!(method, Method::Package(_))).then_some(home),
};
let decision = protocol::decide(APP, ARTIFACT, &channel, &manifest, &install);
tracing::info!(?decision, "update decision");
match decision {
Decision::Reject { reason } => Err(eyre!("the update manifest was rejected: {reason}")),
Decision::None { .. } => {
transport::prune(&updates, None);
Ok(State::Current)
}
Decision::Notify {
command, notes_url, ..
} => Ok(match command {
Some(command) => State::Command { command },
None => State::Download {
url: notes_url.unwrap_or_else(|| "https://anoma.ly/hex".into()),
},
}),
Decision::Install {
reason: protocol::Reason::Switch,
version,
target,
} if *method != Method::DownloadOnly
&& lock(&shared.confirmed).as_deref() != Some(target.sha256.as_str()) =>
{
Ok(State::Switch {
channel,
version,
sha256: target.sha256,
})
}
Decision::Install {
version, target, ..
} => {
if *method == Method::DownloadOnly {
let url = protocol::parse_manifest(&manifest)
.and_then(|manifest| {
manifest
.release
.target(platform::DOWNLOAD_TARGET)
.and_then(|target| protocol::resolve_url(&manifest_url, &target.url))
.or(manifest.release.notes_url)
})
.unwrap_or_else(|| "https://anoma.ly/hex".into());
return Ok(State::Download { url });
}
let url = protocol::resolve_url(&manifest_url, &target.url)
.ok_or_else(|| eyre!("the update URL {} is not usable", target.url))?;
*lock(&shared.state) = State::Downloading;
transport::prune(&updates, Some(&target.sha256));
let file = transport::download(&url, &target, &updates)?;
let staged = platform::stage(&file, &version)
.wrap_err_with(|| format!("could not stage Hex {version}"))?;
Ok(State::Ready(staged))
}
}
}
/// `HEX_RELEASE_BASE_URL` (HTTPS only) points a build at another service
/// origin, for local tests against a fixture service. Nothing defaults to the
/// service's dev stage, which only tests the service itself.
fn manifest_url(channel: &str) -> String {
let origin = std::env::var("HEX_RELEASE_BASE_URL")
.ok()
.filter(|origin| origin.starts_with("https://"));
format!(
"{}/{APP}/{ARTIFACT}/{channel}.json",
origin.as_deref().unwrap_or(ORIGIN).trim_end_matches('/')
)
}
/// This build's target SHA-256, when the platform can tell (the target is
/// the executable itself); hashed once per launch.
fn running_sha256() -> Option<String> {
static SHA256: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
SHA256.get_or_init(platform::running_sha256).clone()
}
fn updates_dir() -> Result<PathBuf> {
let updates = crate::app_paths::support_dir()?.join("updates");
std::fs::create_dir_all(&updates)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&updates, std::fs::Permissions::from_mode(0o700))?;
}
Ok(updates)
}
/// This install's rollout bucket, 0–99: a random 32-bit number drawn once
/// from the OS's secure source and kept with the install. It never leaves
/// the device.
fn rollout_bucket(support: &Path) -> Result<u64> {
let path = support.join("update-bucket");
if let Some(number) = std::fs::read_to_string(&path)
.ok()
.and_then(|text| text.trim().parse::<u32>().ok())
{
return Ok(u64::from(number) % 100);
}
let mut bytes = [0; 4];
getrandom::fill(&mut bytes).map_err(|error| eyre!("no secure random source: {error}"))?;
let number = u32::from_le_bytes(bytes);
std::fs::create_dir_all(support)?;
let partial = path.with_extension("partial");
std::fs::write(&partial, format!("{number}\n"))?;
std::fs::rename(&partial, &path)?;
Ok(u64::from(number) % 100)
}
/// The channel in our installer's receipt at `root`, when it names this app
/// and root and no other user can write the root.
#[cfg_attr(target_os = "macos", allow(dead_code))]
fn receipt_channel(root: &Path) -> Option<String> {
#[derive(serde::Deserialize)]
struct Receipt {
app: String,
artifact: String,
channel: String,
method: String,
root: PathBuf,
}
let receipt: Receipt =
serde_json::from_slice(&std::fs::read(root.join("install.json")).ok()?).ok()?;
let canonical = |path: &Path| path.canonicalize().ok();
(receipt.app == APP
&& receipt.artifact == ARTIFACT
&& receipt.method == "direct"
&& canonical(&receipt.root).is_some()
&& canonical(&receipt.root) == canonical(root)
&& ["stable", "beta", "dev"].contains(&receipt.channel.as_str()))
.then_some(receipt.channel)
}
#[cfg(test)]
mod tests {
use super::*;
fn temporary(name: &str) -> PathBuf {
let path = std::env::temp_dir().join(format!("hex-updater-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
path
}
#[test]
fn the_rollout_bucket_is_drawn_once_and_kept() {
let support = temporary("bucket");
let first = rollout_bucket(&support).unwrap();
assert!(first < 100);
assert_eq!(rollout_bucket(&support).unwrap(), first);
std::fs::write(support.join("update-bucket"), "4294967295\n").unwrap();
assert_eq!(rollout_bucket(&support).unwrap(), 95);
let _ = std::fs::remove_dir_all(support);
}
#[test]
fn receipts_must_name_this_app_and_root() {
let root = temporary("receipt");
let write = |value: serde_json::Value| {
std::fs::write(root.join("install.json"), value.to_string()).unwrap()
};
let receipt = |channel: &str, root_path: &Path| serde_json::json!({"app":"hex","artifact":"desktop","channel":channel,"method":"direct","root":root_path});
assert_eq!(receipt_channel(&root), None);
write(receipt("stable", &root));
assert_eq!(receipt_channel(&root).as_deref(), Some("stable"));
write(receipt("beta", &root));
assert_eq!(receipt_channel(&root).as_deref(), Some("beta"));
write(receipt("nightly", &root));
assert_eq!(receipt_channel(&root), None);
write(receipt("stable", &std::env::temp_dir()));
assert_eq!(receipt_channel(&root), None);
write(
serde_json::json!({"app":"opencode","artifact":"desktop","channel":"stable","method":"direct","root":root}),
);
assert_eq!(receipt_channel(&root), None);
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn methods_map_to_protocol_distributions() {
assert_eq!(
Method::Direct {
channel: "beta".into()
}
.distribution(),
"direct"
);
assert_eq!(
Method::Direct {
channel: "beta".into()
}
.channel(),
"beta"
);
assert_eq!(Method::DownloadOnly.distribution(), "direct");
assert_eq!(Method::Package("aur").distribution(), "aur");
assert_eq!(Method::Unknown.distribution(), "unknown");
assert_eq!(Method::Package("aur").channel(), "stable");
}
#[test]
fn a_package_manager_install_never_shows_its_own_checks() {
let updater = |state: State, packaged: bool| Updater {
shared: Arc::new(Shared {
state: Mutex::new(state),
packaged,
wake: Mutex::new(Wake::default()),
signal: Condvar::new(),
last: Mutex::new(None),
confirmed: Mutex::new(None),
}),
};
for state in [State::Checking, State::Current, State::Failed] {
assert_eq!(
updater(state, true).status(),
DesktopUpdateStatus::PackageManager
);
}
assert_eq!(
updater(State::Checking, false).status(),
DesktopUpdateStatus::Checking
);
assert_eq!(
updater(State::Failed, false).status(),
DesktopUpdateStatus::Failed
);
}
#[test]
fn a_build_belongs_to_the_channel_it_was_published_on() {
let direct = Method::Direct {
channel: "beta".into(),
};
assert_eq!(home_channel(&direct, Some("dev"), "0.0.0-dev-40"), "dev");
assert_eq!(home_channel(&direct, Some("stable"), "2.4.0"), "stable");
// Builds from before the stamp: a dev version, else the receipt.
assert_eq!(home_channel(&direct, None, "2.3.2-dev.29"), "dev");
assert_eq!(home_channel(&direct, None, "0.0.0-dev-40"), "dev");
assert_eq!(home_channel(&direct, None, "2.4.0"), "beta");
assert_eq!(home_channel(&direct, Some("nightly"), "2.4.0"), "beta");
assert_eq!(
home_channel(&Method::Package("aur"), Some("dev"), "0.0.0-dev-40"),
"stable"
);
}
#[test]
fn the_setting_picks_the_channel_unless_a_package_manager_updates_hex() {
let direct = Method::Direct {
channel: "stable".into(),
};
assert_eq!(channel(&direct, None, "dev"), "dev");
assert_eq!(
channel(&direct, Some(UpdateChannel::Stable), "dev"),
"stable"
);
assert_eq!(channel(&direct, Some(UpdateChannel::Dev), "stable"), "dev");
assert_eq!(
channel(&Method::DownloadOnly, Some(UpdateChannel::Dev), "stable"),
"dev"
);
assert_eq!(
channel(&Method::Package("aur"), Some(UpdateChannel::Dev), "stable"),
"stable"
);
}
fn manifest(channel: &str, version: &str, sha: char) -> String {
let sha = sha.to_string().repeat(64);
serde_json::json!({
"schema": 1,
"app": "hex",
"artifact": "desktop",
"channel": channel,
"sequence": 1,
"published_at": "2026-10-27T00:00:00Z",
"release": {
"version": version,
"rollout_percent": 100,
"revoked_versions": [],
"distributions": [{ "kind": "direct" }],
"targets": {
"linux-x64": {
"url": format!("/release/hex/files/{sha}/hex"),
"sha256": sha,
"size": 1
}
}
}
})
.to_string()
}
fn install(version: &str, sha: char, channel: &str) -> Install {
Install {
version: version.into(),
target: "linux-x64".into(),
distribution: "direct".into(),
rollout_bucket: 0,
sha256: Some(sha.to_string().repeat(64)),
channel: Some(channel.into()),
}
}
#[test]
fn versions_are_never_compared_across_or_within_channels() {
let dev = install("0.0.0-dev-40", 'a', "dev");
// A legacy dev version above the new numbering still moves to it.
let legacy = install("2.3.2-dev.29", 'f', "dev");
let next = manifest("dev", "0.0.0-dev-41", 'b');
for running in [&dev, &legacy] {
assert!(matches!(
protocol::decide(APP, ARTIFACT, "dev", &next, running),
Decision::Install {
reason: protocol::Reason::Update,
..
}
));
}
let same = manifest("dev", "0.0.0-dev-40", 'a');
assert!(matches!(
protocol::decide(APP, ARTIFACT, "dev", &same, &dev),
Decision::None { .. }
));
// Stable 2.3.1 is a switch from dev, never "older".
let stable = manifest("stable", "2.3.1", 'c');
assert!(matches!(
protocol::decide(APP, ARTIFACT, "stable", &stable, &dev),
Decision::Install {
reason: protocol::Reason::Switch,
..
}
));
}
#[test]
fn a_switch_waits_for_the_user_to_confirm() {
let updater = Updater::idle_checking();
*lock(&updater.shared.state) = State::Switch {
channel: "stable".into(),
version: "2.3.1".into(),
sha256: "c".repeat(64),
};
assert_eq!(
updater.status(),
DesktopUpdateStatus::SwitchAvailable {
channel: "stable".into(),
version: "2.3.1".into()
}
);
assert!(lock(&updater.shared.confirmed).is_none());
assert!(!updater.act(&DesktopAction::ConfirmUpdateSwitch).unwrap());
assert_eq!(
lock(&updater.shared.confirmed).as_deref(),
Some("c".repeat(64).as_str())
);
assert!(lock(&updater.shared.wake).check, "confirming checks now");
}
#[test]
fn the_dev_channel_checks_every_ten_minutes_and_others_hourly() {
assert_eq!(check_interval("dev"), Duration::from_secs(600));
assert_eq!(check_interval("stable"), Duration::from_secs(3600));
assert_eq!(check_interval("beta"), Duration::from_secs(3600));
}
#[test]
fn focusing_the_window_checks_the_dev_channel_at_most_once_a_minute() {
let updater = Updater::idle_checking();
updater.window_focused();
assert!(lock(&updater.shared.wake).check, "the first focus checks");
lock(&updater.shared.wake).check = false;
*lock(&updater.shared.last) = Some(("dev".into(), std::time::Instant::now()));
updater.window_focused();
assert!(!lock(&updater.shared.wake).check, "a check just started");
*lock(&updater.shared.last) = Some((
"dev".into(),
std::time::Instant::now() - FOCUS_CHECK_GAP - Duration::from_secs(1),
));
updater.window_focused();
assert!(
lock(&updater.shared.wake).check,
"the last check is over a minute old"
);
lock(&updater.shared.wake).check = false;
*lock(&updater.shared.last) =
Some(("stable".into(), std::time::Instant::now() - CHECK_INTERVAL));
updater.window_focused();
assert!(
!lock(&updater.shared.wake).check,
"Stable keeps its hourly checks"
);
}
#[test]
fn the_manifest_url_names_app_artifact_and_channel() {
assert_eq!(
manifest_url("stable"),
"https://anoma.ly/release/hex/desktop/stable.json"
);
}
}