Commit 39411c79 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add admin account moderation UI and global search on Home

AdminPanel's Users tab gains a search box and a per-user Manage panel
(rename, deactivate/reactivate, suspend/unsuspend, reset password),
wired to the new backend endpoints.

Home gains a search box at the top that reuses the existing shared-
library search (same one Library's "Shared" scope already calls) -
while a query is active it replaces the feed sections with results,
reusing the existing HomeSongRow/claim-then-act flow unchanged.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 18253e9a
...@@ -122,10 +122,15 @@ export interface AdminUser { ...@@ -122,10 +122,15 @@ export interface AdminUser {
username: string | null username: string | null
phone_number: string | null phone_number: string | null
role: 'user' | 'business_admin' | 'super_admin' role: 'user' | 'business_admin' | 'super_admin'
is_active: boolean
suspended_until: string | null
} }
export function listUsers(role?: string) { export function listUsers(opts?: { role?: string; q?: string }) {
const suffix = role ? `?${new URLSearchParams({ role })}` : '' const params = new URLSearchParams()
if (opts?.role) params.set('role', opts.role)
if (opts?.q) params.set('q', opts.q)
const suffix = params.toString() ? `?${params}` : ''
return apiFetch<{ status: string; users: AdminUser[] }>(`/soundmarks/admin/users${suffix}`) return apiFetch<{ status: string; users: AdminUser[] }>(`/soundmarks/admin/users${suffix}`)
} }
...@@ -136,6 +141,22 @@ export function updateUserRole(userId: number, role: string) { ...@@ -136,6 +141,22 @@ export function updateUserRole(userId: number, role: string) {
) )
} }
/** Partial update - omit whichever fields aren't being changed. suspendHours: a positive
* number suspends until that many hours from now, 0 clears any existing suspension. */
export function editUser(userId: number, body: { username?: string; is_active?: boolean; suspend_hours?: number }) {
return apiFetch<{ status: string; user: AdminUser }>(`/soundmarks/admin/users/${userId}`, {
method: 'PATCH',
json: body,
})
}
export function resetUserPassword(userId: number, newPassword: string) {
return apiFetch<{ status: string }>(`/soundmarks/admin/users/${userId}/reset-password`, {
method: 'POST',
json: { new_password: newPassword },
})
}
/** For PlayerContext's `streamUrl` override - a direct, token-authenticated URL for a /** For PlayerContext's `streamUrl` override - a direct, token-authenticated URL for a
* soundmark's anthem (streamable regardless of who uploaded the underlying song), mirroring * soundmark's anthem (streamable regardless of who uploaded the underlying song), mirroring
* api/stream.ts's fetchStreamUrl but against the soundmark-specific endpoint. See * api/stream.ts's fetchStreamUrl but against the soundmark-specific endpoint. See
......
...@@ -36,7 +36,7 @@ const LANDMARK: soundmarksApi.Soundmark = { ...@@ -36,7 +36,7 @@ const LANDMARK: soundmarksApi.Soundmark = {
updated_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
} }
const BUSINESS_OWNER: soundmarksApi.AdminUser = { id: 5, username: 'joe', phone_number: '+15559999', role: 'business_admin' } const BUSINESS_OWNER: soundmarksApi.AdminUser = { id: 5, username: 'joe', phone_number: '+15559999', role: 'business_admin', is_active: true, suspended_until: null }
const BUSINESS: soundmarksApi.Soundmark = { const BUSINESS: soundmarksApi.Soundmark = {
...LANDMARK, ...LANDMARK,
...@@ -60,7 +60,7 @@ const SUGGESTION: soundmarksApi.SoundmarkSuggestion = { ...@@ -60,7 +60,7 @@ const SUGGESTION: soundmarksApi.SoundmarkSuggestion = {
created_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
} }
const PLAIN_USER: soundmarksApi.AdminUser = { id: 7, username: 'alex', phone_number: '+15551234', role: 'user' } const PLAIN_USER: soundmarksApi.AdminUser = { id: 7, username: 'alex', phone_number: '+15551234', role: 'user', is_active: true, suspended_until: null }
function mockEmptyQueue() { function mockEmptyQueue() {
return vi.spyOn(soundmarksApi, 'getReviewQueue').mockResolvedValue({ status: 'success', suggestions: [] }) return vi.spyOn(soundmarksApi, 'getReviewQueue').mockResolvedValue({ status: 'success', suggestions: [] })
...@@ -200,6 +200,125 @@ describe('AdminPanel', () => { ...@@ -200,6 +200,125 @@ describe('AdminPanel', () => {
}) })
}) })
it('searches users by username', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
const listUsers = vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.type(screen.getByRole('textbox', { name: 'Search users' }), 'ale')
await waitFor(() => {
expect(listUsers).toHaveBeenCalledWith({ q: 'ale' })
})
})
it('renames a user from the Manage panel', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const editUser = vi.spyOn(soundmarksApi, 'editUser').mockResolvedValue({
status: 'success',
user: { ...PLAIN_USER, username: 'alexrenamed' },
})
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.click(screen.getByRole('button', { name: 'Manage' }))
const usernameField = screen.getByLabelText('Username')
await userEvent.clear(usernameField)
await userEvent.type(usernameField, 'alexrenamed')
await userEvent.click(screen.getByRole('button', { name: 'Rename' }))
await waitFor(() => {
expect(editUser).toHaveBeenCalledWith(PLAIN_USER.id, { username: 'alexrenamed' })
})
await screen.findByText('alexrenamed')
})
it('deactivates a user after confirming', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const editUser = vi.spyOn(soundmarksApi, 'editUser').mockResolvedValue({
status: 'success',
user: { ...PLAIN_USER, is_active: false },
})
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.click(screen.getByRole('button', { name: 'Manage' }))
await userEvent.click(screen.getByRole('button', { name: 'Deactivate account' }))
await waitFor(() => {
expect(editUser).toHaveBeenCalledWith(PLAIN_USER.id, { is_active: false })
})
await screen.findByText('deactivated')
})
it('does not deactivate when the confirmation is declined', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const editUser = vi.spyOn(soundmarksApi, 'editUser')
vi.spyOn(window, 'confirm').mockReturnValue(false)
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.click(screen.getByRole('button', { name: 'Manage' }))
await userEvent.click(screen.getByRole('button', { name: 'Deactivate account' }))
expect(editUser).not.toHaveBeenCalled()
})
it('suspends a user for a given number of hours', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const futureIso = new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString()
const editUser = vi.spyOn(soundmarksApi, 'editUser').mockResolvedValue({
status: 'success',
user: { ...PLAIN_USER, suspended_until: futureIso },
})
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.click(screen.getByRole('button', { name: 'Manage' }))
await userEvent.click(screen.getByRole('button', { name: 'Suspend' }))
await waitFor(() => {
expect(editUser).toHaveBeenCalledWith(PLAIN_USER.id, { suspend_hours: 24 })
})
await screen.findByText('suspended')
})
it('resets a users password from the Manage panel', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
mockEmptyQueue()
const resetPassword = vi.spyOn(soundmarksApi, 'resetUserPassword').mockResolvedValue({ status: 'success' })
renderPanel()
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.click(screen.getByRole('button', { name: 'Manage' }))
await userEvent.type(screen.getByLabelText('New password'), 'brandnewpassword')
await userEvent.click(screen.getByRole('button', { name: 'Reset password' }))
await waitFor(() => {
expect(resetPassword).toHaveBeenCalledWith(PLAIN_USER.id, 'brandnewpassword')
})
})
it('sets an anthem on a major-tier soundmark by picking from the public library', async () => { it('sets an anthem on a major-tier soundmark by picking from the public library', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] }) vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] }) vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
......
...@@ -13,11 +13,13 @@ import { ...@@ -13,11 +13,13 @@ import {
approveSuggestion, approveSuggestion,
createSoundmark, createSoundmark,
deleteSoundmark, deleteSoundmark,
editUser,
getAllSoundmarks, getAllSoundmarks,
getReviewQueue, getReviewQueue,
listUsers, listUsers,
rejectSuggestion, rejectSuggestion,
removePlaylistTrack, removePlaylistTrack,
resetUserPassword,
setSoundmarkSong, setSoundmarkSong,
updateSoundmark, updateSoundmark,
updateUserRole, updateUserRole,
...@@ -476,46 +478,217 @@ function ReviewQueueSection({ ...@@ -476,46 +478,217 @@ function ReviewQueueSection({
) )
} }
function UserManageForm({
user,
savingKey,
onRename,
onToggleActive,
onSuspend,
onClearSuspension,
onResetPassword,
}: {
user: AdminUser
savingKey: string | null
onRename: (username: string) => void
onToggleActive: (isActive: boolean) => void
onSuspend: (hours: number) => void
onClearSuspension: () => void
onResetPassword: (newPassword: string) => void
}) {
const [username, setUsername] = useState(user.username ?? '')
const [suspendHours, setSuspendHours] = useState('24')
const [newPassword, setNewPassword] = useState('')
const isSuspended = !!user.suspended_until && new Date(user.suspended_until) > new Date()
const busy = (suffix: string) => savingKey === `${suffix}-${user.id}`
return (
<div className="space-y-3 border-t border-outline-variant/60 bg-surface-container-low px-1 py-3">
<div className="flex items-end gap-2">
<div className="flex-1">
<label className="mb-1 block text-xs text-outline" htmlFor={`rename-${user.id}`}>
Username
</label>
<Input id={`rename-${user.id}`} value={username} onChange={(e) => setUsername(e.target.value)} />
</div>
<Button
variant="secondary"
disabled={busy('rename') || !username.trim() || username === user.username}
onClick={() => onRename(username.trim())}
>
Rename
</Button>
</div>
<div className="flex flex-wrap items-center gap-2">
{user.is_active ? (
<Button variant="secondary" disabled={busy('active')} onClick={() => onToggleActive(false)}>
Deactivate account
</Button>
) : (
<Button variant="secondary" disabled={busy('active')} onClick={() => onToggleActive(true)}>
Reactivate account
</Button>
)}
<span className={`text-xs ${user.is_active ? 'text-outline' : 'text-error'}`}>
{user.is_active ? 'Active' : 'Deactivated'}
</span>
</div>
<div className="flex flex-wrap items-end gap-2">
<div>
<label className="mb-1 block text-xs text-outline" htmlFor={`suspend-${user.id}`}>
Suspend for (hours)
</label>
<Input
id={`suspend-${user.id}`}
type="number"
min="0.5"
step="0.5"
value={suspendHours}
onChange={(e) => setSuspendHours(e.target.value)}
className="w-24"
/>
</div>
<Button
variant="secondary"
disabled={busy('suspend') || !Number(suspendHours) || Number(suspendHours) <= 0}
onClick={() => onSuspend(Number(suspendHours))}
>
Suspend
</Button>
{isSuspended && (
<Button variant="secondary" disabled={busy('suspend')} onClick={onClearSuspension}>
Clear suspension
</Button>
)}
{isSuspended && user.suspended_until && (
<span className="text-xs text-error">Suspended until {new Date(user.suspended_until).toLocaleString()}</span>
)}
</div>
<div className="flex items-end gap-2">
<div className="flex-1">
<label className="mb-1 block text-xs text-outline" htmlFor={`password-${user.id}`}>
New password
</label>
<Input
id={`password-${user.id}`}
type="password"
placeholder="At least 8 characters"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
/>
</div>
<Button
variant="secondary"
disabled={busy('password') || newPassword.length < 8}
onClick={() => {
onResetPassword(newPassword)
setNewPassword('')
}}
>
Reset password
</Button>
</div>
</div>
)
}
function UsersSection({ function UsersSection({
users, users,
loading, loading,
savingKey, savingKey,
query,
onQueryChange,
expandedUserId,
onToggleExpanded,
onRoleChange, onRoleChange,
onRename,
onToggleActive,
onSuspend,
onClearSuspension,
onResetPassword,
}: { }: {
users: AdminUser[] users: AdminUser[]
loading: boolean loading: boolean
savingKey: string | null savingKey: string | null
query: string
onQueryChange: (q: string) => void
expandedUserId: number | null
onToggleExpanded: (userId: number) => void
onRoleChange: (userId: number, role: string) => void onRoleChange: (userId: number, role: string) => void
onRename: (userId: number, username: string) => void
onToggleActive: (userId: number, isActive: boolean) => void
onSuspend: (userId: number, hours: number) => void
onClearSuspension: (userId: number) => void
onResetPassword: (userId: number, newPassword: string) => void
}) { }) {
return ( return (
<> <>
<div className="px-1 pb-2 pt-3">
<Input
value={query}
onChange={(e) => onQueryChange(e.target.value)}
placeholder="Search by username"
aria-label="Search users"
/>
</div>
{loading && ( {loading && (
<div className="divide-y divide-outline-variant/80"> <div className="divide-y divide-outline-variant/80">
<SkeletonRow /> <SkeletonRow />
<SkeletonRow /> <SkeletonRow />
</div> </div>
)} )}
{!loading && users.length === 0 && <EmptyState icon={MapPin} message="No users yet." />} {!loading && users.length === 0 && <EmptyState icon={MapPin} message="No users found." />}
<ul className="divide-y divide-outline-variant/80"> <ul className="divide-y divide-outline-variant/80">
{users.map((u) => ( {users.map((u) => {
<li key={u.id} className="flex items-center justify-between gap-3 py-3"> const label = u.username ?? `User #${u.id}`
<div className="min-w-0"> const isSuspended = !!u.suspended_until && new Date(u.suspended_until) > new Date()
<p className="truncate font-medium text-on-surface">{u.username ?? `User #${u.id}`}</p> return (
<li key={u.id}>
<div className="flex items-center justify-between gap-3 py-3">
<button
type="button"
onClick={() => onToggleExpanded(u.id)}
className="min-w-0 flex-1 text-left"
aria-expanded={expandedUserId === u.id}
>
<p className="truncate font-medium text-on-surface">
{label}
{!u.is_active && <span className="ml-2 text-xs font-normal text-error">deactivated</span>}
{u.is_active && isSuspended && <span className="ml-2 text-xs font-normal text-error">suspended</span>}
</p>
<p className="truncate text-xs text-outline">{u.phone_number ?? '—'}</p> <p className="truncate text-xs text-outline">{u.phone_number ?? '—'}</p>
</div> </button>
<select <select
value={u.role} value={u.role}
onChange={(e) => onRoleChange(u.id, e.target.value)} onChange={(e) => onRoleChange(u.id, e.target.value)}
disabled={savingKey === `role-${u.id}`} disabled={savingKey === `role-${u.id}`}
aria-label={`Role for ${u.username ?? `User #${u.id}`}`} aria-label={`Role for ${label}`}
className="min-h-[38px] shrink-0 rounded-lg border border-outline-variant bg-surface-container-high px-2.5 text-sm text-on-surface outline-none transition-colors focus:border-primary" className="min-h-[38px] shrink-0 rounded-lg border border-outline-variant bg-surface-container-high px-2.5 text-sm text-on-surface outline-none transition-colors focus:border-primary"
> >
<option value="user">user</option> <option value="user">user</option>
<option value="business_admin">business_admin</option> <option value="business_admin">business_admin</option>
<option value="super_admin">super_admin</option> <option value="super_admin">super_admin</option>
</select> </select>
<Button variant="secondary" onClick={() => onToggleExpanded(u.id)}>
{expandedUserId === u.id ? 'Close' : 'Manage'}
</Button>
</div>
{expandedUserId === u.id && (
<UserManageForm
user={u}
savingKey={savingKey}
onRename={(username) => onRename(u.id, username)}
onToggleActive={(isActive) => onToggleActive(u.id, isActive)}
onSuspend={(hours) => onSuspend(u.id, hours)}
onClearSuspension={() => onClearSuspension(u.id)}
onResetPassword={(newPassword) => onResetPassword(u.id, newPassword)}
/>
)}
</li> </li>
))} )
})}
</ul> </ul>
</> </>
) )
...@@ -533,6 +706,8 @@ export function AdminPanel() { ...@@ -533,6 +706,8 @@ export function AdminPanel() {
const [playlistFor, setPlaylistFor] = useState<number | null>(null) const [playlistFor, setPlaylistFor] = useState<number | null>(null)
const [savingKey, setSavingKey] = useState<string | null>(null) const [savingKey, setSavingKey] = useState<string | null>(null)
const [submittingForm, setSubmittingForm] = useState(false) const [submittingForm, setSubmittingForm] = useState(false)
const [userQuery, setUserQuery] = useState('')
const [expandedUserId, setExpandedUserId] = useState<number | null>(null)
function loadAll() { function loadAll() {
setLoading(true) setLoading(true)
...@@ -548,6 +723,19 @@ export function AdminPanel() { ...@@ -548,6 +723,19 @@ export function AdminPanel() {
useEffect(loadAll, []) useEffect(loadAll, [])
// Debounced so typing doesn't fire a request per keystroke - same 400ms idiom Library.tsx's
// own search uses. Only active once the Users tab has been opened at least once; re-runs on
// every keystroke change to userQuery, cleaning up the pending timeout on the next one.
useEffect(() => {
if (section !== 'users') return
const t = setTimeout(() => {
listUsers({ q: userQuery || undefined })
.then((res) => setUsers(res.users))
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to search users'))
}, 400)
return () => clearTimeout(t)
}, [userQuery, section])
async function handleFormSubmit(values: SoundmarkFormValues) { async function handleFormSubmit(values: SoundmarkFormValues) {
if (values.latitude === null || values.longitude === null) { if (values.latitude === null || values.longitude === null) {
setError('Pick a location on the map before saving.') setError('Pick a location on the map before saving.')
...@@ -663,6 +851,73 @@ export function AdminPanel() { ...@@ -663,6 +851,73 @@ export function AdminPanel() {
} }
} }
async function handleRenameUser(userId: number, username: string) {
setSavingKey(`rename-${userId}`)
setError(null)
try {
const res = await editUser(userId, { username })
setUsers((prev) => prev.map((u) => (u.id === userId ? res.user : u)))
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to rename user')
} finally {
setSavingKey(null)
}
}
async function handleToggleActive(userId: number, isActive: boolean) {
if (!isActive && !window.confirm('Deactivate this account? They will be signed out immediately and unable to log back in until reactivated.')) {
return
}
setSavingKey(`active-${userId}`)
setError(null)
try {
const res = await editUser(userId, { is_active: isActive })
setUsers((prev) => prev.map((u) => (u.id === userId ? res.user : u)))
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to update account status')
} finally {
setSavingKey(null)
}
}
async function handleSuspend(userId: number, hours: number) {
setSavingKey(`suspend-${userId}`)
setError(null)
try {
const res = await editUser(userId, { suspend_hours: hours })
setUsers((prev) => prev.map((u) => (u.id === userId ? res.user : u)))
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to suspend user')
} finally {
setSavingKey(null)
}
}
async function handleClearSuspension(userId: number) {
setSavingKey(`suspend-${userId}`)
setError(null)
try {
const res = await editUser(userId, { suspend_hours: 0 })
setUsers((prev) => prev.map((u) => (u.id === userId ? res.user : u)))
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to clear suspension')
} finally {
setSavingKey(null)
}
}
async function handleResetPassword(userId: number, newPassword: string) {
setSavingKey(`password-${userId}`)
setError(null)
try {
await resetUserPassword(userId, newPassword)
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to reset password')
} finally {
setSavingKey(null)
}
}
async function handleReview(suggestion: SoundmarkSuggestion, decision: 'approve' | 'reject') { async function handleReview(suggestion: SoundmarkSuggestion, decision: 'approve' | 'reject') {
setSavingKey(`review-${suggestion.id}`) setSavingKey(`review-${suggestion.id}`)
try { try {
...@@ -729,7 +984,21 @@ export function AdminPanel() { ...@@ -729,7 +984,21 @@ export function AdminPanel() {
)} )}
{section === 'users' && ( {section === 'users' && (
<UsersSection users={users} loading={loading} savingKey={savingKey} onRoleChange={handleRoleChange} /> <UsersSection
users={users}
loading={loading}
savingKey={savingKey}
query={userQuery}
onQueryChange={setUserQuery}
expandedUserId={expandedUserId}
onToggleExpanded={(userId) => setExpandedUserId((prev) => (prev === userId ? null : userId))}
onRoleChange={handleRoleChange}
onRename={handleRenameUser}
onToggleActive={handleToggleActive}
onSuspend={handleSuspend}
onClearSuspension={handleClearSuspension}
onResetPassword={handleResetPassword}
/>
)} )}
</div> </div>
......
...@@ -136,6 +136,63 @@ describe('Home', () => { ...@@ -136,6 +136,63 @@ describe('Home', () => {
expect(screen.queryByText(/stranger/)).not.toBeInTheDocument() expect(screen.queryByText(/stranger/)).not.toBeInTheDocument()
}) })
it('searches the shared library and replaces the feed with results', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({
status: 'success',
latest_songs: [OWN_SONG],
new_albums: [],
suggestions: [],
})
const search = vi.spyOn(libraryApi, 'searchSharedLibrary').mockResolvedValue({
status: 'success',
songs: [{ ...OTHER_SONG, lyrics: null, file_path: '/tmp/fake.mp3' }],
})
renderHome()
await screen.findByText('My Own Track')
await userEvent.type(screen.getByRole('textbox', { name: 'Search all of Stax' }), 'else')
await waitFor(() => {
expect(search).toHaveBeenCalledWith('else')
})
expect(await screen.findByText("Someone Else's Track")).toBeInTheDocument()
// The normal feed sections are replaced while a search is active, not just supplemented.
expect(screen.queryByText('My Own Track')).not.toBeInTheDocument()
expect(screen.queryByText('New Songs')).not.toBeInTheDocument()
})
it('shows an empty state when a search finds nothing', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [OWN_SONG], new_albums: [], suggestions: [] })
vi.spyOn(libraryApi, 'searchSharedLibrary').mockResolvedValue({ status: 'success', songs: [] })
renderHome()
await screen.findByText('My Own Track')
await userEvent.type(screen.getByRole('textbox', { name: 'Search all of Stax' }), 'nothing here')
expect(await screen.findByText(/No songs found for "nothing here"/)).toBeInTheDocument()
})
it('restores the normal feed once the search query is cleared', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [OWN_SONG], new_albums: [], suggestions: [] })
vi.spyOn(libraryApi, 'searchSharedLibrary').mockResolvedValue({
status: 'success',
songs: [{ ...OTHER_SONG, lyrics: null, file_path: '/tmp/fake.mp3' }],
})
renderHome()
await screen.findByText('My Own Track')
const input = screen.getByRole('textbox', { name: 'Search all of Stax' })
await userEvent.type(input, 'else')
await screen.findByText("Someone Else's Track")
await userEvent.clear(input)
expect(await screen.findByText('My Own Track')).toBeInTheDocument()
expect(screen.queryByText("Someone Else's Track")).not.toBeInTheDocument()
})
it('plays a song the caller already owns directly, without claiming it first', async () => { it('plays a song the caller already owns directly, without claiming it first', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [OWN_SONG], new_albums: [], suggestions: [] }) vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [OWN_SONG], new_albums: [], suggestions: [] })
const claimSharedSong = vi.spyOn(libraryApi, 'claimSharedSong') const claimSharedSong = vi.spyOn(libraryApi, 'claimSharedSong')
......
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { Disc3, Globe, ListMusic, Sparkles, type LucideIcon } from 'lucide-react' import { Disc3, Globe, ListMusic, Search, Sparkles, type LucideIcon } from 'lucide-react'
import { getHomeFeed, type HomeAlbum, type HomeSong } from '../api/home' import { getHomeFeed, type HomeAlbum, type HomeSong } from '../api/home'
import { searchSharedLibrary } from '../api/library'
import { ApiError } from '../api/client' import { ApiError } from '../api/client'
import { Layout } from '../components/Layout' import { Layout } from '../components/Layout'
import { Input } from '../components/ui/Input'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal' import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
import { HomeAlbumCard } from '../components/HomeAlbumCard' import { HomeAlbumCard } from '../components/HomeAlbumCard'
import { HomeSongRow } from '../components/HomeSongRow' import { HomeSongRow } from '../components/HomeSongRow'
...@@ -35,6 +37,9 @@ export function Home() { ...@@ -35,6 +37,9 @@ export function Home() {
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [addingSong, setAddingSong] = useState<{ id: number; title: string } | null>(null) const [addingSong, setAddingSong] = useState<{ id: number; title: string } | null>(null)
const [query, setQuery] = useState('')
const [searchResults, setSearchResults] = useState<HomeSong[] | null>(null)
const [searching, setSearching] = useState(false)
useEffect(() => { useEffect(() => {
getHomeFeed() getHomeFeed()
...@@ -47,10 +52,63 @@ export function Home() { ...@@ -47,10 +52,63 @@ export function Home() {
.finally(() => setLoading(false)) .finally(() => setLoading(false))
}, []) }, [])
// Global search across every user's library (the same pool Home's own feed sections draw
// from), not the caller's own - searchSharedLibrary already excludes anything the caller has
// a copy of, so every result here always goes through HomeSongRow's claim-then-act path via
// useHomeSongPlayback. 400ms debounce, same idiom Library.tsx's own search uses.
const isSearching = query.trim().length > 0
useEffect(() => {
if (!query.trim()) {
setSearchResults(null)
return
}
setSearching(true)
const handle = setTimeout(() => {
searchSharedLibrary(query.trim())
.then((res) => setSearchResults(res.songs))
.catch(() => setSearchResults([]))
.finally(() => setSearching(false))
}, 400)
return () => clearTimeout(handle)
}, [query])
const isEmpty = !loading && !error && latestSongs.length === 0 && newAlbums.length === 0 && suggestions.length === 0 const isEmpty = !loading && !error && latestSongs.length === 0 && newAlbums.length === 0 && suggestions.length === 0
return ( return (
<Layout title="Home"> <Layout title="Home">
<div className="relative mb-6">
<Search size={16} strokeWidth={2} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-on-surface-variant" />
<Input
placeholder="Search all of Stax"
value={query}
onChange={(e) => setQuery(e.target.value)}
className="pl-9"
aria-label="Search all of Stax"
/>
</div>
{isSearching ? (
<div className="animate-content-enter">
{searching && (
<div className="space-y-1">
<SkeletonRow />
<SkeletonRow />
<SkeletonRow />
</div>
)}
{!searching && searchResults && searchResults.length === 0 && (
<EmptyState icon={Search} message={`No songs found for "${query.trim()}".`} />
)}
{!searching && searchResults && searchResults.length > 0 && (
<ul className="space-y-1">
{searchResults.map((song) => (
<HomeSongRow key={song.id} song={song} onAddToPlaylist={setAddingSong} />
))}
</ul>
)}
</div>
) : (
<>
{loading && ( {loading && (
<div className="space-y-1"> <div className="space-y-1">
<SkeletonRow /> <SkeletonRow />
...@@ -105,6 +163,8 @@ export function Home() { ...@@ -105,6 +163,8 @@ export function Home() {
)} )}
</div> </div>
)} )}
</>
)}
{addingSong && <AddToPlaylistModal song={addingSong} onClose={() => setAddingSong(null)} />} {addingSong && <AddToPlaylistModal song={addingSong} onClose={() => setAddingSong(null)} />}
</Layout> </Layout>
......
...@@ -47,6 +47,8 @@ const BACKEND_DONE: DoneGroup[] = [ ...@@ -47,6 +47,8 @@ const BACKEND_DONE: DoneGroup[] = [
'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', '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.', '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.',
'User.has_completed_onboarding (2026-10-08), the signal behind the new first-run walkthrough below - register and login previously returned byte-identical responses, so nothing could tell "brand new account" from "used this for months." server_default=true backfills every existing/historical row (and anything inserted outside /auth/register, including test fixtures) as already-onboarded; only the register handler explicitly passes False for a genuinely new account. New POST /auth/onboarding/complete (idempotent) flips it; GET /auth/me returns the current value.', 'User.has_completed_onboarding (2026-10-08), the signal behind the new first-run walkthrough below - register and login previously returned byte-identical responses, so nothing could tell "brand new account" from "used this for months." server_default=true backfills every existing/historical row (and anything inserted outside /auth/register, including test fixtures) as already-onboarded; only the register handler explicitly passes False for a genuinely new account. New POST /auth/onboarding/complete (idempotent) flips it; GET /auth/me returns the current value.',
'Admin account moderation (2026-10-10): new User.is_active (server_default=true) and suspended_until columns - a deliberate soft-delete design, not a real row delete, since none of the 20+ FK columns across the schema (library songs, playlists, posts, DM threads, remix jobs, soundmarks a business admin manages, etc.) have cascade/ondelete configured, so hard-deleting a User row would leave every one of them dangling. New check_account_usable() (security.py) enforces both the permanent and time-boxed lock, called from every place identity is resolved - /auth/login, /auth/refresh, get_current_user, get_current_user_for_stream, and the websocket token resolver - not just at login, so an admin deactivating or suspending someone takes effect immediately against any already-issued access token, not only on their next sign-in. Checked only after a correct password is confirmed, so a wrong-password attempt against a locked account still gets the generic "invalid username or password" rather than leaking the account\'s lock status to someone who doesn\'t actually have the password.',
'Admin user management endpoints (2026-10-10), extending the existing super-admin-only list/role endpoints in soundmarks.py rather than a new router: GET /soundmarks/admin/users gained an optional q substring filter on username; new PATCH /soundmarks/admin/users/{id} covers rename (with a uniqueness check), deactivate/reactivate, and suspend/unsuspend (a suspend_hours field - positive sets suspended_until that many hours out, 0 clears it) in one endpoint; new POST .../reset-password sets a new password hash directly, bypassing the old one, for support/account-recovery requests.',
], ],
}, },
{ {
...@@ -121,6 +123,7 @@ const BACKEND_DONE: DoneGroup[] = [ ...@@ -121,6 +123,7 @@ const BACKEND_DONE: DoneGroup[] = [
'Library-sourced only now, not raw uploads - skips a fresh identify_audio() call and feeds the already-known title/artist/genre into the planning prompt instead', 'Library-sourced only now, not raw uploads - skips a fresh identify_audio() call and feeds the already-known title/artist/genre into the planning prompt instead',
'Finished remix is library-only, not directly downloadable (2026-08-23) - also closed a real access-control gap: the old download_url pointed at the unauthenticated /downloads static mount with no ownership check at all', 'Finished remix is library-only, not directly downloadable (2026-08-23) - also closed a real access-control gap: the old download_url pointed at the unauthenticated /downloads static mount with no ownership check at all',
'Rate limited: 5 jobs/user/hour (2026-08-28) - the one genuinely expensive endpoint (real Gemini spend + minutes of CPU-bound Demucs per call) that had no throttling at all; reuses RemixJob.created_at as its own counter rather than a separate table, since an accepted request always leaves exactly one row', 'Rate limited: 5 jobs/user/hour (2026-08-28) - the one genuinely expensive endpoint (real Gemini spend + minutes of CPU-bound Demucs per call) that had no throttling at all; reuses RemixJob.created_at as its own counter rather than a separate table, since an accepted request always leaves exactly one row',
'Shelved until after beta launch (2026-10-10, explicit product decision - not a bug, not removed): new REMIX_ENABLED config flag (src/core/config.py, env-driven, off unless explicitly set) gates both POST /remix and GET /remix/{job_id} with a 403 "coming soon" response - mirrors the frontend\'s own pre-existing VITE_ENABLE_REMIX flag, which already hid the nav entry and redirected the route. All existing test coverage for the real pipeline logic is preserved via an autouse pytest fixture that force-enables the flag for every test in test_remix.py except the two new ones that specifically cover the disabled-by-default response - so the feature stays fully regression-tested while dormant, not stripped of coverage.',
], ],
}, },
{ {
...@@ -198,6 +201,7 @@ const FRONTEND_DONE: DoneGroup[] = [ ...@@ -198,6 +201,7 @@ const FRONTEND_DONE: DoneGroup[] = [
'Multi-select save in the chat music list (2026-09-01): each not-yet-saved row gets a checkbox; selecting any shows a sticky "Save N selected" bar. Still calls /music/tag once per song sequentially - there\'s no batch endpoint, and Shazam/AcoustID lookups are heavy enough per call that racing them wouldn\'t help - but it\'s one tap instead of one per song', 'Multi-select save in the chat music list (2026-09-01): each not-yet-saved row gets a checkbox; selecting any shows a sticky "Save N selected" bar. Still calls /music/tag once per song sequentially - there\'s no batch endpoint, and Shazam/AcoustID lookups are heavy enough per call that racing them wouldn\'t help - but it\'s one tap instead of one per song',
'First-run onboarding walkthrough (2026-10-08), closing the one gap left on the backlog since the very first redesign: a brand-new account used to land straight on Home with zero explanation. New OnboardingOverlay, shown once (gated on the account\'s has_completed_onboarding flag, checked in ProtectedRoute.tsx - so it reaches a new user no matter which protected page they land on first, not just /home) - six full-screen steps covering Upload, Telegram linking, Discovery, Social, and Soundmarks, each with a small hand-authored Lottie animation (lottie-react\'s SVG-only/no-expressions LottieLight build - the full build probes a canvas 2D context at import time, which jsdom doesn\'t implement, so tests needed a getContext stub too), then a final privacy step reusing Settings\' own ToggleRow component (extracted into ui/) wired to the real PATCH /auth/privacy - choices made during onboarding actually take effect, not a static preview. "Skip" and the final "Start exploring" both call the new completeOnboarding() (optimistic local flip + fire-and-forget API call) so it never reappears, confirmed against a real fresh login (not just a reload) on another session. Login.tsx also gained a one-line welcome tagline (the PWA manifest\'s own description) above the sign-in form, so onboarding\'s "welcome" framing starts before the account even exists.', 'First-run onboarding walkthrough (2026-10-08), closing the one gap left on the backlog since the very first redesign: a brand-new account used to land straight on Home with zero explanation. New OnboardingOverlay, shown once (gated on the account\'s has_completed_onboarding flag, checked in ProtectedRoute.tsx - so it reaches a new user no matter which protected page they land on first, not just /home) - six full-screen steps covering Upload, Telegram linking, Discovery, Social, and Soundmarks, each with a small hand-authored Lottie animation (lottie-react\'s SVG-only/no-expressions LottieLight build - the full build probes a canvas 2D context at import time, which jsdom doesn\'t implement, so tests needed a getContext stub too), then a final privacy step reusing Settings\' own ToggleRow component (extracted into ui/) wired to the real PATCH /auth/privacy - choices made during onboarding actually take effect, not a static preview. "Skip" and the final "Start exploring" both call the new completeOnboarding() (optimistic local flip + fire-and-forget API call) so it never reappears, confirmed against a real fresh login (not just a reload) on another session. Login.tsx also gained a one-line welcome tagline (the PWA manifest\'s own description) above the sign-in form, so onboarding\'s "welcome" framing starts before the account even exists.',
'Four of the six onboarding animations redrawn to literally depict their feature instead of an abstract motif (2026-10-08, reported as not showing "what is being done"): Upload now shows a file actually dropping into a zone, pulsing, then morphing into a tag+checkmark; Telegram shows two app-icon nodes exchanging packets with a checkmark confirming the connection; Soundmarks keeps its existing pin-drop animation exactly as-is (explicitly requested) but gained a tilted/perspective ground-plane ellipse with grid lines and small block shapes underneath it, so the pin now visibly lands on a map; Privacy\'s hexagon-shield-plus-badge was replaced with a literal padlock (a stroke ring "shackle" that drops and tucks behind a solid body, followed by a keyhole dot). Discovery and Social were explicitly left untouched. Caught and fixed one real Lottie authoring bug along the way: a shape group\'s "tr" entry is the transform for the *group* it sits in, not a per-shape offset - stacking several (path, fill, tr) triples flat in one group silently dropped every shape after the first (confirmed by inspecting the rendered SVG DOM, not just eyeballing screenshots, which can miss a thin checkmark stroke entirely at this icon size), fixed by wrapping each primitive in its own sub-group.', 'Four of the six onboarding animations redrawn to literally depict their feature instead of an abstract motif (2026-10-08, reported as not showing "what is being done"): Upload now shows a file actually dropping into a zone, pulsing, then morphing into a tag+checkmark; Telegram shows two app-icon nodes exchanging packets with a checkmark confirming the connection; Soundmarks keeps its existing pin-drop animation exactly as-is (explicitly requested) but gained a tilted/perspective ground-plane ellipse with grid lines and small block shapes underneath it, so the pin now visibly lands on a map; Privacy\'s hexagon-shield-plus-badge was replaced with a literal padlock (a stroke ring "shackle" that drops and tucks behind a solid body, followed by a keyhole dot). Discovery and Social were explicitly left untouched. Caught and fixed one real Lottie authoring bug along the way: a shape group\'s "tr" entry is the transform for the *group* it sits in, not a per-shape offset - stacking several (path, fill, tr) triples flat in one group silently dropped every shape after the first (confirmed by inspecting the rendered SVG DOM, not just eyeballing screenshots, which can miss a thin checkmark stroke entirely at this icon size), fixed by wrapping each primitive in its own sub-group.',
'AdminPanel\'s Users tab gained real account moderation (2026-10-10) alongside the existing role selector: a search box (debounced, matches the backend\'s new username substring filter), and a per-user "Manage" panel (rename, deactivate/reactivate, suspend-for-N-hours/clear suspension, reset password) that expands inline below the row rather than a separate modal - deliberately lightweight for an admin-only, rarely-used surface. Deactivating asks for confirmation first (same window.confirm pattern as soundmark delete) since it signs the account out immediately.',
], ],
}, },
{ {
...@@ -226,6 +230,7 @@ const FRONTEND_DONE: DoneGroup[] = [ ...@@ -226,6 +230,7 @@ const FRONTEND_DONE: DoneGroup[] = [
area: 'Home', area: 'Home',
items: [ items: [
'New default landing page (2026-10-06), replacing Library as where you land post-login and at the catch-all route - Library remains a full nav destination, just no longer first. Globe nav icon (Globe2 was already taken by Library\'s "Shared" scope toggle, so a distinct icon avoids visual overlap between the two concepts). Three sections backed by GET /home/feed, each with an icon + one-line caption so they read as distinct content types at a glance: "New Songs" (a row list with album-art thumbnails - not a card grid, so it visually reads as "songs" rather than looking identical to the albums grid below it), "New Albums" (a cover-art grid - deliberately a different shape from the songs list), "Suggestions" (row list again). A song the caller already owns plays/favorites/playlists directly via its real library id; everyone else\'s goes through the same claim-then-act flow Library\'s shared search already uses (useHomeSongPlayback, shared by every row/card so the claim logic isn\'t duplicated). Tapping an album the caller owns navigates to its real detail page; someone else\'s album (which has no detail page to navigate to - /library/album is caller-scoped) expands its tracks inline instead. No uploader identity shown anywhere on the page (2026-10-07) - matches the backend feed no longer attaching one. Every song row (New Songs, Suggestions, and an expanded album\'s tracks) also got the same favorite heart Library already has, claiming first if the caller doesn\'t yet own the song.', 'New default landing page (2026-10-06), replacing Library as where you land post-login and at the catch-all route - Library remains a full nav destination, just no longer first. Globe nav icon (Globe2 was already taken by Library\'s "Shared" scope toggle, so a distinct icon avoids visual overlap between the two concepts). Three sections backed by GET /home/feed, each with an icon + one-line caption so they read as distinct content types at a glance: "New Songs" (a row list with album-art thumbnails - not a card grid, so it visually reads as "songs" rather than looking identical to the albums grid below it), "New Albums" (a cover-art grid - deliberately a different shape from the songs list), "Suggestions" (row list again). A song the caller already owns plays/favorites/playlists directly via its real library id; everyone else\'s goes through the same claim-then-act flow Library\'s shared search already uses (useHomeSongPlayback, shared by every row/card so the claim logic isn\'t duplicated). Tapping an album the caller owns navigates to its real detail page; someone else\'s album (which has no detail page to navigate to - /library/album is caller-scoped) expands its tracks inline instead. No uploader identity shown anywhere on the page (2026-10-07) - matches the backend feed no longer attaching one. Every song row (New Songs, Suggestions, and an expanded album\'s tracks) also got the same favorite heart Library already has, claiming first if the caller doesn\'t yet own the song.',
'Global search box added to the top of Home (2026-10-10) - no new backend endpoint: reuses POST /library/shared/search, the exact same global/all-users search Library\'s own "Shared" scope already calls, since Home\'s feed is already that same app-wide pool. While a query is active the three feed sections are replaced (not supplemented) by a results list, reusing HomeSongRow/useHomeSongPlayback unchanged - the response shape is already identical to what that hook needs, so every result (always someone else\'s song by construction, since shared search excludes anything the caller already owns) goes through the existing claim-then-act path with zero new component code. Same 400ms-debounced pattern as Library\'s search.',
], ],
}, },
{ {
......
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