hex/src/updater.rs
Dax b361f49dbf
x86_64: opt-in Ivy Bridge source build (HEX_X86_BASELINE=ivybridge) (#2419)
* x86_64: opt-in Ivy Bridge source build (HEX_X86_BASELINE=ivybridge)

* x86_64 ivybridge build: review fixes
2026-11-22 14:36:17 -05:00

1434 lines
54 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. Checks continue while an update is staged, so a newer
//! release replaces it, and Restart to update checks once more before it
//! switches over. 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(any(target_os = "linux", target_os = "windows"))]
pub mod legacy;
pub(crate) mod notes;
#[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;
#[cfg(any(target_os = "macos", test))]
mod staging;
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, UpdateNotes};
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);
/// Failed checks back off, but never past hourly: the release service counts
/// a running install from at least one check an hour.
const MAX_BACKOFF: Duration = CHECK_INTERVAL;
/// The manifest fetch of an ordinary check.
const MANIFEST_TIMEOUT: Duration = Duration::from_secs(60);
/// The final check behind Restart to update: an unreachable service must
/// not hold the restart for long.
const RESTART_MANIFEST_TIMEOUT: Duration = Duration::from_secs(15);
/// 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, crate::VERSION);
if home == UpdateChannel::Dev.name() {
UpdateChannel::Dev
} else {
UpdateChannel::Stable
}
}
#[derive(Clone, Debug)]
enum State {
Disabled(DesktopUpdateStatus),
Checking,
Current,
Failed,
Downloading,
/// `Shared::staged` waits for the restart.
Ready,
/// 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>>,
/// The newest staged update. Checks continue while one waits, and a
/// different current release replaces it before the restart.
staged: Mutex<Option<StagedUpdate>>,
/// What the staged dev build changed, when the dev notes said.
notes: Mutex<Option<UpdateNotes>>,
/// Why this install can't update itself (Windows), shown with Download
/// update.
blocked: Mutex<Option<&'static str>>,
restart: Mutex<Restart>,
}
impl Shared {
fn new(state: State, packaged: bool) -> Self {
Self {
state: Mutex::new(state),
packaged,
wake: Mutex::new(Wake::default()),
signal: Condvar::new(),
last: Mutex::new(None),
confirmed: Mutex::new(None),
staged: Mutex::new(None),
notes: Mutex::new(None),
blocked: Mutex::new(None),
restart: Mutex::new(Restart::Idle),
}
}
}
/// A staged update and the SHA-256 of the target it came from, which tells
/// a later check whether the channel still offers that release.
#[derive(Clone, Debug)]
struct StagedUpdate {
staged: Staged,
sha256: String,
version: String,
}
#[derive(Debug, Default)]
enum Restart {
#[default]
Idle,
/// Restart to update was pressed: the worker checks the channel once
/// more, then switches to the newest staged update.
Requested,
/// The worker switched over (the host quits) or could not.
Done(std::result::Result<(), 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") || updates_off_by_env() {
Some(DesktopUpdateStatus::Unavailable)
} else if crate::app_paths::is_local_build() {
Some(DesktopUpdateStatus::SourceBuild)
} else if managed_by_policy() {
Some(DesktopUpdateStatus::Managed)
// An `HEX_X86_BASELINE=ivybridge` source build targets an older processor
// than every published artifact, so it never takes one: installing it
// would leave a Hex that can't start. A source build never checks,
// downloads, or installs, and its footer says so.
} else if method == Method::Source || cfg!(hex_x86_ivybridge) {
Some(DesktopUpdateStatus::SourceBuild)
} else {
None
};
let checks = disabled.is_none();
let shared = Arc::new(Shared::new(
match disabled {
Some(status) => State::Disabled(status),
None => State::Checking,
},
matches!(method, Method::Package(_)),
));
if method == Method::Unknown {
*lock(&shared.blocked) = platform::blocked();
}
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::new(State::Current, false)),
}
}
/// 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::new(
State::Disabled(DesktopUpdateStatus::Unavailable),
false,
)),
}
}
/// Checks now instead of at the next interval. A staged update stays
/// offered while the check looks for a newer release.
pub fn check_now(&self) {
let mut state = lock(&self.shared.state);
match &*state {
State::Disabled(_) | State::Applied | State::Downloading => return,
State::Ready => {}
_ => *state = State::Checking,
}
drop(state);
self.wake();
}
fn wake(&self) {
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();
}
/// Why this install can't update itself, while Download update shows:
/// an English sentence the window translates.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub fn blocked(&self) -> Option<&'static str> {
matches!(*lock(&self.shared.state), State::Download { .. })
.then(|| *lock(&self.shared.blocked))
.flatten()
}
/// What the staged dev build changed, while Restart to update shows.
pub fn notes(&self) -> Option<UpdateNotes> {
matches!(*lock(&self.shared.state), State::Ready | State::Applied)
.then(|| lock(&self.shared.notes).clone())
.flatten()
}
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
/// restart into the staged update. A restart finishes on the worker;
/// [`Self::take_restart`] says when Hex must quit.
pub fn act(&self, action: &DesktopAction) -> Result<()> {
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.request_restart(restart_hold())?,
_ => {}
}
Ok(())
}
/// Restart to update: the worker checks the channel once more, so a
/// release published since the update was staged replaces it first,
/// then switches to the newest staged update. A meeting recording holds
/// it: the relaunch would cut the recording short.
fn request_restart(&self, hold: Option<&'static str>) -> Result<()> {
if let Some(hold) = hold {
return Err(eyre!(hold));
}
let mut state = lock(&self.shared.state);
let mut restart = lock(&self.shared.restart);
// A second click while the restart is under way changes nothing.
if matches!(*restart, Restart::Requested) || matches!(*state, State::Applied) {
return Ok(());
}
if !matches!(*state, State::Ready) {
return Err(eyre!("no update is ready"));
}
*restart = Restart::Requested;
*state = State::Checking;
drop(restart);
drop(state);
self.wake();
Ok(())
}
/// The outcome of Restart to update, once: `Ok` when the update starts
/// as soon as Hex quits, which the caller must now do.
pub fn take_restart(&self) -> Option<Result<()>> {
let mut restart = lock(&self.shared.restart);
if !matches!(*restart, Restart::Done(_)) {
return None;
}
match std::mem::take(&mut *restart) {
Restart::Done(result) => Some(result.map_err(|error| eyre!(error))),
Restart::Idle | Restart::Requested => None,
}
}
/// 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::desktop::opencode_catalog::open_url(&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 matches!(*state, State::Applied) {
return;
}
if let Some(update) = lock(&self.shared.staged).as_ref() {
platform::install_on_quit(&update.staged);
*state = State::Applied;
}
}
}
/// `HEX_DISABLE_UPDATES=1` turns this launch's updater off, as a test build
/// has it: no checks, no network, nothing offered. For copies of Hex that
/// must stay quiet, such as benchmarks (docs/perf.md).
fn updates_off_by_env() -> bool {
std::env::var_os("HEX_DISABLE_UPDATES").is_some_and(|value| value == "1")
}
/// 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 {
let restarting = matches!(*lock(&shared.restart), Restart::Requested);
let staged = lock(&shared.staged).clone();
{
// A staged update stays offered while the check runs, and a quit
// that already installed the update is never un-applied.
let mut state = lock(&shared.state);
if !matches!(*state, State::Ready | State::Applied) {
*state = State::Checking;
}
}
let result = check(shared, method, &mut cache, staged.as_ref(), restarting);
let interval = lock(&shared.last)
.as_ref()
.map_or(CHECK_INTERVAL, |(channel, _)| check_interval(channel));
let (next, delay) = match result {
Ok(next) => {
failures = 0;
(next, interval)
}
Err(error) => {
tracing::warn!(error = %format!("{error:#}"), "update check failed");
failures = (failures + 1).min(8);
let next = if lock(&shared.staged).is_some() {
State::Ready
} else {
State::Failed
};
(next, (interval * 2u32.pow(failures)).min(MAX_BACKOFF))
}
};
if restarting {
if finish_restart(
shared,
next,
restart_hold(),
crate::desktop::process_exit::quitting(),
) {
return;
}
} else {
let mut state = lock(&shared.state);
// Restart to update was pressed during this check: the next
// check, which starts at once, finishes it.
if !matches!(*lock(&shared.restart), Restart::Requested) {
keep_applied(&mut state, next);
}
}
if wait(shared, delay) {
return;
}
}
}
/// Whether a release that just finished staging becomes the staged update.
/// A quit installs the staged update itself (`install_on_quit`), so a
/// download that lands afterwards must not replace it: the caller drops the
/// folder it unpacked, because the bundle that update replaced now lives in
/// the folder of the one the quit installed.
fn adopts_staged_update(state: &State, quitting: bool) -> bool {
!quitting && !matches!(state, State::Applied)
}
/// The state a check leaves when it discards the release it staged because a
/// quit is installing (or already installed) another. The older staged update
/// must stay installable at quit (`Ready`), and an installed one keeps
/// `Applied`; `Current` is the honest result when nothing is staged.
fn discarded_state(state: &State, staged: bool) -> State {
if matches!(state, State::Applied) {
State::Applied
} else if staged {
State::Ready
} else {
State::Current
}
}
/// Why Restart to update has to wait: a recording or a launch recovery is
/// still finishing a meeting, and the relaunch would cut it off.
fn restart_hold() -> Option<&'static str> {
crate::meeting::recording()
.then_some("Hex is finishing a meeting; restart to update when it's done")
}
/// Writes `next` unless a quit already installed the staged update. That
/// state must survive every later check: the bundle beneath this process has
/// already been swapped, so a second swap would exchange it back.
fn keep_applied(state: &mut State, next: State) {
if !matches!(*state, State::Applied) {
*state = next;
}
}
/// Switches to the newest staged update once Restart to update's final
/// check has run, whatever its result. True when Hex now quits. A meeting
/// that started recording since the click keeps the update staged and the
/// restart waiting, and a quit that began during the check never swaps: the
/// drain installs the update itself.
fn finish_restart(
shared: &Shared,
next: State,
hold: Option<&'static str>,
quitting: bool,
) -> bool {
let mut state = lock(&shared.state);
// Quitting installs the staged update itself (`install_on_quit`), and it
// holds this lock while it does; a swap here would exchange the same two
// bundles back and lose the update.
if matches!(*state, State::Applied) {
*lock(&shared.restart) = Restart::Done(Ok(()));
return true;
}
if quitting {
// The drain installs what is staged; this check must not swap, nor
// hold the quit for an update that is already being installed.
*lock(&shared.restart) = Restart::Done(Ok(()));
tracing::info!("a quit started during Restart to update; the drain installs it");
return true;
}
if let Some(hold) = hold {
let staged = lock(&shared.staged).is_some();
*state = if staged { State::Ready } else { next };
*lock(&shared.restart) = Restart::Done(Err(hold.into()));
tracing::info!(reason = hold, "Restart to update waits for a meeting");
return false;
}
let staged = lock(&shared.staged).clone();
let result = match &staged {
Some(update) => {
platform::restart_into(&update.staged).map_err(|error| format!("{error:#}"))
}
None => Err("no update is ready".into()),
};
let restarted = result.is_ok();
if let Err(error) = &result {
tracing::warn!(%error, "could not restart into the update");
}
*state = if restarted {
State::Applied
} else if staged.is_some() {
State::Ready
} else {
next
};
*lock(&shared.restart) = Restart::Done(result);
restarted
}
fn check(
shared: &Shared,
method: &Method,
cache: &mut transport::ManifestCache,
staged: Option<&StagedUpdate>,
restarting: bool,
) -> 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, crate::VERSION);
let channel = channel(method, setting, &home);
let user_agent = transport::user_agent(&home, crate::VERSION);
*lock(&shared.last) = Some((channel.clone(), std::time::Instant::now()));
let manifest_url = manifest_url(&channel);
let timeout = if restarting {
RESTART_MANIFEST_TIMEOUT
} else {
MANIFEST_TIMEOUT
};
let manifest = cache.fetch(&manifest_url, &user_agent, &updates, timeout)?;
let install = Install {
version: crate::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 { .. } | Decision::Install { .. }
if staged.is_some_and(|staged| !replaces_staged(&decision, &staged.sha256)) =>
{
// The notes may have been published after the build was staged.
if let Some(staged) = staged
&& !restarting
&& lock(&shared.notes).is_none()
{
fetch_notes(shared, &channel, &user_agent, &updates, &staged.version);
}
Ok(State::Ready)
}
Decision::None { .. } => {
transport::prune(&updates, None);
#[cfg(target_os = "windows")]
if matches!(method, Method::Direct { .. }) && platform::console_missing() {
let installed = download_console(&manifest, &manifest_url, &user_agent, &updates)
.and_then(|file| file.map_or(Ok(()), |file| platform::install_console(&file)));
if let Err(error) = installed {
tracing::warn!(error = %format!("{error:#}"), "could not add hex.com to this install");
}
}
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))?;
// A staged update stays offered while a newer one downloads in
// the background.
if staged.is_none() || restarting {
keep_applied(&mut lock(&shared.state), State::Downloading);
}
transport::prune(&updates, Some(&target.sha256));
#[cfg(target_os = "linux")]
verify_linux_signature(&manifest, &manifest_url, &user_agent, &target, &updates)?;
let file = transport::download(&url, &user_agent, &target, &updates)?;
#[cfg(target_os = "windows")]
let staged = download_console(&manifest, &manifest_url, &user_agent, &updates)
.and_then(|console| platform::stage(&file, console.as_deref(), &version));
#[cfg(not(target_os = "windows"))]
let staged = platform::stage(&file, &version);
let staged = staged.wrap_err_with(|| format!("could not stage Hex {version}"))?;
// A quit installs the staged update itself (`install_on_quit`) and
// holds both locks, so take them in the same order and look again
// under them: a release that lands after that must not replace the
// installed one or remove the folder its replaced bundle lives in.
#[cfg(target_os = "macos")]
let kept = staged.clone();
{
let state = lock(&shared.state);
let mut staged_updates = lock(&shared.staged);
if !adopts_staged_update(&state, crate::desktop::process_exit::quitting()) {
let next = discarded_state(&state, staged_updates.is_some());
drop(staged_updates);
drop(state);
#[cfg(target_os = "macos")]
platform::discard(&kept);
return Ok(next);
}
*staged_updates = Some(StagedUpdate {
staged,
sha256: target.sha256,
version: version.clone(),
});
}
// Now that this release is the staged update, the unpacked folder
// of the release it replaced is no longer needed.
#[cfg(target_os = "macos")]
platform::remove_superseded(&kept);
*lock(&shared.notes) = None;
// Restart to update's final check quits right after; notes
// would only hold it up.
if !restarting {
fetch_notes(shared, &channel, &user_agent, &updates, &version);
}
Ok(State::Ready)
}
}
}
/// What the staged dev build changed; nothing for other channels or when
/// the dev notes don't list it yet.
fn fetch_notes(shared: &Shared, channel: &str, user_agent: &str, updates: &Path, version: &str) {
if channel != UpdateChannel::Dev.name() {
return;
}
let notes = notes::fetch(user_agent, &updates.join("notes"), crate::VERSION, version);
*lock(&shared.notes) = notes;
}
/// Checks the manifest's `<target>-sig` file: Anomaly's release key signing
/// the SHA-256 the executable is downloaded against. Without it, whoever
/// controls the manifest could name any executable.
#[cfg(target_os = "linux")]
fn verify_linux_signature(
manifest: &str,
manifest_url: &str,
user_agent: &str,
target: &protocol::Target,
updates: &Path,
) -> Result<()> {
let manifest = protocol::parse_manifest(manifest)
.ok_or_else(|| eyre!("the update manifest was rejected: malformed"))?;
let signature = manifest
.release
.target(&platform::signature_target())
.ok_or_else(|| eyre!("the Linux update has no signature"))?;
if signature.size != 64 {
return Err(eyre!("the Linux update's signature is malformed"));
}
let url = protocol::resolve_url(manifest_url, &signature.url)
.ok_or_else(|| eyre!("the signature URL {} is not usable", signature.url))?;
let file = transport::download(&url, user_agent, signature, updates)?;
platform::verify_signature(&target.sha256, &std::fs::read(file)?)
}
/// The release's `hex.com` (`<target>-cli`), checked against the manifest's
/// size and SHA-256; none when the release has no console entry point.
#[cfg(target_os = "windows")]
fn download_console(
manifest: &str,
manifest_url: &str,
user_agent: &str,
updates: &Path,
) -> Result<Option<PathBuf>> {
let Some(manifest) = protocol::parse_manifest(manifest) else {
return Ok(None);
};
let Some(target) = manifest.release.target(platform::CONSOLE_TARGET) else {
return Ok(None);
};
let url = protocol::resolve_url(manifest_url, &target.url)
.ok_or_else(|| eyre!("the hex.com URL {} is not usable", target.url))?;
transport::download(&url, user_agent, target, updates).map(Some)
}
/// Whether `decision` replaces the staged update: only a different release
/// this install takes by itself does. A rollout that has not reached this
/// install, an unconfirmed channel switch, or the same release keeps it.
fn replaces_staged(decision: &Decision, staged_sha256: &str) -> bool {
matches!(
decision,
Decision::Install {
reason: protocol::Reason::Update | protocol::Reason::Required,
target,
..
} if target.sha256 != staged_sha256
)
}
/// `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 bytes = std::fs::read(root.join("install.json")).ok()?;
// Tolerate a byte order mark: some UTF-8 writers add one.
let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&bytes);
let receipt: Receipt = serde_json::from_slice(bytes).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::new(state, packaged)),
};
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());
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 only_a_different_release_this_install_takes_replaces_a_staged_update() {
let running = install("0.0.0-dev-40", 'a', "dev");
let staged = "b".repeat(64);
let decide = |channel: &str, version: &str, sha: char| {
protocol::decide(
APP,
ARTIFACT,
channel,
&manifest(channel, version, sha),
&running,
)
};
assert!(!replaces_staged(
&decide("dev", "0.0.0-dev-41", 'b'),
&staged
));
assert!(replaces_staged(
&decide("dev", "0.0.0-dev-42", 'c'),
&staged
));
// The channel rolled back to the running build: nothing to install.
assert!(!replaces_staged(
&decide("dev", "0.0.0-dev-40", 'a'),
&staged
));
// Another channel's release waits for the user to confirm it.
assert!(!replaces_staged(&decide("stable", "2.3.1", 'c'), &staged));
}
#[test]
fn a_restart_after_a_quit_installed_the_update_does_not_swap_again() {
let updater = Updater::idle_checking();
// Quitting installed the staged update and set Applied; the final
// restart check finishes afterwards.
*lock(&updater.shared.state) = State::Applied;
*lock(&updater.shared.restart) = Restart::Requested;
assert!(
finish_restart(&updater.shared, State::Ready, None, false),
"the quit already installed the update; Hex still quits"
);
assert!(matches!(
*lock(&updater.shared.restart),
Restart::Done(Ok(()))
));
assert!(matches!(*lock(&updater.shared.state), State::Applied));
}
#[test]
fn a_restart_check_that_races_a_quit_never_swaps() {
let updater = Updater::idle_checking();
*lock(&updater.shared.state) = State::Ready;
*lock(&updater.shared.restart) = Restart::Requested;
// A quit began during the final check: the drain installs whatever is
// staged, so this check must not swap (nor report "no update").
assert!(finish_restart(&updater.shared, State::Ready, None, true));
assert!(matches!(
*lock(&updater.shared.restart),
Restart::Done(Ok(()))
));
assert!(matches!(*lock(&updater.shared.state), State::Ready));
}
#[test]
fn a_release_discarded_at_quit_leaves_the_older_one_installable() {
// v1 is staged and a quit begins while v2 finishes downloading: v2 is
// discarded, but the state must stay Ready so install_on_quit (which
// skips only Applied) still installs v1.
assert!(matches!(discarded_state(&State::Ready, true), State::Ready));
// A quit that already installed the update keeps Applied.
assert!(matches!(
discarded_state(&State::Applied, true),
State::Applied
));
// Nothing staged: a plain current result, not a claim of installation.
assert!(matches!(
discarded_state(&State::Current, false),
State::Current
));
}
#[test]
fn a_quit_that_installed_the_update_is_never_overwritten() {
let mut state = State::Applied;
keep_applied(&mut state, State::Current);
assert!(matches!(state, State::Applied));
let mut state = State::Ready;
keep_applied(&mut state, State::Current);
assert!(matches!(state, State::Current));
}
#[test]
fn restart_to_update_waits_while_a_meeting_records() {
let updater = Updater::idle_checking();
*lock(&updater.shared.state) = State::Ready;
let hold = Some("Hex is finishing a meeting; restart to update when it's done");
let error = updater.request_restart(hold).unwrap_err();
assert!(error.to_string().contains("meeting"));
assert!(matches!(*lock(&updater.shared.state), State::Ready));
assert!(
matches!(*lock(&updater.shared.restart), Restart::Idle),
"a refused restart is not left pending"
);
// A meeting that started after the click keeps the restart waiting.
// Nothing is staged in this test, so the state follows the check's
// result rather than claiming an update is ready.
assert!(!finish_restart(
&updater.shared,
State::Current,
hold,
false
));
assert!(matches!(*lock(&updater.shared.state), State::Current));
assert!(matches!(
*lock(&updater.shared.restart),
Restart::Done(Err(_))
));
}
#[test]
fn a_release_that_finishes_staging_after_a_quit_installed_one_is_discarded() {
// Hex is still running: the release becomes the staged update.
assert!(adopts_staged_update(&State::Ready, false));
assert!(adopts_staged_update(&State::Checking, false));
assert!(adopts_staged_update(&State::Downloading, false));
assert!(adopts_staged_update(&State::Current, false));
// Quitting installs what was staged (`install_on_quit`), so a release
// that lands later must not replace it: the folder it unpacked into
// holds the bundle the installed update replaced.
assert!(!adopts_staged_update(&State::Ready, true));
assert!(!adopts_staged_update(&State::Downloading, true));
assert!(!adopts_staged_update(&State::Applied, false));
assert!(!adopts_staged_update(&State::Applied, true));
}
#[test]
fn restart_to_update_checks_once_more_and_reports_once() {
let updater = Updater::idle_checking();
assert!(
updater.act(&DesktopAction::RestartIntoUpdate).is_err(),
"nothing is staged"
);
*lock(&updater.shared.state) = State::Ready;
updater.check_now();
assert_eq!(
updater.status(),
DesktopUpdateStatus::ReadyToRestart,
"a check keeps the staged update offered"
);
assert!(
lock(&updater.shared.wake).check,
"a staged update still checks"
);
lock(&updater.shared.wake).check = false;
updater.act(&DesktopAction::RestartIntoUpdate).unwrap();
assert_eq!(updater.status(), DesktopUpdateStatus::Checking);
assert!(
lock(&updater.shared.wake).check,
"the final check starts at once"
);
updater
.act(&DesktopAction::RestartIntoUpdate)
.expect("a second click changes nothing");
assert!(
updater.take_restart().is_none(),
"the final check is running"
);
*lock(&updater.shared.restart) = Restart::Done(Ok(()));
assert!(matches!(updater.take_restart(), Some(Ok(()))));
assert!(updater.take_restart().is_none(), "reported once");
}
#[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"
);
}
}