Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion packages/backend/src/routes/music/stateRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,11 @@ export function setupStateRoutes(app: Express): void {
return
}
try {
res.write(': heartbeat\n\n')
// Real data: payload (not an SSE comment) so clients can
// treat the heartbeat as a liveness stamp for progress UI.
res.write(
`data: ${JSON.stringify({ type: 'heartbeat' })}\n\n`,
)
} catch {
// NOSONAR: Intentionally swallowing heartbeat write exceptions — client disconnected mid-send. The close event handler will clean up the connection.
}
Expand Down
37 changes: 36 additions & 1 deletion packages/frontend/src/hooks/useMusicPlayer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,20 @@ describe('useMusicPlayer', () => {
await waitFor(() => {
expect(result.current.state.volume).toBe(80)
})
expect(result.current.lastStateUpdate).toEqual(expect.any(Number))
})

test('sets lastStateUpdate from initial REST state', async () => {
const { sse } = makeMockSSE()
mockCreateSSEConnection.mockReturnValue(sse)
const restState = { guildId: 'guild-1', isPlaying: true, tracks: [], currentTrack: null, isPaused: false, volume: 60, repeatMode: 'off', shuffled: false, position: 0, voiceChannelId: null, voiceChannelName: null, timestamp: 0 }
mockGetState.mockResolvedValue({ data: restState })

const { result } = renderHook(() => useMusicPlayer('guild-1'))

await waitFor(() => {
expect(result.current.lastStateUpdate).toEqual(expect.any(Number))
})
})

