From 96eec229714771b68ac580988c59d02a471a6faf Mon Sep 17 00:00:00 2001 From: hauke Date: Fri, 6 Nov 2026 15:38:35 +0100 Subject: [PATCH] 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 --- src-tauri/src/commands.rs | 6 ++ src-tauri/src/lib.rs | 6 +- src-tauri/src/state.rs | 7 +- src-tauri/src/updater.rs | 181 ++++++++++++++++++++++++++++----- ui/src/lib/UpdateBanner.svelte | 15 +-- ui/src/lib/api.ts | 30 ++++++ ui/src/routes/Settings.svelte | 128 +++++++++++++++++++++++ 7 files changed, 337 insertions(+), 36 deletions(-) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 8adf399..920e329 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -32,6 +32,12 @@ struct CallEnded { id: CallId, } +/// This build's own version, for the settings' "Updates" section. +#[tauri::command] +pub fn get_app_version(app: AppHandle) -> String { + app.package_info().version.to_string() +} + #[tauri::command] pub fn get_settings(state: State<'_, AppState>) -> Settings { state.settings() diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index bc3680b..a5aa714 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -14,7 +14,7 @@ use tauri_plugin_autostart::MacosLauncher; use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy}; use crate::state::AppState; -use crate::updater::PendingUpdate; +use crate::updater::{PendingUpdate, UpdateSchedule}; /// Command-line flag the login item starts the app with; the main window /// then stays hidden in the tray. @@ -98,6 +98,7 @@ pub fn run() { processing::clear_upload_dir(app.handle()); app.manage(state); app.manage(PendingUpdate::default()); + app.manage(UpdateSchedule::default()); app.manage(backend::LoginWaiters::default()); // Windows are created here (`create: false` in tauri.conf.json) // instead of by Tauri before `setup` runs: their webviews load @@ -130,6 +131,7 @@ pub fn run() { } }) .invoke_handler(tauri::generate_handler![ + commands::get_app_version, commands::get_settings, commands::save_settings, commands::set_api_key, @@ -160,6 +162,8 @@ pub fn run() { backend::upload_transcript, updater::get_update, updater::install_update, + updater::check_for_update_now, + updater::can_self_update, ]) .run(tauri::generate_context!()) .expect("error while building tauri application"); diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 5225837..a0cf769 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -209,7 +209,12 @@ impl AppState { pending_prompts: Mutex::new(VecDeque::new()), processing: Mutex::new(HashSet::new()), devices_busy: AtomicBool::new(false), - backend_url: crate::backend::BACKEND_URL.to_string(), + // Defensive: BACKEND_URL itself must never have a trailing + // slash (see backend::tests::backend_urls_have_no_trailing…), + // but a stored key's base_url is compared against this field. + backend_url: crate::backend::BACKEND_URL + .trim_end_matches('/') + .to_string(), backend_key_lock: Mutex::new(()), uploading: Mutex::new(HashSet::new()), } diff --git a/src-tauri/src/updater.rs b/src-tauri/src/updater.rs index 5eb85d0..75f8389 100644 --- a/src-tauri/src/updater.rs +++ b/src-tauri/src/updater.rs @@ -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, + running: tokio::sync::Mutex<()>, +} + +#[derive(Default, Clone, Copy)] +struct Schedule { + last_attempt: Option, + 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::().is_due(now) { + tauri::async_runtime::block_on(app.state::().run(&app)); } + thread::sleep(WAKE_INTERVAL); }); } @@ -110,9 +172,11 @@ fn check_due(last_attempt: Option, 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::().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::().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 { @@ -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)); + } } diff --git a/ui/src/lib/UpdateBanner.svelte b/ui/src/lib/UpdateBanner.svelte index 1a6c5b4..55b0f15 100644 --- a/ui/src/lib/UpdateBanner.svelte +++ b/ui/src/lib/UpdateBanner.svelte @@ -8,6 +8,8 @@ onRecordingState, onUpdateAvailable, onUpdateProgress, + updateProgressText, + UPDATE_BUSY_HINT, type UpdateInfo, type UpdateProgress, } from './api' @@ -62,16 +64,7 @@ } } - function megabytes(bytes: number): string { - return (bytes / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' MB' - } - - let progressText = $derived.by(() => { - if (!progress) return 'Update wird heruntergeladen…' - if (progress.total === null) return `Update wird heruntergeladen… ${megabytes(progress.downloaded)}` - if (progress.downloaded >= progress.total) return 'Update wird installiert…' - return `Update wird heruntergeladen… ${Math.floor((progress.downloaded * 100) / progress.total)} %` - }) + let progressText = $derived(updateProgressText(progress)) {#if update} @@ -84,7 +77,7 @@ Installieren & neu starten {#if !update.can_install} - Nach der laufenden Aufnahme/Verarbeitung möglich + {UPDATE_BUSY_HINT} {/if} {/if} {#if error} diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index c21e3f8..78f1eb1 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -137,6 +137,15 @@ export interface UpdateProgress { total: number | null } +/** Why the install button is disabled, shown next to it as a hint. */ +export const UPDATE_BUSY_HINT = 'Nach der laufenden Aufnahme/Verarbeitung möglich' + +/** What a check (background or manual) found. */ +export type UpdateCheckResult = + | { status: 'none' } + | { status: 'available'; version: string } + | { status: 'error'; message: string } + export interface Levels { mic: number out: number @@ -185,6 +194,14 @@ export const uploadTranscript = (id: CallId) => invoke('upload_transcript' export const getUpdate = () => invoke('get_update') /** Resolves only on failure: on success the app restarts. */ export const installUpdate = () => invoke('install_update') +/** This build's own version, for the settings' "Updates" section. */ +export const getAppVersion = () => invoke('get_app_version') +/** Whether this build can install an update itself (Windows only). */ +export const canSelfUpdate = () => invoke('can_self_update') +/** "Nach Updates suchen": runs the same check as the background loop, + * immediately. An `available` result leaves the same state `getUpdate` + * reads, so the main window's banner shows it too. */ +export const checkForUpdateNow = () => invoke('check_for_update_now') export const onRecordingState = (handler: (state: RecordingState) => void): Promise => listen('recording-state', (event) => handler(event.payload)) @@ -218,6 +235,19 @@ export function meterFill(level: number): number { return Math.min(1, Math.max(0, (db + 60) / 60)) } +function megabytes(bytes: number): string { + return (bytes / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' MB' +} + +/** Text shown while an update installs (the banner and the settings' + * Updates section share this). */ +export function updateProgressText(progress: UpdateProgress | null): string { + if (!progress) return 'Update wird heruntergeladen…' + if (progress.total === null) return `Update wird heruntergeladen… ${megabytes(progress.downloaded)}` + if (progress.downloaded >= progress.total) return 'Update wird installiert…' + return `Update wird heruntergeladen… ${Math.floor((progress.downloaded * 100) / progress.total)} %` +} + /** Error text of a rejected command. */ export function errorText(err: unknown): string { return typeof err === 'string' ? err : err instanceof Error ? err.message : String(err) diff --git a/ui/src/routes/Settings.svelte b/ui/src/routes/Settings.svelte index 509b549..eab921f 100644 --- a/ui/src/routes/Settings.svelte +++ b/ui/src/routes/Settings.svelte @@ -6,17 +6,26 @@ backendLogout, backendServer, backendStatus, + canSelfUpdate, + checkForUpdateNow, errorText, + getAppVersion, getSettings, + getUpdate, hasApiKey, + installUpdate, listDevices, meterFill, onBackendChanged, onBackendLoginError, + onUpdateAvailable, + onUpdateProgress, openBackendKeysPage, saveSettings, setApiKey, testDevices, + updateProgressText, + UPDATE_BUSY_HINT, type BackendServer, type BackendStatus, type DeviceInfo, @@ -24,6 +33,9 @@ type Devices, type Service, type Settings, + type UpdateCheckResult, + type UpdateInfo, + type UpdateProgress, } from '../lib/api' const services: { id: Service; name: string }[] = [ @@ -48,19 +60,84 @@ // Status answers can arrive out of order; only the newest is applied. let statusRequest = 0 + let appVersion = $state('') + /** `null` until known: whether this build can install an update itself + * (Windows only); avoids guessing wrong for an instant. */ + let selfUpdateCapable = $state(null) + let checking = $state(false) + let checkResult = $state(null) + let pendingUpdate = $state(null) + let installing = $state(false) + let installProgress = $state(null) + let installError = $state('') + onMount(() => { load() backendServer() .then((s) => (server = s)) .catch((err) => (backendError = errorText(err))) refreshBackend() + getAppVersion() + .then((v) => (appVersion = v)) + .catch(() => {}) + canSelfUpdate() + .then((v) => (selfUpdateCapable = v)) + .catch(() => {}) + getUpdate() + .then((u) => (pendingUpdate = u)) + .catch(() => {}) const unlisten = [ onBackendChanged(refreshBackend), onBackendLoginError((msg) => (backendError = msg)), + onUpdateAvailable((info) => (pendingUpdate = info)), + onUpdateProgress((progress) => (installProgress = progress)), ] return () => unlisten.forEach((u) => u.then((off) => off())) }) + /** "Nach Updates suchen": runs the same check as the background loop, + * immediately. An available update also arrives via `update-available` + * (so the main window's banner shows it too), but is applied here as + * well in case that event is missed. */ + async function checkUpdateNow() { + checking = true + checkResult = null + try { + const result = await checkForUpdateNow() + checkResult = result + if (result.status === 'available') pendingUpdate = await getUpdate() + } catch (err) { + checkResult = { status: 'error', message: errorText(err) } + } finally { + checking = false + } + } + + async function refreshPendingUpdate() { + try { + pendingUpdate = await getUpdate() + } catch { + // Optional refresh; the next event or check tries again. + } + } + + /** "Installieren & neu starten" for the update found above; reuses the + * install command and guard the main window's banner uses. */ + async function installUpdateNow() { + installing = true + installProgress = null + installError = '' + try { + // Returns only on failure: on success the app restarts. + await installUpdate() + } catch (err) { + installError = errorText(err) + refreshPendingUpdate() + } finally { + installing = false + } + } + /** Checks the stored key with the backend. */ async function refreshBackend() { const request = ++statusRequest @@ -377,6 +454,48 @@ +
+

Updates

+
+ Version + {appVersion || '…'} +
+
+ + {#if checkResult?.status === 'none'} + Keine neue Version verfügbar (aktuell: {appVersion}) + {:else if checkResult?.status === 'error'} + {checkResult.message} + {/if} +
+ {#if pendingUpdate && selfUpdateCapable !== null} +
+ Update verfügbar (v{pendingUpdate.version}) + {#if selfUpdateCapable} + {#if installing} + {updateProgressText(installProgress)} + {:else} + + {#if !pendingUpdate.can_install} + {UPDATE_BUSY_HINT} + {/if} + {/if} + {#if installError} + {installError} + {/if} + {:else} + + Updates gibt es unter Windows automatisch; unter Linux bitte das .deb neu installieren. + + {/if} +
+ {/if} +
+