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
Mac app: update banner and About row for in-app updates
Pixel (kwant bot)a41fd98f3723
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d1adf991..1ddcd751 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).## Unreleased### Added+- **Update banner in the Mac app.** When a new Mac version is out, a slim bar at the top says+ "kwant bots X.Y.Z is ready" with **Update and restart** and **What's new** (that version's notes).+ It shows download progress, then "Restarting…", then "Updated to X.Y.Z". If the update fails, it+ shows why, with **Try again** and **Download manually**, and the current app keeps working.+ Hiding the bar hides it for that version only. App settings → About shows the running version and+ has **Check for updates**. Nothing shows outside the Mac app, and phones get only the About row.- **Vibration on Android phones.** The web app gives a short buzz when you send a message, answer aquestion or approval card, press **Solve it**, **Done**, **Skip** or **Hand back**, and when a puzzleis solved, with a different buzz for errors. A bot reply arriving while the app is on screen gives adiff --git a/frontend/src/Shell.tsx b/frontend/src/Shell.tsxindex 89694a27..6bcfe490 100644--- a/frontend/src/Shell.tsx+++ b/frontend/src/Shell.tsx@@ -8,6 +8,7 @@ import type { SpaceSettingsTab } from './components/SpaceSettings';import { ArchivedSpacesModal, NewSpaceModal, SpaceRail } from './components/Spaces';import { Toasts, Toast } from './components/Toasts';import { InstallHint } from './components/InstallHint';+import { AppUpdateBanner } from './components/AppUpdateBanner';import { playSfx } from './audio/chiptune';import {Space,@@ -224,34 +225,37 @@ export const App: React.FC = () => {}return (- <div className="h-[var(--kwnt-app-height,100dvh)] w-screen flex bg-zinc-950 text-zinc-100 overflow-hidden font-sans pt-[env(safe-area-inset-top)] pl-[env(safe-area-inset-left)] pr-[env(safe-area-inset-right)]">- <SpaceRail spaces={spaces} currentId={current.id} onSwitch={switchTo} onCreate={openCreate} onOpenAppSettings={() => setAppSettingsOpen(true)} />- <SpaceApp- key={current.id}- space={current}- spaces={spaces}- initialTarget={target}- initialSettingsTab={startTab}- onSwitchSpace={switchTo}- onCreateSpace={openCreate}- onOpenArchived={() => setShowArchived(true)}- onOpenAppSettings={() => setAppSettingsOpen(true)}- onSpacesChanged={reload}- onSpaceArchived={(s) => {- reload().then((list) => {- const next = list?.find((x) => x.is_default) ?? list?.[0];- if (next) open(next.id);- });- const id = ++toastIdRef.current;- setToasts((prev) => [...prev, { id, title: `${s.name} is archived`, detail: 'Its routines are paused. Restore it from Archived spaces.' }]);- }}- onChatChange={(t) => {- rememberChat(current.id, t);- const path = spacePath(current.id, t);- if (window.location.pathname !== path) window.history.replaceState(null, '', path);- }}- onTokensUsed={setTokensUsed}- />+ <div className="h-[var(--kwnt-app-height,100dvh)] w-screen flex flex-col bg-zinc-950 text-zinc-100 overflow-hidden font-sans pt-[env(safe-area-inset-top)] pl-[env(safe-area-inset-left)] pr-[env(safe-area-inset-right)]">+ <AppUpdateBanner />+ <div className="flex-1 min-h-0 flex">+ <SpaceRail spaces={spaces} currentId={current.id} onSwitch={switchTo} onCreate={openCreate} onOpenAppSettings={() => setAppSettingsOpen(true)} />+ <SpaceApp+ key={current.id}+ space={current}+ spaces={spaces}+ initialTarget={target}+ initialSettingsTab={startTab}+ onSwitchSpace={switchTo}+ onCreateSpace={openCreate}+ onOpenArchived={() => setShowArchived(true)}+ onOpenAppSettings={() => setAppSettingsOpen(true)}+ onSpacesChanged={reload}+ onSpaceArchived={(s) => {+ reload().then((list) => {+ const next = list?.find((x) => x.is_default) ?? list?.[0];+ if (next) open(next.id);+ });+ const id = ++toastIdRef.current;+ setToasts((prev) => [...prev, { id, title: `${s.name} is archived`, detail: 'Its routines are paused. Restore it from Archived spaces.' }]);+ }}+ onChatChange={(t) => {+ rememberChat(current.id, t);+ const path = spacePath(current.id, t);+ if (window.location.pathname !== path) window.history.replaceState(null, '', path);+ }}+ onTokensUsed={setTokensUsed}+ />+ </div>{creating && (<NewSpaceModaldiff --git a/frontend/src/appUpdate.ts b/frontend/src/appUpdate.tsnew file mode 100644index 00000000..079d33b2--- /dev/null+++ b/frontend/src/appUpdate.ts@@ -0,0 +1,360 @@+// 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.++export type UpdateState = 'idle' | 'checking' | 'available' | 'downloading' | 'ready' | 'error';++export interface AvailableUpdate {+ version: string;+ /** That version's CHANGELOG section, markdown. */+ notes: string;+ date: string | null;+ /** The release page: "Download manually" when the in-app update fails. */+ url: string;+}++export interface UpdateStatus {+ current: string;+ state: UpdateState;+ available: AvailableUpdate | null;+ progress: number | null;+ error: string | null;+}++/** What the banner shows, or null for no banner. */+export type BannerView =+ | { kind: 'available'; version: string; notes: string; url: string }+ | { kind: 'downloading'; version: string; progress: number | null }+ | { kind: 'restarting'; version: string }+ | { kind: 'error'; version: string; error: string; url: string; notes: string }+ | { kind: 'updated'; version: string };++/** The client's own part: an install it started, and the relaunch after it. */+export type UpdatePhase = 'idle' | 'installing' | 'restarting' | 'updated' | 'stalled';++export interface UpdateModel {+ /** null until the first answer, and forever when unsupported. */+ status: UpdateStatus | null;+ unsupported: boolean;+ phase: UpdatePhase;+ /** The version being installed, or the one just installed. */+ target: string | null;+ /** A refused check or install (409, 403), in the person's words. */+ actionError: string | null;+ /** The same, when it was the install that was refused: the banner shows it with Retry. */+ installError: string | null;+ checkedAt: number | null;+}++export const UPDATE_DISMISSED_KEY = 'kwnt_update_dismissed';+export const UPDATE_PENDING_KEY = 'kwnt_update_pending';++export const IDLE_POLL_MS = 30 * 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;++const STATES: UpdateState[] = ['idle', 'checking', 'available', 'downloading', 'ready', 'error'];++const str = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v : null);++function parseAvailable(raw: unknown): AvailableUpdate | null {+ if (!raw || typeof raw !== 'object') return null;+ const a = raw as Record<string, unknown>;+ const version = str(a.version);+ if (!version) return null;+ const url = str(a.url);+ return {+ version,+ notes: typeof a.notes === 'string' ? a.notes : '',+ date: str(a.date),+ url: url && /^https:\/\//.test(url) ? url : `https://github.com/alexsergivan/kwant/releases/tag/mac-v${version}`,+ };+}++/** The server's answer, or null when it isn't the Mac app (or 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 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) ?? '',+ state,+ available: parseAvailable(r.available),+ progress,+ error: str(r.error),+ };+}++type Store = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;++const defaultStore = (): Store | undefined => {+ try {+ return globalThis.localStorage;+ } catch {+ return undefined;+ }+};++function read(key: string, store: Store | undefined): string | null {+ try {+ return store?.getItem(key) ?? null;+ } catch {+ return null;+ }+}++function write(key: string, value: string | null, store: Store | undefined) {+ try {+ if (value === null) store?.removeItem(key);+ else store?.setItem(key, value);+ } catch {+ // Private browsing or blocked storage: the banner just comes back next time.+ }+}++/** Dismissing hides the banner for that version only; a newer one shows it again. */+export const dismissedVersion = (store = defaultStore()) => read(UPDATE_DISMISSED_KEY, store);+export const dismissVersion = (version: string, store = defaultStore()) => write(UPDATE_DISMISSED_KEY, version, store);++export function bannerView(m: UpdateModel, dismissed: string | null): BannerView | null {+ if (m.unsupported || !m.status) 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) {+ return {+ kind: 'error',+ version: m.target,+ error: 'The app didn’t come back after the update. Open kwant bots again from Applications.',+ url: m.status.available?.url ?? `https://github.com/alexsergivan/kwant/releases/tag/mac-v${m.target}`,+ notes: m.status.available?.notes ?? '',+ };+ }+ const a = m.status.available;+ if (!a) return null;+ const s = m.status.state;+ if (s === 'ready') return { kind: 'restarting', version: a.version };+ if (s === 'downloading' || m.phase === 'installing') return { kind: 'downloading', version: a.version, progress: m.status.progress };+ if (s === 'error' || m.installError) {+ return { kind: 'error', version: a.version, error: m.installError ?? m.status.error ?? 'The update failed.', url: a.url, notes: a.notes };+ }+ if (s !== 'available') return null;+ if (dismissed === a.version) return null;+ return { kind: 'available', version: a.version, notes: a.notes, url: a.url };+}++/** Fast while something is moving, every 30 minutes otherwise. */+export function nextPollMs(m: UpdateModel): number {+ if (m.phase === 'installing' || m.phase === 'restarting') return FAST_POLL_MS;+ const s = m.status?.state;+ 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 {+ 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.' : '';+ }+}++async function errorText(res: Response): Promise<string | null> {+ try {+ const body = await res.json();+ return str(body?.error);+ } catch {+ return 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.';+ return errorText(res).then((e) => e ?? fallback);+}++export interface ControllerEnv {+ fetch: (url: string, init?: RequestInit) => Promise<Response>;+ setTimeout: (fn: () => void, ms: number) => unknown;+ clearTimeout: (id: unknown) => void;+ now: () => number;+ store?: Store;+}++export interface UpdateController {+ get: () => UpdateModel;+ subscribe: (fn: () => void) => () => void;+ start: () => void;+ stop: () => void;+ check: () => 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 };+ const listeners = new Set<() => void>();+ let timer: unknown = null;+ let running = false;+ let restartSince: number | null = null;++ const set = (patch: Partial<UpdateModel>) => {+ model = { ...model, ...patch };+ listeners.forEach((fn) => fn());+ };++ const schedule = (ms = nextPollMs(model)) => {+ if (timer !== null) env.clearTimeout(timer);+ timer = null;+ if (!running || model.unsupported) return;+ timer = env.setTimeout(() => {+ timer = null;+ void load();+ }, ms);+ };++ const apply = (status: UpdateStatus) => {+ const patch: Partial<UpdateModel> = { status, 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.+ write(UPDATE_PENDING_KEY, null, env.store);+ Object.assign(patch, { phase: 'updated', target: pending, actionError: null });+ restartSince = null;+ } else if (model.phase === 'installing' && status.state === 'ready') {+ Object.assign(patch, { phase: 'restarting' });+ restartSince = env.now();+ } else if ((model.phase === 'installing' || model.phase === 'restarting') && status.state === 'error') {+ write(UPDATE_PENDING_KEY, null, env.store);+ Object.assign(patch, { phase: 'idle', target: null });+ restartSince = null;+ } else if (pending && model.phase === 'idle' && status.state !== 'downloading' && status.state !== 'ready') {+ // An install from an earlier window that never landed: forget it, the banner offers it again.+ write(UPDATE_PENDING_KEY, null, env.store);+ }+ if (status.state !== 'error' && model.actionError && model.phase !== 'idle') patch.actionError = null;+ set(patch);+ };++ async function load() {+ let res: Response;+ try {+ res = await env.fetch('/api/app/update', { headers: { Accept: 'application/json' } });+ } catch {+ // No server: it's relaunching after an install, or the network dropped.+ if (model.phase === 'installing' || model.status?.state === 'ready') {+ if (model.phase !== 'restarting') restartSince = env.now();+ set({ phase: 'restarting', target: model.target ?? model.status?.available?.version ?? null });+ }+ if (model.phase === 'restarting' && restartSince !== null && env.now() - restartSince > RESTART_GIVE_UP_MS) {+ set({ phase: 'stalled' });+ return schedule(IDLE_POLL_MS);+ }+ return schedule();+ }+ if (res.status === 404) {+ set({ unsupported: true });+ return schedule();+ }+ if (!res.ok) return schedule(model.phase === 'restarting' ? FAST_POLL_MS : IDLE_POLL_MS);+ let body: unknown = null;+ try {+ body = await res.json();+ } catch {+ return schedule();+ }+ const status = parseUpdateStatus(body);+ if (!status) {+ set({ unsupported: true });+ return schedule();+ }+ apply(status);+ schedule();+ }++ async function post(path: string, fallback: string): Promise<boolean> {+ try {+ const res = await env.fetch(path, { method: 'POST', headers: { Accept: 'application/json' } });+ if (res.ok) {+ const status = parseUpdateStatus(await res.json().catch(() => null));+ if (status) apply(status);+ set({ actionError: null });+ return true;+ }+ set({ actionError: await refusal(res, fallback) });+ } catch {+ set({ actionError: 'The app didn’t answer. Try again in a moment.' });+ }+ return false;+ }++ return {+ get: () => model,+ subscribe(fn) {+ listeners.add(fn);+ return () => listeners.delete(fn);+ },+ start() {+ if (running) return;+ running = true;+ void load();+ },+ stop() {+ running = false;+ if (timer !== null) env.clearTimeout(timer);+ timer = null;+ },+ async check() {+ if (model.unsupported) return;+ set({ actionError: null, installError: null, phase: model.phase === 'updated' ? 'idle' : model.phase });+ await post('/api/app/update/check', 'Couldn’t check for updates.');+ schedule();+ },+ async install() {+ const version = model.status?.available?.version;+ if (model.unsupported || !version) return;+ write(UPDATE_PENDING_KEY, version, env.store);+ set({ phase: 'installing', target: version, actionError: null, installError: null });+ const ok = await post('/api/app/update/install', 'Couldn’t start the update.');+ if (!ok) {+ write(UPDATE_PENDING_KEY, null, env.store);+ set({ phase: 'idle', target: null, installError: model.actionError });+ }+ schedule();+ },+ clearUpdated() {+ if (model.phase === 'updated') set({ phase: 'idle', target: null });+ },+ };+}++let shared: UpdateController | null = null;++/** One poller for the whole page, shared by the banner and App settings. */+export function appUpdateController(): UpdateController {+ shared ??= createUpdateController({+ fetch: (url, init) => fetch(url, init),+ setTimeout: (fn, ms) => window.setTimeout(fn, ms),+ clearTimeout: (id) => window.clearTimeout(id as number),+ now: () => Date.now(),+ store: defaultStore(),+ });+ return shared;+}diff --git a/frontend/src/components/AppUpdateBanner.tsx b/frontend/src/components/AppUpdateBanner.tsxnew file mode 100644index 00000000..5aa89125--- /dev/null+++ b/frontend/src/components/AppUpdateBanner.tsx@@ -0,0 +1,230 @@+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 { MarkdownRenderer } from './MarkdownRenderer';++const PHONE_QUERY = '(max-width: 767px)';+const UPDATED_NOTE_MS = 10000;++/** The shared update state; starts the one poller on first use. */+export function useAppUpdate(ctrl: UpdateController = appUpdateController()) {+ const model = useSyncExternalStore(ctrl.subscribe, ctrl.get, ctrl.get);+ useEffect(() => ctrl.start(), [ctrl]);+ return { model, ctrl };+}++interface ViewProps {+ view: BannerView;+ onUpdate: () => void;+ onDismiss: () => void;+}++const btn =+ 'inline-flex min-h-[32px] items-center gap-1.5 rounded-lg px-3 text-xs font-medium focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';++/** The slim bar itself, without the polling: what tests and screenshots render. */+export const AppUpdateBannerView: React.FC<ViewProps> = ({ view, onUpdate, onDismiss }) => {+ const [notesOpen, setNotesOpen] = useState(false);+ const notesId = useId();+ const notes = view.kind === 'available' || view.kind === 'error' ? view.notes.trim() : '';+ const tone =+ view.kind === 'error'+ ? 'border-amber-500/30 bg-amber-500/10'+ : view.kind === 'updated'+ ? 'border-emerald-500/30 bg-emerald-500/10'+ : 'border-sky-500/30 bg-sky-500/10';++ return (+ <aside aria-label="App update" data-update-banner={view.kind} className={`shrink-0 border-b ${tone} text-xs text-zinc-100`}>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-2">+ <p className="flex min-w-0 flex-1 items-center gap-2" role="status" aria-live="polite">+ {view.kind === 'available' && <ArrowUpCircle size={15} className="shrink-0 text-sky-300" aria-hidden="true" />}+ {(view.kind === 'downloading' || view.kind === 'restarting') && (+ <Loader2 size={15} className="shrink-0 animate-spin text-sky-300 motion-reduce:animate-none" aria-hidden="true" />+ )}+ {view.kind === 'error' && <AlertTriangle size={15} className="shrink-0 text-amber-300" aria-hidden="true" />}+ {view.kind === 'updated' && <CheckCircle2 size={15} className="shrink-0 text-emerald-300" aria-hidden="true" />}+ <span className="min-w-0">+ {view.kind === 'available' && (+ <>+ <span className="font-medium">kwant bots {view.version} is ready.</span>+ <span className="text-zinc-400"> Your chats and bots stay as they are.</span>+ </>+ )}+ {view.kind === 'downloading' && (+ <span className="font-medium">+ Downloading kwant bots {view.version}…{view.progress != null && ` ${Math.round(view.progress * 100)}%`}+ </span>+ )}+ {view.kind === 'restarting' && <span className="font-medium">Restarting the app to finish the update…</span>}+ {view.kind === 'error' && (+ <>+ <span className="font-medium">kwant bots {view.version} didn’t install.</span>+ <span className="text-zinc-300"> {view.error} This version keeps working.</span>+ </>+ )}+ {view.kind === 'updated' && <span className="font-medium">Updated to kwant bots {view.version}.</span>}+ </span>+ </p>++ {(view.kind === 'available' || view.kind === 'error') && (+ <div className="flex shrink-0 flex-wrap items-center gap-2">+ {notes && (+ <button+ type="button"+ aria-expanded={notesOpen}+ aria-controls={notesId}+ onClick={() => setNotesOpen((v) => !v)}+ className={`${btn} text-sky-200 hover:bg-sky-500/15`}+ >+ What’s new+ </button>+ )}+ {view.kind === 'error' && (+ <a href={view.url} target="_blank" rel="noreferrer" className={`${btn} text-zinc-200 hover:bg-zinc-800`}>+ <ExternalLink size={13} aria-hidden="true" /> Download manually+ </a>+ )}+ <button type="button" onClick={onUpdate} className={`${btn} bg-sky-600 text-white hover:bg-sky-500`}>+ {view.kind === 'error' ? <RotateCw size={13} aria-hidden="true" /> : <ArrowUpCircle size={13} aria-hidden="true" />}+ {view.kind === 'error' ? 'Try again' : 'Update and restart'}+ </button>+ </div>+ )}++ {view.kind === 'downloading' && (+ <div+ role="progressbar"+ aria-label={`Downloading kwant bots ${view.version}`}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={view.progress == null ? undefined : Math.round(view.progress * 100)}+ className="h-1.5 w-32 shrink-0 overflow-hidden rounded-full bg-zinc-800"+ >+ <div+ className={`h-full bg-sky-400 transition-[width] motion-reduce:transition-none ${view.progress == null ? 'w-1/3 animate-pulse' : ''}`}+ style={view.progress == null ? undefined : { width: `${Math.round(view.progress * 100)}%` }}+ />+ </div>+ )}++ {(view.kind === 'available' || view.kind === 'updated') && (+ <button+ type="button"+ onClick={onDismiss}+ aria-label={view.kind === 'available' ? `Hide until the next version` : 'Close'}+ title={view.kind === 'available' ? 'Hide until the next version' : undefined}+ className="-my-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"+ >+ <X size={15} />+ </button>+ )}+ </div>+ {notes && (+ <div id={notesId} hidden={!notesOpen} className="max-h-60 overflow-y-auto border-t border-zinc-800/80 px-4 py-3 text-zinc-300 select-text">+ <MarkdownRenderer content={notes} />+ </div>+ )}+ </aside>+ );+};++/** "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). */+export const AppUpdateBanner: React.FC = () => {+ const { model, ctrl } = useAppUpdate();+ const [dismissed, setDismissed] = useState(dismissedVersion);+ const [phone, setPhone] = useState(() => !!window.matchMedia?.(PHONE_QUERY).matches);++ useEffect(() => {+ const mq = window.matchMedia?.(PHONE_QUERY);+ const onMq = () => setPhone(!!mq?.matches);+ mq?.addEventListener('change', onMq);+ return () => mq?.removeEventListener('change', onMq);+ }, []);++ const updated = model.phase === 'updated';+ useEffect(() => {+ if (!updated) return;+ const t = window.setTimeout(() => ctrl.clearUpdated(), UPDATED_NOTE_MS);+ return () => window.clearTimeout(t);+ }, [updated, ctrl]);++ const view = bannerView(model, dismissed);+ if (!view || phone) return null;+ return (+ <AppUpdateBannerView+ key={`${view.kind}-${view.version}`}+ view={view}+ onUpdate={() => void ctrl.install()}+ onDismiss={() => {+ if (view.kind === 'updated') return ctrl.clearUpdated();+ dismissVersion(view.version);+ setDismissed(view.version);+ }}+ />+ );+};++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 Mac <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 26c8d359..b3dd442c 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -26,6 +26,7 @@ import { signedInDevicesVisible } from '../deviceSignIn';import { ComputerModeControl, useComputerMode } from './ComputerModeSwitch';import { useEngines } from '../useEngines';import { LayaStatusRow } from './LayaStatus';+import { AppUpdateAbout } from './AppUpdateBanner';interface SettingsData {anthropic_api_key: string;@@ -331,6 +332,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t</div></div>+ <AppUpdateAbout />+{computer.state.settings && (<div className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3"><div>diff --git a/frontend/tests/appUpdate.test.mjs b/frontend/tests/appUpdate.test.mjsnew file mode 100644index 00000000..fa3f9074--- /dev/null+++ b/frontend/tests/appUpdate.test.mjs@@ -0,0 +1,337 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { readFileSync } from 'node:fs';+import { loadBundled } from './bundle.mjs';++// The markdown renderer pulls in the UI sounds, which read localStorage when loaded.+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };++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';+ export const banner = (props) => renderToStaticMarkup(React.createElement(AppUpdateBannerView, props));+ export const about = (props) => renderToStaticMarkup(React.createElement(AppUpdateAboutView, props));+`);+const src = (path) => readFileSync(new URL(`../src/${path}`, import.meta.url), 'utf8');++const NOTES = '### Added\n- **In-app updates.**';+const status = (over = {}) => ({+ supported: true,+ 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' },+ progress: null,+ error: null,+ ...over,+});+const model = (raw, over = {}) => ({+ status: u.parseUpdateStatus(raw),+ unsupported: false,+ phase: 'idle',+ target: null,+ actionError: null,+ installError: null,+ checkedAt: 1,+ ...over,+});+const memStore = (init = {}) => {+ const m = new Map(Object.entries(init));+ return { m, getItem: (k) => m.get(k) ?? null, setItem: (k, v) => m.set(k, String(v)), removeItem: (k) => m.delete(k) };+};+const json = (body, code = 200) => ({ ok: code >= 200 && code < 300, status: code, json: async () => body });++/** A fake server and clock: records every request and every scheduled poll. */+function harness(answers, store = memStore()) {+ const calls = [];+ const timers = [];+ let now = 0;+ const ctrl = u.createUpdateController({+ fetch: async (url, init = {}) => {+ calls.push(`${init.method ?? 'GET'} ${url}`);+ const a = answers(url, init, calls.length);+ if (a instanceof Error) throw a;+ return a;+ },+ setTimeout: (fn, ms) => {+ const t = { fn, ms, live: true };+ timers.push(t);+ return t;+ },+ clearTimeout: (t) => t && (t.live = false),+ now: () => now,+ store,+ });+ const live = () => timers.filter((t) => t.live);+ const tick = async (advance = 0) => {+ now += advance;+ const t = live()[0];+ assert.ok(t, 'a poll is scheduled');+ t.live = false;+ t.fn();+ await flush();+ };+ return { ctrl, calls, live, tick, store, advance: (ms) => (now += ms) };+}+const flush = () => new Promise((r) => setTimeout(r, 0));++test('parses the contract; supported=false and junk mean not the Mac app', () => {+ const s = u.parseUpdateStatus(status({ progress: 1.7 }));+ assert.equal(s.current, '0.1.2');+ assert.equal(s.available.version, '0.1.3');+ assert.equal(s.progress, 1);+ assert.equal(u.parseUpdateStatus(status({ state: 'weird' })).state, 'idle');+ assert.equal(u.parseUpdateStatus({ ...status(), supported: false }), null);+ assert.equal(u.parseUpdateStatus(null), null);+ assert.equal(u.parseUpdateStatus('nope'), null);+ // 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');+});++test('banner for each state', () => {+ assert.equal(u.bannerView(model(status({ state: 'idle', available: null })), null), null);+ assert.equal(u.bannerView(model(status({ state: 'checking', available: null })), null), null);+ assert.deepEqual(u.bannerView(model(status()), null), { kind: 'available', version: '0.1.3', notes: NOTES, url: status().available.url });+ assert.deepEqual(u.bannerView(model(status({ state: 'downloading', progress: 0.43 })), null), { kind: 'downloading', version: '0.1.3', progress: 0.43 });+ assert.equal(u.bannerView(model(status({ state: 'ready' })), null).kind, 'restarting');+ const err = u.bannerView(model(status({ state: 'error', error: 'The signature check failed.' })), null);+ assert.equal(err.kind, 'error');+ assert.equal(err.error, 'The signature check failed.');+ assert.equal(err.url, status().available.url);+ // A failed check (nothing on offer) stays in Settings, not in the banner.+ assert.equal(u.bannerView(model(status({ state: 'error', available: null, error: 'offline' })), null), null);+ 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');+});++test('dismiss hides that version only, and storage that throws is fine', () => {+ const store = memStore();+ u.dismissVersion('0.1.3', store);+ assert.equal(u.dismissedVersion(store), '0.1.3');+ assert.equal(u.bannerView(model(status()), u.dismissedVersion(store)), null);+ const next = status({ available: { ...status().available, version: '0.1.4' } });+ assert.equal(u.bannerView(model(next), u.dismissedVersion(store)).version, '0.1.4');+ // A dismissed version that then fails to install still shows the error.+ assert.equal(u.bannerView(model(status({ state: 'error', error: 'x' })), '0.1.3').kind, 'error');+ const blocked = { getItem: () => { throw new Error('denied'); }, setItem: () => { throw new Error('denied'); }, removeItem: () => { throw new Error('denied'); } };+ assert.equal(u.dismissedVersion(blocked), null);+ assert.doesNotThrow(() => u.dismissVersion('0.1.3', blocked));+});++test('unsupported (404 or supported=false) renders nothing 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();+ await flush();+ assert.equal(h.ctrl.get().unsupported, true);+ assert.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() {} }), '');+ await h.ctrl.check();+ await h.ctrl.install();+ assert.deepEqual(h.calls, ['GET /api/app/update'], 'check/install do nothing off the Mac app');+ }+});++test('polls on load and every 30 minutes; 1 s while something moves', async () => {+ const h = harness(() => json(status({ state: 'idle', available: null })));+ h.ctrl.start();+ h.ctrl.start();+ await flush();+ assert.deepEqual(h.calls, ['GET /api/app/update'], 'start twice = one poller');+ assert.equal(h.live().length, 1);+ assert.equal(h.live()[0].ms, 30 * 60 * 1000);+ assert.equal(u.nextPollMs(model(status({ state: 'downloading' }))), 1000);+ assert.equal(u.nextPollMs(model(status({ state: 'checking' }))), 1000);+ assert.equal(u.nextPollMs(model(status(), { phase: 'restarting' })), 1000);+ h.ctrl.stop();+ assert.equal(h.live().length, 0);+});++test('install: downloading → restarting while the server is gone → updated when it is back', async () => {+ let phase = 'available';+ const store = memStore();+ const h = harness((url, init) => {+ if (init.method === 'POST') {+ phase = 'downloading';+ return json(status({ state: 'downloading', progress: 0 }), 202);+ }+ if (phase === 'downloading') {+ phase = 'ready';+ return json(status({ state: 'downloading', progress: 0.5 }));+ }+ if (phase === 'ready') {+ phase = 'gone';+ return json(status({ state: 'ready', progress: 1 }));+ }+ if (phase === 'gone') {+ phase = 'back';+ return new TypeError('Failed to fetch');+ }+ return json(phase === 'back' ? status({ current: '0.1.3', state: 'idle', available: null }) : status());+ }, store);+ h.ctrl.start();+ await flush();+ assert.equal(u.bannerView(h.ctrl.get(), null).kind, 'available');+ await h.ctrl.install();+ assert.ok(h.calls.includes('POST /api/app/update/install'));+ assert.equal(store.m.get(u.UPDATE_PENDING_KEY), '0.1.3');+ assert.equal(u.bannerView(h.ctrl.get(), null).kind, 'downloading');+ assert.equal(h.live().length, 1);+ assert.equal(h.live()[0].ms, 1000);+ await h.tick();+ assert.deepEqual(u.bannerView(h.ctrl.get(), null), { kind: 'downloading', version: '0.1.3', progress: 0.5 });+ await h.tick();+ assert.equal(u.bannerView(h.ctrl.get(), null).kind, 'restarting');+ await h.tick();+ assert.equal(h.ctrl.get().phase, 'restarting');+ assert.equal(u.bannerView(h.ctrl.get(), null).kind, 'restarting');+ await 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.');+ h.ctrl.clearUpdated();+ assert.equal(u.bannerView(h.ctrl.get(), null), null);+});++test('a fresh window after the relaunch says "Updated to"; a stale pending install is forgotten', async () => {+ const fresh = harness(() => json(status({ current: '0.1.3', state: 'idle', available: null })), memStore({ [u.UPDATE_PENDING_KEY]: '0.1.3' }));+ fresh.ctrl.start();+ await flush();+ assert.equal(u.bannerView(fresh.ctrl.get(), null).kind, 'updated');+ const stale = harness(() => json(status()), memStore({ [u.UPDATE_PENDING_KEY]: '0.1.3' }));+ stale.ctrl.start();+ await flush();+ assert.equal(stale.store.m.has(u.UPDATE_PENDING_KEY), false);+ assert.equal(u.bannerView(stale.ctrl.get(), null).kind, 'available');+});++test('a failed download shows the error with Try again and Download manually; the app keeps working', async () => {+ let n = 0;+ const h = harness((url, init) => {+ if (init.method === 'POST') return json(status({ state: 'downloading', progress: 0 }), 202);+ n += 1;+ return json(n === 1 ? status() : status({ state: 'error', error: 'The signature check failed.' }));+ });+ h.ctrl.start();+ await flush();+ await h.ctrl.install();+ await h.tick();+ const v = u.bannerView(h.ctrl.get(), null);+ assert.equal(v.kind, 'error');+ assert.equal(h.ctrl.get().phase, 'idle');+ assert.equal(h.store.m.has(u.UPDATE_PENDING_KEY), false);+ const html = ui.banner({ view: v, onUpdate() {}, onDismiss() {} });+ assert.match(html, /kwant bots 0\.1\.3 didn’t install\./);+ assert.match(html, /The signature check failed\./);+ assert.match(html, /This version keeps working/);+ assert.match(html, /Try again/);+ assert.match(html, /href="https:\/\/github\.com\/alexsergivan\/kwant\/releases\/tag\/mac-v0\.1\.3"[^>]*>.*Download manually/);+});++test('a refused install (409, 403) shows in the banner; a refused check stays in Settings', async () => {+ const h = harness((url, init) => {+ if (url.endsWith('/install')) return json({ error: 'An update is already downloading.' }, 409);+ if (url.endsWith('/check')) return json({ error: 'busy' }, 403);+ return json(status());+ });+ h.ctrl.start();+ await flush();+ await h.ctrl.check();+ assert.equal(h.ctrl.get().actionError, 'Only you can update the app, from the Mac it runs on.');+ assert.equal(u.bannerView(h.ctrl.get(), null).kind, 'available');+ await h.ctrl.install();+ const v = u.bannerView(h.ctrl.get(), null);+ assert.equal(v.kind, 'error');+ assert.equal(v.error, 'An update is already downloading.');+ assert.equal(h.store.m.has(u.UPDATE_PENDING_KEY), false);+});++test('Check for updates polls fast while checking, then shows the result', async () => {+ let checking = false;+ const h = harness((url, init) => {+ if (init.method === 'POST') {+ checking = true;+ return json(status({ state: 'checking', available: null }), 202);+ }+ if (checking) {+ checking = false;+ return json(status({ state: 'checking', available: null }));+ }+ return json(status({ state: 'idle', available: null }));+ });+ h.ctrl.start();+ await flush();+ assert.equal(u.aboutLine(h.ctrl.get()), 'You’re up to date.');+ await h.ctrl.check();+ assert.equal(u.aboutLine(h.ctrl.get()), 'Checking for updates…');+ 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.equal(h.live()[0].ms, 30 * 60 * 1000);+});++test('the relaunch gives up after 3 minutes and says so', async () => {+ let gone = false;+ const h = harness((url, init) => {+ if (init.method === 'POST') {+ gone = true;+ return json(status({ state: 'ready' }), 202);+ }+ return gone ? new TypeError('Failed to fetch') : json(status());+ });+ h.ctrl.start();+ await flush();+ await h.ctrl.install();+ await h.tick();+ assert.equal(h.ctrl.get().phase, 'restarting');+ await h.tick(4 * 60 * 1000);+ const v = u.bannerView(h.ctrl.get(), null);+ assert.equal(v.kind, 'error');+ assert.match(v.error, /didn’t come back/);+});++test('banner markup: buttons, notes, progress and dismiss', () => {+ const avail = ui.banner({ view: u.bannerView(model(status()), null), onUpdate() {}, onDismiss() {} });+ assert.match(avail, /kwant bots 0\.1\.3 is ready\./);+ assert.match(avail, /Update and restart/);+ assert.match(avail, /aria-expanded="false"[^>]*>What’s new/);+ assert.match(avail, /hidden=""[^>]*>.*In-app updates/s, 'notes are collapsed until What’s new');+ assert.match(avail, /aria-label="Hide until the next version"/);+ const noNotes = ui.banner({ view: { ...u.bannerView(model(status()), null), notes: '' }, onUpdate() {}, onDismiss() {} });+ assert.doesNotMatch(noNotes, /What’s new/);+ const dl = ui.banner({ view: { kind: 'downloading', version: '0.1.3', progress: 0.43 }, onUpdate() {}, onDismiss() {} });+ assert.match(dl, /Downloading kwant bots 0\.1\.3… 43%/);+ assert.match(dl, /role="progressbar"[^>]*aria-valuenow="43"/);+ assert.doesNotMatch(dl, /Update and restart|aria-label="Hide/);+ assert.match(ui.banner({ view: { kind: 'restarting', version: '0.1.3' }, onUpdate() {}, onDismiss() {} }), /Restarting the app to finish the update…/);+ 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('wired once: the banner in the shell, the About row in App settings, hidden on phones', () => {+ assert.match(src('Shell.tsx'), /<AppUpdateBanner \/>/);+ assert.match(src('components/SettingsModal.tsx'), /<AppUpdateAbout \/>/);+ assert.match(src('components/AppUpdateBanner.tsx'), /if \(!view \|\| phone\) return null;/);+});