diff --git a/web/src/App.tsx b/web/src/App.tsx index 9298a90..2a2f77d 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -1897,32 +1897,141 @@ function StreamSettingsDialog({ ); } +const SW_UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000; +const VERSION_CHECK_INTERVAL_MS = 30 * 60 * 1000; +/** Floor between two version.json fetches, so tab-switching doesn't poll. */ +const VERSION_CHECK_MIN_GAP_MS = 5 * 60 * 1000; +const UPDATE_TOAST_SNOOZE_MS = 30 * 60 * 1000; + +/** What the server actually has right now. Deliberately routed around the + * service worker: version.json is not in Workbox's globPatterns, so it is + * never precached, and the cache-busting query plus `no-store` keeps any + * intermediate cache out of the answer too. */ +async function fetchServerBuildId(): Promise { + try { + const res = await fetch(`${import.meta.env.BASE_URL}version.json?t=${Date.now()}`, { + cache: "no-store", + }); + if (!res.ok) return null; + const data: unknown = await res.json(); + const id = (data as { buildId?: unknown }).buildId; + return typeof id === "string" ? id : null; + } catch { + return null; + } +} + +/** Throw away the worker and everything it cached, then reload from the + * network. Only for a client that is provably stale but isn't being handed + * an update — see `stranded` below. */ +async function resetServiceWorkerAndReload() { + try { + const registrations = await navigator.serviceWorker.getRegistrations(); + await Promise.all(registrations.map((registration) => registration.unregister())); + const cacheKeys = await caches.keys(); + await Promise.all(cacheKeys.map((key) => caches.delete(key))); + } catch { + // Reloading without the cleanup is still better than staying stale. + } + window.location.reload(); +} + function UpdatePrompt() { const t = useT(); - const { - needRefresh: [needRefresh, setNeedRefresh], - updateServiceWorker, - } = useRegisterSW({ + const [visible, setVisible] = useState(false); + /** An update is waiting to be applied, whether or not the toast is showing. */ + const pending = useRef(false); + /** Set when the server is on a different build than we are *and* no new + * service worker turned up to deliver it. Then the worker is wedged and a + * plain reload would just serve the same cached shell again, so the button + * has to clear it out instead. */ + const stranded = useRef(false); + const snoozeTimer = useRef(null); + const lastVersionCheck = useRef(0); + + const announce = (isStranded: boolean) => { + if (isStranded) stranded.current = true; + pending.current = true; + // While snoozed the timer owns the toast; don't pop it back up early. + if (snoozeTimer.current === null) setVisible(true); + }; + + const snooze = () => { + setVisible(false); + // Never a permanent dismissal: a client that misses the prompt for good is + // exactly how clients ended up stranded on a bundle the server no longer + // even serves. + snoozeTimer.current = window.setTimeout(() => { + snoozeTimer.current = null; + if (pending.current) setVisible(true); + }, UPDATE_TOAST_SNOOZE_MS); + }; + + useRegisterSW({ + onNeedReload() { + // autoUpdate: the new worker has already taken over, we only choose the + // moment to reload — mid-call is the user's decision, not ours. + announce(false); + }, onRegisteredSW(_url, registration) { // Poll for a new service worker in the background — otherwise an app // left open for hours/days only checks for updates on next full load. if (!registration) return; - const CHECK_INTERVAL_MS = 60 * 60 * 1000; window.setInterval(() => { registration.update().catch(() => {}); - }, CHECK_INTERVAL_MS); + }, SW_UPDATE_CHECK_INTERVAL_MS); }, }); - if (!needRefresh) return null; + useEffect(() => { + const checkVersion = async () => { + const now = Date.now(); + if (now - lastVersionCheck.current < VERSION_CHECK_MIN_GAP_MS) return; + lastVersionCheck.current = now; + + const serverBuildId = await fetchServerBuildId(); + if (!serverBuildId || serverBuildId === __BUILD_ID__) return; + + // We are demonstrably behind. Give the service worker the first shot at + // fixing it; only if it produces no new worker at all is it wedged. + let registration: ServiceWorkerRegistration | undefined; + try { + registration = await navigator.serviceWorker?.getRegistration(); + await registration?.update(); + } catch { + // An update check that throws is itself a sign of a wedged worker. + } + announce(!registration?.installing && !registration?.waiting); + }; + + void checkVersion(); + const interval = window.setInterval(() => void checkVersion(), VERSION_CHECK_INTERVAL_MS); + const onVisibilityChange = () => { + if (document.visibilityState === "visible") void checkVersion(); + }; + document.addEventListener("visibilitychange", onVisibilityChange); + return () => { + window.clearInterval(interval); + document.removeEventListener("visibilitychange", onVisibilityChange); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + if (!visible) return null; return (
{t("pwa.updateAvailable")} - -
diff --git a/web/src/vite-env.d.ts b/web/src/vite-env.d.ts index 36411c5..8facaa0 100644 --- a/web/src/vite-env.d.ts +++ b/web/src/vite-env.d.ts @@ -1,3 +1,6 @@ /// /// /// + +/** Injected by vite.config.ts; matches the `buildId` in version.json. */ +declare const __BUILD_ID__: string diff --git a/web/vite.config.ts b/web/vite.config.ts index aab13dd..23fd20a 100644 --- a/web/vite.config.ts +++ b/web/vite.config.ts @@ -1,19 +1,65 @@ -import { defineConfig } from 'vite' +import { execSync } from 'node:child_process' +import { defineConfig, type Plugin } from 'vite' import react from '@vitejs/plugin-react' import { VitePWA } from 'vite-plugin-pwa' +// Identifies the build a bundle came from. Only has to differ between two +// builds — the client compares its own baked-in value against version.json to +// notice when it is running something the server no longer serves. +function resolveBuildId(): string { + const fromCi = process.env.CF_PAGES_COMMIT_SHA || process.env.GITHUB_SHA + if (fromCi) return fromCi.slice(0, 12) + try { + return execSync('git rev-parse --short=12 HEAD', { stdio: ['ignore', 'pipe', 'ignore'] }) + .toString() + .trim() + } catch { + // No git checkout (the Docker build copies sources in without .git). + return String(Date.now()) + } +} + +const buildId = resolveBuildId() + +// version.json must never be precached, or a stuck client would ask the very +// cache it is stuck in what the server has. `.json` is not in globPatterns +// below, so Workbox leaves it alone and the fetch always hits the network. +function versionManifest(): Plugin { + return { + name: 'webspeak3-version-manifest', + apply: 'build', + generateBundle() { + this.emitFile({ + type: 'asset', + fileName: 'version.json', + source: `${JSON.stringify({ buildId })}\n`, + }) + }, + } +} + // https://vite.dev/config/ export default defineConfig({ + define: { + __BUILD_ID__: JSON.stringify(buildId), + }, plugins: [ react(), + versionManifest(), VitePWA({ - registerType: 'prompt', - // We register the service worker ourselves (see useSwUpdatePrompt in - // App.tsx) via the virtual:pwa-register/react module so we can show a - // "new version available" toast instead of updating silently — a - // stale-cache tab would otherwise keep running old JS/CSS until the - // user manually reloads (or worse, clears storage), which bit us - // repeatedly while verifying deploys. + // The generated worker takes over as soon as it has installed + // (skipWaiting + clientsClaim). It must NOT wait for the page to ask it + // to: between 2026-09-07 and 2026-09-10 this was `prompt`, and every + // client cached in that window froze — the new worker sat in `waiting` + // forever because the only code that could have released it (the update + // toast) lived in the version behind that worker. Deciding *when* to + // reload is a UI concern and stays one: `onNeedReload` in App.tsx shows + // the toast instead of pulling the page out from under an active + // connection. + registerType: 'autoUpdate', + // We register from inside the app (virtual:pwa-register/react) rather + // than through an injected registerSW.js, because that script would + // reload the page on its own the moment a new worker activates. injectRegister: false, // Dev-time Workbox would sit in front of Vite's own HMR/WS traffic and // stale-cache the app shell while iterating — only ever ship the SW in @@ -35,6 +81,14 @@ export default defineConfig({ ], }, workbox: { + // Both are what `registerType: 'autoUpdate'` is supposed to imply, but + // the plugin only sets them when it also injects registerSW.js (see + // resolveOptions: `injectRegister === 'auto' || injectRegister == null`) + // — with injectRegister: false they have to be spelled out, or the + // generated worker is byte-identical to the `prompt` one and strands + // clients all over again. Verified in dist/sw.js after building. + skipWaiting: true, + clientsClaim: true, // Precache the built app shell (JS/CSS/HTML/icons) only. The gateway's // /ws endpoint and any file-transfer/API traffic must never be // intercepted or cached — Workbox's default fetch handler already