feat #14740: check for updates from the settings

Adds a "Nach Updates suchen" button to the settings' new Updates section,
next to the app's own version. It runs check_for_update_now, the very same
feed check the background loop uses (one implementation, shared via
UpdateSchedule), so a manual check counts as an attempt for the same
scheduler: success resets the 6 h interval and the failure count, a failure
advances the backoff by one step, and a manual and a background check never
run at the same time (serialized).

An available update leaves the same state the background check does, so the
main window's banner still shows it; the settings also show it inline with
the existing "Installieren & neu starten" button and busy guard/hint. "None"
and "error" results are shown inline (unlike the background check, which
never surfaces its errors). On Linux (can_self_update) the button still asks
the feed but offers no install, since Debian builds never self-update.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-06 15:38:35 +01:00
co-authored by Claude Sonnet 5
parent 1735f431dd
commit 96eec22971
7 changed files with 337 additions and 36 deletions
+158 -23
View File
@@ -2,10 +2,15 @@
//! in `tauri.conf.json`) at startup and every 6 h (sooner after a failed
//! check), tells the main window about a newer version and installs it when
//! the user asks, but never while a recording runs or a call is being
//! processed.
//! processed. The settings' "Nach Updates suchen" button
//! ([`check_for_update_now`]) runs the very same check immediately, counts
//! as an attempt for the same scheduler ([`UpdateSchedule`]) and never runs
//! at the same time as the background loop.
//!
//! On Windows the NSIS installer runs in passive mode for the current user
//! (no admin rights) and restarts the app; installing ends this process.
//! Debian builds never self-update; a manual check still asks the feed
//! there (see [`can_self_update`]).
use std::fs;
use std::path::Path;
@@ -58,6 +63,71 @@ pub struct UpdateInfo {
pub can_install: bool,
}
/// Answer of `check_for_update_now`: what a check (background or manual)
/// found. `Available` leaves the same state `get_update` reads and fires
/// the same `update-available` event as the background loop, so the main
/// window's banner shows it too.
#[derive(Serialize, Clone, Debug, PartialEq)]
#[serde(tag = "status", rename_all = "lowercase")]
pub enum UpdateCheckResult {
/// No newer version on the feed.
None,
Available {
version: String,
},
/// The feed could not be asked; safe to show (never a secret).
Error {
message: String,
},
}
/// When the last check attempt (background or manual) started and how many
/// failed in a row, shared so a manual check feeds the same scheduler the
/// background loop uses: success resets the 6 h interval and the failure
/// count, a failure advances the backoff by one step. `running` also
/// serializes checks, so a manual and a background check never run at once.
#[derive(Default)]
pub struct UpdateSchedule {
state: Mutex<Schedule>,
running: tokio::sync::Mutex<()>,
}
#[derive(Default, Clone, Copy)]
struct Schedule {
last_attempt: Option<SystemTime>,
failures: u32,
}
impl UpdateSchedule {
/// Whether a check is due at `now`, per the last recorded attempt.
fn is_due(&self, now: SystemTime) -> bool {
let s = lock(&self.state);
check_due(s.last_attempt, s.failures, now)
}
/// Records the outcome of a check attempt that started at `now`.
fn record(&self, now: SystemTime, success: bool) {
let mut s = lock(&self.state);
s.last_attempt = Some(now);
s.failures = if success {
0
} else {
s.failures.saturating_add(1)
};
}
/// Runs one check attempt right now: serialized against any other check
/// (background or manual) via `running`, and recorded for the
/// scheduler exactly like a background attempt.
async fn run(&self, app: &AppHandle) -> UpdateCheckResult {
let _serialize = self.running.lock().await;
let now = SystemTime::now();
let result = check(app).await;
self.record(now, !matches!(result, UpdateCheckResult::Error { .. }));
result
}
}
/// Payload of `update-progress`.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Progress {
@@ -67,27 +137,19 @@ pub struct Progress {
}
/// Starts the periodic update check. Only on Windows: Debian builds do not
/// update themselves.
/// update themselves (a manual check from the settings still asks the feed
/// on Linux, see `check_for_update_now`).
pub fn spawn(app: AppHandle) {
if !cfg!(windows) {
log::info!("update check disabled on this platform");
return;
}
thread::spawn(move || {
let mut last_attempt = None;
let mut failures = 0;
loop {
let now = SystemTime::now();
if check_due(last_attempt, failures, now) {
last_attempt = Some(now);
if tauri::async_runtime::block_on(check(&app)) {
failures = 0;
} else {
failures = failures.saturating_add(1);
}
}
thread::sleep(WAKE_INTERVAL);
thread::spawn(move || loop {
let now = SystemTime::now();
if app.state::<UpdateSchedule>().is_due(now) {
tauri::async_runtime::block_on(app.state::<UpdateSchedule>().run(&app));
}
thread::sleep(WAKE_INTERVAL);
});
}
@@ -110,9 +172,11 @@ fn check_due(last_attempt: Option<SystemTime>, failures: u32, now: SystemTime) -
.map_or(true, |elapsed| elapsed >= wait)
}
/// Asks the release feed for a newer version; `false` if the check failed.
/// Failures (offline, no release yet) are expected and only logged.
async fn check(app: &AppHandle) -> bool {
/// Asks the release feed for a newer version: the one implementation the
/// background loop and a manual check (`check_for_update_now`) both run.
/// A failed check (offline, no release yet) is expected; only logged here,
/// and shown to the user only by a manual check (via the returned message).
async fn check(app: &AppHandle) -> UpdateCheckResult {
let result = match app.updater_builder().timeout(CHECK_TIMEOUT).build() {
Ok(updater) => updater.check().await,
Err(e) => Err(e),
@@ -122,16 +186,18 @@ async fn check(app: &AppHandle) -> bool {
log::info!("update available: {}", update.version);
let version = update.version.clone();
*lock(&app.state::<PendingUpdate>().update) = Some(update);
let _ = app.emit("update-available", info(app, version));
true
let _ = app.emit("update-available", info(app, version.clone()));
UpdateCheckResult::Available { version }
}
Ok(None) => {
log::info!("no update available");
true
UpdateCheckResult::None
}
Err(e) => {
log::info!("update check failed: {e}");
false
UpdateCheckResult::Error {
message: format!("Update-Server nicht erreichbar: {e}"),
}
}
}
}
@@ -161,6 +227,24 @@ fn info(app: &AppHandle, version: String) -> UpdateInfo {
}
}
/// "Nach Updates suchen" in the settings: runs the same check as the
/// background loop, immediately, reusing its scheduling (a success resets
/// the 6 h interval and the failure count, same as a background success)
/// and never running at the same time as a background check. Works on
/// every platform; see `can_self_update` for whether this build can then
/// install what it finds.
#[tauri::command]
pub async fn check_for_update_now(app: AppHandle) -> UpdateCheckResult {
app.state::<UpdateSchedule>().run(&app).await
}
/// Whether this build can install an update itself (Windows only: Debian
/// builds ship a `.deb` and never self-update, see `spawn`).
#[tauri::command]
pub fn can_self_update() -> bool {
cfg!(windows)
}
/// The update found by the last check, if any.
#[tauri::command]
pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
@@ -350,4 +434,55 @@ mod tests {
let reports = reported(&mut meter, &[half, half, half, half, half], None);
assert_eq!(reports, [MIB / 2, MIB, 2 * MIB]);
}
#[test]
fn update_check_result_maps_to_a_tagged_status() {
assert_eq!(
serde_json::to_value(UpdateCheckResult::None).unwrap(),
serde_json::json!({"status": "none"})
);
assert_eq!(
serde_json::to_value(UpdateCheckResult::Available {
version: "0.3.0".into()
})
.unwrap(),
serde_json::json!({"status": "available", "version": "0.3.0"})
);
assert_eq!(
serde_json::to_value(UpdateCheckResult::Error {
message: "Update-Server nicht erreichbar: x".into()
})
.unwrap(),
serde_json::json!({"status": "error", "message": "Update-Server nicht erreichbar: x"})
);
}
/// A manual check feeds the very scheduler the background loop reads
/// (`record` is the one function either kind of attempt calls): a
/// failure advances the backoff by exactly the one step a single
/// failure always does (never more just for being a manual attempt),
/// and a success resets the interval to 6 h and the failure count.
#[test]
fn a_manual_checks_result_feeds_the_background_scheduler() {
let schedule = UpdateSchedule::default();
assert!(schedule.is_due(t0()), "nothing attempted yet");
// One failed manual check: due again after the 1st retry delay,
// exactly as check_due(_, 1, _) says, not sooner and not later.
schedule.record(t0(), false);
assert!(!schedule.is_due(t0() + MIN - Duration::from_secs(1)));
assert!(schedule.is_due(t0() + MIN));
// A second failed attempt (background or manual, the scheduler does
// not distinguish) advances to the 2nd retry delay, not further.
schedule.record(t0() + MIN, false);
assert!(!schedule.is_due(t0() + MIN + 5 * MIN - Duration::from_secs(1)));
assert!(schedule.is_due(t0() + MIN + 5 * MIN));
// A manual check that then succeeds resets the interval to 6 h and
// the failure count, exactly like a background success.
schedule.record(t0() + MIN, true);
assert!(!schedule.is_due(t0() + MIN + 6 * HOUR - MIN));
assert!(schedule.is_due(t0() + MIN + 6 * HOUR));
}
}