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

devtools-generation-hooks.tsx

371 lines12.0 KB

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