diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9bae2c7..33a1d22 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,7 @@ The workspace contains the root app (`src/`, `tests/`) and `@libras/website` (`w | `AuthStore` / `authenticate` | Credential persistence / token derivation and automatic HTTPS password fallback | | `Network` / `SubsonicClient` | Connection cancellation, normalized domain access / Subsonic protocol requests | | `Cache` | Account-scoped library, queue, images, downloads, playlists, and OPFS persistence | -| `Playback` | Queue commands, server synchronization, and playback orchestration | +| `Playback` | Local queue commands, explicit server exchange, and playback orchestration | | `AudioTransport` | Native audio lifetime, source acquisition, reactive transport state, and seeking | | `AudioPlayer` | Headless keyboard shortcuts and Media Session binding to the app-owned transport | | `Covers` / `TrackEngine` | Resource acquisition, download scheduling, and browser URL lifetimes | @@ -48,10 +48,12 @@ Routes use the bare query, for example `/webapp/?/library/artist/123#section`. E ### Persistence and account safety - Read Cache collections directly; change them through explicit methods. Session owns account details; Cache accepts an opaque account key and hashes it for storage. An undefined key creates an empty, non-persisting fallback. A defined key does not mean hydration succeeded. -- Library, queue, playlist, and image memory updates checkpoint asynchronously. Downloads instead await explicit queued/failed/completed commits in one versioned store; failed jobs require explicit Retry or a bulk Download action. Interrupted queued jobs restart from scratch, never adopting unregistered bytes. Successful byte close wins cancellation while completed metadata commits; cancellation joins that work. Unknown queued/failed job fields, including old attempts, are ignored on load and omitted on subsequent writes; orphan-file reclamation after old attempts or abrupt termination is intentionally out of scope. Offline library limits browsing/listening, not requested downloads. Do not treat visible state as proof of persistence. Unreadable download documents are preserved, not reset; readable saved files remain usable. -- Credentials use localStorage only, until disconnect. Token login stores username/token/salt; verified direct-password fallback stores the actual password. localStorage is not encrypted and is readable by same-origin scripts. Never log credentials or credential-bearing URLs. Legacy token records migrate without changing account keys; migration writeback is best-effort. -- Disconnect retains local data for offline use. Same-account reconnects reuse the live cache to preserve edits. Account changes drain old writes and retire resources before committing the new workspace. Late results must not leak into a different account. -- Startup and manual refresh pull server state. Reconnecting must not upload an offline queue automatically, and refresh must not replace a playing or paused queue. +- Library, queue, playlist, and image memory updates checkpoint asynchronously. Downloads instead await explicit queued/failed/completed commits in one versioned store; failed jobs require explicit Retry or a bulk Download action. Interrupted queued jobs restart from scratch, never adopting unregistered bytes. Successful byte close wins cancellation while completed metadata commits; cancellation joins that work. Unknown queued/failed job fields, including old attempts, are ignored on load and omitted on subsequent writes; orphan-file reclamation after old attempts or abrupt termination is intentionally out of scope. Work offline disables all server domains and pauses queued downloads, retaining durable intent. One Network-owned connection serves every domain; reconnect resumes queued, never failed jobs. All music/Downloaded is a separate browsing preference and never filters or rewrites the queue. Cached playback may continue offline; remote playback stops. Do not treat visible state as proof of persistence. Unreadable download documents are preserved, not reset; readable saved files remain usable. +- New connections default to memory-only credentials. `Session.connect(input, remember)` persists verified credentials only after workspace acceptance when explicitly opted in; credential-free identity persists separately so reload opens local data offline. Existing persisted credentials remain recognized until disconnect/explicit opt-out; do not silently remove legacy records. Token persistence stores username/token/salt; verified direct-password fallback stores the actual password. localStorage is not encrypted and is readable by same-origin scripts. Never log credentials or credential-bearing URLs. Legacy token records migrate without changing account keys; migration writeback is best-effort. Keep injected demo `AuthStore(new MemoryStorage())` supported. Remember is an app persistence choice, not browser autofill policy. +- Session acquires an exclusive Web Lock with `ifAvailable`, named from the same SHA-256 account identity as OPFS, before hydration or authenticated producers. Only one tab activates a persistent account; another is blocked, not a read-only replica. Retry is explicit after closing the owner; there is no polling/takeover. Missing Web Locks blocks activation honestly. Browser document termination releases its lock; it does not guarantee the last in-memory edit survived a crash. +- Disconnect retains local data and ownership for offline use. Same-account reconnects reuse the live cache and lease to preserve edits. Different-account preparation acquires its lease first; failures retain the original workspace. Account changes stop producers and drain old writes before releasing ownership. Disposal stops producers, checkpoints globally and cancels/drains disk operations before releasing. Deletion retains ownership even on failure. Late results must not leak into a different account. +- `Cache.flushQueue()` checkpoints only the queue document, independent of other domains’ pending/failing checkpoints. Playback progress, pause, visibility and explicit queue commands use it. Global `flush()` remains for workspace retirement/disposal. These guarantees apply to Session-owned persistent workspaces; direct Cache construction in focused storage fixtures does not acquire a lease. +- Startup and manual refresh pull library/artwork/playlist state only. The device queue is authoritative: no automatic server queue reads or writes on startup, refresh, reconnect, progress, pause or visibility changes. Local resume checkpoints remain automatic. Queue in navigation opens Now Playing even when empty/stopped; only confirmed Load server queue and explicit Save queue to server exchange queues. Empty saves confirm clearing the server queue. One exchange runs at a time; local edits remain available. Loads discard stale account/connection/revision/playback results and never autoplay. Saves send a stable starting snapshot without changing local playback. Subsonic selects by track ID, not occurrence: retain a matching local occurrence when membership matches, otherwise select the first match. Preserve unknown IDs. Demo exchange controls are disabled. - Preserve queue IDs and occurrence indexes, including duplicates and unavailable tracks. Filtering the UI must not rewrite the saved queue. - Release browser resources explicitly. The service worker caches the app shell, not API responses or music; offline audio downloads are explicit user actions. @@ -73,8 +75,9 @@ Library normalization uses structured `artists`, `displayArtist`, and `genres`, - Use semantic color/type roles and spacing/shape primitives. Containers own gaps and padding. Avoid global element resets and additional token aliases or configuration layers without a concrete consumer. - `src/ui/` contains shared presentation. Artwork delegates acquisition and object-URL ownership to Covers. Atmosphere uses CSS scroll timelines with static fallbacks for unsupported browsers and reduced motion; don't add scroll handlers for decoration. - The app scrolls the document with native page overscroll. Container queries adapt navigation and split layouts without remounting playback. Now Playing is a fullscreen native dialog with its own scrolling. Modal dialogs/backdrops suppress scroll chaining and boundary bounce without changing document overflow. -- Preserve offline filtering, ordered playback, and action scope. Library batches remain lazy. Downloads show real jobs and saved records, not invented progress. Queue rows use original occurrence indexes. -- Keep native validation, keyboard focus, actual error messages, and guarded busy actions. Never expose credentials. A completed connection must not redirect after the user leaves Settings. Update state is shared between sidebar and drawer. +- Library reuses the committed search implementation, including multi-select URL criteria and lazy batches; `/search` is an alias, not a second browse model. Routine Library arrival focuses its heading; explicit search anchors focus the input, and criteria updates preserve focus. Preserve independent downloaded filtering and ordered collection scope. Track Play now replaces with only that track; collection Play now replaces with its scope. Play next inserts after selection; Add to queue appends; neither autoplays inactive queues. Queue removal uses original occurrence indexes, stops selected removal without advancing, and focuses next/previous removal or the heading. +- Downloads show actual jobs and registered completed audio-byte totals (not origin usage). Completed-format removal commits the catalog before reclaiming bytes, preserves failures honestly, and stops/unloads an active cached source without changing queue membership. Bulk removal confirms account scope and excludes pending jobs; cancellation remains separate. +- Keep native validation, keyboard focus, actual error messages, and guarded busy actions. Never expose credentials. A completed connection must not redirect after the user leaves the focused Connect screen. Update state is shared between sidebar and drawer. - Prefer native `commandfor`/`command` invokers for dialogs and popovers. Use imperative APIs only for behavior that cannot be expressed declaratively. Popovers already have implicit invoker anchors. Preserve long-press and swipe dismissal; don't dismiss overlays on resize. - Store UI icons in `src/sprite.svg` and render through typed `Icon`; keep its name union synchronized. Use `currentColor` and accessible labels for icon-only controls. The build injects the sprite into HTML, not JavaScript. - Self-hosted fonts and their license live in `src/fonts/`; preserve optional loading and system fallbacks. Keep font preloads aligned with the faces each entry point uses. @@ -95,20 +98,25 @@ NODE_PATH=/path/to/external/node_modules PREVIEW_URL=http://127.0.0.1:5173 \ Select suites for the behavior being changed: -| Suite in `tests/browser/` | Coverage | -| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `edgerunner.test.cjs` | Shared styles, fonts, native controls, overlays, and reduced motion | -| `navigation.test.cjs` | Document scrolling, shell, playback, query routes, anchors, and optional offline navigation | -| `startup.test.cjs` | Initial Settings route, reloads, and subsequent animated navigation | -| `pwa-updates.test.cjs` | Self-hosted production builds: real worker installation, per-tab consent, repeated discovery, offline application, failed precache, and optional old-plugin migration | -| `library.test.cjs`, `search.test.cjs` | Browsing, actions, responsive layouts, and native dismissal | -| `downloads.test.cjs`, `settings.test.cjs` | Actual app/OPFS behavior with intercepted Subsonic requests | -| `atmosphere.test.cjs` | Document/dialog scroll timelines; self-contained, no server required | -| `website-cascade.test.cjs` | Script-free landing layout, keyboard/FAQ behavior, and standalone demo journeys | -| `design-improvements.test.cjs` | Compact details, full-height player, queue anchors, confirmation, gradients, popover timing, titles, and demo guidance (website server) | +| Suite in `tests/browser/` | Coverage | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `edgerunner.test.cjs` | Shared styles, fonts, native controls, overlays, and reduced motion | +| `navigation.test.cjs` | Document scrolling, shell, playback, query routes, anchors, and optional offline navigation | +| `startup.test.cjs` | Initial Connect route, reloads, and subsequent animated navigation | +| `pwa-updates.test.cjs` | Self-hosted production builds: real worker installation, per-tab consent, repeated discovery, offline application, failed precache, and optional old-plugin migration | +| `library.test.cjs`, `search.test.cjs` | Browsing, actions, responsive layouts, and native dismissal | +| `queue.test.cjs` | Explicit load/save, zero automatic queue requests, empty navigation, native confirmation focus/Escape, sanitized failures, duplicates and 320px reflow (optional `ARTIFACT_DIR` for screenshots) | +| `downloads.test.cjs`, `settings.test.cjs` | Actual app/OPFS behavior with intercepted Subsonic requests; focused connection, memory/remembered reload, queue removal focus, saved-byte removal and confirmation | +| `atmosphere.test.cjs` | Document/dialog scroll timelines; self-contained, no server required | +| `website-cascade.test.cjs` | Script-free landing layout, keyboard/FAQ behavior, and standalone demo journeys | +| `design-improvements.test.cjs` | Compact details, full-height player, queue anchors, confirmation, gradients, popover timing, titles, and demo guidance (website server) | + +`account-ownership.test.cjs` runs against the app **dev** server with real Web Locks and OPFS: two pages, blocked activation/deletion, explicit keyboard Retry after owner close, preserved duplicate/unknown queue entries and resume, unsupported-browser UI and 320px reflow. Set `ARTIFACT_DIR` to capture screenshots and evidence. The deliberate callback delay used for the Checking screenshot is fixture-only; acquisition remains native. `cache-downloads.test.cjs` exercises native OPFS close/publication boundaries and restart-from-scratch behavior by importing the owning modules. Run it against the app **dev** server; Downloads, Settings, and navigation checks can run against production preview. +`downloads.test.cjs` also decodes a small WAV fixture through the real audio element: cached seeking, durable pause/resume across reload without autoplay, browser-network-offline playback/seek, and explicit retry after a native pause. The shell reload itself is online so the suite also works against dev; offline app-shell navigation/update is covered by the production worker suites. Set `BROWSER=webkit` to run this same suite with an externally installed WebKit runtime; failures/unavailable prerequisites are not passes. Neither automation engine establishes physical iPhone background behavior. Use the [physical iPhone protocol](docs/iphone-validation.md) for Safari and installed mode. + Run the website suite against the website server, not the app: ```sh @@ -131,7 +139,7 @@ This suite owns its server and temporary `/webapp/` production builds; no previe NODE_PATH=/path/to/external/node_modules node --test tests/browser/pwa-updates.test.cjs ``` -It uses real generated workers, pre-hash fixture-only document markers, and native events/UI approval. It checks fresh installation, two-tab consent, C/D discovery in an unreloaded B document, offline application, failed-precache recovery, and preexisting waiting updates without clearing storage between versions. Temporary builds, contexts, browser, and server are cleaned up; root/website outputs are untouched. Logs include document tokens, preserved URLs, worker hashes, and native transitions. +It uses real generated workers, pre-hash fixture-only document markers, and native events/UI approval. It checks fresh installation, two-tab consent, C/D discovery in an unreloaded B document, offline application, failed-precache recovery, preexisting waiting updates, and local queue/resume preservation without autoplay after an approved update, without clearing storage between versions. Temporary builds, contexts, browser, and server are cleaned up; root/website outputs are untouched. Logs include document tokens, preserved URLs, worker hashes, and native transitions. Old-plugin migration is explicitly skipped unless `PWA_OLD_DIST` points to an untouched production artifact built at `/webapp/`. To reproduce the original baseline without changing this checkout: diff --git a/README.md b/README.md index 01412ae..c9b6638 100644 --- a/README.md +++ b/README.md @@ -12,17 +12,20 @@ Libras is a browser-based minimalistic music player that connects to your own mu ## Features -- Browse artists, albums, and tracks. +- Browse and search artists, albums, and tracks together in Library, with shareable multi-select type filters. Older Search links keep their criteria. - Stream music from your own server. - Download music for offline playback and manage it in Settings → Downloads. -- Restore your playback queue and position between sessions. +- Restore this device’s playback queue and position between sessions, without autoplay. +- Explicitly Load server queue or Save queue to server from Queue in navigation. Startup, reconnect, library refresh and playback never exchange server queues. Loading confirms replacement and stops playback only after a valid result arrives; failed/stale loads leave local state intact. Saving an empty queue confirms clearing the server queue. Duplicate and unavailable IDs are retained; Subsonic selection uses a track ID, so duplicate occurrences are ambiguous (the local occurrence is retained when membership matches, otherwise the first match is selected). The demo has no server queue exchange. - Install as a standalone web app. ## Get started 1. Open [Libras](https://libras-music.app/webapp/). 2. Connect to your music server with your server address, username, and password. -3. Browse your library and start listening. +3. Browse or search Library and start listening. Settings links back to the focused connection screen for sign-in. + +**Play now** replaces the queue with that track only, or the chosen collection in its current scope. **Play next** inserts after the selected occurrence; **Add to queue** appends. Neither starts an inactive queue. Queue removal preserves other occurrences (including duplicates and unavailable tracks); removing the selected occurrence stops playback without choosing a replacement. Just trying it out? Connect to the [Navidrome demo server](https://demo.navidrome.org/) using `https://demo.navidrome.org` as the server address and `demo` as both the username and password. @@ -30,13 +33,15 @@ You'll need a reachable **HTTPS server with a Subsonic-compatible API**, such as ### Browser support -Safari 26.0 or newer is required; older Safari versions are not supported. The app uses native URLPattern and OPFS writable files. Safari 26.0–26.1 load Navigation API and invoker commands polyfills on demand; Safari 26.2+ use the native APIs. The dialog `closedby` polyfill and relative `rgb()` colors remain necessary for Safari 26. The standalone styleguide uses native browser features without polyfills. +Safari 26.0 or newer is required; older Safari versions are not supported. The app uses native URLPattern, OPFS writable files, and Web Locks. Without Web Locks, account activation is blocked rather than risking conflicting writes. Safari 26.0–26.1 load Navigation API and invoker commands polyfills on demand; Safari 26.2+ use the native APIs. The dialog `closedby` polyfill and relative `rgb()` colors remain necessary for Safari 26. The standalone styleguide uses native browser features without polyfills. ### Authentication and device storage Libras tries salted token authentication first; your password stays in the browser for that attempt. Only a structured server rejection of token authentication (Subsonic code 41 or 42) automatically retries the same username and password over HTTPS, including on localhost. Invalid credentials, connection failures, and other errors never trigger a password retry. -Credentials persist in **localStorage** until you disconnect. Token login saves the username, token, and salt, not your password. Successfully verified direct-password login saves the actual password and sends it with subsequent requests, including artwork and streaming URLs. HTTPS encrypts transport, not localStorage; scripts running on the app's origin and anyone with access to your browser profile can read saved credentials. Use a trusted device and server, and disconnect on shared devices. Disconnect removes credentials but retains your offline account, music, and queue. +New connections keep credentials **in memory only** by default. Reloading retains your credential-free offline identity, music, and queue, but requires signing in again for server access. Select **Remember this device** only on a trusted device to save verified credentials in localStorage after the account workspace is accepted. Existing remembered credentials remain recognized until you disconnect or explicitly opt out; they are not silently deleted on startup. This choice controls Libras storage, not your browser’s password manager. + +Remembered token login saves username/token/salt, not your password. Verified direct-password fallback saves the actual password and sends it with subsequent requests, including artwork and streaming URLs. HTTPS encrypts transport, not localStorage; same-origin scripts and anyone with access to your browser profile can read saved credentials. Disconnect removes credentials but retains offline identity/data unless you also choose local deletion. ## Install @@ -46,15 +51,17 @@ You can use Libras in your browser or install it as a standalone web app: - **Android:** Choose **Install app / Add to home screen** from the browser menu. - **Desktop:** Use the browser's install option, where available. -Installation options vary by browser and device. Offline storage and background playback have not yet been verified on iOS. +Installation options vary by browser and device. Offline storage and background playback have not yet been verified on iOS. Physical iPhone validation is **NOT PERFORMED / PENDING DEVICE ACCESS**; see the [Safari and installed-mode validation protocol](docs/iphone-validation.md). ## Listen offline -Download music while online, then switch to **Offline Library** to listen without a connection. +Download music while connected, then choose **Work offline** in navigation or Settings. This turns off all server access, stops remote playback and pauses requested downloads while retaining their queued intent. Cached playback can continue. Choose **Connect** to resume queued downloads; failed jobs require Retry. Reconnecting never loads or saves the server queue. + +**Library scope → All music / Downloaded** is independent of the connection. Downloaded filters browsing and search without disconnecting or changing your queue, position or active audio. All music can browse saved metadata offline; uncached tracks remain visible as unavailable. -- **Manage downloads:** Settings → Downloads. +- **Manage downloads:** Downloads in navigation (also linked from Settings). Totals count registered completed audio bytes, not total browser storage. Remove individual formats, or confirm **Remove all downloaded music** for this account. Queue membership and server files stay unchanged; pending jobs use the separate Cancel downloads action. Removing an active cached source stops/unloads it. Catalog deletion must succeed before bytes are reclaimed; failures remain visible for retry. - **Refresh library:** Automatic when opening online, or via Settings → Refresh library. -- **Disconnect:** Clears credentials and optionally deletes this account’s local cache and downloads. Remembered identity, preferences, other accounts and server data are unchanged. Close other Libras tabs before deleting local data. +- **Disconnect:** Clears credentials and optionally deletes this account’s local cache and downloads. Remembered identity, preferences, other accounts and server data are unchanged. Only one tab can open an account’s local data at a time, including while deleting it. A second tab is blocked: close the owning tab, then select **Retry**. There is no automatic takeover or live cross-tab queue replication. - **Storage:** Each server/account has its own offline library, saved only in this browser on this device. **Clearing site data deletes it.** ## App updates diff --git a/docs/iphone-validation.md b/docs/iphone-validation.md new file mode 100644 index 0000000..8ef8b87 --- /dev/null +++ b/docs/iphone-validation.md @@ -0,0 +1,28 @@ +# Physical iPhone playback and recovery validation + +**Result: NOT PERFORMED / PENDING DEVICE ACCESS.** No physical iPhone is available in the automated environment. Desktop Chromium or automated WebKit results do not establish iPhone background playback, lock-screen integration, or installed-mode behavior. + +Run this protocol separately in Safari and Add to Home Screen installed mode, on the same tested HTTPS origin. Use a disposable account and retain sanitized observations; never include credentials or credential-bearing media URLs. + +## Record + +- Date/tester, device model, iOS build, Safari version, browser or installed mode. +- App commit/build, origin/base path, server/version and CORS setup. +- Raw audio codec/container and duration; transcoded format and server settings. +- For each step: PASS / FAIL / NOT RUN, actual behavior, timestamps, sanitized logs, and reproduction steps. Do not replace this pending result without device evidence. + +## Protocol (both modes) + +1. Connect to a reachable HTTPS/CORS-enabled server. Play supported raw audio, then a source requiring transcoding fallback. Verify pause, resume, seek forward/backward and track changes. Record any activation-required error and explicit Play retry. +2. Check Media Session title/artwork, lock-screen play/pause/next/previous, screen lock and background playback. Navigate within the app and return from another app; confirm queue/position and that audio is not duplicated. +3. Interrupt with a call/alarm/another audio app. Switch speaker/headphones/Bluetooth output, disconnect the output, then return to the foreground and retry explicitly if required. Record OS-specific pause/resume behavior rather than assuming automatic recovery. +4. Download music to completion. Choose Work offline and airplane mode. Play and seek cached audio, including after pausing/resuming. Confirm uncached queue entries remain visible/removable and unavailable, without silently rewriting the queue. +5. Pause at a known position, background/close and relaunch. Verify saved selection/position, **no autoplay**, then explicit Play offline. Repeat in installed mode. Distinguish normal relaunch from OS termination/eviction; storage and the last uncheckpointed edit are not guaranteed after eviction. +6. Interrupt an active queued download by Work offline, network loss, and app termination (separate trials). Reconnect explicitly. Queued jobs restart from scratch; failed jobs require Retry. Verify playable completed files, correct byte totals, and no phantom completed records or corrupt audio. +7. Lose the network during remote playback/load/seek. Verify honest failure/interruption and explicit recovery after reconnect. Confirm cached playback still works and reconnection never replaces the local queue. Test explicit Load/Save server queue separately; load must not autoplay. +8. With an update waiting, decline/dismiss first: no reload. Approve Update now: only this approving document reloads, route and durable local queue/position survive, playback does not autoplay. Repeat with an already-installed update while offline and a second unapproved tab. +9. Open the same account in another tab: activation is blocked. Close the owner, choose Retry, and verify local queue/resume. Disconnect without deletion: credentials disappear but offline music remains. Reconnect, cancel/Escape local removal, then confirm deletion: this account's bytes disappear and active cached audio unloads; other accounts/server data remain unchanged. + +## Evidence and limitations + +Attach one result table per mode and raw/transcoded source, with failures and unrun steps explicit. Include sanitized console/service-worker observations where available, output-device details, time spent backgrounded/locked, and any OS eviction or termination. A successful short run is not a guarantee of indefinite iOS background execution or durable storage retention. diff --git a/src/_album.svelte b/src/_album.svelte index c0cfdb3..c4a198b 100644 --- a/src/_album.svelte +++ b/src/_album.svelte @@ -1,5 +1,6 @@ + +Connect | {appName} +
+

Connect your music server

+

Use an HTTPS OpenSubsonic-compatible server that allows this app through CORS.

+ {#if demo} +

The demo uses a fixed library. Reload to reconnect.

+ + {:else if session.auth} +

+ {session.offlineMode ? "Working offline" : "Connected"} · {session.auth.username}@{new URL( + session.auth.host, + ).host} +

+ + Account settings + {:else} +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+

+ Keep sign-in credentials in this browser after closing it. Use only on a trusted device. +

+

+ Without remembering, you’ll need to sign in again after reloading. Downloaded music stays on + this device. +

+ {#if session.libraryProgress}

+ {session.libraryProgress.albums.toLocaleString()} albums · {session.libraryProgress.tracks.toLocaleString()} + tracks +

{/if} + {#if session.error}

+ {session.error} +

{/if} +
+ + {#if session.busy}{/if} +
+
+ {/if} + Open library +
diff --git a/src/_downloads.svelte b/src/_downloads.svelte index cf10fd2..f40799e 100644 --- a/src/_downloads.svelte +++ b/src/_downloads.svelte @@ -5,16 +5,49 @@ import type { Cache } from "./cache.svelte"; import type { Covers } from "./covers.svelte"; import type { TrackEngine } from "./track.svelte"; + import type { Playback } from "./playback.svelte"; interface Props { cache: Cache; covers: Covers; trackEngine: TrackEngine; loading: boolean; + playback: Playback; appName?: string; } - let { cache, covers, trackEngine, loading, appName = "Libras" }: Props = $props(); + let { cache, covers, trackEngine, playback, loading, appName = "Libras" }: Props = $props(); + let removing = $state(false); + let removalMessage = $state(""); + const completed = $derived( + [...cache.downloads].filter(([, entry]) => entry.status === "completed"), + ); + const savedBytes = $derived( + completed.reduce((sum, [, entry]) => sum + (entry.status === "completed" ? entry.size : 0), 0), + ); + async function remove(keys: string[]) { + if (removing || loading) return; + removing = true; + removalMessage = ""; + const workspace = cache; + playback.unloadDownloadedTrack( + new Set( + keys.flatMap((key) => { + const entry = workspace.downloads.get(key); + return entry ? [entry.track.id] : []; + }), + ), + ); + try { + await workspace.removeDownloads(keys); + if (workspace === cache) removalMessage = "Downloaded music removed. Queue unchanged."; + } catch { + if (workspace === cache) + removalMessage = "Could not remove downloaded music. Please try again."; + } finally { + removing = false; + } + } const canceling = $derived(trackEngine.cancelingDownloads); const failed = $derived( @@ -27,7 +60,7 @@ for (const entry of cache.downloads.values()) { if (entry.status === "completed") { downloaded.add(entry.track.id); - } else { + } else if (entry.status === "queued") { pending.add(entry.track.id); } } @@ -47,7 +80,7 @@ } async function cancelAll() { - if (loading || canceling || !counts.pending) return; + if (loading || canceling || (!counts.pending && !failed.length)) return; try { await trackEngine.cancelDownloads(); } catch { @@ -85,25 +118,42 @@

Downloads

{counts.downloaded} - {counts.downloaded === 1 ? "track" : "tracks"} available for offline listening, {counts.pending} - pending + {counts.downloaded === 1 ? "track" : "tracks"} downloaded · {sizeFormatter.format( + savedBytes / 1_000_000, + )} downloaded audio +

+

+ {counts.pending} pending · {failed.length} failed

+ {#if trackEngine.waitingForConnection && trackEngine.downloadCount} +

Paused while working offline

+ {/if}
+
+ {#if removalMessage}

{removalMessage}

{/if} {#if cache.reportingError} @@ -155,7 +205,7 @@ data-variant="secondary" data-size="text" aria-label={`Retry download of ${entry.track.title} (${entry.format.toUpperCase()})`} - disabled={loading || canceling} + disabled={loading || removing || canceling} onclick={() => { void trackEngine.download(entry.track.id, { format: entry.format }); }}>Retry + {/if} @@ -188,3 +247,40 @@ {/if} + + +
+

Remove all downloaded music?

+

+ Remove {counts.downloaded} + {counts.downloaded === 1 ? "track" : "tracks"} · {sizeFormatter.format( + savedBytes / 1_000_000, + )} downloaded audio from this account on this device. Queue membership and server files stay unchanged. + Pending downloads are not removed; use Cancel downloads separately. +

+
+ + +
+
+
diff --git a/src/_library.svelte b/src/_library.svelte index 297f8ad..372b05c 100644 --- a/src/_library.svelte +++ b/src/_library.svelte @@ -1,297 +1,7 @@ -Your library | {appName} - -
-

Your library

- {#if session.loadingAfterConnect} -
- -

Loading your library…

- -
- {:else if libraryAvailable} -
- {#if libraryError} -
-

Library needs attention

-

- {libraryError} -

-

Available music is still listed below.

- -
- {/if} -
-

Artists

- -
- {#if visibleArtists.length > 0} -
- {#each artistPage as artist (artist.id)} - - {/each} -
- {#if artistPage.length < visibleArtists.length} - {#key artistLimit} - - - {/key} - {/if} - {:else if !loading} -
-

- {offlineMode ? "No downloaded artists." : "No artists found."} -

-

- {offlineMode - ? "Download music from the library to listen offline." - : "Your server's artists will appear here after synchronization."} -

-
- {/if} -
- {:else if !loading} -
-

- {libraryError ? "Library unavailable" : "Connect your library"} -

-

- {libraryError || "Add your music server to start listening."} -

-
- {#if libraryError && session.auth && !offlineMode} - - {/if} - Open settings -
-
- {/if} -
- - - - {@render artistActions("artist-menu", false)} - - - - -{#snippet artistActions(id: string, popover: boolean)} -
-
-
- -

{menuArtist?.name}

-
- -
-
- - - - -
-
-{/snippet} - - + diff --git a/src/_search.svelte b/src/_search.svelte index 097d40c..0e3625c 100644 --- a/src/_search.svelte +++ b/src/_search.svelte @@ -20,7 +20,7 @@ for (const type of searchTypes) if (types.includes(type)) parameters.append("type", type); if (query) parameters.set("q", query); const suffix = parameters.toString(); - return `?/search${suffix ? `&${suffix}` : ""}`; + return `?/library${suffix ? `&${suffix}` : ""}`; } const searchGroups = ["Artists", "Albums", "Tracks"] as const; @@ -142,6 +142,15 @@ -Search | {appName} +Library | {appName} -
-

Search

+
+

Library

+
-
@@ -356,6 +361,7 @@ {/each}
+ {#if playback.queueMessage}

{playback.queueMessage}

{/if} {#if libraryError}

Library needs attention

@@ -369,7 +375,15 @@
{/if}
- {#if !session.localReady && index.size === 0} + {#if session.loadingAfterConnect} +
+ +

Loading your library…

+ +
+ {:else if !session.localReady && index.size === 0}

Loading your library…

@@ -379,15 +393,15 @@

{cache.savedAt === undefined ? "Connect your library" - : session.offlineMode - ? "No downloaded music to search." + : session.downloadedOnly + ? "No downloaded music." : "Your library is empty."}

{cache.savedAt === undefined ? "Add your music server to start searching." - : session.offlineMode - ? "Download music from the library to search offline." + : session.downloadedOnly + ? "Choose All music to browse all saved metadata." : "Your music will appear here after synchronization."}

@@ -416,69 +430,112 @@

{group}

- +
-
+
{#each records as record (record.id)} - {@const track = group === "Tracks" ? cache.tracks.get(record.id) : undefined} -
+
+

Connection

+ {#if session.auth} + + {:else}Connect{/if} +

+ {session.offlineMode + ? "Server access is off. Requested downloads are paused." + : "Server access is on. Choose Downloaded in Library scope to browse saved music without disconnecting."} +

+ View downloads +
+
+ {@render children?.()} +
{@render disconnectConfirmation("disconnect-dialog")} - - {#snippet disconnectConfirmation(id: string)} -
+

Disconnect from server

Would you also like to clear this account’s data and downloads from this device? Server data @@ -119,22 +197,21 @@

- + />
Cancel {/snippet} - -
-
-

Settings

- -
-
-

Music server

-
-

- - {#if connectionLoading} - - {:else} - - {/if} - - {#if connectionLoading && session.libraryProgress} - - {session.libraryProgress.albums.toLocaleString()} albums · {session.libraryProgress.tracks.toLocaleString()} - tracks - - {:else} - - - {connectionLabel} - {#if session.auth && !connectionLoading} - · - {/if} - - {#if session.auth && !connectionLoading} - {session.auth.username}@{serverAddress} - {/if} - - {/if} -

- {#if session.error} -

{session.error}

- {/if} -
- - {#if session.refreshError} -
-

Synchronization needs attention

-

{session.refreshError}

-

Your existing library is still available.

-
- {/if} - - {#if cleaning} -

Deleting local data…

- {:else if !session.auth && demo} -

- This demo uses a fixed music library and cannot connect to other servers. Reload to - reconnect to the demo. -

-
- -
- {:else if !session.auth} -
-

- Connect to your Navidrome or another OpenSubsonic-compatible server to browse your - library and stream music. -

-
- - -
-
- - -
-
- - -
-
- - {#if session.busy} - - {/if} -
-
- {:else} -
-

- {#if demo} - This demo uses a fixed music library. Disconnect stops streaming; reload to - reconnect. Choose whether to keep its local data. - {:else} - Disconnect to switch users or servers. Choose whether to keep this account’s local - data. - {/if} -

-
- - - -
-
- {/if} -
- -
-
-

- is {session.offlineMode - ? "on" - : "off"} -

- void session.setOfflineMode(event.currentTarget.checked)} - /> -
-

- {#if !session.auth} - {demo - ? "Reload the demo to browse online. Any previews you kept remain available." - : "Connect to a server to browse online. Any music you kept remains available."} - {:else if session.offlineMode} - Showing downloaded music only. Turn this off to browse and stream {demo - ? "demo previews" - : "from your server"}. - {:else} - Browse your full library and stream {demo ? "demo previews" : "from your server"}. Turn - this on to show downloaded music only. - {/if} - Requested downloads continue when connected, including with Offline library on. -

- -
-
- - {@render children?.()} -
-
diff --git a/src/account-ownership.ts b/src/account-ownership.ts new file mode 100644 index 0000000..4d61327 --- /dev/null +++ b/src/account-ownership.ts @@ -0,0 +1,41 @@ +import { hashAccountKey } from "./cache.svelte"; + +export class AccountOwnershipError extends Error { + constructor(readonly reason: "blocked" | "unsupported") { + super( + reason === "blocked" + ? "This account is open in another tab" + : "This browser cannot safely open this account’s local data.", + ); + } +} + +/** One browser-managed exclusive lease, never queued or taken over. */ +export async function acquireAccountOwnership(key: string): Promise<() => Promise> { + if (!navigator.locks) throw new AccountOwnershipError("unsupported"); + const name = `libras-account:${await hashAccountKey(key)}`; + let release!: () => void; + const held = new Promise((resolve) => { + release = resolve; + }); + let accept!: (release: () => Promise) => void; + let reject!: (error: unknown) => void; + const acquired = new Promise<() => Promise>((resolve, fail) => { + accept = resolve; + reject = fail; + }); + const request = navigator.locks.request( + name, + { mode: "exclusive", ifAvailable: true }, + async (lock) => { + if (!lock) throw new AccountOwnershipError("blocked"); + accept(async () => { + release(); + await request; + }); + await held; + }, + ); + void request.catch(reject); + return acquired; +} diff --git a/src/app.svelte b/src/app.svelte index b4c2c69..77ccad8 100644 --- a/src/app.svelte +++ b/src/app.svelte @@ -1,6 +1,6 @@ -{#if player} - = 0 && cache.queue.position > 0)} - hasNext={hasNextTrack} - onprevious={() => playback.previous()} - onnext={() => playback.next()} - /> -{/if} += 0 && cache.queue.position > 0)} + hasNext={hasNextTrack} + onprevious={() => playback.previous()} + onnext={() => playback.next()} +/> {#snippet settingsRoute()} @@ -155,7 +144,7 @@ {#snippet downloadsRoute()} - + {/snippet} {#snippet libraryRoute()} @@ -163,9 +152,9 @@ {/snippet} -{#snippet searchRoute()} +{#snippet connectRoute()} - + {/snippet} {#snippet artistRoute(params: RouteParams)} @@ -177,7 +166,7 @@ {session} {playback} {appName} - playbackState={playbackLoading ? "loading" : player?.playing ? "playing" : "paused"} + playbackState={playbackLoading ? "loading" : player.playing ? "playing" : "paused"} /> {/snippet} @@ -190,7 +179,7 @@ {session} {playback} {appName} - playbackState={playbackLoading ? "loading" : player?.playing ? "playing" : "paused"} + playbackState={playbackLoading ? "loading" : player.playing ? "playing" : "paused"} /> {/snippet} @@ -208,23 +197,26 @@ {#snippet navigation()} +
+

+ {session.blockedAccount + ? "Account not active" + : session.busy + ? "Connecting…" + : offlineMode + ? "Working offline" + : "Connected"} +

+ {#if session.busy} + + {:else if session.auth} + + {:else} +
navigationDrawer?.close()}>Connect + {/if} + {#if offlineMode}

+ Server access is off. Requested downloads are paused. +

{/if} +
{#if appUpdate?.message}
@@ -302,7 +325,7 @@ {@render brand()}
{@render actions()} - +
{/if}
- {#if initialized} + {#if session.blockedAccount} +
+
+

+ {session.ownershipIssue === "unsupported" + ? "This browser cannot safely open this account’s local data." + : "This account is open in another tab"} +

+

+ {session.blockedAccount.username} · {session.blockedAccount.host} +

+

+ {session.ownershipIssue === "unsupported" + ? "Web Locks browser support is required to protect your local data." + : "Close the other Libras tab, then retry."} +

+

+ {session.error.startsWith("This account is still") ? session.error : ""} +

+ {#if session.ownershipIssue !== "unsupported"} + + {/if} + { + if (session.busy) event.preventDefault(); + else session.chooseAnotherAccount(); + }}>Use another account +
+
+ {:else if initialized} {/if}
- + {#if hasErrors}
diff --git a/src/cache.svelte.ts b/src/cache.svelte.ts index f4bc5bd..4e55cfe 100644 --- a/src/cache.svelte.ts +++ b/src/cache.svelte.ts @@ -104,7 +104,7 @@ function serial() { }; } -async function hash(key: string) { +export async function hashAccountKey(key: string) { const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key)); return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); } @@ -198,8 +198,12 @@ class Disk { } } - async removeBinary(fileName: string) { - await (await this.files()).removeEntry(fileName).catch(() => {}); + removeBinary(fileName: string) { + return this.#observe( + (async () => { + await (await this.files()).removeEntry(fileName).catch(() => {}); + })(), + ); } /** Concrete byte I/O only. Successful close is the cancellation boundary. */ @@ -856,6 +860,25 @@ class DownloadStore { ); } + /** Commit catalog deletion before reclaiming registered completed bytes. Pending intent is separate. */ + removeDownloads(keys: readonly string[]) { + return this.#downloadOperation(() => + this.#downloadSerial(async () => { + await this.#loadDownloads(); + const records = new Map(this.downloads); + const files: string[] = []; + for (const key of keys) { + const record = records.get(key); + if (record?.status !== "completed") continue; + files.push(record.fileName); + records.delete(key); + } + await this.#writeDownloads(records); + for (const fileName of files) await this.#requireDisk().removeBinary(fileName); + }), + ); + } + /** Caller freezes, aborts and joins workers before removing all unfinished intent. */ cancelPendingDownloads() { return this.#downloadOperation(() => @@ -1147,7 +1170,7 @@ export class Cache { * Keys are opaque identities; hashing and storage addressing stay internal. */ constructor(key?: string) { this.key = key; - this.#disk = key === undefined ? undefined : new Disk(hash(key)); + this.#disk = key === undefined ? undefined : new Disk(hashAccountKey(key)); this.#library = new CheckpointStore(this.#disk, { document: "library", initial: () => prepareLibrary(null), @@ -1207,7 +1230,7 @@ export class Cache { return this.#library.value.savedAt; } - /** Clear only this account's OPFS data. Other tabs must be closed first. */ + /** Clear only this account's OPFS data. Session retains ownership throughout. */ clear(): Promise { if (this.#clearing) return this.#clearing; const disk = this.#disk; @@ -1278,6 +1301,22 @@ export class Cache { ); } + /** Queue durability is independent of every other domain. */ + flushQueue(): Promise { + return this.#queue.flush(); + } + + /** Stop disk publication after producers have stopped and final checkpoints settled. */ + async retire() { + await this.#clearing?.catch(() => {}); + try { + await this.flush(); + } finally { + this.#disk?.cancel(); + await this.#disk?.drain(); + } + } + /** Checkpoint independent documents, waiting for every attempt before reporting failure. */ async flush(): Promise { const results = await Promise.allSettled([ @@ -1417,6 +1456,10 @@ export class Cache { return this.#downloads.downloads; } + removeDownloads(keys: readonly string[]) { + return this.#downloads.removeDownloads(keys); + } + readDownload( trackId: string, format: DownloadFormat, diff --git a/src/network.svelte.ts b/src/network.svelte.ts index a47ec6f..fdc9087 100644 --- a/src/network.svelte.ts +++ b/src/network.svelte.ts @@ -647,15 +647,8 @@ export class Network { return result; } - /** Open authenticated access. A supplied signal owns an independent lifetime, - * including while browsing is offline; otherwise Network owns browsing access. */ - open(auth: Auth, signal?: AbortSignal) { - if (signal) { - signal.throwIfAborted(); - const connection = this.#createConnection(auth); - signal.addEventListener("abort", () => connection.client.abort(), { once: true }); - return this.#access(connection); - } + /** Open authenticated access within the single Network-owned lifetime. */ + open(auth: Auth) { if (this.#mode === "offline") throw new Error("Network access is offline."); const connection = this.prepare(auth); return this.accept(connection); diff --git a/src/playback.svelte.ts b/src/playback.svelte.ts index 47101c5..39ef956 100644 --- a/src/playback.svelte.ts +++ b/src/playback.svelte.ts @@ -50,7 +50,7 @@ function toRemoteQueue(local: Immutable): RemoteQueue { }; } -/** Owns queue commands, transport coordination and server synchronization. +/** Owns local queue commands, transport coordination and explicit server exchange. * Cache remains the authoritative queue and owns local durability; AudioTransport owns audio. */ export class Playback { #selection: CacheSelection; @@ -61,18 +61,15 @@ export class Playback { #cleanup?: () => void; #selectedTrackId?: string; #sourceIsCached = false; - #connection?: QueueConnection; - #refreshPending?: Promise; - #refreshController?: AbortController; - #uploadTail: Promise = Promise.resolve(); + #connection = $state.raw(); + #exchangeBusy = $state<"load" | "save" | undefined>(); + #exchangeMessage = $state(""); + #queueMessage = $state(""); + #connectionVersion = 0; + #activityVersion = 0; #queueError = $state.raw(); #activity: PlaybackActivity = "inactive"; #lastProgressFlush = 0; - // Reconnect/progress must not replace a remote queue with an offline one. - // Only server adoption or an explicit replacement grants upload permission. - #uploadAllowed = false; - #uploadPending = false; - #syncVersion = 0; #destroyed = false; #saveTimer?: ReturnType; @@ -85,6 +82,9 @@ export class Playback { get #localQueue() { return this.#selection.cache?.queue ?? emptyQueue; } + get queueMessage() { + return this.#queueMessage; + } get queueError() { return this.#queueError; } @@ -107,7 +107,8 @@ export class Playback { /** Session calls this after selecting/loading local data. */ activate() { if (this.#destroyed) return; - this.#resetSync(); + this.#queueMessage = ""; + this.#invalidateExchange(); this.#activity = "inactive"; this.#lastProgressFlush = 0; this.#syncSelection(); @@ -115,7 +116,7 @@ export class Playback { setConnection(connection: QueueConnection | undefined) { if (this.#destroyed || connection === this.#connection) return; this.#connection = connection; - this.#resetSync(); + this.#invalidateExchange(); } setPosition(position: number) { if (!this.#player || this.#destroyed) return; @@ -214,6 +215,7 @@ export class Playback { return; } if (!this.#canPlay(this.#localQueue.index)) return; + this.#activityVersion++; this.#setActivity("active"); if (player.status !== "idle") await player.resume(); else { @@ -246,10 +248,9 @@ export class Playback { if (index >= 0 && index === this.#localQueue.index) await this.toggle(); else await this.playIndex(index); } - /** Replace the queue without starting audio. Explicit replacements permit uploads - * on this connection; progress alone never promotes an offline queue. */ + /** Replace the local queue without starting audio. */ setQueue(state: QueueState) { - this.#changeQueue(state, { replace: true }); + this.#changeQueue(state); } async replaceQueueAndPlay(tracks: readonly string[], startIndex = 0) { if (!tracks.length) { @@ -257,23 +258,33 @@ export class Playback { return; } const index = Math.max(0, Math.min(startIndex, tracks.length - 1)); - this.#changeQueue({ tracks, index, position: 0 }, { replace: true, restart: true }); + this.#changeQueue({ tracks, index, position: 0 }, { restart: true }); if (Number.isInteger(index)) await this.play(); } async enqueue(tracks: readonly string[], placement: "next" | "last") { - if (!tracks.length) return; + if (this.#destroyed || !tracks.length) return; const queue = this.#localQueue; - if (!queue.tracks.length) await this.replaceQueueAndPlay(tracks); - else { - const index = placement === "next" ? queue.index + 1 : queue.tracks.length; - this.setQueue({ - ...queue, - tracks: [...queue.tracks.slice(0, index), ...tracks, ...queue.tracks.slice(index)], - }); - } + const index = placement === "next" ? queue.index + 1 : queue.tracks.length; + this.setQueue({ + ...queue, + tracks: [...queue.tracks.slice(0, index), ...tracks, ...queue.tracks.slice(index)], + }); + this.#queueMessage = "Added to queue"; + } + removeQueueIndex(index: number) { + const queue = this.#localQueue; + if (!Number.isInteger(index) || index < 0 || index >= queue.tracks.length) return; + this.#changeQueue( + { + tracks: queue.tracks.filter((_, occurrence) => occurrence !== index), + index: index === queue.index ? -1 : index < queue.index ? queue.index - 1 : queue.index, + position: index === queue.index ? 0 : queue.position, + }, + { restart: index === queue.index }, + ); } clearQueue() { - this.#changeQueue({ tracks: [], position: 0 }, { replace: true, restart: true }); + this.#changeQueue({ tracks: [], position: 0 }, { restart: true }); } async playIndex(index: number) { if ( @@ -304,6 +315,17 @@ export class Playback { // Seeking a restored queue edits its resume point without loading audio. if (this.#player?.status !== "idle") await this.#player?.seek(position); } + /** Removing saved bytes must release an active cached source without editing the queue. */ + unloadDownloadedTrack(trackIds: ReadonlySet) { + if ( + this.track && + trackIds.has(this.track.id) && + (this.#sourceIsCached || + this.#player?.status === "loading" || + this.#player?.status === "seeking") + ) + this.suspend(); + } suspendNetwork() { if ( !this.#sourceIsCached || @@ -324,7 +346,8 @@ export class Playback { ); } - #changeQueue(state: QueueState, { replace = false, restart = false } = {}) { + #changeQueue(state: QueueState, { restart = false } = {}) { + this.#queueMessage = ""; const cache = this.#selection.cache; if (!cache || this.#destroyed) return; const requestedIndex = state.index ?? -1; @@ -335,9 +358,7 @@ export class Playback { const index = validIndex ? requestedIndex : -1; const position = index >= 0 && Number.isFinite(state.position) ? Math.max(0, state.position) : 0; - if (replace) this.#uploadAllowed = this.#hasConnection(cache); cache.setQueue({ tracks: state.tracks, index, position }); - this.#queueEdited(cache); this.#syncSelection(restart); this.#scheduleQueueFlush(); } @@ -347,7 +368,6 @@ export class Playback { position = Math.max(0, position); if (position === cache.queue.position) return; cache.setQueue({ ...cache.queue, position }, { checkpoint: true }); - this.#queueEdited(cache); // A clock update never changes selection, but metadata may have removed the // selected track since playback began. Preserve its saved queue/resume point. if (this.#selectedTrackId !== undefined && !cache.tracks.has(this.#selectedTrackId)) { @@ -355,23 +375,20 @@ export class Playback { this.suspend(); } } - #queueEdited(cache: Cache) { - this.#refreshController?.abort(); - this.#uploadPending = this.#uploadAllowed && this.#hasConnection(cache); - } - - // Connection-scoped synchronization policy. No independent queue state or lifecycle. - #resetSync() { - this.#refreshController?.abort(); - this.#refreshController = undefined; - this.#refreshPending = undefined; - this.#uploadTail = Promise.resolve(); + #invalidateExchange() { + this.#connectionVersion++; this.#queueError = undefined; - this.#syncVersion++; - this.#uploadPending = false; - this.#uploadAllowed = false; - clearTimeout(this.#saveTimer); - this.#saveTimer = undefined; + this.#exchangeMessage = ""; + } + get exchangeBusy() { + return this.#exchangeBusy; + } + get exchangeMessage() { + return this.#exchangeMessage; + } + get canExchangeQueue() { + const cache = this.#selection.cache; + return !!cache && !this.#destroyed && this.#hasConnection(cache); } #hasConnection(cache: Cache) { return ( @@ -380,12 +397,12 @@ export class Playback { cache.key === getAccountKey(this.#connection.account) ); } - /** Commands publish intent before awaiting Player; explicit transport events - * reconcile actual status here. Both paths share idempotent save/read policy. */ + /** Commands publish intent before awaiting transport; events reconcile status. + * Activity changes checkpoint locally and invalidate pending loads. */ #setActivity(state: PlaybackActivity) { if (this.#destroyed || state === this.#activity) return; this.#activity = state; - if (state !== "inactive") this.#refreshController?.abort(); + if (state !== "inactive") this.#activityVersion++; if (state === "active") this.#scheduleQueueFlush(); else void this.flushQueue(); } @@ -402,90 +419,73 @@ export class Playback { clearTimeout(this.#saveTimer); this.#saveTimer = undefined; try { - await this.#selection.cache?.flush(); - await this.#uploadQueue(); + await this.#selection.cache?.flushQueue(); } catch { // Cache retains checkpoint errors and dirty data for retry. } } - #uploadQueue(): Promise { - const connection = this.#connection; - const cache = this.#selection.cache; - if (!cache || !connection || !this.#hasConnection(cache) || this.#destroyed) - return Promise.resolve(); - const version = this.#syncVersion; - const isCurrentConnection = () => - !this.#destroyed && - version === this.#syncVersion && - cache === this.#selection.cache && - !connection.signal.aborted; - const task = this.#uploadTail.then(async () => { - if (!isCurrentConnection()) return; - const revision = cache.queueRevision; - await cache.flush(); - if (!isCurrentConnection() || !this.#uploadPending) return; - const checkpointIsCurrent = !cache.queueDirty && revision === cache.queueRevision; - if (!checkpointIsCurrent) return; - const state = cache.queue; - this.#queueError = undefined; - try { - await connection.write(toRemoteQueue(state)); - if (isCurrentConnection() && revision === cache.queueRevision) this.#uploadPending = false; - } catch (error) { - if (isCurrentConnection()) this.#queueError = error; - } - }); - // A failed checkpoint rejects this attempt without poisoning later attempts. - this.#uploadTail = task.catch(() => {}); - return task; + /** Explicit exchange only. Callers confirm replacement/empty saves before invoking. */ + loadServerQueue() { + return this.#exchangeQueue("load"); } - refreshQueue(): Promise { + saveServerQueue() { + return this.#exchangeQueue("save"); + } + async #exchangeQueue(action: "load" | "save") { const connection = this.#connection; const cache = this.#selection.cache; - if (!connection || !cache || !this.#hasConnection(cache) || this.#destroyed) - return Promise.resolve(); - if (this.#refreshPending) return this.#refreshPending; - const version = this.#syncVersion; - const controller = new AbortController(); - this.#refreshController = controller; - const signal = AbortSignal.any([connection.signal, controller.signal]); - const isCurrentConnection = () => - version === this.#syncVersion && + if (this.#exchangeBusy || !connection || !cache || !this.canExchangeQueue) return; + const version = this.#connectionVersion; + const revision = cache.queueRevision; + const activityVersion = this.#activityVersion; + const snapshot = toRemoteQueue({ ...cache.queue, tracks: [...cache.queue.tracks] }); + const current = () => !this.#destroyed && + version === this.#connectionVersion && cache === this.#selection.cache && !connection.signal.aborted; - return (this.#refreshPending = (async () => { - try { - try { - await this.#uploadQueue(); - } catch { - // Cache reports checkpoint failures; do not retain a duplicate sync error. + this.#exchangeBusy = action; + this.#exchangeMessage = ""; + this.#queueError = undefined; + try { + if (action === "save") { + await connection.write(snapshot); + if (current()) this.#exchangeMessage = "Queue saved to server."; + } else { + const remote = await connection.read(); + if (!current()) { + if (!this.#destroyed) + this.#exchangeMessage = "Connection changed while loading. Nothing was replaced."; + return; + } + if (revision !== cache.queueRevision || activityVersion !== this.#activityVersion) { + this.#exchangeMessage = "Queue changed while loading. Nothing was replaced."; return; } - if (!isCurrentConnection()) return; - this.#queueError = undefined; - const revision = cache.queueRevision; - const remote = await connection.read(); - if (!isCurrentConnection() || signal.aborted) return; - const queueWasEdited = revision !== cache.queueRevision; - const playbackInUse = this.#activity !== "inactive"; - if (queueWasEdited || playbackInUse) return; cache.setQueue(fromRemoteQueue(remote, cache.queue)); - this.#uploadPending = false; - this.#uploadAllowed = true; - this.#syncSelection(); - } catch (error) { - if (isCurrentConnection() && !signal.aborted) this.#queueError = error; + this.#syncSelection(true); + this.#scheduleQueueFlush(); + this.#exchangeMessage = "Server queue loaded. Playback is stopped."; } - })().finally(() => { - if (this.#refreshController === controller) this.#refreshController = undefined; - if (version === this.#syncVersion) this.#refreshPending = undefined; - })); + } catch { + // Never publish request URLs or arbitrary server error text. + if (current()) { + const message = + action === "load" + ? "Could not load server queue. Nothing was replaced." + : "Could not save queue to server. Try again."; + this.#queueError = new Error(message); + this.#exchangeMessage = message; + } + } finally { + this.#exchangeBusy = undefined; + } } destroy() { this.#destroyed = true; this.#cleanup?.(); - this.#resetSync(); + this.#invalidateExchange(); + clearTimeout(this.#saveTimer); return ( this.#selection.cache?.flush().then( () => {}, diff --git a/src/router.svelte b/src/router.svelte index eacac8b..f10aabf 100644 --- a/src/router.svelte +++ b/src/router.svelte @@ -127,7 +127,9 @@ ) return; - const sameSearch = routePath(current) === "/search" && routePath(destination) === "/search"; + const sameSearch = + ["/library", "/search"].includes(routePath(current) ?? "") && + ["/library", "/search"].includes(routePath(destination) ?? ""); event.intercept({ // Keep typing/toggle focus; leave scrolling and history restoration native. ...(sameSearch ? { focusReset: "manual" as const } : {}), diff --git a/src/session.svelte.ts b/src/session.svelte.ts index 84eaa89..26a70a3 100644 --- a/src/session.svelte.ts +++ b/src/session.svelte.ts @@ -1,4 +1,11 @@ -import { authenticate, getAccountKey, type Auth, type AuthStore, type PasswordAuth } from "./auth"; +import { + authenticate, + getAccountKey, + normalizeAndValidateServerHost, + type Auth, + type AuthStore, + type PasswordAuth, +} from "./auth"; import type { Covers } from "./covers.svelte"; import { NetworkTransportError, @@ -14,6 +21,8 @@ import type { TrackEngine } from "./track.svelte"; import { Cache } from "./cache.svelte"; import { withoutDownloadErrors } from "./download-error"; +import { acquireAccountOwnership, AccountOwnershipError } from "./account-ownership"; + const offlineModeStorageKey = "navidrome-offline-mode"; interface SessionOptions { @@ -25,6 +34,7 @@ interface SessionOptions { playback: Playback; playlists?: Playlists; preferences: Storage; + acquireOwnership?: typeof acquireAccountOwnership; } function connectionError(error: unknown): string { @@ -42,6 +52,9 @@ export class Session { status = $state("disconnected"); error = $state(""); localReady = $state(false); + ownershipIssue = $state<"blocked" | "unsupported">(); + #ownership?: { key: string; release: () => Promise }; + #restoreAccount?: Account; loadingAfterConnect = $state(false); #options: SessionOptions; @@ -54,22 +67,21 @@ export class Session { #restoration: Promise = Promise.resolve(); #loadController?: AbortController; #authController?: AbortController; - #downloadController?: AbortController; #operationId = 0; #started = false; #destroyed = false; + #deleting?: Promise; constructor(options: SessionOptions) { this.#options = options; } - #openDownloadAccess() { - if (!this.auth) return; - this.#downloadController?.abort(); - const controller = new AbortController(); - const connection = this.#options.network.open(this.auth, controller.signal); - this.#downloadController = controller; - this.#options.tracks.setDownloadConnection(connection.audio); + /** Browsing preference only; never changes playback or connection ownership. */ + downloadedOnly = $state(false); + + setDownloadedOnly(enabled: boolean) { + this.downloadedOnly = enabled; + this.#options.preferences.setItem("libras-downloaded-only", String(enabled)); } get libraryProgress() { @@ -115,11 +127,12 @@ export class Session { #fail(error: unknown, operationId: number) { if (!this.#isCurrentOperation(operationId)) return; + if (error instanceof AccountOwnershipError) this.ownershipIssue = error.reason; this.error = connectionError(error); this.status = this.error ? "error" : "disconnected"; } - /** Detach browsing and playback; requested downloads have a separate lifetime. */ + /** Detach all server access; durable queued download intent remains paused. */ #detach() { this.#authController?.abort(); this.#authController = undefined; @@ -136,11 +149,18 @@ export class Session { /** Publish connection changes in one place; Network owns their shared abort signal. */ #setConnection(connection: ActiveNetworkConnection | undefined) { + if ( + connection && + (this.#ownership?.key !== getAccountKey(connection.account) || + this.cache?.key !== this.#ownership.key) + ) + throw new Error("Activate this account’s local data before connecting."); this.#connection = connection; const { playback, covers, tracks } = this.#options; playback.setConnection(connection?.queue); covers.setConnection(connection?.artwork); tracks.setPlaybackConnection(connection?.audio); + tracks.setDownloadConnection(connection?.audio); this.#options.playlists?.setConnection(connection?.playlists); } @@ -153,11 +173,17 @@ export class Session { this.#options.tracks.activate(); } + /** Remembered identity is known before its asynchronously owned workspace opens. */ + get hasLocalAccount() { + return !!(this.#account ?? this.#restoreAccount); + } + start(): Auth | null { if (this.#started || this.#destroyed) return this.auth; this.#started = true; const operationId = this.#beginOperation(); try { + this.downloadedOnly = this.#options.preferences.getItem("libras-downloaded-only") === "true"; this.auth = this.#loadSavedAuth(); const account = this.auth ? { host: this.auth.host, username: this.auth.username } @@ -173,7 +199,8 @@ export class Session { } // Migrate existing installations before credentials can be removed. this.#options.auth.saveAccount(account); - this.#restoration = this.#restore(account); + this.#restoreAccount = account; + this.#restoration = this.#restore(account).catch((error) => this.#fail(error, operationId)); if (this.auth) this.status = "connecting"; void this.#finishStartup(operationId).catch((error) => this.#fail(error, operationId)); } catch (error) { @@ -193,8 +220,7 @@ export class Session { async #finishStartup(operationId: number) { await this.#restoration; - if (!this.#isCurrentOperation(operationId)) return; - this.#openDownloadAccess(); + if (!this.#isCurrentOperation(operationId) || !this.#ownership) return; if (!this.auth || this.offlineMode) { this.status = "disconnected"; return; @@ -205,7 +231,15 @@ export class Session { async #restore(account: Account) { const { covers, playback, selection } = this.#options; - const cache = new Cache(getAccountKey(account)); + const key = getAccountKey(account); + const release = await (this.#options.acquireOwnership ?? acquireAccountOwnership)(key); + if (this.#destroyed) { + await release(); + return; + } + this.#ownership = { key, release }; + this.ownershipIssue = undefined; + const cache = new Cache(key); this.#select(cache, account); this.#loadController?.abort(); const controller = new AbortController(); @@ -233,10 +267,7 @@ export class Session { /** Load local data for verified credentials, without selecting the account. * Same-account reconnects reuse the live writer to retain queue edits. */ - async #prepareWorkspace(connection: NetworkConnection) { - const previous = this.#options.selection.cache; - const key = getAccountKey(connection.account); - const cache = previous?.key === key ? previous : new Cache(key); + async #prepareWorkspace(connection: NetworkConnection, cache: Cache) { // Independent cache failures remain visible after acceptance; a background // refresh can repair the library without making login depend on its availability. await cache.load(connection.signal).catch((error) => { @@ -271,10 +302,18 @@ export class Session { /** No awaits: credentials, selection and engine connections commit in one turn. * Storage is not transactional; connect's failure path clears partial credentials. */ - #commitWorkspace(cache: Cache, credentials: Auth, connection: NetworkConnection) { + #commitWorkspace( + cache: Cache, + credentials: Auth, + connection: NetworkConnection, + remember: boolean, + ) { connection.signal.throwIfAborted(); + if (this.#ownership?.key !== getAccountKey(connection.account)) + throw new Error("Activate this account’s local data before connecting."); const { auth, preferences, network, playback } = this.#options; - auth.save(credentials); + if (remember) auth.save(credentials); + else auth.clear(); auth.saveAccount(connection.account); preferences.setItem(offlineModeStorageKey, "false"); const active = network.accept(connection); @@ -283,7 +322,6 @@ export class Session { playback.activate(); this.auth = credentials; this.#setConnection(active); - this.#openDownloadAccess(); this.localReady = true; } @@ -298,25 +336,54 @@ export class Session { } /** Authentication verifies; Session commits the workspace, then syncs in the background. */ - async connect(input: PasswordAuth): Promise { - if (this.auth || this.busy || this.#destroyed) return false; + async connect(input: PasswordAuth, remember = false): Promise { + if (this.auth || this.busy || this.#destroyed || this.#deleting) return false; const operationId = this.#beginOperation(); const controller = new AbortController(); + let candidate: { key: string; release: () => Promise } | undefined; + let candidateCache: Cache | undefined; this.#authController = controller; this.status = "connecting"; try { + await this.#restoration; + const key = getAccountKey({ ...input, host: normalizeAndValidateServerHost(input.host) }); + if (this.#ownership?.key !== key) { + const release = await (this.#options.acquireOwnership ?? acquireAccountOwnership)(key); + candidate = { key, release }; + } + controller.signal.throwIfAborted(); + if (!this.#isCurrentOperation(operationId)) return false; const verified = await authenticate(input, this.#options.network, controller.signal); if (!this.#isCurrentOperation(operationId)) return false; const { auth, connection } = verified; await this.#restoration; if (!this.#isCurrentOperation(operationId)) return false; connection.signal.throwIfAborted(); - const cache = await this.#prepareWorkspace(connection); + const workspaceKey = getAccountKey(connection.account); + const previous = this.cache; + const cache = previous?.key === workspaceKey ? previous : new Cache(workspaceKey); + candidateCache = cache; + await this.#prepareWorkspace(connection, cache); connection.signal.throwIfAborted(); if (!this.#isCurrentOperation(operationId)) return false; await this.#retireWorkspace(cache, connection.signal); if (!this.#isCurrentOperation(operationId)) return false; - this.#commitWorkspace(cache, auth, connection); + const previousCache = this.cache; + const previousOwnership = this.#ownership; + this.#ownership = candidate ?? previousOwnership; + try { + this.#commitWorkspace(cache, auth, connection, remember); + } catch (error) { + this.#ownership = previousOwnership; + throw error; + } + if (candidate) { + candidate = undefined; + if (previousCache && previousCache !== cache) await previousCache.retire().catch(() => {}); + await previousOwnership?.release(); + } + if (!this.#isCurrentOperation(operationId)) return false; + this.ownershipIssue = undefined; this.status = "connected"; this.loadingAfterConnect = true; void this.#refresh(false); @@ -328,12 +395,21 @@ export class Session { } return false; } finally { + if (candidate) { + if (candidateCache && candidateCache !== this.cache) + await candidateCache.retire().catch(() => {}); + await candidate.release(); + } if (this.#authController === controller) this.#authController = undefined; if (this.#isCurrentOperation(operationId) && this.status === "connecting") this.status = "disconnected"; } } + get blockedAccount() { + return !this.#ownership && this.ownershipIssue ? this.#restoreAccount : undefined; + } + get cache() { return this.#options.selection.cache; } @@ -343,9 +419,6 @@ export class Session { const operationId = this.#beginOperation(); this.auth = null; this.#detach(); - this.#downloadController?.abort(); - this.#downloadController = undefined; - this.#options.tracks.setDownloadConnection(undefined); this.status = "disconnected"; try { this.#options.auth.clear(); @@ -358,8 +431,18 @@ export class Session { } } + get canResumeOnline() { + const key = this.auth ? getAccountKey(this.auth) : undefined; + return ( + !this.#destroyed && + key !== undefined && + this.#ownership?.key === key && + this.cache?.key === key + ); + } + #resumeOnline() { - if (!this.auth) return; + if (!this.auth || !this.canResumeOnline) return; this.#setConnection(this.#options.network.open(this.auth)); this.status = "connected"; } @@ -403,7 +486,7 @@ export class Session { #refresh(force: boolean): Promise { if (this.#refreshPending) return this.#refreshPending; const operationId = this.#operationId; - const { covers, playback } = this.#options; + const { covers } = this.#options; this.#syncState = force ? "manual" : "automatic"; this.#libraryProgress = undefined; this.#refreshError = undefined; @@ -413,7 +496,7 @@ export class Session { await this.#refreshLibrary(force, operationId); } finally { // Only the owning operation can reveal content after an explicit connect. - // Artwork, playlists and queue synchronization must not block the library. + // Artwork and playlists must not block the library. if (this.#isCurrentOperation(operationId)) this.loadingAfterConnect = false; } if (!this.#isCurrentOperation(operationId)) return; @@ -428,12 +511,6 @@ export class Session { } catch (error) { if (this.#isCurrentOperation(operationId)) this.#refreshError ??= error; } - if (!this.#isCurrentOperation(operationId)) return; - try { - await playback.refreshQueue(); - } catch (error) { - if (this.#isCurrentOperation(operationId)) this.#refreshError ??= error; - } })().finally(() => { if (!this.#isCurrentOperation(operationId)) return; // Keep final scan counts until all sync work settles, then publish completion together. @@ -444,7 +521,7 @@ export class Session { } async setOfflineMode(enabled: boolean) { - if (!this.auth || this.#destroyed) return; + if (!this.auth || !this.canResumeOnline) return; if (enabled === this.offlineMode) return; const operationId = this.#beginOperation(); try { @@ -464,14 +541,56 @@ export class Session { } } - destroy() { + /** Leave a blocked startup for the connection form, without opening or deleting its data. */ + chooseAnotherAccount() { + if (this.#ownership || this.busy) return; + this.disconnect(); + this.ownershipIssue = undefined; + this.#restoreAccount = undefined; + this.localReady = true; + } + + async retryOwnership() { + if (this.busy || this.#destroyed || this.#ownership || !this.#restoreAccount) return; + const operationId = this.#beginOperation(); + this.status = "connecting"; + this.#restoration = this.#restore(this.#restoreAccount).catch((error) => + this.#fail(error, operationId), + ); + await this.#finishStartup(operationId); + if (this.ownershipIssue === "blocked") + this.error = "This account is still open in another tab."; + } + + /** Stop producers before deletion; a failed deletion retains the active lease. */ + clearLocalData(): Promise { + if (this.#deleting) return this.#deleting; + const cache = this.cache; + if (!this.#ownership || !cache || this.#destroyed || this.busy) return Promise.resolve(); + if (!this.disconnect()) return Promise.reject(new Error(this.error)); + this.#options.playback.suspend(); + this.#options.covers.activate(); + return (this.#deleting = (async () => { + await this.#options.tracks.activate(); + await cache.clear(); + })().finally(() => { + this.#deleting = undefined; + })); + } + + async destroy() { this.#destroyed = true; this.#operationId++; this.#loadController?.abort(); this.#loadController = undefined; this.#detach(); - this.#downloadController?.abort(); - this.#downloadController = undefined; - this.#options.tracks.setDownloadConnection(undefined); + this.#options.playback.suspend(); + this.#options.covers.destroy(); + await this.#options.tracks.activate(); + await this.#restoration; + await this.#deleting?.catch(() => {}); + await this.cache?.retire().catch(() => {}); + await this.#ownership?.release(); + this.#ownership = undefined; } } diff --git a/src/track.svelte.ts b/src/track.svelte.ts index 58d7593..4c6a180 100644 --- a/src/track.svelte.ts +++ b/src/track.svelte.ts @@ -104,6 +104,7 @@ export class TrackEngine { return this.downloadJobs.length; } get waitingForConnection() { + this.#version; return ( !this.#downloadConnection || this.#downloadConnection.signal.aborted || @@ -115,7 +116,7 @@ export class TrackEngine { void operation.finally(() => this.#operations.delete(operation)).catch(() => {}); return operation; } - /** Session hydration and connection attachment restore queued and failed intent. */ + /** Session hydration and connection attachment resume queued intent, never failed jobs. */ async restoreDownloads() { const cache = this.#selection.cache; const lifetime = this.#lifetime; @@ -138,7 +139,6 @@ export class TrackEngine { ) return; const entries = [...cache.downloads]; - const failed = new Set(); for (const [key, intent] of entries) { if (this.#jobs.has(key)) { continue; @@ -149,11 +149,8 @@ export class TrackEngine { { key, cacheKey: cache.key!, format: intent.format, contentType: intent.contentType }, true, ); - } else if (intent.status === "failed") { - failed.add(intent.track.id); } } - this.downloadMany(failed); this.#drain(); } catch { /* Unreadable download storage stays intact and blocks this domain only. */ @@ -489,6 +486,13 @@ export class TrackEngine { } return null; } + /** Registered completed bytes remain usable while another format is queued or failing. */ + isDownloaded(trackId: string): boolean { + const cache = this.#selection.cache; + return (["raw", "mp3"] as const).some( + (format) => cache?.downloads.get(downloadKey(trackId, format))?.status === "completed", + ); + } getStatus(trackId: string): TrackStatus { this.#version; const cache = this.#selection.cache; diff --git a/src/ui/library-scope.svelte b/src/ui/library-scope.svelte new file mode 100644 index 0000000..19e7c3f --- /dev/null +++ b/src/ui/library-scope.svelte @@ -0,0 +1,40 @@ + + +
+ Library scope +
+ {#each [["all", "All music"], ["downloaded", "Downloaded"]] as [value, label]} + + {/each} +
+ {#if session.downloadedOnly} + + {/if} +
+ + diff --git a/src/ui/player.svelte b/src/ui/player.svelte index 233983c..573143a 100644 --- a/src/ui/player.svelte +++ b/src/ui/player.svelte @@ -1,5 +1,6 @@