fix(music): shuffle tracks paged into an already-shuffled queue

Reloading the playlist with preserveShuffle kept the existing order but
appended newly loaded tracks in server order, so playback went
sequential once the previously loaded window ran out.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-08-30 15:25:07 -04:00
parent e4bf57643b
commit 8b3ca227e2
2 changed files with 41 additions and 3 deletions

View File

@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { createPinia, setActivePinia } from "pinia";
import { describe, expect, it, vi } from "vitest";
import { FRONTEND_RESOURCES_PATH } from "@/utils";
import {
import useSoundtrackPlayer, {
resolveSoundtrackGameArtwork,
type SoundtrackArtworkRom,
} from "./soundtrackPlayer";
@@ -85,3 +86,37 @@ describe("resolveSoundtrackGameArtwork", () => {
expect(resolveSoundtrackGameArtwork(makeRom())).toBeUndefined();
});
});
describe("loadPlaylist with preserved shuffle", () => {
function makeTracks(count: number, offset = 0) {
return Array.from({ length: count }, (_, i) => ({
romId: 1,
fileId: offset + i + 1,
fileName: `track-${offset + i + 1}.mp3`,
url: `/tracks/${offset + i + 1}`,
}));
}
it("shuffles freshly paged-in tracks instead of appending them in order", () => {
setActivePinia(createPinia());
const player = useSoundtrackPlayer();
const firstPage = makeTracks(4);
player.loadPlaylist(firstPage, {}, null);
player.toggleShuffle();
const shuffledFirstPage = [...player.playlist];
const nextPage = makeTracks(4, 4);
// Force the worst shuffle luck: Math.random() = 0 still may not produce
// the identity permutation, so an in-order tail proves the bug.
const randomSpy = vi.spyOn(Math, "random").mockReturnValue(0);
player.loadPlaylist([...firstPage, ...nextPage], {}, null, true);
randomSpy.mockRestore();
const ids = (tracks: { fileId: number }[]) => tracks.map((t) => t.fileId);
// The already-shuffled window keeps its order.
expect(ids(player.playlist.slice(0, 4))).toEqual(ids(shuffledFirstPage));
// The appended window holds the same tracks but not in server order.
expect(ids(player.playlist.slice(4)).sort()).toEqual(ids(nextPage).sort());
expect(ids(player.playlist.slice(4))).not.toEqual(ids(nextPage));
});
});

View File

@@ -168,9 +168,12 @@ const useSoundtrackPlayer = defineStore("soundtrackPlayer", () => {
tracksByKey.delete(item.romId + ":" + item.fileId);
return [next];
});
// Tracks not in the previous order (a freshly paged-in window) join
// shuffled too, or playback would turn sequential once the already
// loaded portion of the queue runs out.
playlist.value =
restored.length > 0
? [...restored, ...tracksByKey.values()]
? [...restored, ...shuffled([...tracksByKey.values()])]
: shuffled([...tracksByKey.values()]);
return;
}