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
4 changes: 3 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ Select suites for the behavior being changed:

`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
Expand All @@ -137,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:

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ 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

Expand Down
28 changes: 28 additions & 0 deletions docs/iphone-validation.md
Original file line number Diff line number Diff line change
@@ -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.
64 changes: 64 additions & 0 deletions tests/audio-transport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,70 @@ describe("AudioTransport without a mounted component", () => {
expect(release).toHaveBeenCalledOnce();
});

it("ignores a delayed play rejection after interruption and retries only explicitly", async () => {
const { transport, audio, track, getSource, release } = setup();
const playing = deferred<void>();
audio.play.mockReturnValueOnce(playing.promise);
const pending = transport.play(track);
await vi.waitFor(() => expect(audio.play).toHaveBeenCalledOnce());
transport.pause();
playing.reject(new DOMException("Interrupted", "AbortError"));
await pending;
expect(transport.status).toBe("ready");
expect(transport.error).toBeUndefined();
expect(transport.playing).toBe(false);
expect(release).toHaveBeenCalledOnce();
expect(getSource).toHaveBeenCalledOnce();
await transport.resume();
expect(transport.playing).toBe(true);
expect(getSource).toHaveBeenCalledTimes(2);
transport.dispose();
expect(release).toHaveBeenCalledTimes(2);
});

it("cancels a seek waiting for metadata and ignores late metadata and errors", async () => {
const { transport, audio, track, getSource, release } = setup();
getSource.mockResolvedValue({ url: "blob:stream", seekMode: "buffered", release });
await transport.play(track);
audio.readyState = 0;
const seeking = transport.seek(75);
await vi.waitFor(() => expect(audio.src).toBe("blob:stream"));
expect(transport.status).toBe("seeking");
transport.pause();
await seeking;
audio.dispatchEvent(new Event("loadedmetadata"));
audio.dispatchEvent(new Event("error"));
expect(transport.position).toBe(75);
expect(transport.status).toBe("ready");
expect(transport.playing).toBe(false);
expect(audio.src).toBe("");
expect(release).toHaveBeenCalledTimes(2);
audio.readyState = 1;
await transport.resume();
expect(audio.currentTime).toBe(75);
expect(transport.playing).toBe(true);
transport.dispose();
expect(release).toHaveBeenCalledTimes(3);
});

it("does not let a failed retired seek poison a replacement track", async () => {
const { transport, audio, track, getSource, release } = setup();
getSource.mockResolvedValueOnce({ url: "blob:stream", seekMode: "buffered", release });
await transport.play(track);
const source = deferred<PlayerSource>();
getSource.mockReturnValueOnce(source.promise);
const seeking = transport.seek(90);
const signal = getSource.mock.calls[1]![0].signal;
await transport.play({ ...track, metadata: { title: "Replacement" } });
source.reject(new Error("Retired account failed"));
await seeking;
expect(signal.aborted).toBe(true);
expect(transport.metadata?.title).toBe("Replacement");
expect(transport.error).toBeUndefined();
expect(transport.playing).toBe(true);
expect(audio.src).toBe("blob:track");
});

it("does not restart if an idle notification disposes the transport during replacement", async () => {
const { transport, track, getSource, onstatechange } = setup();
await transport.play(track);
Expand Down
119 changes: 117 additions & 2 deletions tests/browser/downloads.test.cjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Real app/engines/OPFS, with only the Subsonic transport intercepted.
const assert = require("node:assert/strict");
const { test } = require("node:test");
const { chromium } = require("playwright");
const { chromium, webkit } = require("playwright");
const fs = require("node:fs/promises");
const path = require("node:path");

Expand All @@ -15,6 +15,7 @@ const tracks = Array.from({ length: 6 }, (_, i) => ({
album: album.name,
artists: [artist],
contentType: "audio/mpeg",
duration: 60,
...(i === 0 ? { coverArt: "cover" } : {}),
}));

Expand All @@ -32,12 +33,21 @@ const otherTracks = [
];

test("Downloads redesign preserves real transfer states and offline files", async (t) => {
const browser = await chromium.launch({ headless: true });
const browserType = process.env.BROWSER === "webkit" ? webkit : chromium;
const browser = await browserType.launch({ headless: true });
console.log(`Playback/download recovery: ${browserType.name()} ${browser.version()}`);
const page = await browser.newPage({
viewport: { width: 1280, height: 900 },
reducedMotion: "reduce",
});
await page.addInitScript(() => {
const NativeAudio = window.Audio;
window.Audio = class extends NativeAudio {
constructor(...args) {
super(...args);
window.testAudio = this;
}
};
const play = HTMLMediaElement.prototype.play;
HTMLMediaElement.prototype.play = function (...args) {
window.testAudio = this;
Expand Down Expand Up @@ -463,6 +473,111 @@ test("Downloads redesign preserves real transfer states and offline files", asyn
assert.equal(await page.getByRole("button", { name: /^Retry download of 6/ }).count(), 0);
});

await t.test(
"decoded cached audio seeks offline and restores local resume without autoplay",
async () => {
await navigate("/library");
await playCached();
await page.waitForFunction(() => window.testAudio.currentTime > 0);
assert.equal(await page.evaluate(() => window.testAudio.duration), 60);
await page
.locator(".app-sidebar")
.getByRole("button", { name: "Work offline", exact: true })
.click();
const before = requests;
// Native input event drives the real Playback/transport seek, not a parallel model.
await page
.getByRole("slider", { name: "Playback position" })
.filter({ visible: true })
.evaluate((input) => {
input.value = "23";
input.dispatchEvent(new Event("input", { bubbles: true }));
});
await page.waitForFunction(() => window.testAudio.currentTime >= 23);
await page
.locator(".mini-player")
.getByRole("button", { name: "Pause", exact: true })
.click();
const savedQueue = await page.locator("#player-dialog .track-row .label").allTextContents();
const savedPosition = await page
.getByRole("slider", { name: "Playback position" })
.filter({ visible: true })
.inputValue();
// Observe the actual queue checkpoint before simulating termination/reload.
await page.waitForFunction(async (position) => {
const accounts = await (
await navigator.storage.getDirectory()
).getDirectoryHandle("accounts");
for await (const [, directory] of accounts.entries()) {
const file = await (await directory.getFileHandle("queue.json")).getFile();
if (Math.abs(JSON.parse(await file.text()).position - Number(position)) < 1)
return true;
}
return false;
}, savedPosition);
// Reload the shell online (also supports the dev server); Work offline persists.
// Native network-offline playback is checked below after hydration.
await page.reload();
await page.getByRole("radio", { name: "Downloaded", exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.testAudio.paused), true);
assert.equal(await page.evaluate(() => window.testAudio.currentSrc), "");
assert.deepEqual(
await page.locator("#player-dialog .track-row .label").allTextContents(),
savedQueue,
);
assert.ok(
Math.abs(
Number(
await page
.getByRole("slider", { name: "Playback position" })
.filter({ visible: true })
.inputValue(),
) - Number(savedPosition),
) < 1,
);
await page.context().setOffline(true);
await page
.locator(".mini-player")
.getByRole("button", { name: "Play", exact: true })
.click();
await page.waitForFunction(
() =>
!window.testAudio.paused &&
window.testAudio.currentTime >= 23 &&
window.testAudio.currentSrc.startsWith("blob:"),
);
await page
.getByRole("slider", { name: "Playback position" })
.filter({ visible: true })
.evaluate((input) => {
input.value = "35";
input.dispatchEvent(new Event("input", { bubbles: true }));
});
await page.waitForFunction(() => window.testAudio.currentTime >= 35);
// A native pause models foreground interruption only, not iOS/OS integration.
await page.evaluate(() => window.testAudio.pause());
await page
.locator(".mini-player")
.getByRole("button", { name: "Play", exact: true })
.click();
await page.waitForFunction(() => !window.testAudio.paused);
assert.equal(requests, before, "cached seek/reload/retry must not contact the server");
await page.context().setOffline(false);
await page
.locator(".mini-player")
.getByRole("button", { name: "Pause", exact: true })
.click();
await page
.locator(".app-sidebar")
.getByRole("button", { name: "Connect", exact: true })
.click();
await page
.locator(".app-sidebar")
.getByRole("button", { name: "Work offline", exact: true })
.waitFor();
},
);

await t.test("unchecked disconnect retains cached playback and offline downloads", async () => {
await navigate("/library");
await playCached();
Expand Down
Loading
Loading