import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { createRoot, createSignal } from "solid-js"; import { captureArtifact, expectNoDiagnostics } from "../../test/diagnostics"; import { clearConnection, saveConnection } from "../connection"; import type { ConnectionSettings } from "../subsonic/types"; import type { LibrarySong } from "../harvest/types"; import { SubsonicClient } from "../subsonic/client"; import { createAudioEngine } from "./engine"; import { forgetMediaVerdicts } from "./media"; import { createPlayerStore, type PlayerStore } from "./store"; import { peekSession, startPlayerSession } from "./session"; import { FakeAudioContext, soundingPasses, stubStreamFetch, type StreamFetchStub, } from "../../test/audio"; /** * Coming back to where the page left off. The store is real, the audio world is * faked (src/test/audio.ts), and the library is the two thunks the wiring is handed * — which is the seam that lets a test say "the index says this track exists" * without booting a whole harvest to say it. * * What is asserted is what a returning listener feels: the bar shows the track they * were on at the second they were at, nothing made a sound or asked the server for a * byte until they said so, and the queue that comes back is the queue that went * away. */ const CONN: ConnectionSettings = { host: "https://nav.example.com", username: "admin", password: "wordpass", }; /** the same identity startPlayerSync switches on: host and user, never password */ const SERVER = "https://nav.example.com\u0000admin"; const KEY = "hackermusic.player.session.v1"; const CLIENT = new SubsonicClient({ host: CONN.host, username: CONN.username, password: CONN.password, }); function song(n: number, over: Partial = {}): LibrarySong { return { id: `s${n}`, title: `Track ${n}`, album: "Album", artist: "Artist", duration: 200 + n, suffix: "flac", source: "subsonic", ...over, }; } const tracks = [song(1), song(2), song(3)]; const store = (raw: unknown): void => localStorage.setItem(KEY, JSON.stringify(raw)); let ctx: FakeAudioContext; let stream: StreamFetchStub; const roots: (() => void)[] = []; function makeStore(): PlayerStore { ctx = new FakeAudioContext(); return createPlayerStore({ engine: createAudioEngine({ createContext: () => ctx }), client: () => CLIENT, fetch: stream.fetch, }); } /** * Wire the session half of the app around a store, the way the app root does — and * hand back the two switches the real wiring holds in the harvest: whether the index * has settled, and what is in it. */ function boot( player: PlayerStore, opts: { songs?: LibrarySong[]; ready?: boolean } = {}, ): { setSongs: (rows: LibrarySong[]) => void; setReady: (ready: boolean) => void } { const [songs, setSongs] = createSignal(opts.songs ?? tracks); const [ready, setReady] = createSignal(opts.ready ?? true); createRoot((dispose) => { roots.push(dispose); startPlayerSession({ // read imperatively, exactly as the app wires it: the connection is not a // thing this effect reacts to (see SessionSyncDeps) connection: () => CONN, ready, songs, store: player, }); }); return { setSongs, setReady }; } beforeEach(() => { localStorage.clear(); clearConnection(); forgetMediaVerdicts(); FakeAudioContext.reset(); stream = stubStreamFetch(); vi.stubGlobal("fetch", stream.fetch); saveConnection(CONN); }); afterEach(() => { roots.splice(0).forEach((dispose) => dispose()); vi.unstubAllGlobals(); // a test that failed under fake timers must not hand them to its neighbour: the // next one's waitFor would be waiting on a clock nobody is advancing vi.useRealTimers(); }); it("keeps the queue, the track, and the second the transport was left at", async () => { const player = makeStore(); player.playSongs(tracks, 1, 42); // mid-file, on the second of three await vi.waitFor(() => expect(player.peekState()).toBe("playing")); expect(peekSession()).toEqual({ server: SERVER, ids: ["s1", "s2", "s3"], at: "s2", atOffset: 42, }); }); it("keeps the A–B region the track was looping, against the track it was set on", async () => { const player = makeStore(); player.playSongs(tracks, 1, 12); await vi.waitFor(() => expect(player.peekState()).toBe("playing")); expect(player.setLoop({ start: 10, end: 30 })).toBe(true); // Taking a region moves the clock to its start, so the session now remembers A — which is // the right thing to have been listening to when the tab closed, and is why the seek below // is what has to carry the "not at A" case for the reload test that reads this record. expect(player.peekPosition()).toBe(10); player.seek(12); // inside the region, so the region survives the move // The press writes it, not the five-second tick: that cadence exists to spare the // disk during a drag, and a region is one deliberate keypress that must not be the // kind of thing a reload is allowed to forget. expect(peekSession()).toEqual({ server: SERVER, ids: ["s1", "s2", "s3"], at: "s2", atOffset: 12, // stamped with the track, which is what lets the read-back refuse a region that // has drifted onto another timeline loop: { at: "s2", start: 10, end: 30 }, }); // and clearing it writes that too — a stale region coming back at the next reload // would be a loop nobody set expect(player.setLoop(null)).toBe(true); expect(peekSession()!.loop).toBeUndefined(); }); it("comes back to the loop, and the second pass starts at A", async () => { const before = makeStore(); before.playSongs(tracks, 1, 12); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); expect(before.setLoop({ start: 10, end: 30 })).toBe(true); // The press left the clock on A, which is the point of the press — and the reason a // deliberate move is needed here: without one, the assert below that the restored pass // starts at 12 rather than 10 would be true for the wrong reason and would stop testing // anything the moment the clock began following the region. before.seek(12); FakeAudioContext.reset(); const after = makeStore(); boot(after); await vi.waitFor(() => expect(after.peekCurrent()?.id).toBe("s2")); // Restored without a byte fetched or a boundary placed: there is nothing to measure // against until the bytes land, so the region waits rather than being drawn against // the index's claim or clamped to a number nobody has verified. expect(after.peekState()).toBe("idle"); expect(after.peekLoop()).toEqual({ start: 10, end: 30 }); expect(ctx.decodeRequests).toEqual([]); after.toggle(); await vi.waitFor(() => expect(after.peekState()).toBe("playing")); const first = soundingPasses(ctx, "s2")[0]!; expect(first.startOffset).toBe(12); // where it was left, not where A is expect(first.stopAt).toBeCloseTo(first.startedAt! + (30 - 12), 6); ctx.advance(25); const again = soundingPasses(ctx, "s2")[1]!; expect(again.startOffset).toBe(10); // ...and from here on it is A every time expect(after.peekCursor()).toBe(1); }); it("survives a reload of the restored state, with nothing pressed in between", async () => { const before = makeStore(); before.playSongs(tracks, 1, 12); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); expect(before.setLoop({ start: 10, end: 30 })).toBe(true); FakeAudioContext.reset(); const restored = makeStore(); boot(restored); await vi.waitFor(() => expect(restored.peekCurrent()?.id).toBe("s2")); // No press, no play, no fetch: the only write between the two boots is the flush that // puts the restored blob back when the tab goes away. If it drops the region, the next // reload loses a loop the user set and never got a chance to clear — which is the // difference between persisting the loop and happening to keep it until someone touches // the transport. window.dispatchEvent(new Event("pagehide")); expect(peekSession()!.loop).toEqual({ at: "s2", start: 10, end: 30 }); const again = makeStore(); boot(again); await vi.waitFor(() => expect(again.peekCurrent()?.id).toBe("s2")); expect(again.peekLoop()).toEqual({ start: 10, end: 30 }); }); it("drops a stored region belonging to another track", async () => { const before = makeStore(); before.playSongs(tracks, 1, 12); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); // A blob whose region names a different track from the one the session is on: a poke // in DevTools, an older build, a tab that wrote between two presses. The position // gets this guarantee for free by being read beside `at`; the region asks for it by // name, and a loop that silently moved onto the next track is a wrong number on the // bar rather than a preference kept. store({ server: SERVER, ids: ["s1", "s2", "s3"], at: "s2", atOffset: 12, loop: { at: "s1", start: 10, end: 30 }, }); const after = makeStore(); boot(after); await vi.waitFor(() => expect(after.peekCurrent()?.id).toBe("s2")); expect(after.peekPosition()).toBe(12); // the position came back; the region did not expect(after.peekLoop()).toBeNull(); after.toggle(); await vi.waitFor(() => expect(after.peekState()).toBe("playing")); expect(ctx.sourceFor("s2")!.stopAt).toBeUndefined(); }); it("reads a junk region as nothing stored, not as a boundary", async () => { const base = { server: SERVER, ids: ["s1"], at: "s1", atOffset: 0 }; const junk = [ { ...base, loop: { at: "s1", start: "10", end: 20 } }, { ...base, loop: { at: "s1", start: Number.NaN, end: 20 } }, // to null through JSON { ...base, loop: { at: "s1", start: 20, end: 10 } }, // end before start { ...base, loop: { at: "s1", start: -1, end: 20 } }, // before the track begins { ...base, loop: { at: "", start: 1, end: 2 } }, // belonging to no track { ...base, loop: "loop" }, { ...base, loop: null }, ]; for (const raw of junk) { localStorage.setItem(KEY, JSON.stringify(raw)); const fresh = makeStore(); boot(fresh); await vi.waitFor(() => expect(ctx.decodeRequests).toEqual([])); // The whole blob goes, as it does for every other junk value here: to a caller a // region nobody can trust and no region at all are the same answer, and NaN used // as a boundary is the one outcome that cannot be allowed. expect(fresh.peekCurrent(), JSON.stringify(raw)).toBeNull(); expect(fresh.peekLoop(), JSON.stringify(raw)).toBeNull(); } }); it("comes back to the same track and the same second, silent", async () => { const before = makeStore(); before.playSongs(tracks, 1, 42); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); const requested = stream.urls.length; // The reload: a player with nothing in it, and the same page's storage. The // reset comes after the fixture's context exists, so what is counted is what the // restore itself would have built. const after = makeStore(); FakeAudioContext.reset(); expect(after.peekCurrent()).toBeNull(); boot(after); await vi.waitFor(() => expect(after.peekCurrent()?.id).toBe("s2")); expect(after.peekState()).toBe("idle"); // not "paused": nothing was ever loaded expect(after.peekPosition()).toBe(42); expect(after.peekCursor()).toBe(1); expect(after.queueIds()).toEqual(["s1", "s2", "s3"]); // The claim that makes this a restore rather than a play: no audio context was // built, no byte was decoded, and no request was made. A restore that reached for // the graph would also be a page making noise at whoever opened it. expect(FakeAudioContext.instances).toHaveLength(0); expect(ctx.decodeRequests).toEqual([]); expect(stream.urls).toHaveLength(requested); }); it("pressing play after the return starts at the second on the bar", async () => { const before = makeStore(); before.playSongs(tracks, 1, 42); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); FakeAudioContext.reset(); const after = makeStore(); boot(after); await vi.waitFor(() => expect(after.peekCurrent()?.id).toBe("s2")); after.toggle(); // the space bar, which is the whole point of coming back await vi.waitFor(() => expect(after.peekState()).toBe("playing")); // not the top of the track: the second the slider has been showing since the // page opened, which is the promise the bar makes and this keeps expect(ctx.sourceFor("s2")!.startOffset).toBe(42); }); it("the saved second does not ride onto the next track", async () => { const before = makeStore(); before.playSongs(tracks, 0, 42); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); FakeAudioContext.reset(); const after = makeStore(); boot(after); await vi.waitFor(() => expect(after.peekCurrent()?.id).toBe("s1")); after.next(); // a choice, and a different track: it starts where tracks start await vi.waitFor(() => expect(after.peekState()).toBe("playing")); expect(ctx.sourceFor("s2")!.startOffset).toBe(0); }); it("leaves a queue that belongs to another server where it found it", async () => { const player = makeStore(); store({ server: "https://other.example\u0000admin", ids: ["s1"], at: "s1", atOffset: 9 }); boot(player); await vi.waitFor(() => expect(ctx.decodeRequests).toEqual([])); // Not restored — those ids are another server's — and not cleared either: one key // holds one session and the user may well go back, so overwriting what is stored // is the next session's business rather than this check's. expect(player.peekCurrent()).toBeNull(); expect(peekSession()).toMatchObject({ server: "https://other.example\u0000admin", at: "s1" }); }); it("treats a session whose track left the library as no session", async () => { const player = makeStore(); store({ server: SERVER, ids: ["s1", "s2", "gone"], at: "gone", atOffset: 10 }); boot(player); await vi.waitFor(() => expect(peekSession()).toBeNull()); // The position belongs to a file that is off the server and there is no nearest // second to fall back to: coming back to the row next to where the user was, in // the middle of a different track, would be an invention. expect(player.peekCurrent()).toBeNull(); expect(player.queueIds()).toEqual([]); }); it("reads a stored shape that cannot mean anything as nothing stored", async () => { const player = makeStore(); // Each of these parses as an object with the right keys; none is a session. The // first three would otherwise reach the store as values — an empty queue with an // empty track in it at a negative second — and be refused there, in a code path // with nothing left to say about it. const junk = [ { server: SERVER, ids: [], at: "", atOffset: 0 }, { server: "", ids: ["s1"], at: "s1", atOffset: 0 }, { server: SERVER, ids: ["s1"], at: "s1", atOffset: -5 }, { server: SERVER, ids: ["s1"], at: "s1", atOffset: "long" }, ["not", "an", "object"], ]; for (const raw of junk) { localStorage.setItem(KEY, raw instanceof Array ? raw.join("-") : JSON.stringify(raw)); const fresh = makeStore(); boot(fresh); await vi.waitFor(() => expect(ctx.decodeRequests).toEqual([])); expect(fresh.peekCurrent(), JSON.stringify(raw)).toBeNull(); expect(fresh.queueIds(), JSON.stringify(raw)).toEqual([]); } expect(player.peekCurrent()).toBeNull(); }); it("leaves the queue the listener started alone when the index arrives late", async () => { const player = makeStore(); player.playSongs([song(9, { id: "mine" })], 0); await vi.waitFor(() => expect(player.peekState()).toBe("playing")); store({ server: SERVER, ids: ["s1", "s2"], at: "s2", atOffset: 7 }); boot(player); // the harvest was already done; the restore gets its chance now await vi.waitFor(() => expect(ctx.decodeRequests.length).toBeGreaterThan(0)); // A harvest landing after the listener pressed play must not trade the track they // chose for the one from before the reload. What is stored is theirs to lose. expect(player.peekCurrent()?.id).toBe("mine"); expect(peekSession()).toMatchObject({ at: "s2", atOffset: 7 }); }); it("waits for the index instead of concluding the queue is gone", async () => { const before = makeStore(); before.playSongs(tracks, 1, 42); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); const after = makeStore(); const index = boot(after, { ready: false, songs: [] }); await vi.waitFor(() => expect(after.peekCurrent()).toBeNull()); // A first crawl serves up "nothing resolves" as its normal answer, and acting on // that would delete a good session because the harvest was slow. expect(peekSession()).not.toBeNull(); index.setReady(true); index.setSongs(tracks); await vi.waitFor(() => expect(after.peekCurrent()?.id).toBe("s2")); expect(after.peekPosition()).toBe(42); }); it("forgets the session when the queue runs out", async () => { const player = makeStore(); player.playSongs(tracks, 0); await vi.waitFor(() => expect(player.peekState()).toBe("playing")); expect(peekSession()).not.toBeNull(); // An album that finished and a player the user emptied are both the listener // saying they are done; bringing either back at the next reload is a claim about // listening that is no longer true. player.stop(); expect(peekSession()).toBeNull(); }); it("forgets the session when the listener leaves the server", async () => { const player = makeStore(); player.playSongs(tracks, 0); await vi.waitFor(() => expect(player.peekState()).toBe("playing")); expect(peekSession()).not.toBeNull(); // What signing out does to the transport: startPlayerSync disposes the player for // the server it was attached to, and an emptied player has no session to hand to // the next visit — the queue belongs to the server it came from. player.dispose(); expect(peekSession()).toBeNull(); }); it("the thumb can be moved before anything has been heard, and play goes there", async () => { const before = makeStore(); before.playSongs(tracks, 1, 42); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); FakeAudioContext.reset(); const after = makeStore(); boot(after); await vi.waitFor(() => expect(after.peekCurrent()?.id).toBe("s2")); // The bar shows a timeline the listener has not yet started: dragging it is the // way they say where to begin, and what they dragged to beats what was stored. after.seek(90); expect(after.peekPosition()).toBe(90); after.toggle(); await vi.waitFor(() => expect(after.peekState()).toBe("playing")); expect(ctx.sourceFor("s2")!.startOffset).toBe(90); }); it("the saved second does not ride onto the next track", async () => { const before = makeStore(); before.playSongs(tracks, 0, 42); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); FakeAudioContext.reset(); const after = makeStore(); boot(after); await vi.waitFor(() => expect(after.peekCurrent()?.id).toBe("s1")); // A position belongs to the track it was measured on. `n` is a choice about what // to hear, not a request to start track two at thirty-seven seconds. after.next(); await vi.waitFor(() => expect(after.peekState()).toBe("playing")); expect(ctx.sourceFor("s2")!.startOffset).toBe(0); }); it("the thumb can be moved before anything has been heard, and play goes there", async () => { const before = makeStore(); before.playSongs(tracks, 1, 42); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); FakeAudioContext.reset(); const after = makeStore(); boot(after); await vi.waitFor(() => expect(after.peekCurrent()?.id).toBe("s2")); // The bar offers a timeline the listener has not started yet: dragging is how // they say where to begin, and where they dragged beats what was stored. after.seek(90); expect(after.peekPosition()).toBe(90); after.toggle(); await vi.waitFor(() => expect(after.peekState()).toBe("playing")); expect(ctx.sourceFor("s2")!.startOffset).toBe(90); }); it("the second a pause left on the clock is the second that is kept", async () => { const player = makeStore(); player.playSongs(tracks, 1, 42); await vi.waitFor(() => expect(player.peekState()).toBe("playing")); expect(peekSession()?.atOffset).toBe(42); // where it was asked to start // 30 seconds of listening later — and pause is when the number stops moving, so // it is the last honest moment before the page goes away ctx.advance(30); await vi.waitFor(() => expect(player.peekPosition()).toBeCloseTo(42 + 30 - 0.08, 1)); player.toggle(); expect(player.peekState()).toBe("paused"); expect(peekSession()?.atOffset).toBeCloseTo(42 + 30 - 0.08, 1); }); it("keeps up with a track nobody paused on", async () => { // Fake timers from the start: the position ticker is a real interval, and one // created before the clock was captured would never be advanced by this test. vi.useFakeTimers(); const player = makeStore(); player.playSongs(tracks, 0); await vi.advanceTimersByTimeAsync(300); expect(player.peekState()).toBe("playing"); expect(peekSession()?.atOffset).toBe(0); // An announced exit is the easy case; this is the phone tab the OS closes without // asking. The position has to reach disk on its own, on a coarse tick. ctx.advance(20); await vi.advanceTimersByTimeAsync(5300); // past the five-second write expect(peekSession()?.atOffset).toBeCloseTo(20 - 0.08, 1); }); it("puts the exact second on disk when the page goes away", async () => { const player = makeStore(); boot(player); player.playSongs(tracks, 0); await vi.waitFor(() => expect(player.peekState()).toBe("playing")); // not a multiple of the five-second bucket, so a stored second here can only have // come from the clock itself rather than from the last coarse write ctx.advance(12.3); await vi.waitFor(() => expect(player.peekPosition()).toBeCloseTo(12.22, 1)); document.dispatchEvent(new Event("visibilitychange")); // the phone case expect(peekSession()?.atOffset).toBeCloseTo(12.22, 1); window.dispatchEvent(new Event("pagehide")); // the reload case expect(peekSession()?.atOffset).toBeCloseTo(12.22, 1); }); it("writes nothing on the way out for a session it never took over", async () => { const player = makeStore(); player.playSongs(tracks, 1, 42); // the store's own write: 42 is on disk await vi.waitFor(() => expect(player.peekState()).toBe("playing")); expect(peekSession()?.atOffset).toBe(42); boot(player, { ready: false }); // the index never settled: this page has no session ctx.advance(30); // and the clock has since moved on await new Promise((r) => setTimeout(r, 300)); // long enough to write, short of a tick window.dispatchEvent(new Event("pagehide")); // What the flush would have written is the live position, over the second the // session was earned at — which is the one thing a backgrounded tab must not do // to a visit it has not yet taken over. expect(peekSession()).toEqual({ server: SERVER, ids: ["s1", "s2", "s3"], at: "s2", atOffset: 42, }); }); it("keeps a queue of a thousand tracks, around the track that matters", async () => { const many = Array.from({ length: 1400 }, (_, i) => song(i + 1)); const player = makeStore(); player.playSongs(many, 1300); await vi.waitFor(() => expect(player.peekState()).toBe("playing")); const saved = peekSession()!; expect(saved.ids).toHaveLength(1000); // centred where the track is, and slid back to fit when the centre would have // pushed the window off the end: a window that stopped short of the last track // would leave `n` running out with tracks still queued expect(saved.at).toBe("s1301"); expect(saved.ids).toContain("s1301"); expect(saved.ids[0]).toBe("s401"); expect(saved.ids.at(-1)).toBe("s1400"); }); it("does not adopt a session that appeared in storage after this page read it", async () => { const player = makeStore(); const index = boot(player); // nothing stored: the reader came up empty, and is done await vi.waitFor(() => expect(player.peekCurrent()).toBeNull()); // A second tab, or a session written by the next visit while this one sits idle. // Re-reading it here would put a queue on a transport the listener never touched. store({ server: SERVER, ids: ["s2", "s3"], at: "s2", atOffset: 4 }); index.setReady(false); // the poll re-harvests, which is what re-offers the read index.setReady(true); await vi.waitFor(() => expect(player.queueIds()).toEqual([])); expect(player.peekCurrent()).toBeNull(); }); it("restores with zero reactive diagnostics, and once per connection only", async () => { const before = makeStore(); before.playSongs(tracks, 1, 42); await vi.waitFor(() => expect(before.peekState()).toBe("playing")); const after = makeStore(); const { artifact } = await captureArtifact(async () => { const index = boot(after); await vi.waitFor(() => expect(after.peekCurrent()?.id).toBe("s2")); // A re-harvest republishes the index, and another visit may have left a session // of its own in storage since. This page already read its answer: adopting twice // would mean the queue on the bar is whatever the storage holds now, rather than // the one this page came back with. localStorage.setItem( KEY, JSON.stringify({ server: SERVER, ids: ["s3"], at: "s3", atOffset: 5 }), ); index.setReady(false); // the poll re-harvests; what this page read does not move index.setReady(true); await vi.waitFor(() => expect(after.queueIds()).toEqual(["s1", "s2", "s3"])); expect(after.peekCurrent()?.id).toBe("s2"); expect(after.peekPosition()).toBe(42); // ...and the same holds over a queue the listener replaced: what the storage // says is not allowed to reach the transport a second time. after.playSongs([song(7, { id: "other" })], 0); index.setReady(false); index.setReady(true); await vi.waitFor(() => expect(after.queueIds()).toEqual(["other"])); expect(after.peekCurrent()?.id).toBe("other"); }); expectNoDiagnostics(artifact); });