diff --git a/docs/PWA.md b/docs/PWA.md index afe58e07..e6b4a116 100644 --- a/docs/PWA.md +++ b/docs/PWA.md @@ -14,6 +14,11 @@ This is an **online-first app shell**, not an offline radio player. - The worker pre-caches **only** `offline.html`, a small static, noindex, self-contained explanation. Navigation requests go to the network first. On a network failure, the worker displays the translated offline explanation. + The fallback page listens for browser connectivity changes and also probes the + same-origin, deployment-scoped web manifest with a 5-second timeout and + backoff (3 to 15 seconds). It reloads the **original URL** only after a valid + network response, does not loop-refresh while offline, and pauses background + probes while hidden. The manual Retry button uses the same verification. - There is **no audio cache**: MP3/AAC, .m3u8 playlists, HLS segments, provider requests, API, JS, CSS, search index JSON and all real station HTML stay network-only. A stream always requires a current online connection. @@ -41,7 +46,12 @@ tabs; test on the actual device before marking #340 or #346 complete. - [ ] Install on Android Chrome and open the app from its launcher. - [ ] Add to Home Screen on Safari iOS, test lock-screen/audio interruptions. - [ ] With the app open, go offline then navigate: see the offline explanation; - retry after restoring connection should fetch a fresh live page. + restore connection and verify automatic recovery to the same page without + pressing Retry. Also verify Retry works and no repeated reloads occur + while disconnected, including when the browser omits an online event. +- [ ] Repeat the recovery test on a station deep link and on a + `/pr-preview/pr-N/` deployment: its connectivity probe must stay within + the active Pages scope. A browser reload must leave the player paused. - [ ] Use DevTools Application → Cache Storage: **only** `offline.html` is precached; no station catalog, stream segments or signed URLs. - [ ] Update the worker: no forced reload, old audio continues, next visits @@ -49,5 +59,6 @@ tabs; test on the actual device before marking #340 or #346 complete. - [ ] `npm test`, `npm run generate:site`, SEO/GA4 noindex and GitHub Pages subpath validations, mobile light/dark and safe-area smoke tests. -The automated tests verify worker/cache policy and manifest URL resolution. +The automated tests verify worker/cache policy, manifest URL resolution, and +offline-page automatic recovery, polling backoff and preview-scoped probes. Physical iOS/Android QA remains **not run** until independently documented. diff --git a/public/offline.html b/public/offline.html index fa3b43a2..2e2dd09d 100644 --- a/public/offline.html +++ b/public/offline.html @@ -18,7 +18,9 @@ button { appearance: none; border: 0; border-radius: 13px; background: #e11d48; color: white; font: inherit; font-weight: 650; padding: 13px 25px; min-height: 48px; cursor: pointer; } button:focus-visible { outline: 3px solid #fda4af; outline-offset: 4px; } button:hover { background: #be123c; } - .note { display: block; margin-top: 18px; color: #aaaab6; font-size: 12px; } + .connection-state { display: block; min-height: 20px; margin-top: 14px; color: #fda4af; font-size: 13px; } + .note { display: block; margin-top: 12px; color: #aaaab6; font-size: 12px; } + button:disabled { cursor: progress; opacity: .75; } @media (prefers-reduced-motion: no-preference) { button { transition: background .15s ease; } } @@ -31,18 +33,19 @@

You're offline

Live radio needs an internet connection. Reconnect to keep listening.

