Commit 04d2c5c1 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Multi-select in Upload and Telegram chat music identification

Upload now takes multiple files in one go: each gets its own queued
row (removable before upload), progress, result, and error state, fed
through the existing one-file-at-a-time endpoint sequentially rather
than in parallel - the per-file identify/tag pipeline is already the
expensive part, so racing several through it wouldn't help.

TelegramLink's chat music list gets the equivalent for saving: a
checkbox per not-yet-saved row and a sticky "Save N selected" action
that calls /music/tag once per song, same sequential reasoning. The
existing per-song Save button still works for saving just one.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 3592c605
Pipeline #1158 canceled with stage
......@@ -160,8 +160,9 @@ const FRONTEND_DONE: DoneGroup[] = [
items: [
'Login page: username/password + register, toggled in place',
'Route guards redirect to /login when signed out instead of showing a blank page',
'Telegram linking page: phone + code (+ two-step verification password if the account has it enabled), then browse linked chats and save any found song to the library (tags via /music/tag, one song at a time)',
'Telegram linking page: phone + code (+ two-step verification password if the account has it enabled), then browse linked chats and save any found song to the library (tags via /music/tag)',
'Per-song 30-second preview button in the chat music list, playable through the shared player before deciding whether to save (2026-08-23)',
'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',
],
},
{
......@@ -192,6 +193,7 @@ const FRONTEND_DONE: DoneGroup[] = [
'Add-to-playlist modal from the Library page (add existing or create-and-add)',
'Delete-from-library (2026-08-31): swipe a Library row left past a threshold to reveal and trigger delete (right instead adds to queue) - confirms via the same window.confirm pattern already used for soundmark delete, then removes the file on disk and reconciles the song out of every local list it could be showing in (the full library, the current search\'s Songs section, and any album groupings within it)',
'Upload\'s result card swaps its download link for "Add to playlist" (2026-09-01), reusing AddToPlaylistModal (narrowed its song prop to just {id, title} rather than the full LibrarySong shape, since Upload\'s freshly-tagged result isn\'t one) - the card itself is now tappable to play the track immediately via the shared player instead of only offering a file to save locally',
'Upload accepts multiple files at once (2026-09-01): each selected file gets its own queued row (removable before upload) and its own progress/result/error state, uploaded sequentially through the same one-file-at-a-time endpoint rather than all at once - the identify/tag pipeline per file is already the heavy part, so nothing would be gained by racing several through it in parallel',
],
},
{
......
......@@ -11,6 +11,7 @@ import * as musicApi from '../api/music'
const CHAT = { id: 1, title: 'Music Sharing', type: 'group' }
const MUSIC = { message_id: 1, title: 'Invisible', artist: 'Duran Duran', duration: 200, file_name: 'invisible.mp3' }
const MUSIC_2 = { message_id: 2, title: 'Rio', artist: 'Duran Duran', duration: 210, file_name: 'rio.mp3' }
const TAG_RESPONSE = {
status: 'success',
metadata: {
......@@ -298,4 +299,40 @@ describe('TelegramLink', () => {
expect(await screen.findByText('Saved')).toBeInTheDocument()
expect(tagFromChat).toHaveBeenCalledTimes(2)
})
it('saves multiple selected songs at once', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [CHAT] })
vi.spyOn(authApi, 'getChatMusic').mockResolvedValue({ status: 'success', music: [MUSIC, MUSIC_2] })
const tagFromChat = vi.spyOn(musicApi, 'tagFromChat').mockResolvedValue(TAG_RESPONSE)
renderPage()
await userEvent.click(await screen.findByText('Music Sharing'))
await screen.findByText('Invisible')
await screen.findByText('Rio')
await userEvent.click(screen.getByLabelText('Select Invisible'))
await userEvent.click(screen.getByLabelText('Select Rio'))
expect(screen.getByText('2 selected')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Save 2 selected' }))
expect(tagFromChat).toHaveBeenCalledWith(1, 1)
expect(tagFromChat).toHaveBeenCalledWith(1, 2)
expect(tagFromChat).toHaveBeenCalledTimes(2)
await waitFor(() => expect(screen.getAllByText('Saved')).toHaveLength(2))
expect(screen.queryByText(/selected/)).not.toBeInTheDocument()
})
it('does not show a select checkbox for a song already saved', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [CHAT] })
vi.spyOn(authApi, 'getChatMusic').mockResolvedValue({ status: 'success', music: [MUSIC] })
vi.spyOn(musicApi, 'tagFromChat').mockResolvedValue(TAG_RESPONSE)
renderPage()
await userEvent.click(await screen.findByText('Music Sharing'))
await userEvent.click(await screen.findByRole('button', { name: /Save/ }))
await screen.findByText('Saved')
expect(screen.queryByLabelText('Select Invisible')).not.toBeInTheDocument()
})
})
......@@ -49,9 +49,10 @@ export function TelegramLink() {
const [musicLoading, setMusicLoading] = useState(false)
const [musicError, setMusicError] = useState<string | null>(null)
const [savingId, setSavingId] = useState<number | null>(null)
const [savingIds, setSavingIds] = useState<Set<number>>(new Set())
const [savedMeta, setSavedMeta] = useState<Record<number, TagMetadata>>({})
const [saveErrors, setSaveErrors] = useState<Record<number, string>>({})
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
const { currentSong, isPlaying, toggle } = usePlayer()
......@@ -143,15 +144,25 @@ export function TelegramLink() {
setMusicLoading(true)
setSavedMeta({})
setSaveErrors({})
setSelectedIds(new Set())
getChatMusic(chat.id)
.then((res) => setMusic(res.music))
.catch((err) => setMusicError(err instanceof ApiError ? err.message : 'Failed to load music from this chat'))
.finally(() => setMusicLoading(false))
}
function toggleSelected(messageId: number) {
setSelectedIds((prev) => {
const next = new Set(prev)
if (next.has(messageId)) next.delete(messageId)
else next.add(messageId)
return next
})
}
async function handleSave(m: ChatMusic) {
if (!selectedChat) return
setSavingId(m.message_id)
setSavingIds((prev) => new Set(prev).add(m.message_id))
setSaveErrors((prev) => {
const next = { ...prev }
delete next[m.message_id]
......@@ -166,7 +177,27 @@ export function TelegramLink() {
[m.message_id]: err instanceof ApiError ? err.message : 'Failed to save this song',
}))
} finally {
setSavingId(null)
setSavingIds((prev) => {
const next = new Set(prev)
next.delete(m.message_id)
return next
})
setSelectedIds((prev) => {
const next = new Set(prev)
next.delete(m.message_id)
return next
})
}
}
async function handleSaveSelected() {
if (!music) return
// Sequential, same reasoning as Upload's multi-file queue - /music/tag runs the same
// network- and CPU-heavy identify/tag pipeline per song, so this deliberately doesn't
// race several through it at once.
for (const m of music) {
if (!selectedIds.has(m.message_id) || savedMeta[m.message_id]) continue
await handleSave(m)
}
}
......@@ -285,14 +316,32 @@ export function TelegramLink() {
{!musicLoading && !musicError && music?.length === 0 && (
<EmptyState icon={Music2} message="No music found in this chat." />
)}
{selectedIds.size > 0 && (
<div className="sticky top-0 z-10 -mx-2 mb-2 flex items-center justify-between gap-3 bg-background/95 px-2 py-2 backdrop-blur">
<p className="text-sm text-on-surface-variant">{selectedIds.size} selected</p>
<Button size="sm" disabled={savingIds.size > 0} onClick={handleSaveSelected}>
{savingIds.size > 0 ? 'Saving…' : `Save ${selectedIds.size} selected`}
</Button>
</div>
)}
<ul className="divide-y divide-outline-variant/80">
{music?.map((m) => {
const saved = savedMeta[m.message_id]
const saveError = saveErrors[m.message_id]
const saving = savingId === m.message_id
const saving = savingIds.has(m.message_id)
const isCurrent = currentSong?.id === -m.message_id
return (
<li key={m.message_id} className="flex items-center gap-4 px-2 py-3">
{!saved && (
<input
type="checkbox"
checked={selectedIds.has(m.message_id)}
onChange={() => toggleSelected(m.message_id)}
disabled={saving}
aria-label={`Select ${m.title}`}
className="h-4 w-4 shrink-0 accent-primary"
/>
)}
<button
onClick={() => toggle(toPreviewPlayable(selectedChat.id, m))}
aria-label={isCurrent && isPlaying ? `Pause ${m.title}` : `Play 30 second preview of ${m.title}`}
......
......@@ -101,4 +101,47 @@ describe('Upload', () => {
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
it('accepts multiple files at once and tags each one independently', async () => {
const responses: Record<string, typeof TAG_RESPONSE> = {
'one.mp3': { ...TAG_RESPONSE, metadata: { ...TAG_RESPONSE.metadata, library_song_id: 1, title: 'Song One' } },
'two.mp3': { ...TAG_RESPONSE, metadata: { ...TAG_RESPONSE.metadata, library_song_id: 2, title: 'Song Two' } },
}
const uploadDirect = vi.spyOn(musicApi, 'uploadDirect').mockImplementation(async (file, onProgress) => {
onProgress?.(100)
return responses[file.name]
})
renderPage()
const files = [
new File([new Uint8Array([1])], 'one.mp3', { type: 'audio/mpeg' }),
new File([new Uint8Array([2])], 'two.mp3', { type: 'audio/mpeg' }),
]
const input = document.querySelector('input[type="file"]') as HTMLInputElement
await userEvent.upload(input, files)
expect(screen.getByText('one.mp3')).toBeInTheDocument()
expect(screen.getByText('two.mp3')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Upload 2 files' }))
expect(await screen.findByText('Song One')).toBeInTheDocument()
expect(await screen.findByText('Song Two')).toBeInTheDocument()
expect(uploadDirect).toHaveBeenCalledTimes(2)
})
it('lets a still-queued file be removed before uploading', async () => {
vi.spyOn(musicApi, 'uploadDirect')
renderPage()
const file = new File([new Uint8Array([1])], 'test.mp3', { type: 'audio/mpeg' })
const input = document.querySelector('input[type="file"]') as HTMLInputElement
await userEvent.upload(input, file)
expect(screen.getByText('test.mp3')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Remove test.mp3' }))
expect(screen.queryByText('test.mp3')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Upload/ })).not.toBeInTheDocument()
})
})
This diff is collapsed.
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