fix(playback): preserve the current queue until direct play starts

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 18:37:50 +08:00
1 parent de6b050646
commit b0393b42b2
5 files changed
+206 -62

No files matched your search

+92 -1
View File
@@ -1397,6 +1397,7 @@ const playSingleSong = BotInstance.prototype.playSingleSong as (
this: unknown, this: unknown,
song: unknown, song: unknown,
requesterName?: string, requesterName?: string,
onFailure?: (failure: PlayFailure, currentTrackContinues?: boolean) => void,
) => Promise<boolean>; ) => Promise<boolean>;
const loadSavedQueue = BotInstance.prototype.loadSavedQueue as ( const loadSavedQueue = BotInstance.prototype.loadSavedQueue as (
this: unknown, this: unknown,
@@ -1439,7 +1440,10 @@ describe("BotInstance.playSingleSong / playKeepsQueue (#119)", () => {
isSameSong, isSameSong,
disableFmMode: vi.fn(), disableFmMode: vi.fn(),
sweepLocalAudio: vi.fn(), sweepLocalAudio: vi.fn(),
resolveAndPlay: vi.fn(async () => true), resolveAndPlay: vi.fn(async (_song, _onFailure, commitQueue?: () => void) => {
commitQueue?.();
return true;
}),
} as any; } as any;
} }
@@ -1473,6 +1477,93 @@ describe("BotInstance.playSingleSong / playKeepsQueue (#119)", () => {
expect(ctx.queue.list().map((s: any) => s.id)).toEqual(["b"]); expect(ctx.queue.list().map((s: any) => s.id)).toEqual(["b"]);
expect(ctx.queue.current()?.id).toBe("b"); expect(ctx.queue.current()?.id).toBe("b");
}); });
it.each([
[false, "new"], [false, "old"], [true, "new"], [true, "old"],
] as const)("retains the current queue and stream after a failed direct start (keep=%s, requested=%s)", async (keep, id) => {
const ctx = makeCtx(keep);
const current = song119("old");
ctx.queue.add(current);
ctx.queue.add(song119("following"));
ctx.queue.play();
ctx.player._play();
ctx.player.getPlaybackSessionId = () => 3;
ctx.resolveAndPlay.mockImplementation(async (_track: QueuedSong, onFailure?: (failure: PlayFailure) => void) => {
onFailure?.({ platform: "netease", songId: id, code: "unknown", message: "No URL" });
return false;
});
const failure = vi.fn();
expect(await playSingleSong.call(ctx, song119(id), "alice", failure)).toBe(false);
expect(ctx.queue.current()).toBe(current);
expect(ctx.queue.list().map((song: QueuedSong) => song.id)).toEqual(["old", "following"]);
expect(ctx.player.stop).not.toHaveBeenCalled();
expect(ctx.disableFmMode).not.toHaveBeenCalled();
expect(ctx.sweepLocalAudio).not.toHaveBeenCalled();
expect(failure).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: "No URL" }), id === "old");
});
function makeRealStartCtx() {
const queue = new PlayQueue();
queue.add(song119("old"));
queue.add(song119("following"));
queue.play();
const player = Object.assign(new EventEmitter(), makePlayer(), {
resetFailures: vi.fn(), getPlaybackSessionId: () => 1,
});
const ctx = Object.assign(makeResolveCtx({ controller: makeController(), player, url: "" }), {
queue, player, withRequester, isSameSong, disableFmMode: vi.fn(),
sweepLocalAudio: vi.fn(), spotifyController: new EventEmitter(),
resumeInterruptedStream: async () => false,
});
ctx.playNext = BotInstance.prototype.playNext.bind(ctx);
ctx.resolveAndPlay = BotInstance.prototype.resolveAndPlay.bind(ctx);
setupPlayerEvents.call(ctx);
return ctx;
}
it("looks up a successful direct play once and commits the queue before status publication", async () => {
const ctx = makeRealStartCtx();
const getSongUrl = vi.fn(async () => ({ url: "https://example.test/new.mp3" }));
ctx.getProviderFor.mockReturnValue({ platform: "netease", getSongUrl });
ctx.emit.mockImplementation((event: string) => {
if (event === "stateChange") expect(ctx.queue.current()?.id).toBe("new");
});
expect(await playSingleSong.call(ctx, song119("new"), "alice")).toBe(true);
expect(getSongUrl).toHaveBeenCalledTimes(1);
expect(ctx.queue.current()).toMatchObject({ id: "new", requestedBy: "alice", url: "https://example.test/new.mp3" });
expect(ctx.emit).toHaveBeenCalledExactlyOnceWith("stateChange");
});
it("lets the current track end normally during an unresolved direct request", async () => {
const ctx = makeRealStartCtx();
ctx.player.play("https://example.test/old.mp3");
ctx.player.play.mockClear();
const lookupStarted = deferred();
const directLookup = deferred<{ url: string }>();
const getSongUrl = vi.fn(async (id: string) => {
if (id === "new") {
lookupStarted.resolve();
return directLookup.promise;
}
return { url: "https://example.test/following.mp3" };
});
ctx.getProviderFor.mockReturnValue({ platform: "netease", getSongUrl });
const request = playSingleSong.call(ctx, song119("new"));
await lookupStarted.promise;
expect(ctx.queue.current()?.id).toBe("old");
expect(ctx.player.getState()).toBe("playing");
ctx.player.stop();
ctx.player.emit("trackEnd");
await new Promise<void>(resolve => setImmediate(resolve));
directLookup.resolve({ url: "https://example.test/stale.mp3" });
expect(await request).toBe(false);
expect(ctx.queue.current()?.id).toBe("following");
expect(getSongUrl.mock.calls.map(([id]) => id)).toEqual(["new", "following"]);
expect(ctx.player.play).toHaveBeenCalledExactlyOnceWith("https://example.test/following.mp3", 0, 1);
});
}); });
describe("BotInstance.loadSavedQueue (#119)", () => { describe("BotInstance.loadSavedQueue (#119)", () => {
+53 -51
View File
@@ -1077,7 +1077,11 @@ export class BotInstance extends EventEmitter {
} }
/** Resolve the URL and start playback if this request still owns the queue. */ /** Resolve the URL and start playback if this request still owns the queue. */
async resolveAndPlay(song: QueuedSong, onFailure?: (failure: PlayFailure) => void): Promise<boolean> { async resolveAndPlay(
song: QueuedSong,
onFailure?: (failure: PlayFailure) => void,
commitQueue?: () => void,
): Promise<boolean> {
const request = Symbol(); const request = Symbol();
this.playbackRequest = request; this.playbackRequest = request;
const generation = this.lifecycleGeneration; const generation = this.lifecycleGeneration;
@@ -1098,10 +1102,6 @@ export class BotInstance extends EventEmitter {
fail("该机器人已关闭本地音频播放"); fail("该机器人已关闭本地音频播放");
return false; return false;
} }
// Clear any accumulated skip votes — every fresh track starts with a
// clean slate, regardless of which code path loaded it (cmdPlay,
// cmdPlaylist, cmdAlbum, cmdFm, trackEnd auto-advance, etc.).
this.voteSkipUsers.clear();
try { try {
const provider = this.getProviderFor(song.platform); const provider = this.getProviderFor(song.platform);
if (song.platform === "bilibili" && (!song.id.includes("?p=") || song.duration === 0)) { if (song.platform === "bilibili" && (!song.id.includes("?p=") || song.duration === 0)) {
@@ -1221,7 +1221,8 @@ export class BotInstance extends EventEmitter {
// frame counter is not reset, so player.getElapsed() over-reads for the // frame counter is not reset, so player.getElapsed() over-reads for the
// 2nd+ consecutive Spotify track. Cosmetic only — the authoritative // 2nd+ consecutive Spotify track. Cosmetic only — the authoritative
// elapsed shown to users is status.track.position from the backend poll. // elapsed shown to users is status.track.position from the backend poll.
if (!this.player.isExternalActive()) { if (commitQueue) this.player.resetFailures();
if (commitQueue || !this.player.isExternalActive()) {
this.player.playPcmStream(this.spotifyController.getPcmStream(), { this.player.playPcmStream(this.spotifyController.getPcmStream(), {
// The sidecar PCM pipe is long-lived; per-track end arrives via the // The sidecar PCM pipe is long-lived; per-track end arrives via the
// controller "trackEnded" WS event, not stream EOF. A real EOF here // controller "trackEnded" WS event, not stream EOF. A real EOF here
@@ -1259,6 +1260,7 @@ export class BotInstance extends EventEmitter {
this.logger.warn({ err }, "Failed to pause Spotify sidecar on source switch")); this.logger.warn({ err }, "Failed to pause Spotify sidecar on source switch"));
this.currentSourceIsSpotify = false; this.currentSourceIsSpotify = false;
} }
if (commitQueue) this.player.resetFailures();
this.effectiveDuration = result.trialDuration ?? song.duration; this.effectiveDuration = result.trialDuration ?? song.duration;
this.player.play(result.url, 0, this.effectiveDuration); this.player.play(result.url, 0, this.effectiveDuration);
} }
@@ -1271,6 +1273,9 @@ export class BotInstance extends EventEmitter {
return false; return false;
} }
// A direct play request commits its queue only after playback starts.
commitQueue?.();
this.voteSkipUsers.clear();
// Playback has started. Failures in bookkeeping must not skip a track // Playback has started. Failures in bookkeeping must not skip a track
// or turn an otherwise successful playback request into an error. // or turn an otherwise successful playback request into an error.
this.autoPaused = false; this.autoPaused = false;
@@ -1503,56 +1508,53 @@ export class BotInstance extends EventEmitter {
if (error) return error; if (error) return error;
const song0 = song!; const song0 = song!;
let why: string | undefined; let why: string | undefined;
const ok = await this.playSingleSong(song0, requesterName, failure => { why = failure.message; }); const ok = await this.playSingleSong(song0, requesterName, (failure, currentTrackContinues) => {
if (!ok) return why ? `Cannot play: ${song0.name} — ${why}` : `Cannot play: ${song0.name}`; why = currentTrackContinues
? `Could not restart ${song0.name}. The current track is still playing: ${failure.message}`
: `Cannot play: ${song0.name} — ${failure.message}`;
});
if (!ok) return why ?? `Cannot play: ${song0.name}`;
return `Now playing: ${song0.name} - ${song0.artist}`; return `Now playing: ${song0.name} - ${song0.artist}`;
} }
/** /** Start the requested song before changing the queue or stopping FM. */
* Play a single resolved song immediately, honoring config.playKeepsQueue: async playSingleSong(
* - false (default): clear the queue and play only this song — today's song: QueuedSong,
* behavior. The prior track is stopped and released local uploads swept. requesterName?: string,
* - true (and the queue is non-empty): insert the song after the current onFailure?: (failure: PlayFailure, currentTrackContinues?: boolean) => void,
* track and jump to it (reusing addNext + playAt — no new queue logic), so ): Promise<boolean> {
* the rest of the queue survives and continues after it. FM auto-refill is const requested = this.withRequester(song, requesterName);
* stopped (manual takeover), but existing queued songs are preserved.
*
* Shared by chat !play and the web /play-song route so the toggle decision
* lives in exactly one place (#119). Returns true if a track started playing.
*/
async playSingleSong(song: QueuedSong, requesterName?: string, onFailure?: (failure: PlayFailure) => void): Promise<boolean> {
const s = this.withRequester(song, requesterName);
if (this.config.playKeepsQueue && !this.queue.isEmpty()) {
const insertedAt =
this.queue.getCurrentIndex() < 0
? this.queue.size()
: this.queue.getCurrentIndex() + 1;
this.player.stop();
this.disableFmMode();
this.queue.addNext(s);
this.queue.playAt(insertedAt);
this.player.resetFailures();
// No sweep here: the queue is kept, so no local uploads were released.
return this.resolveAndPlay(this.queue.current()!, onFailure);
}
// Legacy replace behavior (default).
const previous = this.queue.current(); const previous = this.queue.current();
if (previous && !this.isSameSong(previous, s)) { const previousSession = this.isSameSong(previous, requested) ? this.player.getPlaybackSessionId() : undefined;
this.player.stop(); const keepQueue = this.config.playKeepsQueue && !this.queue.isEmpty();
let failure: PlayFailure | undefined;
const started = await this.resolveAndPlay(requested, reason => { failure = reason; }, () => {
this.disableFmMode();
if (keepQueue) {
const currentIndex = this.queue.getCurrentIndex();
const index = currentIndex < 0 ? this.queue.size() : currentIndex + 1;
this.queue.addNext(requested);
this.queue.playAt(index);
} else {
this.queue.clear();
this.queue.add(requested);
this.queue.play();
}
});
if (!started) {
const currentTrackContinues = previousSession !== undefined &&
this.queue.current() === previous && this.player.getPlaybackSessionId() === previousSession &&
this.player.getState() === "playing";
onFailure?.(failure ?? {
platform: song.platform,
songId: song.id,
code: "unknown",
message: "播放请求已取消",
}, currentTrackContinues);
return false;
} }
this.queue.clear(); if (!keepQueue) this.sweepLocalAudio("replaced");
this.disableFmMode(); return true;
this.queue.add(s);
this.queue.play();
// Reset failure counter on user-initiated play
this.player.resetFailures();
const ok = await this.resolveAndPlay(this.queue.current()!, onFailure);
// Sweep AFTER the new song is queued+resolved: the replaced songs are no
// longer referenced (and get deleted), but the song — if it is the same
// local upload that was already playing — stays referenced and is preserved.
this.sweepLocalAudio("replaced");
return ok;
} }
/** /**
+41
View File
@@ -265,3 +265,44 @@ describe("play a queue position", () => {
expect(queue.current()?.id).toBe("unavailable"); expect(queue.current()?.id).toBe("unavailable");
}); });
}); });
it("reports a failed restart while the existing track is still playing", async () => {
const bot = {
runExclusive: (work: () => Promise<unknown>) => work(),
async playSingleSong(_song: Song, _requester: string, failure: (error: { message: string }, continues: boolean) => void) {
failure({ message: "No URL" }, true);
return false;
},
};
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
const response = await request(app).post("/api/player/b/play-song").send({ song: song("playing") });
expect(response.body).toEqual({ ok: false, message: expect.stringContaining("当前曲目继续播放") });
});
it("tries the newly appended track when idle and reports a failed URL lookup", async () => {
const queue = new PlayQueue();
queue.add(song("already-queued"));
const bot = {
getQueueManager: () => queue,
getPlayer: () => ({ getState: () => "idle", resetFailures: vi.fn() }),
runExclusive: (work: () => Promise<unknown>) => work(),
resolveAndPlay: vi.fn(async (_track: Song, onFailure?: (failure: { message: string }) => void) => {
onFailure?.({ message: "No URL" });
return false;
}),
emit: vi.fn(),
};
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
const response = await request(app).post("/api/player/b/add-song").send({ song: song("newly-added") });
expect(bot.resolveAndPlay.mock.calls.map(([track]) => track.id)).toEqual(["newly-added"]);
expect(queue.list().map(track => track.id)).toEqual(["already-queued", "newly-added"]);
expect(response.body).toEqual({ ok: false, message: expect.stringContaining("No URL") });
});
+18 -9
View File
@@ -540,7 +540,7 @@ export function createPlayerRouter(
// requests can't interleave the queue mutation + playback (#119). // requests can't interleave the queue mutation + playback (#119).
router.post("/:botId/play-song", authorize({ capability: "player.control" }), async (req, res) => { router.post("/:botId/play-song", authorize({ capability: "player.control" }), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot: BotInstance = (req as any).bot;
const { song } = req.body; const { song } = req.body;
if (!song || !song.id || !song.platform) { if (!song || !song.id || !song.platform) {
res.status(400).json({ error: "song object with id and platform is required" }); res.status(400).json({ error: "song object with id and platform is required" });
@@ -554,11 +554,15 @@ export function createPlayerRouter(
// clear branch — do NOT also call it here, or it would delete retained // clear branch — do NOT also call it here, or it would delete retained
// local uploads in keep-queue mode. // local uploads in keep-queue mode.
const body = await bot.runExclusive(async () => { const body = await bot.runExclusive(async () => {
let reason: string | undefined; let errorMessage = whyUnplayable(song);
const ok = await bot.playSingleSong({ ...song }, requesterName(req), (failure: PlayFailure) => { reason = failure.message; }); const ok = await bot.playSingleSong({ ...song }, requesterName(req), (failure, currentTrackContinues) => {
errorMessage = currentTrackContinues
? `未能重新播放「${song.name || song.id}」,当前曲目继续播放:${failure.message}`
: whyUnplayable(song, failure.message);
});
return ok return ok
? { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` } ? { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` }
: { ok: false, message: whyUnplayable(song, reason) }; : { ok: false, message: errorMessage };
}); });
res.json(body); res.json(body);
} catch (err) { } catch (err) {
@@ -653,7 +657,7 @@ export function createPlayerRouter(
router.post("/:botId/add-song", authorize({ capability: "player.queue", guestFlag: "addToQueue" }), async (req, res) => { router.post("/:botId/add-song", authorize({ capability: "player.queue", guestFlag: "addToQueue" }), async (req, res) => {
try { try {
const bot = (req as any).bot; const bot: BotInstance = (req as any).bot;
const { song } = req.body; const { song } = req.body;
if (!song || !song.id || !song.platform) { if (!song || !song.id || !song.platform) {
res.status(400).json({ error: "song object with id and platform is required" }); res.status(400).json({ error: "song object with id and platform is required" });
@@ -672,13 +676,18 @@ export function createPlayerRouter(
// If nothing was playing, start this newly-added song immediately. // If nothing was playing, start this newly-added song immediately.
if (wasIdle) { if (wasIdle) {
queue.playAt(queue.size() - 1); const added = queue.playAt(queue.size() - 1)!;
bot.getPlayer().resetFailures(); bot.getPlayer().resetFailures();
await bot.resolveAndPlay(queue.current()!); let reason: string | undefined;
return { message: `Now playing: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` }; const ok = await bot.resolveAndPlay(added, failure => { reason = failure.message; });
if (!ok) {
bot.emit("stateChange");
return { ok: false, message: `已加入队列,但${whyUnplayable(added, reason)}` };
}
return { ok: true, message: `Now playing: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` };
} }
return { message: `Added to queue: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'} (position ${queue.size()})` }; return { ok: true, message: `Added to queue: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'} (position ${queue.size()})` };
}); });
res.json(body); res.json(body);
} catch (err) { } catch (err) {
+2 -1
View File
@@ -585,7 +585,8 @@ export const usePlayerStore = defineStore('player', {
const handled = await this.checkBilibiliMultiPart(song, 'add'); const handled = await this.checkBilibiliMultiPart(song, 'add');
if (handled) return; if (handled) return;
} }
await axios.post(`/api/player/${this.activeBotId}/add-song`, { song }); const res = await axios.post(`/api/player/${this.activeBotId}/add-song`, { song });
if (res.data?.ok === false && res.data?.message) this.notify(res.data.message, 'error');
}, },
async playPlaylist(playlistId: string, platform = 'netease') { async playPlaylist(playlistId: string, platform = 'netease') {