Commit 69fd45e8 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add a Telegram linking page so the chat-scan feature is actually testable

New /telegram-link page (in nav): phone number -> code -> link, then
browse your linked Telegram chats and the music found in each. On load it
checks whether you're already linked (a clean 400 from GET
/auth/telegram/chats means not yet) and skips straight to the chat list
if so, instead of always showing the phone form.

Added getChatMusic() to api/auth.ts to round out the client (getChats
already existed, unused by any page until now).

Built this specifically so the just-fixed backend linking flow (see
stax_backend_api: /auth/telegram/login now actually attaches to the
caller instead of creating a separate identity) has something to actually
click through and test with a real account, rather than requiring raw API
calls. Updated the Roadmap to reflect this - Telegram linking UI moves
from Frontend to-do into Frontend done.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 9ca024f6
Pipeline #1103 canceled with stage
import { Navigate, Route, Routes } from 'react-router-dom'
import { Library } from './pages/Library'
import { Playlists } from './pages/Playlists'
import { TelegramLink } from './pages/TelegramLink'
import { Upload } from './pages/Upload'
import { Discovery } from './pages/Discovery'
import { Rooms } from './pages/Rooms'
......@@ -26,6 +27,7 @@ export function App() {
<Route path="/login" element={<Login />} />
<Route path="/library" element={protect(<Library />)} />
<Route path="/playlists" element={protect(<Playlists />)} />
<Route path="/telegram-link" element={protect(<TelegramLink />)} />
<Route path="/upload" element={protect(<Upload />)} />
<Route path="/discovery" element={protect(<Discovery />)} />
<Route path="/rooms" element={protect(<Rooms />)} />
......
......@@ -64,6 +64,18 @@ export function getChats() {
return apiFetch<{ status: string; chats: Chat[] }>('/auth/telegram/chats')
}
export interface ChatMusic {
message_id: number
title: string
artist: string
duration: number
file_name: string
}
export function getChatMusic(chatId: number) {
return apiFetch<{ status: string; music: ChatMusic[] }>(`/auth/telegram/chats/${chatId}/music`)
}
export type UserRole = 'user' | 'business_admin' | 'super_admin'
export interface CurrentUser {
......
......@@ -5,6 +5,7 @@ import {
Disc3,
Headphones,
Library,
Link2,
ListMusic,
LogOut,
Map,
......@@ -36,6 +37,7 @@ const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/remix', label: 'Remix', icon: Wand2 },
{ to: '/nearby', label: 'Soundmarks', icon: MapPin },
{ to: '/drops', label: 'Drops', icon: MapPinned },
{ to: '/telegram-link', label: 'Telegram', icon: Link2 },
]
export function Layout({ title, children }: { title: string; children: ReactNode }) {
......
......@@ -43,7 +43,7 @@ const BACKEND_DONE: DoneGroup[] = [
area: 'Auth',
items: [
'Username/password register, login, refresh (rotating), logout (real server-side revoke) - PBKDF2, stdlib only',
'Telegram phone/code account-linking (/auth/telegram/*), separate from primary login',
'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)',
'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',
],
},
......@@ -124,7 +124,14 @@ const BACKEND_TODO: WorkItem[] = [
// --- Frontend ---
const FRONTEND_DONE: DoneGroup[] = [
{ area: 'Auth', items: ['Login page: username/password + register, toggled in place', 'Route guards redirect to /login when signed out instead of showing a blank page'] },
{
area: 'Auth',
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, then browse linked chats and the music found in each',
],
},
{ area: 'Soundmarks', items: ['Nearby page: dark-themed map, tier-aware display, proposals + voting UI'] },
{ area: 'Rooms', items: ['RoomView: chat, reactions, DJ song picker, pass-the-aux controls, now-playing card'] },
{ area: 'Channels', items: ['List + follow/unfollow UI only - vibe sets/stories/showcase have no UI yet'] },
......@@ -161,11 +168,6 @@ const FRONTEND_TODO: WorkItem[] = [
status: 'ready',
note: 'POST /library/search already works, unused from the frontend.',
},
{
item: 'Telegram linking UI (phone + code, attaches to the logged-in user)',
status: 'ready',
note: '/auth/telegram/request_code and /auth/telegram/login both already exist and work.',
},
{
item: 'Test coverage for Upload, Discovery, and Remix pages',
status: 'ready',
......@@ -263,8 +265,8 @@ export function Roadmap() {
{[
['9', 'Feature areas'],
['0', 'Critical security gaps'],
['227', 'Backend tests'],
['168', 'Frontend tests'],
['229', 'Backend tests'],
['178', 'Frontend tests'],
['4', 'Pages w/ zero tests'],
].map(([n, l]) => (
<div key={l}>
......
import { render, screen } 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 { TelegramLink } from './TelegramLink'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import { ApiError } from '../api/client'
import * as authApi from '../api/auth'
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' }
function renderPage() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<TelegramLink />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('TelegramLink', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows the phone form when no Telegram session is linked yet', async () => {
vi.spyOn(authApi, 'getChats').mockRejectedValue(new ApiError(400, 'No linked Telegram session', null))
renderPage()
expect(await screen.findByLabelText('Phone number')).toBeInTheDocument()
})
it('goes straight to the chat list when already linked', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [CHAT] })
renderPage()
expect(await screen.findByText('Music Sharing')).toBeInTheDocument()
expect(screen.queryByLabelText('Phone number')).not.toBeInTheDocument()
})
it('sends a code and moves to the verification step', async () => {
vi.spyOn(authApi, 'getChats').mockRejectedValue(new ApiError(400, 'No linked Telegram session', null))
const requestTelegramCode = vi.spyOn(authApi, 'requestTelegramCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
expect(requestTelegramCode).toHaveBeenCalledWith('+15551234567')
expect(await screen.findByLabelText('Verification code')).toBeInTheDocument()
expect(screen.getByText(/Enter the code sent to \+15551234567/)).toBeInTheDocument()
})
it('verifies the code, links the account, and shows the chat list', async () => {
vi.spyOn(authApi, 'getChats')
.mockRejectedValueOnce(new ApiError(400, 'No linked Telegram session', null))
.mockResolvedValueOnce({ status: 'success', chats: [CHAT] })
vi.spyOn(authApi, 'requestTelegramCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
const linkTelegram = vi.spyOn(authApi, 'linkTelegram').mockResolvedValue({ status: 'success', phone_number: '+15551234567' })
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '12345')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
expect(linkTelegram).toHaveBeenCalledWith('+15551234567', 'hash-123', '12345')
expect(await screen.findByText('Music Sharing')).toBeInTheDocument()
})
it('shows the backend error when the code is wrong, without leaving the code step', async () => {
vi.spyOn(authApi, 'getChats').mockRejectedValue(new ApiError(400, 'No linked Telegram session', null))
vi.spyOn(authApi, 'requestTelegramCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
vi.spyOn(authApi, 'linkTelegram').mockRejectedValue(new ApiError(400, 'Invalid code', null))
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await userEvent.type(await screen.findByLabelText('Verification code'), '00000')
await userEvent.click(screen.getByRole('button', { name: 'Verify & link' }))
expect(await screen.findByText('Invalid code')).toBeInTheDocument()
expect(screen.queryByText('Music Sharing')).not.toBeInTheDocument()
})
it('lets you go back and use a different number', async () => {
vi.spyOn(authApi, 'getChats').mockRejectedValue(new ApiError(400, 'No linked Telegram session', null))
vi.spyOn(authApi, 'requestTelegramCode').mockResolvedValue({
status: 'success',
data: { phone_code_hash: 'hash-123', is_registered: true },
})
renderPage()
await userEvent.type(await screen.findByLabelText('Phone number'), '+15551234567')
await userEvent.click(screen.getByRole('button', { name: 'Send code' }))
await screen.findByLabelText('Verification code')
await userEvent.click(screen.getByRole('button', { name: 'Use a different number' }))
expect(screen.getByLabelText('Phone number')).toBeInTheDocument()
})
it('shows an empty state when there are no chats', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [] })
renderPage()
expect(await screen.findByText('No chats found.')).toBeInTheDocument()
})
it('opens a chat and shows the music found in it', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [CHAT] })
const getChatMusic = vi.spyOn(authApi, 'getChatMusic').mockResolvedValue({ status: 'success', music: [MUSIC] })
renderPage()
await userEvent.click(await screen.findByText('Music Sharing'))
expect(getChatMusic).toHaveBeenCalledWith(1)
expect(await screen.findByText('Invisible')).toBeInTheDocument()
expect(screen.getByText('Duran Duran')).toBeInTheDocument()
})
it('shows an empty state when a chat has no music', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [CHAT] })
vi.spyOn(authApi, 'getChatMusic').mockResolvedValue({ status: 'success', music: [] })
renderPage()
await userEvent.click(await screen.findByText('Music Sharing'))
expect(await screen.findByText('No music found in this chat.')).toBeInTheDocument()
})
it('goes back from a chat to the chat list', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [CHAT] })
vi.spyOn(authApi, 'getChatMusic').mockResolvedValue({ status: 'success', music: [MUSIC] })
renderPage()
await userEvent.click(await screen.findByText('Music Sharing'))
await screen.findByText('Invisible')
await userEvent.click(screen.getByText('← Chats'))
expect(await screen.findByText('Linked. Tap a chat to see the music found in it.')).toBeInTheDocument()
})
})
import { useEffect, useState } from 'react'
import { MessageCircle, Music2 } from 'lucide-react'
import {
getChatMusic,
getChats,
linkTelegram,
requestTelegramCode,
type Chat,
type ChatMusic,
} from '../api/auth'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
type Step = 'checking' | 'phone' | 'code' | 'linked'
export function TelegramLink() {
const [step, setStep] = useState<Step>('checking')
const [chats, setChats] = useState<Chat[]>([])
const [chatsError, setChatsError] = useState<string | null>(null)
const [phoneNumber, setPhoneNumber] = useState('')
const [phoneCodeHash, setPhoneCodeHash] = useState('')
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const [selectedChat, setSelectedChat] = useState<Chat | null>(null)
const [music, setMusic] = useState<ChatMusic[] | null>(null)
const [musicLoading, setMusicLoading] = useState(false)
const [musicError, setMusicError] = useState<string | null>(null)
function loadChats() {
setChatsError(null)
getChats()
.then((res) => {
setChats(res.chats)
setStep('linked')
})
.catch((err) => {
// "No linked Telegram session" (400) just means: haven't linked yet, show the
// phone/code form instead of treating this as a real error.
if (err instanceof ApiError && err.status === 400) {
setStep('phone')
} else {
setChatsError(err instanceof ApiError ? err.message : 'Failed to load Telegram chats')
setStep('phone')
}
})
}
useEffect(() => {
loadChats()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
async function handleSendCode(e: React.FormEvent) {
e.preventDefault()
if (!phoneNumber.trim()) return
setBusy(true)
setError(null)
try {
const res = await requestTelegramCode(phoneNumber.trim())
setPhoneCodeHash(res.data.phone_code_hash)
setStep('code')
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to send a code. Please try again.')
} finally {
setBusy(false)
}
}
async function handleVerifyCode(e: React.FormEvent) {
e.preventDefault()
if (!code.trim()) return
setBusy(true)
setError(null)
try {
await linkTelegram(phoneNumber.trim(), phoneCodeHash, code.trim())
loadChats()
} catch (err) {
setError(err instanceof ApiError ? err.message : "That code didn't work. Please try again.")
} finally {
setBusy(false)
}
}
function handleChangeNumber() {
setStep('phone')
setCode('')
setError(null)
}
function openChat(chat: Chat) {
setSelectedChat(chat)
setMusic(null)
setMusicError(null)
setMusicLoading(true)
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))
}
if (step === 'checking') {
return (
<Layout title="Link Telegram">
<div className="space-y-3">
<SkeletonRow />
<SkeletonRow />
</div>
</Layout>
)
}
if (step === 'phone' || step === 'code') {
return (
<Layout title="Link Telegram">
<div className="mx-auto w-full max-w-sm">
<p className="mb-6 text-sm text-neutral-400">
{step === 'phone'
? 'Link your Telegram account to scan your chats for music.'
: `Enter the code sent to ${phoneNumber}.`}
</p>
{chatsError && <p className="mb-4 text-sm text-red-400">{chatsError}</p>}
{step === 'phone' ? (
<form onSubmit={handleSendCode} className="space-y-3">
<Input
type="tel"
inputMode="tel"
autoComplete="tel"
autoFocus
placeholder="+1 555 123 4567"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
aria-label="Phone number"
/>
{error && <p className="text-sm text-red-400">{error}</p>}
<Button type="submit" disabled={busy || !phoneNumber.trim()} className="w-full">
{busy ? 'Sending code…' : 'Send code'}
</Button>
</form>
) : (
<form onSubmit={handleVerifyCode} className="space-y-3">
<Input
type="text"
inputMode="numeric"
autoComplete="one-time-code"
autoFocus
placeholder="12345"
value={code}
onChange={(e) => setCode(e.target.value)}
aria-label="Verification code"
/>
{error && <p className="text-sm text-red-400">{error}</p>}
<Button type="submit" disabled={busy || !code.trim()} className="w-full">
{busy ? 'Verifying…' : 'Verify & link'}
</Button>
<button
type="button"
onClick={handleChangeNumber}
className="w-full text-center text-sm text-neutral-500 transition-colors hover:text-neutral-300"
>
Use a different number
</button>
</form>
)}
</div>
</Layout>
)
}
if (selectedChat) {
return (
<Layout title={selectedChat.title}>
<button
onClick={() => setSelectedChat(null)}
className="mb-4 text-sm text-neutral-400 transition-colors hover:text-white"
>
← Chats
</button>
{musicLoading && (
<div className="space-y-3">
<SkeletonRow />
<SkeletonRow />
</div>
)}
{musicError && <p className="text-sm text-red-400">{musicError}</p>}
{!musicLoading && !musicError && music?.length === 0 && (
<EmptyState icon={Music2} message="No music found in this chat." />
)}
<ul className="divide-y divide-neutral-800/80">
{music?.map((m) => (
<li key={m.message_id} className="flex items-center gap-4 px-2 py-3">
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-white">{m.title}</p>
<p className="truncate text-sm text-neutral-400">{m.artist}</p>
</div>
</li>
))}
</ul>
</Layout>
)
}
return (
<Layout title="Telegram Chats">
<p className="mb-4 text-sm text-neutral-400">Linked. Tap a chat to see the music found in it.</p>
{chats.length === 0 && <EmptyState icon={MessageCircle} message="No chats found." />}
<ul className="divide-y divide-neutral-800/80">
{chats.map((chat) => (
<li key={chat.id}>
<button
onClick={() => openChat(chat)}
className="-mx-2 flex w-full items-center gap-4 rounded-lg px-2 py-3 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<MessageCircle size={18} strokeWidth={1.75} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-white">{chat.title}</p>
<p className="truncate text-sm text-neutral-400">{chat.type}</p>
</div>
</button>
</li>
))}
</ul>
</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