diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fde9b20..e5f915a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,7 +48,7 @@ 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. +- 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. - 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. diff --git a/README.md b/README.md index ccbf763..e9262c9 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,9 @@ Installation options vary by browser and device. Offline storage and background ## 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. - **Refresh library:** Automatic when opening online, or via Settings → Refresh library. diff --git a/src/_album.svelte b/src/_album.svelte index c0cfdb3..d6ce476 100644 --- a/src/_album.svelte +++ b/src/_album.svelte @@ -1,5 +1,6 @@ + +
+ 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 441bfa1..038ba14 100644 --- a/src/ui/player.svelte +++ b/src/ui/player.svelte @@ -195,8 +195,7 @@ max={maximum} step="0.1" {value} - disabled={!maximum || - (offlineMode && track && trackEngine.getStatus(track.id) !== "downloaded")} + disabled={!maximum || (offlineMode && track && !trackEngine.isDownloaded(track.id))} style:--progress={`${maximum ? (value / maximum) * 100 : 0}%`} aria-label="Playback position" aria-valuetext={`${formatDuration(position)} of ${formatDuration(duration)}`} @@ -362,6 +361,11 @@

{track.title}

+ {#if offlineMode && !trackEngine.isDownloaded(track.id)} +

+ Unavailable offline +

+ {/if} {#if credit}

{credit}

{/if} @@ -370,10 +374,22 @@
+ {#if offlineMode && !trackEngine.isDownloaded(track.id)} + + {/if}
+ {/if} {/each} diff --git a/tests/album-page.test.ts b/tests/album-page.test.ts index e4a5a9b..0edb9b8 100644 --- a/tests/album-page.test.ts +++ b/tests/album-page.test.ts @@ -339,6 +339,7 @@ it("keeps pause/cancel available offline but never substitutes another track for vi.spyOn(tracks, "getStatus").mockImplementation((id) => id === "first" ? "downloaded" : "idle", ); + vi.spyOn(tracks, "isDownloaded").mockImplementation((id) => id === "first"); await playback.replaceQueueAndPlay(["unrelated", "second", "second"], 2); await playback.seek(25); replace.mockClear(); @@ -392,7 +393,7 @@ it("keeps pause/cancel available offline but never substitutes another track for button().click(); await settle(); state("playing"); - expect(replace).toHaveBeenCalledExactlyOnceWith(["first"]); + expect(replace).toHaveBeenCalledExactlyOnceWith(["first", "second"]); }); it("shows playing indicators only on selected track rows and labels pending transports Pause", async () => { diff --git a/tests/app-cache.test.ts b/tests/app-cache.test.ts index 1e8cdbc..25f546c 100644 --- a/tests/app-cache.test.ts +++ b/tests/app-cache.test.ts @@ -39,6 +39,9 @@ vi.mock("../src/session.svelte", () => ({ get offlineMode() { return mocks.isOffline(); } + get downloadedOnly() { + return mocks.isOffline(); + } localReady = mocks.localReady; loadingAfterConnect = mocks.loadingAfterConnect; constructor(options: NonNullable) { @@ -323,6 +326,7 @@ it("keeps all queue occurrences including unavailable offline rows", async () => vi.spyOn(TrackEngine.prototype, "getStatus").mockImplementation((id) => id === "one" ? "downloaded" : "idle", ); + vi.spyOn(TrackEngine.prototype, "isDownloaded").mockImplementation((id) => id === "one"); const target = document.createElement("main"); document.body.append(target); const component = mount(App, { target }); @@ -613,6 +617,7 @@ it("preserves artist pagination when offline eligibility changes", async () => { vi.spyOn(TrackEngine.prototype, "getStatus").mockImplementation((id) => downloaded.has(id) ? "downloaded" : "idle", ); + vi.spyOn(TrackEngine.prototype, "isDownloaded").mockImplementation((id) => downloaded.has(id)); let callback: IntersectionObserverCallback; const observed = new Set(); vi.stubGlobal( @@ -679,7 +684,7 @@ it("preserves artist pagination when offline eligibility changes", async () => { downloaded.clear(); flushSync(); expect(count()).toBe(0); - expect(target.textContent).toContain("No downloaded artists."); + expect(target.textContent).toContain("No downloaded music."); flags.clear(); flushSync(); expect(count()).toBe(96); diff --git a/tests/app-settings.test.ts b/tests/app-settings.test.ts index b92ad69..7e0f4a2 100644 --- a/tests/app-settings.test.ts +++ b/tests/app-settings.test.ts @@ -113,7 +113,7 @@ async function setup( (button.getAttribute("aria-label") ?? button.textContent?.trim()) === label && (label !== "Disconnect" || button.id === "settings-disconnect"), )!; - const offline = () => target.querySelector("#settings-offline")!; + const offline = () => ({ checked: fixture.session.offlineMode, disabled: !fixture.session.auth }); const confirmDisconnect = (cleanup = false) => { const dialog = target.querySelector("#disconnect-dialog")!; const checkbox = dialog.querySelector('input[type="checkbox"]')!; @@ -370,14 +370,9 @@ describe("app settings", () => { ); expect(server.querySelector("#server-password")?.getAttribute("type")).toBe("password"); expect(offline.classList.contains("card")).toBe(true); - const control = offline.querySelector('input[role="switch"]')!; - expect(control.classList.contains("switch")).toBe(true); - expect(target.querySelector('label[for="settings-offline"]')?.textContent).toBe( - "Offline library", - ); - expect(control.id).toBe("settings-offline"); - expect(target.querySelector("#settings-offline-title")?.textContent).toContain("is on"); - expect(control.getAttribute("aria-describedby")).toBe("settings-offline-help"); + expect(offline.querySelector('input[role="switch"]')).toBeNull(); + expect(target.querySelector("#settings-offline-title")?.textContent).toBe("Connection"); + expect(offline.textContent).toContain("Working offline"); expect(target.querySelector("select")).toBeNull(); }); @@ -385,14 +380,12 @@ describe("app settings", () => { const { target, session } = await setup(true); const help = () => target.querySelector("#settings-offline-help")!.textContent!.replace(/\s+/g, " ").trim(); - expect(help()).toContain("Browse your full library and stream from your server."); - expect(help()).toContain("Turn this on to show downloaded music only."); - expect(help()).not.toContain("Turn this off"); + expect(help()).toContain("Server access is on."); + expect(help()).toContain("without disconnecting."); await session.setOfflineMode(true); flushSync(); - expect(help()).toContain("Showing downloaded music only."); - expect(help()).toContain("Turn this off to browse and stream from your server."); - expect(help()).not.toContain("Turn this on"); + expect(help()).toContain("Server access is off. Requested downloads are paused."); + expect(target.querySelector("#settings-offline-card button")?.textContent).toBe("Connect"); }); it("keeps decorative status glyphs and loading aligned with the connection label", async () => { @@ -468,7 +461,7 @@ describe("app settings", () => { for (const owner of [".app-sidebar", "#navigation-dialog"]) { const notice = target.querySelector(`${owner} [aria-label="App update"]`)!; expect(notice.previousElementSibling?.matches("hr.separator")).toBe(true); - expect(notice.previousElementSibling?.previousElementSibling?.tagName).toBe("NAV"); + expect(target.querySelector(`${owner} nav`)).not.toBeNull(); const action = notice.querySelector("button")!; expect(action.title).toContain("A new version of Libras is available."); expect(action.title).toContain("interrupts playback"); diff --git a/tests/artist-page.test.ts b/tests/artist-page.test.ts index c2379c7..c475f6c 100644 --- a/tests/artist-page.test.ts +++ b/tests/artist-page.test.ts @@ -291,6 +291,7 @@ it("uses unfiltered membership offline, allowing pause/cancel but never substitu vi.spyOn(tracks, "getStatus").mockImplementation((id) => id === "first" ? "downloaded" : "idle", ); + vi.spyOn(tracks, "isDownloaded").mockImplementation((id) => id === "first"); await playback.replaceQueueAndPlay(["unrelated", "later", "later"], 2); await playback.seek(25); replace.mockClear(); @@ -344,5 +345,5 @@ it("uses unfiltered membership offline, allowing pause/cancel but never substitu button().click(); await settle(); state("playing"); - expect(replace).toHaveBeenCalledExactlyOnceWith(["first"]); + expect(replace).toHaveBeenCalledExactlyOnceWith(["first", "second", "later", "cameo"]); }); diff --git a/tests/browser/downloads.test.cjs b/tests/browser/downloads.test.cjs index 03b4e1f..d68a237 100644 --- a/tests/browser/downloads.test.cjs +++ b/tests/browser/downloads.test.cjs @@ -2,6 +2,8 @@ const assert = require("node:assert/strict"); const { test } = require("node:test"); const { chromium } = require("playwright"); +const fs = require("node:fs/promises"); +const path = require("node:path"); const base = `${(process.env.PREVIEW_URL ?? "http://127.0.0.1:5173").replace(/\/$/, "")}/`; const artist = { id: "artist", name: "Download test artist" }; @@ -47,6 +49,28 @@ test("Downloads redesign preserves real transfer states and offline files", asyn release = resolve; }); let streams = 0; + let requests = 0; + const evidence = async (name) => { + for (const [width, height] of [ + [390, 844], + [1440, 900], + [320, 844], + ]) { + await page.setViewportSize({ width, height }); + assert.ok( + await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), + `${name}: ${width}px overflow`, + ); + if (process.env.ARTIFACT_DIR && width !== 320) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ + path: path.join(process.env.ARTIFACT_DIR, `${name}-${width}.png`), + fullPage: true, + }); + } + } + await page.setViewportSize({ width: 1280, height: 900 }); + }; let retrySucceeds = false; let libraryGate = Promise.resolve(); let releaseLibrary = () => {}; @@ -68,6 +92,7 @@ test("Downloads redesign preserves real transfer states and offline files", asyn const unexpected = []; page.on("pageerror", (error) => errors.push(error.message)); await page.route("https://music.example.test/rest/**", async (route) => { + requests++; const url = new URL(route.request().url()); const method = url.pathname.split("/").pop().replace(".view", ""); if (method === "stream") { @@ -121,6 +146,7 @@ test("Downloads redesign preserves real transfer states and offline files", asyn await page.getByLabel("Username", { exact: true }).fill(username); await page.getByLabel("Password", { exact: true }).fill("fictional-password"); await page.getByRole("button", { name: "Connect", exact: true }).click(); + await page.getByRole("radio", { name: "All music", exact: true }).check(); await page .getByRole("link", { name: username === "other" ? otherArtist.name : artist.name, @@ -255,6 +281,40 @@ test("Downloads redesign preserves real transfer states and offline files", asyn }, ); + await t.test( + "Work offline makes zero server requests and reconnect resumes queued jobs", + async () => { + await page.setViewportSize({ width: 1280, height: 900 }); + await page + .locator(".app-sidebar") + .getByRole("button", { name: "Work offline", exact: true }) + .click(); + await page.getByText("Paused while working offline", { exact: true }).waitFor(); + await page.waitForFunction( + () => document.querySelectorAll('[aria-label="Downloading"]').length === 0, + ); + const before = requests; + await evidence("offline-paused-downloads"); + await page.locator('.app-sidebar a[href="?/search"]').click(); + await page.locator('input[type="search"]').fill("long music"); + await page.locator(".track-row").first().waitFor(); + assert.equal(await page.getByText("Unavailable offline", { exact: true }).count(), 3); + assert.equal(await page.locator(".track-row button.link-target:disabled").count(), 3); + await evidence("offline-all-unavailable"); + await page.locator('.app-sidebar a[href="?/downloads"]').click(); + assert.equal(requests, before, "Work offline must not access any server domain"); + streams = 0; // Count the resumed attempt separately from the aborted transfers. + await page + .locator(".app-sidebar") + .getByRole("button", { name: "Connect", exact: true }) + .click(); + await page.waitForFunction( + () => document.querySelectorAll('[aria-label="Downloading"]').length === 3, + ); + assert.equal(streams, 3); + }, + ); + await t.test( "Cancel downloads retires real active and queued intent across reload", async () => { @@ -353,54 +413,82 @@ test("Downloads redesign preserves real transfer states and offline files", asyn }, ); - await t.test( - "online reopen automatically retries failures once; row Retry and Retry all still work", - async () => { - const automaticRetry = page.waitForResponse((response) => { - const url = new URL(response.url()); - return ( - /\/stream(?:\.view)?$/.test(url.pathname) && url.searchParams.get("id") === "track-6" - ); - }); - await page.reload(); - await automaticRetry; - await page.getByRole("button", { name: /^Retry download of 6/ }).waitFor(); - await page.waitForFunction( - () => document.querySelectorAll("[aria-labelledby=downloads-heading] time").length === 5, - ); - assert.equal(streams, 7); - assert.equal( - await page.getByRole("button", { name: "Show errors", exact: true }).count(), - 0, - ); - const retried = page.waitForResponse((response) => { - const url = new URL(response.url()); - return ( - /\/stream(?:\.view)?$/.test(url.pathname) && url.searchParams.get("id") === "track-6" - ); - }); - await page.getByRole("button", { name: /^Retry download of 6/ }).click(); - await retried; - await page.getByRole("button", { name: /^Retry download of 6/ }).waitFor(); - await page.waitForFunction(() => - document.querySelector( - '[aria-labelledby=downloads-heading] [aria-label="Download failed"]', - ), - ); - assert.equal(streams, 8); - retrySucceeds = true; - await page.getByRole("button", { name: "Retry all", exact: true }).click(); - await page.waitForFunction( - () => document.querySelectorAll("[aria-labelledby=downloads-heading] time").length === 6, + await t.test("online reopen leaves failures for explicit row Retry and Retry all", async () => { + await page + .locator(".app-sidebar") + .getByRole("link", { name: "Your library", exact: true }) + .click(); + await page.getByRole("radio", { name: "Downloaded", exact: true }).check(); + await evidence("connected-downloaded"); + assert.equal( + await page + .locator(".app-sidebar") + .getByRole("button", { name: "Work offline", exact: true }) + .isVisible(), + true, + ); + await page.locator('.app-sidebar a[href="?/downloads"]').click(); + await page.reload(); + await page.getByRole("button", { name: /^Retry download of 6/ }).waitFor(); + await page.waitForFunction( + () => document.querySelectorAll("[aria-labelledby=downloads-heading] time").length === 5, + ); + assert.equal(streams, 6); + assert.equal(await page.getByRole("button", { name: "Show errors", exact: true }).count(), 0); + const retried = page.waitForResponse((response) => { + const url = new URL(response.url()); + return ( + /\/stream(?:\.view)?$/.test(url.pathname) && url.searchParams.get("id") === "track-6" ); - assert.equal(streams, 9); - assert.equal(await page.getByRole("button", { name: /^Retry download of 6/ }).count(), 0); - }, - ); + }); + await page.getByRole("button", { name: /^Retry download of 6/ }).click(); + await retried; + await page.getByRole("button", { name: /^Retry download of 6/ }).waitFor(); + await page.waitForFunction(() => + document.querySelector( + '[aria-labelledby=downloads-heading] [aria-label="Download failed"]', + ), + ); + assert.equal(streams, 7); + retrySucceeds = true; + await page.getByRole("button", { name: "Retry all", exact: true }).click(); + await page.waitForFunction( + () => document.querySelectorAll("[aria-labelledby=downloads-heading] time").length === 6, + ); + assert.equal(streams, 8); + assert.equal(await page.getByRole("button", { name: /^Retry download of 6/ }).count(), 0); + }); await t.test("unchecked disconnect retains cached playback and offline downloads", async () => { await navigate("/library"); await playCached(); + const source = await page.evaluate(() => window.testAudio.currentSrc); + const queue = await page.locator("#player-dialog .track-row .label").allTextContents(); + const selected = await page + .locator('#player-dialog .track-row[aria-current="true"] .label') + .textContent(); + await page.getByRole("radio", { name: "All music", exact: true }).check(); + await page.getByRole("radio", { name: "Downloaded", exact: true }).check(); + assert.deepEqual( + await page.locator("#player-dialog .track-row .label").allTextContents(), + queue, + ); + assert.equal( + await page.locator('#player-dialog .track-row[aria-current="true"] .label').textContent(), + selected, + ); + assert.equal( + await page.evaluate(() => !window.testAudio.paused && window.testAudio.currentSrc), + source, + ); + await page + .locator(".app-sidebar") + .getByRole("button", { name: "Work offline", exact: true }) + .click(); + assert.equal( + await page.evaluate(() => !window.testAudio.paused && window.testAudio.currentSrc), + source, + ); await page.getByRole("link", { name: "Settings", exact: true }).click(); await page.getByRole("button", { name: "Disconnect", exact: true }).click(); await page @@ -422,7 +510,7 @@ test("Downloads redesign preserves real transfer states and offline files", asyn ); assert.equal(await page.locator("[aria-labelledby=downloads-heading] time").count(), 6); assert.equal(await page.getByRole("heading", { name: "No downloads yet" }).count(), 0); - assert.equal(streams, 9); + assert.equal(streams, 8); assert.equal(await page.getByRole("button", { name: /^Retry download of 6/ }).count(), 0); assert.equal(await page.getByRole("button", { name: "Show errors", exact: true }).count(), 0); }); diff --git a/tests/browser/queue.test.cjs b/tests/browser/queue.test.cjs index 30e4c62..add3c69 100644 --- a/tests/browser/queue.test.cjs +++ b/tests/browser/queue.test.cjs @@ -215,7 +215,10 @@ test("local queue and native explicit exchange", async () => { .filter({ visible: true }) .click(); const beforeOffline = calls.filter((m) => /PlayQueue/.test(m)).length; - await page.locator("#settings-offline").check(); + await page + .locator("#settings-offline-card") + .getByRole("button", { name: "Work offline", exact: true }) + .click(); await openQueue(); assert.equal( await player.getByRole("button", { name: "Load server queue" }).isDisabled(), diff --git a/tests/browser/settings.test.cjs b/tests/browser/settings.test.cjs index 532c192..ad8f1e9 100644 --- a/tests/browser/settings.test.cjs +++ b/tests/browser/settings.test.cjs @@ -77,7 +77,7 @@ test("Settings native controls, layout, and persistence", async (t) => { page.waitForFunction( () => !!document.querySelector("#settings-server-identity") && - !document.querySelector("#settings-offline")?.checked && + document.querySelector("#settings-offline-card button")?.textContent === "Work offline" && document.querySelector("#settings-refresh")?.getAttribute("aria-busy") === "false", ); @@ -213,8 +213,8 @@ test("Settings native controls, layout, and persistence", async (t) => { }, ); - await t.test("keyboard offline mode persists through reload without reconnecting", async () => { - const control = page.getByRole("switch", { name: "Offline library", exact: true }); + await t.test("keyboard Work offline persists through reload without reconnecting", async () => { + const control = page.locator("#settings-offline-card button"); await control.focus(); await page.keyboard.press("Space"); await page.waitForFunction(() => @@ -225,25 +225,13 @@ test("Settings native controls, layout, and persistence", async (t) => { await page.waitForFunction(() => document.querySelector("#settings-connection-status")?.textContent.includes("Offline mode"), ); - assert.equal(await control.isChecked(), true); - const onThumb = await control.evaluate( - (node) => getComputedStyle(node, "::before").backgroundColor, - ); - assert.equal(onThumb, "rgb(239, 191, 4)"); - assert.equal( - await control.evaluate((node) => getComputedStyle(node).backgroundColor), - "rgb(129, 0, 0)", - ); + assert.equal(await control.textContent(), "Connect"); assert.equal(calls.filter((method) => method === "ping").length, pings); const searches = calls.filter((method) => method === "search3").length; await control.focus(); await page.keyboard.press("Space"); await waitConnected(); - assert.equal(await control.isChecked(), false); - assert.notEqual( - await control.evaluate((node) => getComputedStyle(node, "::before").backgroundColor), - onThumb, - ); + assert.equal(await control.textContent(), "Work offline"); assert.equal(calls.filter((method) => method === "search3").length, searches); await page.getByRole("link", { name: "Libras home", exact: true }).click(); await page.locator("[aria-labelledby=library-heading] .tile").waitFor(); diff --git a/tests/mixed-download-availability.test.ts b/tests/mixed-download-availability.test.ts new file mode 100644 index 0000000..0e28776 --- /dev/null +++ b/tests/mixed-download-availability.test.ts @@ -0,0 +1,149 @@ +// @vitest-environment happy-dom +import { flushSync, mount, unmount } from "svelte"; +import { expect, it, vi } from "vitest"; +import Album from "../src/_album.svelte"; +import { AuthStore, getAccountKey } from "../src/auth"; +import { Cache, downloadKey } from "../src/cache.svelte"; +import { Covers } from "../src/covers.svelte"; +import { Network } from "../src/network.svelte"; +import { Playback } from "../src/playback.svelte"; +import { Session } from "../src/session.svelte"; +import { TrackEngine } from "../src/track.svelte"; +import { AudioTransport } from "../src/audio-transport.svelte"; +import { AudioStub } from "./audio-test-helpers"; +import { installDisk } from "./cache-test-helpers"; +import { TestSelection } from "./cache-selection-test-helpers.svelte"; +import { createStorage, credentials, deferred } from "./session-test-helpers"; + +it("keeps completed MP3 browsable and playable when a raw retry is paused by Work offline", async () => { + installDisk(); + vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:cached-mp3"); + vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {}); + const audio = new AudioStub(); + vi.stubGlobal("Audio", function () { + return audio; + }); + const selection = new TestSelection(); + const cache = new Cache(getAccountKey(credentials)); + const song = { id: "mixed", title: "Mixed formats", artist: "Artist", album: "Album" }; + await cache.replaceLibrary({ + savedAt: 1, + lastModified: 1, + artists: [{ id: "artist", name: "Artist" }], + albums: [{ id: "album", title: "Album", artistIds: ["artist"], genres: [] }], + tracks: [ + { + id: song.id, + title: song.title, + albumId: "album", + artistIds: ["artist"], + genres: [], + }, + ], + }); + await cache.saveDownload( + song, + "mp3", + "audio/mpeg", + new Response("cached MP3"), + new AbortController().signal, + ); + await cache.enqueueDownload(song, "raw", "audio/flac"); + await cache.failDownload(downloadKey(song.id, "raw")); + selection.cache = cache; + const covers = new Covers(selection); + const tracks = new TrackEngine({ selection }); + const network = new Network(); + const storage = createStorage(); + const auth = new AuthStore(storage); + const playback = new Playback({ + selection, + tracks, + covers, + isAvailable: (id) => network.mode === "online" || tracks.isDownloaded(id), + }); + const transport = new AudioTransport({ + onstatechange: (state) => playback.updatePlayerState(state), + }); + playback.attach(transport); + const session = new Session({ + selection, + network, + auth, + covers, + tracks, + playback, + preferences: storage, + }); + vi.spyOn(network, "validate").mockResolvedValue(undefined); + const accept = network.accept.bind(network); + vi.spyOn(network, "accept").mockImplementation((candidate) => { + const active = accept(candidate); + return { ...active, metadata: { ...active.metadata, getModifiedAt: async () => 1 } }; + }); + const pending = deferred(); + const fetcher = vi.fn(async () => pending.promise); + vi.stubGlobal("fetch", fetcher); + const target = document.createElement("main"); + document.body.append(target); + let app: ReturnType | undefined; + try { + expect( + await session.connect({ + host: credentials.host, + username: credentials.username, + password: "fictional", + }), + ).toBe(true); + expect(cache.downloads.get(downloadKey(song.id, "raw"))?.status).toBe("failed"); + const retry = tracks.download(song.id, { format: "raw" }); + await vi.waitFor(() => expect(tracks.getStatus(song.id)).toBe("downloading")); + expect(tracks.isDownloaded(song.id)).toBe(true); + await session.setOfflineMode(true); + await expect(retry).rejects.toBeDefined(); + expect(tracks.getStatus(song.id)).toBe("queued"); + expect(tracks.waitingForConnection).toBe(true); + expect(cache.downloads.get(downloadKey(song.id, "raw"))?.status).toBe("queued"); + session.setDownloadedOnly(true); + app = mount(Album, { + target, + props: { + params: { albumId: "album" }, + cache, + covers, + trackEngine: tracks, + session, + playback, + playbackState: "paused", + }, + }); + flushSync(); + const play = target.querySelector( + `button[aria-label="Play ${song.title}"]`, + )!; + expect(play).not.toBeNull(); + expect(play.disabled).toBe(false); + expect(target.textContent).not.toContain("Unavailable offline"); + const requests = fetcher.mock.calls.length; + play.click(); + await vi.waitFor(() => expect(audio.paused).toBe(false)); + expect(audio.src).toBe("blob:cached-mp3"); + expect(cache.queue.tracks).toEqual([song.id]); + expect(fetcher).toHaveBeenCalledTimes(requests); + // Classification comes from the acquired source, not the pending raw transfer. + playback.suspendNetwork(); + expect(audio.paused).toBe(false); + expect(tracks.getStatus(song.id)).toBe("queued"); + } finally { + if (app) await unmount(app); + target.remove(); + session.destroy(); + await playback.destroy(); + transport.dispose(); + tracks.destroy(); + covers.destroy(); + pending.resolve(new Response("aborted raw")); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + } +}); diff --git a/tests/network.test.ts b/tests/network.test.ts index 7a0a835..2f12d8d 100644 --- a/tests/network.test.ts +++ b/tests/network.test.ts @@ -240,20 +240,15 @@ describe("Network connection lifecycle", () => { other.setMode("offline"); }); - it("keeps caller-owned access independent of browsing mode and login candidates", () => { + it("blocks new access offline and aborts every domain in the shared lifetime", () => { const network = new Network(); - const candidate = network.prepare(auth); - const controller = new AbortController(); - const independent = network.open(auth, controller.signal); - expect(network.mode).toBe("offline"); - const browsing = network.accept(candidate); + expect(() => network.open(auth)).toThrow("Network access is offline."); + network.setMode("online"); + const connection = network.open(auth); network.setMode("offline"); - expect(browsing.signal.aborted).toBe(true); - expect(independent.signal.aborted).toBe(false); - controller.abort(); - expect(independent.signal.aborted).toBe(true); - expect(() => independent.audio.url("track", { format: "raw" })).toThrowError(/abort/i); - expect(() => network.open(auth, controller.signal)).toThrowError(/abort/i); + expect(connection.signal.aborted).toBe(true); + expect(() => connection.audio.url("track", { format: "raw" })).toThrowError(/abort/i); + expect(() => network.open(auth)).toThrow("Network access is offline."); }); it("exposes only frozen, credential-free connection identity", () => { diff --git a/tests/playback-page-test-helpers.ts b/tests/playback-page-test-helpers.ts index dd3602b..4ae7e46 100644 --- a/tests/playback-page-test-helpers.ts +++ b/tests/playback-page-test-helpers.ts @@ -58,7 +58,7 @@ export async function setupPlaybackPage(library: Parameters !offlineState.current || tracks.getStatus(id) === "downloaded", + isAvailable: (id) => !offlineState.current || tracks.isDownloaded(id), }); const replace = vi.spyOn(playback, "replaceQueueAndPlay"); const target = document.createElement("div"); diff --git a/tests/playback-queue.test.ts b/tests/playback-queue.test.ts index 02c0248..72d848f 100644 --- a/tests/playback-queue.test.ts +++ b/tests/playback-queue.test.ts @@ -82,6 +82,18 @@ afterEach(async () => { }); describe("local authoritative queue", () => { + it("removes an unavailable original occurrence without dropping duplicates or shifting playback", async () => { + const { playback, cache, audio, connection } = await setup(); + await playback.play(); + playback.removeQueueIndex(1); + expect(cache.queue).toEqual({ tracks: ["a", "a"], index: 1, position: 12.5 }); + expect(audio.paused).toBe(false); + playback.removeQueueIndex(1); + expect(cache.queue).toEqual({ tracks: ["a"], index: -1, position: 0 }); + expect(audio.paused).toBe(true); + expect(connection.read).not.toHaveBeenCalled(); + expect(connection.write).not.toHaveBeenCalled(); + }); it("never exchanges automatically on activation, reconnect, edits, progress, pause, visibility or flush", async () => { const { playback, connection, cache } = await setup(); playback.activate(); diff --git a/tests/search-filters.test.ts b/tests/search-filters.test.ts index 85b2d8a..dd6accd 100644 --- a/tests/search-filters.test.ts +++ b/tests/search-filters.test.ts @@ -37,7 +37,7 @@ function fixture(count = 120) { }, session: { localReady: true, offlineMode: false }, covers: {}, - trackEngine: { getStatus: () => "downloaded" }, + trackEngine: { getStatus: () => "downloaded", isDownloaded: () => true }, playback: { toggleTrack: vi.fn(), replaceQueueAndPlay: vi.fn(), enqueue: vi.fn() }, } as unknown as ComponentProps; } @@ -80,7 +80,7 @@ describe("independent search filters", () => { window.navigation.navigate("?/search&type=track#anchor", { history: "push" }); flushSync(); expect(target.querySelectorAll(".track-row")).toHaveLength(120); - const input = target.querySelector("input")!; + const input = target.querySelector('input[type="search"]')!; input.value = "Fixture"; input.dispatchEvent(new Event("input", { bubbles: true })); flushSync(); @@ -94,8 +94,11 @@ describe("independent search filters", () => { const props = fixture(3); const offlineProps = { ...props, - session: { localReady: true, offlineMode: true }, - trackEngine: { getStatus: (id: string) => (id === "t2" ? "downloaded" : "idle") }, + session: { localReady: true, offlineMode: true, downloadedOnly: true }, + trackEngine: { + getStatus: (id: string) => (id === "t2" ? "downloaded" : "idle"), + isDownloaded: (id: string) => id === "t2", + }, } as unknown as ComponentProps; const target = document.createElement("main"); document.body.append(target); @@ -113,7 +116,7 @@ describe("independent search filters", () => { expect(play.getAttribute("aria-label")).toBe("Play Fixture track 2"); play.click(); expect(props.playback.toggleTrack).toHaveBeenCalledWith("t2", ["t2"]); - const input = target.querySelector("input")!; + const input = target.querySelector('input[type="search"]')!; input.value = "Fixture track 0"; input.dispatchEvent(new Event("input", { bubbles: true })); flushSync(); @@ -151,7 +154,7 @@ describe("independent search filters", () => { expect(target.querySelector("section[aria-label] header")?.textContent).toContain("120"); expect(target.textContent).not.toContain("Show more"); } else expect(target.textContent).toContain("Type to find music"); - const input = target.querySelector("input")!; + const input = target.querySelector('input[type="search"]')!; input.value = "Fixture"; input.dispatchEvent(new Event("input", { bubbles: true })); flushSync(); diff --git a/tests/search-page.test.ts b/tests/search-page.test.ts index 3f79f4f..7973c33 100644 --- a/tests/search-page.test.ts +++ b/tests/search-page.test.ts @@ -33,7 +33,7 @@ it("focuses the input, expands previews, retains URL criteria, and uses album pl artistAlbums: new Map([["artist", [{ id: "album" }]]]), }, session: { localReady: true, offlineMode: false, refreshError: "Synchronization failed." }, - trackEngine: { getStatus: () => "downloaded", downloadMany }, + trackEngine: { getStatus: () => "downloaded", isDownloaded: () => true, downloadMany }, covers: { ensureCover: () => cover, }, @@ -48,7 +48,7 @@ it("focuses the input, expands previews, retains URL criteria, and uses album pl (b) => (b.getAttribute("aria-label") ?? b.textContent?.trim()) === label, )!; try { - let input = target.querySelector("input")!; + let input = target.querySelector('input[type="search"]')!; expect(document.activeElement).toBe(input); expect(target.textContent).toContain("Type to find music"); expect(target.textContent).toContain("Synchronization failed."); @@ -151,7 +151,7 @@ it("focuses the input, expands previews, retains URL criteria, and uses album pl flushSync(); button("Toggle route").click(); flushSync(); - input = target.querySelector("input")!; + input = target.querySelector('input[type="search"]')!; expect(input.value).toBe("Song"); expect(target.querySelectorAll(".track-row button.link-target")).toHaveLength(3); // Native search cancellation emits an input event with an empty value. @@ -181,7 +181,7 @@ it.each([ { localReady: false, savedAt: undefined, offlineMode: false, heading: undefined }, { localReady: true, savedAt: undefined, offlineMode: false, heading: "Connect your library" }, { localReady: true, savedAt: 1, offlineMode: false, heading: "Your library is empty." }, - { localReady: true, savedAt: 1, offlineMode: true, heading: "No downloaded music to search." }, + { localReady: true, savedAt: 1, offlineMode: true, heading: "No downloaded music." }, ])( "represents library availability: $heading", async ({ localReady, savedAt, offlineMode, heading }) => { @@ -197,8 +197,8 @@ it.each([ artistAlbums: new Map(), albumTracks: new Map(), }, - session: { localReady, offlineMode }, - trackEngine: { getStatus: () => "idle" }, + session: { localReady, offlineMode, downloadedOnly: offlineMode }, + trackEngine: { getStatus: () => "idle", isDownloaded: () => false }, covers: {}, playback: {}, } as unknown as ComponentProps; diff --git a/tests/session.test.ts b/tests/session.test.ts index 5754db0..fe9efb8 100644 --- a/tests/session.test.ts +++ b/tests/session.test.ts @@ -54,6 +54,28 @@ describe("disconnect and cache clear", () => { }); describe("session", () => { + it("keeps browsing scope independent of connection, duplicate queue occurrences and resume", async () => { + const { session, selection, tracks, playback } = await connected(); + const cache = selection.cache!; + cache.setQueue({ tracks: ["missing", "same", "same"], index: 2, position: 17 }); + const queue = cache.queue; + const audio = tracks.setPlaybackConnection.mock.calls.at(-1)![0]; + playback.suspendNetwork.mockClear(); + session.setDownloadedOnly(true); + expect(session.downloadedOnly).toBe(true); + expect(session.offlineMode).toBe(false); + expect(audio!.signal.aborted).toBe(false); + expect(cache.queue).toEqual(queue); + expect(playback.suspendNetwork).not.toHaveBeenCalled(); + await session.setOfflineMode(true); + expect(session.downloadedOnly).toBe(true); + session.setDownloadedOnly(false); + expect(cache.queue).toEqual(queue); + expect(session.offlineMode).toBe(true); + await session.setOfflineMode(false); + expect(cache.queue).toEqual(queue); + expect(session.downloadedOnly).toBe(false); + }); it("reports failed metadata restoration without preventing offline queue restoration", async () => { const { session, metadata, playback, storage, loadCache } = setup(true); storage.setItem("navidrome-offline-mode", "true"); @@ -833,7 +855,7 @@ describe("session", () => { expect(previous.queueDirty).toBe(false); }); - it("keeps three active and three queued downloads across both offline toggles", async () => { + it("pauses all server requests offline and resumes queued downloads on reconnect", async () => { installDisk(); const { session, trackEngine, metadata, playback } = await connected(); const first = deferred(); @@ -851,20 +873,20 @@ describe("session", () => { await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(3)); expect(trackEngine.downloadCount).toBe(6); await session.setOfflineMode(true); - expect(signals.every((signal) => !signal.aborted)).toBe(true); + expect(signals.every((signal) => signal.aborted)).toBe(true); expect(trackEngine.downloadCount).toBe(6); first.resolve(); - await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(4)); + release.resolve(); + await Promise.allSettled(work); + await session.refresh(); + expect(fetcher).toHaveBeenCalledTimes(3); expect(session.offlineMode).toBe(true); - expect(trackEngine.downloadCount).toBe(5); await session.setOfflineMode(false); - expect(signals.every((signal) => !signal.aborted)).toBe(true); expect(metadata.getModifiedAt).toHaveBeenCalledOnce(); expect(playback.refreshQueue).not.toHaveBeenCalled(); release.resolve(); - await Promise.all(work); - expect(fetcher).toHaveBeenCalledTimes(6); - expect(trackEngine.downloadCount).toBe(0); + await vi.waitFor(() => expect(trackEngine.downloadCount).toBe(0)); + expect(fetcher).toHaveBeenCalledTimes(9); }); it("closes download access when the session is destroyed", async () => { @@ -877,19 +899,18 @@ describe("session", () => { expect(connection.signal.aborted).toBe(true); }); - it("retains download access on offline startup without browsing sync or restoring cleared credentials", async () => { + it("opens no server access on offline startup or after clearing credentials", async () => { const { session, storage, network, metadata, auth } = setup(true); storage.setItem("navidrome-offline-mode", "true"); const open = vi.spyOn(network, "open"); session.start(); - await vi.waitFor(() => expect(open).toHaveBeenCalledOnce()); + await vi.waitFor(() => expect(session.localReady).toBe(true)); + expect(open).not.toHaveBeenCalled(); expect(metadata.getModifiedAt).not.toHaveBeenCalled(); - const connection = open.mock.results[0].value; session.disconnect(); - expect(connection.signal.aborted).toBe(true); expect(auth.load()).toBeNull(); await session.setOfflineMode(false); - expect(open).toHaveBeenCalledOnce(); + expect(open).not.toHaveBeenCalled(); expect(session.auth).toBeNull(); }); diff --git a/tests/track-engine.test.ts b/tests/track-engine.test.ts index 991829f..8dda083 100644 --- a/tests/track-engine.test.ts +++ b/tests/track-engine.test.ts @@ -674,12 +674,12 @@ describe("TrackEngine using Cache", () => { const fetcher = vi.fn(async () => new Response(body)); vi.stubGlobal("fetch", fetcher); const network = new Network(); - const controller = new AbortController(); + network.setMode("online"); const { engine, cache } = setup({ concurrency: 1 }); - engine.setDownloadConnection(network.open(auth, controller.signal).audio); + engine.setDownloadConnection(network.open(auth).audio); const results = Promise.allSettled([engine.download("active"), engine.download("queued")]); await wrote.promise; - controller.abort(); + network.setMode("offline"); expect((await results).map((result) => result.status)).toEqual(["rejected", "rejected"]); await vi.waitFor(() => expect(cancel).toHaveBeenCalledOnce()); expect(fetcher).toHaveBeenCalledOnce(); @@ -906,7 +906,7 @@ describe("durable download scheduling", () => { }, ); - it("restores queued and failed work on reopen without fetching completed files again", async () => { + it("restores queued work on reopen but leaves failed jobs for explicit retry", async () => { install(); const first = setup({ online: true, concurrency: 1 }); const fetcher = vi.fn(async () => new Response("bad", { status: 500 })); @@ -922,10 +922,12 @@ describe("durable download scheduling", () => { const next = setup({ cache: restored, concurrency: 1 }); fetcher.mockImplementation(async () => new Response("audio")); next.engine.setDownloadConnection(connection()); - await vi.waitFor(() => expect(completedDownloadCount(restored)).toBe(4)); - expect(next.engine.getStatus("bad")).toBe("downloaded"); + await vi.waitFor(() => expect(completedDownloadCount(restored)).toBe(3)); + expect(next.engine.getStatus("bad")).toBe("failed"); await next.engine.restoreDownloads(); - expect(fetcher.mock.calls).toHaveLength(4); + expect(fetcher.mock.calls).toHaveLength(3); + await next.engine.download("bad"); + expect(completedDownloadCount(restored)).toBe(4); }); it("joins close before confirmed cancellation, preserves committed files, and retires all unfinished intent", async () => { @@ -1173,6 +1175,8 @@ describe("reviewed download failure boundaries", () => { disk.state.beforeClose = async () => {}; const current = reopen ? setup({ cache: new Cache(first.cache.key), online: true }) : first; await current.engine.restoreDownloads(); + expect(current.engine.getStatus("recoverable")).toBe("failed"); + await current.engine.download("recoverable"); await vi.waitFor(() => expect(current.engine.getStatus("recoverable")).toBe("downloaded")); expect(expectCompletedDownload(current.cache, key).size).toBe(14); expect(current.engine.getStatus("recoverable")).toBe("downloaded"); @@ -1233,7 +1237,6 @@ describe("reviewed download failure boundaries", () => { }; const next = new Cache(getAccountKey(other)); await next.enqueueDownload({ ...track, id: "b" }, "mp3", "audio/mpeg"); - await next.failDownload(downloadKey("b", "mp3")); selection.cache = next; engine.activate(); engine.setDownloadConnection(connection(other)); @@ -1244,7 +1247,7 @@ describe("reviewed download failure boundaries", () => { }); }); -it("retries failed formats in one restore batch without a self-retry loop", async () => { +it("leaves failed formats paused on restore and retries only on explicit Download", async () => { install(); const { engine, cache } = setup(); for (const format of ["raw", "mp3"] as const) { @@ -1255,6 +1258,9 @@ it("retries failed formats in one restore batch without a self-retry loop", asyn const fetcher = vi.fn(async () => new Response("bad", { status: 500 })); vi.stubGlobal("fetch", fetcher); engine.setDownloadConnection(connection()); + await engine.restoreDownloads(); + expect(fetcher).not.toHaveBeenCalled(); + engine.downloadMany([track.id]); await vi.waitFor(() => { expect(fetcher).toHaveBeenCalledTimes(2); expect(engine.getStatus(track.id)).toBe("failed"); diff --git a/website/demo.test.ts b/website/demo.test.ts index 83207a6..161ac23 100644 --- a/website/demo.test.ts +++ b/website/demo.test.ts @@ -234,17 +234,18 @@ it("renders supplied track names verbatim without UI badges", async () => { }); it("resets preferences on a new mount without writing to localStorage", async () => { - const toggle = () => document.querySelector("#settings-offline"); + const toggle = () => document.querySelector("#settings-offline-card button"); render(); - await vi.waitFor(() => expect(toggle()?.disabled).toBe(false)); - expect(toggle()!.checked).toBe(false); + await vi.waitFor(() => { + expect(toggle()?.textContent).toBe("Work offline"); + expect(toggle()?.disabled).toBe(false); + }); toggle()!.click(); - await vi.waitFor(() => expect(toggle()!.checked).toBe(true)); + await vi.waitFor(() => expect(toggle()?.textContent).toBe("Connect")); await unmount(component!); component = undefined; render(); - await vi.waitFor(() => expect(toggle()?.disabled).toBe(false)); - expect(toggle()!.checked).toBe(false); + await vi.waitFor(() => expect(toggle()?.textContent).toBe("Work offline")); expect(localStorage.length).toBe(0); });