Open History to see the last commit
1import { useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { useGenerateAudio } from '@tanstack/ai-react'
4import type { UseGenerateAudioReturn } from '@tanstack/ai-react'
5import { fetchServerSentEvents } from '@tanstack/ai-client'
6import type { AudioGenerationResult } from '@tanstack/ai'
7import { generateAudioFn } from '../lib/server-fns'
8import {
9 AUDIO_PROVIDERS,
10 type AudioProviderConfig,
11 type AudioProviderId,
12} from '../lib/audio-providers'
13
14type Mode = 'hooks' | 'server-fn'
15
16// Persist each variant's lightweight resume snapshot across reloads.
17
18interface AudioOutput {
19 url: string
20 contentType?: string
21 duration?: number
22 model: string
23}
24
25/**
26 * Map an AudioGenerationResult to the UI-friendly shape. Returns `null`
27 * when the result has neither `url` nor `b64Json` — per the `onResult`
28 * contract, a `null` return tells the hook to keep the previous result
29 * and the real failure is surfaced via `onError` / the hook's error state.
30 */
31function toAudioOutput(raw: AudioGenerationResult): AudioOutput | null {
32 const { audio } = raw
33 if (audio.url) {
34 return {
35 url: audio.url,
36 contentType: audio.contentType,
37 duration: audio.duration,
38 model: raw.model,
39 }
40 }
41 if (audio.b64Json) {
42 const binary = atob(audio.b64Json)
43 const bytes = new Uint8Array(binary.length)
44 for (let i = 0; i < binary.length; i++) {
45 bytes[i] = binary.charCodeAt(i)
46 }
47 const blob = new Blob([bytes], {
48 type: audio.contentType ?? 'audio/mpeg',
49 })
50 return {
51 url: URL.createObjectURL(blob),
52 contentType: audio.contentType,
53 duration: audio.duration,
54 model: raw.model,
55 }
56 }
57 // Don't throw — that bypasses the hook's error plumbing. Return null so
58 // the hook keeps the previous result unchanged; callers can rely on the
59 // `error` state (populated via `onError`) if they want to surface this.
60 return null
61}
62
63function AudioGenerationForm({
64 mode,
65 config,
66}: {
67 mode: Mode
68 config: AudioProviderConfig
69}) {
70 const [prompt, setPrompt] = useState('')
71 const [duration, setDuration] = useState<number | undefined>(
72 config.defaultDuration,
73 )
74 const [selectedModel, setSelectedModel] = useState<string>(config.model)
75
76 const hookOptions = useMemo(() => {
77 if (mode === 'hooks') {
78 return {
79 threadId: `audio:${mode}:${config.id}`,
80 connection: fetchServerSentEvents('/api/generate/audio'),
81 body: { provider: config.id, model: selectedModel },
82 persistence: true,
83 onResult: toAudioOutput,
84 }
85 }
86 return {
87 threadId: `audio:${mode}:${config.id}`,
88 fetcher: (input: { prompt: string; duration?: number }) =>
89 generateAudioFn({
90 data: { ...input, provider: config.id, model: selectedModel },
91 }),
92 persistence: true,
93 onResult: toAudioOutput,
94 }
95 }, [mode, config.id, selectedModel])
96
97 const hookReturn = useGenerateAudio(hookOptions)
98
99 return (
100 <AudioGenerationUI
101 {...hookReturn}
102 config={config}
103 prompt={prompt}
104 setPrompt={setPrompt}
105 duration={duration}
106 setDuration={setDuration}
107 selectedModel={selectedModel}
108 setSelectedModel={setSelectedModel}
109 />
110 )
111}
112
113function AudioGenerationUI({
114 config,
115 prompt,
116 setPrompt,
117 duration,
118 setDuration,
119 selectedModel,
120 setSelectedModel,
121 generate,
122 result,
123 isLoading,
124 error,
125 reset,
126}: UseGenerateAudioReturn<AudioOutput> & {
127 config: AudioProviderConfig
128 prompt: string
129 setPrompt: (v: string) => void
130 duration: number | undefined
131 setDuration: (v: number | undefined) => void
132 selectedModel: string
133 setSelectedModel: (v: string) => void
134}) {
135 const handleGenerate = () => {
136 if (!prompt.trim()) return
137 generate({ prompt: prompt.trim(), duration })
138 }
139
140 // Track the last object URL we created so we can revoke it when the
141 // result changes, reset is invoked, or the component unmounts.
142 const lastBlobUrlRef = useRef<string | null>(null)
143 useEffect(() => {
144 const current = result?.url
145 // Only track blob: URLs — remote URLs returned directly by providers
146 // are not ours to revoke.
147 if (current && current.startsWith('blob:')) {
148 if (lastBlobUrlRef.current && lastBlobUrlRef.current !== current) {
149 URL.revokeObjectURL(lastBlobUrlRef.current)
150 }
151 lastBlobUrlRef.current = current
152 } else if (!current && lastBlobUrlRef.current) {
153 URL.revokeObjectURL(lastBlobUrlRef.current)
154 lastBlobUrlRef.current = null
155 }
156 }, [result?.url])
157 useEffect(() => {
158 return () => {
159 if (lastBlobUrlRef.current) {
160 URL.revokeObjectURL(lastBlobUrlRef.current)
161 lastBlobUrlRef.current = null
162 }
163 }
164 }, [])
165
166 return (
167 <div className="space-y-6">
168 <div className="space-y-2">
169 {config.models && config.models.length > 1 ? (
170 <div className="flex items-center gap-3">
171 <label
172 htmlFor="audio-model-select"
173 className="text-xs text-gray-400"
174 >
175 Model:
176 </label>
177 <select
178 id="audio-model-select"
179 data-testid="audio-model-select"
180 value={selectedModel}
181 onChange={(e) => setSelectedModel(e.target.value)}
182 disabled={isLoading}
183 className="flex-1 rounded-md border border-orange-500/20 bg-gray-800/50 px-2 py-1 text-xs text-gray-200 focus:outline-none focus:ring-2 focus:ring-orange-500/50 disabled:opacity-50"
184 >
185 {config.models.map((m) => (
186 <option key={m.id} value={m.id}>
187 {m.label} — {m.id}
188 </option>
189 ))}
190 </select>
191 </div>
192 ) : (
193 <p className="text-xs text-gray-400">
194 Model: <span className="text-gray-200">{config.model}</span>
195 </p>
196 )}
197 <p className="text-xs text-gray-500">{config.description}</p>
198 </div>
199
200 <div className="space-y-3">
201 <label className="text-sm text-gray-400">Prompt</label>
202 <textarea
203 data-testid="audio-prompt-input"
204 value={prompt}
205 onChange={(e) => setPrompt(e.target.value)}
206 placeholder={config.placeholder}
207 className="w-full rounded-lg border border-orange-500/20 bg-gray-800/50 px-4 py-3 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-orange-500/50 resize-none"
208 rows={4}
209 disabled={isLoading}
210 />
211 {config.samplePrompts.length > 0 && (
212 <div className="flex flex-wrap gap-2">
213 <span className="text-xs text-gray-500 self-center">Try:</span>
214 {config.samplePrompts.map((sample) => (
215 <button
216 key={sample.label}
217 type="button"
218 onClick={() => setPrompt(sample.prompt)}
219 disabled={isLoading}
220 data-testid={`audio-sample-${sample.label
221 .toLowerCase()
222 .replace(/\s+/g, '-')}`}
223 className="px-3 py-1 rounded-full border border-orange-500/30 bg-orange-500/10 text-xs text-orange-200 hover:bg-orange-500/20 hover:border-orange-500/50 disabled:opacity-50 transition-colors"
224 >
225 {sample.label}
226 </button>
227 ))}
228 </div>
229 )}
230 </div>
231
232 {config.defaultDuration != null && (
233 <div className="space-y-3">
234 <label className="text-sm text-gray-400">
235 Duration ({duration ?? 0}s)
236 </label>
237 <input
238 data-testid="audio-duration-input"
239 type="range"
240 min={1}
241 max={60}
242 value={duration ?? config.defaultDuration}
243 onChange={(e) => setDuration(Number(e.target.value))}
244 disabled={isLoading}
245 className="w-full accent-orange-500"
246 />
247 </div>
248 )}
249
250 <div className="flex gap-3">
251 <button
252 onClick={handleGenerate}
253 disabled={!prompt.trim() || isLoading}
254 data-testid="audio-generate-button"
255 className="px-6 py-2 bg-orange-600 hover:bg-orange-700 disabled:bg-gray-700 disabled:text-gray-500 text-white rounded-lg text-sm font-medium transition-colors"
256 >
257 {isLoading ? 'Generating...' : 'Generate Audio'}
258 </button>
259 {result && (
260 <button
261 onClick={reset}
262 className="px-6 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
263 >
264 Clear
265 </button>
266 )}
267 </div>
268
269 {error && (
270 <div
271 data-testid="audio-error"
272 className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg"
273 >
274 <p className="text-red-400 text-sm">{error.message}</p>
275 </div>
276 )}
277
278 {result && (
279 <div className="p-4 bg-gray-800/50 border border-gray-700 rounded-lg space-y-3">
280 <p className="text-sm text-gray-400">
281 Model: <span className="text-gray-200">{result.model}</span>
282 {result.contentType != null && ` | Type: ${result.contentType}`}
283 {result.duration != null && ` | Duration: ${result.duration}s`}
284 </p>
285 <audio
286 data-testid="audio-player"
287 src={result.url}
288 controls
289 className="w-full"
290 />
291 </div>
292 )}
293 </div>
294 )
295}
296
297function AudioGenerationPage() {
298 const [mode, setMode] = useState<Mode>('hooks')
299 const [provider, setProvider] = useState<AudioProviderId>('gemini-lyria')
300
301 const config = AUDIO_PROVIDERS.find((p) => p.id === provider)!
302
303 return (
304 <div className="flex flex-col h-[calc(100vh-72px)] bg-gray-900 text-white">
305 <div className="border-b border-orange-500/20 bg-gray-800 px-6 py-4">
306 <div className="flex items-center justify-between">
307 <div>
308 <h2 className="text-xl font-semibold">Audio Generation</h2>
309 <p className="text-sm text-gray-400 mt-1">
310 Generate music and sound effects from text prompts.
311 </p>
312 </div>
313 <div className="flex gap-1 bg-gray-900/50 rounded-lg p-1">
314 {(['hooks', 'server-fn'] as const).map((m) => (
315 <button
316 key={m}
317 onClick={() => setMode(m)}
318 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
319 mode === m
320 ? 'bg-orange-600 text-white'
321 : 'text-gray-400 hover:text-white'
322 }`}
323 >
324 {m === 'server-fn' ? 'Server Fn' : 'Hooks'}
325 </button>
326 ))}
327 </div>
328 </div>
329 </div>
330
331 <div className="border-b border-orange-500/20 bg-gray-800/60 px-6 py-3">
332 <div className="flex flex-wrap gap-2">
333 {AUDIO_PROVIDERS.map((p) => (
334 <button
335 key={p.id}
336 data-testid={`provider-tab-${p.id}`}
337 onClick={() => setProvider(p.id)}
338 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
339 provider === p.id
340 ? 'bg-orange-500/80 text-white'
341 : 'bg-gray-900 text-gray-300 hover:bg-gray-700'
342 }`}
343 >
344 {p.label}
345 </button>
346 ))}
347 </div>
348 </div>
349
350 <div className="flex-1 overflow-y-auto p-6">
351 <div className="max-w-2xl mx-auto">
352 <AudioGenerationForm
353 key={`${mode}-${config.id}`}
354 mode={mode}
355 config={config}
356 />
357 </div>
358 </div>
359 </div>
360 )
361}
362
363export const Route = createFileRoute('/generations/audio')({
364 component: AudioGenerationPage,
365})