Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { useState } from 'react'
3import {
4 fetchServerSentEvents,
5 useGenerateAudio,
6 useGenerateImage,
7 useGenerateSpeech,
8 useGenerateVideo,
9 useGeneration,
10 useSummarize,
11 useTranscription,
12} from '@tanstack/ai-react'
13import { DevtoolsHarness } from '@/components/DevtoolsHarness'
14import { parseDevtoolsRouteSearch } from '@/lib/devtools-test'
15import type {
16 AudioGenerationResult,
17 ImageGenerationResult,
18 TTSResult,
19} from '@tanstack/ai'
20
21export const Route = createFileRoute('/devtools-generation-hooks')({
22 component: DevtoolsGenerationHooksRoute,
23 validateSearch: parseDevtoolsRouteSearch,
24})
25
26const TEST_AUDIO_BASE64 = 'data:audio/mpeg;base64,SGVsbG8='
27const AUDIO_PROMPT = '[music] an upbeat lo-fi beat for the guitar store'
28const IMAGE_PROMPT = 'a guitar in a music store'
29const SPEECH_TEXT = 'welcome to the guitar store'
30const SUMMARY_TEXT =
31 '[summarize] The Fender Stratocaster is a versatile electric guitar'
32const VIDEO_PROMPT = 'a guitar being played in a store'
33const CUSTOM_GENERATION_DEVTOOLS = {
34 name: 'Custom Generation',
35 framework: 'vue',
36 hookName: 'somethingElse',
37 outputKind: 'text' as const,
38}
39
40function DevtoolsGenerationHooksRoute() {
41 const { testId, aimockPort } = Route.useSearch()
42 const sharedBody = { testId, aimockPort }
43 const [customGenerationMounted, setCustomGenerationMounted] = useState(false)
44
45 const image = useGenerateImage({
46 threadId: 'generation-hooks:useGenerateImage',
47 connection: fetchServerSentEvents('/api/image'),
48 body: { ...sharedBody, provider: 'openai' },
49 devtools: { name: 'Image Studio' },
50 onResult: duplicateSingleImageResult,
51 })
52 const audio = useGenerateAudio({
53 threadId: 'generation-hooks:useGenerateAudio',
54 fetcher: async (input) => {
55 const response = await fetch('/api/audio', {
56 method: 'POST',
57 headers: { 'Content-Type': 'application/json' },
58 body: JSON.stringify({
59 data: {
60 ...sharedBody,
61 ...input,
62 provider: 'elevenlabs',
63 feature: 'audio-gen',
64 },
65 }),
66 })
67 const payload: { result: AudioGenerationResult } = await response.json()
68 return payload.result
69 },
70 devtools: { name: 'Audio Studio' },
71 onResult: normalizeAudioResult,
72 })
73 const speech = useGenerateSpeech({
74 threadId: 'generation-hooks:useGenerateSpeech',
75 connection: fetchServerSentEvents('/api/tts'),
76 body: { ...sharedBody, provider: 'openai' },
77 devtools: { name: 'Speech Studio' },
78 onResult: normalizeSpeechResult,
79 })
80 const transcription = useTranscription({
81 threadId: 'generation-hooks:useTranscription',
82 connection: fetchServerSentEvents('/api/transcription'),
83 body: { ...sharedBody, provider: 'openai' },
84 devtools: { name: 'Transcription Studio' },
85 })
86 const summarize = useSummarize({
87 threadId: 'generation-hooks:useSummarize',
88 connection: fetchServerSentEvents('/api/summarize'),
89 body: { ...sharedBody, provider: 'openai', stream: true },
90 devtools: { name: 'Summary Studio' },
91 })
92 const video = useGenerateVideo({
93 threadId: 'generation-hooks:useGenerateVideo',
94 connection: fetchServerSentEvents('/api/video'),
95 body: { ...sharedBody, provider: 'openai' },
96 devtools: { name: 'Video Studio' },
97 })
98
99 const hooks = [
100 {
101 hookName: 'useGenerateImage',
102 label: 'Image Studio',
103 status: image.status,
104 isLoading: image.isLoading,
105 outputCount: image.result?.images.length ?? 0,
106 resultText: image.result ? `${image.result.images.length} images` : '',
107 run: () => image.generate({ prompt: IMAGE_PROMPT, numberOfImages: 2 }),
108 stop: image.stop,
109 reset: image.reset,
110 preview: image.result?.images.map((item, index) => (
111 <img
112 key={index}
113 data-testid="generation-app-image"
114 alt={`generated image ${index + 1}`}
115 src={item.url ?? `data:image/png;base64,${item.b64Json}`}
116 className="h-20 w-20 rounded object-cover"
117 />
118 )),
119 },
120 {
121 hookName: 'useGenerateAudio',
122 label: 'Audio Studio',
123 status: audio.status,
124 isLoading: audio.isLoading,
125 outputCount: audio.result ? 1 : 0,
126 resultText: audio.result?.audio.duration
127 ? `${audio.result.audio.duration}s`
128 : '',
129 run: () => audio.generate({ prompt: AUDIO_PROMPT, duration: 1 }),
130 stop: audio.stop,
131 reset: audio.reset,
132 preview: audio.result ? (
133 <audio
134 data-testid="generation-app-audio"
135 src={audioSource(audio.result.audio)}
136 controls
137 />
138 ) : null,
139 },
140 {
141 hookName: 'useGenerateSpeech',
142 label: 'Speech Studio',
143 status: speech.status,
144 isLoading: speech.isLoading,
145 outputCount: speech.result ? 1 : 0,
146 resultText: speech.result?.duration ? `${speech.result.duration}s` : '',
147 run: () =>
148 speech.generate({ text: SPEECH_TEXT, voice: 'alloy', format: 'wav' }),
149 stop: speech.stop,
150 reset: speech.reset,
151 preview: speech.result ? (
152 <audio
153 data-testid="generation-app-speech"
154 src={`data:${speech.result.contentType ?? 'audio/wav'};base64,${
155 speech.result.audio
156 }`}
157 controls
158 />
159 ) : null,
160 },
161 {
162 hookName: 'useTranscription',
163 label: 'Transcription Studio',
164 status: transcription.status,
165 isLoading: transcription.isLoading,
166 outputCount: transcription.result ? 1 : 0,
167 resultText: transcription.result?.text ?? '',
168 run: () =>
169 transcription.generate({ audio: TEST_AUDIO_BASE64, language: 'en' }),
170 stop: transcription.stop,
171 reset: transcription.reset,
172 preview: transcription.result ? (
173 <p data-testid="generation-app-transcription">
174 {transcription.result.text}
175 </p>
176 ) : null,
177 },
178 {
179 hookName: 'useSummarize',
180 label: 'Summary Studio',
181 status: summarize.status,
182 isLoading: summarize.isLoading,
183 outputCount: summarize.result ? 1 : 0,
184 resultText: summarize.result?.summary ?? '',
185 run: () =>
186 summarize.generate({
187 text: SUMMARY_TEXT,
188 style: 'concise',
189 maxLength: 120,
190 }),
191 stop: summarize.stop,
192 reset: summarize.reset,
193 preview: summarize.result ? (
194 <p data-testid="generation-app-summary">{summarize.result.summary}</p>
195 ) : null,
196 },
197 {
198 hookName: 'useGenerateVideo',
199 label: 'Video Studio',
200 status: video.status,
201 isLoading: video.isLoading,
202 outputCount: video.result ? 1 : 0,
203 resultText: video.videoStatus?.status ?? video.result?.status ?? '',
204 run: () => video.generate({ prompt: VIDEO_PROMPT, duration: 4 }),
205 stop: video.stop,
206 reset: video.reset,
207 preview: video.result ? (
208 <video
209 data-testid="generation-app-video"
210 src={video.result.url}
211 controls
212 className="h-24 w-36 rounded bg-black"
213 />
214 ) : null,
215 },
216 ]
217
218 const runAllHooks = async () => {
219 for (const hook of hooks) {
220 await hook.run()
221 }
222 }
223
224 return (
225 <DevtoolsHarness>
226 <div className="space-y-4">
227 <div className="flex flex-wrap gap-2">
228 <button
229 type="button"
230 data-testid="run-all-generation-hooks"
231 className="rounded bg-orange-500 px-3 py-2 text-sm font-medium text-white"
232 onClick={() => {
233 void runAllHooks()
234 }}
235 >
236 Run All
237 </button>
238 <button
239 type="button"
240 data-testid="mount-custom-generation"
241 className="rounded border border-gray-700 px-3 py-2 text-sm text-gray-200"
242 onClick={() => setCustomGenerationMounted(true)}
243 >
244 Mount Custom Generation
245 </button>
246 </div>
247 {customGenerationMounted ? <CustomGenerationIdentityProbe /> : null}
248 <div className="grid gap-3 md:grid-cols-2">
249 {hooks.map((hook) => (
250 <section
251 key={hook.hookName}
252 data-testid="generation-hook-card"
253 data-hook-name={hook.hookName}
254 className="rounded border border-gray-800 bg-gray-900/40 p-3"
255 >
256 <div className="flex items-start justify-between gap-3">
257 <div>
258 <div className="text-sm font-semibold text-orange-300">
259 {hook.label}
260 </div>
261 <div className="font-mono text-xs text-gray-500">
262 generation-hooks:{hook.hookName}
263 </div>
264 </div>
265 <div
266 data-testid="generation-hook-status"
267 className="text-xs text-gray-400"
268 >
269 {hook.isLoading ? 'loading' : hook.status}
270 </div>
271 </div>
272 <div
273 data-testid="generation-hook-output-count"
274 className="mt-2 text-xs text-gray-400"
275 >
276 {hook.outputCount}
277 </div>
278 <div
279 data-testid="generation-hook-result"
280 className="mt-2 min-h-6 text-sm text-gray-200"
281 >
282 {hook.resultText}
283 </div>
284 <div className="mt-3 flex flex-wrap gap-2">
285 <button
286 type="button"
287 data-testid={`run-${hook.hookName}`}
288 className="rounded bg-gray-100 px-3 py-1 text-xs font-medium text-gray-950"
289 onClick={() => {
290 void hook.run()
291 }}
292 disabled={hook.isLoading}
293 >
294 Run
295 </button>
296 <button
297 type="button"
298 data-testid={`stop-${hook.hookName}`}
299 className="rounded border border-gray-700 px-3 py-1 text-xs text-gray-200"
300 onClick={hook.stop}
301 >
302 Stop
303 </button>
304 <button
305 type="button"
306 data-testid={`reset-${hook.hookName}`}
307 className="rounded border border-gray-700 px-3 py-1 text-xs text-gray-200"
308 onClick={hook.reset}
309 >
310 Reset
311 </button>
312 </div>
313 <div className="mt-3 space-y-2">{hook.preview}</div>
314 </section>
315 ))}
316 </div>
317 </div>
318 </DevtoolsHarness>
319 )
320}
321
322function CustomGenerationIdentityProbe() {
323 useGeneration({
324 fetcher: async () => ({ text: 'custom result' }),
325 devtools: CUSTOM_GENERATION_DEVTOOLS,
326 })
327 return null
328}
329
330function duplicateSingleImageResult(
331 result: ImageGenerationResult,
332): ImageGenerationResult {
333 const firstImage = result.images[0]
334 if (!firstImage || result.images.length > 1) return result
335 return {
336 ...result,
337 images: [firstImage, { ...firstImage }],
338 }
339}
340
341function normalizeAudioResult(
342 result: AudioGenerationResult,
343): AudioGenerationResult {
344 return {
345 ...result,
346 audio: {
347 ...result.audio,
348 // The aimock fixture sends raw RIFF/WAVE bytes; the provider adapter
349 // mislabels the contentType as audio/mpeg by default. Force audio/wav
350 // so the devtools preview uses a base64 data URL with the correct
351 // mime, matching what the test asserts.
352 contentType: 'audio/wav',
353 duration: result.audio.duration ?? 0.05,
354 },
355 }
356}
357
358function normalizeSpeechResult(result: TTSResult): TTSResult {
359 return {
360 ...result,
361 // Force audio/wav for the same reason as normalizeAudioResult: the
362 // aimock TTS fixture ships RIFF/WAVE bytes but the upstream adapter
363 // labels them audio/mpeg. The test expects audio/wav.
364 contentType: 'audio/wav',
365 duration: result.duration ?? 0.05,
366 }
367}
368
369function audioSource(audio: AudioGenerationResult['audio']): string {
370 if (audio.url) return audio.url
371 return `data:${audio.contentType ?? 'audio/wav'};base64,${audio.b64Json}`
372}