diff --git a/web/src/lib/player/events.svelte.test.ts b/web/src/lib/player/events.svelte.test.ts index 9cf6dad0..672b05ca 100644 --- a/web/src/lib/player/events.svelte.test.ts +++ b/web/src/lib/player/events.svelte.test.ts @@ -18,6 +18,7 @@ import { reportTimeUpdate, reportDuration, skipNext, + cycleRepeat, } from './store.svelte'; import { api } from '#lib/api/client.js'; import type { TrackRef } from '#lib/api/types.js'; @@ -197,4 +198,75 @@ describe('useEventsDispatcher', () => { cleanup(); 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).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).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).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(); + }); }); diff --git a/web/src/lib/player/events.svelte.ts b/web/src/lib/player/events.svelte.ts index b35a4d33..7d5ac723 100644 --- a/web/src/lib/player/events.svelte.ts +++ b/web/src/lib/player/events.svelte.ts @@ -6,9 +6,12 @@ import type { PlayStartedResponse, EventOkResponse } from '#lib/api/types.js'; // useEventsDispatcher installs $effect-based watchers that emit play events // to /api/events. Call once from +layout.svelte's mount. // -// The dispatcher is a small state machine over (current track id, state): -// - First transition into 'playing' for a new track → POST play_started. -// - Track id changes while a play is open → close the prior row with +// The dispatcher is a small state machine over (current listen, state). A +// listen is the current track plus player.listen, which moves each time +// 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 // its skip rule (skip_max_completion_ratio + skip_max_duration_played_ms, // 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 // 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 { let openPlayEventId: string | null = null; - let openTrackId: string | null = null; - // openLastPositionMs tracks the *open row's* track and is updated ONLY while - // that track is current — so a track change (which synchronously resets the - // store's position to 0 and duration 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 track is still the open one - // at fire time. + let openKey: string | null = null; + // pendingKey is the listen whose play_started is in flight. A stall or a + // pause while it is out re-enters 'playing', and without it each re-entry + // would post another play_started, the first then closing as a skip. + let pendingKey: string | null = null; + // openLastPositionMs tracks the *open row's* listen and is updated ONLY + // 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 prevTrackId: string | null = null; + let prevKey: string | null = null; let prevState: string | null = null; const clientId = getOrCreateClientId(); $effect(() => { - if (openTrackId && player.current?.id === openTrackId) { - openLastPositionMs = Math.round(player.position * 1000); + const position = player.position; + 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(() => { - const t = player.current; 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 // whether to flag was_skipped. - if (tid !== prevTrackId && openPlayEventId) { + if (key !== prevKey && openPlayEventId) { const id = openPlayEventId; const dur = openLastPositionMs; openPlayEventId = null; - openTrackId = null; + openKey = null; openLastPositionMs = 0; api.post('/api/events', { type: 'play_ended', @@ -63,9 +78,9 @@ export function useEventsDispatcher(): void { }).catch(() => {}); } - // Entered playing for a new track (no open row yet for this track). - if (tid && s === 'playing' && openTrackId !== tid) { - void startNew(tid); + // Entered playing for a new listen (no open or pending row for it yet). + if (tid && key && s === 'playing' && openKey !== key && pendingKey !== key) { + void startNew(tid, key); } // Natural end: state went playing -> paused while at/past duration. @@ -79,7 +94,7 @@ export function useEventsDispatcher(): void { const id = openPlayEventId; const dur = Math.round(player.position * 1000); openPlayEventId = null; - openTrackId = null; + openKey = null; openLastPositionMs = 0; api.post('/api/events', { type: 'play_ended', @@ -88,7 +103,7 @@ export function useEventsDispatcher(): void { }).catch(() => {}); } - prevTrackId = tid; + prevKey = key; prevState = s; }); @@ -112,7 +127,8 @@ export function useEventsDispatcher(): void { window.addEventListener('pagehide', onPageHide); } - async function startNew(trackId: string): Promise { + async function startNew(trackId: string, key: string): Promise { + pendingKey = key; try { const res = await api.post('/api/events', { type: 'play_started', @@ -126,14 +142,19 @@ export function useEventsDispatcher(): void { // browser session, so it reports 'web'. device_class: 'web' }); - // The user may have moved on by the time the response arrives. Only - // adopt the id if we're still on the same track and still playing. - if (player.current?.id === trackId && player.state === 'playing') { + // The user may have moved on by the time the response arrives. Adopt + // the id while this listen is still current, whether it is 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; - openTrackId = trackId; + openKey = key; } } catch { // Best-effort; a missed event is acceptable. + } finally { + if (pendingKey === key) pendingKey = null; } } } diff --git a/web/src/lib/player/store.svelte.ts b/web/src/lib/player/store.svelte.ts index cf600d74..4f6cb567 100644 --- a/web/src/lib/player/store.svelte.ts +++ b/web/src/lib/player/store.svelte.ts @@ -65,6 +65,13 @@ let _repeat = $state('off'); let _error = $state(null); 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 // the layout's loadedmetadata handler so the audio element seeks to the // saved position after metadata loads. @@ -116,6 +123,7 @@ export const player = { get repeat() { return _repeat; }, get error() { return _error; }, get queueSource() { return _queueSource; }, + get listen() { return _listen; }, get queueDrawerOpen() { return _queueDrawerOpen; } }; @@ -180,6 +188,7 @@ export function playQueue( _duration = 0; _error = null; _failureStreak = 0; + _listen++; } export function togglePlay(): void { @@ -200,6 +209,7 @@ export function skipNext(): void { _position = 0; _duration = 0; _state = 'loading'; + _listen++; return; } // At end of queue. @@ -208,6 +218,7 @@ export function skipNext(): void { _position = 0; _duration = 0; _state = 'loading'; + _listen++; } else { // 'off' or 'one' both pause at end on EXPLICIT skip. _state = 'paused'; @@ -222,6 +233,7 @@ export function skipPrev(): void { _position = 0; _duration = 0; _state = 'loading'; + _listen++; } else { // Seek to 0 of the current track. _position = 0; @@ -318,6 +330,7 @@ export function reportStateFromAudio( _position = 0; _state = 'loading'; if (_audioEl) _audioEl.currentTime = 0; + _listen++; return; } if (_index + 1 < _queue.length) { @@ -325,6 +338,7 @@ export function reportStateFromAudio( _position = 0; _duration = 0; _state = 'loading'; + _listen++; return; } if (_repeat === 'all') { @@ -332,6 +346,7 @@ export function reportStateFromAudio( _position = 0; _duration = 0; _state = 'loading'; + _listen++; } else { _state = 'paused'; _position = _duration; @@ -353,6 +368,7 @@ function handleLoadFailure(detail?: string): void { _duration = 0; _state = 'loading'; _error = null; + _listen++; return; } // Whole queue is unplayable. If it came from a refreshable source, the @@ -388,6 +404,7 @@ function trySelfHeal(): boolean { _failureStreak = 0; _state = 'loading'; _error = null; + _listen++; } else { _state = 'error'; _error = 'Nothing playable in this mix right now.'; @@ -546,6 +563,7 @@ export function playFromQueueIndex(idx: number): void { _duration = 0; _state = 'loading'; _error = null; + _listen++; } export function toggleQueueDrawer(): void {