test('ignores malformed SSE messages gracefully', async () => {
Expand All @@ -183,10 +197,31 @@ describe('useMusicPlayer', () => {
const volumeBefore = result.current.state.volume

act(() => {
listeners.onmessage?.({ data: ': heartbeat' })
listeners.onmessage?.({ data: 'not-json' })
})

expect(result.current.state.volume).toBe(volumeBefore)
})

test('heartbeat payload refreshes lastStateUpdate without changing state', async () => {
const { sse, listeners } = makeMockSSE()
mockCreateSSEConnection.mockReturnValue(sse)

const { result } = renderHook(() => useMusicPlayer('guild-1'))
const volumeBefore = result.current.state.volume
const before = result.current.lastStateUpdate

act(() => {
listeners.onmessage?.({
data: JSON.stringify({ type: 'heartbeat' }),
})
})

expect(result.current.state.volume).toBe(volumeBefore)
expect(result.current.lastStateUpdate).toEqual(expect.any(Number))
if (before !== null) {
expect(result.current.lastStateUpdate).toBeGreaterThanOrEqual(before)
}
})

test('sets isConnected false and calls close on SSE error', async () => {
Expand Down
31 changes: 25 additions & 6 deletions packages/frontend/src/hooks/useMusicPlayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export function useMusicPlayer(guildId: string | undefined) {
)
const [isConnected, setIsConnected] = useState(false)
const [error, setError] = useState<string | null>(null)
/** Wall-clock ms of the last successful state payload (SSE or REST). */
const [lastStateUpdate, setLastStateUpdate] = useState<number | null>(null)
const sseRef = useRef<EventSource | null>(null)
const retryRef = useRef(0)
const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
Expand All @@ -64,10 +66,16 @@ export function useMusicPlayer(guildId: string | undefined) {
setIsLoading(false)
}, [guildId])

const applyState = useCallback((next: QueueState) => {
setState(next)
setLastStateUpdate(Date.now())
}, [])

useEffect(() => {
if (!guildId) {
setState(EMPTY_STATE)
setIsConnected(false)
setLastStateUpdate(null)
return
}

Expand All @@ -88,9 +96,17 @@ export function useMusicPlayer(guildId: string | undefined) {
sse.onmessage = (event) => {
if (cancelled) return
try {
setState(JSON.parse(event.data))
const payload = JSON.parse(event.data) as {
type?: string
} & QueueState
// Heartbeat is liveness only; do not clobber queue state.
if (payload?.type === 'heartbeat') {
setLastStateUpdate(Date.now())
return
}
applyState(payload)
Comment thread
LucasSantana-Dev marked this conversation as resolved.
} catch {
/* heartbeat or malformed data */
/* malformed data */
}
}

Expand All @@ -115,7 +131,7 @@ export function useMusicPlayer(guildId: string | undefined) {
api.music
.getState(guildId)
.then((res) => {
if (!cancelled) setState(res.data)
if (!cancelled) applyState(res.data)
})
.catch(() => {})

Expand All @@ -126,7 +142,7 @@ export function useMusicPlayer(guildId: string | undefined) {
if (retryTimerRef.current) clearTimeout(retryTimerRef.current)
setIsConnected(false)
}
}, [guildId])
}, [guildId, applyState])

const sendCommand = useCallback(
async (
Expand Down Expand Up @@ -168,7 +184,9 @@ export function useMusicPlayer(guildId: string | undefined) {
try {
const response =
await api.music.getState(commandGuildId)
if (isLiveCommand()) setState(response.data)
// applyState (not setState) so the rollback refresh
// also stamps liveness for the stale-progress logic.
if (isLiveCommand()) applyState(response.data)
Comment thread
LucasSantana-Dev marked this conversation as resolved.
} catch (refreshError) {
if (!isLiveCommand()) return
const refreshMessage =
Expand Down Expand Up @@ -199,7 +217,7 @@ export function useMusicPlayer(guildId: string | undefined) {
}
}
},
[guildId],
[guildId, applyState],
)

const clearError = useCallback(() => setError(null), [])
Expand All @@ -212,6 +230,7 @@ export function useMusicPlayer(guildId: string | undefined) {
pendingAction,
isConnected,
error,
lastStateUpdate,
clearError,
...commands,
}
Expand Down
1 change: 1 addition & 0 deletions packages/frontend/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,7 @@
"pause": "Pause",
"nextTrack": "Next track",
"repeatMode": "Repeat: {{mode}}",
"progressMayBeOutdated": "may be outdated",
"commandInProgress": "Working on that command…",
"dismissError": "Dismiss",
"playerNotConnected": "Player is not connected"
Expand Down
1 change: 1 addition & 0 deletions packages/frontend/src/locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,7 @@
"pause": "Pausar",
"nextTrack": "Próxima faixa",
"repeatMode": "Repetição: {{mode}}",
"progressMayBeOutdated": "pode estar desatualizado",
"commandInProgress": "Executando o comando…",
"dismissError": "Dispensar",
"playerNotConnected": "O player não está conectado"
Expand Down
47 changes: 43 additions & 4 deletions packages/frontend/src/pages/Music.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
Music2,
Expand Down Expand Up @@ -97,6 +97,7 @@ export default function MusicPage() {

<NowPlayingHero
state={player.state}
lastStateUpdate={player.lastStateUpdate}
controlsEnabled={controlsEnabled}
pendingAction={player.pendingAction}
onPlayPause={handlePlayPause}
Expand Down Expand Up @@ -179,8 +180,15 @@ export default function MusicPage() {
)
}

/**
* Progress is stale when no SSE/REST state or heartbeat arrives this long.
* Server heartbeat is 30s (stateRoutes stream); 1.5x that misses one ping.
*/
const STALE_AFTER_MS = 45_000

function NowPlayingHero({
state,
lastStateUpdate,
controlsEnabled,
pendingAction,
onPlayPause,
Expand All @@ -191,6 +199,7 @@ function NowPlayingHero({
onVolumeChange,
}: {
state: QueueState
lastStateUpdate: number | null
controlsEnabled: boolean
pendingAction: MusicActionKey | null
onPlayPause: () => void
Expand All @@ -205,6 +214,19 @@ function NowPlayingHero({
// upcoming queue for older state payloads that only filled tracks[].
const currentTrack = state.currentTrack ?? state.tracks[0]
const busy = Boolean(pendingAction)
const [now, setNow] = useState(() => Date.now())

// Re-tick while playing so the bar can flip to stale without a new SSE event.
useEffect(() => {
if (!state.isPlaying) return
const id = window.setInterval(() => setNow(Date.now()), 1000)
return () => window.clearInterval(id)
}, [state.isPlaying])

const isStale =
state.isPlaying &&
lastStateUpdate !== null &&
now - lastStateUpdate > STALE_AFTER_MS

if (!currentTrack) {
return (
Expand Down Expand Up @@ -269,15 +291,32 @@ function NowPlayingHero({

<div>
<div className='flex items-center gap-2 mb-3'>
<div className='flex-1 h-1 bg-lucky-bg-active rounded-full overflow-hidden'>
<div
className={`flex-1 h-1 bg-lucky-bg-active rounded-full overflow-hidden ${
isStale ? 'opacity-50' : ''
}`}
>
<div
className='h-full bg-lucky-brand rounded-full'
className={`h-full rounded-full ${
isStale
? 'bg-lucky-warning'
: 'bg-lucky-brand'
}`}
style={{ width: `${progress}%` }}
/>
</div>
</div>
<div className='flex justify-between type-body-sm text-lucky-text-tertiary'>
{/* Relative wrapper so the stale notice does not shift the timestamps. */}
<div className='relative flex justify-between type-body-sm text-lucky-text-tertiary'>
<span>{formatSeconds(position)}</span>
{isStale ? (
<span
role='status'
className='pointer-events-none absolute left-1/2 -translate-x-1/2 text-lucky-warning'
>
{t('music.progressMayBeOutdated')}
</span>
) : null}
<span>{formatSeconds(duration)}</span>
</div>
</div>
Expand Down
Loading