+ Waiting for a connection… Live stations cannot play offline. diff --git a/public/service-worker.js b/public/service-worker.js index 16d75eef..3ec7146e 100644 --- a/public/service-worker.js +++ b/public/service-worker.js @@ -4,7 +4,7 @@ */ const OFFLINE_SCOPE_KEY = encodeURIComponent(new URL(self.registration.scope).pathname); const OFFLINE_CACHE_PREFIX = 'onair-offline-shell-' + OFFLINE_SCOPE_KEY + '-v'; -const OFFLINE_CACHE_NAME = OFFLINE_CACHE_PREFIX + '1'; +const OFFLINE_CACHE_NAME = OFFLINE_CACHE_PREFIX + '2'; const OFFLINE_URL = new URL('offline.html', self.registration.scope).href; self.addEventListener('install', event => { diff --git a/tests/pwa-install-shell.test.mjs b/tests/pwa-install-shell.test.mjs index b0929742..4080b108 100644 --- a/tests/pwa-install-shell.test.mjs +++ b/tests/pwa-install-shell.test.mjs @@ -13,6 +13,7 @@ function workerHarness(source) { const cacheKeys = [ 'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v0', 'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v1', + 'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v2', 'onair-offline-shell-%2Fpr-preview%2Fpr-3%2F-v0', 'some-other-app', ]; @@ -22,7 +23,7 @@ function workerHarness(source) { add: async request => { saved.push(request.url || request); }, }; const caches = { - open: async name => { assert.equal(name, 'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v1'); return cache; }, + open: async name => { assert.equal(name, 'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v2'); return cache; }, keys: async () => cacheKeys, delete: async name => { deleted.push(name); return true; }, match: async url => url === 'https://radio.example/pr-preview/pr-2/offline.html' @@ -79,7 +80,10 @@ test('service worker caches only the noindex offline explanation, not stations o assert.deepEqual(worker.saved, ['https://radio.example/pr-preview/pr-2/offline.html']); assert.doesNotMatch(source, /self\.skipWaiting\(|self\.clients\.claim\(|cache\.put\(/); await worker.run('activate'); - assert.deepEqual(worker.deleted, ['onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v0']); + assert.deepEqual(worker.deleted, [ + 'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v0', + 'onair-offline-shell-%2Fpr-preview%2Fpr-2%2F-v1', + ]); for (const request of [ { mode: 'no-cors', method: 'GET', destination: 'audio', url: 'https://stream.example/live.mp3' }, @@ -124,4 +128,9 @@ test('offline HTML explicitly refuses offline radio, is noindex and is self-cont assert.doesNotMatch(html, /<(?:script|link)[^>]+(?:src|href)=["']https?:\/\//i); assert.match(html, /env\(safe-area-inset-bottom\)/); assert.match(html, /window\.location\.reload\(\)/); + assert.match(html, /getRegistration\?\.\(\)/); + assert.match(html, /brand\/site\.webmanifest/); + assert.match(html, /aria-live="polite"/); + assert.match(html, /cache: 'no-store'/); + assert.match(html, /document\.addEventListener\('visibilitychange'/); }); diff --git a/tests/pwa-reconnect.test.mjs b/tests/pwa-reconnect.test.mjs new file mode 100644 index 00000000..a1a61085 --- /dev/null +++ b/tests/pwa-reconnect.test.mjs @@ -0,0 +1,167 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { runInNewContext } from 'node:vm'; + +const read = path => readFile(new URL('../' + path, import.meta.url), 'utf8'); + +async function offlinePageHarness({ reachable = false, hidden = false, validManifest = true, serviceWorkerFails = false } = {}) { + const html = await read('public/offline.html'); + const openingTag = '', start); + assert.ok(start >= 0 && end > start, 'offline page must contain a self-contained reconnect script'); + const script = html.slice(start + openingTag.length, end); + + const state = { reachable, validManifest }; + const windowEvents = new Map(); + const documentEvents = new Map(); + const timers = new Map(); + const requests = []; + let reloadCount = 0; + let nextTimerId = 1; + + const elements = Object.fromEntries( + ['offline-title', 'offline-description', 'offline-note', 'retry', 'connection-state'] + .map(id => [id, { + textContent: '', disabled: false, listeners: new Map(), + addEventListener(name, listener) { this.listeners.set(name, listener); }, + }]), + ); + + const document = { + hidden, + documentElement: { lang: '' }, + getElementById: id => elements[id], + addEventListener: (name, listener) => documentEvents.set(name, listener), + }; + const window = { + location: { + origin: 'https://preview.radio.eplus.dev', + pathname: '/pr-preview/pr-24/asia/viet-nam/station', + reload: () => { reloadCount += 1; }, + }, + addEventListener: (name, listener) => windowEvents.set(name, listener), + }; + const navigator = { + language: 'vi-VN', + serviceWorker: { + getRegistration: async () => { + if (serviceWorkerFails) throw new Error('Service worker lookup blocked'); + return { scope: 'https://preview.radio.eplus.dev/pr-preview/pr-24/' }; + }, + }, + }; + + runInNewContext(script, { + window, document, navigator, URL, AbortController, + fetch: async (url, options) => { + requests.push({ url, options }); + if (!state.reachable) throw new TypeError('Network unavailable'); + return { + ok: true, + json: async () => state.validManifest + ? { name: 'ePlus OnAir — Listen Beyond Borders.', start_url: '../', scope: '../' } + : { unexpected: 'captive portal' }, + }; + }, + setTimeout: (callback, delay) => { + const id = nextTimerId++; + timers.set(id, { callback, delay }); + return id; + }, + clearTimeout: id => { timers.delete(id); }, + }); + + return { + elements, + requests, + timers, + get reloadCount() { return reloadCount; }, + setReachable: value => { state.reachable = value; }, + setValidManifest: value => { state.validManifest = value; }, + setHidden: value => { document.hidden = value; }, + emitWindow: event => windowEvents.get(event)?.(), + emitDocument: event => documentEvents.get(event)?.(), + clickRetry: () => elements.retry.listeners.get('click')(), + runRetryTimer: delay => { + const entry = [...timers.entries()].find(([, timer]) => timer.delay === delay); + assert.ok(entry, 'expected a ' + delay + 'ms retry timer'); + timers.delete(entry[0]); + entry[1].callback(); + }, + flush: () => new Promise(resolve => setImmediate(resolve)), + }; +} + +test('PWA offline shell verifies connectivity and automatically restores the original page', async () => { + const page = await offlinePageHarness(); + await page.flush(); + assert.equal(page.reloadCount, 0); + assert.equal(page.elements['connection-state'].textContent, 'Đang chờ kết nối mạng…'); + assert.deepEqual([...page.timers.values()].map(timer => timer.delay), [3_000]); + + page.setReachable(true); + page.emitWindow('online'); + await page.flush(); + + assert.equal(page.reloadCount, 1); + assert.equal(page.elements['connection-state'].textContent, 'Đã có mạng. Đang mở lại radio…'); + assert.equal(page.requests.at(-1).url, + 'https://preview.radio.eplus.dev/pr-preview/pr-24/brand/site.webmanifest'); + assert.equal(page.requests.at(-1).options.cache, 'no-store'); + assert.equal(page.requests.at(-1).options.redirect, 'error'); + assert.equal(page.timers.size, 0, 'successful recovery stops all further probes'); +}); + +test('PWA offline shell retries with bounded backoff without a reload loop', async () => { + const page = await offlinePageHarness(); + await page.flush(); + assert.equal(page.requests.length, 1); + for (const [before, next] of [[3_000, 6_000], [6_000, 12_000], [12_000, 15_000], [15_000, 15_000]]) { + page.runRetryTimer(before); + await page.flush(); + assert.deepEqual([...page.timers.values()].map(timer => timer.delay), [next]); + assert.equal(page.reloadCount, 0); + } + + page.setReachable(true); + page.runRetryTimer(15_000); // Some browsers do not reliably fire online. + await page.flush(); + assert.equal(page.reloadCount, 1); +}); + +test('manual Retry only reloads after an actual valid same-origin response', async () => { + const page = await offlinePageHarness(); + await page.flush(); + page.setReachable(true); + page.setValidManifest(false); + page.clickRetry(); + await page.flush(); + assert.equal(page.reloadCount, 0, 'a bogus or captive-portal response is not recovery'); + + page.setValidManifest(true); + page.clickRetry(); + await page.flush(); + assert.equal(page.reloadCount, 1); +}); + +test('PWA offline shell suspends probing when hidden and checks on foreground', async () => { + const page = await offlinePageHarness({ hidden: true, reachable: true }); + await page.flush(); + assert.equal(page.requests.length, 0); + assert.equal(page.timers.size, 0); + + page.setHidden(false); + page.emitDocument('visibilitychange'); + await page.flush(); + assert.equal(page.reloadCount, 1); +}); + +test('PWA offline shell survives denied service-worker lookup and retains preview scope', async () => { + const page = await offlinePageHarness({ reachable: true, serviceWorkerFails: true }); + await page.flush(); + assert.equal(page.reloadCount, 1); + assert.equal(page.requests[0].url, + 'https://preview.radio.eplus.dev/pr-preview/pr-24/brand/site.webmanifest'); +});