Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ Routes use the bare query, for example `/webapp/?/library/artist/123#section`. E
- 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. 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.
- 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.
- 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.
Expand Down Expand Up @@ -108,6 +110,8 @@ Select suites for the behavior being changed:
| `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.

Run the website suite against the website server, not the app:
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ 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

Expand All @@ -57,7 +57,7 @@ Download music while connected, then choose **Work offline** in navigation or Se

- **Manage downloads:** Settings → Downloads.
- **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
Expand Down
2 changes: 1 addition & 1 deletion src/_settings.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
if (!deleteLocalData) return;
cleaning = true;
try {
await session.cache?.clear();
await session.clearLocalData();
} catch {
// Disconnect succeeds even if optional local deletion fails.
} finally {
Expand Down
41 changes: 41 additions & 0 deletions src/account-ownership.ts
Original file line number Diff line number Diff line change
@@ -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<void>> {
if (!navigator.locks) throw new AccountOwnershipError("unsupported");
const name = `libras-account:${await hashAccountKey(key)}`;
let release!: () => void;
const held = new Promise<void>((resolve) => {
release = resolve;
});
let accept!: (release: () => Promise<void>) => void;
let reject!: (error: unknown) => void;
const acquired = new Promise<() => Promise<void>>((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;
}
66 changes: 62 additions & 4 deletions src/app.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang="ts">
import Icon from "./icon.svelte";
import { onDestroy, onMount, untrack, type Snippet } from "svelte";
import { onDestroy, onMount, tick, untrack, type Snippet } from "svelte";
import { installLongPress } from "./long-press";
import { Playback } from "./playback.svelte";
import { Playlists } from "./playlists.svelte";
Expand Down Expand Up @@ -251,16 +251,26 @@
</nav>
<section class="stack-sm" aria-label="Connection">
<p class="caption text-secondary">
{session.busy ? "Connecting…" : offlineMode ? "Working offline" : "Connected"}
{session.blockedAccount
? "Account not active"
: session.busy
? "Connecting…"
: offlineMode
? "Working offline"
: "Connected"}
</p>
{#if session.busy}
<button
class="menu-item"
disabled={!!session.blockedAccount}
onclick={() => (session.auth ? void session.setOfflineMode(true) : session.cancelConnect())}
>Cancel</button
>
{:else if session.auth}
<button class="menu-item" onclick={() => void session.setOfflineMode(!offlineMode)}
<button
class="menu-item"
disabled={!session.canResumeOnline}
onclick={() => void session.setOfflineMode(!offlineMode)}
>{offlineMode ? "Connect" : "Work offline"}</button
>
{:else}
Expand Down Expand Up @@ -345,7 +355,55 @@
<div class="row-sm app-status-actions">{@render actions()}</div>
{/if}
<main class="app-page">
{#if initialized}
{#if session.blockedAccount}
<div class="container-md stack-lg">
<section class="card stack-md" aria-labelledby="account-blocked-heading">
<h1 id="account-blocked-heading" class="heading-lg uppercase">
{session.ownershipIssue === "unsupported"
? "This browser cannot safely open this account’s local data."
: "This account is open in another tab"}
</h1>
<p class="body" style="overflow-wrap: anywhere">
{session.blockedAccount.username} · {session.blockedAccount.host}
</p>
<p class="body">
{session.ownershipIssue === "unsupported"
? "Web Locks browser support is required to protect your local data."
: "Close the other Libras tab, then retry."}
</p>
<p class="body" role="status">
{session.error.startsWith("This account is still") ? session.error : ""}
</p>
{#if session.ownershipIssue !== "unsupported"}
<button
class="button"
data-size="text"
data-variant="primary"
disabled={session.busy}
onclick={async (event) => {
const button = event.currentTarget;
await session.retryOwnership();
await tick();
if (button.isConnected && document.activeElement === document.body)
button.focus();
}}
>
{session.busy ? "Checking…" : "Retry"}
</button>
{/if}
<a
class="button"
data-size="text"
data-variant="secondary"
href="?/settings"
onclick={(event) => {
if (session.busy) event.preventDefault();
else session.chooseAnotherAccount();
}}>Use another account</a
>
</section>
</div>
{:else if initialized}
<Router
routes={[
{ pattern: "/library", render: libraryRoute },
Expand Down
30 changes: 25 additions & 5 deletions src/cache.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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("");
}
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -1147,7 +1151,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),
Expand Down Expand Up @@ -1207,7 +1211,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<void> {
if (this.#clearing) return this.#clearing;
const disk = this.#disk;
Expand Down Expand Up @@ -1278,6 +1282,22 @@ export class Cache {
);
}

/** Queue durability is independent of every other domain. */
flushQueue(): Promise<void> {
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<void> {
const results = await Promise.allSettled([
Expand Down
2 changes: 1 addition & 1 deletion src/playback.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ export class Playback {
clearTimeout(this.#saveTimer);
this.#saveTimer = undefined;
try {
await this.#selection.cache?.flush();
await this.#selection.cache?.flushQueue();
} catch {
// Cache retains checkpoint errors and dirty data for retry.
}
Expand Down
Loading
Loading