From b0393b42b2d5cd3bca6236fc852753b52aa590b6 Mon Sep 17 00:00:00 2001 From: TIANYAO ZHANG <88520881+ZHANGTIANYAO1@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:37:17 +0800 Subject: [PATCH] fix(playback): preserve the current queue until direct play starts --- src/bot/instance.test.ts | 93 +++++++++++++++++++++++++++- src/bot/instance.ts | 104 ++++++++++++++++---------------- src/web/api/play-artist.test.ts | 41 +++++++++++++ src/web/api/player.ts | 27 ++++++--- web/src/stores/player.ts | 3 +- 5 files changed, 206 insertions(+), 62 deletions(-) diff --git a/src/bot/instance.test.ts b/src/bot/instance.test.ts index e991ff1..4d4236e 100644 --- a/src/bot/instance.test.ts +++ b/src/bot/instance.test.ts @@ -1397,6 +1397,7 @@ const playSingleSong = BotInstance.prototype.playSingleSong as ( this: unknown, song: unknown, requesterName?: string, + onFailure?: (failure: PlayFailure, currentTrackContinues?: boolean) => void, ) => Promise; const loadSavedQueue = BotInstance.prototype.loadSavedQueue as ( this: unknown, @@ -1439,7 +1440,10 @@ describe("BotInstance.playSingleSong / playKeepsQueue (#119)", () => { isSameSong, disableFmMode: vi.fn(), sweepLocalAudio: vi.fn(), - resolveAndPlay: vi.fn(async () => true), + resolveAndPlay: vi.fn(async (_song, _onFailure, commitQueue?: () => void) => { + commitQueue?.(); + return true; + }), } 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.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(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)", () => { diff --git a/src/bot/instance.ts b/src/bot/instance.ts index 2bd1a3d..1004d5a 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -1077,7 +1077,11 @@ export class BotInstance extends EventEmitter { } /** Resolve the URL and start playback if this request still owns the queue. */ - async resolveAndPlay(song: QueuedSong, onFailure?: (failure: PlayFailure) => void): Promise { + async resolveAndPlay( + song: QueuedSong, + onFailure?: (failure: PlayFailure) => void, + commitQueue?: () => void, + ): Promise { const request = Symbol(); this.playbackRequest = request; const generation = this.lifecycleGeneration; @@ -1098,10 +1102,6 @@ export class BotInstance extends EventEmitter { fail("该机器人已关闭本地音频播放"); 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 { const provider = this.getProviderFor(song.platform); 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 // 2nd+ consecutive Spotify track. Cosmetic only — the authoritative // 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(), { // The sidecar PCM pipe is long-lived; per-track end arrives via the // 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.currentSourceIsSpotify = false; } + if (commitQueue) this.player.resetFailures(); this.effectiveDuration = result.trialDuration ?? song.duration; this.player.play(result.url, 0, this.effectiveDuration); } @@ -1271,6 +1273,9 @@ export class BotInstance extends EventEmitter { 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 // or turn an otherwise successful playback request into an error. this.autoPaused = false; @@ -1503,56 +1508,53 @@ export class BotInstance extends EventEmitter { if (error) return error; const song0 = song!; let why: string | undefined; - const ok = await this.playSingleSong(song0, requesterName, failure => { why = failure.message; }); - if (!ok) return why ? `Cannot play: ${song0.name} — ${why}` : `Cannot play: ${song0.name}`; + const ok = await this.playSingleSong(song0, requesterName, (failure, currentTrackContinues) => { + 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}`; } - /** - * Play a single resolved song immediately, honoring config.playKeepsQueue: - * - false (default): clear the queue and play only this song — today's - * behavior. The prior track is stopped and released local uploads swept. - * - true (and the queue is non-empty): insert the song after the current - * track and jump to it (reusing addNext + playAt — no new queue logic), so - * the rest of the queue survives and continues after it. FM auto-refill is - * 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 { - 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). + /** Start the requested song before changing the queue or stopping FM. */ + async playSingleSong( + song: QueuedSong, + requesterName?: string, + onFailure?: (failure: PlayFailure, currentTrackContinues?: boolean) => void, + ): Promise { + const requested = this.withRequester(song, requesterName); const previous = this.queue.current(); - if (previous && !this.isSameSong(previous, s)) { - this.player.stop(); + const previousSession = this.isSameSong(previous, requested) ? this.player.getPlaybackSessionId() : undefined; + 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(); - this.disableFmMode(); - 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; + if (!keepQueue) this.sweepLocalAudio("replaced"); + return true; } /** diff --git a/src/web/api/play-artist.test.ts b/src/web/api/play-artist.test.ts index 5faccef..7b6fe9e 100644 --- a/src/web/api/play-artist.test.ts +++ b/src/web/api/play-artist.test.ts @@ -265,3 +265,44 @@ describe("play a queue position", () => { expect(queue.current()?.id).toBe("unavailable"); }); }); + +it("reports a failed restart while the existing track is still playing", async () => { + const bot = { + runExclusive: (work: () => Promise) => 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) => 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") }); +}); diff --git a/src/web/api/player.ts b/src/web/api/player.ts index f044c85..fad12b5 100644 --- a/src/web/api/player.ts +++ b/src/web/api/player.ts @@ -540,7 +540,7 @@ export function createPlayerRouter( // requests can't interleave the queue mutation + playback (#119). router.post("/:botId/play-song", authorize({ capability: "player.control" }), async (req, res) => { try { - const bot = (req as any).bot; + const bot: BotInstance = (req as any).bot; const { song } = req.body; if (!song || !song.id || !song.platform) { 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 // local uploads in keep-queue mode. const body = await bot.runExclusive(async () => { - let reason: string | undefined; - const ok = await bot.playSingleSong({ ...song }, requesterName(req), (failure: PlayFailure) => { reason = failure.message; }); + let errorMessage = whyUnplayable(song); + const ok = await bot.playSingleSong({ ...song }, requesterName(req), (failure, currentTrackContinues) => { + errorMessage = currentTrackContinues + ? `未能重新播放「${song.name || song.id}」,当前曲目继续播放:${failure.message}` + : whyUnplayable(song, failure.message); + }); return ok ? { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` } - : { ok: false, message: whyUnplayable(song, reason) }; + : { ok: false, message: errorMessage }; }); res.json(body); } catch (err) { @@ -653,7 +657,7 @@ export function createPlayerRouter( router.post("/:botId/add-song", authorize({ capability: "player.queue", guestFlag: "addToQueue" }), async (req, res) => { try { - const bot = (req as any).bot; + const bot: BotInstance = (req as any).bot; const { song } = req.body; if (!song || !song.id || !song.platform) { 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 (wasIdle) { - queue.playAt(queue.size() - 1); + const added = queue.playAt(queue.size() - 1)!; bot.getPlayer().resetFailures(); - await bot.resolveAndPlay(queue.current()!); - return { message: `Now playing: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` }; + let reason: string | undefined; + 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); } catch (err) { diff --git a/web/src/stores/player.ts b/web/src/stores/player.ts index 9b3f55a..42edc80 100644 --- a/web/src/stores/player.ts +++ b/web/src/stores/player.ts @@ -585,7 +585,8 @@ export const usePlayerStore = defineStore('player', { const handled = await this.checkBilibiliMultiPart(song, 'add'); 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') {