diff --git a/crates/waybetter-host/src/update.rs b/crates/waybetter-host/src/update.rs index 86123f0..504f206 100644 --- a/crates/waybetter-host/src/update.rs +++ b/crates/waybetter-host/src/update.rs @@ -14,6 +14,16 @@ pub const READY_DEADLINE: Duration = Duration::from_secs(30); /// Launches of an updated version without `app_ready` before automatic apply is disabled. pub const MAX_FAILED_BOOTS: u32 = 2; pub const PENDING_FILE: &str = "update-pending.json"; +/// Least time between two checks the owner asks for ("Check for updates"): a row clicked again +/// and again asks the server once. +pub const MANUAL_CHECK_GAP: Duration = Duration::from_secs(10); + +/// Whether a check the owner asked for may start: never while one is in flight (the timer's or +/// an earlier request's), and not within [`MANUAL_CHECK_GAP`] of the last request. A refused +/// request answers with the current status; nothing is queued and nothing retries. +pub fn may_check_now(in_flight: bool, since_last_request: Option) -> bool { + !in_flight && since_last_request.is_none_or(|elapsed| elapsed >= MANUAL_CHECK_GAP) +} /// Wait before the next check: 30 min +/- 5 min, from any 64-bit entropy value. pub fn next_check_delay(entropy: u64) -> Duration { @@ -76,6 +86,16 @@ pub fn on_boot(pending: Option, current_version: &str) -> BootDec mod tests { use super::*; + #[test] + fn a_requested_check_runs_once_and_never_piles_up() { + assert!(may_check_now(false, None), "the first request checks"); + assert!(!may_check_now(true, None), "not while the timer's check is in flight"); + assert!(!may_check_now(true, Some(Duration::from_secs(3600)))); + assert!(!may_check_now(false, Some(Duration::from_secs(2))), "a row clicked again asks the server once"); + assert!(may_check_now(false, Some(MANUAL_CHECK_GAP))); + assert!(may_check_now(false, Some(Duration::from_secs(60)))); + } + #[test] fn delay_stays_within_jitter() { for entropy in [0, 1, 300, 600, 601, u64::MAX] { diff --git a/crates/waybetter-host/src/updater.rs b/crates/waybetter-host/src/updater.rs index d80ac1b..dc6f0e8 100644 --- a/crates/waybetter-host/src/updater.rs +++ b/crates/waybetter-host/src/updater.rs @@ -4,8 +4,8 @@ //! its verification are [`crate::hotfix`]. //! //! The app registers the updater plugin, calls [`init`] from `setup` with its [`UpdaterConfig`], -//! and wraps [`status`], [`apply`] and [`ready`] in its own shell-only commands; its shell gets an -//! `update-status` event. Site tabs get no updater IPC at all, only verified hotfix data +//! and wraps [`status`], [`apply`], [`ready`] and [`check_now`] in its own shell-only commands; its +//! shell gets an `update-status` event. Site tabs get no updater IPC at all, only verified hotfix data //! ([`hotfix_script`]). use crate::hotfix::{self, Hotfix, Outcome}; @@ -49,6 +49,10 @@ struct Inner { hotfix: Option, /// Automatic apply is off after repeated failed starts of an update. problem: bool, + /// A check is running (the timer's or one the owner asked for): a second one never starts beside it. + checking: bool, + /// When the owner last asked for a check ([`check_now`]). + asked: Option, } struct UpdateState { @@ -111,13 +115,48 @@ pub fn init(app: &AppHandle, config: &'static UpdaterConfig) { tauri::async_runtime::spawn(async move { tokio::time::sleep(update::FIRST_CHECK).await; loop { - check_native(&app).await; + check_once(&app).await; check_hotfix(&app).await; tokio::time::sleep(update::next_check_delay(entropy())).await; } }); } +/// One native check, unless one is already running. +async fn check_once(app: &AppHandle) { + { + let state = app.state::(); + let Ok(mut inner) = state.inner.lock() else { return }; + if inner.checking { + return; + } + inner.checking = true; + } + check_native(app).await; + if let Ok(mut inner) = app.state::().inner.lock() { + inner.checking = false; + } +} + +/// A check the owner asked for (the app's shell-only `update_check`, the app menu's "Check for +/// updates"): the same check the timer runs, once, now, against the same updater endpoint (no +/// other network destination). It never queues or retries: while a check is in flight, or within +/// [`update::MANUAL_CHECK_GAP`] of the last request, it only answers with the current status. +/// Returns the status once the check has finished (the shell also hears each step as events). +pub async fn check_now(app: &AppHandle) -> Result { + { + let state = app.try_state::().ok_or("UPDATE: state unavailable")?; + let mut inner = state.inner.lock().map_err(|_| "UPDATE: state unavailable")?; + let now = std::time::Instant::now(); + if !update::may_check_now(inner.checking, inner.asked.map(|asked| now.duration_since(asked))) { + return Ok(status_of(state.config, &inner)); + } + inner.asked = Some(now); + } + check_once(app).await; + status(app) +} + async fn check_native(app: &AppHandle) { { let state = app.state::(); diff --git a/packages/shell/src/frame/AppMenu.tsx b/packages/shell/src/frame/AppMenu.tsx index 180884d..634146b 100644 --- a/packages/shell/src/frame/AppMenu.tsx +++ b/packages/shell/src/frame/AppMenu.tsx @@ -13,14 +13,15 @@ import { useEffect, useLayoutEffect, useReducer, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'; import { createPortal } from 'react-dom'; -import { invoke } from './bridge.ts'; +import { parseUpdateStatus, type UpdateStatus } from '../updateModel.ts'; +import { invoke, listen } from './bridge.ts'; import { decks } from './deckStore.ts'; import { refreshDev } from './devHost.ts'; import { useDev, usePaneTick, useT } from './hooks.ts'; import { formatNumber } from './i18n.ts'; import { Icon, type IconName } from './icons.tsx'; import { - DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, + DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow, type BuiltinMenuItem, type MenuEnv, type MenuItemRow, type MenuRow, } from './menuModel.ts'; import { hasFeature, site } from './site.ts'; @@ -77,6 +78,8 @@ export function AppMenu() { const [mode, setMode] = useState(null); const [asking, setAsking] = useState<{ to: string; changes: number } | null>(null); const [version, setVersion] = useState(''); + const [update, setUpdate] = useState({ state: 'idle' }); + const [askedUpdate, setAskedUpdate] = useState(false); const [error, setError] = useState(''); const [, tick] = useReducer((n: number) => n + 1, 0); const button = useRef(null); @@ -121,6 +124,8 @@ export function AppMenu() { void config.themes?.loadThemes(); menu.modes?.current().then(setMode, () => {}); if (!version) menu.version?.().then(setVersion, () => {}); + setAskedUpdate(false); + if (hasFeature('updates')) invoke('update_status').then(value => setUpdate(parseUpdateStatus(value)), () => {}); } /** `escape`: back to what had focus before. `action` and `away`: nothing focused, so typing returns to the active pane. */ @@ -133,6 +138,17 @@ export function AppMenu() { before.current = null; } + // The updater's steps (checking, downloading, ready) as they happen. + useEffect(() => { + if (!hasFeature('updates')) return; + let disposed = false; + let unlisten: (() => void) | undefined; + listen('update-status', event => setUpdate(parseUpdateStatus(event.payload))) + .then(dispose => { if (disposed) dispose(); else unlisten = dispose; }) + .catch(() => {}); + return () => { disposed = true; unlisten?.(); }; + }, []); + useEffect(() => { const onRequest = (event: Event) => { const request = (event as CustomEvent).detail ?? {}; @@ -269,7 +285,22 @@ export function AppMenu() { case 'shortcuts': return item(id, menuText('shortcuts'), 'keyboard', { run: () => (menu.shortcuts ? menu.shortcuts() : shell.shortcut('command-palette')) }); case 'palette': return item(id, menuText('palette'), 'command', { shortcut: 'Ctrl+K', run: () => shell.shortcut('command-palette') }); case 'developer': return item(id, menuText('developer'), 'code', { submenu: true }); - case 'updates': return item(id, section(t('wb.panel.section.updates')), 'reload', { hint: version || undefined, run: () => shell.openPanelSection('updates') }); + case 'updates': { + // A real check: the row asks the updater now and says what came of it (the titlebar chip stays the loud part). + const row = updateRow(update, askedUpdate, version); + return item(id, row.label, 'reload', { + hint: row.hint, title: row.title, keepOpen: row.action === 'check' || row.action === 'wait', + run: async () => { + if (row.action === 'open') { shell.openPanelSection('updates'); return; } + if (row.action === 'restart') { await invoke('apply_update'); return; } + if (row.action !== 'check') return; + setAskedUpdate(true); + setUpdate({ state: 'checking' }); + // One request, no retry: whatever the updater answers is what the row says. + try { setUpdate(parseUpdateStatus(await invoke('update_check'))); } catch { setUpdate({ state: 'error', message: '' }); } + }, + }); + } case 'about': return item(id, menuText('about', { product: config.product }), 'info', { run: () => shell.openPanelSection('home') }); case 'settings': return item(id, section(t('wb.panel.section.settings')), 'settings', { run: () => shell.openPanelSection('settings') }); } @@ -442,7 +473,7 @@ export function AppMenu() { ; } const expanded = row.submenu ? path[level] === row.id : undefined; - return