App menu: "Check for updates" is a real check, once, now, and says what came of it calmly

Host: `updater::check_now` runs the same check the timer runs (the same updater endpoint, nothing else) for the app's shell-only `update_check`. It never queues or retries: while a check is in flight (the timer's or an earlier request's), or within 10 seconds of the last request, it only answers with the current status (`update::may_check_now`, tested). The timer's loop uses the same single-flight guard.

Frame: the menu's Updates row is that check (`updateRow`, tested): "Checking…", "Up to date · <version>", "Downloading <version>…", "Restart to update" when an update is ready (the row then installs it), and "Could not check" with a plain sentence as its tooltip when the server does not answer. The updater's error text is never shown there, and a failure is only mentioned when the owner asked for the check in this menu; the timer's own failures stay quiet.
This commit is contained in:
CRTkafa 2026-09-30 22:54:51 +07:00
parent db3fbc8ece
commit f3f895c0f3
6 changed files with 162 additions and 9 deletions

View file

@ -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. /// Launches of an updated version without `app_ready` before automatic apply is disabled.
pub const MAX_FAILED_BOOTS: u32 = 2; pub const MAX_FAILED_BOOTS: u32 = 2;
pub const PENDING_FILE: &str = "update-pending.json"; 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<Duration>) -> 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. /// Wait before the next check: 30 min +/- 5 min, from any 64-bit entropy value.
pub fn next_check_delay(entropy: u64) -> Duration { pub fn next_check_delay(entropy: u64) -> Duration {
@ -76,6 +86,16 @@ pub fn on_boot(pending: Option<PendingUpdate>, current_version: &str) -> BootDec
mod tests { mod tests {
use super::*; 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] #[test]
fn delay_stays_within_jitter() { fn delay_stays_within_jitter() {
for entropy in [0, 1, 300, 600, 601, u64::MAX] { for entropy in [0, 1, 300, 600, 601, u64::MAX] {

View file

@ -4,8 +4,8 @@
//! its verification are [`crate::hotfix`]. //! its verification are [`crate::hotfix`].
//! //!
//! The app registers the updater plugin, calls [`init`] from `setup` with its [`UpdaterConfig`], //! 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 //! and wraps [`status`], [`apply`], [`ready`] and [`check_now`] in its own shell-only commands; its
//! `update-status` event. Site tabs get no updater IPC at all, only verified hotfix data //! shell gets an `update-status` event. Site tabs get no updater IPC at all, only verified hotfix data
//! ([`hotfix_script`]). //! ([`hotfix_script`]).
use crate::hotfix::{self, Hotfix, Outcome}; use crate::hotfix::{self, Hotfix, Outcome};
@ -49,6 +49,10 @@ struct Inner {
hotfix: Option<Hotfix>, hotfix: Option<Hotfix>,
/// Automatic apply is off after repeated failed starts of an update. /// Automatic apply is off after repeated failed starts of an update.
problem: bool, 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<std::time::Instant>,
} }
struct UpdateState { struct UpdateState {
@ -111,13 +115,48 @@ pub fn init(app: &AppHandle, config: &'static UpdaterConfig) {
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
tokio::time::sleep(update::FIRST_CHECK).await; tokio::time::sleep(update::FIRST_CHECK).await;
loop { loop {
check_native(&app).await; check_once(&app).await;
check_hotfix(&app).await; check_hotfix(&app).await;
tokio::time::sleep(update::next_check_delay(entropy())).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::<UpdateState>();
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::<UpdateState>().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<UpdateStatus, String> {
{
let state = app.try_state::<UpdateState>().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) { async fn check_native(app: &AppHandle) {
{ {
let state = app.state::<UpdateState>(); let state = app.state::<UpdateState>();

View file

@ -13,14 +13,15 @@
import { useEffect, useLayoutEffect, useReducer, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'; import { useEffect, useLayoutEffect, useReducer, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { createPortal } from 'react-dom'; 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 { decks } from './deckStore.ts';
import { refreshDev } from './devHost.ts'; import { refreshDev } from './devHost.ts';
import { useDev, usePaneTick, useT } from './hooks.ts'; import { useDev, usePaneTick, useT } from './hooks.ts';
import { formatNumber } from './i18n.ts'; import { formatNumber } from './i18n.ts';
import { Icon, type IconName } from './icons.tsx'; import { Icon, type IconName } from './icons.tsx';
import { 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, type BuiltinMenuItem, type MenuEnv, type MenuItemRow, type MenuRow,
} from './menuModel.ts'; } from './menuModel.ts';
import { hasFeature, site } from './site.ts'; import { hasFeature, site } from './site.ts';
@ -77,6 +78,8 @@ export function AppMenu() {
const [mode, setMode] = useState<string | null>(null); const [mode, setMode] = useState<string | null>(null);
const [asking, setAsking] = useState<{ to: string; changes: number } | null>(null); const [asking, setAsking] = useState<{ to: string; changes: number } | null>(null);
const [version, setVersion] = useState(''); const [version, setVersion] = useState('');
const [update, setUpdate] = useState<UpdateStatus>({ state: 'idle' });
const [askedUpdate, setAskedUpdate] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [, tick] = useReducer((n: number) => n + 1, 0); const [, tick] = useReducer((n: number) => n + 1, 0);
const button = useRef<HTMLButtonElement>(null); const button = useRef<HTMLButtonElement>(null);
@ -121,6 +124,8 @@ export function AppMenu() {
void config.themes?.loadThemes(); void config.themes?.loadThemes();
menu.modes?.current().then(setMode, () => {}); menu.modes?.current().then(setMode, () => {});
if (!version) menu.version?.().then(setVersion, () => {}); 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. */ /** `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; 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(() => { useEffect(() => {
const onRequest = (event: Event) => { const onRequest = (event: Event) => {
const request = (event as CustomEvent<AppMenuRequest | undefined>).detail ?? {}; const request = (event as CustomEvent<AppMenuRequest | undefined>).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 '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 '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 '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 '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') }); case 'settings': return item(id, section(t('wb.panel.section.settings')), 'settings', { run: () => shell.openPanelSection('settings') });
} }
@ -442,7 +473,7 @@ export function AppMenu() {
</div>; </div>;
} }
const expanded = row.submenu ? path[level] === row.id : undefined; const expanded = row.submenu ? path[level] === row.id : undefined;
return <button key={row.id} type="button" tabIndex={-1} disabled={row.disabled} data-item={row.id} data-label={row.label} return <button key={row.id} type="button" tabIndex={-1} disabled={row.disabled} data-item={row.id} data-label={row.label} title={row.title}
role={row.check === 'radio' ? 'menuitemradio' : row.check ? 'menuitemcheckbox' : 'menuitem'} aria-checked={row.check ? !!row.checked : undefined} role={row.check === 'radio' ? 'menuitemradio' : row.check ? 'menuitemcheckbox' : 'menuitem'} aria-checked={row.check ? !!row.checked : undefined}
aria-haspopup={row.submenu ? 'menu' : undefined} aria-expanded={expanded} aria-haspopup={row.submenu ? 'menu' : undefined} aria-expanded={expanded}
onPointerMove={event => onHover(row, level, event.currentTarget)} onClick={() => void activate(row, level)}> onPointerMove={event => onHover(row, level, event.currentTarget)} onClick={() => void activate(row, level)}>

View file

@ -27,5 +27,14 @@
"wb.menu.findNone": "No matches", "wb.menu.findNone": "No matches",
"wb.menu.findNext": "Next match", "wb.menu.findNext": "Next match",
"wb.menu.findPrevious": "Previous match", "wb.menu.findPrevious": "Previous match",
"wb.menu.findClose": "Close find bar" "wb.menu.findClose": "Close find bar",
"wb.menu.updateCheck": "Check for updates",
"wb.menu.updateChecking": "Checking…",
"wb.menu.updateUpToDate": "Up to date",
"wb.menu.updateUpToDateVersion": "Up to date · {version}",
"wb.menu.updateDownloading": "Downloading {version}…",
"wb.menu.updateInstalling": "Installing {version}…",
"wb.menu.updateRestart": "Restart to update",
"wb.menu.updateFailed": "Could not check",
"wb.menu.updateFailedHint": "The update server did not answer. Nothing is wrong with the app; it checks again later on its own."
} }

View file

@ -8,6 +8,7 @@
// have them. Words the panel already has (section names, the mode question) are reused. // have them. Words the panel already has (section names, the mode question) are reused.
import { formatMessage } from '../../../runtime/src/i18n.ts'; import { formatMessage } from '../../../runtime/src/i18n.ts';
import type { UpdateStatus } from '../updateModel.ts';
import EN from './menuMessages.en.json' with { type: 'json' }; import EN from './menuMessages.en.json' with { type: 'json' };
import { tx, type Params } from './i18n.ts'; import { tx, type Params } from './i18n.ts';
import type { IconName } from './icons.tsx'; import type { IconName } from './icons.tsx';
@ -216,6 +217,8 @@ export type MenuItemRow = {
/** The label's own language and direction (a language's native name). */ /** The label's own language and direction (a language's native name). */
lang?: string; lang?: string;
dir?: 'ltr' | 'rtl'; dir?: 'ltr' | 'rtl';
/** The row's tooltip (a plain sentence that does not fit the row). */
title?: string;
/** A theme's colors, drawn as three dots (`ThemeAdapter.dots`). */ /** A theme's colors, drawn as three dots (`ThemeAdapter.dots`). */
swatch?: { page: string; bg: string; border: string; text: string; accent: string }; swatch?: { page: string; bg: string; border: string; text: string; accent: string };
run?(): unknown; run?(): unknown;
@ -385,6 +388,40 @@ export function zoomStep(factor: number, direction: 1 | -1 | 0): number {
return [...ZOOM_STEPS].reverse().find(step => step < factor - near) ?? ZOOM_MIN; return [...ZOOM_STEPS].reverse().find(step => step < factor - near) ?? ZOOM_MIN;
} }
// ---------------------------------------------------------------------------------------------
// Updates
/** The Updates row: what it says and what choosing it does. */
export type UpdateRow = {
label: string;
/** Quiet text at the end of the row: the state, or the version while nothing is happening. */
hint?: string;
/** A plain sentence for the row's tooltip (why a check did not get through). */
title?: string;
/** `check`: ask the updater now. `restart`: install the downloaded update. `open`: the Updates section. `wait`: nothing, a step is running. */
action: 'check' | 'restart' | 'open' | 'wait';
};
/**
* The Updates row for the updater's status. `asked`: the owner asked for a check in this menu;
* only then does a check that did not get through say so (the timer's own failures stay quiet),
* and it says it calmly: a short state, never the error text.
*/
export function updateRow(status: UpdateStatus, asked: boolean, version: string): UpdateRow {
const check = menuText('updateCheck');
const quiet = version || undefined;
switch (status.state) {
case 'ready': return { label: menuText('updateRestart'), hint: status.version || quiet, action: 'restart' };
case 'installing': return { label: check, hint: menuText('updateInstalling', { version: status.version }), action: 'wait' };
case 'downloading': return { label: check, hint: menuText('updateDownloading', { version: status.version }), action: 'wait' };
case 'checking': return { label: check, hint: menuText('updateChecking'), action: 'wait' };
case 'problem': return { label: tx('wb.update.problemLabel'), hint: quiet, action: 'open' };
case 'upToDate': return { label: check, hint: version ? menuText('updateUpToDateVersion', { version }) : menuText('updateUpToDate'), action: 'check' };
case 'error': return asked ? { label: check, hint: menuText('updateFailed'), title: menuText('updateFailedHint'), action: 'check' } : { label: check, hint: quiet, action: 'check' };
default: return { label: check, hint: quiet, action: 'check' };
}
}
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
// Find in page // Find in page

View file

@ -9,7 +9,7 @@ import { fileURLToPath } from 'node:url';
import { setShellI18n, type ShellI18n } from '../src/frame/i18n.ts'; import { setShellI18n, type ShellI18n } from '../src/frame/i18n.ts';
import { import {
DEFAULT_MENU, MENU_BUILTINS, MENU_MESSAGES, ZOOM_MAX, ZOOM_MIN, ZOOM_STEPS, builtinAvailable, findLabel, findSpec, joinGroups, languageChoice, languageRows, menuText, menuWith, DEFAULT_MENU, MENU_BUILTINS, MENU_MESSAGES, ZOOM_MAX, ZOOM_MIN, ZOOM_STEPS, builtinAvailable, findLabel, findSpec, joinGroups, languageChoice, languageRows, menuText, menuWith,
menuWithout, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, zoomPercent, zoomStep, menuWithout, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow, zoomPercent, zoomStep,
type MenuEnv, type MenuGroups, type MenuItemRow, type MenuItemSpec, type MenuLanguage, type MenuRow, type MenuEnv, type MenuGroups, type MenuItemRow, type MenuItemSpec, type MenuLanguage, type MenuRow,
} from '../src/frame/menuModel.ts'; } from '../src/frame/menuModel.ts';
import { buildItems } from '../src/frame/paletteModel.ts'; import { buildItems } from '../src/frame/paletteModel.ts';
@ -236,6 +236,23 @@ test("the menu's words: English from menuMessages.en.json until a catalog has th
for (const key of Object.keys(MENU_MESSAGES)) assert.ok(used.has(key), `${key} is used`); for (const key of Object.keys(MENU_MESSAGES)) assert.ok(used.has(key), `${key} is used`);
}); });
test('the Updates row: a real check that says what came of it, calmly', () => {
assert.deepEqual(updateRow({ state: 'idle' }, false, '1.3.2'), { label: 'Check for updates', hint: '1.3.2', action: 'check' });
assert.deepEqual(updateRow({ state: 'checking' }, true, '1.3.2'), { label: 'Check for updates', hint: 'Checking…', action: 'wait' });
assert.deepEqual(updateRow({ state: 'upToDate' }, true, '1.3.2'), { label: 'Check for updates', hint: 'Up to date · 1.3.2', action: 'check' });
assert.equal(updateRow({ state: 'upToDate' }, true, '').hint, 'Up to date');
assert.deepEqual(updateRow({ state: 'downloading', version: '1.4.0' }, true, '1.3.2'), { label: 'Check for updates', hint: 'Downloading 1.4.0…', action: 'wait' });
assert.deepEqual(updateRow({ state: 'ready', version: '1.4.0', notes: '' }, false, '1.3.2'), { label: 'Restart to update', hint: '1.4.0', action: 'restart' });
assert.equal(updateRow({ state: 'installing', version: '1.4.0' }, false, '1.3.2').action, 'wait');
assert.equal(updateRow({ state: 'problem', downloadUrl: 'https://example.com/download' }, false, '1.3.2').action, 'open');
// A check that did not get through: a short state and a plain sentence, never the error text; and only
// when the owner asked (the timer's own failures stay quiet).
const failed = updateRow({ state: 'error', message: 'UPDATE: error sending request for url (https://updates.example/x): dns error' }, true, '1.3.2');
assert.deepEqual([failed.label, failed.hint, failed.action], ['Check for updates', 'Could not check', 'check']);
assert.ok(failed.title && !/UPDATE:|https?:|dns|[Ee]rror/.test(`${failed.hint} ${failed.title}`), 'no error dump');
assert.deepEqual(updateRow({ state: 'error', message: 'UPDATE: offline' }, false, '1.3.2'), { label: 'Check for updates', hint: '1.3.2', action: 'check' });
});
test("the find bar says which match of how many, in the reader's numbers", () => { test("the find bar says which match of how many, in the reader's numbers", () => {
assert.equal(findLabel({ count: 17, index: 2 }), '3/17'); assert.equal(findLabel({ count: 17, index: 2 }), '3/17');
assert.equal(findLabel({ count: 1, index: 0 }), '1/1'); assert.equal(findLabel({ count: 1, index: 0 }), '1/1');