Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
One kwant version card in Settings (latest / available / couldn't check) (#547)
Oleksandr Ivanchenko7701697153d5
diff --git a/apps/mac/src/main.rs b/apps/mac/src/main.rsindex 2b396406..dcad10dc 100644--- a/apps/mac/src/main.rs+++ b/apps/mac/src/main.rs@@ -442,6 +442,11 @@ fn fix_path() {/// Starts kwant on its own runtime thread; the returned handle stops it.fn start_server(config: kwnt::Config) -> Server {+ // This app checks and installs its own updates (update::start), so the server's release+ // check stays out. Windows has no in-app update yet: there the server says how to update.+ if !cfg!(windows) {+ kwnt::app_update::UpdateHub::shared().mark_desktop_app();+ }let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();let (done_tx, done_rx) = mpsc::channel();std::thread::Builder::new()diff --git a/apps/mac/src/update.rs b/apps/mac/src/update.rsindex 323fb709..c09efb45 100644--- a/apps/mac/src/update.rs+++ b/apps/mac/src/update.rs@@ -1,5 +1,6 @@//! In-app updates. The app asks GitHub's latest Mac release (`latest.json`, see `plugins.updater`-//! in tauri.conf.json) on start and every 6 hours. The state lives on kwant's+//! in tauri.conf.json) on start and every hour, by the wall clock (a Mac asleep overnight checks+//! when it wakes). The state lives on kwant's//! [`UpdateHub`](kwnt::app_update::UpdateHub), so the web app shows it through `/api/app/update`//! and the person starts the install there or from the menu-bar icon.//!@@ -9,14 +10,17 @@use kwnt::app_update::{Available, State, Status, UpdateHub, Updater};use std::sync::{Arc, Mutex};-use std::time::Duration;+use std::time::{Duration, SystemTime};use tauri::AppHandle;use tauri_plugin_updater::{Update, UpdaterExt};const RELEASES: &str = "https://github.com/alexsergivan/kwant/releases";/// After start, so the check doesn't compete with kwant starting up.const FIRST_CHECK_AFTER: Duration = Duration::from_secs(15);-const CHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60);+const CHECK_EVERY: Duration = Duration::from_secs(60 * 60);+/// How often the loop looks at the clock. A thread's sleep stops while the Mac sleeps, so a+/// plain `sleep(CHECK_EVERY)` could put the next check off by days; this keeps it close to due.+const LOOK_EVERY: Duration = Duration::from_secs(5 * 60);/// Long enough for the web app to show "Restarting…" before the window goes away.const RELAUNCH_AFTER: Duration = Duration::from_millis(1500);@@ -55,15 +59,30 @@ pub fn start(app: &AppHandle) {.name("kwant-update-check".into()).spawn(move || {std::thread::sleep(FIRST_CHECK_AFTER);+ let mut last: Option<SystemTime> = None;loop {- // Busy (downloading, relaunching) means there's nothing to check- let _ = hub.check();- std::thread::sleep(CHECK_EVERY);+ if check_due(last, SystemTime::now()) {+ // Busy (downloading, relaunching) means there's nothing to check+ let _ = hub.check();+ last = Some(SystemTime::now());+ }+ std::thread::sleep(LOOK_EVERY);}}).ok();}+/// Due on the first look, then once `CHECK_EVERY` has passed on the wall clock (or the clock+/// went back).+fn check_due(last: Option<SystemTime>, now: SystemTime) -> bool {+ match last {+ None => true,+ Some(last) => now+ .duration_since(last)+ .map_or(true, |gone| gone >= CHECK_EVERY),+ }+}+struct MacUpdater {app: AppHandle,hub: Arc<UpdateHub>,@@ -160,9 +179,25 @@ mod tests {}),progress,error: None,+ can_install: true,+ checked_at: None,+ how: None,}}+ #[test]+ fn checks_by_the_wall_clock() {+ let t = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000);+ assert!(check_due(None, t));+ assert!(!check_due(Some(t), t + Duration::from_secs(59 * 60)));+ // a night asleep: due on the first look after waking+ assert!(check_due(Some(t), t + Duration::from_secs(9 * 60 * 60)));+ assert!(+ check_due(Some(t + Duration::from_secs(60)), t),+ "clock went back"+ );+ }+#[test]fn release_pages() {assert_eq!(release_page("0.1.2"), "https://github.com/alexsergivan/kwant/releases/tag/mac-v0.1.2");diff --git a/frontend/src/appUpdate.ts b/frontend/src/appUpdate.tsindex 079d33b2..50158a59 100644--- a/frontend/src/appUpdate.ts+++ b/frontend/src/appUpdate.ts@@ -1,7 +1,8 @@-// In-app updates for the Mac app. The Mac shell checks GitHub for a newer signed release and hands-// the result to the in-process server; this module polls GET /api/app/update and drives the banner-// and the About row in App settings. Off the Mac app (VPS, Docker, dev) the endpoint answers 404 or-// supported=false, and then nothing renders and nothing polls again.+// Updates. The Mac shell checks GitHub for a newer signed release and installs it; elsewhere (VPS,+// Docker, Windows) the server checks GitHub's latest release itself and only reports it+// (can_install=false, with `how`: the command that updates this install). This module polls+// GET /api/app/update and drives the Mac banner and the kwant card in App settings. With the check+// off (404 or supported=false) nothing polls again and the card shows the version alone.export type UpdateState = 'idle' | 'checking' | 'available' | 'downloading' | 'ready' | 'error';@@ -14,8 +15,19 @@ export interface AvailableUpdate {url: string;}+/** How this install updates when the app can't do it: one command (none on Windows: a new installer). */+export interface HowToUpdate {+ kind: 'docker' | 'binary' | 'windows' | 'source';+ command: string | null;+}+export interface UpdateStatus {current: string;+ /** The Mac app installs; elsewhere Update opens How to update. */+ canInstall: boolean;+ /** When the server last heard back from GitHub (ms), null before the first answer. */+ lastChecked: number | null;+ how: HowToUpdate | null;state: UpdateState;available: AvailableUpdate | null;progress: number | null;@@ -37,6 +49,8 @@ export interface UpdateModel {/** null until the first answer, and forever when unsupported. */status: UpdateStatus | null;unsupported: boolean;+ /** The running version, also when updates are unsupported (null when the server never said). */+ current: string | null;phase: UpdatePhase;/** The version being installed, or the one just installed. */target: string | null;@@ -51,6 +65,8 @@ export const UPDATE_DISMISSED_KEY = 'kwnt_update_dismissed';export const UPDATE_PENDING_KEY = 'kwnt_update_pending';export const IDLE_POLL_MS = 30 * 60 * 1000;+/** Opening the kwant card checks again when the last answer is older than this. */+export const STALE_CHECK_MS = 60 * 60 * 1000;export const FAST_POLL_MS = 1000;/** After this long without the app coming back, say so instead of spinning forever. */export const RESTART_GIVE_UP_MS = 3 * 60 * 1000;@@ -73,15 +89,29 @@ function parseAvailable(raw: unknown): AvailableUpdate | null {};}-/** The server's answer, or null when it isn't the Mac app (or isn't an answer at all). */+const HOW_KINDS: HowToUpdate['kind'][] = ['docker', 'binary', 'windows', 'source'];++function parseHow(raw: unknown): HowToUpdate | null {+ if (!raw || typeof raw !== 'object') return null;+ const h = raw as Record<string, unknown>;+ if (!HOW_KINDS.includes(h.kind as HowToUpdate['kind'])) return null;+ return { kind: h.kind as HowToUpdate['kind'], command: str(h.command) };+}++/** The server's answer, or null when updates are off there (or it isn't an answer at all). */export function parseUpdateStatus(raw: unknown): UpdateStatus | null {if (!raw || typeof raw !== 'object') return null;const r = raw as Record<string, unknown>;if (r.supported !== true) return null;+ const checked = typeof r.checked_at === 'string' ? Date.parse(r.checked_at) : NaN;const state = STATES.includes(r.state as UpdateState) ? (r.state as UpdateState) : 'idle';const progress = typeof r.progress === 'number' && Number.isFinite(r.progress) ? Math.min(1, Math.max(0, r.progress)) : null;return {current: str(r.current) ?? '',+ // A Mac app from before can_install only ever answered supported=true from the app itself+ canInstall: r.can_install !== false,+ lastChecked: Number.isFinite(checked) ? checked : null,+ how: parseHow(r.how),state,available: parseAvailable(r.available),progress,@@ -120,8 +150,9 @@ function write(key: string, value: string | null, store: Store | undefined) {export const dismissedVersion = (store = defaultStore()) => read(UPDATE_DISMISSED_KEY, store);export const dismissVersion = (version: string, store = defaultStore()) => write(UPDATE_DISMISSED_KEY, version, store);+/** The Mac app's bar. Elsewhere the update can't run from the app, so the kwant card says it. */export function bannerView(m: UpdateModel, dismissed: string | null): BannerView | null {- if (m.unsupported || !m.status) return null;+ if (m.unsupported || !m.status || !m.status.canInstall) return null;if (m.phase === 'updated' && m.target) return { kind: 'updated', version: m.target };if (m.phase === 'restarting' && m.target) return { kind: 'restarting', version: m.target };if (m.phase === 'stalled' && m.target) {@@ -153,26 +184,66 @@ export function nextPollMs(m: UpdateModel): number {return s === 'checking' || s === 'downloading' || s === 'ready' ? FAST_POLL_MS : IDLE_POLL_MS;}-/** The About row's one-line result. */-export function aboutLine(m: UpdateModel): string {+/** A failed check (not a failed install): the Mac app and the server both start it so. */+export const isCheckError = (error: string | null) => !!error && /^Couldn[’']t check/i.test(error);++/** Line 2 of the kwant card: exactly one of these. */+export type VersionLine =+ | { kind: 'loading' }+ | { kind: 'off' }+ | { kind: 'checking' }+ | { kind: 'latest'; checkedAt: number | null }+ | { kind: 'available'; version: string; notes: string; date: string | null; url: string; canInstall: boolean }+ | { kind: 'downloading'; version: string; progress: number | null }+ | { kind: 'restarting'; version: string }+ | { kind: 'install-error'; version: string; error: string; url: string; notes: string; date: string | null }+ | { kind: 'check-error'; error: string }+ | { kind: 'updated'; version: string };++/** Never says "latest" without a check that said so. */+export function versionLine(m: UpdateModel): VersionLine {+ if (m.unsupported) return { kind: 'off' };const s = m.status;- if (!s) return '';- if (m.actionError) return m.actionError;- if (m.phase === 'updated' && m.target) return `Updated to ${m.target}.`;- switch (s.state) {- case 'checking':- return 'Checking for updates…';- case 'available':- return s.available ? `kwant bots ${s.available.version} is ready.` : 'You’re up to date.';- case 'downloading':- return s.progress == null ? 'Downloading the update…' : `Downloading the update… ${Math.round(s.progress * 100)}%`;- case 'ready':- return 'Restarting the app…';- case 'error':- return s.error ?? 'The last check failed.';- default:- return m.checkedAt != null ? 'You’re up to date.' : '';+ if (!s) return { kind: 'loading' };+ if (m.phase === 'updated' && m.target) return { kind: 'updated', version: m.target };+ if (m.phase === 'restarting' && m.target) return { kind: 'restarting', version: m.target };+ const a = s.available;+ if (m.phase === 'stalled' && m.target) {+ return {+ kind: 'install-error',+ version: m.target,+ error: 'The app didn’t come back after the update. Open kwant bots again from Applications.',+ url: a?.url ?? `https://github.com/alexsergivan/kwant/releases/tag/mac-v${m.target}`,+ notes: a?.notes ?? '',+ date: a?.date ?? null,+ };+ }+ if (s.state === 'checking') return { kind: 'checking' };+ if (a && s.state === 'ready') return { kind: 'restarting', version: a.version };+ if (a && (s.state === 'downloading' || m.phase === 'installing')) return { kind: 'downloading', version: a.version, progress: s.progress };+ const failed = m.installError ?? (s.state === 'error' ? s.error ?? 'The update failed.' : null);+ if (a && failed && !isCheckError(failed)) {+ return { kind: 'install-error', version: a.version, error: failed, url: a.url, notes: a.notes, date: a.date };}+ // A version found earlier is still there after a failed re-check: offering it isn't wrong+ if (a) return { kind: 'available', version: a.version, notes: a.notes, date: a.date, url: a.url, canInstall: s.canInstall };+ if (s.state === 'error') return { kind: 'check-error', error: s.error ?? 'Couldn’t check for updates.' };+ if (m.actionError) return { kind: 'check-error', error: m.actionError };+ // No answer from GitHub yet (the first check runs seconds after start)+ if (s.lastChecked == null) return { kind: 'checking' };+ return { kind: 'latest', checkedAt: s.lastChecked };+}++/** "Checked just now", "Checked 2 min ago", "Checked 3 h ago", "Checked 2 days ago". */+export function checkedAgo(at: number | null, now: number): string {+ if (at == null) return '';+ const min = Math.floor(Math.max(0, now - at) / 60000);+ if (min < 1) return 'Checked just now';+ if (min < 60) return `Checked ${min} min ago`;+ const h = Math.floor(min / 60);+ if (h < 24) return `Checked ${h} h ago`;+ const d = Math.floor(h / 24);+ return `Checked ${d} day${d === 1 ? '' : 's'} ago`;}async function errorText(res: Response): Promise<string | null> {@@ -184,8 +255,10 @@ async function errorText(res: Response): Promise<string | null> {}}-function refusal(res: Response, fallback: string): Promise<string> | string {- if (res.status === 401 || res.status === 403) return 'Only you can update the app, from the Mac it runs on.';+function refusal(res: Response, fallback: string, canInstall: boolean): Promise<string> | string {+ if (res.status === 401 || res.status === 403) {+ return canInstall ? 'Only you can update the app, from the Mac it runs on.' : 'Only the person who runs this kwant bots can check for updates.';+ }return errorText(res).then((e) => e ?? fallback);}@@ -203,13 +276,15 @@ export interface UpdateController {start: () => void;stop: () => void;check: () => Promise<void>;+ /** Checks quietly when the last answer is older than STALE_CHECK_MS (the kwant card opening). */+ checkIfStale: () => Promise<void>;install: () => Promise<void>;/** Hide the "Updated to …" note. */clearUpdated: () => void;}export function createUpdateController(env: ControllerEnv): UpdateController {- let model: UpdateModel = { status: null, unsupported: false, phase: 'idle', target: null, actionError: null, installError: null, checkedAt: null };+ let model: UpdateModel = { status: null, unsupported: false, current: null, phase: 'idle', target: null, actionError: null, installError: null, checkedAt: null };const listeners = new Set<() => void>();let timer: unknown = null;let running = false;@@ -231,7 +306,7 @@ export function createUpdateController(env: ControllerEnv): UpdateController {};const apply = (status: UpdateStatus) => {- const patch: Partial<UpdateModel> = { status, checkedAt: status.state === 'checking' ? model.checkedAt : env.now() };+ const patch: Partial<UpdateModel> = { status, current: status.current || model.current, checkedAt: status.state === 'checking' ? model.checkedAt : env.now() };const pending = read(UPDATE_PENDING_KEY, env.store);if (pending && status.current === pending) {// Back on the new version: in this page after the relaunch, or in the fresh window.@@ -282,14 +357,15 @@ export function createUpdateController(env: ControllerEnv): UpdateController {}const status = parseUpdateStatus(body);if (!status) {- set({ unsupported: true });+ const current = body && typeof body === 'object' ? str((body as Record<string, unknown>).current) : null;+ set({ unsupported: true, current: current ?? model.current });return schedule();}apply(status);schedule();}- async function post(path: string, fallback: string): Promise<boolean> {+ async function post(path: string, fallback: string, quiet = false): Promise<boolean> {try {const res = await env.fetch(path, { method: 'POST', headers: { Accept: 'application/json' } });if (res.ok) {@@ -298,9 +374,10 @@ export function createUpdateController(env: ControllerEnv): UpdateController {set({ actionError: null });return true;}- set({ actionError: await refusal(res, fallback) });+ const why = await refusal(res, fallback, model.status?.canInstall ?? true);+ if (!quiet) set({ actionError: why });} catch {- set({ actionError: 'The app didn’t answer. Try again in a moment.' });+ if (!quiet) set({ actionError: 'The app didn’t answer. Try again in a moment.' });}return false;}@@ -327,6 +404,14 @@ export function createUpdateController(env: ControllerEnv): UpdateController {await post('/api/app/update/check', 'Couldn’t check for updates.');schedule();},+ async checkIfStale() {+ const s = model.status;+ if (model.unsupported || !s || model.phase !== 'idle') return;+ if (s.state === 'checking' || s.state === 'downloading' || s.state === 'ready') return;+ if (s.lastChecked != null && env.now() - s.lastChecked < STALE_CHECK_MS) return;+ await post('/api/app/update/check', 'Couldn’t check for updates.', true);+ schedule();+ },async install() {const version = model.status?.available?.version;if (model.unsupported || !version) return;diff --git a/frontend/src/components/AppUpdateBanner.tsx b/frontend/src/components/AppUpdateBanner.tsxindex 25cefee5..bf3eeec6 100644--- a/frontend/src/components/AppUpdateBanner.tsx+++ b/frontend/src/components/AppUpdateBanner.tsx@@ -1,8 +1,7 @@import React, { useEffect, useId, useState, useSyncExternalStore } from 'react';-import { AlertTriangle, ArrowUpCircle, CheckCircle2, ExternalLink, Info, Loader2, RotateCw, X } from 'lucide-react';-import { BannerView, UpdateController, UpdateModel, aboutLine, appUpdateController, bannerView, dismissVersion, dismissedVersion } from '../appUpdate';+import { AlertTriangle, ArrowUpCircle, CheckCircle2, ExternalLink, Loader2, RotateCw, X } from 'lucide-react';+import { BannerView, UpdateController, appUpdateController, bannerView, dismissVersion, dismissedVersion } from '../appUpdate';import { MarkdownRenderer } from './MarkdownRenderer';-import { desktopAppOs } from '../externalLinks';import { hasWhatsNew } from './WhatsNewSheet';import { openWhatsNew } from '../whatsNewSheet';@@ -146,7 +145,7 @@ export const AppUpdateBannerView: React.FC<ViewProps> = ({ view, onUpdate, onDis};/** "kwant X.Y.Z is ready" across the top of the Mac app. Renders nothing off the Mac app and on- * phone-sized screens (the update runs on the Mac, so a phone gets the About row only). */+ * phone-sized screens (the update runs on the Mac, so a phone gets the kwant card in Settings only). */export const AppUpdateBanner: React.FC = () => {const { model, ctrl } = useAppUpdate();const [dismissed, setDismissed] = useState(dismissedVersion);@@ -182,66 +181,3 @@ export const AppUpdateBanner: React.FC = () => {/>);};--interface AboutProps {- model: UpdateModel;- onCheck: () => void;- onUpdate: () => void;-}--/** Settings → About: the running version, Check for updates and the latest result. */-export const AppUpdateAboutView: React.FC<AboutProps> = ({ model, onCheck, onUpdate }) => {- const s = model.status;- if (model.unsupported || !s) return null;- const busy = s.state === 'checking' || s.state === 'downloading' || s.state === 'ready' || model.phase === 'installing' || model.phase === 'restarting';- const line = aboutLine(model);- const offer = s.available && (s.state === 'available' || s.state === 'error') && model.phase !== 'installing';- const failed = !!model.actionError || s.state === 'error';- return (- <section aria-labelledby="about-title" data-update-about={s.state} className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3">- <div className="flex flex-wrap items-center gap-3">- <div className="flex-1 min-w-0">- <h3 id="about-title" className="flex items-center gap-2 text-xs font-medium text-zinc-300">- <Info size={15} className="text-sky-400" aria-hidden="true" />- <span>About</span>- </h3>- <p className="mt-1 text-xs text-zinc-200">- kwant bots for {desktopAppOs()} <span className="font-mono text-zinc-300">{s.current || 'unknown version'}</span>- </p>- </div>- <button- type="button"- onClick={onCheck}- disabled={busy}- className="inline-flex min-h-[32px] items-center gap-1.5 rounded-lg border border-zinc-700 px-3 text-xs font-medium text-zinc-200 hover:bg-zinc-800 disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"- >- {s.state === 'checking' ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <RotateCw size={13} aria-hidden="true" />}- Check for updates- </button>- </div>- <div role="status" aria-live="polite" className="flex flex-wrap items-center gap-2 text-[11px]">- {line && <span className={failed ? 'text-amber-300' : 'text-zinc-400'}>{line}</span>}- {offer && (- <button- type="button"- onClick={onUpdate}- className="inline-flex min-h-[28px] items-center gap-1.5 rounded-lg bg-sky-600 px-2.5 text-[11px] font-medium text-white hover:bg-sky-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400"- >- <ArrowUpCircle size={12} aria-hidden="true" />- {s.state === 'error' ? 'Try again' : `Update to ${s.available!.version} and restart`}- </button>- )}- {offer && s.state === 'error' && (- <a href={s.available!.url} target="_blank" rel="noreferrer" className="text-sky-300 underline-offset-2 hover:underline">- Download manually- </a>- )}- </div>- </section>- );-};--export const AppUpdateAbout: React.FC = () => {- const { model, ctrl } = useAppUpdate();- return <AppUpdateAboutView model={model} onCheck={() => void ctrl.check()} onUpdate={() => void ctrl.install()} />;-};diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex 12e16615..228afe81 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -35,8 +35,8 @@ import { signedInDevicesVisible } from '../deviceSignIn';import { ComputerModeControl, useComputerMode } from './ComputerModeSwitch';import { ClaudeIsolationRow } from './ClaudeIsolationRow';import { LayaStatusRow } from './LayaStatus';-import { AppUpdateAbout, useAppUpdate } from './AppUpdateBanner';-import { WhatsNewAbout } from './WhatsNewSheet';+import { useAppUpdate } from './AppUpdateBanner';+import { VersionCard } from './VersionCard';import { StarAskSettingsLink } from './StarAsk';import { ProactiveSettings, WORK_AHEAD_CAP_MAX, WORK_AHEAD_CAP_MIN, parseProactiveSettings } from '../decideFirst';import { IDEA_CAP_DEFAULT, IDEA_CAP_MAX, IDEA_CAP_MIN, ideaCapForSwitch, lastIdeaCap, parseIdeaCap, rememberIdeaCap } from '../ideaShell';@@ -343,7 +343,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tconst [webhookUrl, setWebhookUrl] = useState('');const [notifyOn, setNotifyOn] = useState<NotifyKind[]>(NOTIFY_KINDS.map((k) => k.id));// The Mac app's update API answered: only then is there an App updates notification to switch- const appUpdates = useAppUpdate().model.status !== null;+ const appUpdates = useAppUpdate().model.status?.canInstall === true;const [browserNotify, setBrowserNotify] = useState(browserNotifyEnabled);const [permission, setPermission] = useState(notificationPermission);const [notifyEnv] = useState(() => readNotifyEnv());@@ -671,8 +671,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t</div></div>- <AppUpdateAbout />- <WhatsNewAbout />+ <VersionCard /><StarAskSettingsLink />{computer.state.settings && (diff --git a/frontend/src/components/VersionCard.tsx b/frontend/src/components/VersionCard.tsxnew file mode 100644index 00000000..268600d0--- /dev/null+++ b/frontend/src/components/VersionCard.tsx@@ -0,0 +1,287 @@+// Settings › kwant: the running version, whether a newer one is out, and What's new.+// One card everywhere: the Mac app installs the update; elsewhere Update says how (one command).+import React, { useEffect, useId, useState } from 'react';+import { AlertTriangle, ArrowUpCircle, Check, CheckCircle2, ChevronRight, Copy, ExternalLink, Loader2, RotateCw } from 'lucide-react';+import { type HowToUpdate, type UpdateModel, type VersionLine, checkedAgo, versionLine } from '../appUpdate';+import { useAppUpdate } from './AppUpdateBanner';+import { WhatsNewMark } from './WhatsNewSheet';+import { RELEASES_URL, type WhatsNewEntry, entrySummary, openWhatsNew, shortDate } from '../whatsNewSheet';+import { whatsNewFor } from '../whatsNewContent';++const focus = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';+const quiet = `inline-flex min-h-[28px] items-center gap-1 rounded-md px-1.5 text-xs font-medium text-sky-300 hover:bg-sky-500/[0.12] hover:text-sky-200 max-md:min-h-[44px] ${focus}`;+const primary = `inline-flex min-h-[32px] items-center gap-1.5 rounded-lg bg-sky-600 px-3 text-xs font-semibold text-white hover:bg-sky-500 max-md:min-h-[44px] ${focus}`;+const ghost = `inline-flex min-h-[32px] items-center gap-1.5 rounded-lg border border-zinc-700 px-3 text-xs font-medium text-zinc-200 hover:bg-zinc-800 max-md:min-h-[44px] ${focus}`;++/** Where the How to update command runs, in plain words. */+const HOW_WHERE: Record<HowToUpdate['kind'], string> = {+ docker: 'Run this in the folder with your docker-compose.yml:',+ binary: 'Run this on the server kwant bots runs on:',+ source: 'Run this in your kwant bots folder:',+ windows: 'Download the new installer and run it. Your chats and bots stay as they are.',+};++const HowToUpdatePanel: React.FC<{ id: string; how: HowToUpdate | null; version: string; url: string }> = ({ id, how, version, url }) => {+ const [copied, setCopied] = useState(false);+ useEffect(() => {+ if (!copied) return;+ const t = window.setTimeout(() => setCopied(false), 2000);+ return () => window.clearTimeout(t);+ }, [copied]);+ const command = how?.command ?? null;+ return (+ <div id={id} data-how-to-update={how?.kind ?? 'none'} className="mt-3 rounded-lg border border-zinc-800 bg-zinc-900/70 p-3">+ <p className="m-0 text-xs font-semibold text-zinc-200">How to update</p>+ <p className="mb-0 mt-1 text-xs text-zinc-400">{how ? HOW_WHERE[how.kind] : 'Get the new version from its release page.'}</p>+ {command && (+ <div className="mt-2 flex items-start gap-2">+ <pre className="m-0 min-w-0 flex-1 whitespace-pre-wrap break-all rounded-md bg-black/40 px-2.5 py-2 font-mono text-[11.5px] leading-[18px] text-zinc-100 select-text">+ {command}+ </pre>+ <button+ type="button"+ onClick={() => {+ void navigator.clipboard?.writeText(command).then(+ () => setCopied(true),+ () => setCopied(false),+ );+ }}+ className={`${ghost} shrink-0`}+ aria-label={copied ? 'Copied' : 'Copy the command'}+ >+ {copied ? <Check size={13} aria-hidden="true" /> : <Copy size={13} aria-hidden="true" />}+ {copied ? 'Copied' : 'Copy'}+ </button>+ </div>+ )}+ {!command && (+ <a href={url} target="_blank" rel="noreferrer" className={`${primary} mt-2`}>+ <ExternalLink size={13} aria-hidden="true" /> Download kwant bots {version}+ </a>+ )}+ {command && <p className="mb-0 mt-2 text-[11px] text-zinc-500">Your chats and bots stay as they are.</p>}+ </div>+ );+};++/** "What's new in X ›" in the What's new card's look: the current version's sheet. */+const WhatsNewButton: React.FC<{ entry: WhatsNewEntry; onPick: (version: string) => void }> = ({ entry, onPick }) => (+ <button+ type="button"+ onClick={() => onPick(entry.version)}+ data-whats-new-current={entry.version}+ className={`mt-3 flex min-h-[56px] w-full items-center gap-3 rounded-[10px] bg-sky-500/10 py-2 pl-2.5 pr-3 text-left shadow-[inset_0_0_0_1px_rgb(157_143_255/.25)] hover:bg-sky-500/[0.16] max-md:min-h-[60px] ${focus}`}+ >+ <span className="grid h-9 w-9 shrink-0 place-items-center rounded-[9px] bg-surface-overlay shadow-[inset_0_0_0_1px_rgb(255_255_255/.14)]">+ <WhatsNewMark size={24} />+ </span>+ <span className="min-w-0 flex-1">+ <b className="block text-[13.5px] font-semibold leading-5 text-zinc-100">What’s new in {entry.version}</b>+ <span className="block text-xs leading-[18px] text-zinc-400">+ {shortDate(entry.date)} · {entrySummary(entry)}+ </span>+ </span>+ <ChevronRight size={15} className="shrink-0 text-sky-300" aria-hidden="true" />+ </button>+);++export interface VersionCardProps {+ model: UpdateModel;+ /** For "Checked 2 min ago". */+ now: number;+ onCheck: () => void;+ onInstall: () => void;+ /** The current version's sheet (bundled). */+ onWhatsNew: (version: string) => void;+ /** A newer version's release notes (not bundled in this app). */+ onReleaseNotes: (version: string, notes: string, date: string | null) => void;+ /** The current version's bundled sheet, if any. */+ entryFor?: (version: string) => WhatsNewEntry | null;+ /** Start with How to update open (screenshots). */+ howOpen?: boolean;+}++/** The card itself, without polling: what tests and screenshots render. */+export const VersionCardView: React.FC<VersionCardProps> = ({ model, now, onCheck, onInstall, onWhatsNew, onReleaseNotes, entryFor = whatsNewFor, howOpen = false }) => {+ const [showHow, setShowHow] = useState(howOpen);+ const howId = useId();+ const line: VersionLine = versionLine(model);+ const current = model.status?.current || model.current || '';+ const entry = current ? entryFor(current) : null;+ const newer = line.kind === 'available' || line.kind === 'install-error' ? line : null;+ const newerSheet = newer && (entryFor(newer.version) || newer.notes.trim()) ? newer : null;++ const status = (() => {+ switch (line.kind) {+ case 'latest':+ return (+ <>+ <span className="inline-flex items-center gap-1.5 font-medium text-zinc-100">+ <CheckCircle2 size={15} className="shrink-0 text-emerald-400" aria-hidden="true" />+ You’re on the latest version+ </span>+ <button type="button" onClick={onCheck} className={quiet}>+ Check again+ </button>+ {line.checkedAt != null && <span className="w-full pl-[21px] text-[11px] text-zinc-500">{checkedAgo(line.checkedAt, now)}</span>}+ </>+ );+ case 'available':+ return (+ <>+ <span className="inline-flex min-w-0 flex-1 items-center gap-1.5 font-medium text-zinc-100">+ <ArrowUpCircle size={15} className="shrink-0 text-sky-300" aria-hidden="true" />+ kwant bots {line.version} is available+ </span>+ <button+ type="button"+ onClick={() => (line.canInstall ? onInstall() : setShowHow((v) => !v))}+ aria-expanded={line.canInstall ? undefined : showHow}+ aria-controls={line.canInstall ? undefined : howId}+ className={primary}+ data-version-update+ >+ <ArrowUpCircle size={13} aria-hidden="true" />+ Update+ </button>+ </>+ );+ case 'checking':+ case 'loading':+ return (+ <span className="inline-flex items-center gap-1.5 text-zinc-300">+ <Loader2 size={15} className="shrink-0 animate-spin text-sky-300 motion-reduce:animate-none" aria-hidden="true" />+ Checking for updates…+ </span>+ );+ case 'downloading':+ return (+ <>+ <span className="inline-flex min-w-0 flex-1 items-center gap-1.5 font-medium text-zinc-100">+ <Loader2 size={15} className="shrink-0 animate-spin text-sky-300 motion-reduce:animate-none" aria-hidden="true" />+ Downloading kwant bots {line.version}…{line.progress != null && ` ${Math.round(line.progress * 100)}%`}+ </span>+ <span+ role="progressbar"+ aria-label={`Downloading kwant bots ${line.version}`}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={line.progress == null ? undefined : Math.round(line.progress * 100)}+ className="block h-1.5 w-28 shrink-0 overflow-hidden rounded-full bg-zinc-800"+ >+ <span+ className={`block h-full bg-sky-400 transition-[width] motion-reduce:transition-none ${line.progress == null ? 'w-1/3 animate-pulse' : ''}`}+ style={line.progress == null ? undefined : { width: `${Math.round(line.progress * 100)}%` }}+ />+ </span>+ </>+ );+ case 'restarting':+ return (+ <span className="inline-flex items-center gap-1.5 font-medium text-zinc-100">+ <Loader2 size={15} className="shrink-0 animate-spin text-sky-300 motion-reduce:animate-none" aria-hidden="true" />+ Restarting the app to finish the update…+ </span>+ );+ case 'install-error':+ return (+ <>+ <span className="inline-flex min-w-0 flex-1 items-start gap-1.5 text-zinc-200">+ <AlertTriangle size={15} className="mt-px shrink-0 text-amber-300" aria-hidden="true" />+ <span>+ <span className="font-medium text-zinc-100">kwant bots {line.version} didn’t install.</span> {line.error} This version keeps working.+ </span>+ </span>+ <a href={line.url} target="_blank" rel="noreferrer" className={quiet}>+ Download manually+ </a>+ <button type="button" onClick={onInstall} className={primary}>+ <RotateCw size={13} aria-hidden="true" /> Try again+ </button>+ </>+ );+ case 'check-error': {+ const why = line.error.replace(/^Couldn[’']t check for updates[:.]?\s*/i, '');+ return (+ <>+ <span className="inline-flex min-w-0 items-center gap-1.5 font-medium text-zinc-100">+ <AlertTriangle size={15} className="shrink-0 text-amber-300" aria-hidden="true" />+ Couldn’t check for updates+ </span>+ <button type="button" onClick={onCheck} className={quiet}>+ <RotateCw size={12} aria-hidden="true" /> Try again+ </button>+ {why && <span className="w-full pl-[21px] text-[11px] text-zinc-500">{why}</span>}+ </>+ );+ }+ case 'updated':+ return (+ <span className="inline-flex items-center gap-1.5 font-medium text-zinc-100">+ <CheckCircle2 size={15} className="shrink-0 text-emerald-400" aria-hidden="true" />+ Updated to kwant bots {line.version}+ </span>+ );+ case 'off':+ return <span className="text-zinc-400">Update checks are turned off here.</span>;+ }+ })();++ return (+ <section aria-labelledby="version-card-title" data-version-card={line.kind} className="rounded-xl border border-zinc-800 bg-zinc-950/60 p-4">+ <h3 id="version-card-title" className="m-0 text-sm font-semibold text-zinc-100">+ kwant bots <span className="font-mono text-[13px] font-medium text-zinc-300">{current || 'version unknown'}</span>+ </h3>+ <div role="status" aria-live="polite" className="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs" data-version-line>+ {status}+ </div>+ {newerSheet && (+ <button+ type="button"+ onClick={() => (entryFor(newerSheet.version) ? onWhatsNew(newerSheet.version) : onReleaseNotes(newerSheet.version, newerSheet.notes, newerSheet.date))}+ className={`${quiet} -ml-1.5 mt-1`}+ data-whats-new-next={newerSheet.version}+ >+ What’s new in {newerSheet.version} <ChevronRight size={13} aria-hidden="true" />+ </button>+ )}+ {line.kind === 'available' && !line.canInstall && showHow && (+ <HowToUpdatePanel id={howId} how={model.status?.how ?? null} version={line.version} url={line.url} />+ )}+ {entry && <WhatsNewButton entry={entry} onPick={onWhatsNew} />}+ <a href={RELEASES_URL} target="_blank" rel="noreferrer" className={`mt-2 inline-flex items-center gap-1.5 py-1 text-xs text-sky-300 hover:underline max-md:min-h-[44px] ${focus}`}>+ All releases on GitHub <ExternalLink size={13} aria-hidden="true" />+ </a>+ </section>+ );+};++/** Ticks once a minute, for "Checked N min ago". */+function useNow(ms = 30_000) {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const t = window.setInterval(() => setNow(Date.now()), ms);+ return () => window.clearInterval(t);+ }, [ms]);+ return now;+}++export const VersionCard: React.FC = () => {+ const { model, ctrl } = useAppUpdate();+ const now = useNow();+ const known = model.status !== null;+ // Opening Settings checks again when the last answer is over an hour old+ useEffect(() => {+ if (known) void ctrl.checkIfStale();+ }, [known, ctrl]);+ return (+ <VersionCardView+ model={model}+ now={now}+ onCheck={() => void ctrl.check()}+ onInstall={() => void ctrl.install()}+ onWhatsNew={(v) => openWhatsNew(v)}+ onReleaseNotes={(v, notes, date) => openWhatsNew(v, { notes, date })}+ />+ );+};diff --git a/frontend/src/components/WhatsNewSheet.tsx b/frontend/src/components/WhatsNewSheet.tsxindex 65ff726f..d5860ec4 100644--- a/frontend/src/components/WhatsNewSheet.tsx+++ b/frontend/src/components/WhatsNewSheet.tsx@@ -1,7 +1,7 @@// "What's new in kwant X.Y.Z" (spec: next-076/whats-new, design: Mira's whatsnew.html).-// WhatsNewSheetView draws one version; WhatsNewHost decides when it opens; WhatsNewAbout is the Settings › About card.+// WhatsNewSheetView draws one version; WhatsNewHost decides when it opens. Settings opens it from the kwant card (VersionCard).import React, { useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';-import { ArrowRight, ChevronDown, ChevronLeft, ChevronRight, ExternalLink, List, X } from 'lucide-react';+import { ArrowRight, ChevronDown, ChevronLeft, ExternalLink, List, X } from 'lucide-react';import { MarkdownRenderer } from './MarkdownRenderer';import { useEscapeLayer } from '../escape';import { useMedia } from '../useMedia';@@ -10,24 +10,21 @@ import type { SpaceView } from '../nav';import {FIXES_FOLD_OVER,FIXES_SHOWN,- RELEASES_URL,type WhatsNewEntry,decideOnLoad,- entrySummary,highlightView,markSeen,openRequest,- openWhatsNew,otherDialogOpen,releaseUrl,seenVersion,shortDate,subscribeOpen,} from '../whatsNewSheet';-import { WHATS_NEW, changelogFor, latestWhatsNew, whatsNewFor } from '../whatsNewContent';+import { changelogFor, latestWhatsNew, whatsNewFor } from '../whatsNewContent';/** kwant's own pixel bot with a teal hat: the sheet's and the Settings row's mark. */-const Mark: React.FC<{ size: number }> = ({ size }) => {+export const WhatsNewMark: React.FC<{ size: number }> = ({ size }) => {const r = (x: number, y: number, w = 1, h = 1, f = '#b8adff') => <rect x={x} y={y} width={w} height={h} fill={f} />;const eye = '#120e26';return (@@ -59,11 +56,13 @@ export interface SheetProps {onOpen: (view: SpaceView) => void;/** Start on the All changes view (screenshots). */initialPage?: 'main' | 'all';+ /** Only the release notes (`changelog`), for a version this app has no sheet for yet. */+ notesOnly?: boolean;}/** The sheet itself, without deciding when: what tests and screenshots render. */-export const WhatsNewSheetView: React.FC<SheetProps> = ({ entry, changelog, phone, updatedFrom, onClose, onOpen, initialPage = 'main' }) => {- const [page, setPage] = useState<'main' | 'all'>(initialPage === 'all' && changelog ? 'all' : 'main');+export const WhatsNewSheetView: React.FC<SheetProps> = ({ entry, changelog, phone, updatedFrom, onClose, onOpen, initialPage = 'main', notesOnly = false }) => {+ const [page, setPage] = useState<'main' | 'all'>(notesOnly || (initialPage === 'all' && changelog) ? 'all' : 'main');const [fixesOpen, setFixesOpen] = useState(false);const rootRef = useRef<HTMLDivElement>(null);const titleRef = useRef<HTMLHeadingElement>(null);@@ -109,7 +108,7 @@ export const WhatsNewSheetView: React.FC<SheetProps> = ({ entry, changelog, phon<><div className={`flex shrink-0 items-center ${phone ? 'gap-3 py-3 pl-[18px] pr-[52px]' : 'gap-3.5 pb-3.5 pl-6 pr-14 pt-5'}`}><span className={`grid shrink-0 place-items-center rounded-xl bg-surface-overlay shadow-[inset_0_0_0_1px_rgb(255_255_255/.14)] ${phone ? 'h-10 w-10' : 'h-11 w-11'}`}>- <Mark size={phone ? 26 : 30} />+ <WhatsNewMark size={phone ? 26 : 30} /></span><div className="min-w-0"><p className="m-0 text-xs leading-[18px] text-zinc-400" data-whats-new-eyebrow>@@ -217,6 +216,11 @@ export const WhatsNewSheetView: React.FC<SheetProps> = ({ entry, changelog, phonconst all = (<><div className={`flex shrink-0 flex-col items-start gap-1 ${phone ? 'py-3 pl-[18px] pr-[52px]' : 'pb-3.5 pl-6 pr-14 pt-5'}`}>+ {notesOnly ? (+ <p className="m-0 text-xs leading-[18px] text-zinc-400" data-whats-new-eyebrow>+ {date ? `Released ${date}` : 'New version'}+ </p>+ ) : (<buttontype="button"onClick={() => setPage('main')}@@ -224,8 +228,9 @@ export const WhatsNewSheetView: React.FC<SheetProps> = ({ entry, changelog, phon><ChevronLeft size={15} aria-hidden="true" /> What’s new</button>+ )}<h2 ref={titleRef} id={titleId} tabIndex={-1} className={`m-0 font-semibold text-zinc-50 outline-none ${phone ? 'text-[17px] leading-6' : 'text-lg leading-[26px]'}`}>- All changes in {entry.version}+ {notesOnly ? `What’s new in kwant bots ${entry.version}` : `All changes in ${entry.version}`}</h2></div>{close}@@ -271,8 +276,18 @@ export const WhatsNewSheetView: React.FC<SheetProps> = ({ entry, changelog, phoninterface Open {entry: WhatsNewEntry;updatedFrom: string | null | undefined;+ /** Release notes only: a version with no sheet in this app (the one an update offers). */+ notes?: string;}+/** A sheet for a version this app doesn't bundle: its release notes, nothing else. */+const notesEntry = (version: string, date: string | null | undefined): WhatsNewEntry => ({+ version,+ date: date && /^\d{4}-\d{2}-\d{2}/.test(date) ? date.slice(0, 10) : '',+ highlights: [],+ fixes: [],+});+/*** Opens the sheet once per device after an update, and whenever the update banner or Settings › About asks.* `established`: this person has used kwant before (an account works, or they've written in a chat); false@@ -316,7 +331,10 @@ export const WhatsNewHost: React.FC<{ established: boolean | null; onOpen: (viewif (!req || req.seq === handled.current) return;handled.current = req.seq;const entry = whatsNewFor(req.version);- if (!entry) return;+ if (!entry) {+ if (req.notes?.trim()) setOpen({ entry: notesEntry(req.version, req.date), updatedFrom: null, notes: req.notes });+ return;+ }markSeen(entry.version);setOpen({ entry, updatedFrom: null });}, [req]);@@ -326,7 +344,8 @@ export const WhatsNewHost: React.FC<{ established: boolean | null; onOpen: (view<WhatsNewSheetViewkey={open.entry.version}entry={open.entry}- changelog={changelogFor(open.entry.version)}+ changelog={open.notes ?? changelogFor(open.entry.version)}+ notesOnly={open.notes !== undefined}phone={phone}updatedFrom={open.updatedFrom}onClose={() => setOpen(null)}@@ -338,64 +357,5 @@ export const WhatsNewHost: React.FC<{ established: boolean | null; onOpen: (view);};-/** Settings › About: "What's new in X" and the earlier versions. Shown everywhere (the update card is Mac-only). */-export const WhatsNewAboutView: React.FC<{ entries: WhatsNewEntry[]; onPick: (version: string) => void }> = ({ entries, onPick }) => {- const [latest, ...earlier] = entries;- if (!latest) return null;- return (- <section aria-labelledby="whats-new-about-title" data-whats-new-about className="space-y-0 rounded-xl border border-zinc-800 bg-zinc-950/60 p-4">- <h3 id="whats-new-about-title" className="flex items-center gap-2 text-xs font-medium text-zinc-300">- <List size={15} className="text-sky-400" aria-hidden="true" />- <span>What’s new</span>- </h3>- <button- type="button"- onClick={() => onPick(latest.version)}- className={`mt-3 flex min-h-[56px] w-full items-center gap-3 rounded-[10px] bg-sky-500/10 py-2 pl-2.5 pr-3 text-left shadow-[inset_0_0_0_1px_rgb(157_143_255/.25)] hover:bg-sky-500/[0.16] max-md:min-h-[60px] ${focus}`}- >- <span className="grid h-9 w-9 shrink-0 place-items-center rounded-[9px] bg-surface-overlay shadow-[inset_0_0_0_1px_rgb(255_255_255/.14)]">- <Mark size={24} />- </span>- <span className="min-w-0 flex-1">- <b className="block text-[13.5px] font-semibold leading-5 text-zinc-100">What’s new in {latest.version}</b>- <span className="block text-xs leading-[18px] text-zinc-400">- {shortDate(latest.date)} · {entrySummary(latest)}- </span>- </span>- <ChevronRight size={15} className="shrink-0 text-sky-300" aria-hidden="true" />- </button>- {earlier.length > 0 && (- <>- <p className="mb-1 mt-3.5 text-[11px] font-semibold uppercase tracking-[.08em] text-zinc-400">Earlier versions</p>- <ul className="m-0 list-none p-0">- {earlier.map((e, i) => (- <li key={e.version} className={i ? 'border-t border-white/[0.07]' : ''}>- <button- type="button"- onClick={() => onPick(e.version)}- aria-label={`What’s new in ${e.version}`}- className={`flex min-h-[44px] w-full items-center gap-3 rounded-lg px-2.5 py-1.5 text-left hover:bg-white/[0.04] ${focus}`}- >- <span className="w-[54px] shrink-0 font-mono text-[13px] font-semibold text-zinc-200">{e.version}</span>- <span className="w-[52px] shrink-0 text-xs text-zinc-400">{shortDate(e.date)}</span>- <span className="min-w-0 flex-1 truncate text-[12.5px] text-zinc-300">{entrySummary(e)}</span>- <ChevronRight size={15} className="shrink-0 text-zinc-500" aria-hidden="true" />- </button>- </li>- ))}- </ul>- </>- )}- <a href={RELEASES_URL} target="_blank" rel="noreferrer" className={`mt-2 inline-flex items-center gap-1.5 py-1 text-xs text-sky-300 hover:underline ${focus}`}>- Older releases on GitHub <ExternalLink size={13} aria-hidden="true" />- </a>- </section>- );-};--export const WhatsNewAbout: React.FC<{ onPick?: (version: string) => void }> = ({ onPick }) => (- <WhatsNewAboutView entries={WHATS_NEW} onPick={onPick ?? openWhatsNew} />-);-/** Whether the banner's "See what's new" has something to open for `version`. */export const hasWhatsNew = (version: string) => !!whatsNewFor(version);diff --git a/frontend/src/whatsNewSheet.ts b/frontend/src/whatsNewSheet.tsindex 7b1a99e3..d2fabb7f 100644--- a/frontend/src/whatsNewSheet.ts+++ b/frontend/src/whatsNewSheet.ts@@ -189,6 +189,10 @@ export function otherDialogOpen(doc: Document | null = typeof document === 'undeexport interface OpenRequest {version: string;seq: number;+ /** A version this app has no sheet for (one not installed yet): its release notes, markdown. */+ notes?: string;+ /** That release's date, YYYY-MM-DD or RFC 3339. */+ date?: string | null;}let request: OpenRequest | null = null;let seq = 0;@@ -199,7 +203,7 @@ export const subscribeOpen = (l: () => void) => {};export const openRequest = () => request;/** Ask the mounted sheet host to open `version`'s sheet. */-export function openWhatsNew(version: string): void {- request = { version, seq: ++seq };+export function openWhatsNew(version: string, notes?: { notes: string; date?: string | null }): void {+ request = { version, seq: ++seq, ...(notes ? { notes: notes.notes, date: notes.date ?? null } : {}) };listeners.forEach((l) => l());}diff --git a/frontend/tests/appUpdate.test.mjs b/frontend/tests/appUpdate.test.mjsindex d8b9c571..907a7a33 100644--- a/frontend/tests/appUpdate.test.mjs+++ b/frontend/tests/appUpdate.test.mjs@@ -10,15 +10,22 @@ const u = await loadBundled(`export * from './src/appUpdate';`);const ui = await loadBundled(`import React from 'react';import { renderToStaticMarkup } from 'react-dom/server.browser';- import { AppUpdateBannerView, AppUpdateAboutView } from './src/components/AppUpdateBanner';+ import { AppUpdateBannerView } from './src/components/AppUpdateBanner';+ import { VersionCardView } from './src/components/VersionCard';export const banner = (props) => renderToStaticMarkup(React.createElement(AppUpdateBannerView, props));- export const about = (props) => renderToStaticMarkup(React.createElement(AppUpdateAboutView, props));+ const noop = () => {};+ export const card = (props) =>+ renderToStaticMarkup(React.createElement(VersionCardView, { now: Date.parse('2026-11-12T22:02:00Z'), onCheck: noop, onInstall: noop, onWhatsNew: noop, onReleaseNotes: noop, ...props }));`);const src = (path) => readFileSync(new URL(`../src/${path}`, import.meta.url), 'utf8');const NOTES = '### Added\n- **In-app updates.**';+const CHECKED = '2026-11-12T22:00:00Z';const status = (over = {}) => ({supported: true,+ can_install: true,+ checked_at: CHECKED,+ how: null,current: '0.1.2',state: 'available',available: { version: '0.1.3', notes: NOTES, date: '2026-10-27T10:00:00Z', url: 'https://github.com/alexsergivan/kwant/releases/tag/mac-v0.1.3' },@@ -29,6 +36,7 @@ const status = (over = {}) => ({const model = (raw, over = {}) => ({status: u.parseUpdateStatus(raw),unsupported: false,+ current: null,phase: 'idle',target: null,actionError: null,@@ -88,6 +96,16 @@ test('parses the contract; supported=false and junk mean not the Mac app', () =>// A non-https link never becomes the Download manually href.const odd = u.parseUpdateStatus(status({ available: { version: '0.1.3', notes: '', url: 'javascript:alert(1)' } }));assert.equal(odd.available.url, 'https://github.com/alexsergivan/kwant/releases/tag/mac-v0.1.3');+ // The Mac app installs; elsewhere the server says how+ assert.equal(s.canInstall, true);+ assert.equal(s.lastChecked, Date.parse(CHECKED));+ assert.equal(s.how, null);+ const off = u.parseUpdateStatus(status({ can_install: false, checked_at: null, how: { kind: 'docker', command: 'docker compose pull kwnt && docker compose up -d' } }));+ assert.equal(off.canInstall, false);+ assert.equal(off.lastChecked, null);+ assert.deepEqual(off.how, { kind: 'docker', command: 'docker compose pull kwnt && docker compose up -d' });+ assert.deepEqual(u.parseUpdateStatus(status({ how: { kind: 'windows', command: null } })).how, { kind: 'windows', command: null });+ assert.equal(u.parseUpdateStatus(status({ how: { kind: 'rm -rf', command: 'x' } })).how, null);});test('banner for each state', () => {@@ -105,6 +123,8 @@ test('banner for each state', () => {assert.equal(u.bannerView(model(status(), { phase: 'restarting', target: '0.1.3' }), null).kind, 'restarting');assert.deepEqual(u.bannerView(model(status({ state: 'idle', available: null }), { phase: 'updated', target: '0.1.3' }), null), { kind: 'updated', version: '0.1.3' });assert.equal(u.bannerView(model(status(), { phase: 'stalled', target: '0.1.3' }), null).kind, 'error');+ // Off the Mac app the update can't run from the app: no bar, the kwant card says it+ assert.equal(u.bannerView(model(status({ can_install: false })), null), null);});test('dismiss hides that version only, and storage that throws is fine', () => {@@ -121,7 +141,7 @@ test('dismiss hides that version only, and storage that throws is fine', () => {assert.doesNotThrow(() => u.dismissVersion('0.1.3', blocked));});-test('unsupported (404 or supported=false) renders nothing and never polls again', async () => {+test('unsupported (404 or supported=false) shows the version alone and never polls again', async () => {for (const answer of [json({ error: 'not found' }, 404), json({ ...status(), supported: false })]) {const h = harness(() => answer);h.ctrl.start();@@ -130,7 +150,11 @@ test('unsupported (404 or supported=false) renders nothing and never polls againassert.equal(h.live().length, 0, 'no timer left');assert.deepEqual(h.calls, ['GET /api/app/update']);assert.equal(u.bannerView(h.ctrl.get(), null), null);- assert.equal(ui.about({ model: h.ctrl.get(), onCheck() {}, onUpdate() {} }), '');+ assert.equal(u.versionLine(h.ctrl.get()).kind, 'off');+ const html = ui.card({ model: h.ctrl.get() });+ assert.match(html, /Update checks are turned off here\./);+ assert.doesNotMatch(html, /latest version/);+ if (answer.status === 200) assert.match(html, /kwant bots <span[^>]*>0\.1\.2<\/span>/, 'the version from the answer');await h.ctrl.check();await h.ctrl.install();assert.deepEqual(h.calls, ['GET /api/app/update'], 'check/install do nothing off the Mac app');@@ -193,7 +217,7 @@ test('install: downloading → restarting while the server is gone → updated wawait h.tick();assert.deepEqual(u.bannerView(h.ctrl.get(), null), { kind: 'updated', version: '0.1.3' });assert.equal(store.m.has(u.UPDATE_PENDING_KEY), false);- assert.equal(u.aboutLine(h.ctrl.get()), 'Updated to 0.1.3.');+ assert.deepEqual(u.versionLine(h.ctrl.get()), { kind: 'updated', version: '0.1.3' });h.ctrl.clearUpdated();assert.equal(u.bannerView(h.ctrl.get(), null), null);});@@ -266,13 +290,13 @@ test('Check for updates polls fast while checking, then shows the result', async});h.ctrl.start();await flush();- assert.equal(u.aboutLine(h.ctrl.get()), 'You’re up to date.');+ assert.equal(u.versionLine(h.ctrl.get()).kind, 'latest');await h.ctrl.check();- assert.equal(u.aboutLine(h.ctrl.get()), 'Checking for updates…');+ assert.equal(u.versionLine(h.ctrl.get()).kind, 'checking');assert.equal(h.live()[0].ms, 1000);await h.tick();await h.tick();- assert.equal(u.aboutLine(h.ctrl.get()), 'You’re up to date.');+ assert.deepEqual(u.versionLine(h.ctrl.get()), { kind: 'latest', checkedAt: Date.parse(CHECKED) });assert.equal(h.live()[0].ms, 30 * 60 * 1000);});@@ -313,26 +337,118 @@ test('banner markup: buttons, notes, progress and dismiss', () => {assert.match(ui.banner({ view: { kind: 'updated', version: '0.1.3' }, onUpdate() {}, onDismiss() {} }), /Updated to kwant bots 0\.1\.3\./);});-test('About row: version, Check for updates, and the offer', () => {- const up = ui.about({ model: model(status({ state: 'idle', available: null })), onCheck() {}, onUpdate() {} });- assert.match(up, /kwant bots for Mac <span[^>]*>0\.1\.2<\/span>/);- assert.match(up, /Check for updates/);- assert.match(up, /You’re up to date\./);- assert.doesNotMatch(up, /disabled=""/);- const offer = ui.about({ model: model(status()), onCheck() {}, onUpdate() {} });- assert.match(offer, /kwant bots 0\.1\.3 is ready\./);- assert.match(offer, /Update to 0\.1\.3 and restart/);- const busy = ui.about({ model: model(status({ state: 'downloading', progress: 0.2 })), onCheck() {}, onUpdate() {} });- assert.match(busy, /disabled=""/);- assert.match(busy, /Downloading the update… 20%/);- const failed = ui.about({ model: model(status({ state: 'error', available: null, error: 'GitHub didn’t answer.' })), onCheck() {}, onUpdate() {} });- assert.match(failed, /text-amber-300[^>]*>GitHub didn’t answer\./);- assert.equal(ui.about({ model: model(null), onCheck() {}, onUpdate() {} }), '');+test('version line: one of latest, available, checking, couldn’t check — never a wrong latest', () => {+ const line = (raw, over) => u.versionLine(model(raw, over));+ assert.deepEqual(line(status({ state: 'idle', available: null })), { kind: 'latest', checkedAt: Date.parse(CHECKED) });+ assert.equal(line(status()).kind, 'available');+ assert.equal(line(status()).canInstall, true);+ assert.equal(line(status({ can_install: false })).canInstall, false);+ assert.equal(line(status({ state: 'checking', available: null })).kind, 'checking');+ // Never checked yet: checking, not "latest"+ assert.equal(line(status({ state: 'idle', available: null, checked_at: null })).kind, 'checking');+ assert.equal(line(null).kind, 'loading');+ const cant = line(status({ state: 'error', available: null, error: 'Couldn’t check for updates: GitHub couldn’t be reached.' }));+ assert.equal(cant.kind, 'check-error');+ // A refused Check again with nothing known+ assert.equal(line(status({ state: 'idle', available: null }), { actionError: 'busy' }).kind, 'check-error');+ // A version found earlier stays on offer after a failed re-check+ assert.equal(line(status({ state: 'error', error: 'Couldn’t check for updates: offline' })).kind, 'available');+ // A failed install is its own line, with Try again and Download manually+ const inst = line(status({ state: 'error', error: 'The signature check failed.' }));+ assert.equal(inst.kind, 'install-error');+ assert.equal(inst.error, 'The signature check failed.');+ assert.equal(line(status({ state: 'downloading', progress: 0.2 })).kind, 'downloading');+ assert.equal(line(status({ state: 'ready' })).kind, 'restarting');});-test('wired once: the banner in the shell, the About row in App settings, hidden on phones', () => {+test('checked ago, in plain words', () => {+ const t = Date.parse(CHECKED);+ assert.equal(u.checkedAgo(null, t), '');+ assert.equal(u.checkedAgo(t, t + 20_000), 'Checked just now');+ assert.equal(u.checkedAgo(t, t + 2 * 60_000), 'Checked 2 min ago');+ assert.equal(u.checkedAgo(t, t + 3 * 3600_000), 'Checked 3 h ago');+ assert.equal(u.checkedAgo(t, t + 26 * 3600_000), 'Checked 1 day ago');+ assert.equal(u.checkedAgo(t, t + 50 * 3600_000), 'Checked 2 days ago');+});++test('kwant card: the version, one status line, What’s new, All releases — no earlier versions', () => {+ const latest = ui.card({ model: model(status({ state: 'idle', available: null })) });+ assert.match(latest, /data-version-card="latest"/);+ assert.match(latest, /kwant bots <span[^>]*>0\.1\.2<\/span>/);+ assert.match(latest, /You’re on the latest version/);+ assert.match(latest, /Check again/);+ assert.match(latest, /Checked 2 min ago/);+ assert.match(latest, /All releases on GitHub/);+ assert.doesNotMatch(latest, /Earlier versions|Update<|is available/);++ const mac = ui.card({ model: model(status()) });+ assert.match(mac, /kwant bots 0\.1\.3 is available/);+ assert.match(mac, /data-version-update[^>]*>.*Update<\/button>/s);+ assert.doesNotMatch(mac, /aria-expanded/, 'on the Mac, Update installs');+ assert.match(mac, /What’s new in 0\.1\.3/, 'the newer version’s notes');+ assert.doesNotMatch(mac, /latest version/);++ const how = { kind: 'docker', command: 'docker compose pull kwnt && docker compose up -d' };+ const docker = ui.card({ model: model(status({ can_install: false, how })), howOpen: true });+ assert.match(docker, /aria-expanded="true"/);+ assert.match(docker, /How to update/);+ assert.match(docker, /docker compose pull kwnt && docker compose up -d/);+ assert.match(docker, /Copy/);+ const closed = ui.card({ model: model(status({ can_install: false, how })) });+ assert.match(closed, /aria-expanded="false"/);+ assert.doesNotMatch(closed, /How to update/);+ const win = ui.card({ model: model(status({ can_install: false, how: { kind: 'windows', command: null } })), howOpen: true });+ assert.match(win, /Download kwant bots 0\.1\.3/);+ assert.match(win, /href="https:\/\/github\.com\/alexsergivan\/kwant\/releases\/tag\/mac-v0\.1\.3"/);++ const cant = ui.card({ model: model(status({ state: 'error', available: null, error: 'Couldn’t check for updates: GitHub couldn’t be reached.' })) });+ assert.match(cant, /data-version-card="check-error"/);+ assert.match(cant, /Couldn’t check for updates/);+ assert.match(cant, /Try again/);+ assert.match(cant, />GitHub couldn’t be reached\.</);+ assert.doesNotMatch(cant, /latest version/);++ const failed = ui.card({ model: model(status({ state: 'error', error: 'The signature check failed.' })) });+ assert.match(failed, /kwant bots 0\.1\.3 didn’t install\./);+ assert.match(failed, /Download manually/);++ const dl = ui.card({ model: model(status({ state: 'downloading', progress: 0.43 })) });+ assert.match(dl, /Downloading kwant bots 0\.1\.3… 43%/);+ assert.match(dl, /role="progressbar"[^>]*aria-valuenow="43"/);++ // The current version’s sheet, in the What’s new card’s look, when this app bundles one+ const entry = { version: '0.1.2', date: '2026-11-10', highlights: [{ id: 'a', title: 'A', text: 'a' }, { id: 'b', title: 'B', text: 'b' }], fixes: ['x'] };+ const withSheet = ui.card({ model: model(status({ state: 'idle', available: null })), entryFor: (v) => (v === '0.1.2' ? entry : null) });+ assert.match(withSheet, /data-whats-new-current="0\.1\.2"/);+ assert.match(withSheet, /What’s new in 0\.1\.2/);+ assert.match(withSheet, /Nov 10 · 2 new things, 1 fix/);+});++test('opening Settings checks again when the last answer is over an hour old, quietly', async () => {+ let checks = 0;+ const h = harness((url, init) => {+ if (init.method === 'POST') {+ checks++;+ return json({ error: 'nope' }, 409);+ }+ return json(status({ state: 'idle', available: null }));+ });+ h.ctrl.start();+ await flush();+ h.advance(Date.parse(CHECKED) + 10 * 60_000);+ await h.ctrl.checkIfStale();+ assert.equal(checks, 0, 'fresh: no check');+ h.advance(2 * 3600_000);+ await h.ctrl.checkIfStale();+ assert.equal(checks, 1);+ assert.equal(h.ctrl.get().actionError, null, 'a refused quiet check says nothing');+});++test('wired once: the banner in the shell, the kwant card in App settings, hidden on phones', () => {assert.match(src('Shell.tsx'), /<AppUpdateBanner \/>/);- assert.match(src('components/SettingsModal.tsx'), /<AppUpdateAbout \/>/);+ const settings = src('components/SettingsModal.tsx');+ assert.equal(settings.match(/<VersionCard \/>/g)?.length, 1);+ assert.doesNotMatch(settings, /AppUpdateAbout|WhatsNewAbout/);assert.match(src('components/AppUpdateBanner.tsx'), /if \(!view \|\| phone\) return null;/);});@@ -354,9 +470,9 @@ test('app_update is saved in the Mac app and never sent to a server without it',assert.deepEqual(notify.notifyOnToSave(['turn_finished'], true), ['turn_finished']);});-test('App settings shows the switch only when the update API is supported', () => {+test('App settings shows the switch only where the app installs updates (the Mac app)', () => {const s = src('components/SettingsModal.tsx');- assert.match(s, /const appUpdates = useAppUpdate\(\)\.model\.status !== null;/);+ assert.match(s, /const appUpdates = useAppUpdate\(\)\.model\.status\?\.canInstall === true;/);assert.match(s, /notifyKindsFor\(appUpdates, !!proactive, !!discovery(, [^)]+)?\)\.map/);assert.match(s, /notify_on: notifyOnToSave\(notifyOn, appUpdates, !!proactive, !!discovery(, [^)]+)?\)/);assert.doesNotMatch(s, /\{NOTIFY_KINDS\.map/);diff --git a/frontend/tests/whatsNew076.test.mjs b/frontend/tests/whatsNew076.test.mjsindex d9b73b58..b3eedfc3 100644--- a/frontend/tests/whatsNew076.test.mjs+++ b/frontend/tests/whatsNew076.test.mjs@@ -36,7 +36,8 @@ const ui = await loadBundled(export { default as React } from 'react';export { createRoot } from 'react-dom/client';export { renderToStaticMarkup } from 'react-dom/server.browser';- export { WhatsNewHost, WhatsNewSheetView, WhatsNewAboutView, WhatsNewAbout, hasWhatsNew } from './src/components/WhatsNewSheet';+ export { WhatsNewHost, WhatsNewSheetView, hasWhatsNew } from './src/components/WhatsNewSheet';+ export { VersionCardView } from './src/components/VersionCard';export { AppUpdateBannerView } from './src/components/AppUpdateBanner';export { openWhatsNew, SEEN_KEY } from './src/whatsNewSheet';export { WHATS_NEW } from './src/whatsNewContent';@@ -302,23 +303,50 @@ test('banner: "See what’s new" on the "Updated to" bar only, and only when thaassert.equal(ui.hasWhatsNew('0.7.4'), false);});-test('Settings › About: What’s new in the latest version, then earlier versions, then GitHub', async () => {- const html = ui.renderToStaticMarkup(React.createElement(ui.WhatsNewAboutView, { entries: ui.WHATS_NEW, onPick() {} }));+test('Settings › kwant: What’s new in the running version opens its sheet; a newer one opens its release notes', async () => {+ const model = (available) => ({+ status: { current: '0.7.6', canInstall: false, lastChecked: Date.now(), how: null, state: available ? 'available' : 'idle', available, progress: null, error: null },+ unsupported: false,+ current: '0.7.6',+ phase: 'idle',+ target: null,+ actionError: null,+ installError: null,+ checkedAt: 1,+ });+ const props = (available) => ({+ model: model(available),+ now: Date.now(),+ onCheck() {},+ onInstall() {},+ onWhatsNew: (v) => ui.openWhatsNew(v),+ onReleaseNotes: (v, notes, date) => ui.openWhatsNew(v, { notes, date }),+ });+ const html = ui.renderToStaticMarkup(React.createElement(ui.VersionCardView, props(null)));assert.match(html, /What’s new in 0\.7\.6<\/b><span[^>]*>Nov 14 · 3 new things, 6 fixes/);- assert.match(html, /Earlier versions/);- assert.match(html, /0\.7\.5<\/span><span[^>]*>Nov 7<\/span><span[^>]*>6 new things, 4 fixes/);- assert.match(html, /Older releases on GitHub/);- assert.equal(ui.renderToStaticMarkup(React.createElement(ui.WhatsNewAboutView, { entries: [], onPick() {} })), '');+ assert.doesNotMatch(html, /Earlier versions|0\.7\.5/);+ assert.match(html, /All releases on GitHub/);- // Picking a row opens that version's sheet through the host.localStorage.setItem(ui.SEEN_KEY, '0.7.6');await host({ established: true });const el = document.createElement('div');document.body.append(el);const root = createRoot(el);mounted.push(root);- await act(async () => root.render(React.createElement(ui.WhatsNewAbout)));+ await act(async () => root.render(React.createElement(ui.VersionCardView, props(null))));await settle();- await click(el.querySelector('button[aria-label="What’s new in 0.7.5"]'));- assert.equal(sheet()?.querySelector('h2')?.textContent, 'What’s new in kwant bots 0.7.5');+ await click(el.querySelector('button[data-whats-new-current="0.7.6"]'));+ assert.equal(sheet()?.querySelector('h2')?.textContent, 'What’s new in kwant bots 0.7.6');+ await click(sheet().querySelector('[data-whats-new-done]'));+ assert.equal(sheet(), null);++ // A version this app doesn't bundle: only its release notes, no way "back" to a sheet it doesn't have+ const next = { version: '9.9.9', notes: '### Added\n- **Faster bots.**', date: '2026-11-12T20:49:18Z', url: 'https://github.com/alexsergivan/kwant/releases/tag/mac-v9.9.9' };+ await act(async () => root.render(React.createElement(ui.VersionCardView, props(next))));+ await settle();+ await click(el.querySelector('button[data-whats-new-next="9.9.9"]'));+ assert.equal(sheet()?.querySelector('h2')?.textContent, 'What’s new in kwant bots 9.9.9');+ assert.match(sheet().textContent, /Released Nov 12/);+ assert.match(sheet().textContent, /Faster bots\./);+ assert.doesNotMatch(sheet().textContent, /All changes in/);});diff --git a/src/app_update.rs b/src/app_update.rsindex b52e71d7..9385153b 100644--- a/src/app_update.rs+++ b/src/app_update.rs@@ -1,7 +1,9 @@-//! In-app updates for the Mac app. The Mac shell (apps/mac) links this crate, runs the server in its-//! own process and registers an [`Updater`] on the shared [`UpdateHub`]; the server's-//! `/api/app/update` routes read and drive the hub. Anywhere else (`kwnt serve`, Docker, a VPS)-//! nothing registers, so the routes report `supported: false` and the web app shows no update UI.+//! Updates. The Mac shell (apps/mac) links this crate, runs the server in its own process and+//! registers an [`Updater`] on the shared [`UpdateHub`] that installs (`can_install: true`); the+//! server's `/api/app/update` routes read and drive the hub. Anywhere else (`kwnt serve`, Docker, a+//! VPS, the Windows beta) the server registers [`release_check`] instead: it reads the same+//! `latest.json` the Mac app does, on start and every 6 hours, and says how this install updates+//! ([`How`]) with `can_install: false`. `KWNT_UPDATE_CHECK=off` turns that off (`supported: false`).//!//! The hub owns the state machine: idle → checking → available → downloading → ready, with error//! from checking or downloading. The updater only does the work (fetch, verify, install, relaunch)@@ -9,9 +11,26 @@//! [`UpdateHub::failed`].use serde::Serialize;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;use tokio::sync::watch;+/// The release feed both the Mac app and the server read: the newest non-prerelease release's+/// `latest.json` (`{version, notes, pub_date, ...}`), written by scripts/mac_latest_json.py.+pub const LATEST_JSON: &str =+ "https://github.com/alexsergivan/kwant/releases/latest/download/latest.json";+pub const RELEASES: &str = "https://github.com/alexsergivan/kwant/releases";+/// How often the server looks again on its own; "Check again" looks at once.+pub const RECHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60);+/// A check that takes longer than this says it couldn't check, never "latest".+pub const CHECK_TIMEOUT: Duration = Duration::from_secs(8);++/// A version's release page: "What's new" and "Download".+pub fn release_page(version: &str) -> String {+ format!("{RELEASES}/tag/mac-v{version}")+}+/// What the updater is doing.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "lowercase")]@@ -37,11 +56,23 @@ pub struct Available {pub url: String,}+/// How an install the app can't update by itself gets the new version: shown under "Update".+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct How {+ /// `docker`, `binary` (a prebuilt `kwnt` on Linux), `windows` (the beta installer) or `source`+ /// (built from a clone).+ pub kind: &'static str,+ /// The lines to run, one per line; `None` when it's a download (Windows) or a build.+ pub command: Option<String>,+}+/// `GET /api/app/update`.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct Status {- /// Whether this process is the Mac app and can update itself.+ /// Whether this server knows about updates: the app's own updater, or the release check.pub supported: bool,+ /// Whether "Update" installs here (the Mac app). Otherwise `how` says what to run.+ pub can_install: bool,/// The running app's version (the kwnt crate's version off-Mac).pub current: String,pub state: State,@@ -49,6 +80,10 @@ pub struct Status {/// Download progress 0–1, while downloading and the size is known.pub progress: Option<f64>,pub error: Option<String>,+ /// When the last check finished, found something or not (RFC 3339). `None` before the first.+ pub checked_at: Option<String>,+ /// With `can_install: false`: how this install updates.+ pub how: Option<How>,}/// The Mac shell's side: does the work, reports back through the hub. Both calls return at once.@@ -65,8 +100,10 @@ pub trait Updater: Send + Sync + 'static {/// Why a check or install can't start now.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Refused {- /// Not the Mac app.+ /// No updater at all.Unsupported,+ /// Install where only the release check runs (not the Mac app).+ CannotInstall,/// Already checking, downloading or relaunching.Busy,/// Install without a newer version found.@@ -76,7 +113,10 @@ pub enum Refused {impl Refused {pub fn message(&self) -> &'static str {match self {- Refused::Unsupported => "updates are only available in the kwant bots Mac app",+ Refused::Unsupported => "this kwant doesn't check for updates (KWNT_UPDATE_CHECK=off)",+ Refused::CannotInstall => {+ "this kwant updates with a command, not from the app: see How to update"+ }Refused::Busy => "an update check or install is already running",Refused::NothingToInstall => "no newer version is available",}@@ -86,6 +126,9 @@ impl Refused {pub struct UpdateHub {updater: Mutex<Option<Arc<dyn Updater>>>,status: watch::Sender<Status>,+ /// Set by the desktop app before it starts the server: its own updater registers shortly, so+ /// the server doesn't start the release check.+ desktop_app: AtomicBool,}impl Default for UpdateHub {@@ -98,13 +141,20 @@ impl UpdateHub {pub fn new() -> Self {let (status, _) = watch::channel(Status {supported: false,+ can_install: false,current: env!("CARGO_PKG_VERSION").to_string(),state: State::Idle,available: None,progress: None,error: None,+ checked_at: None,+ how: None,});- Self { updater: Mutex::new(None), status }+ Self {+ updater: Mutex::new(None),+ status,+ desktop_app: AtomicBool::new(false),+ }}/// The hub of this process: the Mac shell registers on it, the server reads it.@@ -113,15 +163,43 @@ impl UpdateHub {SHARED.get_or_init(|| Arc::new(UpdateHub::new())).clone()}- /// Makes updates supported, running `current` (the app's version, not the crate's).+ /// Makes updates supported and installable, running `current` (the app's version, not the+ /// crate's). Replaces a release check registered before it.pub fn register(&self, current: &str, updater: Arc<dyn Updater>) {*self.updater.lock().unwrap() = Some(updater);self.status.send_modify(|s| {s.supported = true;+ s.can_install = true;+ s.how = None;s.current = current.to_string();});}+ /// The desktop app runs this server and registers its own updater: no release check here.+ pub fn mark_desktop_app(&self) {+ self.desktop_app.store(true, Ordering::Relaxed);+ }++ /// Whether the app's own updater runs (or is about to): the release check stays out.+ pub fn app_updates(&self) -> bool {+ self.desktop_app.load(Ordering::Relaxed) || self.status.borrow().can_install+ }++ /// Off the app: a check that only reports, with `how` for the Update button. Does nothing+ /// when the app's own updater is (or will be) registered.+ pub fn register_check(&self, updater: Arc<dyn Updater>, how: How) -> bool {+ if self.app_updates() {+ return false;+ }+ *self.updater.lock().unwrap() = Some(updater);+ self.status.send_modify(|s| {+ s.supported = true;+ s.can_install = false;+ s.how = Some(how);+ });+ true+ }+pub fn status(&self) -> Status {self.status.borrow().clone()}@@ -160,6 +238,9 @@ impl UpdateHub {/// Starts installing the version found, also after a failed attempt.pub fn install(&self) -> Result<Status, Refused> {let updater = self.updater().ok_or(Refused::Unsupported)?;+ if !self.status.borrow().can_install {+ return Err(Refused::CannotInstall);+ }let mut result = Err(Refused::NothingToInstall);self.status.send_if_modified(|s| match (s.state, &s.available) {(State::Checking | State::Downloading | State::Ready, _) => {@@ -188,6 +269,7 @@ impl UpdateHub {s.available = release;s.progress = None;s.error = None;+ s.checked_at = Some(now_rfc3339());});}@@ -222,6 +304,9 @@ impl UpdateHub {pub fn failed(&self, error: &str) {let error: String = error.chars().take(300).collect();self.status.send_modify(|s| {+ if s.state == State::Checking {+ s.checked_at = Some(now_rfc3339());+ }s.state = State::Error;s.progress = None;s.error = Some(error);@@ -229,6 +314,253 @@ impl UpdateHub {}}+fn now_rfc3339() -> String {+ chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)+}++// ---------- off the app: the release check ----------++/// How this install updates, from where and how it runs.+pub fn how_here() -> How {+ let exe = std::env::current_exe().ok();+ let home = std::env::var_os("HOME").map(std::path::PathBuf::from);+ let unit = std::fs::read_to_string("/proc/self/cgroup")+ .ok()+ .and_then(|c| Unit::from_cgroup(&c));+ how_for(+ crate::doctor::Platform::detect(),+ std::env::consts::OS,+ std::env::consts::ARCH,+ exe.as_deref(),+ home.as_deref(),+ unit,+ )+}++/// The systemd unit kwnt runs as, when it is `kwnt.service`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Unit {+ /// `systemctl --user` (what install.sh sets up).+ User,+ System,+}++impl Unit {+ /// From `/proc/self/cgroup`: `…/[email protected]/app.slice/kwnt.service` or `/system.slice/kwnt.service`.+ pub fn from_cgroup(cgroup: &str) -> Option<Unit> {+ cgroup.lines().find_map(|l| {+ let path = l.rsplit(':').next()?;+ if !path.split('/').any(|part| part == "kwnt.service") {+ return None;+ }+ Some(if path.split('/').any(|part| part.starts_with("user@")) {+ Unit::User+ } else {+ Unit::System+ })+ })+ }+}++/// The one line kwant's own page gives for installing on Linux; run again, it upgrades in place.+pub const INSTALL_SH: &str = "curl -fsSL https://kwant.si/install.sh | sh";++/// [`how_here`] from its parts: `home` is `$HOME`, `unit` the systemd unit kwnt runs as, if any.+pub fn how_for(+ platform: crate::doctor::Platform,+ os: &str,+ arch: &str,+ exe: Option<&std::path::Path>,+ home: Option<&std::path::Path>,+ unit: Option<Unit>,+) -> How {+ use crate::doctor::Platform;+ if platform == Platform::Docker {+ return How {+ kind: "docker",+ command: Some("docker compose pull kwnt && docker compose up -d".into()),+ };+ }+ if os == "windows" {+ return How {+ kind: "windows",+ command: None,+ };+ }+ let built_here = exe.is_none_or(|p| p.components().any(|c| c.as_os_str() == "target"));+ let arch = match arch {+ "x86_64" => Some("x86_64"),+ "aarch64" => Some("aarch64"),+ _ => None,+ };+ match (os, arch, exe.and_then(|p| p.parent())) {+ ("linux", Some(arch), Some(dir)) if !built_here => {+ // install.sh's own place: running it again downloads, checks and restarts (never sudo).+ if home.is_some_and(|h| dir == h.join(".local/bin")) {+ return How {+ kind: "binary",+ command: Some(INSTALL_SH.into()),+ };+ }+ let sudo = if home.is_some_and(|h| dir.starts_with(h)) {+ ""+ } else {+ "sudo "+ };+ let get = format!("curl -fsSL {RELEASES}/latest/download/kwnt-linux-{arch}.tar.gz | {sudo}tar -xz -C {} kwnt", dir.display());+ let restart = match unit {+ Some(Unit::User) => "systemctl --user restart kwnt",+ Some(Unit::System) => "sudo systemctl restart kwnt",+ None => "# then stop kwnt serve and start it again",+ };+ How {+ kind: "binary",+ command: Some(format!("{get}\n{restart}")),+ }+ }+ _ => How {+ kind: "source",+ command: Some("git pull && make build".into()),+ },+ }+}++/// The latest release, from [`LATEST_JSON`]. `Err` with the person's words when it can't tell.+pub async fn fetch_latest(client: &reqwest::Client, url: &str) -> Result<Available, String> {+ let res = client+ .get(url)+ .timeout(CHECK_TIMEOUT)+ .send()+ .await+ .map_err(|e| {+ if e.is_timeout() {+ "GitHub didn't answer in time.".to_string()+ } else {+ "GitHub couldn't be reached.".to_string()+ }+ })?;+ if !res.status().is_success() {+ return Err(format!("GitHub answered {}.", res.status().as_u16()));+ }+ let v: serde_json::Value = res+ .json()+ .await+ .map_err(|_| "GitHub's answer wasn't readable.".to_string())?;+ parse_latest(&v).ok_or_else(|| "GitHub's answer had no version.".to_string())+}++/// `latest.json` → the release, or `None` when it has no `x.y.z` version.+pub fn parse_latest(v: &serde_json::Value) -> Option<Available> {+ let version = v["version"]+ .as_str()?+ .trim()+ .trim_start_matches('v')+ .to_string();+ release_parts(&version)?;+ Some(Available {+ notes: v["notes"].as_str().unwrap_or_default().to_string(),+ date: v["pub_date"].as_str().map(str::to_string),+ url: release_page(&version),+ version,+ })+}++/// After a failed look, the next one comes sooner.+pub const RETRY_AFTER_ERROR: Duration = Duration::from_secs(30 * 60);++/// Whether the release check should look again now.+pub fn check_due(s: &Status, now: chrono::DateTime<chrono::Utc>) -> bool {+ let Some(at) = s+ .checked_at+ .as_deref()+ .and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok())+ else {+ return true;+ };+ let every = if s.state == State::Error && s.available.is_none() {+ RETRY_AFTER_ERROR+ } else {+ RECHECK_EVERY+ };+ now.signed_duration_since(at).to_std().unwrap_or_default() >= every+}++/// The server's updater off the app: looks, never installs.+struct ReleaseCheck {+ hub: Arc<UpdateHub>,+ client: reqwest::Client,+ url: String,+}++impl Updater for ReleaseCheck {+ fn check(&self) {+ let (hub, client, url) = (self.hub.clone(), self.client.clone(), self.url.clone());+ let work = async move {+ match fetch_latest(&client, &url).await {+ Ok(release) => hub.found(Some(release)),+ Err(e) => {+ tracing::info!(error = %e, "update check failed");+ hub.failed(&format!("Couldn't check for updates: {e}"));+ }+ }+ };+ match tokio::runtime::Handle::try_current() {+ Ok(rt) => drop(rt.spawn(work)),+ Err(_) => self.hub.failed("Couldn't check for updates: no runtime."),+ }+ }++ fn install(&self, _version: &str) {+ self.hub.failed(Refused::CannotInstall.message());+ }+}++/// Starts the release check on `hub` when the app's own updater isn't there: one look a few+/// seconds after start, then every [`RECHECK_EVERY`] (wall clock, so a sleeping laptop looks+/// again when it wakes). Stops if the app's updater takes over. `KWNT_UPDATE_CHECK=off` skips it.+pub fn start_release_check(hub: Arc<UpdateHub>) {+ if std::env::var("KWNT_UPDATE_CHECK")+ .is_ok_and(|v| matches!(v.trim(), "off" | "0" | "false" | "no"))+ {+ tracing::info!("update check off (KWNT_UPDATE_CHECK)");+ return;+ }+ let client = reqwest::Client::builder()+ .user_agent(concat!("kwnt/", env!("CARGO_PKG_VERSION")))+ .build()+ .unwrap_or_default();+ // A test feed (a local latest.json) for trying the states; GitHub's otherwise+ let url = std::env::var("KWNT_UPDATE_FEED")+ .ok()+ .filter(|u| {+ u.starts_with("https://")+ || u.starts_with("http://127.0.0.1")+ || u.starts_with("http://localhost")+ })+ .unwrap_or_else(|| LATEST_JSON.to_string());+ let check = Arc::new(ReleaseCheck {+ hub: hub.clone(),+ client,+ url,+ });+ if !hub.register_check(check, how_here()) {+ return;+ }+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_secs(5)).await;+ loop {+ if hub.status().can_install {+ return;+ }+ if check_due(&hub.status(), chrono::Utc::now()) {+ // Busy means a check is already running+ let _ = hub.check();+ }+ tokio::time::sleep(Duration::from_secs(5 * 60)).await;+ }+ });+}+/// `x.y.z` as numbers; `None` for anything else, including prereleases (`0.2.0-rc.1`).fn release_parts(version: &str) -> Option<[u64; 3]> {let mut parts = version.trim().trim_start_matches('v').split('.');@@ -397,6 +729,272 @@ mod tests {assert_eq!(hub.status().error, None);}+ struct Looks;+ impl Updater for Looks {+ fn check(&self) {}+ fn install(&self, _: &str) {}+ }++ fn how() -> How {+ How {+ kind: "docker",+ command: Some("docker compose pull kwnt && docker compose up -d".into()),+ }+ }++ #[test]+ fn release_check_reports_but_never_installs() {+ let hub = UpdateHub::new();+ assert!(hub.register_check(Arc::new(Looks), how()));+ let s = hub.status();+ assert!(s.supported);+ assert!(!s.can_install);+ assert_eq!(s.how.as_ref().unwrap().kind, "docker");+ assert_eq!(s.current, env!("CARGO_PKG_VERSION"));+ assert_eq!(s.checked_at, None);+ hub.check().unwrap();+ hub.found(Some(release("99.0.0")));+ let s = hub.status();+ assert_eq!(s.state, State::Available);+ assert!(s.checked_at.is_some(), "a finished check says when");+ assert_eq!(hub.install(), Err(Refused::CannotInstall));+ assert_eq!(+ hub.status().state,+ State::Available,+ "a refused install changes nothing"+ );+ }++ #[test]+ fn the_app_updater_wins_over_the_release_check() {+ // The app registers after the server started its check: it takes over+ let hub = UpdateHub::new();+ assert!(hub.register_check(Arc::new(Looks), how()));+ hub.register("0.1.1", Arc::new(Fake::default()));+ let s = hub.status();+ assert!(s.can_install);+ assert_eq!(s.how, None);+ // The app said it's coming: the server doesn't start a check+ let hub = UpdateHub::new();+ hub.mark_desktop_app();+ assert!(!hub.register_check(Arc::new(Looks), how()));+ assert!(!hub.status().supported);+ // Already registered: same+ let (hub, _) = hub_pair();+ assert!(!hub.register_check(Arc::new(Looks), how()));+ assert!(hub.status().can_install);+ }++ fn hub_pair() -> (UpdateHub, Arc<Fake>) {+ hub()+ }++ #[test]+ fn a_failed_check_never_says_latest() {+ let hub = UpdateHub::new();+ hub.register_check(Arc::new(Looks), how());+ hub.check().unwrap();+ hub.failed("Couldn't check for updates: GitHub couldn't be reached.");+ let s = hub.status();+ assert_eq!(s.state, State::Error);+ assert_eq!(s.available, None);+ assert!(s.checked_at.is_some());+ // a failed install doesn't move checked_at+ let (hub, _) = hub_pair();+ hub.check().unwrap();+ hub.found(Some(release("0.2.0")));+ let at = hub.status().checked_at;+ hub.install().unwrap();+ hub.failed("download failed");+ assert_eq!(hub.status().checked_at, at);+ }++ #[test]+ fn rechecks_every_6_hours_and_30_minutes_after_a_failure() {+ let hub = UpdateHub::new();+ hub.register_check(Arc::new(Looks), how());+ let now = chrono::Utc::now();+ assert!(check_due(&hub.status(), now), "never checked");+ hub.check().unwrap();+ hub.found(None);+ let s = hub.status();+ let at: chrono::DateTime<chrono::Utc> =+ chrono::DateTime::parse_from_rfc3339(s.checked_at.as_deref().unwrap())+ .unwrap()+ .into();+ assert!(!check_due(&s, at + chrono::Duration::hours(5)));+ assert!(check_due(&s, at + chrono::Duration::hours(6)));+ hub.check().unwrap();+ hub.failed("offline");+ let s = hub.status();+ let at: chrono::DateTime<chrono::Utc> =+ chrono::DateTime::parse_from_rfc3339(s.checked_at.as_deref().unwrap())+ .unwrap()+ .into();+ assert!(!check_due(&s, at + chrono::Duration::minutes(29)));+ assert!(check_due(&s, at + chrono::Duration::minutes(30)));+ }++ #[test]+ fn latest_json_parses() {+ let v = serde_json::json!({"version": "0.9.4", "notes": "kwant 0.9.4: things", "pub_date": "2026-11-12T20:49:18Z", "platforms": {}});+ let a = parse_latest(&v).unwrap();+ assert_eq!(a.version, "0.9.4");+ assert_eq!(a.notes, "kwant 0.9.4: things");+ assert_eq!(a.date.as_deref(), Some("2026-11-12T20:49:18Z"));+ assert_eq!(+ a.url,+ "https://github.com/alexsergivan/kwant/releases/tag/mac-v0.9.4"+ );+ assert_eq!(+ parse_latest(&serde_json::json!({"version": "v1.0.0"}))+ .unwrap()+ .version,+ "1.0.0"+ );+ assert_eq!(+ parse_latest(&serde_json::json!({"version": "latest"})),+ None+ );+ assert_eq!(parse_latest(&serde_json::json!({})), None);+ }++ #[tokio::test]+ async fn fetch_latest_says_why_it_couldnt() {+ let client = reqwest::Client::new();+ // nothing listens on port 9 here+ let e = fetch_latest(&client, "http://127.0.0.1:9/latest.json")+ .await+ .unwrap_err();+ assert_eq!(e, "GitHub couldn't be reached.");+ }++ #[test]+ fn how_each_install_updates() {+ use crate::doctor::Platform;+ use std::path::Path;+ let home = Some(Path::new("/home/me"));+ let docker = how_for(+ Platform::Docker,+ "linux",+ "x86_64",+ Some(Path::new("/usr/local/bin/kwnt")),+ home,+ None,+ );+ assert_eq!(docker.kind, "docker");+ assert_eq!(+ docker.command.as_deref(),+ Some("docker compose pull kwnt && docker compose up -d")+ );+ // install.sh's place: run it again (it upgrades in place, restarts its user unit, never sudo)+ let installed = how_for(+ Platform::Linux,+ "linux",+ "x86_64",+ Some(Path::new("/home/me/.local/bin/kwnt")),+ home,+ Some(Unit::User),+ );+ assert_eq!(+ installed,+ How {+ kind: "binary",+ command: Some(INSTALL_SH.into())+ }+ );+ let bin = how_for(+ Platform::Linux,+ "linux",+ "x86_64",+ Some(Path::new("/usr/local/bin/kwnt")),+ home,+ Some(Unit::System),+ );+ assert_eq!(bin.kind, "binary");+ assert_eq!(+ bin.command.as_deref(),+ Some("curl -fsSL https://github.com/alexsergivan/kwant/releases/latest/download/kwnt-linux-x86_64.tar.gz | sudo tar -xz -C /usr/local/bin kwnt\nsudo systemctl restart kwnt")+ );+ let arm = how_for(+ Platform::Linux,+ "linux",+ "aarch64",+ Some(Path::new("/opt/kwnt/kwnt")),+ home,+ None,+ );+ assert!(arm.command.as_deref().unwrap().contains(+ "kwnt-linux-aarch64.tar.gz | sudo tar -xz -C /opt/kwnt kwnt\n# then stop kwnt serve"+ ));+ // under the home folder: no sudo+ let mine = how_for(+ Platform::Linux,+ "linux",+ "aarch64",+ Some(Path::new("/home/me/apps/kwnt")),+ home,+ Some(Unit::User),+ );+ assert!(mine+ .command+ .as_deref()+ .unwrap()+ .contains("| tar -xz -C /home/me/apps kwnt\nsystemctl --user restart kwnt"));+ let src = how_for(+ Platform::Linux,+ "linux",+ "x86_64",+ Some(Path::new("/home/me/kwant/target/release/kwnt")),+ home,+ None,+ );+ assert_eq!(src.kind, "source");+ assert_eq!(+ how_for(+ Platform::Mac,+ "macos",+ "aarch64",+ Some(Path::new("/usr/local/bin/kwnt")),+ home,+ None+ )+ .kind,+ "source"+ );+ assert_eq!(+ how_for(Platform::Linux, "windows", "x86_64", None, home, None),+ How {+ kind: "windows",+ command: None+ }+ );+ }++ #[test]+ fn systemd_unit_from_cgroup() {+ assert_eq!(+ Unit::from_cgroup(+ "0::/user.slice/user-1000.slice/[email protected]/app.slice/kwnt.service\n"+ ),+ Some(Unit::User)+ );+ assert_eq!(+ Unit::from_cgroup("0::/system.slice/kwnt.service\n"),+ Some(Unit::System)+ );+ // another service's child (a shell in a bot host) is not kwnt's unit+ assert_eq!(+ Unit::from_cgroup("0::/system.slice/openmausbot.service\n"),+ None+ );+ assert_eq!(+ Unit::from_cgroup("0::/user.slice/user-1000.slice/session-3.scope\n"),+ None+ );+ assert_eq!(Unit::from_cgroup(""), None);+ }+#[test]fn status_json_shape() {let (hub, _) = hub();@@ -411,5 +1009,8 @@ mod tests {assert!(v["available"]["url"].as_str().unwrap().ends_with("/mac-v0.1.2"));assert!(v["progress"].is_null());assert!(v["error"].is_null());+ assert_eq!(v["can_install"], true);+ assert!(v["checked_at"].as_str().unwrap().ends_with('Z'));+ assert!(v["how"].is_null());}}diff --git a/src/serve.rs b/src/serve.rsindex 48a023ff..9ca10bf5 100644--- a/src/serve.rs+++ b/src/serve.rs@@ -73,6 +73,8 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(crate::server::engine_routes::spawn_startup_check(state.clone());crate::server::parallel_routes::spawn_startup_sweep(state.clone());crate::server::app_update_routes::spawn_notifier(state.clone());+ // Off the desktop app: look for a newer release, so Settings can say "latest" or how to update+ crate::app_update::start_release_check(state.app_update.clone());// browser containers left by this or another kwant: remove orphans, stop idle oneslet browser = state.browser_service.clone();browser.clone().spawn_reaper(cancel.clone());diff --git a/src/server/app_update_routes.rs b/src/server/app_update_routes.rsindex e14fbf90..3932200a 100644--- a/src/server/app_update_routes.rs+++ b/src/server/app_update_routes.rs@@ -1,5 +1,6 @@-//! `/api/app/update`: the Mac app's in-app update (see [`crate::app_update`]). GET is open to-//! bots like other status reads; check and install are person-only (`auth::person_only`).+//! `/api/app/update`: the Mac app's in-app update, and elsewhere the release check (see+//! [`crate::app_update`]). GET is open to bots like other status reads; check and install are+//! person-only (`auth::person_only`).use super::continuity::{notify, Notification};use super::AppState;@@ -12,18 +13,19 @@ use axum::Json;/// The setting that remembers which version the person was already told about.pub const NOTIFIED_SETTING: &str = "app_update_notified_version";-/// `GET /api/app/update`: `{supported, current, state, available, progress, error}`.+/// `GET /api/app/update`: `{supported, can_install, current, state, available, progress, error,+/// checked_at, how}`.pub async fn get_status(AxState(state): AxState<AppState>) -> Json<Status> {Json(state.app_update.status())}-/// `POST /api/app/update/check`: 202 with the status; 409 off the Mac app or while busy.+/// `POST /api/app/update/check`: 202 with the status; 409 with the check off or while busy.pub async fn check(AxState(state): AxState<AppState>) -> Response {reply(state.app_update.check())}-/// `POST /api/app/update/install`: 202 with the status; 409 off the Mac app, while busy, or with-/// no newer version found. The app relaunches by itself once the new version is in place.+/// `POST /api/app/update/install`: 202 with the status; 409 off the Mac app (`can_install: false`),+/// while busy, or with no newer version found. The app relaunches by itself once the new version is in place.pub async fn install(AxState(state): AxState<AppState>) -> Response {reply(state.app_update.install())}@@ -36,14 +38,15 @@ fn reply(result: Result<Status, Refused>) -> Response {}/// Tells the person once per version that an update is out, through the usual notifications.-/// Runs for the life of the server; does nothing off the Mac app, where the state never changes.+/// Runs for the life of the server; only in the app that installs (a server's own "is ready, open+/// kwant bots to update" would be wrong: there the card says how).pub fn spawn_notifier(state: AppState) {let mut rx = state.app_update.subscribe();tokio::spawn(async move {loop {let available = {let s = rx.borrow_and_update();- (s.state == State::Available).then(|| s.available.clone()).flatten()+ (s.can_install && s.state == State::Available).then(|| s.available.clone()).flatten()};if let Some(a) = available {notify_once(&state, &a.version).await;diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 643f3df4..b7afffce 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -1716,7 +1716,7 @@ pub fn effective_kinds(saved: &[String], known: &[String]) -> Vec<String> {/// Kinds this server can't raise, so its settings page doesn't offer them: the web app leaves/// them out of a save, which must not read as the person turning them off.fn unavailable_kinds(state: &AppState) -> Vec<&'static str> {- if state.app_update.status().supported {+ if state.app_update.status().can_install {Vec::new()} else {vec!["app_update"]diff --git a/tests/app_update_test.rs b/tests/app_update_test.rsindex a42ecad5..0211ad94 100644--- a/tests/app_update_test.rs+++ b/tests/app_update_test.rs@@ -1,5 +1,6 @@-//! The Mac app's in-app update routes: `/api/app/update` reads the state for anyone, check and-//! install are the person's, and off the Mac app (nothing registered) updates are unsupported.+//! The update routes: `/api/app/update` reads the state for anyone, check and install are the+//! person's. The Mac app installs; off it the release check only reports (`can_install: false`,+//! with `how`), and with nothing registered (`KWNT_UPDATE_CHECK=off`) updates are unsupported.use axum::{body::{to_bytes, Body},@@ -7,7 +8,7 @@ use axum::{Router,};use kwnt::{- app_update::{Available, State, UpdateHub, Updater},+ app_update::{Available, How, State, UpdateHub, Updater},broker::PermissionBroker,config::Config,db::{spaces::SpaceId, Database},@@ -102,11 +103,12 @@ fn release(version: &str) -> Available {}#[tokio::test]-async fn unsupported_off_the_mac_app() {+async fn unsupported_with_the_check_off() {let e = setup(None).await;let (status, v) = call(&e.app, "GET", "/api/app/update", None).await;assert_eq!(status, StatusCode::OK, "{v}");assert_eq!(v["supported"], false);+ assert_eq!(v["can_install"], false);assert_eq!(v["current"], env!("CARGO_PKG_VERSION"));assert_eq!(v["state"], "idle");assert!(v["available"].is_null());@@ -115,10 +117,97 @@ async fn unsupported_off_the_mac_app() {for uri in ["/api/app/update/check", "/api/app/update/install"] {let (status, v) = call(&e.app, "POST", uri, None).await;assert_eq!(status, StatusCode::CONFLICT, "{uri}: {v}");- assert!(v["error"].as_str().unwrap().contains("Mac app"), "{v}");+ assert!(+ v["error"]+ .as_str()+ .unwrap()+ .contains("doesn't check for updates"),+ "{v}"+ );}}+#[tokio::test]+async fn off_the_mac_app_the_check_reports_and_says_how() {+ let e = setup(None).await;+ let check = Arc::new(FakeUpdater::default());+ let how = How {+ kind: "docker",+ command: Some("docker compose pull kwnt && docker compose up -d".into()),+ };+ assert!(e.state.app_update.register_check(check.clone(), how));+ let person = e.state.api_token.reveal().to_string();++ let (_, v) = call(&e.app, "GET", "/api/app/update", None).await;+ assert_eq!(v["supported"], true);+ assert_eq!(v["can_install"], false);+ assert_eq!(v["how"]["kind"], "docker");+ assert_eq!(+ v["how"]["command"],+ "docker compose pull kwnt && docker compose up -d"+ );+ assert!(v["checked_at"].is_null(), "not checked yet");++ // Check again: the person's, like on the Mac+ let (status, v) = call(&e.app, "POST", "/api/app/update/check", Some(&person)).await;+ assert_eq!(status, StatusCode::ACCEPTED, "{v}");+ assert_eq!(v["state"], "checking");+ e.state.app_update.found(Some(release("99.0.0")));+ let (_, v) = call(&e.app, "GET", "/api/app/update", None).await;+ assert_eq!(v["state"], "available");+ assert_eq!(v["available"]["version"], "99.0.0");+ assert!(v["checked_at"].as_str().is_some());++ // Never installs here+ let (status, v) = call(&e.app, "POST", "/api/app/update/install", Some(&person)).await;+ assert_eq!(status, StatusCode::CONFLICT, "{v}");+ assert!(+ v["error"].as_str().unwrap().contains("How to update"),+ "{v}"+ );+ assert_eq!(*check.calls.lock().unwrap(), vec!["check"]);++ // GitHub can't be reached: an error, never "latest"+ e.state.app_update.check().unwrap();+ e.state+ .app_update+ .failed("Couldn't check for updates: GitHub couldn't be reached.");+ let (_, v) = call(&e.app, "GET", "/api/app/update", None).await;+ assert_eq!(v["state"], "error");+ assert!(v["error"].as_str().unwrap().starts_with("Couldn't check"));+}++#[tokio::test]+async fn no_ready_to_install_notification_off_the_mac_app() {+ let e = setup(None).await;+ e.state.app_update.register_check(+ Arc::new(FakeUpdater::default()),+ How {+ kind: "docker",+ command: None,+ },+ );+ let mut events = e.state.event_sender.subscribe();+ app_update_routes::spawn_notifier(e.state.clone());+ e.state.app_update.check().unwrap();+ e.state.app_update.found(Some(release("99.0.0")));+ tokio::time::sleep(Duration::from_millis(200)).await;+ while let Ok(ev) = events.try_recv() {+ assert!(+ !matches!(ev, RuntimeEvent::Notify { ref kind, .. } if kind == "app_update"),+ "no notification"+ );+ }+ assert_eq!(+ e.state+ .db+ .get_setting(app_update_routes::NOTIFIED_SETTING)+ .await+ .unwrap(),+ None+ );+}+#[tokio::test]async fn bots_read_but_never_check_or_install() {let fake = Arc::new(FakeUpdater::default());