Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Installed web app: the plan's exercise media stays offline, across updates, and a still that will not load shows a plain tile (#281)

Duarte Santos2536bc4dc60d
diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.md
index 5e8e4f19f..72e12e177 100644
--- a/docs/SELF_HOSTING.md
+++ b/docs/SELF_HOSTING.md
@@ -417,6 +417,7 @@ browser (see section 2).
| The app says "Your server answered with an error (HTTP …)" | The code is what the server or its proxy sent: 502/504 usually means the API container is down or unreachable from `web`, 413 that the proxy's upload limit is too small. Changes stay on the device and go through once the server answers. |
| `docker compose pull` fails with "denied" / "unauthorized" | The prebuilt images aren't published yet, or need to be, or the GHCR package is still private — build from source instead (`docker compose up -d --build`). |
| Exercise images/GIFs blank when a routine is open | Fixed in current images (issue #79). On an older build, see the note below. |
+| An exercise shows a plain tile instead of its animation when offline | The installed web app keeps the media of every exercise in your plan and your current workout, fetched in the background once the app has settled (not on a cellular or Data Saver connection, where the browser says so), plus everything it has shown you, up to 150 MB, across updates. An exercise outside your plan that was never shown while online has nothing to show offline. The phone app loads media from a CDN and is not covered by this. |
### `VITE_IMG_BASE` / `VITE_GIF_BASE` are build-time, not run-time
diff --git a/frontend/public/sw.js b/frontend/public/sw.js
index 8e71c5952..59ce57c1c 100644
--- a/frontend/public/sw.js
+++ b/frontend/public/sw.js
@@ -1,10 +1,33 @@
/* openGym service worker — the app shell and its hashed assets are cached at install and kept
- fresh network-first, media (img/gif) cache-first. A home-screen app reopened without a network
- comes back from here with the same bundle it last ran; the state itself lives in localStorage.
- `CACHE` carries the build hash (vite.config.js rewrites it), so every deploy is a new worker
- with its own cache and the previous build's files are dropped on activate. */
+ fresh network-first, media (img/gif) cache-first in a cache of its own. A home-screen app
+ reopened without a network comes back from here with the same bundle it last ran; the state
+ itself lives in localStorage. `CACHE` carries the build hash (vite.config.js rewrites it), so
+ every deploy is a new worker with its own cache and the previous build's files are dropped on
+ activate; the media cache (`MEDIA`) is kept across builds. */
const CACHE = 'opengym-rt-__BUILD__'
+/* Exercise media (img/, gif/) lives in a cache of its own that outlives builds (#281). It used to
+ share the build's cache, so every update swept every animation along with the old bundle, and
+ an installed app opened offline after an update showed broken tiles for exercises it had shown
+ the day before. The media never changes under a given URL, so there is nothing to invalidate.
+
+ It is bounded instead: past MEDIA_MAX_BYTES (or MEDIA_MAX_ITEMS, for a server that sends no
+ Content-Length) the least recently used entries go first. The Cache API keeps entries in the
+ order they were written, so a hit is written back once per worker lifetime to move it to the
+ end: least recently used as far as this worker has seen, which is what "LRU-ish" means here.
+ The whole catalogue is about 140 MB, so the cap only bites for someone who has browsed most of
+ it. lib/media-prefetch.js fills this cache for the exercises in the plan and names it too, so
+ a new name has to change there as well (sw-media.test.js pins the two together). */
+const MEDIA = 'opengym-media-v1'
+const MEDIA_MAX_BYTES = 150 * 1024 * 1024
+const MEDIA_MAX_ITEMS = 3000
+// What an entry without a Content-Length is counted as: a little above the catalogue's average.
+const MEDIA_GUESS_BYTES = 64 * 1024
+// Trimming lists the whole cache, so it runs after every MEDIA_TRIM_EVERY new entries rather
+// than after each one, and once when a new worker activates.
+const MEDIA_TRIM_EVERY = 20
+const isMediaPath = p => p.includes('/img/') || p.includes('/gif/')
+
// What the shell needs to boot without a network: index.html plus every script/style/icon it
// references. Read from the served index.html so the list follows the build, not a hand-kept
// manifest that would go stale the first time a chunk is renamed.
@@ -54,13 +77,71 @@ self.addEventListener('activate', e => {
// next load with a network.
const c = await caches.open(CACHE)
if (await c.match('index.html')) {
- const keys = await caches.keys()
- await Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
+ const old = (await caches.keys()).filter(k => k !== CACHE && k !== MEDIA)
+ // A build from before MEDIA existed kept its media in its own cache: move it across first,
+ // so the first update to this worker does not cost what the device already had offline.
+ await Promise.all(old.map(k => adoptMedia(k).catch(() => {})))
+ await Promise.all(old.map(k => caches.delete(k)))
+ await trimMedia().catch(() => {})
}
await self.clients.claim()
})())
})
+async function adoptMedia(name) {
+ const from = await caches.open(name)
+ const media = (await from.keys()).filter(r => { try { return isMediaPath(new URL(r.url || r, location.href).pathname) } catch { return false } })
+ if (!media.length) return
+ const to = await caches.open(MEDIA)
+ for (const r of media) {
+ if (await to.match(r)) continue
+ const res = await from.match(r)
+ if (res) await to.put(r, res)
+ }
+}
+
+let mediaPuts = 0
+// Oldest first, which after the write-backs below is least recently used first.
+async function trimMedia() {
+ if (!(await caches.keys()).includes(MEDIA)) return
+ const c = await caches.open(MEDIA)
+ const keys = await c.keys()
+ const sizes = await Promise.all(keys.map(k => c.match(k).then(r => Number(r && r.headers && r.headers.get('content-length')) || MEDIA_GUESS_BYTES, () => MEDIA_GUESS_BYTES)))
+ let bytes = sizes.reduce((a, b) => a + b, 0)
+ let items = keys.length
+ for (let i = 0; i < keys.length && (bytes > MEDIA_MAX_BYTES || items > MEDIA_MAX_ITEMS); i++) {
+ await c.delete(keys[i])
+ bytes -= sizes[i]; items--
+ }
+}
+
+// URLs written back this worker lifetime; see MEDIA above.
+const touched = new Set()
+function media(e) {
+ return caches.open(MEDIA).then(c => c.match(e.request).then(hit => {
+ if (hit) {
+ if (!touched.has(e.request.url)) {
+ touched.add(e.request.url)
+ const copy = hit.clone()
+ e.waitUntil(c.put(e.request, copy).catch(() => {}))
+ }
+ return hit
+ }
+ return fetch(e.request).then(res => {
+ // Only a real answer is kept. A gated instance answers a lapsed session with 401, and an
+ // auth proxy in front with its login page, a 200 of HTML after a redirect; stored under an
+ // image's URL, that would stand in for the animation for good.
+ const type = (res.headers && res.headers.get('content-type')) || ''
+ if (res.ok && !res.redirected && !/text\/html/i.test(type)) {
+ touched.add(e.request.url)
+ const copy = res.clone()
+ e.waitUntil(c.put(e.request, copy).then(() => { if (++mediaPuts >= MEDIA_TRIM_EVERY) { mediaPuts = 0; return trimMedia() } }).catch(() => {}))
+ }
+ return res
+ })
+ }))
+}
+
// The payload is parsed inside waitUntil: a push whose handler throws before showing anything is
// a "silent push", which Chrome counts against the site and eventually revokes. A body that is
// not JSON still shows a notification.
@@ -116,11 +197,8 @@ self.addEventListener('fetch', e => {
if (e.request.method !== 'GET' || url.origin !== location.origin) return
if (url.pathname.startsWith('/api/') || url.pathname.startsWith(API)) return // never cache auth/data
- const isMedia = url.pathname.includes('/img/') || url.pathname.includes('/gif/')
- if (isMedia) {
- e.respondWith(caches.open(CACHE).then(c => c.match(e.request).then(hit =>
- hit || fetch(e.request).then(res => { if (res.ok) c.put(e.request, res.clone()); return res })
- )))
+ if (isMediaPath(url.pathname)) {
+ e.respondWith(media(e))
return
}
// Network first; the copy for the cache is cloned before the response is handed to the page —
diff --git a/frontend/src/components/Media.jsx b/frontend/src/components/Media.jsx
index 1c90fcca8..0781e8149 100644
--- a/frontend/src/components/Media.jsx
+++ b/frontend/src/components/Media.jsx
@@ -50,7 +50,13 @@ export default function Media({ ex, id, compact, minimizable }) {
)
}
+// A still that will not load (offline and never cached, a lapsed session on a gated instance, a
+// CDN hiccup) gets the same neutral tile as an exercise without media, instead of the browser's
+// broken-image glyph in a list of them (#281). The failure is remembered per image, so a list
+// that re-renders does not ask again; a new exercise in the same slot tries its own.
export function Thumb({ ex }) {
- if (!ex.img) return <div className="thumb thumb-x"><Icon name="dumbbell" /></div>
- return <img className="thumb" loading="lazy" decoding="async" draggable={false} src={imgSrc(ex)} alt="" />
+ const src = ex.img ? imgSrc(ex) : null
+ const [broken, setBroken] = useState(null)
+ if (!src || broken === src) return <div className="thumb thumb-x"><Icon name="dumbbell" /></div>
+ return <img className="thumb" loading="lazy" decoding="async" draggable={false} src={src} alt="" onError={() => setBroken(src)} />
}
diff --git a/frontend/src/components/Media.thumb.test.jsx b/frontend/src/components/Media.thumb.test.jsx
new file mode 100644
index 000000000..8a2f4b435
--- /dev/null
+++ b/frontend/src/components/Media.thumb.test.jsx
@@ -0,0 +1,45 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+// A still that will not load (offline and never cached, a lapsed session on a gated instance)
+// gets the neutral tile an exercise without media has, not the browser's broken-image glyph (#281).
+vi.mock('../store/useStore.js', () => ({ useStore: () => null }))
+const { Thumb } = await import('./Media.jsx')
+
+const mounted = []
+function mount(el) {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push({ root, host })
+ act(() => root.render(el))
+ return { host, root }
+}
+afterEach(() => { act(() => { mounted.splice(0).forEach(({ root, host }) => { root.unmount(); host.remove() }) }) })
+
+describe('Thumb', () => {
+ it('shows the still, and the neutral tile once it fails to load', () => {
+ const { host } = mount(<Thumb ex={{ id: 'a', img: 'a.jpg' }} />)
+ const img = host.querySelector('img.thumb')
+ expect(img.getAttribute('src')).toMatch(/a\.jpg$/)
+ act(() => { img.dispatchEvent(new Event('error')) })
+ expect(host.querySelector('img')).toBeNull()
+ expect(host.querySelector('.thumb.thumb-x')).toBeTruthy()
+ })
+
+ it('another exercise in the same place tries its own still', () => {
+ const { host, root } = mount(<Thumb ex={{ id: 'a', img: 'a.jpg' }} />)
+ act(() => { host.querySelector('img').dispatchEvent(new Event('error')) })
+ act(() => root.render(<Thumb ex={{ id: 'b', img: 'b.jpg' }} />))
+ expect(host.querySelector('img.thumb').getAttribute('src')).toMatch(/b\.jpg$/)
+ })
+
+ it('an exercise without media has the tile from the start', () => {
+ const { host } = mount(<Thumb ex={{ id: 'c' }} />)
+ expect(host.querySelector('.thumb-x')).toBeTruthy()
+ })
+})
diff --git a/frontend/src/lib/media-prefetch.js b/frontend/src/lib/media-prefetch.js
new file mode 100644
index 000000000..372e31a4b
--- /dev/null
+++ b/frontend/src/lib/media-prefetch.js
@@ -0,0 +1,135 @@
+// Offline exercise media for the installed web app (#281).
+//
+// The service worker keeps every animation and still it has served in a cache that outlives
+// updates (public/sw.js, MEDIA). What it cannot do on its own is hold the media for a workout
+// nobody has opened yet: a GIF was offline only if it had once been shown online. So once the app
+// has settled, and again when the plan changes or the network comes back, the media for every
+// exercise in the plan and in the session in progress is fetched through the worker, which keeps
+// it. URLs already in the cache are skipped, so after the first run this is a cache lookup per
+// exercise and no traffic.
+//
+// It stays off the network when the browser says data costs something: Data Saver, a cellular
+// connection, or a 2G-class one. Safari and Firefox say nothing about the connection, and there it
+// runs; the set is bounded by the plan (a few MB for a typical one) and each file goes once.
+//
+// Not in the phone app: it has no service worker, and its media comes from the CDN.
+import { EXIDX, imgSrc, gifSrc } from './exercises.js'
+
+// The worker's media cache, public/sw.js MEDIA. Duplicated because the worker is not bundled;
+// sw-media.test.js pins the two together.
+export const MEDIA_CACHE = 'opengym-media-v1'
+// Long enough after boot or an edit that the app's own requests go first.
+export const PREFETCH_DELAY_MS = 8000
+const CONCURRENCY = 2
+// A server that refuses three in a row (a gated instance answering a guest with 401, a proxy
+// that is down) is not asked for the rest until the next run.
+const MAX_FAILURES = 3
+
+/** Every same-origin img/gif URL for the exercises in the plan and the active session. */
+export function planMediaUrls(S, base = globalThis.location?.href, index = EXIDX) {
+ if (!base) return []
+ const ids = new Set()
+ ;(S?.routines || []).forEach(r => (r?.ex || []).forEach(e => { if (e?.id) ids.add(e.id) }))
+ ;(S?.active?.entries || []).forEach(en => { if (en?.id) ids.add(en.id) })
+ const origin = new URL(base).origin
+ const urls = new Set()
+ for (const id of ids) {
+ const ex = index[id]
+ if (!ex) continue // a custom exercise has no media; an unknown id has nothing to fetch
+ for (const src of [ex.gif && gifSrc(ex), ex.img && imgSrc(ex)]) {
+ if (!src) continue
+ const u = new URL(src, base)
+ // Media on another origin (a build that points at a CDN) never passes through this
+ // worker, so fetching it here would only warm the browser's HTTP cache.
+ if (u.origin === origin) urls.add(u.href)
+ }
+ }
+ return [...urls]
+}
+
+/** Whether the connection is one to spend a few megabytes on without asking. */
+export function prefetchAllowed(nav = globalThis.navigator) {
+ if (!nav || nav.onLine === false) return false
+ const c = nav.connection
+ if (!c) return true
+ if (c.saveData) return false
+ if (c.type === 'cellular') return false
+ if (/(^|-)2g$/.test(c.effectiveType || '')) return false
+ return true
+}
+
+/**
+ * Fetch whatever of `urls` the cache does not hold yet, through the worker. Two at a time,
+ * and it stops as soon as the connection stops qualifying or the server keeps refusing.
+ */
+export async function prefetchMedia(urls, { cache, fetchImpl = globalThis.fetch, allowed = prefetchAllowed } = {}) {
+ const missing = cache
+ ? (await Promise.all(urls.map(async u => ((await cache.match(u).catch(() => null)) ? null : u)))).filter(Boolean)
+ : urls.slice()
+ let next = 0
+ let fetched = 0
+ let failures = 0
+ const lane = async () => {
+ while (next < missing.length && failures < MAX_FAILURES && allowed()) {
+ const u = missing[next++]
+ try {
+ const res = await fetchImpl(u, { priority: 'low' })
+ // Read to the end, so the worker's copy of the same stream is complete as well.
+ await res.arrayBuffer()
+ if (res.ok) { fetched++; failures = 0 } else failures++
+ } catch (e) { failures++ }
+ }
+ }
+ await Promise.all(Array.from({ length: CONCURRENCY }, lane))
+ return { wanted: urls.length, missing: missing.length, fetched }
+}
+
+/**
+ * Keep the plan's media offline for as long as the page is open. `store` is the zustand store
+ * (getState/subscribe). Returns a function that stops it.
+ */
+export function startMediaPrefetch(store, { delay = PREFETCH_DELAY_MS, nav = globalThis.navigator, cachesApi = globalThis.caches } = {}) {
+ const sw = nav?.serviceWorker
+ if (!sw || !cachesApi) return () => {}
+ let timer = null
+ let running = false
+ // The URL set the last complete run covered; the same set again has nothing left to fetch.
+ let done = ''
+ const run = async () => {
+ timer = null
+ // Only through a worker that is in charge of this page: without one nothing would be kept.
+ if (running || !sw.controller || !prefetchAllowed(nav)) return
+ const urls = planMediaUrls(store.getState().S)
+ const key = urls.join('\n')
+ if (!urls.length || key === done) return
+ running = true
+ try {
+ const r = await prefetchMedia(urls, { cache: await cachesApi.open(MEDIA_CACHE), allowed: () => prefetchAllowed(nav) })
+ if (r.fetched === r.missing) done = key
+ } catch (e) { /* best effort: the next change or reconnect tries again */ }
+ finally { running = false }
+ }
+ const schedule = () => {
+ if (timer) clearTimeout(timer)
+ timer = setTimeout(() => {
+ if (typeof globalThis.requestIdleCallback === 'function') globalThis.requestIdleCallback(() => run(), { timeout: 30000 })
+ else run()
+ }, delay)
+ }
+ let seen = store.getState().S
+ const unsubscribe = store.subscribe(st => {
+ const S = st.S
+ if (S?.routines === seen?.routines && S?.active === seen?.active) return
+ seen = S
+ schedule()
+ })
+ globalThis.addEventListener?.('online', schedule)
+ sw.addEventListener?.('controllerchange', schedule)
+ schedule()
+ return () => {
+ unsubscribe()
+ if (timer) clearTimeout(timer)
+ globalThis.removeEventListener?.('online', schedule)
+ sw.removeEventListener?.('controllerchange', schedule)
+ }
+}
diff --git a/frontend/src/lib/media-prefetch.test.js b/frontend/src/lib/media-prefetch.test.js
new file mode 100644
index 000000000..a2af499a5
--- /dev/null
+++ b/frontend/src/lib/media-prefetch.test.js
@@ -0,0 +1,147 @@
+// @vitest-environment node
+
+/* The page's half of offline exercise media (#281): which URLs the plan needs, when the
+ * connection is one to spend them on, and fetching only what the worker's cache is missing. */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { planMediaUrls, prefetchAllowed, prefetchMedia, startMediaPrefetch, MEDIA_CACHE, PREFETCH_DELAY_MS } from './media-prefetch.js'
+import { EXIDX, imgSrc, gifSrc } from './exercises.js'
+
+const BASE = 'https://gym.test/app/'
+const abs = src => new URL(src, BASE).href
+const bench = EXIDX['0025'] || Object.values(EXIDX).find(e => e.gif)
+const other = Object.values(EXIDX).find(e => e.gif && e.id !== bench.id)
+
+const answer = (status = 200) => ({ ok: status < 400, status, arrayBuffer: async () => new ArrayBuffer(1) })
+const cacheWith = urls => ({ match: async u => (urls.includes(u) ? {} : undefined) })
+
+afterEach(() => { vi.useRealTimers() })
+
+describe('planMediaUrls', () => {
+ it('names the still and the animation of every exercise in the plan and the session in progress, once each', () => {
+ const S = {
+ routines: [{ ex: [{ id: bench.id }, { id: bench.id }] }, { ex: [{ id: 'custom-1' }, {}] }, null],
+ active: { entries: [{ id: other.id }, { id: bench.id }] },
+ }
+ const urls = planMediaUrls(S, BASE, { ...EXIDX, 'custom-1': { id: 'custom-1', n: 'Mine' } })
+ expect(urls.sort()).toEqual([abs(gifSrc(bench)), abs(imgSrc(bench)), abs(gifSrc(other)), abs(imgSrc(other))].sort())
+ })
+
+ it('an empty or missing plan needs nothing', () => {
+ expect(planMediaUrls({}, BASE)).toEqual([])
+ expect(planMediaUrls(null, BASE)).toEqual([])
+ expect(planMediaUrls({ routines: [{ ex: [{ id: bench.id }] }] }, undefined)).toEqual([])
+ })
+
+ it('leaves out media a build points at another origin, which never passes through the worker', async () => {
+ // The demo build's media comes from a CDN (VITE_IMG_BASE/VITE_GIF_BASE, read at load).
+ vi.resetModules()
+ vi.stubEnv('VITE_IMG_BASE', 'https://cdn.test/images/')
+ vi.stubEnv('VITE_GIF_BASE', 'https://cdn.test/videos/')
+ try {
+ const fresh = await import('./media-prefetch.js')
+ expect(fresh.planMediaUrls({ routines: [{ ex: [{ id: bench.id }] }] }, BASE)).toEqual([])
+ } finally { vi.unstubAllEnvs(); vi.resetModules() }
+ })
+})
+
+describe('prefetchAllowed', () => {
+ it('spends data only where the browser does not say it costs something', () => {
+ expect(prefetchAllowed({ onLine: true })).toBe(true) // Safari, Firefox: no word
+ expect(prefetchAllowed({ onLine: true, connection: { type: 'wifi', effectiveType: '4g' } })).toBe(true)
+ expect(prefetchAllowed({ onLine: false })).toBe(false)
+ expect(prefetchAllowed({ onLine: true, connection: { saveData: true, type: 'wifi' } })).toBe(false)
+ expect(prefetchAllowed({ onLine: true, connection: { type: 'cellular', effectiveType: '4g' } })).toBe(false)
+ expect(prefetchAllowed({ onLine: true, connection: { effectiveType: '2g' } })).toBe(false)
+ expect(prefetchAllowed({ onLine: true, connection: { effectiveType: 'slow-2g' } })).toBe(false)
+ expect(prefetchAllowed(undefined)).toBe(false)
+ })
+})
+
+describe('prefetchMedia', () => {
+ it('fetches only what the cache is missing, and reads each answer to the end', async () => {
+ const read = vi.fn(async () => new ArrayBuffer(1))
+ const fetchImpl = vi.fn(async () => ({ ok: true, status: 200, arrayBuffer: read }))
+ const r = await prefetchMedia(['a', 'b', 'c'], { cache: cacheWith(['b']), fetchImpl, allowed: () => true })
+ expect(fetchImpl.mock.calls.map(c => c[0]).sort()).toEqual(['a', 'c'])
+ expect(read).toHaveBeenCalledTimes(2)
+ expect(r).toEqual({ wanted: 3, missing: 2, fetched: 2 })
+ })
+
+ it('gives up after three refusals in a row, and stops when the connection stops qualifying', async () => {
+ const refused = vi.fn(async () => answer(401))
+ const urls = [...Array(20)].map((_, i) => 'u' + i)
+ const r = await prefetchMedia(urls, { fetchImpl: refused, allowed: () => true })
+ expect(refused.mock.calls.length).toBeLessThanOrEqual(4) // two lanes, one may be mid-flight
+ expect(r.fetched).toBe(0)
+
+ let budget = 3
+ const ok = vi.fn(async () => answer())
+ await prefetchMedia(urls, { fetchImpl: ok, allowed: () => budget-- > 0 })
+ expect(ok).toHaveBeenCalledTimes(3)
+
+ const down = vi.fn(async () => { throw new TypeError('Failed to fetch') })
+ await prefetchMedia(urls, { fetchImpl: down, allowed: () => true })
+ expect(down.mock.calls.length).toBeLessThanOrEqual(4)
+ })
+})
+
+describe('startMediaPrefetch', () => {
+ function setup({ controller = {}, S = { routines: [{ ex: [{ id: bench.id }] }] } } = {}) {
+ const listeners = new Set()
+ const store = { state: { S }, getState: () => store.state, subscribe: fn => { listeners.add(fn); return () => listeners.delete(fn) } }
+ store.set = S => { store.state = { S }; listeners.forEach(fn => fn(store.state)) }
+ const cached = []
+ const cachesApi = { open: vi.fn(async () => cacheWith(cached)) }
+ const nav = { onLine: true, serviceWorker: { controller, addEventListener() {}, removeEventListener() {} } }
+ const fetchImpl = vi.fn(async u => { cached.push(u); return answer() })
+ vi.stubGlobal('fetch', fetchImpl)
+ vi.stubGlobal('location', { href: BASE })
+ return { store, cachesApi, nav, fetchImpl, listeners }
+ }
+ afterEach(() => { vi.unstubAllGlobals() })
+ const flush = async () => { for (let i = 0; i < 10; i++) await Promise.resolve() }
+
+ it('waits for the app to settle, fetches the plan\'s media through the worker, then only what a plan change adds', async () => {
+ vi.useFakeTimers()
+ const { store, cachesApi, nav, fetchImpl } = setup()
+ const stop = startMediaPrefetch(store, { nav, cachesApi })
+ expect(fetchImpl).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ expect(cachesApi.open).toHaveBeenCalledWith(MEDIA_CACHE)
+ expect(fetchImpl.mock.calls.map(c => c[0]).sort()).toEqual([abs(gifSrc(bench)), abs(imgSrc(bench))].sort())
+
+ // Something unrelated changes: nothing new to fetch.
+ store.set({ ...store.state.S, unit: 'lb' })
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ expect(fetchImpl).toHaveBeenCalledTimes(2)
+
+ // A routine gains an exercise: its two files, and only those.
+ store.set({ routines: [{ ex: [{ id: bench.id }, { id: other.id }] }] })
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ expect(fetchImpl.mock.calls.slice(2).map(c => c[0]).sort()).toEqual([abs(gifSrc(other)), abs(imgSrc(other))].sort())
+ stop()
+ })
+
+ it('does nothing without a worker in charge of the page, or on a connection that costs', async () => {
+ vi.useFakeTimers()
+ const a = setup({ controller: null })
+ const stopA = startMediaPrefetch(a.store, { nav: a.nav, cachesApi: a.cachesApi })
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ expect(a.fetchImpl).not.toHaveBeenCalled()
+ stopA()
+
+ const b = setup()
+ b.nav.connection = { saveData: true }
+ const stop = startMediaPrefetch(b.store, { nav: b.nav, cachesApi: b.cachesApi })
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ expect(b.fetchImpl).not.toHaveBeenCalled()
+ stop()
+
+ expect(startMediaPrefetch(b.store, { nav: {}, cachesApi: b.cachesApi })).toBeTypeOf('function')
+ })
+})
diff --git a/frontend/src/lib/sw-media.test.js b/frontend/src/lib/sw-media.test.js
new file mode 100644
index 000000000..7953f1586
--- /dev/null
+++ b/frontend/src/lib/sw-media.test.js
@@ -0,0 +1,140 @@
+// @vitest-environment node
+
+/* Exercise media offline (#281). The worker keeps img/ and gif/ in a cache of its own that an
+ * update does not sweep, adopts what an older build had cached, never keeps a login page or a
+ * refusal under an image's URL, and stays under its size cap by dropping the least recently
+ * used first. public/sw.js is evaluated as-is against a small worker environment whose caches
+ * keep entries in write order, the way the Cache API does. */
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { MEDIA_CACHE } from './media-prefetch.js'
+
+const SW = readFileSync(fileURLToPath(new URL('../../public/sw.js', import.meta.url)), 'utf8')
+const BUILD = 'opengym-rt-__BUILD__'
+const MEDIA = 'opengym-media-v1'
+const ORIGIN = 'https://gym.test'
+const keyOf = r => (typeof r === 'string' ? new URL(r, ORIGIN + '/').href : r.url)
+
+class OrderedCache {
+ constructor() { this.m = new Map() }
+ async put(req, res) { const k = keyOf(req); this.m.delete(k); this.m.set(k, res) } // a write moves to the end
+ async match(req) { const r = this.m.get(keyOf(req)); return r ? r.clone() : undefined }
+ async keys() { return [...this.m.keys()].map(url => ({ url })) }
+ async delete(req) { return this.m.delete(keyOf(req)) }
+ urls() { return [...this.m.keys()] }
+}
+// `all` carries the caches over from an earlier worker: the browser stops an idle worker and
+// starts a fresh one, and the caches are what survives.
+function worker(all = new Map()) {
+ const handlers = {}
+ const caches = {
+ open: async n => { if (!all.has(n)) all.set(n, new OrderedCache()); return all.get(n) },
+ keys: async () => [...all.keys()],
+ delete: async n => all.delete(n),
+ match: async req => { for (const c of all.values()) { const hit = await c.match(req); if (hit) return hit } return undefined },
+ }
+ const env = { net: { up: true, answer: null }, fetched: [], all, caches }
+ const fetch = async req => {
+ const url = keyOf(req)
+ env.fetched.push(url)
+ if (!env.net.up) throw new TypeError('Failed to fetch')
+ if (env.net.answer) return env.net.answer(url)
+ return new Response('GIF89a' + url, { status: 200, headers: { 'content-type': 'image/gif', 'content-length': String(40 * 1024 * 1024) } })
+ }
+ const self = { addEventListener: (t, f) => { handlers[t] = f }, skipWaiting: () => {}, clients: { claim: async () => {} }, registration: {} }
+ new Function('self', 'caches', 'fetch', 'location', SW)(self, caches, fetch, new URL(ORIGIN + '/sw.js'))
+ env.get = async path => {
+ const pending = []
+ let responded = null
+ const e = { request: { url: ORIGIN + path, method: 'GET', mode: 'no-cors' }, respondWith: p => { responded = p }, waitUntil: p => { pending.push(p) } }
+ handlers.fetch(e)
+ const res = await responded
+ await Promise.all(pending)
+ // A write-back may have been queued after the answer was handed over.
+ for (let i = 0; i < 3; i++) { await new Promise(r => setTimeout(r, 0)); await Promise.all(pending) }
+ return res
+ }
+ env.activate = async () => {
+ let done
+ handlers.activate({ waitUntil: p => { done = p } })
+ await done
+ }
+ env.media = () => all.get(MEDIA)
+ return env
+}
+
+describe('sw.js exercise media', () => {
+ it('is kept in a cache of its own and answers offline from it', async () => {
+ const w = worker()
+ const res = await w.get('/gif/0001.gif')
+ expect(res.status).toBe(200)
+ expect(w.media().urls()).toEqual([ORIGIN + '/gif/0001.gif'])
+ expect(w.all.get(BUILD)?.urls() || []).toEqual([])
+
+ w.net.up = false
+ const again = await w.get('/gif/0001.gif')
+ expect(await again.text()).toBe('GIF89a' + ORIGIN + '/gif/0001.gif')
+ })
+
+ it('survives an update: activate sweeps old builds, never the media, and adopts what an old build had cached', async () => {
+ const w = worker()
+ await w.get('/img/0002.jpg')
+ const old = await w.caches.open('opengym-rt-oldbuild')
+ await old.put(ORIGIN + '/gif/0003.gif', new Response('old gif', { headers: { 'content-type': 'image/gif' } }))
+ await old.put(ORIGIN + '/assets/index-old.js', new Response('old code'))
+ const shell = await w.caches.open(BUILD)
+ await shell.put('index.html', new Response('<html></html>'))
+
+ await w.activate()
+ expect(await w.caches.keys()).toEqual(expect.arrayContaining([BUILD, MEDIA]))
+ expect(await w.caches.keys()).not.toContain('opengym-rt-oldbuild')
+ expect(w.media().urls()).toEqual([ORIGIN + '/img/0002.jpg', ORIGIN + '/gif/0003.gif'])
+
+ w.net.up = false
+ expect(await (await w.get('/gif/0003.gif')).text()).toBe('old gif')
+ })
+
+ it('an activate with no media anywhere creates no media cache', async () => {
+ const w = worker()
+ const shell = await w.caches.open(BUILD)
+ await shell.put('index.html', new Response('<html></html>'))
+ await w.activate()
+ expect(await w.caches.keys()).toEqual([BUILD])
+ })
+
+ it('keeps no login page, redirect or refusal under an image\'s URL', async () => {
+ const w = worker()
+ w.net.answer = url => url.endsWith('a.gif')
+ ? Object.defineProperty(new Response('<html>sign in</html>', { headers: { 'content-type': 'text/html' } }), 'redirected', { value: true })
+ : url.endsWith('b.gif') ? new Response('<html>sign in</html>', { headers: { 'content-type': 'text/html; charset=utf-8' } })
+ : new Response('no', { status: 401 })
+ await w.get('/gif/a.gif'); await w.get('/gif/b.gif'); await w.get('/gif/c.gif')
+ expect(w.media().urls()).toEqual([])
+ })
+
+ it('stays under its cap, dropping the least recently used first', async () => {
+ const first = worker()
+ // 40 MB each by Content-Length: the cap (150 MB) holds three of them.
+ for (const n of [1, 2, 3]) await first.get(`/gif/${n}.gif`)
+ // A later worker that shows the oldest again moves it to the back of the line, once.
+ const w = worker(first.all)
+ await w.get('/gif/1.gif')
+ await w.get('/gif/1.gif')
+ expect(w.media().urls().map(u => u.slice(-5))).toEqual(['2.gif', '3.gif', '1.gif'])
+ expect(w.fetched).toEqual([]) // both from the cache
+ // Trimming runs every twentieth new entry this worker writes; small ones fill the gap.
+ w.net.answer = url => new Response('x', { headers: { 'content-type': 'image/jpeg', 'content-length': url.includes('/img/') ? '1024' : String(40 * 1024 * 1024) } })
+ await w.get('/gif/4.gif')
+ for (let i = 0; i < 19; i++) await w.get(`/img/${i}.jpg`)
+ const left = w.media().urls().map(u => u.slice(u.lastIndexOf('/') + 1))
+ expect(left).not.toContain('2.gif')
+ expect(left).toEqual(expect.arrayContaining(['3.gif', '1.gif', '4.gif', '0.jpg', '18.jpg']))
+ expect(left).toHaveLength(22)
+ })
+
+ it('names the same cache as the page-side prefetch', () => {
+ expect(SW).toContain(`const MEDIA = '${MEDIA_CACHE}'`)
+ expect(MEDIA_CACHE).toBe(MEDIA)
+ })
+})
diff --git a/frontend/src/main.jsx b/frontend/src/main.jsx
index 3f5b788f5..f57590454 100644
--- a/frontend/src/main.jsx
+++ b/frontend/src/main.jsx
@@ -2,6 +2,7 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import { MOBILE } from './lib/mobile.js'
+import { useStore } from './store/useStore.js'
import './index.css'
// App.jsx restores per-route scroll itself; the browser's own attempt races it.
@@ -14,4 +15,6 @@ createRoot(document.getElementById('root')).render(
// Not in the mobile build: the native shell already serves everything from disk.
if (!MOBILE && 'serviceWorker' in navigator && location.protocol === 'https:') {
navigator.serviceWorker.register('sw.js').catch(() => {})
+ // The plan's exercise media, kept by the worker for a workout opened without a network (#281).
+ import('./lib/media-prefetch.js').then(m => m.startMediaPrefetch(useStore)).catch(() => {})
}