fix(queue): persist timeline play history across queue replace (#1096) (#1204)

* fix(queue): persist timeline play history across queue replace (#1096)

Add a session-scoped play-history buffer (with play_session cold bootstrap)
and timeline UI that shows history + current + upcoming without mutating
the canonical queue or Subsonic sync.

* fix(queue): pin timeline current to top and replay history in-place

Timeline scroll matches queue mode (current at top). History clicks insert
after the playing track instead of replacing the queue, and replayed tracks
stay visible in the history strip.

* docs: add CHANGELOG and credits for timeline play history (PR #1204)

* fix(queue): resolve cross-server cover art for timeline history

Include album/cover ids in play_session bootstrap rows, prefetch history
refs through the queue resolver per server, and resolve before replay so
Now Playing artwork works for inactive-server tracks.

* fix(now-playing): stop playbackReport on cross-server track switch

Send stopped to the previous server's playbackReport session when the
playback server changes (queue click, history replay, etc.) so Who is
listening clears on the server that was showing the prior track.

* fix(queue): close timeline history review gaps for PR #1204

Defer play_session bootstrap until the library index is ready with retry
while timeline mode is active; resolve history and queue rows by serverId
+ trackId for mixed-server queues; add tests for bootstrap defer and ref lookup.

* chore(queue): remove dead timeline scroll guard in QueueList

Timeline scroll is handled in the virtual-rows effect; the legacy branch
is queue/playlist only.

* fix(queue): address PR review nits for timeline play history

Use authoritative row.ref.serverId for history clicks before resolver fill;
simplify empty bootstrap seed; tighten completion types; unify recent_plays SQL.

* fix(queue): immutable session history append for useSyncExternalStore

Replace in-place push with a fresh array so getSnapshot returns a new
reference and React re-renders on live appends without a playerStore update.
This commit is contained in:
cucadmuh
2026-06-28 05:08:02 +03:00
committed by GitHub
parent 979eb85ad1
commit 281e86fd3b
44 changed files with 1416 additions and 169 deletions
+60
View File
@@ -0,0 +1,60 @@
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import {
_resetTimelineSessionHistoryForTest,
isTimelineBootstrapAttempted,
} from '../store/timelineSessionHistory';
import {
_resetTimelineBootstrapInFlightForTest,
ensureTimelineBootstrap,
} from './useTimelinePlayHistory';
vi.mock('../api/library', () => ({
libraryGetRecentPlaySessions: vi.fn(async () => []),
TIMELINE_HISTORY_BOOTSTRAP_LIMIT: 50,
}));
vi.mock('../utils/queue/timelineBootstrapReady', () => ({
timelineBootstrapIndexReady: vi.fn(),
}));
vi.mock('../utils/library/queueTrackResolver', async importOriginal => {
const actual = await importOriginal<typeof import('../utils/library/queueTrackResolver')>();
return { ...actual, seedQueueResolver: vi.fn() };
});
import { libraryGetRecentPlaySessions } from '../api/library';
import { timelineBootstrapIndexReady } from '../utils/queue/timelineBootstrapReady';
describe('ensureTimelineBootstrap', () => {
beforeEach(() => {
_resetTimelineSessionHistoryForTest();
_resetTimelineBootstrapInFlightForTest();
vi.mocked(timelineBootstrapIndexReady).mockReset();
vi.mocked(libraryGetRecentPlaySessions).mockClear();
});
afterEach(() => {
vi.useRealTimers();
});
it('defers without marking attempted when the index is not ready', async () => {
vi.mocked(timelineBootstrapIndexReady).mockResolvedValue(false);
await ensureTimelineBootstrap();
expect(isTimelineBootstrapAttempted()).toBe(false);
expect(libraryGetRecentPlaySessions).not.toHaveBeenCalled();
});
it('fetches once when the index is ready', async () => {
vi.mocked(timelineBootstrapIndexReady).mockResolvedValue(true);
await ensureTimelineBootstrap();
expect(isTimelineBootstrapAttempted()).toBe(true);
expect(libraryGetRecentPlaySessions).toHaveBeenCalledTimes(1);
});
it('does not fetch twice in the same session', async () => {
vi.mocked(timelineBootstrapIndexReady).mockResolvedValue(true);
await ensureTimelineBootstrap();
await ensureTimelineBootstrap();
expect(libraryGetRecentPlaySessions).toHaveBeenCalledTimes(1);
});
});
+112
View File
@@ -0,0 +1,112 @@
import { useEffect, useMemo, useSyncExternalStore } from 'react';
import { libraryGetRecentPlaySessions, type PlaySessionRecentTrack } from '../api/library';
import { seedQueueResolver, resolveBatch } from '../utils/library/queueTrackResolver';
import {
applyTimelineBootstrap,
getTimelineSessionHistorySnapshot,
isTimelineBootstrapAttempted,
markTimelineBootstrapAttempted,
subscribeTimelineSessionHistory,
TIMELINE_HISTORY_BOOTSTRAP_LIMIT,
type TimelinePlayedRef,
} from '../store/timelineSessionHistory';
import {
bootstrapTrackFromPlaySession,
timelineHistoryToQueueRefs,
} from '../utils/queue/timelineHistoryRefs';
import { timelineBootstrapIndexReady } from '../utils/queue/timelineBootstrapReady';
const BOOTSTRAP_RETRY_MS = 2_000;
let bootstrapInFlight = false;
function bootstrapRowToRef(row: PlaySessionRecentTrack): TimelinePlayedRef {
return {
serverId: row.serverId,
trackId: row.trackId,
playedAtMs: row.startedAtMs,
};
}
function seedResolverFromBootstrap(rows: PlaySessionRecentTrack[]): void {
const byServer = new Map<string, ReturnType<typeof bootstrapTrackFromPlaySession>[]>();
for (const row of rows) {
const track = bootstrapTrackFromPlaySession(row);
const arr = byServer.get(row.serverId) ?? [];
arr.push(track);
byServer.set(row.serverId, arr);
}
for (const [serverId, tracks] of byServer) {
seedQueueResolver(serverId, tracks);
}
}
/** Test-only: reset in-flight bootstrap guard. */
export function _resetTimelineBootstrapInFlightForTest(): void {
bootstrapInFlight = false;
}
export async function ensureTimelineBootstrap(): Promise<void> {
if (isTimelineBootstrapAttempted() || bootstrapInFlight) return;
if (!(await timelineBootstrapIndexReady())) return;
bootstrapInFlight = true;
if (!markTimelineBootstrapAttempted()) {
bootstrapInFlight = false;
return;
}
try {
const rows = await libraryGetRecentPlaySessions({ limit: TIMELINE_HISTORY_BOOTSTRAP_LIMIT });
seedResolverFromBootstrap(rows);
const oldestFirst = [...rows].reverse().map(bootstrapRowToRef);
applyTimelineBootstrap(oldestFirst);
} catch {
/* bootstrapAttempted stays true — no retry until next app launch */
} finally {
bootstrapInFlight = false;
}
}
export function useTimelinePlayHistory(): TimelinePlayedRef[] {
return useSyncExternalStore(subscribeTimelineSessionHistory, getTimelineSessionHistorySnapshot);
}
export function useTimelineBootstrapOnMode(isTimeline: boolean): void {
useEffect(() => {
if (!isTimeline) return;
let cancelled = false;
const run = async () => {
while (!cancelled && !isTimelineBootstrapAttempted()) {
await ensureTimelineBootstrap();
if (cancelled || isTimelineBootstrapAttempted()) break;
await new Promise<void>(resolve => {
window.setTimeout(resolve, BOOTSTRAP_RETRY_MS);
});
}
};
void run();
return () => {
cancelled = true;
};
}, [isTimeline]);
}
/** Prefetch full track metadata (incl. cover ids) for cross-server history rows. */
export function useTimelineHistoryResolver(
historyRefs: TimelinePlayedRef[],
enabled: boolean,
): void {
const refsKey = useMemo(
() => historyRefs.map(r => `${r.serverId}:${r.trackId}:${r.playedAtMs}`).join('\u0001'),
[historyRefs],
);
useEffect(() => {
if (!enabled || historyRefs.length === 0) return;
void resolveBatch(timelineHistoryToQueueRefs(historyRefs));
}, [enabled, refsKey, historyRefs]);
}