Commit 68164f7a authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Wire up now-playing, DJ song picking, and pass-aux in the Rooms UI

Rooms had chat, reactions, and "request aux" working, but the DJ had no
way to actually pick a song or hand off the aux, and now_playing_changed
was never even handled - the core "pass the aux" mechanic wasn't
reachable from the UI at all. Adds a now-playing card (streams via the
shared player, same pattern as Soundmarks), a song picker for the DJ
(reuses the existing SongPicker), a Pass Aux button, and visible
feedback for server-side errors (e.g. "only the DJ can do that").

Also adds the first frontend test coverage for any social feature -
Rooms/RoomView had none before this.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 4957eaf3
Pipeline #1070 canceled with stage
......@@ -17,15 +17,32 @@ export interface ChatMessage {
text: string
}
export interface RoomSong {
id: number
title: string
artist: string
album: string | null
coverart: string | null
}
export type RoomEvent =
| { type: 'snapshot'; dj_id: number; current_song_id: number | null; presence: number[]; chat_history: ChatMessage[]; fire_count: number; dj_queue: number[] }
| {
type: 'snapshot'
dj_id: number
current_song_id: number | null
current_song: RoomSong | null
presence: number[]
chat_history: ChatMessage[]
fire_count: number
dj_queue: number[]
}
| ChatMessage
| { type: 'reaction'; user_id: number; emoji: string; fire_count: number }
| { type: 'user_joined'; user_id: number }
| { type: 'user_left'; user_id: number }
| { type: 'queue_updated'; dj_queue: number[] }
| { type: 'dj_changed'; dj_id: number; dj_queue: number[] }
| { type: 'now_playing_changed'; song_id: number; dj_id: number }
| { type: 'now_playing_changed'; song_id: number | null; song: RoomSong | null; dj_id: number }
| { type: 'error'; detail: string }
/** Raw WebSocket wrapper for /social/rooms/{id}/ws - auth here is just a user_id query param
......@@ -58,3 +75,8 @@ export function requestAux(ws: WebSocket) {
export function passAux(ws: WebSocket, toUserId?: number) {
ws.send(JSON.stringify({ type: 'pass_aux', to_user_id: toUserId }))
}
/** DJ-only - the backend rejects this (with an `error` event) from anyone else. */
export function sendNowPlaying(ws: WebSocket, songId: number) {
ws.send(JSON.stringify({ type: 'now_playing', song_id: songId }))
}
import { apiFetch } from './client'
import { API_BASE_URL, apiFetch, getAccessToken } from './client'
export interface Post {
id: number
......@@ -63,3 +63,19 @@ export function getActiveRooms() {
export function createRoom(name: string) {
return apiFetch<LiveRoom>('/social/rooms', { method: 'POST', json: { name } })
}
/** For PlayerContext's `streamUrl` override - fetches whatever's currently playing in a room
* as an authenticated blob, regardless of who uploaded the underlying song (mirrors
* api/soundmarks.ts's fetchSoundmarkStreamUrl against the analogous room-scoped endpoint).
* Caller is responsible for calling URL.revokeObjectURL() when done. */
export async function fetchRoomStreamUrl(roomId: number): Promise<string> {
const token = getAccessToken()
const res = await fetch(`${API_BASE_URL}/social/rooms/${roomId}/stream`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
})
if (!res.ok) {
throw new Error(`Failed to load audio (${res.status})`)
}
const blob = await res.blob()
return URL.createObjectURL(blob)
}
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { RoomView } from './RoomView'
import { PlayerProvider } from '../context/PlayerContext'
import { clearTokens, setTokens } from '../api/client'
import * as roomSocketApi from '../api/roomSocket'
import type { RoomEvent } from '../api/roomSocket'
import * as socialApi from '../api/social'
import * as libraryApi from '../api/library'
/** Builds a real base64url-encoded JWT shape (unsigned - getCurrentUserId never verifies,
* that's the server's job), matching api/jwt.test.ts's own helper. */
function fakeJwt(payload: object): string {
const base64url = (obj: object) =>
btoa(JSON.stringify(obj)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
return `${base64url({ alg: 'HS256', typ: 'JWT' })}.${base64url(payload)}.fake-signature`
}
const SONG = { id: 42, title: 'Now Playing Track', artist: 'The Band', album: null, coverart: null }
function renderRoom(roomId = 1, onLeave = vi.fn()) {
return render(
<PlayerProvider>
<RoomView roomId={roomId} onLeave={onLeave} />
</PlayerProvider>,
)
}
describe('RoomView', () => {
let emit: (e: RoomEvent) => void
let fakeWs: { close: ReturnType<typeof vi.fn>; send: ReturnType<typeof vi.fn> }
beforeEach(() => {
clearTokens()
setTokens(fakeJwt({ sub: '1', type: 'access' }), 'refresh-token-unused')
fakeWs = { close: vi.fn(), send: vi.fn() }
vi.spyOn(roomSocketApi, 'connectToRoom').mockImplementation((_roomId, _userId, onEvent) => {
emit = onEvent
return fakeWs as unknown as WebSocket
})
})
afterEach(() => {
clearTokens()
vi.restoreAllMocks()
})
function snapshot(overrides: Partial<Extract<RoomEvent, { type: 'snapshot' }>> = {}) {
act(() => {
emit({
type: 'snapshot',
dj_id: 2,
current_song_id: null,
current_song: null,
presence: [1, 2],
chat_history: [],
fire_count: 0,
dj_queue: [],
...overrides,
})
})
}
it('shows the DJ and a waiting message for a listener when nothing is playing', () => {
renderRoom()
snapshot({ dj_id: 2 })
expect(screen.getByText('DJ #2')).toBeInTheDocument()
expect(screen.getByText("Nothing playing yet - waiting on the DJ.")).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Pick a song' })).not.toBeInTheDocument()
})
it("shows the DJ their own picker and pass-aux controls when it's their turn", () => {
renderRoom()
snapshot({ dj_id: 1 })
expect(screen.getByText('Nothing playing - pick a song below.')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Pick a song' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Pass aux/ })).toBeInTheDocument()
})
it('sends a chat message and clears the input', async () => {
renderRoom()
snapshot()
await userEvent.type(screen.getByPlaceholderText('Say something…'), 'hey everyone')
await userEvent.click(screen.getByRole('button', { name: 'Send' }))
expect(fakeWs.send).toHaveBeenCalledWith(JSON.stringify({ type: 'chat', text: 'hey everyone' }))
expect(screen.getByPlaceholderText('Say something…')).toHaveValue('')
})
it('renders incoming chat messages from the broadcast', () => {
renderRoom()
snapshot()
act(() => emit({ type: 'chat', user_id: 2, text: 'sup' }))
expect(screen.getByText('sup')).toBeInTheDocument()
expect(screen.getByText('#2:')).toBeInTheDocument()
})
it('sends a reaction and reflects the broadcasted fire count', async () => {
renderRoom()
snapshot()
await userEvent.click(screen.getByRole('button', { name: /React/ }))
expect(fakeWs.send).toHaveBeenCalledWith(JSON.stringify({ type: 'reaction', emoji: '🔥' }))
act(() => emit({ type: 'reaction', user_id: 1, emoji: '🔥', fire_count: 3 }))
expect(screen.getByText('3')).toBeInTheDocument()
})
it('lets a non-DJ request the aux and shows "Queued" once the broadcast confirms it', async () => {
renderRoom()
snapshot({ dj_id: 2 })
const button = screen.getByRole('button', { name: /Request aux/ })
await userEvent.click(button)
expect(fakeWs.send).toHaveBeenCalledWith(JSON.stringify({ type: 'request_aux' }))
act(() => emit({ type: 'queue_updated', dj_queue: [1] }))
expect(screen.getByRole('button', { name: 'Queued' })).toBeInTheDocument()
})
it('does not show a request-aux button for the current DJ', () => {
renderRoom()
snapshot({ dj_id: 1 })
expect(screen.queryByRole('button', { name: /Request aux/ })).not.toBeInTheDocument()
})
it('lets the DJ pass the aux', async () => {
renderRoom()
snapshot({ dj_id: 1 })
await userEvent.click(screen.getByRole('button', { name: /Pass aux/ }))
expect(fakeWs.send).toHaveBeenCalledWith(JSON.stringify({ type: 'pass_aux', to_user_id: undefined }))
})
it('lets the DJ pick a song from the library, sending it as now_playing', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({
status: 'success',
library: [
{
id: 55,
user_id: 1,
title: 'My Pick',
artist: 'Me',
album: null,
genre: null,
coverart: null,
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
},
],
})
renderRoom()
snapshot({ dj_id: 1 })
await userEvent.click(screen.getByRole('button', { name: 'Pick a song' }))
await userEvent.click(await screen.findByText('My Pick'))
expect(fakeWs.send).toHaveBeenCalledWith(JSON.stringify({ type: 'now_playing', song_id: 55 }))
})
it('shows the now-playing song from the initial snapshot and plays it on tap', async () => {
vi.spyOn(socialApi, 'fetchRoomStreamUrl').mockResolvedValue('blob:fake-room-stream')
renderRoom(7)
snapshot({ dj_id: 2, current_song_id: SONG.id, current_song: SONG })
expect(screen.getByText('Now Playing Track')).toBeInTheDocument()
expect(screen.getByText('The Band')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await waitFor(() => expect(socialApi.fetchRoomStreamUrl).toHaveBeenCalledWith(7))
expect(await screen.findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
it('updates the now-playing card when the DJ changes the song mid-session', () => {
renderRoom()
snapshot({ dj_id: 2 })
expect(screen.getByText("Nothing playing yet - waiting on the DJ.")).toBeInTheDocument()
act(() => emit({ type: 'now_playing_changed', song_id: SONG.id, song: SONG, dj_id: 2 }))
expect(screen.getByText('Now Playing Track')).toBeInTheDocument()
expect(screen.queryByText("Nothing playing yet - waiting on the DJ.")).not.toBeInTheDocument()
})
it('shows a server error message that clears itself after a few seconds', () => {
vi.useFakeTimers()
try {
renderRoom()
snapshot({ dj_id: 2 })
act(() => emit({ type: 'error', detail: 'Only the current DJ can change what\'s playing.' }))
expect(screen.getByText("Only the current DJ can change what's playing.")).toBeInTheDocument()
act(() => vi.advanceTimersByTime(4000))
expect(screen.queryByText("Only the current DJ can change what's playing.")).not.toBeInTheDocument()
} finally {
vi.useRealTimers()
}
})
it('closes the websocket connection when the room is left/unmounted', () => {
const { unmount } = renderRoom()
snapshot()
unmount()
expect(fakeWs.close).toHaveBeenCalled()
})
it('calls onLeave when the Leave button is clicked', async () => {
const onLeave = vi.fn()
renderRoom(1, onLeave)
snapshot()
await userEvent.click(screen.getByRole('button', { name: /Leave/ }))
expect(onLeave).toHaveBeenCalled()
})
})
import { useEffect, useRef, useState } from 'react'
import { ArrowLeft, Flame, Hand, Send } from 'lucide-react'
import { ArrowLeft, Flame, Hand, Music2, Pause, Play, Send, SkipForward } from 'lucide-react'
import { getCurrentUserId } from '../api/jwt'
import { connectToRoom, sendChat, sendReaction, requestAux, type ChatMessage } from '../api/roomSocket'
import { fetchRoomStreamUrl } from '../api/social'
import {
connectToRoom,
passAux,
requestAux,
sendChat,
sendNowPlaying,
sendReaction,
type ChatMessage,
type RoomSong,
} from '../api/roomSocket'
import { usePlayer } from '../context/PlayerContext'
import { Button } from './ui/Button'
import { Input } from './ui/Input'
import { SongPicker } from './SongPicker'
function toPlayable(roomId: number, song: RoomSong) {
return {
// Negative to avoid colliding with a real LibrarySong id (see PlayableSong's `streamUrl`
// doc) - keyed off the room, not the song, so the play/pause glyph stays correctly tied
// to "whatever this room is playing" even across a now_playing change.
id: -roomId,
title: song.title,
artist: song.artist,
album: song.album,
coverart: song.coverart,
streamUrl: () => fetchRoomStreamUrl(roomId),
}
}
export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => void }) {
const userId = getCurrentUserId()
......@@ -11,9 +37,20 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
const [fireCount, setFireCount] = useState(0)
const [djId, setDjId] = useState<number | null>(null)
const [djQueue, setDjQueue] = useState<number[]>([])
const [currentSong, setCurrentSong] = useState<RoomSong | null>(null)
const [text, setText] = useState('')
const [errorMessage, setErrorMessage] = useState<string | null>(null)
const [showSongPicker, setShowSongPicker] = useState(false)
const wsRef = useRef<WebSocket | null>(null)
const messagesEndRef = useRef<HTMLDivElement | null>(null)
const errorTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const { currentSong: playerSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
function flashError(detail: string) {
setErrorMessage(detail)
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
errorTimeoutRef.current = setTimeout(() => setErrorMessage(null), 4000)
}
useEffect(() => {
if (userId === null) return
......@@ -24,6 +61,7 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
setFireCount(event.fire_count)
setDjId(event.dj_id)
setDjQueue(event.dj_queue)
setCurrentSong(event.current_song)
break
case 'chat':
setMessages((m) => [...m, event])
......@@ -38,10 +76,20 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
setDjId(event.dj_id)
setDjQueue(event.dj_queue)
break
case 'now_playing_changed':
setCurrentSong(event.song)
break
case 'error':
flashError(event.detail)
break
}
})
wsRef.current = ws
return () => ws.close()
return () => {
ws.close()
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [roomId, userId])
useEffect(() => {
......@@ -55,10 +103,16 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
setText('')
}
function handlePickSong(song: { id: number }) {
setShowSongPicker(false)
if (wsRef.current) sendNowPlaying(wsRef.current, song.id)
}
const isDj = djId !== null && userId === djId
const active = currentSong ? toPlayable(roomId, currentSong) : null
const isCurrent = !!active && playerSong?.id === active.id
return (
// h-dvh (dynamic viewport height), not min-h-screen: on mobile, min-h-screen can end up
// taller than what's actually visible once browser chrome/the keyboard are accounted
// for, which breaks the "input pinned to the bottom of the screen" layout this needs.
<div className="flex h-dvh flex-col bg-neutral-950 text-white">
<header
className="flex shrink-0 items-center justify-between border-b border-neutral-800/80 px-4 py-3"
......@@ -82,6 +136,62 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
</div>
</header>
<div className="shrink-0 border-b border-neutral-800/80 px-4 py-3">
{currentSong && active ? (
<button
onClick={() => toggle(active)}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
className="flex w-full items-center gap-3 rounded-lg p-1 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-not-allowed"
>
{currentSong.coverart ? (
<img src={currentSong.coverart} alt="" className="h-12 w-12 shrink-0 rounded-lg object-cover" />
) : (
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-white">{currentSong.title}</p>
<p className="truncate text-xs text-neutral-400">{currentSong.artist}</p>
</div>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white">
{isCurrent && streamLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
) : isCurrent && isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</button>
) : (
<p className="px-1 py-2 text-sm text-neutral-500">
{isDj ? 'Nothing playing - pick a song below.' : "Nothing playing yet - waiting on the DJ."}
</p>
)}
{isDj && (
<div className="mt-2 flex gap-2 px-1">
<Button variant="secondary" size="sm" onClick={() => setShowSongPicker(true)}>
{currentSong ? 'Change song' : 'Pick a song'}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => wsRef.current && passAux(wsRef.current)}
className="gap-1.5"
>
<SkipForward size={14} strokeWidth={2} />
Pass aux
</Button>
</div>
)}
</div>
{errorMessage && (
<p className="shrink-0 bg-red-950/40 px-4 py-2 text-center text-xs text-red-400">{errorMessage}</p>
)}
<div className="flex-1 overflow-y-auto px-4 py-4">
<ul className="space-y-2">
{messages.map((m, i) => (
......@@ -116,6 +226,8 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
</Button>
</form>
</div>
{showSongPicker && <SongPicker onClose={() => setShowSongPicker(false)} onSelect={handlePickSong} />}
</div>
)
}
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Rooms } from './Rooms'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as socialApi from '../api/social'
// RoomView renders a real WebSocket-backed chat UI, fully covered by its own test file - here
// it's stubbed down to its essential contract: show which room it's in and call onLeave.
vi.mock('../components/RoomView', () => ({
RoomView: ({ roomId, onLeave }: { roomId: number; onLeave: () => void }) => (
<div>
<p>In room {roomId}</p>
<button onClick={onLeave}>Leave</button>
</div>
),
}))
const ROOM: socialApi.LiveRoom = {
id: 1,
dj_id: 5,
current_song_id: null,
name: 'Friday Night Vibes',
is_active: true,
created_at: '2026-01-01T00:00:00Z',
}
function renderRooms() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Rooms />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Rooms', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows an empty state when there are no active rooms', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
renderRooms()
expect(await screen.findByText(/No active rooms right now/)).toBeInTheDocument()
})
it('lists active rooms with their DJ', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([ROOM])
renderRooms()
expect(await screen.findByText('Friday Night Vibes')).toBeInTheDocument()
expect(screen.getByText('DJ #5')).toBeInTheDocument()
})
it('joins a room when clicked, and leaving returns to the list', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([ROOM])
renderRooms()
await userEvent.click(await screen.findByText('Friday Night Vibes'))
expect(await screen.findByText('In room 1')).toBeInTheDocument()
expect(screen.queryByText('Friday Night Vibes')).not.toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Leave' }))
expect(await screen.findByText('Friday Night Vibes')).toBeInTheDocument()
})
it('creates a room and jumps straight into it', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
const create = vi.spyOn(socialApi, 'createRoom').mockResolvedValue({
id: 9,
dj_id: 1,
current_song_id: null,
name: 'New Room',
is_active: true,
created_at: '2026-01-01T00:00:00Z',
})
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.type(screen.getByPlaceholderText('Room name'), 'New Room')
await userEvent.click(screen.getByRole('button', { name: 'Start' }))
await waitFor(() => expect(create).toHaveBeenCalledWith('New Room'))
expect(await screen.findByText('In room 9')).toBeInTheDocument()
})
it('does not create a room from a blank name', async () => {
vi.spyOn(socialApi, 'getActiveRooms').mockResolvedValue([])
const create = vi.spyOn(socialApi, 'createRoom')
renderRooms()
await screen.findByText(/No active rooms right now/)
await userEvent.click(screen.getByRole('button', { name: 'Start' }))
expect(create).not.toHaveBeenCalled()
})
})
......@@ -9,3 +9,8 @@ window.HTMLMediaElement.prototype.pause = vi.fn()
// jsdom has no real object URL storage - fine for tests, we just need these to not throw.
window.URL.createObjectURL = vi.fn(() => 'blob:mock-url')
window.URL.revokeObjectURL = vi.fn()
// jsdom doesn't implement layout, so Element.prototype.scrollIntoView doesn't exist at all
// (not a no-op, genuinely undefined) - anything that auto-scrolls a new message/item into
// view (e.g. RoomView's chat) throws without this.
window.HTMLElement.prototype.scrollIntoView = vi.fn()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment