Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Update card: recover from "Update checks are turned off" (Check again + latest release link) (#597)

Oleksandr Ivanchenko702cb415dff3
diff --git a/frontend/src/appUpdate.ts b/frontend/src/appUpdate.ts
index 50158a59..f0bc0bea 100644
--- a/frontend/src/appUpdate.ts
+++ b/frontend/src/appUpdate.ts
@@ -1,8 +1,10 @@
// 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.
+// GET /api/app/update and drives the Mac banner and the kwant card in App settings. An off answer
+// (404 or supported=false) is never final: the Mac app registers its updater a few seconds after the
+// window first asks, so off asks again after 10 s, 60 s, then every 30 minutes, and a later supported
+// answer turns everything back on.
export type UpdateState = 'idle' | 'checking' | 'available' | 'downloading' | 'ready' | 'error';
@@ -46,9 +48,12 @@ export type BannerView =
export type UpdatePhase = 'idle' | 'installing' | 'restarting' | 'updated' | 'stalled';
export interface UpdateModel {
- /** null until the first answer, and forever when unsupported. */
+ /** null until the first supported answer. */
status: UpdateStatus | null;
+ /** The last answer was off (404 or supported=false). Asked again later; a supported answer clears it. */
unsupported: boolean;
+ /** Check again pressed while off: the ask is out. */
+ rechecking?: boolean;
/** The running version, also when updates are unsupported (null when the server never said). */
current: string | null;
phase: UpdatePhase;
@@ -65,6 +70,10 @@ export const UPDATE_DISMISSED_KEY = 'kwnt_update_dismissed';
export const UPDATE_PENDING_KEY = 'kwnt_update_pending';
export const IDLE_POLL_MS = 30 * 60 * 1000;
+/** After an off answer: ask again after 10 s, then 60 s, then every IDLE_POLL_MS. */
+export const OFF_RETRY_MS = [10_000, 60_000];
+/** Where "Get the latest version" goes when this app can't check by itself. */
+export const LATEST_RELEASE_URL = 'https://github.com/alexsergivan/kwant/releases/latest';
/** 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;
@@ -184,13 +193,20 @@ export function nextPollMs(m: UpdateModel): number {
return s === 'checking' || s === 'downloading' || s === 'ready' ? FAST_POLL_MS : IDLE_POLL_MS;
}
+/** The wait before asking again after `offAnswers` off answers in a row (1 = the first). */
+export function offRetryMs(offAnswers: number, phase: UpdatePhase = 'idle'): number {
+ // A relaunch after an install: the new app's updater registers seconds later, keep asking fast
+ if (phase === 'installing' || phase === 'restarting') return FAST_POLL_MS;
+ return OFF_RETRY_MS[offAnswers - 1] ?? IDLE_POLL_MS;
+}
+
/** 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: 'off'; rechecking: boolean }
| { kind: 'checking' }
| { kind: 'latest'; checkedAt: number | null }
| { kind: 'available'; version: string; notes: string; date: string | null; url: string; canInstall: boolean }
@@ -202,7 +218,7 @@ export type VersionLine =
/** Never says "latest" without a check that said so. */
export function versionLine(m: UpdateModel): VersionLine {
- if (m.unsupported) return { kind: 'off' };
+ if (m.unsupported) return { kind: 'off', rechecking: !!m.rechecking };
const s = m.status;
if (!s) return { kind: 'loading' };
if (m.phase === 'updated' && m.target) return { kind: 'updated', version: m.target };
@@ -276,7 +292,7 @@ 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). */
+ /** Checks quietly when the last answer is older than STALE_CHECK_MS (the kwant card opening); asks again when off. */
checkIfStale: () => Promise<void>;
install: () => Promise<void>;
/** Hide the "Updated to …" note. */
@@ -289,24 +305,33 @@ export function createUpdateController(env: ControllerEnv): UpdateController {
let timer: unknown = null;
let running = false;
let restartSince: number | null = null;
+ /** Off answers to scheduled polls in a row: picks the next wait (OFF_RETRY_MS). Asks the person triggers don't count. */
+ let offAnswers = 0;
const set = (patch: Partial<UpdateModel>) => {
model = { ...model, ...patch };
listeners.forEach((fn) => fn());
};
- const schedule = (ms = nextPollMs(model)) => {
+ const schedule = (ms = model.unsupported ? offRetryMs(offAnswers, model.phase) : nextPollMs(model)) => {
if (timer !== null) env.clearTimeout(timer);
timer = null;
- if (!running || model.unsupported) return;
+ if (!running) return;
timer = env.setTimeout(() => {
timer = null;
void load();
}, ms);
};
+ const off = (current: string | null, asked: boolean) => {
+ // A person's ask (Settings opened, Check again) doesn't push the next retry later; only the first off answer counts
+ if (!asked || offAnswers === 0) offAnswers++;
+ set({ unsupported: true, current: current ?? model.current });
+ };
+
const apply = (status: UpdateStatus) => {
- const patch: Partial<UpdateModel> = { status, current: status.current || model.current, checkedAt: status.state === 'checking' ? model.checkedAt : env.now() };
+ offAnswers = 0;
+ const patch: Partial<UpdateModel> = { status, unsupported: false, 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.
@@ -328,7 +353,9 @@ export function createUpdateController(env: ControllerEnv): UpdateController {
set(patch);
};
- async function load() {
+ /** asked: the person triggered this ask. While still off it keeps the pending retry instead of a later one. */
+ async function load(asked = false) {
+ const next = (ms?: number) => (asked && model.unsupported && timer !== null ? undefined : schedule(ms));
let res: Response;
try {
res = await env.fetch('/api/app/update', { headers: { Accept: 'application/json' } });
@@ -340,29 +367,28 @@ export function createUpdateController(env: ControllerEnv): UpdateController {
}
if (model.phase === 'restarting' && restartSince !== null && env.now() - restartSince > RESTART_GIVE_UP_MS) {
set({ phase: 'stalled' });
- return schedule(IDLE_POLL_MS);
+ return next(IDLE_POLL_MS);
}
- return schedule();
+ return next();
}
if (res.status === 404) {
- set({ unsupported: true });
- return schedule();
+ off(null, asked);
+ return next();
}
- if (!res.ok) return schedule(model.phase === 'restarting' ? FAST_POLL_MS : IDLE_POLL_MS);
+ if (!res.ok) return next(model.phase === 'restarting' ? FAST_POLL_MS : IDLE_POLL_MS);
let body: unknown = null;
try {
body = await res.json();
} catch {
- return schedule();
+ return next();
}
const status = parseUpdateStatus(body);
if (!status) {
- const current = body && typeof body === 'object' ? str((body as Record<string, unknown>).current) : null;
- set({ unsupported: true, current: current ?? model.current });
- return schedule();
+ off(body && typeof body === 'object' ? str((body as Record<string, unknown>).current) : null, asked);
+ return next();
}
apply(status);
- schedule();
+ next();
}
async function post(path: string, fallback: string, quiet = false): Promise<boolean> {
@@ -399,14 +425,25 @@ export function createUpdateController(env: ControllerEnv): UpdateController {
timer = null;
},
async check() {
- if (model.unsupported) return;
+ if (model.unsupported) {
+ // Off here (so far): ask again now; a supported answer brings the card back
+ set({ rechecking: true });
+ try {
+ await load(true);
+ } finally {
+ set({ rechecking: false });
+ }
+ 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 checkIfStale() {
+ // Off is never final: opening Settings asks again
+ if (model.unsupported) return load(true);
const s = model.status;
- if (model.unsupported || !s || model.phase !== 'idle') return;
+ if (!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);
diff --git a/frontend/src/components/VersionCard.tsx b/frontend/src/components/VersionCard.tsx
index 268600d0..d0978d08 100644
--- a/frontend/src/components/VersionCard.tsx
+++ b/frontend/src/components/VersionCard.tsx
@@ -2,7 +2,7 @@
// 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 { type HowToUpdate, LATEST_RELEASE_URL, 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';
@@ -223,7 +223,25 @@ export const VersionCardView: React.FC<VersionCardProps> = ({ model, now, onChec
</span>
);
case 'off':
- return <span className="text-zinc-400">Update checks are turned off here.</span>;
+ // Not a dead end: ask again, or get the release by hand
+ return (
+ <>
+ <span className="text-zinc-400">Update checks are turned off here.</span>
+ <button
+ type="button"
+ onClick={() => !line.rechecking && onCheck()}
+ aria-disabled={line.rechecking || undefined}
+ className={`${quiet} aria-disabled:cursor-default aria-disabled:opacity-70`}
+ data-version-recheck
+ >
+ {line.rechecking ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : null}
+ {line.rechecking ? 'Checking…' : 'Check again'}
+ </button>
+ <a href={LATEST_RELEASE_URL} target="_blank" rel="noreferrer" className={`${quiet} max-md:-ml-1.5 max-md:basis-full max-md:w-fit`} data-version-latest>
+ Get the latest version <ExternalLink size={12} aria-hidden="true" />
+ </a>
+ </>
+ );
}
})();
@@ -249,9 +267,12 @@ export const VersionCardView: React.FC<VersionCardProps> = ({ model, now, onChec
<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>
+ {/* Off already links the latest release; one GitHub link is enough */}
+ {line.kind !== 'off' && (
+ <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>
);
};
@@ -270,9 +291,9 @@ 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
+ // Opening Settings checks again when the last answer is over an hour old, and always when it was off
useEffect(() => {
- if (known) void ctrl.checkIfStale();
+ if (known || ctrl.get().unsupported) void ctrl.checkIfStale();
}, [known, ctrl]);
return (
<VersionCardView
diff --git a/frontend/tests/appUpdate.test.mjs b/frontend/tests/appUpdate.test.mjs
index 907a7a33..c9554004 100644
--- a/frontend/tests/appUpdate.test.mjs
+++ b/frontend/tests/appUpdate.test.mjs
@@ -141,26 +141,137 @@ 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) shows the version alone and never polls again', async () => {
+test('off (404 or supported=false) shows the version, Check again and the latest release, and is never final', 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(u.versionLine(h.ctrl.get()).kind, 'off');
const html = ui.card({ model: h.ctrl.get() });
+ assert.match(html, /data-version-card="off"/);
assert.match(html, /Update checks are turned off here\./);
- assert.doesNotMatch(html, /latest version/);
+ assert.match(html, /data-version-recheck[^>]*>Check again<\/button>/);
+ assert.match(html, /href="https:\/\/github\.com\/alexsergivan\/kwant\/releases\/latest"[^>]*>Get the latest version/);
+ assert.doesNotMatch(html, /latest version<\/span>|Update<\/button>/);
+ assert.doesNotMatch(html, /All releases on GitHub/, 'off has one GitHub link, not two');
if (answer.status === 200) assert.match(html, /kwant bots <span[^>]*>0\.1\.2<\/span>/, 'the version from the answer');
- await h.ctrl.check();
+ // Asked again after 10 s, 60 s, then every 30 minutes
+ assert.deepEqual(h.live().map((t) => t.ms), [10_000]);
+ await h.tick(10_000);
+ assert.deepEqual(h.live().map((t) => t.ms), [60_000]);
+ await h.tick(60_000);
+ assert.deepEqual(h.live().map((t) => t.ms), [30 * 60 * 1000]);
+ await h.tick();
+ assert.deepEqual(h.live().map((t) => t.ms), [30 * 60 * 1000]);
+ assert.equal(h.calls.length, 4);
await h.ctrl.install();
- assert.deepEqual(h.calls, ['GET /api/app/update'], 'check/install do nothing off the Mac app');
+ assert.ok(!h.calls.some((c) => c.startsWith('POST')), 'no install or check POST while off');
+ }
+});
+
+test('off, then supported: the card and the banner come back (the Mac updater registers late)', async () => {
+ for (const off of [json({ error: 'not found' }, 404), json({ supported: false, current: '0.1.2' })]) {
+ let n = 0;
+ const h = harness(() => (++n === 1 ? off : json(status())));
+ h.ctrl.start();
+ await flush();
+ assert.equal(u.versionLine(h.ctrl.get()).kind, 'off');
+ await h.tick(10_000);
+ const m = h.ctrl.get();
+ assert.equal(m.unsupported, false);
+ assert.equal(u.versionLine(m).kind, 'available');
+ assert.equal(u.bannerView(m, null)?.kind, 'available');
+ assert.match(ui.card({ model: m }), /kwant bots 0\.1\.3 is available/);
+ assert.deepEqual(h.live().map((t) => t.ms), [30 * 60 * 1000], 'back on the normal poll');
+ // Off again later starts the short retries over
+ n = 0;
+ await h.tick();
+ assert.equal(h.ctrl.get().unsupported, true);
+ assert.deepEqual(h.live().map((t) => t.ms), [10_000]);
}
});
+test('Check again while off asks now (a GET, no POST) and says Checking… meanwhile', async () => {
+ let answer = json({ supported: false });
+ let release;
+ const h = harness(() => answer);
+ h.ctrl.start();
+ await flush();
+ const gate = new Promise((r) => (release = r));
+ answer = gate.then(() => json(status({ state: 'idle', available: null })));
+ const pressed = h.ctrl.check();
+ assert.equal(h.ctrl.get().rechecking, true);
+ assert.deepEqual(u.versionLine(h.ctrl.get()), { kind: 'off', rechecking: true });
+ const busy = ui.card({ model: h.ctrl.get() });
+ assert.match(busy, /aria-disabled="true"[^>]*data-version-recheck[^>]*>.*Checking…<\/button>/s);
+ release();
+ await pressed;
+ assert.equal(h.ctrl.get().rechecking, false);
+ assert.deepEqual(h.calls, ['GET /api/app/update', 'GET /api/app/update']);
+ assert.equal(u.versionLine(h.ctrl.get()).kind, 'latest');
+ assert.equal(h.live().length, 1, 'one poll scheduled, not two');
+});
+
+test('opening Settings asks again when the last answer was off', async () => {
+ let n = 0;
+ const h = harness(() => (++n === 1 ? json({ supported: false }) : json(status())));
+ h.ctrl.start();
+ await flush();
+ await h.ctrl.checkIfStale();
+ assert.deepEqual(h.calls, ['GET /api/app/update', 'GET /api/app/update']);
+ assert.equal(u.versionLine(h.ctrl.get()).kind, 'available');
+ assert.match(src('components/VersionCard.tsx'), /if \(known \|\| ctrl\.get\(\)\.unsupported\) void ctrl\.checkIfStale\(\);/);
+});
+
+test('opening Settings 3 s after an off answer keeps the 10 s retry (N1)', async () => {
+ let answer = json({ supported: false, current: '0.1.2' });
+ const h = harness(() => answer);
+ h.ctrl.start();
+ await flush();
+ const [retry] = h.live();
+ assert.equal(retry.ms, 10_000);
+ h.advance(3_000);
+ await h.ctrl.checkIfStale(); // Settings opened: asks now, still off
+ assert.equal(h.calls.length, 2);
+ assert.equal(h.ctrl.get().unsupported, true);
+ assert.deepEqual(h.live(), [retry], 'the pending 10 s retry is kept, not replaced by a later one');
+ // The Mac updater is up by now: the retry at 10 s brings the card back
+ answer = json(status());
+ await h.tick(7_000);
+ assert.equal(h.ctrl.get().unsupported, false);
+ assert.equal(u.versionLine(h.ctrl.get()).kind, 'available');
+});
+
+test('Check again three times while off leaves the next automatic retry where it was (N1)', async () => {
+ const h = harness(() => json({ supported: false }));
+ h.ctrl.start();
+ await flush();
+ await h.tick(10_000); // the scheduled retry, still off: next one in 60 s
+ const [retry] = h.live();
+ assert.equal(retry.ms, 60_000);
+ for (let i = 0; i < 3; i++) {
+ h.advance(1_000);
+ await h.ctrl.check();
+ }
+ assert.equal(h.calls.length, 5);
+ assert.ok(!h.calls.some((c) => c.startsWith('POST')));
+ assert.deepEqual(h.live(), [retry], 'still the 60 s retry, not pushed to 30 min');
+ // Only scheduled polls advance the waits: the 60 s retry, still off, goes to 30 min
+ await h.tick(57_000);
+ assert.deepEqual(h.live().map((t) => t.ms), [30 * 60 * 1000]);
+});
+
+test('an off answer while the app relaunches after an install keeps asking every second', () => {
+ assert.equal(u.offRetryMs(1, 'restarting'), 1000);
+ assert.equal(u.offRetryMs(5, 'installing'), 1000);
+ assert.equal(u.offRetryMs(1), 10_000);
+ assert.equal(u.offRetryMs(2), 60_000);
+ assert.equal(u.offRetryMs(3), 30 * 60 * 1000);
+});
+
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();