Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

generations.audio.tsx

373 lines11.8 KB

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
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
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: (
89 input: { prompt: string; duration?: number },
90 { threadId }: { threadId: string },
91 ) =>
92 generateAudioFn({
93 data: {
94 ...input,
95 provider: config.id,
96 model: selectedModel,
97 threadId,
98 },
99 }),
100 persistence: true,
101 onResult: toAudioOutput,
102 }
103 }, [mode, config.id, selectedModel])
104​
105 const hookReturn = useGenerateAudio(hookOptions)
106​
107 return (
108 <AudioGenerationUI
109 {...hookReturn}
110 config={config}
111 prompt={prompt}
112 setPrompt={setPrompt}
113 duration={duration}
114 setDuration={setDuration}
115 selectedModel={selectedModel}
116 setSelectedModel={setSelectedModel}
117 />
118 )
120​
121function AudioGenerationUI({
122 config,
123 prompt,
124 setPrompt,
125 duration,
126 setDuration,
127 selectedModel,
128 setSelectedModel,
129 generate,
130 result,
131 isLoading,
132 error,
133 reset,
134}: UseGenerateAudioReturn<AudioOutput> & {
135 config: AudioProviderConfig
136 prompt: string
137 setPrompt: (v: string) => void
138 duration: number | undefined
139 setDuration: (v: number | undefined) => void
140 selectedModel: string
141 setSelectedModel: (v: string) => void
142}) {
143 const handleGenerate = () => {
144 if (!prompt.trim()) return
145 generate({ prompt: prompt.trim(), duration })
146 }
147​
148 // Track the last object URL we created so we can revoke it when the
149 // result changes, reset is invoked, or the component unmounts.
150 const lastBlobUrlRef = useRef<string | null>(null)
151 useEffect(() => {
152 const current = result?.url
153 // Only track blob: URLs — remote URLs returned directly by providers
154 // are not ours to revoke.
155 if (current && current.startsWith('blob:')) {
156 if (lastBlobUrlRef.current && lastBlobUrlRef.current !== current) {
157 URL.revokeObjectURL(lastBlobUrlRef.current)
158 }
159 lastBlobUrlRef.current = current
160 } else if (!current && lastBlobUrlRef.current) {
161 URL.revokeObjectURL(lastBlobUrlRef.current)
162 lastBlobUrlRef.current = null
163 }
164 }, [result?.url])
165 useEffect(() => {
166 return () => {
167 if (lastBlobUrlRef.current) {
168 URL.revokeObjectURL(lastBlobUrlRef.current)
169 lastBlobUrlRef.current = null
170 }
171 }
172 }, [])
173​
174 return (
175 <div className="space-y-6">
176 <div className="space-y-2">
177 {config.models && config.models.length > 1 ? (
178 <div className="flex items-center gap-3">
179 <label
180 htmlFor="audio-model-select"
181 className="text-xs text-gray-400"
182 >
183 Model:
184 </label>
185 <select
186 id="audio-model-select"
187 data-testid="audio-model-select"
188 value={selectedModel}
189 onChange={(e) => setSelectedModel(e.target.value)}
190 disabled={isLoading}
191 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"
192 >
193 {config.models.map((m) => (
194 <option key={m.id} value={m.id}>
195 {m.label} — {m.id}
196 </option>
197 ))}
198 </select>
199 </div>
200 ) : (
201 <p className="text-xs text-gray-400">
202 Model: <span className="text-gray-200">{config.model}</span>
203 </p>
204 )}
205 <p className="text-xs text-gray-500">{config.description}</p>
206 </div>
207​
208 <div className="space-y-3">
209 <label className="text-sm text-gray-400">Prompt</label>
210 <textarea
211 data-testid="audio-prompt-input"
212 value={prompt}
213 onChange={(e) => setPrompt(e.target.value)}
214 placeholder={config.placeholder}
215 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"
216 rows={4}
217 disabled={isLoading}
218 />
219 {config.samplePrompts.length > 0 && (
220 <div className="flex flex-wrap gap-2">
221 <span className="text-xs text-gray-500 self-center">Try:</span>
222 {config.samplePrompts.map((sample) => (
223 <button
224 key={sample.label}
225 type="button"
226 onClick={() => setPrompt(sample.prompt)}
227 disabled={isLoading}
228 data-testid={`audio-sample-${sample.label
229 .toLowerCase()
230 .replace(/\s+/g, '-')}`}
231 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"
232 >
233 {sample.label}
234 </button>
235 ))}
236 </div>
237 )}
238 </div>
239​
240 {config.defaultDuration != null && (
241 <div className="space-y-3">
242 <label className="text-sm text-gray-400">
243 Duration ({duration ?? 0}s)
244 </label>
245 <input
246 data-testid="audio-duration-input"
247 type="range"
248 min={1}
249 max={60}
250 value={duration ?? config.defaultDuration}
251 onChange={(e) => setDuration(Number(e.target.value))}
252 disabled={isLoading}
253 className="w-full accent-orange-500"
254 />
255 </div>
256 )}
257​
258 <div className="flex gap-3">
259 <button
260 onClick={handleGenerate}
261 disabled={!prompt.trim() || isLoading}
262 data-testid="audio-generate-button"
263 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"
264 >
265 {isLoading ? 'Generating...' : 'Generate Audio'}
266 </button>
267 {result && (
268 <button
269 onClick={reset}
270 className="px-6 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
271 >
272 Clear
273 </button>
274 )}
275 </div>
276​
277 {error && (
278 <div
279 data-testid="audio-error"
280 className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg"
281 >
282 <p className="text-red-400 text-sm">{error.message}</p>
283 </div>
284 )}
285​
286 {result && (
287 <div className="p-4 bg-gray-800/50 border border-gray-700 rounded-lg space-y-3">
288 <p className="text-sm text-gray-400">
289 Model: <span className="text-gray-200">{result.model}</span>
290 {result.contentType != null && ` | Type: ${result.contentType}`}
291 {result.duration != null && ` | Duration: ${result.duration}s`}
292 </p>
293 <audio
294 data-testid="audio-player"
295 src={result.url}
296 controls
297 className="w-full"
298 />
299 </div>
300 )}
301 </div>
302 )
304​
305function AudioGenerationPage() {
306 const [mode, setMode] = useState<Mode>('hooks')
307 const [provider, setProvider] = useState<AudioProviderId>('gemini-lyria')
308​
309 const config = AUDIO_PROVIDERS.find((p) => p.id === provider)!
310​
311 return (
312 <div className="flex flex-col h-[calc(100vh-72px)] bg-gray-900 text-white">
313 <div className="border-b border-orange-500/20 bg-gray-800 px-6 py-4">
314 <div className="flex items-center justify-between">
315 <div>
316 <h2 className="text-xl font-semibold">Audio Generation</h2>
317 <p className="text-sm text-gray-400 mt-1">
318 Generate music and sound effects from text prompts.
319 </p>
320 </div>
321 <div className="flex gap-1 bg-gray-900/50 rounded-lg p-1">
322 {(['hooks', 'server-fn'] as const).map((m) => (
323 <button
324 key={m}
325 onClick={() => setMode(m)}
326 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
327 mode === m
328 ? 'bg-orange-600 text-white'
329 : 'text-gray-400 hover:text-white'
330 }`}
331 >
332 {m === 'server-fn' ? 'Server Fn' : 'Hooks'}
333 </button>
334 ))}
335 </div>
336 </div>
337 </div>
338​
339 <div className="border-b border-orange-500/20 bg-gray-800/60 px-6 py-3">
340 <div className="flex flex-wrap gap-2">
341 {AUDIO_PROVIDERS.map((p) => (
342 <button
343 key={p.id}
344 data-testid={`provider-tab-${p.id}`}
345 onClick={() => setProvider(p.id)}
346 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
347 provider === p.id
348 ? 'bg-orange-500/80 text-white'
349 : 'bg-gray-900 text-gray-300 hover:bg-gray-700'
350 }`}
351 >
352 {p.label}
353 </button>
354 ))}
355 </div>
356 </div>
357​
358 <div className="flex-1 overflow-y-auto p-6">
359 <div className="max-w-2xl mx-auto">
360 <AudioGenerationForm
361 key={`${mode}-${config.id}`}
362 mode={mode}
363 config={config}
364 />
365 </div>
366 </div>
367 </div>
368 )
370​
371export const Route = createFileRoute('/generations/audio')({
372 component: AudioGenerationPage,
373})