Commit e2fa0f05 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add direct messages, location/DM privacy toggles, presence map, and joint playlist

New DM UI (inbox + threaded conversation) as a 4th Social tab, backed by
the new backend DM router. New /settings page for the two opt-in privacy
toggles. Soundmarks' Map tab now shows live listener presence with a
Message button; "Play my geo playlist" evolved into a continuous joint
playlist that keeps its queue live on the existing 15s nearby-refresh,
including a fix so a departed listener's currently-playing track finishes
instead of silently cutting out. Room chat is now keyed by real message
ids instead of array position, matching the backend's move off an
in-memory deque.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 8d5e0200
......@@ -21,6 +21,8 @@ const BusinessPanel = lazy(() => import('./pages/BusinessPanel').then((m) => ({
const AdminPanel = lazy(() => import('./pages/AdminPanel').then((m) => ({ default: m.AdminPanel })))
const Roadmap = lazy(() => import('./pages/Roadmap').then((m) => ({ default: m.Roadmap })))
const Login = lazy(() => import('./pages/Login').then((m) => ({ default: m.Login })))
const Settings = lazy(() => import('./pages/Settings').then((m) => ({ default: m.Settings })))
const DMThreadView = lazy(() => import('./components/DMThreadView').then((m) => ({ default: m.DMThreadView })))
function protect(element: React.ReactElement) {
return <ProtectedRoute>{element}</ProtectedRoute>
......@@ -49,6 +51,8 @@ export function App() {
<Route path="/upload" element={protect(<Upload />)} />
<Route path="/discovery" element={protect(<Discovery />)} />
<Route path="/social" element={protect(<Social />)} />
<Route path="/dm/:threadId" element={protect(<DMThreadView />)} />
<Route path="/settings" element={protect(<Settings />)} />
{/* Gated by a build-time flag (see config/flags.ts) rather than removed - fully built
and used elsewhere, just not yet exposed to prod users. Redirects rather than 404s
so a stale link/bookmark lands somewhere real instead of a dead end. */}
......
......@@ -93,12 +93,26 @@ export async function fetchChatMusicPreviewUrl(chatId: number, messageId: number
export type UserRole = 'user' | 'business_admin' | 'super_admin'
export interface PrivacySettings {
share_location_enabled: boolean
allow_direct_messages: boolean
}
export interface CurrentUser {
id: number
username: string | null
role: UserRole
privacy: PrivacySettings
}
export function getMe() {
return apiFetch<{ status: string; user: CurrentUser }>('/auth/me')
}
/** Partial update - pass just the field(s) you're changing. */
export function updatePrivacy(update: Partial<PrivacySettings>) {
return apiFetch<{ status: string; privacy: PrivacySettings }>('/auth/privacy', {
method: 'PATCH',
json: update,
})
}
import { apiFetch } from './client'
export interface DMThread {
id: number
user_a_id: number
user_b_id: number
created_at: string
}
export interface DMMessage {
type: 'chat'
id: number
thread_id: number
sender_id: number
text: string
created_at: string
}
/** Creates (or, if the pair already has one, reuses) a thread with recipientId - 403s if
* they haven't opted into direct messages (see PrivacySettings.allow_direct_messages), unless
* a thread with them already exists (in which case there's no re-check of the flag). */
export function createDMThread(recipientId: number) {
return apiFetch<DMThread>('/dm/threads', { method: 'POST', json: { recipient_id: recipientId } })
}
/** Only ever returns threads the caller is actually a participant in. */
export function listDMThreads() {
return apiFetch<DMThread[]>('/dm/threads')
}
export function getDMMessages(threadId: number, beforeId?: number, limit = 50) {
const params = new URLSearchParams({ limit: String(limit) })
if (beforeId !== undefined) params.set('before_id', String(beforeId))
return apiFetch<DMMessage[]>(`/dm/threads/${threadId}/messages?${params.toString()}`)
}
import { API_BASE_URL } from './client'
import type { DMMessage } from './dm'
/** Unlike fetch(), the WebSocket constructor won't resolve a schemeless URL against the page's
* own protocol - it requires ws:/wss: explicitly, so a relative API_BASE_URL (dev's same-origin
* proxy, see vite.config.ts) needs its scheme derived from the current page by hand. Mirrors
* roomSocket.ts's identical helper. */
function resolveWsBase(): string {
if (/^https?:\/\//.test(API_BASE_URL)) {
return API_BASE_URL.replace(/^http/, 'ws')
}
const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws'
return `${scheme}://${window.location.host}${API_BASE_URL}`
}
export type DMEvent = DMMessage | { type: 'error'; detail: string }
/** Raw WebSocket wrapper for /dm/threads/{id}/ws - mirrors connectToRoom's shape exactly (same
* JWT-over-query-param verification, since browsers' native WebSocket API can't set an
* Authorization header). */
export function connectToDMThread(threadId: number, accessToken: string, onEvent: (e: DMEvent) => void): WebSocket {
const wsBase = resolveWsBase()
const ws = new WebSocket(`${wsBase}/dm/threads/${threadId}/ws?token=${encodeURIComponent(accessToken)}`)
ws.onmessage = (msg) => {
try {
onEvent(JSON.parse(msg.data) as DMEvent)
} catch {
// ignore malformed frames
}
}
return ws
}
export function sendDMChat(ws: WebSocket, text: string) {
ws.send(JSON.stringify({ type: 'chat', text }))
}
......@@ -13,8 +13,10 @@ function resolveWsBase(): string {
export interface ChatMessage {
type: 'chat'
id: number
user_id: number
text: string
created_at: string
}
export interface RoomSong {
......
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { DMInbox } from './DMInbox'
import { clearTokens, setTokens } from '../api/client'
import * as dmApi from '../api/dm'
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`
}
function renderInbox() {
return render(
<MemoryRouter initialEntries={['/social']}>
<Routes>
<Route path="/social" element={<DMInbox />} />
<Route path="/dm/:threadId" element={<div>Thread view</div>} />
</Routes>
</MemoryRouter>,
)
}
describe('DMInbox', () => {
beforeEach(() => {
clearTokens()
setTokens(fakeJwt({ sub: '1', type: 'access' }), 'refresh-token-unused')
})
afterEach(() => {
clearTokens()
vi.restoreAllMocks()
})
it('shows an empty state with no threads', async () => {
vi.spyOn(dmApi, 'listDMThreads').mockResolvedValue([])
renderInbox()
expect(await screen.findByText(/No conversations yet/)).toBeInTheDocument()
})
it('lists threads by the other participant, regardless of which side of the pair the caller is', async () => {
vi.spyOn(dmApi, 'listDMThreads').mockResolvedValue([
{ id: 10, user_a_id: 1, user_b_id: 5, created_at: '2026-01-01T00:00:00Z' }, // caller is user_a
{ id: 11, user_a_id: 3, user_b_id: 1, created_at: '2026-01-01T00:00:00Z' }, // caller is user_b
])
renderInbox()
expect(await screen.findByText('User #5')).toBeInTheDocument()
expect(screen.getByText('User #3')).toBeInTheDocument()
})
it('navigates to the thread when tapped', async () => {
vi.spyOn(dmApi, 'listDMThreads').mockResolvedValue([
{ id: 10, user_a_id: 1, user_b_id: 5, created_at: '2026-01-01T00:00:00Z' },
])
renderInbox()
await userEvent.click(await screen.findByText('User #5'))
expect(await screen.findByText('Thread view')).toBeInTheDocument()
})
})
import { useEffect, useState } from 'react'
import { ChevronRight, MessageCircle } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { getCurrentUserId } from '../api/jwt'
import { listDMThreads, type DMThread } from '../api/dm'
import { EmptyState } from './ui/EmptyState'
/** Thread list for Social.tsx's "Messages" tab. Threads carry only user ids, not usernames
* (see DMThread) - "User #<id>" matches the same fallback RoomView/GeoDrops already use
* wherever a username isn't available. */
export function DMInbox() {
const [threads, setThreads] = useState<DMThread[]>([])
const [loading, setLoading] = useState(true)
const navigate = useNavigate()
const userId = getCurrentUserId()
useEffect(() => {
listDMThreads()
.then(setThreads)
.finally(() => setLoading(false))
}, [])
if (!loading && threads.length === 0) {
return (
<EmptyState
icon={MessageCircle}
message="No conversations yet - start one from a listener's marker on the Soundmarks map."
/>
)
}
return (
<ul className="space-y-2">
{threads.map((thread) => {
const otherId = thread.user_a_id === userId ? thread.user_b_id : thread.user_a_id
return (
<li key={thread.id}>
<button
onClick={() => navigate(`/dm/${thread.id}`)}
className="flex min-h-[52px] w-full items-center justify-between gap-3 rounded-lg border border-outline-variant bg-surface-container px-4 py-3 text-left transition-colors duration-150 hover:border-outline-variant hover:bg-surface-container/70"
>
<div className="flex items-center gap-3">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-surface-container-high text-on-surface-variant">
<MessageCircle size={16} strokeWidth={1.75} />
</span>
<p className="font-medium text-on-surface">User #{otherId}</p>
</div>
<ChevronRight size={18} strokeWidth={2} className="shrink-0 text-on-surface-variant" />
</button>
</li>
)
})}
</ul>
)
}
import { act, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { DMThreadView } from './DMThreadView'
import { clearTokens, setTokens } from '../api/client'
import * as dmApi from '../api/dm'
import * as dmSocketApi from '../api/dmSocket'
import type { DMEvent } from '../api/dmSocket'
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`
}
function renderThread(threadId = 1) {
return render(
<MemoryRouter initialEntries={[`/dm/${threadId}`]}>
<Routes>
<Route path="/dm/:threadId" element={<DMThreadView />} />
<Route path="/social" element={<div>Back on Social</div>} />
</Routes>
</MemoryRouter>,
)
}
describe('DMThreadView', () => {
let emit: (e: DMEvent) => 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(dmSocketApi, 'connectToDMThread').mockImplementation((_threadId, _accessToken, onEvent) => {
emit = onEvent
return fakeWs as unknown as WebSocket
})
vi.spyOn(dmApi, 'getDMMessages').mockResolvedValue([])
})
afterEach(() => {
clearTokens()
vi.restoreAllMocks()
})
it('loads and shows prior scrollback history', async () => {
vi.spyOn(dmApi, 'getDMMessages').mockResolvedValue([
{ type: 'chat', id: 1, thread_id: 1, sender_id: 2, text: 'hey', created_at: '2026-01-01T00:00:00Z' },
])
renderThread()
expect(await screen.findByText('hey')).toBeInTheDocument()
})
it('sends a message and clears the input', async () => {
renderThread()
await screen.findByPlaceholderText('Message…')
await userEvent.type(screen.getByPlaceholderText('Message…'), 'yo')
await userEvent.click(screen.getByRole('button', { name: 'Send' }))
expect(fakeWs.send).toHaveBeenCalledWith(JSON.stringify({ type: 'chat', text: 'yo' }))
expect(screen.getByPlaceholderText('Message…')).toHaveValue('')
})
it('renders an incoming message pushed over the socket, keyed by its real id', async () => {
renderThread()
await screen.findByPlaceholderText('Message…')
act(() => emit({ type: 'chat', id: 9, thread_id: 1, sender_id: 2, text: 'incoming', created_at: '2026-01-01T00:00:00Z' }))
expect(screen.getByText('incoming')).toBeInTheDocument()
})
it('shows a server error pushed over the socket', async () => {
renderThread()
await screen.findByPlaceholderText('Message…')
act(() => emit({ type: 'error', detail: 'Something went wrong' }))
expect(await screen.findByText('Something went wrong')).toBeInTheDocument()
})
it('navigates back to Social', async () => {
renderThread()
await screen.findByPlaceholderText('Message…')
await userEvent.click(screen.getByRole('button', { name: /Back/ }))
expect(await screen.findByText('Back on Social')).toBeInTheDocument()
})
})
import { useEffect, useRef, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { ArrowLeft, Send } from 'lucide-react'
import { getCurrentUserId } from '../api/jwt'
import { getAccessToken } from '../api/client'
import { getDMMessages, type DMMessage } from '../api/dm'
import { connectToDMThread, sendDMChat, type DMEvent } from '../api/dmSocket'
import { Button } from './ui/Button'
import { Input } from './ui/Input'
/** Mirrors RoomView.tsx's shape (header, scrollback, input) - keyed by real message ids from
* the start, since DM messages (unlike Rooms chat originally) always have one. */
export function DMThreadView() {
const { threadId: threadIdParam } = useParams<{ threadId: string }>()
const threadId = Number(threadIdParam)
const navigate = useNavigate()
const userId = getCurrentUserId()
const [messages, setMessages] = useState<DMMessage[]>([])
const [text, setText] = useState('')
const [errorMessage, setErrorMessage] = useState<string | null>(null)
const wsRef = useRef<WebSocket | null>(null)
const messagesEndRef = useRef<HTMLDivElement | null>(null)
const errorTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
function flashError(detail: string) {
setErrorMessage(detail)
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
errorTimeoutRef.current = setTimeout(() => setErrorMessage(null), 4000)
}
useEffect(() => {
if (!Number.isFinite(threadId)) return
getDMMessages(threadId)
.then(setMessages)
.catch(() => flashError("Couldn't load this conversation."))
const accessToken = getAccessToken()
if (accessToken === null) return
const ws = connectToDMThread(threadId, accessToken, (event: DMEvent) => {
if (event.type === 'chat') {
setMessages((m) => [...m, event])
} else if (event.type === 'error') {
flashError(event.detail)
}
})
wsRef.current = ws
return () => {
ws.close()
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [threadId])
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ block: 'end', behavior: 'smooth' })
}, [messages])
function handleSend(e: React.FormEvent) {
e.preventDefault()
if (!text.trim() || !wsRef.current) return
sendDMChat(wsRef.current, text.trim())
setText('')
}
return (
<div className="flex h-dvh flex-col bg-background text-on-surface">
<header
className="flex shrink-0 items-center border-b border-outline-variant/80 px-4 py-3"
style={{ paddingTop: 'calc(env(safe-area-inset-top) + 0.75rem)' }}
>
<button
onClick={() => navigate('/social')}
className="flex min-h-[44px] items-center gap-1.5 pr-2 text-sm text-on-surface-variant transition-colors hover:text-on-surface"
>
<ArrowLeft size={16} strokeWidth={2} />
Back
</button>
<span className="ml-1 text-sm font-medium text-on-surface-variant">Direct message</span>
</header>
{errorMessage && (
<p className="shrink-0 bg-red-950/40 px-4 py-2 text-center text-xs text-error">{errorMessage}</p>
)}
<div className="flex-1 overflow-y-auto px-4 py-4">
<ul className="space-y-2">
{messages.map((m) => (
<li key={m.id} className={`animate-message-enter flex ${m.sender_id === userId ? 'justify-end' : 'justify-start'}`}>
<span
className={`max-w-[80%] rounded-2xl px-3 py-1.5 text-sm ${
m.sender_id === userId ? 'bg-primary text-on-primary' : 'bg-surface-container text-on-surface'
}`}
>
{m.text}
</span>
</li>
))}
</ul>
<div ref={messagesEndRef} />
</div>
<form
onSubmit={handleSend}
className="flex shrink-0 gap-2 border-t border-outline-variant/80 px-4 pt-3"
style={{ paddingBottom: 'calc(env(safe-area-inset-bottom) + 0.75rem)' }}
>
<Input value={text} onChange={(e) => setText(e.target.value)} placeholder="Message…" />
<Button size="icon" aria-label="Send">
<Send size={17} strokeWidth={2} />
</Button>
</form>
</div>
)
}
......@@ -11,6 +11,7 @@ import {
MapPin,
MoreHorizontal,
Radio,
Settings as SettingsIcon,
ShieldCheck,
Store,
Upload,
......@@ -43,6 +44,7 @@ const ALL_NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/remix', label: 'Remix', icon: Wand2 },
{ to: '/soundmarks', label: 'Soundmarks', icon: MapPin },
{ to: '/telegram-link', label: 'Telegram', icon: Link2 },
{ to: '/settings', label: 'Settings', icon: SettingsIcon },
]
const NAV_ITEMS = REMIX_ENABLED ? ALL_NAV_ITEMS : ALL_NAV_ITEMS.filter((item) => item.to !== '/remix')
......
......@@ -91,11 +91,23 @@ describe('RoomView', () => {
it('renders incoming chat messages from the broadcast', () => {
renderRoom()
snapshot()
act(() => emit({ type: 'chat', user_id: 2, text: 'sup' }))
act(() => emit({ type: 'chat', id: 101, user_id: 2, text: 'sup', created_at: '2026-01-01T00:00:00Z' }))
expect(screen.getByText('sup')).toBeInTheDocument()
expect(screen.getByText('#2:')).toBeInTheDocument()
})
it('keys the chat list by message id, not array position', () => {
renderRoom()
snapshot()
act(() => emit({ type: 'chat', id: 5, user_id: 2, text: 'first', created_at: '2026-01-01T00:00:00Z' }))
const firstLi = screen.getByText('first').closest('li')
act(() => emit({ type: 'chat', id: 6, user_id: 2, text: 'second', created_at: '2026-01-01T00:00:01Z' }))
// The first message's <li> node must be the same DOM node after a second message arrives -
// if it were still keyed by array index, React would reuse/mutate positions instead of
// tracking each message by its real identity.
expect(screen.getByText('first').closest('li')).toBe(firstLi)
})
it('sends a reaction and reflects the broadcasted fire count', async () => {
renderRoom()
snapshot()
......
......@@ -196,8 +196,8 @@ export function RoomView({ roomId, onLeave }: { roomId: number; onLeave: () => v
<div className="flex-1 overflow-y-auto px-4 py-4">
<ul className="space-y-2">
{messages.map((m, i) => (
<li key={i} className="animate-message-enter text-sm">
{messages.map((m) => (
<li key={m.id} className="animate-message-enter text-sm">
<span className="text-outline">#{m.user_id}:</span> {m.text}
</li>
))}
......
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { describe, expect, it } from 'vitest'
import { SoundmarkMap } from './SoundmarkMap'
import type { NearbySoundmark } from '../api/soundmarks'
import type { LiveListener } from '../api/social'
const NEARBY: NearbySoundmark = {
id: 1,
......@@ -22,19 +24,44 @@ const NEARBY: NearbySoundmark = {
distance_meters: 10,
}
const LISTENER: { listener: LiveListener; distance_km: number } = {
listener: {
user_id: 9,
username: 'nearby-user',
song: { id: 2, title: 'Their Song', artist: 'Their Artist', album: null, coverart: null },
latitude: 37.7749,
longitude: -122.4194,
updated_at: '2026-01-01T00:00:00Z',
},
distance_km: 0.1,
}
function renderMap(props: Partial<React.ComponentProps<typeof SoundmarkMap>> = {}) {
return render(
<MemoryRouter>
<SoundmarkMap userLocation={{ lat: 37.7749, lon: -122.4194 }} soundmarks={[NEARBY]} {...props} />
</MemoryRouter>,
)
}
describe('SoundmarkMap', () => {
it('renders without crashing given a live location and nearby soundmarks', () => {
render(<SoundmarkMap userLocation={{ lat: 37.7749, lon: -122.4194 }} soundmarks={[NEARBY]} />)
renderMap()
expect(screen.getByRole('button', { name: 'Center on me' })).toBeInTheDocument()
})
it('renders with an empty soundmarks list (just the live location dot)', () => {
render(<SoundmarkMap userLocation={{ lat: 0, lon: 0 }} soundmarks={[]} />)
renderMap({ soundmarks: [] })
expect(screen.getByRole('button', { name: 'Center on me' })).toBeInTheDocument()
})
it('the "Center on me" button is clickable without throwing', async () => {
render(<SoundmarkMap userLocation={{ lat: 37.7749, lon: -122.4194 }} soundmarks={[NEARBY]} />)
renderMap()
await userEvent.click(screen.getByRole('button', { name: 'Center on me' }))
})
it('renders without crashing given nearby live listeners', () => {
renderMap({ listeners: [LISTENER] })
expect(screen.getByRole('button', { name: 'Center on me' })).toBeInTheDocument()
})
})
......@@ -2,14 +2,54 @@ import { useEffect, useState } from 'react'
import { CircleMarker, MapContainer, Marker, Popup, TileLayer, useMap } from 'react-leaflet'
import type { Map as LeafletMap } from 'leaflet'
import { LocateFixed } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import type { NearbySoundmark } from '../api/soundmarks'
import { DARK_TILE_ATTRIBUTION, DARK_TILE_URL, soundmarkIcon } from '../lib/mapTheme'
import type { LiveListener } from '../api/social'
import { createDMThread } from '../api/dm'
import { ApiError } from '../api/client'
import { DARK_TILE_ATTRIBUTION, DARK_TILE_URL, listenerIcon, soundmarkIcon } from '../lib/mapTheme'
const INITIAL_ZOOM = 16
interface SoundmarkMapProps {
userLocation: { lat: number; lon: number }
soundmarks: NearbySoundmark[]
/** Same shape getNearbyLiveListeners() returns - already privacy-filtered server-side (only
* users who've opted into share_location_enabled show up at all), no extra frontend check
* needed. */
listeners?: { listener: LiveListener; distance_km: number }[]
}
/** Starts (or reuses) a DM thread with a listener from their map popup. A 403 - they haven't
* opted into direct messages - is an expected, non-error outcome given the opt-in design, not
* a failure state, so it renders as an inline message rather than a toast/error. */
function MessageButton({ userId }: { userId: number }) {
const navigate = useNavigate()
const [status, setStatus] = useState<'idle' | 'sending' | 'declined'>('idle')
async function handleClick() {
setStatus('sending')
try {
const thread = await createDMThread(userId)
navigate(`/dm/${thread.id}`)
} catch (err) {
setStatus(err instanceof ApiError && err.status === 403 ? 'declined' : 'idle')
}
}
if (status === 'declined') {
return <p className="mt-1 text-xs text-on-surface-variant">Not accepting messages right now.</p>
}
return (
<button
onClick={handleClick}
disabled={status === 'sending'}
className="mt-1 text-xs font-medium text-primary hover:underline disabled:opacity-50"
>
{status === 'sending' ? 'Starting…' : 'Message'}
</button>
)
}
/** Pans to the user's position exactly once, when the map first mounts (the very first GPS
......@@ -28,7 +68,7 @@ function CenterOnMount({ lat, lon }: { lat: number; lon: number }) {
/** Live-updating "you are here" dot, plus pins for whatever soundmarks are currently in range
* (from the same /soundmarks/nearby result the card view below uses) - a real map screen
* alongside the text-based summary, not a replacement for it. */
export function SoundmarkMap({ userLocation, soundmarks }: SoundmarkMapProps) {
export function SoundmarkMap({ userLocation, soundmarks, listeners }: SoundmarkMapProps) {
const [map, setMap] = useState<LeafletMap | null>(null)
function centerOnMe() {
......@@ -66,6 +106,17 @@ export function SoundmarkMap({ userLocation, soundmarks }: SoundmarkMapProps) {
</Popup>
</Marker>
))}
{listeners?.map(({ listener }) => (
<Marker key={listener.user_id} position={[listener.latitude, listener.longitude]} icon={listenerIcon()}>
<Popup>
<span className="font-medium">{listener.username ?? `User #${listener.user_id}`}</span>
<br />
{listener.song ? `${listener.song.title} · ${listener.song.artist}` : 'Not playing anything'}
<br />
<MessageButton userId={listener.user_id} />
</Popup>
</Marker>
))}
</MapContainer>
<button
onClick={centerOnMe}
......
......@@ -69,7 +69,7 @@ describe('AuthProvider bootstrap from stored tokens', () => {
it('is authenticated immediately when a token is already stored (e.g. a prior real login)', async () => {
setTokens('stored-access-token', 'stored-refresh-token')
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user' } })
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user', privacy: { share_location_enabled: false, allow_direct_messages: false } } })
render(
<AuthProvider>
......@@ -87,7 +87,7 @@ describe('AuthProvider bootstrap from stored tokens', () => {
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: 1, username: 'dev-test-user', role: 'super_admin' },
user: { id: 1, username: 'dev-test-user', role: 'super_admin', privacy: { share_location_enabled: false, allow_direct_messages: false } },
})
render(
......@@ -107,7 +107,7 @@ describe('AuthProvider bootstrap from stored tokens', () => {
it('leaves role null (not "user") until the fetch resolves, and plain "user" role gates out admin UI', async () => {
setTokens('stored-access-token', 'stored-refresh-token')
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user' } })
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user', privacy: { share_location_enabled: false, allow_direct_messages: false } } })
render(
<AuthProvider>
......@@ -203,7 +203,7 @@ describe('completeLogin', () => {
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: 1, username: 'real-user', role: 'user' },
user: { id: 1, username: 'real-user', role: 'user', privacy: { share_location_enabled: false, allow_direct_messages: false } },
})
function LoginButton() {
......@@ -248,7 +248,7 @@ describe('logout', () => {
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: 1, username: 'x', role: 'super_admin' },
user: { id: 1, username: 'x', role: 'super_admin', privacy: { share_location_enabled: false, allow_direct_messages: false } },
})
vi.spyOn(authApi, 'logout').mockResolvedValue({ status: 'success' })
......
......@@ -51,6 +51,10 @@ interface PlayerContextValue {
* never starts, stops, or replaces whatever's currently playing (or isn't). A no-op if the
* song is already queued, rather than moving it to the end. */
addToQueue: (song: PlayableSong) => void
/** Replaces the queue array wholesale without touching currentSong/isPlaying/isLoading -
* for a continuously-refreshed source (the Soundmarks joint playlist) where the whole set
* of upcoming tracks changes on a timer, not one song at a time like addToQueue. */
updateQueue: (songs: PlayableSong[]) => void
pause: () => void
next: () => void
/** Restarts the current track if more than a few seconds in (Spotify convention),
......@@ -261,6 +265,11 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
}
}, [])
const updateQueue = useCallback((songs: PlayableSong[]) => {
originalQueueRef.current = songs
setQueue(songs)
}, [])
return (
<PlayerContext.Provider
value={{
......@@ -278,6 +287,7 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
playbackError,
toggle,
addToQueue,
updateQueue,
pause,
next,
previous,
......
......@@ -40,3 +40,21 @@ export function soundmarkIcon(tier: MarkerTier): L.DivIcon {
iconCache.set(tier, icon)
return icon
}
let listenerIconCache: L.DivIcon | null = null
/** A small filled circle for nearby live listeners - visually distinct from soundmarkIcon's
* teardrop pins so "a person, right now" and "a fixed spot" are unambiguous at a glance. */
export function listenerIcon(): L.DivIcon {
if (listenerIconCache) return listenerIconCache
listenerIconCache = L.divIcon({
className: 'stax-map-pin',
html: `<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<circle cx="10" cy="10" r="8" fill="#34d399" stroke="#0a0a0a" stroke-width="2"/>
</svg>`,
iconSize: [20, 20],
iconAnchor: [10, 10],
popupAnchor: [0, -10],
})
return listenerIconCache
}
import { render, screen, waitFor, within } from '@testing-library/react'
import { act, fireEvent, render, screen, waitFor, within } 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'
......@@ -19,6 +19,18 @@ const LISTENER_A: { listener: socialApi.LiveListener; distance_km: number } = {
distance_km: 0.12,
}
const LISTENER_B: { listener: socialApi.LiveListener; distance_km: number } = {
listener: {
user_id: 7,
username: 'newcomer',
song: { id: 43, title: 'Arriving Track', artist: 'Fresh Band', album: null, coverart: null },
latitude: 37.7749,
longitude: -122.4194,
updated_at: '2026-01-01T00:00:00Z',
},
distance_km: 0.2,
}
const LISTENER_NO_SONG: { listener: socialApi.LiveListener; distance_km: number } = {
listener: {
user_id: 6,
......@@ -31,6 +43,18 @@ const LISTENER_NO_SONG: { listener: socialApi.LiveListener; distance_km: number
distance_km: 0.5,
}
/** Exposes the shared player's live queue/currentSong so tests can assert on the joint
* playlist's merge behavior without reaching into PlayerContext internals. */
function QueueInspector() {
const { currentSong, queue } = usePlayer()
return (
<div>
<span data-testid="current-id">{currentSong?.id ?? 'none'}</span>
<span data-testid="queue-ids">{queue.map((s) => s.id).join(',')}</span>
</div>
)
}
function mockGeolocation({ succeed = true, code = 1 }: { succeed?: boolean; code?: number } = {}) {
const position = { coords: { latitude: 37.7749, longitude: -122.4194 } } as GeolocationPosition
const geolocation = {
......@@ -233,7 +257,7 @@ describe('GeoDrops (live location)', () => {
expect(await within(card).findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
it('disables the geo playlist button when no one nearby has a song', async () => {
it('disables the joint playlist button when no one nearby has a song', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([LISTENER_NO_SONG])
......@@ -241,10 +265,10 @@ describe('GeoDrops (live location)', () => {
await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
await screen.findByText('quiet-one')
expect(screen.getByRole('button', { name: /Play my geo playlist/ })).toBeDisabled()
expect(screen.getByRole('button', { name: /Play joint playlist/ })).toBeDisabled()
})
it('shuffles nearby songs into a queue and starts playing on "Play my geo playlist"', async () => {
it('shuffles nearby songs into a queue and starts playing on "Play joint playlist"', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([LISTENER_A])
vi.spyOn(socialApi, 'fetchLiveLocationStreamUrl').mockResolvedValue('blob:fake-url')
......@@ -253,12 +277,70 @@ describe('GeoDrops (live location)', () => {
await userEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
await screen.findByText('Their Track')
await userEvent.click(screen.getByRole('button', { name: /Play my geo playlist/ }))
await userEvent.click(screen.getByRole('button', { name: /Play joint playlist/ }))
await waitFor(() => {
expect(socialApi.fetchLiveLocationStreamUrl).toHaveBeenCalledWith(LISTENER_A.listener.user_id)
})
const card = screen.getByText(/120m away/).closest('li')!
expect(await within(card).findByRole('button', { name: 'Pause' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Stop joint playlist/ })).toBeInTheDocument()
})
it("keeps a departed listener's currently-playing song queued until it finishes, but drops a departed non-playing listener immediately", async () => {
mockGeolocation({ succeed: true })
const getNearby = vi.spyOn(socialApi, 'getNearbyLiveListeners')
getNearby.mockResolvedValueOnce([LISTENER_A])
vi.spyOn(socialApi, 'fetchLiveLocationStreamUrl').mockResolvedValue('blob:fake-url')
render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<QueueInspector />
<GeoDrops />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
// Fake timers have to be active before "Find nearby listeners" is clicked, since that's
// what starts the component's NEARBY_REFRESH_MS setInterval - switching afterward wouldn't
// take over an interval already registered against the real clock.
vi.useFakeTimers()
try {
fireEvent.click(screen.getByRole('button', { name: 'Find nearby listeners' }))
await act(async () => {
await vi.advanceTimersByTimeAsync(0)
})
fireEvent.click(screen.getByRole('button', { name: /Play joint playlist/ }))
await act(async () => {
await vi.advanceTimersByTimeAsync(0)
})
expect(screen.getByTestId('current-id').textContent).toBe('-5')
expect(screen.getByTestId('queue-ids').textContent).toBe('-5')
// Poll 1: A (currently playing) leaves vicinity, B arrives.
getNearby.mockResolvedValueOnce([LISTENER_B])
await act(async () => {
await vi.advanceTimersByTimeAsync(15_000)
})
expect(screen.getByTestId('current-id').textContent).toBe('-5') // untouched, still playing
expect(screen.getByTestId('queue-ids').textContent).toBe('-5,-7') // preserved, then the arrival appended
// Poll 2: B (never played) leaves too; nobody nearby at all.
getNearby.mockResolvedValueOnce([])
await act(async () => {
await vi.advanceTimersByTimeAsync(15_000)
})
expect(screen.getByTestId('current-id').textContent).toBe('-5') // still untouched
expect(screen.getByTestId('queue-ids').textContent).toBe('-5') // B dropped immediately, A still preserved
} finally {
vi.useRealTimers()
}
})
})
......@@ -10,7 +10,7 @@ import {
stopSharingLiveLocation,
type LiveListener,
} from '../api/social'
import { usePlayer } from '../context/PlayerContext'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
type Status = 'idle' | 'locating' | 'ready' | 'error'
type NearbyListener = { listener: LiveListener; distance_km: number }
......@@ -59,7 +59,12 @@ export function GeoDrops() {
const sharingRef = useRef(false)
const positionRef = useRef<{ lat: number; lon: number } | null>(null)
const currentSongIdRef = useRef<number | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const [jointPlaylistMode, setJointPlaylistMode] = useState(false)
// Stable relative order of user_ids currently in the joint playlist - a still-nearby user
// keeps their spot instead of getting reshuffled on every 15s tick, only newly-arrived
// users get shuffled in and departed ones drop out.
const orderedUserIdsRef = useRef<number[]>([])
const { currentSong, isPlaying, isLoading: streamLoading, toggle, updateQueue } = usePlayer()
function refreshNearby(loc: { lat: number; lon: number }) {
getNearbyLiveListeners(loc.lat, loc.lon)
......@@ -70,7 +75,17 @@ export function GeoDrops() {
function pushPresence() {
const pos = positionRef.current
if (!pos) return
shareLiveLocation(pos.lat, pos.lon, currentSongIdRef.current).catch(() => {})
shareLiveLocation(pos.lat, pos.lon, currentSongIdRef.current).catch((err) => {
if (err instanceof ApiError && err.status === 403) {
// Sharing got turned off server-side (or was never turned on) - revert local state
// rather than silently retrying every heartbeat, and point at the actual fix instead
// of a generic error.
setSharing(false)
sharingRef.current = false
if (heartbeatRef.current) clearInterval(heartbeatRef.current)
setError('Enable location sharing in Settings before broadcasting your live location.')
}
})
}
function handlePosition(position: GeolocationPosition) {
......@@ -150,17 +165,61 @@ export function GeoDrops() {
stopSharingLiveLocation().catch(() => {})
} else {
setSharing(true)
setError(null)
pushPresence()
heartbeatRef.current = setInterval(pushPresence, HEARTBEAT_MS)
}
}
function playGeoPlaylist() {
const playable = shuffle(nearby.filter((n) => n.listener.song)).map((n) => toPlayable(n.listener))
if (playable.length === 0) return
toggle(playable[0], playable)
function toggleJointPlaylist() {
if (jointPlaylistMode) {
setJointPlaylistMode(false)
return
}
const withSongs = nearby.filter((n) => n.listener.song)
if (withSongs.length === 0) return
const order = shuffle(withSongs.map((n) => n.listener.user_id))
orderedUserIdsRef.current = order
const byId = new Map(withSongs.map((n) => [n.listener.user_id, n]))
const merged = order.map((id) => toPlayable(byId.get(id)!.listener))
setJointPlaylistMode(true)
toggle(merged[0], merged)
}
// Recomputes the joint playlist's queue every time `nearby` refreshes (the existing
// NEARBY_REFRESH_MS poll), via a stable merge: still-nearby users keep their relative order,
// newly-arrived ones get shuffled in, departed ones drop out - except the one currently
// playing, which stays until it naturally finishes (see the module-level comment below) so
// `next()` always has somewhere resolvable to advance to instead of silently stopping.
useEffect(() => {
if (!jointPlaylistMode) return
const withSongs = nearby.filter((n) => n.listener.song)
const byId = new Map(withSongs.map((n) => [n.listener.user_id, n]))
const stillNearby = orderedUserIdsRef.current.filter((id) => byId.has(id))
const arrivedIds = withSongs
.map((n) => n.listener.user_id)
.filter((id) => !orderedUserIdsRef.current.includes(id))
const newOrder = [...stillNearby, ...shuffle(arrivedIds)]
orderedUserIdsRef.current = newOrder
let merged: PlayableSong[] = newOrder.map((id) => toPlayable(byId.get(id)!.listener))
// PlayerContext's currentIndex is queue.findIndex(s => s.id === currentSong.id); if the
// currently-playing song's source user has left vicinity and we simply drop them, next()
// (fired by the audio's native `ended` event) finds currentIndex === -1 and - under the
// default "off" repeat mode - silently stops instead of advancing. Prepending it back in
// keeps currentIndex resolvable (always 0 here) so next() correctly moves on to the next
// legitimately-nearby track once this one naturally finishes; the following tick no longer
// re-adds it once it's no longer currentSong.
if (currentSong && !merged.some((s) => s.id === currentSong.id)) {
merged = [currentSong, ...merged]
}
updateQueue(merged)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [nearby, jointPlaylistMode])
useEffect(() => {
return () => {
if (watchIdRef.current !== null) navigator.geolocation?.clearWatch(watchIdRef.current)
......@@ -219,9 +278,15 @@ export function GeoDrops() {
<Radio size={16} strokeWidth={2} className={sharing ? 'text-primary' : ''} />
{sharing ? 'Stop sharing' : 'Share my live location'}
</Button>
<Button variant="secondary" onClick={playGeoPlaylist} disabled={!canPlayPlaylist} className="gap-1.5">
<Shuffle size={16} strokeWidth={2} />
Play my geo playlist
<Button
variant="secondary"
onClick={toggleJointPlaylist}
disabled={!jointPlaylistMode && !canPlayPlaylist}
aria-pressed={jointPlaylistMode}
className="gap-1.5"
>
<Shuffle size={16} strokeWidth={2} className={jointPlaylistMode ? 'text-primary' : ''} />
{jointPlaylistMode ? 'Stop joint playlist' : 'Play joint playlist'}
</Button>
</div>
{sharing && (
......
......@@ -45,7 +45,7 @@ describe('Login', () => {
refresh_token: 'real-refresh',
token_type: 'bearer',
})
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'alice', role: 'user' } })
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'alice', role: 'user', privacy: { share_location_enabled: false, allow_direct_messages: false } } })
renderLogin()
await userEvent.type(screen.getByLabelText('Username'), 'alice')
......@@ -76,7 +76,7 @@ describe('Login', () => {
})
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: 1, username: 'alice', role: 'business_admin' },
user: { id: 1, username: 'alice', role: 'business_admin', privacy: { share_location_enabled: false, allow_direct_messages: false } },
})
renderLogin([{ pathname: '/login', state: { from: { pathname: '/business' } } }])
......@@ -93,7 +93,7 @@ describe('Login', () => {
refresh_token: 'real-refresh',
token_type: 'bearer',
})
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 2, username: 'newuser', role: 'user' } })
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 2, username: 'newuser', role: 'user', privacy: { share_location_enabled: false, allow_direct_messages: false } } })
renderLogin()
await userEvent.click(screen.getByText("Don't have an account? Register"))
......
......@@ -7,6 +7,7 @@ import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as soundmarksApi from '../api/soundmarks'
import * as libraryApi from '../api/library'
import * as socialApi from '../api/social'
import { clearTokens } from '../api/client'
const FOUND_MARK: soundmarksApi.NearbySoundmark = {
......@@ -124,6 +125,17 @@ describe('Nearby', () => {
expect(soundmarksApi.getNearbySoundmarks).toHaveBeenCalledWith(37.7749, -122.4194)
})
it('fetches nearby live listeners alongside soundmarks, for the map presence markers', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
const getListeners = vi.spyOn(socialApi, 'getNearbyLiveListeners').mockResolvedValue([])
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
await waitFor(() => expect(getListeners).toHaveBeenCalledWith(37.7749, -122.4194))
})
it('plays the found anthem through the shared player when tapped', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] })
......
......@@ -16,10 +16,15 @@ import {
type NearbySoundmark,
type SoundmarkProposal,
} from '../api/soundmarks'
import { getNearbyLiveListeners, type LiveListener } from '../api/social'
import { usePlayer } from '../context/PlayerContext'
type Status = 'idle' | 'locating' | 'ready' | 'error'
// Matches GeoDrops.tsx's own cadence - keeps a listener's marker disappearing within one poll
// of them opting out, without needing a page reload.
const LISTENER_REFRESH_MS = 15_000
const TIER_LABEL: Record<NearbySoundmark['tier'], string> = {
major: 'Landmark',
business: 'Business',
......@@ -49,16 +54,24 @@ export function Nearby() {
const [showSongPicker, setShowSongPicker] = useState(false)
const [votingKey, setVotingKey] = useState<number | 'propose' | null>(null)
const [suggestionSent, setSuggestionSent] = useState(false)
const [listeners, setListeners] = useState<{ listener: LiveListener; distance_km: number }[]>([])
const watchIdRef = useRef<number | null>(null)
const listenerRefreshRef = useRef<ReturnType<typeof setInterval> | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
function refreshListeners(loc: { lat: number; lon: number }) {
getNearbyLiveListeners(loc.lat, loc.lon).then(setListeners).catch(() => {})
}
function handlePosition(position: GeolocationPosition) {
setStatus('ready')
setError(null)
setUserLocation({ lat: position.coords.latitude, lon: position.coords.longitude })
getNearbySoundmarks(position.coords.latitude, position.coords.longitude)
const loc = { lat: position.coords.latitude, lon: position.coords.longitude }
setUserLocation(loc)
getNearbySoundmarks(loc.lat, loc.lon)
.then((res) => setSoundmarks(res.soundmarks))
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to check nearby soundmarks'))
refreshListeners(loc)
}
function handlePositionError(err: GeolocationPositionError) {
......@@ -106,6 +119,22 @@ export function Nearby() {
}
}, [])
// Listener presence needs its own timer independent of watchPosition (which only fires on
// actual movement) - otherwise a listener opting out wouldn't disappear from the map until
// the viewer happened to move.
useEffect(() => {
if (listenerRefreshRef.current) clearInterval(listenerRefreshRef.current)
if (status === 'ready') {
listenerRefreshRef.current = setInterval(() => {
if (userLocation) refreshListeners(userLocation)
}, LISTENER_REFRESH_MS)
}
return () => {
if (listenerRefreshRef.current) clearInterval(listenerRefreshRef.current)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [status])
const closest = soundmarks[0]
const active = closest?.song ? toPlayable(closest as NearbySoundmark & { song: NonNullable<NearbySoundmark['song']> }) : null
const isCurrent = !!active && currentSong?.id === active.id
......@@ -212,7 +241,7 @@ export function Nearby() {
{userLocation && (status === 'ready' || status === 'locating') && (
<div className="mb-4">
<SoundmarkMap userLocation={userLocation} soundmarks={soundmarks} />
<SoundmarkMap userLocation={userLocation} soundmarks={soundmarks} listeners={listeners} />
</div>
)}
......
......@@ -45,6 +45,7 @@ const BACKEND_DONE: DoneGroup[] = [
'Username/password register, login, refresh (rotating), logout (real server-side revoke) - PBKDF2, stdlib only',
'Telegram phone/code account-linking (/auth/telegram/*), attaches to the already-authenticated caller (fixed 2026-08-18 - used to silently create a disconnected identity instead); handles accounts with two-step verification via a 412 + /auth/telegram/password step',
'Rate limited: login (10 attempts/account/15min, 100/source/hr), Telegram request_code (5/phone/10min, 20/IP/hr) - independent of each other despite sharing a table',
'Privacy settings (2026-09-13): two opt-in booleans on UserProfile (share_location_enabled, allow_direct_messages - both default False), surfaced on GET /auth/me and updated via PATCH /auth/privacy. UserProfile existed before this but had no reader/writer anywhere; _get_or_create_profile treats a missing row as "opted out," not an error, since that\'s the actual shape of every account that existed before these columns did.',
],
},
{
......@@ -60,6 +61,15 @@ const BACKEND_DONE: DoneGroup[] = [
'WebSocket: chat, reactions, DJ queue, pass-the-aux handoff, now-playing',
'Connection requires a verified access token, not a client-supplied user_id',
'Cross-user song streaming - a listener hears what the DJ actually picked',
'Chat is DB-backed now (2026-09-13, RoomMessage table), not a 50-message in-memory deque that used to be thrown away the instant a room\'s last connection dropped - a room emptying and refilling now still has its history. New GET /social/rooms/{id}/messages?before_id=&limit= for scrollback beyond the join snapshot\'s own cap. The websocket connection-registry logic (connect/disconnect/broadcast/presence) was extracted into a generic ConnectionManager (src/services/connection_manager.py) so Direct Messages below could reuse the exact same shape instead of a second hand-rolled implementation; RoomConnectionManager now delegates to it.',
],
},
{
area: 'Direct Messages',
items: [
'New (2026-09-13): 1-on-1 threads, gated by the recipient\'s allow_direct_messages flag - POST /dm/threads creates-or-reuses a canonicalized (min(id), max(id)) thread, 403s only on first contact (an existing thread survives the recipient later opting out, matching how every other app\'s "who can message me" toggle behaves - turning it off blocks new contact, not an already-consented-to conversation)',
'GET /dm/threads is filtered to threads the caller actually participates in - the single most important line in the feature; GET /dm/threads/{id}/messages and the WS both 403/4403 for a non-participant',
'WS /dm/threads/{id}/ws?token= mirrors the Rooms socket exactly (JWT-over-query-param, same ConnectionManager) rather than inventing a second transport',
],
},
{
......@@ -75,6 +85,7 @@ const BACKEND_DONE: DoneGroup[] = [
items: [
'Share / stop / distance-sorted nearby list / cross-user stream',
'Stale entries (>5min since last heartbeat) drop out of nearby results automatically',
'Opt-in gated (2026-09-13, closes a real privacy gap - LiveLocation rows were visible to any authenticated user with zero consent check before this): PUT /live-location 403s unless share_location_enabled is on (DELETE stays ungated, stopping must always work); /nearby and /{user_id}/stream both filtered through one shared _visible_live_locations_query outer-joined against UserProfile, so a row with no profile at all - the actual shape of every row that predates this feature - is excluded by default rather than erroring or defaulting to visible',
],
},
{
......@@ -173,8 +184,10 @@ const FRONTEND_DONE: DoneGroup[] = [
items: [
'Merged with Live Location under one nav destination (2026-08-23) - Map (curated/voted anthem tied to a fixed place) and Live (broadcast of wherever someone currently is) are related but distinct concepts, now reached via an in-page tab switcher instead of two separate top-level tabs',
'Map tab: dark-themed map, tier-aware display, proposals + voting UI',
'Live tab: share toggle, live nearby list, cross-account playback, geo-playlist shuffle-play',
'Live tab: share toggle, live nearby list, cross-account playback, joint playlist (below)',
"Admin location picker: locate-me button on the map itself - drops the pin at the browser's location and reverse-geocodes it into the address field, still fully correctable by search/click/drag afterward",
'Map tab shows live listener presence too now (2026-09-13): a distinct marker per nearby opted-in listener (username, current song or "not playing," a Message button that creates-or-opens a DM thread), refetched on its own 15s timer independent of watchPosition so a listener opting out disappears from the map without a reload. shareLiveLocation\'s new possible 403 (see the backend privacy gate) surfaces as a specific "enable location sharing in Settings" prompt on the Live tab instead of the generic error path.',
'"Play my geo playlist" evolved into a continuous "joint playlist" mode (2026-09-13): the one-shot shuffle-and-play button became a toggle that keeps the queue live on the existing 15s nearby-refresh - still-nearby listeners keep their relative order, new arrivals get shuffled in, departed ones drop out. Fixed a real correctness bug in the naive version before it shipped: PlayerContext\'s next() only advances when the current song is still in the queue, so simply dropping a departed user\'s song the instant they left vicinity would silently stop playback dead (under the default repeat-off mode) instead of finishing the track and moving on. Fix: the currently-playing song is prepended back into the merged queue if it would otherwise be dropped, so next() always has somewhere resolvable to go once it naturally finishes - PlayerContext gained a new updateQueue() for this (replaces the queue array without touching what\'s currently playing, unlike toggle/addToQueue).',
],
},
{
......@@ -184,6 +197,8 @@ const FRONTEND_DONE: DoneGroup[] = [
'Rooms: chat, reactions, DJ song picker, pass-the-aux controls, now-playing card (RoomView stays a genuinely full-screen experience, not wrapped in the app chrome)',
'Channels: list + follow/unfollow UI only - vibe sets/stories/showcase have no UI yet',
'Posts: feed, composer, recursive remix-tree view with "remix this" at every node',
'New "Messages" 4th tab (2026-09-13, DMInbox) for the new Direct Messages backend - a thread list (shown as "User #<id>", since threads carry only participant ids, not usernames) linking out to a real routed page at /dm/:threadId (DMThreadView, mirrors RoomView\'s header/scrollback/input shape) for the actual conversation. Room chat messages are now keyed by their real database id instead of array position, matching the backend\'s move off the old in-memory deque.',
'New minimal /settings page (2026-09-13): the two privacy toggles (share live location, allow direct messages), both off by default - kept out of Social.tsx since they\'re account-level, not social content.',
],
},
{
......
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 { Settings } from './Settings'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import { ApiError } from '../api/client'
import * as authApi from '../api/auth'
function renderSettings() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Settings />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Settings', () => {
beforeEach(() => {
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: {
id: 1,
username: 'me',
role: 'user',
privacy: { share_location_enabled: false, allow_direct_messages: false },
},
})
})
afterEach(() => {
vi.restoreAllMocks()
})
it('renders both toggles off by default', async () => {
renderSettings()
const locationToggle = await screen.findByRole('switch', { name: 'Share my live location' })
const dmToggle = screen.getByRole('switch', { name: 'Allow direct messages' })
expect(locationToggle).toHaveAttribute('aria-checked', 'false')
expect(dmToggle).toHaveAttribute('aria-checked', 'false')
})
it('turns a toggle on and saves it', async () => {
const update = vi.spyOn(authApi, 'updatePrivacy').mockResolvedValue({
status: 'success',
privacy: { share_location_enabled: true, allow_direct_messages: false },
})
renderSettings()
const locationToggle = await screen.findByRole('switch', { name: 'Share my live location' })
await userEvent.click(locationToggle)
await waitFor(() => expect(update).toHaveBeenCalledWith({ share_location_enabled: true }))
await waitFor(() => expect(locationToggle).toHaveAttribute('aria-checked', 'true'))
})
it('toggling one setting leaves the other untouched', async () => {
vi.spyOn(authApi, 'updatePrivacy').mockResolvedValue({
status: 'success',
privacy: { share_location_enabled: false, allow_direct_messages: true },
})
renderSettings()
const dmToggle = await screen.findByRole('switch', { name: 'Allow direct messages' })
await userEvent.click(dmToggle)
await waitFor(() => expect(dmToggle).toHaveAttribute('aria-checked', 'true'))
expect(screen.getByRole('switch', { name: 'Share my live location' })).toHaveAttribute('aria-checked', 'false')
})
it('shows an error message if saving fails', async () => {
vi.spyOn(authApi, 'updatePrivacy').mockRejectedValue(new ApiError(500, 'Failed to update setting', null))
renderSettings()
const locationToggle = await screen.findByRole('switch', { name: 'Share my live location' })
await userEvent.click(locationToggle)
expect(await screen.findByText('Failed to update setting')).toBeInTheDocument()
expect(locationToggle).toHaveAttribute('aria-checked', 'false')
})
})
import { useEffect, useState } from 'react'
import { MapPin, MessageCircle, type LucideIcon } from 'lucide-react'
import { Layout } from '../components/Layout'
import { ApiError } from '../api/client'
import { getMe, updatePrivacy, type PrivacySettings } from '../api/auth'
function ToggleRow({
icon: Icon,
label,
description,
checked,
saving,
onToggle,
}: {
icon: LucideIcon
label: string
description: string
checked: boolean
saving: boolean
onToggle: () => void
}) {
return (
<div className="flex items-center gap-3 rounded-xl border border-outline-variant bg-surface-container p-4">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-surface-container-high text-on-surface-variant">
<Icon size={16} strokeWidth={1.75} />
</span>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-on-surface">{label}</p>
<p className="text-xs text-on-surface-variant">{description}</p>
</div>
<button
role="switch"
aria-checked={checked}
aria-label={label}
disabled={saving}
onClick={onToggle}
className={`relative h-6 w-11 shrink-0 rounded-full transition-colors disabled:opacity-50 ${
checked ? 'bg-primary' : 'bg-surface-container-high'
}`}
>
<span
className={`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${
checked ? 'translate-x-[22px]' : 'translate-x-0.5'
}`}
/>
</button>
</div>
)
}
/** Both privacy toggles are account-level, not "social content," so they get their own minimal
* page rather than living inside Social.tsx. Both default off (opt-in) - see PrivacySettings. */
export function Settings() {
const [privacy, setPrivacy] = useState<PrivacySettings | null>(null)
const [error, setError] = useState<string | null>(null)
const [savingKey, setSavingKey] = useState<keyof PrivacySettings | null>(null)
useEffect(() => {
getMe()
.then((res) => setPrivacy(res.user.privacy))
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to load settings'))
}, [])
async function handleToggle(key: keyof PrivacySettings) {
if (!privacy) return
const next = !privacy[key]
setSavingKey(key)
setError(null)
try {
const res = await updatePrivacy({ [key]: next })
setPrivacy(res.privacy)
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to update setting')
} finally {
setSavingKey(null)
}
}
return (
<Layout title="Settings">
<p className="mb-6 text-sm leading-relaxed text-on-surface-variant">
Both of these are off by default - turn them on if you want other Stax users to see you or message you.
</p>
{error && <p className="mb-4 text-sm text-error">{error}</p>}
{privacy && (
<div className="space-y-3">
<ToggleRow
icon={MapPin}
label="Share my live location"
description="Let nearby users see your location and what you're playing on Soundmarks."
checked={privacy.share_location_enabled}
saving={savingKey === 'share_location_enabled'}
onToggle={() => handleToggle('share_location_enabled')}
/>
<ToggleRow
icon={MessageCircle}
label="Allow direct messages"
description="Let other users start a direct message conversation with you."
checked={privacy.allow_direct_messages}
saving={savingKey === 'allow_direct_messages'}
onToggle={() => handleToggle('allow_direct_messages')}
/>
</div>
)}
</Layout>
)
}
import { useState } from 'react'
import { Disc3, Radio, Rss } from 'lucide-react'
import { Disc3, MessageCircle, Radio, Rss } from 'lucide-react'
import { Layout } from '../components/Layout'
import { Rooms } from './Rooms'
import { Channels } from './Channels'
import { Posts } from './Posts'
import { DMInbox } from '../components/DMInbox'
type Tab = 'rooms' | 'channels' | 'posts'
type Tab = 'rooms' | 'channels' | 'posts' | 'messages'
const TABS: { id: Tab; label: string; icon: typeof Radio }[] = [
{ id: 'rooms', label: 'Rooms', icon: Radio },
{ id: 'channels', label: 'Channels', icon: Rss },
{ id: 'posts', label: 'Posts', icon: Disc3 },
{ id: 'messages', label: 'Messages', icon: MessageCircle },
]
/** Every socially-driven feature (live listening rooms, creator channels, the post/remix
......@@ -48,6 +50,7 @@ export function Social() {
{tab === 'rooms' && <Rooms />}
{tab === 'channels' && <Channels />}
{tab === 'posts' && <Posts />}
{tab === 'messages' && <DMInbox />}
</div>
</Layout>
)
......
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