fix(web): a song on repeat is a play per listen, and a stall before play_started answers doesn't record it twice (#8071, #8072)
The events dispatcher keyed a play on the track id, so repeat-one, a one-track queue on repeat-all, or the same song twice in a row stayed one play, closed at the last loop's position and usually graded a skip. The player store now counts listens (player.listen moves whenever playback starts an item from its beginning) and the dispatcher keys a play on (track, listen). play_started's reply was adopted only while still 'playing', and nothing marked a start in flight, so a stall or pause just after starting threw the id away and the next 'playing' posted a second start, which closed the first as a skip. The dispatcher now holds the pending listen and adopts the reply whenever that listen is still current. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -18,6 +18,7 @@ import {
|
|||||||
reportTimeUpdate,
|
reportTimeUpdate,
|
||||||
reportDuration,
|
reportDuration,
|
||||||
skipNext,
|
skipNext,
|
||||||
|
cycleRepeat,
|
||||||
} from './store.svelte';
|
} from './store.svelte';
|
||||||
import { api } from '#lib/api/client.js';
|
import { api } from '#lib/api/client.js';
|
||||||
import type { TrackRef } from '#lib/api/types.js';
|
import type { TrackRef } from '#lib/api/types.js';
|
||||||
@@ -197,4 +198,75 @@ describe('useEventsDispatcher', () => {
|
|||||||
cleanup();
|
cleanup();
|
||||||
beacon.mockRestore();
|
beacon.mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// A song on repeat-one is a play per time through: each loop closes at its
|
||||||
|
// full length and the next opens a new play.
|
||||||
|
test('repeat-one closes each loop as ended and starts a new play', async () => {
|
||||||
|
const cleanup = $effect.root(() => useEventsDispatcher());
|
||||||
|
cycleRepeat(); // all
|
||||||
|
cycleRepeat(); // one
|
||||||
|
|
||||||
|
playQueue([track('1', 200)]);
|
||||||
|
flushSync();
|
||||||
|
reportDuration(200);
|
||||||
|
reportStateFromAudio('playing');
|
||||||
|
flushSync();
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
reportTimeUpdate(200);
|
||||||
|
flushSync();
|
||||||
|
reportStateFromAudio('ended');
|
||||||
|
flushSync();
|
||||||
|
reportStateFromAudio('playing');
|
||||||
|
flushSync();
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
const bodies = (api.post as ReturnType<typeof vi.fn>).mock.calls.map(
|
||||||
|
(c) => c[1] as { type: string; play_event_id?: string; duration_played_ms?: number }
|
||||||
|
);
|
||||||
|
expect(bodies.filter((b) => b.type === 'play_started').length).toBe(2);
|
||||||
|
const closed = bodies.find((b) => b.type === 'play_ended' && b.play_event_id === 'pe-1');
|
||||||
|
expect(closed?.duration_played_ms).toBe(200000);
|
||||||
|
|
||||||
|
cycleRepeat(); // back to off
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
|
|
||||||
|
// A stall or pause while play_started is still in flight is the same
|
||||||
|
// listen: no second play_started, and the reply is adopted anyway.
|
||||||
|
test('a stall before play_started answers starts the play once', async () => {
|
||||||
|
let answer: (v: { play_event_id: string; session_id: string }) => void = () => {};
|
||||||
|
(api.post as ReturnType<typeof vi.fn>).mockImplementationOnce(
|
||||||
|
() => new Promise((resolve) => (answer = resolve))
|
||||||
|
);
|
||||||
|
const cleanup = $effect.root(() => useEventsDispatcher());
|
||||||
|
|
||||||
|
playQueue([track('1', 200), track('2', 200)]);
|
||||||
|
flushSync();
|
||||||
|
reportDuration(200);
|
||||||
|
reportStateFromAudio('playing');
|
||||||
|
flushSync();
|
||||||
|
reportStateFromAudio('waiting');
|
||||||
|
flushSync();
|
||||||
|
answer({ play_event_id: 'pe-slow', session_id: 's-1' });
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
reportStateFromAudio('playing');
|
||||||
|
flushSync();
|
||||||
|
await Promise.resolve();
|
||||||
|
reportTimeUpdate(50);
|
||||||
|
flushSync();
|
||||||
|
skipNext();
|
||||||
|
flushSync();
|
||||||
|
await Promise.resolve();
|
||||||
|
|
||||||
|
const bodies = (api.post as ReturnType<typeof vi.fn>).mock.calls.map(
|
||||||
|
(c) => c[1] as { type: string; play_event_id?: string }
|
||||||
|
);
|
||||||
|
expect(bodies.filter((b) => b.type === 'play_started').length).toBe(1);
|
||||||
|
expect(bodies.some((b) => b.type === 'play_ended' && b.play_event_id === 'pe-slow')).toBe(true);
|
||||||
|
|
||||||
|
cleanup();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,9 +6,12 @@ import type { PlayStartedResponse, EventOkResponse } from '#lib/api/types.js';
|
|||||||
// useEventsDispatcher installs $effect-based watchers that emit play events
|
// useEventsDispatcher installs $effect-based watchers that emit play events
|
||||||
// to /api/events. Call once from +layout.svelte's mount.
|
// to /api/events. Call once from +layout.svelte's mount.
|
||||||
//
|
//
|
||||||
// The dispatcher is a small state machine over (current track id, state):
|
// The dispatcher is a small state machine over (current listen, state). A
|
||||||
// - First transition into 'playing' for a new track → POST play_started.
|
// listen is the current track plus player.listen, which moves each time
|
||||||
// - Track id changes while a play is open → close the prior row with
|
// playback starts an item from its beginning, so a song on repeat is a play
|
||||||
|
// per time through:
|
||||||
|
// - First transition into 'playing' for a new listen → POST play_started.
|
||||||
|
// - The listen changes while a play is open → close the prior row with
|
||||||
// play_ended carrying the actual position played to. Server applies
|
// play_ended carrying the actual position played to. Server applies
|
||||||
// its skip rule (skip_max_completion_ratio + skip_max_duration_played_ms,
|
// its skip rule (skip_max_completion_ratio + skip_max_duration_played_ms,
|
||||||
// default 50%/30s) and decides was_skipped from that.
|
// default 50%/30s) and decides was_skipped from that.
|
||||||
@@ -21,40 +24,52 @@ import type { PlayStartedResponse, EventOkResponse } from '#lib/api/types.js';
|
|||||||
// "within 3s of duration" rule would leave the server's threshold dead and
|
// "within 3s of duration" rule would leave the server's threshold dead and
|
||||||
// treat every "next" tap as a skip even after most of the track played.
|
// treat every "next" tap as a skip even after most of the track played.
|
||||||
|
|
||||||
|
// listenKey names the listen under way: the track and the store's listen
|
||||||
|
// count, or null with nothing current.
|
||||||
|
function listenKey(): string | null {
|
||||||
|
const tid = player.current?.id;
|
||||||
|
return tid ? `${tid}#${player.listen}` : null;
|
||||||
|
}
|
||||||
|
|
||||||
export function useEventsDispatcher(): void {
|
export function useEventsDispatcher(): void {
|
||||||
let openPlayEventId: string | null = null;
|
let openPlayEventId: string | null = null;
|
||||||
let openTrackId: string | null = null;
|
let openKey: string | null = null;
|
||||||
// openLastPositionMs tracks the *open row's* track and is updated ONLY while
|
// pendingKey is the listen whose play_started is in flight. A stall or a
|
||||||
// that track is current — so a track change (which synchronously resets the
|
// pause while it is out re-enters 'playing', and without it each re-entry
|
||||||
// store's position to 0 and duration to 0) can't clobber it before the close
|
// would post another play_started, the first then closing as a skip.
|
||||||
// branch reads it. The pagehide + natural-end branches can read
|
let pendingKey: string | null = null;
|
||||||
// player.position directly because their current track is still the open one
|
// openLastPositionMs tracks the *open row's* listen and is updated ONLY
|
||||||
// at fire time.
|
// while that listen is current — so a track change or a repeat (which
|
||||||
|
// synchronously resets the store's position to 0) can't clobber it before
|
||||||
|
// the close branch reads it. The pagehide + natural-end branches can read
|
||||||
|
// player.position directly because their current listen is still the open
|
||||||
|
// one at fire time.
|
||||||
let openLastPositionMs = 0;
|
let openLastPositionMs = 0;
|
||||||
let prevTrackId: string | null = null;
|
let prevKey: string | null = null;
|
||||||
let prevState: string | null = null;
|
let prevState: string | null = null;
|
||||||
const clientId = getOrCreateClientId();
|
const clientId = getOrCreateClientId();
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (openTrackId && player.current?.id === openTrackId) {
|
const position = player.position;
|
||||||
openLastPositionMs = Math.round(player.position * 1000);
|
if (openKey && listenKey() === openKey) {
|
||||||
|
openLastPositionMs = Math.round(position * 1000);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Main state machine. Reacts only to (current track id, state) transitions.
|
// Main state machine. Reacts only to (current listen, state) transitions.
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
const t = player.current;
|
|
||||||
const s = player.state;
|
const s = player.state;
|
||||||
const tid = t?.id ?? null;
|
const key = listenKey();
|
||||||
|
const tid = player.current?.id ?? null;
|
||||||
|
|
||||||
// Track changed: close the prior open row. Always send play_ended
|
// Listen changed: close the prior open row. Always send play_ended
|
||||||
// with the actual position played; the server's skip rule decides
|
// with the actual position played; the server's skip rule decides
|
||||||
// whether to flag was_skipped.
|
// whether to flag was_skipped.
|
||||||
if (tid !== prevTrackId && openPlayEventId) {
|
if (key !== prevKey && openPlayEventId) {
|
||||||
const id = openPlayEventId;
|
const id = openPlayEventId;
|
||||||
const dur = openLastPositionMs;
|
const dur = openLastPositionMs;
|
||||||
openPlayEventId = null;
|
openPlayEventId = null;
|
||||||
openTrackId = null;
|
openKey = null;
|
||||||
openLastPositionMs = 0;
|
openLastPositionMs = 0;
|
||||||
api.post<EventOkResponse>('/api/events', {
|
api.post<EventOkResponse>('/api/events', {
|
||||||
type: 'play_ended',
|
type: 'play_ended',
|
||||||
@@ -63,9 +78,9 @@ export function useEventsDispatcher(): void {
|
|||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Entered playing for a new track (no open row yet for this track).
|
// Entered playing for a new listen (no open or pending row for it yet).
|
||||||
if (tid && s === 'playing' && openTrackId !== tid) {
|
if (tid && key && s === 'playing' && openKey !== key && pendingKey !== key) {
|
||||||
void startNew(tid);
|
void startNew(tid, key);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Natural end: state went playing -> paused while at/past duration.
|
// Natural end: state went playing -> paused while at/past duration.
|
||||||
@@ -79,7 +94,7 @@ export function useEventsDispatcher(): void {
|
|||||||
const id = openPlayEventId;
|
const id = openPlayEventId;
|
||||||
const dur = Math.round(player.position * 1000);
|
const dur = Math.round(player.position * 1000);
|
||||||
openPlayEventId = null;
|
openPlayEventId = null;
|
||||||
openTrackId = null;
|
openKey = null;
|
||||||
openLastPositionMs = 0;
|
openLastPositionMs = 0;
|
||||||
api.post<EventOkResponse>('/api/events', {
|
api.post<EventOkResponse>('/api/events', {
|
||||||
type: 'play_ended',
|
type: 'play_ended',
|
||||||
@@ -88,7 +103,7 @@ export function useEventsDispatcher(): void {
|
|||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
prevTrackId = tid;
|
prevKey = key;
|
||||||
prevState = s;
|
prevState = s;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -112,7 +127,8 @@ export function useEventsDispatcher(): void {
|
|||||||
window.addEventListener('pagehide', onPageHide);
|
window.addEventListener('pagehide', onPageHide);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startNew(trackId: string): Promise<void> {
|
async function startNew(trackId: string, key: string): Promise<void> {
|
||||||
|
pendingKey = key;
|
||||||
try {
|
try {
|
||||||
const res = await api.post<PlayStartedResponse>('/api/events', {
|
const res = await api.post<PlayStartedResponse>('/api/events', {
|
||||||
type: 'play_started',
|
type: 'play_started',
|
||||||
@@ -126,14 +142,19 @@ export function useEventsDispatcher(): void {
|
|||||||
// browser session, so it reports 'web'.
|
// browser session, so it reports 'web'.
|
||||||
device_class: 'web'
|
device_class: 'web'
|
||||||
});
|
});
|
||||||
// The user may have moved on by the time the response arrives. Only
|
// The user may have moved on by the time the response arrives. Adopt
|
||||||
// adopt the id if we're still on the same track and still playing.
|
// the id while this listen is still current, whether it is playing,
|
||||||
if (player.current?.id === trackId && player.state === 'playing') {
|
// buffering or paused: it is the same listen either way. A listen
|
||||||
|
// that has ended leaves its row to the server, which closes it when
|
||||||
|
// the next play starts.
|
||||||
|
if (listenKey() === key) {
|
||||||
openPlayEventId = res.play_event_id;
|
openPlayEventId = res.play_event_id;
|
||||||
openTrackId = trackId;
|
openKey = key;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Best-effort; a missed event is acceptable.
|
// Best-effort; a missed event is acceptable.
|
||||||
|
} finally {
|
||||||
|
if (pendingKey === key) pendingKey = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,6 +65,13 @@ let _repeat = $state<RepeatMode>('off');
|
|||||||
let _error = $state<string | null>(null);
|
let _error = $state<string | null>(null);
|
||||||
let _queueDrawerOpen = $state(false);
|
let _queueDrawerOpen = $state(false);
|
||||||
|
|
||||||
|
// _listen counts listens begun: it moves whenever playback starts an item
|
||||||
|
// from its beginning (a new queue, a skip, a track ending into the next, a
|
||||||
|
// repeat). The events dispatcher keys a play on (track, listen), so a song
|
||||||
|
// on repeat-one, a one-track queue on repeat-all, or the same song twice in
|
||||||
|
// a row is a play per listen rather than one long play.
|
||||||
|
let _listen = $state(0);
|
||||||
|
|
||||||
// C1: one-shot restore position — set by restoreQueue, consumed once by
|
// C1: one-shot restore position — set by restoreQueue, consumed once by
|
||||||
// the layout's loadedmetadata handler so the audio element seeks to the
|
// the layout's loadedmetadata handler so the audio element seeks to the
|
||||||
// saved position after metadata loads.
|
// saved position after metadata loads.
|
||||||
@@ -116,6 +123,7 @@ export const player = {
|
|||||||
get repeat() { return _repeat; },
|
get repeat() { return _repeat; },
|
||||||
get error() { return _error; },
|
get error() { return _error; },
|
||||||
get queueSource() { return _queueSource; },
|
get queueSource() { return _queueSource; },
|
||||||
|
get listen() { return _listen; },
|
||||||
get queueDrawerOpen() { return _queueDrawerOpen; }
|
get queueDrawerOpen() { return _queueDrawerOpen; }
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -180,6 +188,7 @@ export function playQueue(
|
|||||||
_duration = 0;
|
_duration = 0;
|
||||||
_error = null;
|
_error = null;
|
||||||
_failureStreak = 0;
|
_failureStreak = 0;
|
||||||
|
_listen++;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function togglePlay(): void {
|
export function togglePlay(): void {
|
||||||
@@ -200,6 +209,7 @@ export function skipNext(): void {
|
|||||||
_position = 0;
|
_position = 0;
|
||||||
_duration = 0;
|
_duration = 0;
|
||||||
_state = 'loading';
|
_state = 'loading';
|
||||||
|
_listen++;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// At end of queue.
|
// At end of queue.
|
||||||
@@ -208,6 +218,7 @@ export function skipNext(): void {
|
|||||||
_position = 0;
|
_position = 0;
|
||||||
_duration = 0;
|
_duration = 0;
|
||||||
_state = 'loading';
|
_state = 'loading';
|
||||||
|
_listen++;
|
||||||
} else {
|
} else {
|
||||||
// 'off' or 'one' both pause at end on EXPLICIT skip.
|
// 'off' or 'one' both pause at end on EXPLICIT skip.
|
||||||
_state = 'paused';
|
_state = 'paused';
|
||||||
@@ -222,6 +233,7 @@ export function skipPrev(): void {
|
|||||||
_position = 0;
|
_position = 0;
|
||||||
_duration = 0;
|
_duration = 0;
|
||||||
_state = 'loading';
|
_state = 'loading';
|
||||||
|
_listen++;
|
||||||
} else {
|
} else {
|
||||||
// Seek to 0 of the current track.
|
// Seek to 0 of the current track.
|
||||||
_position = 0;
|
_position = 0;
|
||||||
@@ -318,6 +330,7 @@ export function reportStateFromAudio(
|
|||||||
_position = 0;
|
_position = 0;
|
||||||
_state = 'loading';
|
_state = 'loading';
|
||||||
if (_audioEl) _audioEl.currentTime = 0;
|
if (_audioEl) _audioEl.currentTime = 0;
|
||||||
|
_listen++;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (_index + 1 < _queue.length) {
|
if (_index + 1 < _queue.length) {
|
||||||
@@ -325,6 +338,7 @@ export function reportStateFromAudio(
|
|||||||
_position = 0;
|
_position = 0;
|
||||||
_duration = 0;
|
_duration = 0;
|
||||||
_state = 'loading';
|
_state = 'loading';
|
||||||
|
_listen++;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (_repeat === 'all') {
|
if (_repeat === 'all') {
|
||||||
@@ -332,6 +346,7 @@ export function reportStateFromAudio(
|
|||||||
_position = 0;
|
_position = 0;
|
||||||
_duration = 0;
|
_duration = 0;
|
||||||
_state = 'loading';
|
_state = 'loading';
|
||||||
|
_listen++;
|
||||||
} else {
|
} else {
|
||||||
_state = 'paused';
|
_state = 'paused';
|
||||||
_position = _duration;
|
_position = _duration;
|
||||||
@@ -353,6 +368,7 @@ function handleLoadFailure(detail?: string): void {
|
|||||||
_duration = 0;
|
_duration = 0;
|
||||||
_state = 'loading';
|
_state = 'loading';
|
||||||
_error = null;
|
_error = null;
|
||||||
|
_listen++;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Whole queue is unplayable. If it came from a refreshable source, the
|
// Whole queue is unplayable. If it came from a refreshable source, the
|
||||||
@@ -388,6 +404,7 @@ function trySelfHeal(): boolean {
|
|||||||
_failureStreak = 0;
|
_failureStreak = 0;
|
||||||
_state = 'loading';
|
_state = 'loading';
|
||||||
_error = null;
|
_error = null;
|
||||||
|
_listen++;
|
||||||
} else {
|
} else {
|
||||||
_state = 'error';
|
_state = 'error';
|
||||||
_error = 'Nothing playable in this mix right now.';
|
_error = 'Nothing playable in this mix right now.';
|
||||||
@@ -546,6 +563,7 @@ export function playFromQueueIndex(idx: number): void {
|
|||||||
_duration = 0;
|
_duration = 0;
|
||||||
_state = 'loading';
|
_state = 'loading';
|
||||||
_error = null;
|
_error = null;
|
||||||
|
_listen++;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function toggleQueueDrawer(): void {
|
export function toggleQueueDrawer(): void {
|
||||||
|
|||||||
Reference in New Issue
Block a user