diff --git a/README.md b/README.md
index 4579280..64daa2d 100644
--- a/README.md
+++ b/README.md
@@ -352,7 +352,7 @@ npm install
SONDA_URL=http://127.0.0.1:8080 npm run dev # open http://localhost:5173, /api is proxied to Sonda
```
-What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys, a volume slider with mute (remembered in the browser) and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Playlists have a page of their own, shown as cards with a collage of their covers (as the mixes and the smart playlists have): make one, put a song in it with the button next to any song (or make a new playlist right there), play it, rename it, delete it, move a song up or down and take one out; a song whose files are gone is shown as not available and skipped when the playlist plays. Mixes have a page too: a card for each mix, with a collage of the covers of its albums (the ones from your listening first, then one for each genre), and on a mix its songs, Play, Shuffle again (another set of songs) and Save as playlist, which keeps what you see as a playlist of your own. Where a playlist is renamed, and where a smart playlist is edited, a Suggest a name button asks for a name. Smart playlists have their own page too, which begins with the ones Sonda makes for you (ready to play, to keep as a playlist, or to make your own with a click), and then yours: make one with an editor of the rules (genres, format and bitrate, when it was added, your listening and taste, the length, the order and the limit) and a live preview of the songs it gives, play it, shuffle it again (for the random order), keep what you see as a playlist, edit it or delete it; rules by artist and album are in the API only, and an edit keeps them. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. Providers have a card each that says what the provider is sent: turning one on asks first, the API key is write-only (never shown, and gone from the page once saved), and there are a test of the key, the contact or address, removing what a provider gave, and, for Lidarr, the profiles and root folder to use when an artist is added. The bulk jobs (album covers, artist pictures, artist descriptions) each have a card that says what the job sends and to whom: starting one asks first and says it goes through the whole library, reading everything again is a separate choice, a job whose providers are off cannot be started, and the page follows its progress and can stop it. The menu on the left folds to a narrow bar with the icons of the pages (a button in it, remembered in the browser; on a phone it stays a row of links). There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings.
+What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys, a volume slider with mute (remembered in the browser) and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Playlists have a page of their own, shown as cards with a collage of their covers (as the mixes and the smart playlists have): make one, put a song in it with the button next to any song (or make a new playlist right there), play it, rename it, delete it, move a song up or down and take one out; a song whose files are gone is shown as not available and skipped when the playlist plays. Mixes have a page too: a card for each mix, with a collage of the covers of its albums (the ones from your listening first, then one for each genre), and on a mix its songs, Play, Shuffle again (another set of songs) and Save as playlist, which keeps what you see as a playlist of your own. Where a playlist is renamed, and where a smart playlist is edited, a Suggest a name button asks for a name. Smart playlists have their own page too, which begins with the ones Sonda makes for you (ready to play, to keep as a playlist, or to make your own with a click), and then yours: make one with an editor of the rules (genres, format and bitrate, when it was added, your listening and taste, the length, the order and the limit) and a live preview of the songs it gives, play it, shuffle it again (for the random order), keep what you see as a playlist, edit it or delete it; rules by artist and album are in the API only, and an edit keeps them. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. Providers have a card each that says what the provider is sent: turning one on asks first, the API key is write-only (never shown, and gone from the page once saved), and there are a test of the key, the contact or address, removing what a provider gave, and, for Lidarr, the profiles and root folder to use when an artist is added. The bulk jobs (album covers, artist pictures, artist descriptions) each have a card that says what the job sends and to whom: starting one asks first and says it goes through the whole library, reading everything again is a separate choice, a job whose providers are off cannot be started, and the page follows its progress and can stop it. The web app is a PWA: it has a manifest and a service worker, so a browser can install it (Settings has an Install button where the browser lets a page ask) and it opens at once from its own icon, and shows its own page when the server cannot be reached. The worker keeps only the files of the app (the page, its scripts and styles, the manifest and the icons) and never anything from `/api/`: the catalog, the covers, the songs and what a person did are private and are not kept. A new version waits until you press Reload, so nothing changes under a song. It needs https, or localhost. The menu on the left folds to a narrow bar with the icons of the pages (a button in it, remembered in the browser; on a phone it stays a row of links). There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings.
More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). `npm run build` writes to `internal/webui/dist` (git-ignored), not to `web/dist`.
diff --git a/internal/api/http/web.go b/internal/api/http/web.go
index 1a625b0..22edfc0 100644
--- a/internal/api/http/web.go
+++ b/internal/api/http/web.go
@@ -19,6 +19,11 @@ const appPolicy = "default-src 'self'; script-src 'self'; style-src 'self'; styl
"img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self'; connect-src 'self'; " +
"object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
+func init() {
+ // The manifest of the app has no type in the tables of the system, and "text/plain" would stop a browser from installing it.
+ _ = mime.AddExtensionType(".webmanifest", "application/manifest+json")
+}
+
// Files under assets/ have a hash in their name, so a name never means two different files.
const (
assetsDir = "assets"
diff --git a/internal/api/http/web_test.go b/internal/api/http/web_test.go
index c4bf28e..82d1723 100644
--- a/internal/api/http/web_test.go
+++ b/internal/api/http/web_test.go
@@ -234,3 +234,50 @@ func TestWithNoAppTheRootSaysHowToBuildIt(t *testing.T) {
}
}
}
+
+// ---- the app can be installed ----
+
+func TestTheManifestAndTheServiceWorkerAreServedWithTheirTypeAndAskedAgain(t *testing.T) {
+ app := theApp()
+ app["manifest.webmanifest"] = &fstest.MapFile{Data: []byte(`{"name":"Sonda"}`)}
+ app["sw.js"] = &fstest.MapFile{Data: []byte("self.addEventListener('fetch', () => {})")}
+ for path, wantType := range map[string]string{
+ "/manifest.webmanifest": "application/manifest+json",
+ "/sw.js": "text/javascript",
+ } {
+ rec := serve(t, app, http.MethodGet, path)
+ if rec.Code != http.StatusOK {
+ t.Errorf("%s: status %d", path, rec.Code)
+ continue
+ }
+ if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, wantType) {
+ t.Errorf("%s: Content-Type %q, want %s", path, ct, wantType)
+ }
+ // A new version of the worker or of the manifest must be seen at once: they are asked again every time.
+ if got := rec.Header().Get("Cache-Control"); got != "no-cache" {
+ t.Errorf("%s: Cache-Control %q, want no-cache", path, got)
+ }
+ if rec.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Errorf("%s: no nosniff", path)
+ }
+ }
+}
+
+func TestThePolicyOfTheAppLetsItRunItsOwnWorkerAndNothingElse(t *testing.T) {
+ rec := serve(t, theApp(), http.MethodGet, "/")
+ policy := rec.Header().Get("Content-Security-Policy")
+ // Workers and the manifest fall back to the sources of scripts and of everything else: the server itself.
+ for _, want := range []string{"default-src 'self'", "script-src 'self'", "connect-src 'self'"} {
+ if !strings.Contains(policy, want) {
+ t.Errorf("policy %q lacks %q", policy, want)
+ }
+ }
+ for _, never := range []string{"worker-src *", "worker-src http", "unsafe-eval", "script-src *"} {
+ if strings.Contains(policy, never) {
+ t.Errorf("policy %q has %q", policy, never)
+ }
+ }
+ if strings.Contains(policy, "worker-src") || strings.Contains(policy, "manifest-src") {
+ t.Errorf("policy %q names worker-src or manifest-src: they must follow default-src", policy)
+ }
+}
diff --git a/web/index.html b/web/index.html
index c423c0d..7c6ab11 100644
--- a/web/index.html
+++ b/web/index.html
@@ -6,6 +6,9 @@
+
+
+
Sonda
diff --git a/web/public/icon-maskable-512.png b/web/public/icon-maskable-512.png
new file mode 100644
index 0000000..c2dc749
Binary files /dev/null and b/web/public/icon-maskable-512.png differ
diff --git a/web/public/manifest.webmanifest b/web/public/manifest.webmanifest
new file mode 100644
index 0000000..bf9ce26
--- /dev/null
+++ b/web/public/manifest.webmanifest
@@ -0,0 +1,38 @@
+{
+ "name": "Sonda",
+ "short_name": "Sonda",
+ "description": "Your own music, on your own server.",
+ "id": "/",
+ "start_url": "/",
+ "scope": "/",
+ "display": "standalone",
+ "orientation": "any",
+ "background_color": "#041d3a",
+ "theme_color": "#041d3a",
+ "icons": [
+ {
+ "src": "/icon-192.png",
+ "sizes": "192x192",
+ "type": "image/png",
+ "purpose": "any"
+ },
+ {
+ "src": "/icon-512.png",
+ "sizes": "512x512",
+ "type": "image/png",
+ "purpose": "any"
+ },
+ {
+ "src": "/icon-maskable-512.png",
+ "sizes": "512x512",
+ "type": "image/png",
+ "purpose": "maskable"
+ },
+ {
+ "src": "/favicon.svg",
+ "sizes": "any",
+ "type": "image/svg+xml",
+ "purpose": "any"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/web/public/sw.js b/web/public/sw.js
new file mode 100644
index 0000000..3a0bafc
--- /dev/null
+++ b/web/public/sw.js
@@ -0,0 +1,121 @@
+// The service worker of Sonda.
+//
+// It keeps the files of the app (the page, its scripts and styles, the manifest and the icons) so that the app opens at
+// once and, when the server cannot be reached, shows the page of the app instead of an error of the browser.
+//
+// It never touches the API. What comes from /api/ is private (the catalog, the covers, the songs, what a person did, and
+// the address of a song carries the session): it is not kept, not answered from a cache, and not even asked for by the
+// worker; the browser does it as if the worker were not there.
+//
+// A new version of the worker waits until the page tells it to take over (the page shows "a new version is ready" and
+// a button), so that nobody is switched to new files in the middle of a song.
+
+const VERSION = 'v1'
+const CACHE = `sonda-shell-${VERSION}`
+const PREFIX = 'sonda-shell-'
+// How many files under /assets/ are kept. The scripts and styles have a hash in their name, so a new build brings
+// new names: the oldest go, the page and its icons stay.
+const MAX_ASSETS = 120
+const KEPT = ['/', '/manifest.webmanifest', '/favicon.svg', '/icon-192.png', '/icon-512.png', '/icon-maskable-512.png', '/apple-touch-icon.png']
+const OFFLINE =
+ '' +
+ 'Sonda' +
+ '
Sonda
The server cannot be reached, and this page was not kept on this device yet.
' +
+ '
Open Sonda once while you are connected to it, and the app will open from then on even when the server is far.
'
+
+const isAsset = (url) => url.pathname.startsWith('/assets/')
+
+/** Keeps the page and what it names under /assets/. */
+async function keepShell() {
+ const cache = await caches.open(CACHE)
+ // The page is asked again from the server, not from the cache of the browser.
+ const page = await fetch('/', { cache: 'reload' })
+ if (page.ok) {
+ await cache.put('/', page.clone())
+ const html = await page.text()
+ const names = [...html.matchAll(/(?:src|href)="(\/assets\/[^"]+)"/g)].map((m) => m[1])
+ await Promise.all(
+ names.concat(KEPT.slice(1)).map(async (name) => {
+ try {
+ const res = await fetch(name)
+ if (res.ok) await cache.put(name, res)
+ } catch {
+ // A file that cannot be had now is simply not kept: the app still works online.
+ }
+ }),
+ )
+ }
+}
+
+/** Takes the oldest files of /assets/ out when there are more than MAX_ASSETS. */
+async function trim(cache) {
+ const assets = (await cache.keys()).filter((r) => isAsset(new URL(r.url)))
+ for (const r of assets.slice(0, Math.max(0, assets.length - MAX_ASSETS))) await cache.delete(r)
+}
+
+self.addEventListener('install', (event) => {
+ event.waitUntil(keepShell())
+})
+
+self.addEventListener('activate', (event) => {
+ event.waitUntil(
+ (async () => {
+ for (const name of await caches.keys()) {
+ if (name.startsWith(PREFIX) && name !== CACHE) await caches.delete(name)
+ }
+ await self.clients.claim()
+ })(),
+ )
+})
+
+self.addEventListener('message', (event) => {
+ if (event.data && event.data.type === 'SKIP_WAITING') self.skipWaiting()
+})
+
+/** A link inside the app: the server first, so that an update shows at once, and the kept page when it cannot be reached. */
+async function page(request) {
+ try {
+ const res = await fetch(request)
+ if (res.ok) (await caches.open(CACHE)).put('/', res.clone())
+ return res
+ } catch {
+ const kept = await (await caches.open(CACHE)).match('/')
+ return kept || new Response(OFFLINE, { status: 503, headers: { 'Content-Type': 'text/html; charset=utf-8' } })
+ }
+}
+
+/** A script or a style: the one that is kept, else from the server, and kept. Its name has a hash, so it never changes. */
+async function asset(request) {
+ const cache = await caches.open(CACHE)
+ const hit = await cache.match(request)
+ if (hit) return hit
+ const res = await fetch(request)
+ if (res.ok) {
+ await cache.put(request, res.clone())
+ await trim(cache)
+ }
+ return res
+}
+
+/** An icon or the manifest: the server first, and the kept one when it cannot be reached. Nothing new is kept. */
+async function other(request) {
+ try {
+ return await fetch(request)
+ } catch (err) {
+ const kept = await (await caches.open(CACHE)).match(request)
+ if (kept) return kept
+ throw err
+ }
+}
+
+self.addEventListener('fetch', (event) => {
+ const request = event.request
+ const url = new URL(request.url)
+ // Not its business: anything but a GET to its own server, a song being read in pieces, and the whole API.
+ if (request.method !== 'GET' || url.origin !== self.location.origin || request.headers.has('range')) return
+ if (url.pathname === '/api' || url.pathname.startsWith('/api/')) return
+
+ if (request.mode === 'navigate') event.respondWith(page(request))
+ else if (isAsset(url)) event.respondWith(asset(request))
+ else event.respondWith(other(request))
+})
diff --git a/web/src/components/layout/Shell.tsx b/web/src/components/layout/Shell.tsx
index 0a91e94..df9b2c1 100644
--- a/web/src/components/layout/Shell.tsx
+++ b/web/src/components/layout/Shell.tsx
@@ -1,5 +1,6 @@
import { Outlet } from 'react-router-dom'
import { usePlayerEngine } from '@/player/usePlayer'
+import UpdateNotice from '@/pwa/UpdateNotice'
import PlayerBar from './PlayerBar'
import Sidebar from './Sidebar'
@@ -18,6 +19,7 @@ export default function Shell() {
+
)
}
diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json
index 40d312e..df8248c 100644
--- a/web/src/i18n/locales/en.json
+++ b/web/src/i18n/locales/en.json
@@ -57,6 +57,7 @@
"account": "Account",
"admin": "Admin",
"signOut": "Sign out",
+ "app": "App",
"appearance": "Appearance",
"theme": "Theme",
"language": "Language",
@@ -723,5 +724,12 @@
"suggest": "Suggest a name",
"claude": "Suggested by Claude",
"local": "Suggested on this server"
+ },
+ "pwa": {
+ "updateReady": "A new version of Sonda is ready.",
+ "reload": "Reload",
+ "later": "Later",
+ "install": "Install Sonda",
+ "installIntro": "Install Sonda on this device to open it like an app, from its own icon and in its own window."
}
}
diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json
index 9854c44..a699824 100644
--- a/web/src/i18n/locales/it.json
+++ b/web/src/i18n/locales/it.json
@@ -57,6 +57,7 @@
"account": "Account",
"admin": "Admin",
"signOut": "Esci",
+ "app": "App",
"appearance": "Aspetto",
"theme": "Tema",
"language": "Lingua",
@@ -723,5 +724,12 @@
"suggest": "Suggerisci un nome",
"claude": "Suggerito da Claude",
"local": "Suggerito da questo server"
+ },
+ "pwa": {
+ "updateReady": "È pronta una nuova versione di Sonda.",
+ "reload": "Ricarica",
+ "later": "Più tardi",
+ "install": "Installa Sonda",
+ "installIntro": "Installa Sonda su questo dispositivo per aprirla come un'app, con la sua icona e nella sua finestra."
}
}
diff --git a/web/src/main.tsx b/web/src/main.tsx
index 4aa850c..693a143 100644
--- a/web/src/main.tsx
+++ b/web/src/main.tsx
@@ -4,10 +4,13 @@ import './index.css'
import App from './App.tsx'
import { restoreSession } from './auth/session'
import { initI18n } from './i18n'
+import { usePwa } from './pwa/store'
+import { registerServiceWorker } from './pwa/register'
import { initTheme } from './theme/theme'
initTheme()
void restoreSession()
+registerServiceWorker({ onWaiting: (registration) => usePwa.getState().setWaiting(registration) })
void initI18n().then(() => {
createRoot(document.getElementById('root')!).render(
diff --git a/web/src/pages/SettingsPage.test.tsx b/web/src/pages/SettingsPage.test.tsx
index 21f3aba..2e2d9e8 100644
--- a/web/src/pages/SettingsPage.test.tsx
+++ b/web/src/pages/SettingsPage.test.tsx
@@ -1,5 +1,5 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { render, screen } from '@testing-library/react'
+import { act, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { beforeEach, expect, test, vi } from 'vitest'
@@ -172,3 +172,26 @@ test('signing out forgets the session', async () => {
await userEvent.click(screen.getByRole('button', { name: 'Sign out' }))
await vi.waitFor(() => expect(sessionStore.getState().status).toBe('anonymous'))
})
+
+// --- installing the app ----------------------------------------------------------------------------------------
+
+test('there is no App section when the browser does not offer to install the app', () => {
+ renderSettings()
+ expect(screen.queryByRole('region', { name: 'App' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Install Sonda' })).not.toBeInTheDocument()
+})
+
+test('when the browser offers it, the page can ask to install the app, once', async () => {
+ window.matchMedia = vi.fn().mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }) as unknown as typeof window.matchMedia
+ renderSettings()
+ const offer = new Event('beforeinstallprompt', { cancelable: true }) as Event & { prompt: () => Promise; userChoice: Promise<{ outcome: string }> }
+ offer.prompt = vi.fn(async () => {})
+ offer.userChoice = Promise.resolve({ outcome: 'accepted' })
+ act(() => {
+ window.dispatchEvent(offer)
+ })
+ expect(await screen.findByRole('region', { name: 'App' })).toBeInTheDocument()
+ await userEvent.click(screen.getByRole('button', { name: 'Install Sonda' }))
+ expect(offer.prompt).toHaveBeenCalledTimes(1)
+ await vi.waitFor(() => expect(screen.queryByRole('button', { name: 'Install Sonda' })).not.toBeInTheDocument())
+})
diff --git a/web/src/pages/SettingsPage.tsx b/web/src/pages/SettingsPage.tsx
index 698f9e4..28065a6 100644
--- a/web/src/pages/SettingsPage.tsx
+++ b/web/src/pages/SettingsPage.tsx
@@ -5,6 +5,7 @@ import { logout, useSession } from '@/auth/session'
import ChoiceGroup from '@/components/ChoiceGroup'
import ListeningSwitch from '@/components/ListeningSwitch'
import Section from '@/components/Section'
+import { useInstall } from '@/pwa/useInstall'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
@@ -102,6 +103,7 @@ export default function SettingsPage() {
const { user } = useSession()
const { theme, setTheme } = useTheme()
const { lang, setLanguage } = useLanguage()
+ const app = useInstall()
return (
+
+
+ )}
+
diff --git a/web/src/pwa/UpdateNotice.test.tsx b/web/src/pwa/UpdateNotice.test.tsx
new file mode 100644
index 0000000..ed9e17d
--- /dev/null
+++ b/web/src/pwa/UpdateNotice.test.tsx
@@ -0,0 +1,48 @@
+import { act, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, expect, test, vi } from 'vitest'
+import { initI18n } from '@/i18n'
+import UpdateNotice from './UpdateNotice'
+import { usePwa } from './store'
+
+beforeEach(async () => {
+ vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
+ await initI18n()
+ usePwa.setState({ registration: null })
+})
+
+function waitingRegistration() {
+ const postMessage = vi.fn()
+ return { postMessage, registration: { waiting: { postMessage } } as unknown as ServiceWorkerRegistration }
+}
+
+test('nothing is shown while there is no new version', () => {
+ render()
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
+})
+
+test('a new version is announced, with a button that tells the worker to take over', async () => {
+ const { postMessage, registration } = waitingRegistration()
+ const listeners: Record void> = {}
+ Object.defineProperty(navigator, 'serviceWorker', { value: { addEventListener: (t: string, fn: () => void) => (listeners[t] = fn) }, configurable: true })
+ const reload = vi.fn()
+ vi.stubGlobal('location', { ...window.location, reload })
+ render()
+ act(() => usePwa.getState().setWaiting(registration))
+ expect(await screen.findByRole('status')).toHaveTextContent('A new version of Sonda is ready.')
+ await userEvent.click(screen.getByRole('button', { name: 'Reload' }))
+ expect(postMessage).toHaveBeenCalledWith({ type: 'SKIP_WAITING' })
+ // The page reloads once the new worker has taken over, and not before: the old one still serves until then.
+ expect(reload).not.toHaveBeenCalled()
+ listeners.controllerchange()
+ expect(reload).toHaveBeenCalledTimes(1)
+ vi.unstubAllGlobals()
+})
+
+test('a notice can be put away, and comes back only for the next version', async () => {
+ const { registration } = waitingRegistration()
+ render()
+ act(() => usePwa.getState().setWaiting(registration))
+ await userEvent.click(await screen.findByRole('button', { name: 'Later' }))
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
+})
diff --git a/web/src/pwa/UpdateNotice.tsx b/web/src/pwa/UpdateNotice.tsx
new file mode 100644
index 0000000..0ba1766
--- /dev/null
+++ b/web/src/pwa/UpdateNotice.tsx
@@ -0,0 +1,29 @@
+import { useTranslation } from 'react-i18next'
+import { Button } from '@/components/ui/button'
+import { usePwa } from './store'
+
+/**
+ * A line at the foot of the page that says a new version of the app is ready. The button tells the waiting worker to take
+ * over and the page reloads once it has, so nobody is switched to new files in the middle of a song.
+ */
+export default function UpdateNotice() {
+ const { t } = useTranslation()
+ const registration = usePwa((s) => s.registration)
+ const dismiss = usePwa((s) => s.dismiss)
+ if (!registration) return null
+
+ function reload() {
+ navigator.serviceWorker.addEventListener('controllerchange', () => window.location.reload(), { once: true })
+ registration?.waiting?.postMessage({ type: 'SKIP_WAITING' })
+ }
+
+ return (
+
+ {t('pwa.updateReady')}
+
+
+
+ )
+}
diff --git a/web/src/pwa/register.test.ts b/web/src/pwa/register.test.ts
new file mode 100644
index 0000000..aa34a0a
--- /dev/null
+++ b/web/src/pwa/register.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, beforeEach, expect, test, vi } from 'vitest'
+import { registerServiceWorker } from './register'
+
+type Listener = () => void
+
+/** A page with a service worker API that does what a browser does, as far as the registration goes. */
+function fakeBrowser({ controlled = true, waiting = false } = {}) {
+ const worker = { state: 'installing', listeners: [] as Listener[], addEventListener(_t: string, fn: Listener) { this.listeners.push(fn) } }
+ const registration = {
+ waiting: waiting ? { state: 'installed' } : null,
+ installing: worker as unknown,
+ listeners: {} as Record,
+ addEventListener(type: string, fn: Listener) {
+ this.listeners[type] = fn
+ },
+ }
+ const register = vi.fn(async () => registration)
+ Object.defineProperty(navigator, 'serviceWorker', { value: { register, controller: controlled ? {} : null }, configurable: true })
+ return { register, registration, worker }
+}
+
+beforeEach(() => {
+ Object.defineProperty(window, 'isSecureContext', { value: true, configurable: true })
+})
+afterEach(() => {
+ // @ts-expect-error the fake is removed again
+ delete navigator.serviceWorker
+})
+
+/** The page has loaded: the handlers that this test asked for run (those of other tests are not on the page). */
+const handlers: Array<() => void> = []
+beforeEach(() => {
+ handlers.length = 0
+ vi.spyOn(window, 'addEventListener').mockImplementation(((type: string, fn: () => void) => {
+ if (type === 'load') handlers.push(fn)
+ }) as typeof window.addEventListener)
+})
+afterEach(() => vi.restoreAllMocks())
+
+const loaded = async () => {
+ handlers.forEach((fn) => fn())
+ await Promise.resolve()
+ await Promise.resolve()
+}
+
+test('the worker is registered once the page has loaded, at the root of the app', async () => {
+ const b = fakeBrowser()
+ registerServiceWorker({ enabled: true, onWaiting: vi.fn() })
+ expect(b.register).not.toHaveBeenCalled() // the page loads first
+ await loaded()
+ expect(b.register).toHaveBeenCalledWith('/sw.js', { scope: '/' })
+})
+
+test('nothing is registered in development, on a page that is not secure, or in a browser with no workers', async () => {
+ const b = fakeBrowser()
+ registerServiceWorker({ enabled: false, onWaiting: vi.fn() })
+ Object.defineProperty(window, 'isSecureContext', { value: false, configurable: true })
+ registerServiceWorker({ enabled: true, onWaiting: vi.fn() })
+ await loaded()
+ expect(b.register).not.toHaveBeenCalled()
+
+ Object.defineProperty(window, 'isSecureContext', { value: true, configurable: true })
+ // @ts-expect-error no service worker API at all
+ delete navigator.serviceWorker
+ expect(() => registerServiceWorker({ enabled: true, onWaiting: vi.fn() })).not.toThrow()
+})
+
+test('a new version that is already waiting is announced', async () => {
+ fakeBrowser({ waiting: true })
+ const onWaiting = vi.fn()
+ registerServiceWorker({ enabled: true, onWaiting })
+ await loaded()
+ expect(onWaiting).toHaveBeenCalledTimes(1)
+})
+
+test('a new version that finishes installing while the page is open is announced, but the first one is not', async () => {
+ const b = fakeBrowser({ controlled: true })
+ const onWaiting = vi.fn()
+ registerServiceWorker({ enabled: true, onWaiting })
+ await loaded()
+ b.registration.listeners.updatefound()
+ b.worker.state = 'installed'
+ b.worker.listeners.forEach((fn) => fn())
+ expect(onWaiting).toHaveBeenCalledTimes(1)
+})
+
+test('the very first worker has nothing to announce: nobody runs an old version yet', async () => {
+ const b = fakeBrowser({ controlled: false })
+ const onWaiting = vi.fn()
+ registerServiceWorker({ enabled: true, onWaiting })
+ await loaded()
+ b.registration.listeners.updatefound()
+ b.worker.state = 'installed'
+ b.worker.listeners.forEach((fn) => fn())
+ expect(onWaiting).not.toHaveBeenCalled()
+})
+
+test('a registration that fails is no error of the app', async () => {
+ const b = fakeBrowser()
+ b.register.mockRejectedValueOnce(new Error('no'))
+ registerServiceWorker({ enabled: true, onWaiting: vi.fn() })
+ await expect(loaded()).resolves.toBeUndefined()
+})
diff --git a/web/src/pwa/register.ts b/web/src/pwa/register.ts
new file mode 100644
index 0000000..fd19085
--- /dev/null
+++ b/web/src/pwa/register.ts
@@ -0,0 +1,31 @@
+export interface RegisterOptions {
+ /** Only a build for production registers the worker; in development files change under it. */
+ enabled?: boolean
+ /** Called when a new version of the app is installed and waits for the page to say it may take over. */
+ onWaiting: (registration: ServiceWorkerRegistration) => void
+}
+
+/**
+ * Registers the service worker once the page has loaded (so that it never slows the first screen), on a page that is
+ * secure and in a browser that has workers. It says when a new version is waiting: not for the very first worker, since
+ * nobody is on an old version then. A registration that fails is no business of the app: it simply stays online-only.
+ */
+export function registerServiceWorker({ enabled = import.meta.env.PROD, onWaiting }: RegisterOptions): void {
+ if (!enabled || !('serviceWorker' in navigator) || !window.isSecureContext) return
+ window.addEventListener('load', () => {
+ void (async () => {
+ try {
+ const registration = await navigator.serviceWorker.register('/sw.js', { scope: '/' })
+ if (registration.waiting && navigator.serviceWorker.controller) onWaiting(registration)
+ registration.addEventListener('updatefound', () => {
+ const worker = registration.installing
+ worker?.addEventListener('statechange', () => {
+ if (worker.state === 'installed' && navigator.serviceWorker.controller) onWaiting(registration)
+ })
+ })
+ } catch {
+ // The app works without it.
+ }
+ })()
+ })
+}
diff --git a/web/src/pwa/store.ts b/web/src/pwa/store.ts
new file mode 100644
index 0000000..d1c0475
--- /dev/null
+++ b/web/src/pwa/store.ts
@@ -0,0 +1,14 @@
+import { create } from 'zustand'
+
+interface PwaState {
+ /** The registration whose new version waits to take over, or null. */
+ registration: ServiceWorkerRegistration | null
+ setWaiting: (registration: ServiceWorkerRegistration) => void
+ dismiss: () => void
+}
+
+export const usePwa = create((set) => ({
+ registration: null,
+ setWaiting: (registration) => set({ registration }),
+ dismiss: () => set({ registration: null }),
+}))
diff --git a/web/src/pwa/sw.test.ts b/web/src/pwa/sw.test.ts
new file mode 100644
index 0000000..1f0b821
--- /dev/null
+++ b/web/src/pwa/sw.test.ts
@@ -0,0 +1,228 @@
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { beforeEach, expect, test, vi } from 'vitest'
+
+const ORIGIN = 'https://sonda.test'
+const CODE = readFileSync(join(process.cwd(), 'public/sw.js'), 'utf8')
+
+const INDEX = ''
+const key = (r: RequestInfo | URL) => new URL(typeof r === 'string' ? r : r instanceof URL ? r.href : r.url, ORIGIN).href
+
+class FakeCache {
+ map = new Map()
+ async match(r: RequestInfo | URL) {
+ return this.map.get(key(r))?.clone()
+ }
+ async put(r: RequestInfo | URL, res: Response) {
+ this.map.delete(key(r)) // a put goes to the end, as in a real cache
+ this.map.set(key(r), res)
+ }
+ async keys() {
+ return [...this.map.keys()].map((u) => new Request(u))
+ }
+ async delete(r: RequestInfo | URL) {
+ return this.map.delete(key(r))
+ }
+}
+
+class FakeCaches {
+ stores = new Map()
+ async open(name: string) {
+ if (!this.stores.has(name)) this.stores.set(name, new FakeCache())
+ return this.stores.get(name)!
+ }
+ async keys() {
+ return [...this.stores.keys()]
+ }
+ async delete(name: string) {
+ return this.stores.delete(name)
+ }
+ async match(r: RequestInfo | URL) {
+ for (const s of this.stores.values()) {
+ const hit = await s.match(r)
+ if (hit) return hit
+ }
+ return undefined
+ }
+}
+
+type Listener = (event: unknown) => void
+
+/** Runs the worker against a fake page, a fake cache and a fake network. */
+function boot(network: (url: string, init?: RequestInit) => Response | Promise) {
+ const listeners: Record = {}
+ const caches = new FakeCaches()
+ const asked: string[] = []
+ const self = {
+ location: { origin: ORIGIN },
+ addEventListener: (type: string, fn: Listener) => (listeners[type] = fn),
+ skipWaiting: vi.fn(),
+ clients: { claim: vi.fn(async () => {}) },
+ }
+ const fetchStub = async (r: RequestInfo | URL, init?: RequestInit) => {
+ const url = key(r)
+ asked.push(url)
+ return network(url, init)
+ }
+ new Function('self', 'caches', 'fetch', CODE)(self, caches, fetchStub)
+
+ const waitUntil = async (type: string) => {
+ const waits: Promise[] = []
+ listeners[type]({ waitUntil: (p: Promise) => waits.push(p) })
+ await Promise.all(waits)
+ }
+ /** Sends a request through the worker: the response it gave, or null when it let the browser do it. */
+ const send = async (url: string, init: { method?: string; mode?: string; headers?: Record } = {}) => {
+ const request = new Request(url.startsWith('http') ? url : ORIGIN + url, { method: init.method ?? 'GET', headers: init.headers })
+ Object.defineProperty(request, 'mode', { value: init.mode ?? 'cors' })
+ let answer: Promise | null = null
+ listeners.fetch({ request, respondWith: (p: Promise) => (answer = p) })
+ return answer ? await (answer as Promise) : null
+ }
+ return { listeners, caches, asked, self, waitUntil, send }
+}
+
+const ok = (body: string, type = 'text/plain') => new Response(body, { status: 200, headers: { 'Content-Type': type } })
+const online = (url: string) => {
+ const path = new URL(url).pathname
+ // A link inside the app is answered with the page, as the server does.
+ if (path === '/' || (!path.includes('.') && !path.startsWith('/api') && !path.startsWith('/assets'))) return ok(INDEX, 'text/html')
+ if (path.startsWith('/assets/')) return ok(`file ${path}`, 'text/javascript')
+ if (path.startsWith('/api/')) return ok('{"private":true}', 'application/json')
+ return ok(`file ${path}`)
+}
+const offline = () => {
+ throw new TypeError('Failed to fetch')
+}
+
+let sw: ReturnType
+beforeEach(() => {
+ sw = boot(online)
+})
+
+const cached = async () => {
+ const out: string[] = []
+ for (const s of sw.caches.stores.values()) out.push(...(await s.keys()).map((r) => new URL(r.url).pathname))
+ return out.sort()
+}
+
+test('installing keeps the page, its scripts and styles, the manifest and the icons, and nothing else', async () => {
+ await sw.waitUntil('install')
+ expect(await cached()).toEqual(
+ ['/', '/apple-touch-icon.png', '/assets/app-1.css', '/assets/app-1.js', '/favicon.svg', '/icon-192.png', '/icon-512.png', '/icon-maskable-512.png', '/manifest.webmanifest'].sort(),
+ )
+ expect(sw.asked.every((u) => !u.includes('/api/'))).toBe(true)
+})
+
+test('a new version waits to be told, and takes over only when the page says so', async () => {
+ await sw.waitUntil('install')
+ expect(sw.self.skipWaiting).not.toHaveBeenCalled()
+ sw.listeners.message({ data: { type: 'SKIP_WAITING' } })
+ expect(sw.self.skipWaiting).toHaveBeenCalledTimes(1)
+ sw.listeners.message({ data: { type: 'SOMETHING_ELSE' } })
+ sw.listeners.message({ data: null })
+ expect(sw.self.skipWaiting).toHaveBeenCalledTimes(1)
+})
+
+test('activating drops the caches of old versions of the worker, keeps its own, and takes the open pages', async () => {
+ await sw.waitUntil('install')
+ await sw.caches.open('sonda-shell-v0')
+ await sw.caches.open('someone-elses')
+ await sw.waitUntil('activate')
+ const names = await sw.caches.keys()
+ expect(names).toContain('someone-elses')
+ expect(names).not.toContain('sonda-shell-v0')
+ expect(names.filter((n) => n.startsWith('sonda-shell-'))).toHaveLength(1)
+ expect(sw.self.clients.claim).toHaveBeenCalled()
+})
+
+test('the API is never touched: not kept, not answered, not even asked of the network by the worker', async () => {
+ await sw.waitUntil('install')
+ const before = await cached()
+ const asked = sw.asked.length
+ for (const url of ['/api/v1/albums', '/api/v1/auth/login', '/api/v1/tracks/3/stream', '/api/v1/albums/9/cover?access_token=secret', '/api']) {
+ expect(await sw.send(url)).toBeNull()
+ expect(await sw.send(url, { mode: 'navigate' })).toBeNull()
+ }
+ expect(await cached()).toEqual(before)
+ expect(sw.asked.length).toBe(asked)
+})
+
+test('only a GET to its own server is its business', async () => {
+ await sw.waitUntil('install')
+ expect(await sw.send('/assets/app-1.js', { method: 'POST' })).toBeNull()
+ expect(await sw.send('/assets/app-1.js', { method: 'PUT' })).toBeNull()
+ expect(await sw.send('https://elsewhere.example/assets/app-1.js')).toBeNull()
+ expect(await sw.send('/assets/app-1.js', { headers: { Range: 'bytes=0-99' } })).toBeNull()
+})
+
+test('a script that is kept is given at once, and one that is not is fetched and kept', async () => {
+ await sw.waitUntil('install')
+ sw.asked.length = 0
+ const hit = await sw.send('/assets/app-1.js')
+ expect(await hit?.text()).toBe('file /assets/app-1.js')
+ expect(sw.asked).toEqual([])
+ const miss = await sw.send('/assets/chunk-2.js')
+ expect(await miss?.text()).toBe('file /assets/chunk-2.js')
+ expect(sw.asked).toEqual([ORIGIN + '/assets/chunk-2.js'])
+ expect(await cached()).toContain('/assets/chunk-2.js')
+})
+
+test('a file that failed is not kept', async () => {
+ sw = boot((url) => (new URL(url).pathname === '/assets/gone.js' ? new Response('no', { status: 404 }) : online(url)))
+ await sw.waitUntil('install')
+ const res = await sw.send('/assets/gone.js')
+ expect(res?.status).toBe(404)
+ expect(await cached()).not.toContain('/assets/gone.js')
+})
+
+test('the cache of scripts does not grow without end: the oldest go', async () => {
+ await sw.waitUntil('install')
+ for (let i = 0; i < 160; i++) await sw.send(`/assets/chunk-${i}.js`)
+ const files = (await cached()).filter((p) => p.startsWith('/assets/'))
+ expect(files.length).toBeLessThanOrEqual(120)
+ expect(files).toContain('/assets/chunk-159.js')
+ expect(files).not.toContain('/assets/chunk-0.js')
+ expect(await cached()).toContain('/') // the shell stays
+})
+
+test('a link inside the app asks the server, keeps what came back, and gives the page when the server is far', async () => {
+ await sw.waitUntil('install')
+ const fresh = await sw.send('/albums/3', { mode: 'navigate' })
+ expect(fresh?.status).toBe(200)
+ expect(await fresh?.text()).toBe(INDEX)
+ sw = boot(offline)
+ await sw.caches.open('sonda-shell-v1').then((c) => c.put('/', ok(INDEX, 'text/html')))
+ const away = await sw.send('/admin/users', { mode: 'navigate' })
+ expect(away?.status).toBe(200)
+ expect(await away?.text()).toBe(INDEX)
+})
+
+test('with nothing kept and no server there is a plain page that says so, not a browser error', async () => {
+ sw = boot(offline)
+ const res = await sw.send('/', { mode: 'navigate' })
+ expect(res?.status).toBe(503)
+ expect(res?.headers.get('Content-Type')).toContain('text/html')
+ expect(await res?.text()).toContain('Sonda')
+})
+
+test('a page that the server answered with an error is not kept as the page of the app', async () => {
+ await sw.waitUntil('install')
+ sw = boot((url) => (new URL(url).pathname === '/broken' ? new Response('oops', { status: 500 }) : online(url)))
+ await sw.waitUntil('install')
+ const res = await sw.send('/broken', { mode: 'navigate' })
+ expect(res?.status).toBe(500)
+ const shell = await (await sw.caches.open('sonda-shell-v1')).match('/')
+ expect(await shell?.text()).toBe(INDEX)
+})
+
+test('other files of the app (icons, the manifest) come from the server and fall back to the kept ones; unknown ones are never kept', async () => {
+ await sw.waitUntil('install')
+ const res = await sw.send('/manifest.webmanifest')
+ expect(await res?.text()).toBe('file /manifest.webmanifest')
+ expect(await sw.send('/something.json')).not.toBeNull()
+ expect(await cached()).not.toContain('/something.json')
+ sw = boot(offline)
+ await (await sw.caches.open('sonda-shell-v1')).put('/icon-192.png', ok('kept icon'))
+ expect(await (await sw.send('/icon-192.png'))?.text()).toBe('kept icon')
+})
diff --git a/web/src/pwa/useInstall.test.tsx b/web/src/pwa/useInstall.test.tsx
new file mode 100644
index 0000000..e7810e5
--- /dev/null
+++ b/web/src/pwa/useInstall.test.tsx
@@ -0,0 +1,59 @@
+import { act, renderHook } from '@testing-library/react'
+import { beforeEach, expect, test, vi } from 'vitest'
+import { useInstall } from './useInstall'
+
+function installEvent(outcome: 'accepted' | 'dismissed' = 'accepted') {
+ const e = new Event('beforeinstallprompt', { cancelable: true }) as Event & { prompt: () => Promise; userChoice: Promise<{ outcome: string }> }
+ e.prompt = vi.fn(async () => {})
+ e.userChoice = Promise.resolve({ outcome })
+ return e
+}
+
+beforeEach(() => {
+ window.matchMedia = vi.fn().mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }) as unknown as typeof window.matchMedia
+})
+
+test('an app that the browser lets be installed says so, and installs when asked', async () => {
+ const { result } = renderHook(() => useInstall())
+ expect(result.current.available).toBe(false)
+ const e = installEvent()
+ act(() => {
+ window.dispatchEvent(e)
+ })
+ expect(e.defaultPrevented).toBe(true) // the browser does not show its own bar: the page asks when it wants
+ expect(result.current.available).toBe(true)
+ await act(async () => {
+ await result.current.install()
+ })
+ expect(e.prompt).toHaveBeenCalledTimes(1)
+ expect(result.current.available).toBe(false) // a prompt can be used once
+})
+
+test('an app that was installed has nothing to offer', () => {
+ const { result } = renderHook(() => useInstall())
+ act(() => {
+ window.dispatchEvent(installEvent())
+ })
+ expect(result.current.available).toBe(true)
+ act(() => {
+ window.dispatchEvent(new Event('appinstalled'))
+ })
+ expect(result.current.available).toBe(false)
+})
+
+test('an app that is already running as an app does not offer to be installed', () => {
+ window.matchMedia = vi.fn().mockReturnValue({ matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() }) as unknown as typeof window.matchMedia
+ const { result } = renderHook(() => useInstall())
+ act(() => {
+ window.dispatchEvent(installEvent())
+ })
+ expect(result.current.available).toBe(false)
+})
+
+test('the listeners are taken away with the page that used them', () => {
+ const remove = vi.spyOn(window, 'removeEventListener')
+ const { unmount } = renderHook(() => useInstall())
+ unmount()
+ expect(remove).toHaveBeenCalledWith('beforeinstallprompt', expect.any(Function))
+ expect(remove).toHaveBeenCalledWith('appinstalled', expect.any(Function))
+})
diff --git a/web/src/pwa/useInstall.ts b/web/src/pwa/useInstall.ts
new file mode 100644
index 0000000..702c8ad
--- /dev/null
+++ b/web/src/pwa/useInstall.ts
@@ -0,0 +1,40 @@
+import { useCallback, useEffect, useState } from 'react'
+
+/** What the browser gives to ask a person to install the app: only some browsers have it. */
+interface InstallPrompt extends Event {
+ prompt: () => Promise
+ userChoice: Promise<{ outcome: string }>
+}
+
+/**
+ * Lets a page offer to install the app when the browser allows it. The bar of the browser is kept back, so the page asks
+ * when it wants: in Settings. It is offered once, only when the app is not already running as an app, and not after it
+ * was installed.
+ */
+export function useInstall(): { available: boolean; install: () => Promise } {
+ const [prompt, setPrompt] = useState(null)
+
+ useEffect(() => {
+ const standalone = typeof window.matchMedia === 'function' && window.matchMedia('(display-mode: standalone)').matches
+ const onPrompt = (e: Event) => {
+ e.preventDefault()
+ if (!standalone) setPrompt(e as InstallPrompt)
+ }
+ const onInstalled = () => setPrompt(null)
+ window.addEventListener('beforeinstallprompt', onPrompt)
+ window.addEventListener('appinstalled', onInstalled)
+ return () => {
+ window.removeEventListener('beforeinstallprompt', onPrompt)
+ window.removeEventListener('appinstalled', onInstalled)
+ }
+ }, [])
+
+ const install = useCallback(async () => {
+ if (!prompt) return
+ await prompt.prompt()
+ await prompt.userChoice
+ setPrompt(null) // a prompt can be used once
+ }, [prompt])
+
+ return { available: prompt !== null, install }
+}