Commit b4f425df authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Remix composer sources from the Stax library, not local file uploads

Replaced the file-drop control with RemixSongPicker - a multi-select
(up to 5) modal over the caller's own library, matching how library
songs already get better treatment server-side (skips a fresh,
slower, less reliable identify_audio() call and uses verified
title/artist/genre directly instead). createRemix() dropped its whole
XHR/upload-progress path along with it - there's no file transfer left
to track progress on, just a plain form POST with prompt +
library_song_ids.

First tests for Remix.tsx (previously zero coverage), plus tests for
the new RemixSongPicker component.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent bfeb291d
Pipeline #1125 canceled with stage
import { API_BASE_URL, apiFetch, getAccessToken } from './client' import { apiFetch } from './client'
export interface RemixStatus { export interface RemixStatus {
job_id: number job_id: number
...@@ -12,46 +12,15 @@ export interface RemixStatus { ...@@ -12,46 +12,15 @@ export interface RemixStatus {
error?: string error?: string
} }
/** XHR, not fetch() - same reasoning as music.ts's uploadDirect: it's the only way to get /** Sources are always library_song_ids now, not uploaded files - the backend skips a fresh
* real upload-progress events for the file transfer itself. */ * (slower, less reliable) identify_audio() call for a library song and uses its already-known
export function createRemix( * title/artist/genre directly, which is what actually makes the resulting remix's plan
files: File[], * better-informed. No file transfer means no upload-progress tracking either - a plain form
prompt: string, * POST via apiFetch, not the XHR machinery a real file upload would need. */
libraryIds: number[] = [], export function createRemix(prompt: string, libraryIds: number[]): Promise<{ job_id: number; status: string; status_url: string }> {
onProgress?: (percent: number) => void, return apiFetch<{ job_id: number; status: string; status_url: string }>('/remix', {
): Promise<{ job_id: number; status: string; status_url: string }> { method: 'POST',
return new Promise((resolve, reject) => { form: { prompt, library_song_ids: libraryIds.join(',') },
const token = getAccessToken()
const body = new FormData()
body.append('prompt', prompt)
for (const f of files) body.append('files', f)
if (libraryIds.length) body.append('library_song_ids', libraryIds.join(','))
const xhr = new XMLHttpRequest()
xhr.open('POST', `${API_BASE_URL}/remix`)
if (token) xhr.setRequestHeader('Authorization', `Bearer ${token}`)
xhr.upload.onprogress = (e) => {
if (e.lengthComputable && onProgress) onProgress(Math.round((e.loaded / e.total) * 100))
}
xhr.onload = () => {
let parsed: unknown = null
try {
parsed = JSON.parse(xhr.responseText)
} catch {
// non-JSON response body, parsed stays null
}
if (xhr.status >= 200 && xhr.status < 300) {
resolve(parsed as { job_id: number; status: string; status_url: string })
} else {
const detail = (parsed as { detail?: string } | null)?.detail
reject(new Error(detail ?? `Remix request failed (${xhr.status})`))
}
}
xhr.onerror = () => reject(new Error('Network error starting remix'))
xhr.send(body)
}) })
} }
......
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RemixSongPicker, MAX_REMIX_SONGS } from './RemixSongPicker'
import * as libraryApi from '../api/library'
import type { LibrarySong } from '../api/library'
function song(id: number, title: string, artist = 'Some Artist'): LibrarySong {
return {
id,
user_id: 1,
title,
artist,
album: null,
genre: null,
coverart: null,
lyrics: null,
file_path: `/x${id}.mp3`,
added_at: '2026-01-01T00:00:00Z',
}
}
describe('RemixSongPicker', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('lists the library and toggles a song into the selection on click', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [song(1, 'Invisible')] })
const onChange = vi.fn()
render(<RemixSongPicker selected={[]} onChange={onChange} onClose={() => {}} />)
await userEvent.click(await screen.findByText('Invisible'))
expect(onChange).toHaveBeenCalledWith([song(1, 'Invisible')])
})
it('deselects an already-selected song on click', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [song(1, 'Invisible')] })
const onChange = vi.fn()
render(<RemixSongPicker selected={[song(1, 'Invisible')]} onChange={onChange} onClose={() => {}} />)
await userEvent.click(await screen.findByText('Invisible'))
expect(onChange).toHaveBeenCalledWith([])
})
it('filters by title or artist as you type', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({
status: 'success',
library: [song(1, 'Invisible', 'Duran Duran'), song(2, 'Rio', 'Duran Duran'), song(3, 'Africa', 'Toto')],
})
render(<RemixSongPicker selected={[]} onChange={() => {}} onClose={() => {}} />)
await screen.findByText('Africa')
await userEvent.type(screen.getByPlaceholderText('Search your library'), 'toto')
expect(screen.getByText('Africa')).toBeInTheDocument()
expect(screen.queryByText('Invisible')).not.toBeInTheDocument()
})
it(`disables further selection once ${MAX_REMIX_SONGS} songs are picked`, async () => {
const songs = Array.from({ length: MAX_REMIX_SONGS + 1 }, (_, i) => song(i + 1, `Song ${i + 1}`))
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: songs })
const onChange = vi.fn()
render(<RemixSongPicker selected={songs.slice(0, MAX_REMIX_SONGS)} onChange={onChange} onClose={() => {}} />)
const extraButton = (await screen.findByText(`Song ${MAX_REMIX_SONGS + 1}`)).closest('button')!
expect(extraButton).toBeDisabled()
await userEvent.click(extraButton)
expect(onChange).not.toHaveBeenCalled()
})
it('closes on Escape', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
const onClose = vi.fn()
render(<RemixSongPicker selected={[]} onChange={() => {}} onClose={onClose} />)
await userEvent.keyboard('{Escape}')
await waitFor(() => expect(onClose).toHaveBeenCalled())
})
})
import { useEffect, useState } from 'react'
import { Check, Music2, X } from 'lucide-react'
import { getLibrary, type LibrarySong } from '../api/library'
import { Button } from './ui/Button'
import { Input } from './ui/Input'
export const MAX_REMIX_SONGS = 5
interface RemixSongPickerProps {
selected: LibrarySong[]
onChange: (songs: LibrarySong[]) => void
onClose: () => void
}
/** Multi-select picker for Remix - always the caller's own library (the backend only ever
* accepts library_song_ids scoped to the caller, same as SongPicker's "mine" tab, but there's
* no "public library" option here: a remix sourced from someone else's library song isn't
* something the backend supports, unlike a soundmark anthem). Distinct from SongPicker (single
* select, has a public tab) rather than overloading it with a multi-select mode it wasn't
* designed for. */
export function RemixSongPicker({ selected, onChange, onClose }: RemixSongPickerProps) {
const [library, setLibrary] = useState<LibrarySong[]>([])
const [query, setQuery] = useState('')
useEffect(() => {
getLibrary()
.then((res) => setLibrary(res.library))
.catch(() => {
// Empty list on failure - not worth a dedicated error state for a picker.
})
}, [])
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
if (e.key === 'Escape') onClose()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [onClose])
const q = query.trim().toLowerCase()
const filtered = q ? library.filter((s) => s.title.toLowerCase().includes(q) || s.artist.toLowerCase().includes(q)) : library
function toggle(song: LibrarySong) {
const isSelected = selected.some((s) => s.id === song.id)
if (isSelected) {
onChange(selected.filter((s) => s.id !== song.id))
} else if (selected.length < MAX_REMIX_SONGS) {
onChange([...selected, song])
}
}
return (
<div
role="dialog"
aria-modal="true"
aria-label="Choose songs to remix"
className="fixed inset-0 z-40 flex items-end justify-center bg-black/60 sm:items-center"
onClick={onClose}
>
<div
className="flex max-h-[80vh] w-full max-w-md flex-col overflow-hidden rounded-t-2xl bg-neutral-900 sm:rounded-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between border-b border-neutral-800 px-4 py-3">
<p className="text-sm font-semibold text-white">Choose up to {MAX_REMIX_SONGS} songs</p>
<button
onClick={onClose}
aria-label="Close"
className="rounded-full p-1.5 text-neutral-400 transition-colors hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<X size={18} strokeWidth={2} />
</button>
</div>
<div className="px-4 pt-3">
<Input placeholder="Search your library" value={query} onChange={(e) => setQuery(e.target.value)} autoFocus />
</div>
<ul className="mt-2 flex-1 overflow-y-auto px-2 pb-3">
{filtered.length === 0 && (
<p className="px-2 py-8 text-center text-sm text-neutral-500">
{library.length === 0 ? 'Your library is empty.' : 'No songs found.'}
</p>
)}
{filtered.map((song) => {
const isSelected = selected.some((s) => s.id === song.id)
const disabled = !isSelected && selected.length >= MAX_REMIX_SONGS
return (
<li key={song.id}>
<button
onClick={() => toggle(song)}
disabled={disabled}
aria-pressed={isSelected}
className={`flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-not-allowed disabled:opacity-40 ${
isSelected ? 'bg-emerald-500/10' : 'hover:bg-white/5'
}`}
>
<div
className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-md ${
isSelected ? 'bg-emerald-500/20 text-emerald-400' : 'bg-neutral-800 text-neutral-600'
}`}
>
{isSelected ? <Check size={16} strokeWidth={2.5} /> : <Music2 size={14} strokeWidth={1.75} />}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-white">{song.title}</p>
<p className="truncate text-xs text-neutral-500">{song.artist}</p>
</div>
</button>
</li>
)
})}
</ul>
<div className="border-t border-neutral-800 p-3">
<Button onClick={onClose} className="w-full">
Done ({selected.length}/{MAX_REMIX_SONGS})
</Button>
</div>
</div>
</div>
)
}
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Remix } from './Remix'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as libraryApi from '../api/library'
import * as remixApi from '../api/remix'
import type { LibrarySong } from '../api/library'
const SONG: LibrarySong = {
id: 1,
user_id: 1,
title: 'Invisible',
artist: 'Duran Duran',
album: null,
genre: null,
coverart: null,
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
}
function renderRemix() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Remix />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
async function pickSong(title: string) {
await userEvent.click(screen.getByText('Choose up to 5 songs from your library'))
await userEvent.click(await screen.findByText(title))
await userEvent.click(screen.getByRole('button', { name: /Done/ }))
}
describe('Remix', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('disables submission until a song is picked and a prompt is written', async () => {
renderRemix()
expect(screen.getByRole('button', { name: /Create Remix/ })).toBeDisabled()
await pickSong('Invisible')
expect(screen.getByRole('button', { name: /Create Remix/ })).toBeDisabled()
await userEvent.type(screen.getByPlaceholderText(/Blend the vocals/), 'make it dreamy')
expect(screen.getByRole('button', { name: /Create Remix/ })).not.toBeDisabled()
})
it('picking a song shows it in the selected list and lets it be removed', async () => {
renderRemix()
await pickSong('Invisible')
expect(screen.getAllByText('Invisible').length).toBeGreaterThan(0)
await userEvent.click(screen.getByRole('button', { name: 'Remove Invisible' }))
expect(screen.getByRole('button', { name: /Create Remix/ })).toBeDisabled()
})
it('submits with the picked library song ids, not any uploaded file', async () => {
const createRemix = vi
.spyOn(remixApi, 'createRemix')
.mockResolvedValue({ job_id: 7, status: 'queued', status_url: '/remix/7' })
vi.spyOn(remixApi, 'getRemixStatus').mockResolvedValue({
job_id: 7,
status: 'queued',
stage_detail: null,
remix_name: null,
})
renderRemix()
await pickSong('Invisible')
await userEvent.type(screen.getByPlaceholderText(/Blend the vocals/), 'make it dreamy')
await userEvent.click(screen.getByRole('button', { name: /Create Remix/ }))
await waitFor(() => {
expect(createRemix).toHaveBeenCalledWith('make it dreamy', [1])
})
})
it('shows an error message when starting the remix fails', async () => {
vi.spyOn(remixApi, 'createRemix').mockRejectedValue(new Error('Something went wrong'))
renderRemix()
await pickSong('Invisible')
await userEvent.type(screen.getByPlaceholderText(/Blend the vocals/), 'make it dreamy')
await userEvent.click(screen.getByRole('button', { name: /Create Remix/ }))
expect(await screen.findByText('Something went wrong')).toBeInTheDocument()
})
})
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { AlertCircle, Music2, Sparkles, X } from 'lucide-react' import { AlertCircle, ListMusic, Music2, Sparkles, X } from 'lucide-react'
import { Layout } from '../components/Layout' import { Layout } from '../components/Layout'
import { RemixSongPicker } from '../components/RemixSongPicker'
import { Button } from '../components/ui/Button' import { Button } from '../components/ui/Button'
import { Textarea } from '../components/ui/Input' import { Textarea } from '../components/ui/Input'
import { ProgressBar } from '../components/ui/ProgressBar'
import { createRemix, getRemixStatus, type RemixStatus } from '../api/remix' import { createRemix, getRemixStatus, type RemixStatus } from '../api/remix'
import type { LibrarySong } from '../api/library'
const STAGES: RemixStatus['status'][] = ['queued', 'planning', 'separating', 'mixing', 'mastering', 'tagging', 'done'] const STAGES: RemixStatus['status'][] = ['queued', 'planning', 'separating', 'mixing', 'mastering', 'tagging', 'done']
export function Remix() { export function Remix() {
const [files, setFiles] = useState<File[]>([]) const [selectedSongs, setSelectedSongs] = useState<LibrarySong[]>([])
const [pickerOpen, setPickerOpen] = useState(false)
const [prompt, setPrompt] = useState('') const [prompt, setPrompt] = useState('')
const [status, setStatus] = useState<RemixStatus | null>(null) const [status, setStatus] = useState<RemixStatus | null>(null)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false) const [submitting, setSubmitting] = useState(false)
const [uploadPercent, setUploadPercent] = useState<number | null>(null)
const pollRef = useRef<number | null>(null) const pollRef = useRef<number | null>(null)
useEffect(() => { useEffect(() => {
...@@ -23,22 +24,21 @@ export function Remix() { ...@@ -23,22 +24,21 @@ export function Remix() {
} }
}, []) }, [])
function removeFile(index: number) { function removeSong(songId: number) {
setFiles((f) => f.filter((_, i) => i !== index)) setSelectedSongs((s) => s.filter((song) => song.id !== songId))
} }
async function handleSubmit(e: React.FormEvent) { async function handleSubmit(e: React.FormEvent) {
e.preventDefault() e.preventDefault()
if (files.length === 0 || !prompt.trim()) return if (selectedSongs.length === 0 || !prompt.trim()) return
setSubmitting(true) setSubmitting(true)
setError(null) setError(null)
setStatus(null) setStatus(null)
setUploadPercent(0)
try { try {
const { job_id } = await createRemix(files, prompt.trim(), [], (percent) => { const { job_id } = await createRemix(
setUploadPercent(percent) prompt.trim(),
}) selectedSongs.map((s) => s.id),
setUploadPercent(null) // upload done - "Starting…" (indeterminate) until the first poll lands )
pollRef.current = window.setInterval(async () => { pollRef.current = window.setInterval(async () => {
const s = await getRemixStatus(job_id) const s = await getRemixStatus(job_id)
setStatus(s) setStatus(s)
...@@ -49,7 +49,6 @@ export function Remix() { ...@@ -49,7 +49,6 @@ export function Remix() {
}, 2000) }, 2000)
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : 'Could not start the remix') setError(err instanceof Error ? err.message : 'Could not start the remix')
setUploadPercent(null)
setSubmitting(false) setSubmitting(false)
} }
} }
...@@ -59,35 +58,38 @@ export function Remix() { ...@@ -59,35 +58,38 @@ export function Remix() {
return ( return (
<Layout title="AI Remix"> <Layout title="AI Remix">
<p className="mb-6 text-sm leading-relaxed text-neutral-400"> <p className="mb-6 text-sm leading-relaxed text-neutral-400">
Upload 1-5 songs and describe the remix in plain language. Gemini directs the arrangement, Pick 1-5 songs from your library and describe the remix in plain language. Gemini directs the
Demucs does the stem separation. arrangement using each song's real audio and already-known title/artist/genre, Demucs does the
stem separation.
</p> </p>
<form onSubmit={handleSubmit} className="space-y-4"> <form onSubmit={handleSubmit} className="space-y-4">
<label className="flex cursor-pointer flex-col items-center gap-2 rounded-xl border border-dashed border-neutral-700 p-6 text-center transition-colors duration-150 hover:border-neutral-600 hover:bg-neutral-900/50"> <button
<Music2 size={22} strokeWidth={1.5} className="text-neutral-500" /> type="button"
<span className="text-sm text-neutral-400">Choose up to 5 audio files</span> onClick={() => setPickerOpen(true)}
<input className="flex w-full cursor-pointer flex-col items-center gap-2 rounded-xl border border-dashed border-neutral-700 p-6 text-center transition-colors duration-150 hover:border-neutral-600 hover:bg-neutral-900/50"
type="file" >
accept="audio/*" <ListMusic size={22} strokeWidth={1.5} className="text-neutral-500" />
multiple <span className="text-sm text-neutral-400">Choose up to 5 songs from your library</span>
onChange={(e) => setFiles(Array.from(e.target.files ?? []).slice(0, 5))} </button>
className="hidden"
/>
</label>
{files.length > 0 && ( {selectedSongs.length > 0 && (
<ul className="space-y-1.5"> <ul className="space-y-1.5">
{files.map((f, i) => ( {selectedSongs.map((song) => (
<li <li
key={`${f.name}-${i}`} key={song.id}
className="flex items-center justify-between rounded-lg bg-neutral-900 px-3 py-2 text-sm text-neutral-300" className="flex items-center justify-between gap-2 rounded-lg bg-neutral-900 px-3 py-2 text-sm text-neutral-300"
> >
<span className="truncate">{f.name}</span> <span className="flex min-w-0 items-center gap-2">
<Music2 size={14} strokeWidth={1.75} className="shrink-0 text-neutral-500" />
<span className="truncate">
{song.title} <span className="text-neutral-500">· {song.artist}</span>
</span>
</span>
<button <button
type="button" type="button"
onClick={() => removeFile(i)} onClick={() => removeSong(song.id)}
aria-label="Remove file" aria-label={`Remove ${song.title}`}
className="ml-2 flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-neutral-500 hover:bg-neutral-800 hover:text-white" className="ml-2 flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-neutral-500 hover:bg-neutral-800 hover:text-white"
> >
<X size={14} strokeWidth={2} /> <X size={14} strokeWidth={2} />
...@@ -104,16 +106,21 @@ export function Remix() { ...@@ -104,16 +106,21 @@ export function Remix() {
placeholder="e.g. Blend the vocals of the first song over the drums of the second, slowed down with heavy reverb" placeholder="e.g. Blend the vocals of the first song over the drums of the second, slowed down with heavy reverb"
/> />
<Button type="submit" disabled={submitting || files.length === 0 || !prompt.trim()} className="w-full"> <Button type="submit" disabled={submitting || selectedSongs.length === 0 || !prompt.trim()} className="w-full">
<Sparkles size={16} strokeWidth={2} /> <Sparkles size={16} strokeWidth={2} />
{submitting ? 'Starting…' : 'Create Remix'} {submitting ? 'Starting…' : 'Create Remix'}
</Button> </Button>
</form> </form>
{pickerOpen && (
<RemixSongPicker selected={selectedSongs} onChange={setSelectedSongs} onClose={() => setPickerOpen(false)} />
)}
{submitting && !status && ( {submitting && !status && (
<div className="mt-4"> <p className="mt-4 flex items-center gap-2 text-sm text-neutral-400">
<ProgressBar percent={uploadPercent} label={uploadPercent !== null ? 'Uploading' : 'Starting…'} /> <span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-neutral-700 border-t-neutral-300" />
</div> Starting…
</p>
)} )}
{error && ( {error && (
......
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