Commit 92661638 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add a real progress bar to Upload and Remix

fetch() has no upload-progress equivalent to onUploadProgress, so
uploadDirect (music.ts) and createRemix (remix.ts) switch to XMLHttpRequest
for real byte-level transfer progress via xhr.upload.onprogress - the only
way to get this data.

New ProgressBar component: shows real 0-100% during the transfer, then
switches to an indeterminate/pulsing state once the transfer completes and
the server's identify/tag pipeline takes over (which has no progress
reporting of its own to report, unlike /remix's job-status polling).

Remix already had a stage-based progress bar for job polling but nothing
during the initial upload itself, which can be slow for up to 5 files -
now shows real upload progress first, then "Starting…" until the first
poll lands, then hands off to the existing stage bar once real status data
arrives.

Typechecks clean, production build succeeds, dev server HMR'd cleanly.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 4a6f7e60
......@@ -25,18 +25,41 @@ export function tagFromChat(chatId: number, messageId: number, languagePreferenc
})
}
export async function uploadDirect(file: File) {
const token = getAccessToken()
const body = new FormData()
body.append('file', file)
const res = await fetch(`${API_BASE_URL}/music/upload`, {
method: 'POST',
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
body,
/** fetch() has no way to report upload progress (no onUploadProgress equivalent) - XHR is
* the only way to get real byte-level progress for the transfer itself. onProgress fires
* with 0-100 during the upload; once the transfer hits 100 there's no more progress data
* available (the server's identify/tag pipeline has no progress reporting of its own, unlike
* /remix's job-status polling), so the caller shows an indeterminate state from there. */
export function uploadDirect(file: File, onProgress?: (percent: number) => void): Promise<TagResponse> {
return new Promise((resolve, reject) => {
const token = getAccessToken()
const body = new FormData()
body.append('file', file)
const xhr = new XMLHttpRequest()
xhr.open('POST', `${API_BASE_URL}/music/upload`)
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 TagResponse)
} else {
const detail = (parsed as { detail?: string } | null)?.detail
reject(new Error(detail ?? `Upload failed (${xhr.status})`))
}
}
xhr.onerror = () => reject(new Error('Network error during upload'))
xhr.send(body)
})
if (!res.ok) {
const detail = await res.json().catch(() => null)
throw new Error(detail?.detail ?? `Upload failed (${res.status})`)
}
return res.json() as Promise<TagResponse>
}
......@@ -12,20 +12,47 @@ export interface RemixStatus {
error?: string
}
export async function createRemix(files: File[], prompt: string, libraryIds: number[] = []) {
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(','))
/** XHR, not fetch() - same reasoning as music.ts's uploadDirect: it's the only way to get
* real upload-progress events for the file transfer itself. */
export function createRemix(
files: File[],
prompt: string,
libraryIds: number[] = [],
onProgress?: (percent: number) => void,
): Promise<{ job_id: number; status: string; status_url: string }> {
return new Promise((resolve, reject) => {
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 res = await fetch(`${API_BASE_URL}/remix`, {
method: 'POST',
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
body,
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)
})
if (!res.ok) throw new Error(`Remix request failed (${res.status})`)
return res.json() as Promise<{ job_id: number; status: string; status_url: string }>
}
export function getRemixStatus(jobId: number) {
......
/** `percent === null` renders an indeterminate/pulsing state - used once the upload transfer
* itself hits 100% but the server's identify/tag pipeline (which has no progress reporting
* of its own) is still running. */
export function ProgressBar({ percent, label }: { percent: number | null; label: string }) {
return (
<div>
<div className="mb-1.5 flex items-center justify-between text-xs text-neutral-400">
<span>{label}</span>
{percent !== null && <span className="tabular-nums text-neutral-500">{percent}%</span>}
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-neutral-800">
{percent !== null ? (
<div
className="h-full rounded-full bg-emerald-500 transition-[width] duration-200 ease-out"
style={{ width: `${percent}%` }}
/>
) : (
<div className="h-full w-1/3 animate-[indeterminate_1.2s_ease-in-out_infinite] rounded-full bg-emerald-500" />
)}
</div>
</div>
)
}
......@@ -14,3 +14,12 @@
.animate-message-enter {
animation: message-enter 200ms ease-out;
}
@keyframes indeterminate {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(300%);
}
}
......@@ -3,6 +3,7 @@ import { AlertCircle, Music2, Sparkles, X } from 'lucide-react'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { Textarea } from '../components/ui/Input'
import { ProgressBar } from '../components/ui/ProgressBar'
import { createRemix, getRemixStatus, type RemixStatus } from '../api/remix'
const STAGES: RemixStatus['status'][] = ['queued', 'planning', 'separating', 'mixing', 'mastering', 'tagging', 'done']
......@@ -13,6 +14,7 @@ export function Remix() {
const [status, setStatus] = useState<RemixStatus | null>(null)
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
const [uploadPercent, setUploadPercent] = useState<number | null>(null)
const pollRef = useRef<number | null>(null)
useEffect(() => {
......@@ -31,18 +33,23 @@ export function Remix() {
setSubmitting(true)
setError(null)
setStatus(null)
setUploadPercent(0)
try {
const { job_id } = await createRemix(files, prompt.trim())
const { job_id } = await createRemix(files, prompt.trim(), [], (percent) => {
setUploadPercent(percent)
})
setUploadPercent(null) // upload done - "Starting…" (indeterminate) until the first poll lands
pollRef.current = window.setInterval(async () => {
const s = await getRemixStatus(job_id)
setStatus(s)
setSubmitting(false) // stage bar (driven by `status`) takes over from here
if (s.status === 'done' || s.status === 'error') {
if (pollRef.current) window.clearInterval(pollRef.current)
}
}, 2000)
} catch (err) {
setError(err instanceof Error ? err.message : 'Could not start the remix')
} finally {
setUploadPercent(null)
setSubmitting(false)
}
}
......@@ -103,6 +110,12 @@ export function Remix() {
</Button>
</form>
{submitting && !status && (
<div className="mt-4">
<ProgressBar percent={uploadPercent} label={uploadPercent !== null ? 'Uploading' : 'Starting…'} />
</div>
)}
{error && (
<p className="mt-4 flex items-center gap-1.5 text-sm text-red-400">
<AlertCircle size={14} strokeWidth={2} />
......
......@@ -2,29 +2,42 @@ import { useState } from 'react'
import { UploadCloud } from 'lucide-react'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { ProgressBar } from '../components/ui/ProgressBar'
import { uploadDirect, type TagResponse } from '../api/music'
type Stage = 'idle' | 'uploading' | 'processing'
export function Upload() {
const [file, setFile] = useState<File | null>(null)
const [busy, setBusy] = useState(false)
const [stage, setStage] = useState<Stage>('idle')
const [uploadPercent, setUploadPercent] = useState(0)
const [result, setResult] = useState<TagResponse | null>(null)
const [error, setError] = useState<string | null>(null)
async function handleUpload() {
if (!file) return
setBusy(true)
setStage('uploading')
setUploadPercent(0)
setError(null)
setResult(null)
try {
const res = await uploadDirect(file)
const res = await uploadDirect(file, (percent) => {
setUploadPercent(percent)
// The transfer itself is done once this hits 100 - everything after that (identify,
// lyrics, genre, tag, store) is the server's job and has no progress of its own to
// report, so the bar switches to an indeterminate state for that part.
if (percent >= 100) setStage('processing')
})
setResult(res)
} catch (err) {
setError(err instanceof Error ? err.message : 'Upload failed')
} finally {
setBusy(false)
setStage('idle')
}
}
const busy = stage !== 'idle'
return (
<Layout title="Upload &amp; Tag">
<p className="mb-6 text-sm leading-relaxed text-neutral-400">
......@@ -40,13 +53,23 @@ export function Upload() {
<input
type="file"
accept="audio/*"
disabled={busy}
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
className="hidden"
/>
</label>
{busy && (
<div className="mt-4">
<ProgressBar
percent={stage === 'uploading' ? uploadPercent : null}
label={stage === 'uploading' ? 'Uploading' : 'Identifying & tagging…'}
/>
</div>
)}
<Button onClick={handleUpload} disabled={!file || busy} className="mt-4 w-full">
{busy ? 'Identifying & tagging…' : 'Upload'}
{stage === 'uploading' ? 'Uploading…' : stage === 'processing' ? 'Processing…' : 'Upload'}
</Button>
{error && <p className="mt-4 text-sm text-red-400">{error}</p>}
......
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