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

VideoGenerator.tsx

623 lines21.9 KB

1import { useCallback, useEffect, useRef, useState } from 'react'
2import { Film, Loader2, Shuffle, Upload, Wand2, X } from 'lucide-react'
3import { useGenerateVideo } from '@tanstack/ai-react'
4import type { BilledUsage } from '@tanstack/ai'
5import type { VideoModel, VideoMode } from '@/lib/models'
6import type { AttachedMedia } from '@/lib/media'
7import type { MediaPrompt, MediaPromptPart } from '@tanstack/ai/client'
8import type { VideoBilling } from '@/lib/billing'
9​
10import { generateVideoFn } from '@/lib/server-functions'
11import { byok, callWithByok, toByokProvider } from '@/lib/byok'
12import { VIDEO_MODELS } from '@/lib/models'
13import { getRandomVideoPrompt } from '@/lib/prompts'
14import { imageUrlToPart, readMediaFile, toVideoPart } from '@/lib/media'
15import { readVideoBilling } from '@/lib/billing'
16​
17interface VideoGeneratorProps {
18 initialImageUrl?: string | null
20​
21/**
22 * One submission. Each card builds its own prompt from this, because which
23 * parts a model may receive depends on the model: only Omni takes a video
24 * part.
25 */
26interface VideoRequest {
27 prompt: string
28 mode: VideoMode
29 imageUrl: string | null
30 video: AttachedMedia | null
32​
33/** What each card hands the parent so it can drive that card's hook. */
34interface VideoCardHandle {
35 run: (request: VideoRequest) => void
36 clear: () => void
38​
39/**
40 * Image conditioning rides in the prompt: the start frame is an image part
41 * tagged `role: 'start_frame'`, which the fal adapter routes to the
42 * endpoint's start-image field (e.g. `image_url` on Kling i2v) and Omni takes
43 * as an interaction content block. Video parts (a reference clip or a clip to
44 * edit) are an Omni capability only, so they never reach the other providers.
45 */
46function buildVideoPrompt(
47 request: VideoRequest,
48 model: VideoModel,
49): MediaPrompt {
50 const parts: Array<MediaPromptPart> = [
51 { type: 'text', content: request.prompt },
52 ]
53 if (request.mode === 'image-to-video' && request.imageUrl) {
54 parts.push(imageUrlToPart(request.imageUrl, { role: 'start_frame' }))
55 }
56 if (request.video && model.provider === 'gemini') {
57 parts.push(toVideoPart(request.video))
58 }
59 return parts.length === 1 ? request.prompt : parts
61​
62/**
63 * Human label for a billed quantity, driven by the unit the adapter reported —
64 * no guessing from provider identity or cost presence.
65 */
66function describeBilled({ quantity, unit }: BilledUsage): string {
67 const plural = quantity === 1 ? '' : 's'
68 switch (unit) {
69 case 'seconds':
70 return `${quantity} second${plural} of video`
71 case 'units':
72 return `${quantity} fal unit${plural}`
73 default:
74 return `${quantity} ${unit}`
75 }
77​
78export default function VideoGenerator({
79 initialImageUrl,
80}: VideoGeneratorProps) {
81 const [mode, setMode] = useState<VideoMode>('text-to-video')
82 const [prompt, setPrompt] = useState('')
83 const [selectedModel, setSelectedModel] = useState<string>('all')
84 const [imagePreview, setImagePreview] = useState<string | null>(
85 initialImageUrl ?? null,
86 )
87 const [attachedVideo, setAttachedVideo] = useState<AttachedMedia | null>(null)
88 /** Whether anything has been generated for the current model selection. */
89 const [submitted, setSubmitted] = useState(false)
90 const [running, setRunning] = useState<Record<string, boolean>>({})
91 const fileInputRef = useRef<HTMLInputElement>(null)
92 const videoInputRef = useRef<HTMLInputElement>(null)
93 // Generation is started from the click, not from an effect on the cards:
94 // a hook only exists inside a mounted component, so the cards mount with
95 // the picker and hand the parent a way to run and clear them.
96 const cardsRef = useRef(new Map<string, VideoCardHandle>())
97​
98 const filteredModels: ReadonlyArray<VideoModel> = VIDEO_MODELS.filter(
99 (m) => m.mode === mode,
100 )
101 const falModels = filteredModels.filter((m) => m.provider === 'fal')
102 const xaiModels = filteredModels.filter((m) => m.provider === 'xai')
103 const geminiModels = filteredModels.filter((m) => m.provider === 'gemini')
104 const byteplusModels = filteredModels.filter((m) => m.provider === 'byteplus')
105 const openrouterModels = filteredModels.filter(
106 (m) => m.provider === 'openrouter',
107 )
108 const activeModels =
109 selectedModel === 'all'
110 ? filteredModels
111 : filteredModels.filter((model) => model.id === selectedModel)
112​
113 // Gemini Omni Flash additionally accepts video prompt parts (a reference
114 // clip or a video to edit). Offer the upload whenever an Omni model is in
115 // the running — other providers never receive the video part.
116 const omniInRun =
117 selectedModel === 'all'
118 ? geminiModels.length > 0
119 : selectedModel.startsWith('gemini-omni')
120​
121 // Each card runs its own generation, so the form is busy while any of them
122 // reports that it is.
123 const isGenerating = Object.values(running).some(Boolean)
124​
125 useEffect(() => {
126 if (initialImageUrl) {
127 setImagePreview(initialImageUrl)
128 }
129 }, [initialImageUrl])
130​
131 useEffect(() => {
132 // When mode changes, reset to "all" or first available model — and with
133 // it the results, which belong to the models that produced them.
134 setSelectedModel('all')
135 setSubmitted(false)
136 setRunning({})
137 }, [mode])
138​
139 const handleImageSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
140 const file = e.target.files?.[0]
141 if (fileInputRef.current) fileInputRef.current.value = ''
142 if (!file) return
143 const attached = await readMediaFile(file)
144 setImagePreview(attached.dataUrl)
145 }
146​
147 const clearImage = () => {
148 setImagePreview(null)
149 if (fileInputRef.current) fileInputRef.current.value = ''
150 }
151​
152 const handleVideoSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
153 const file = e.target.files?.[0]
154 if (videoInputRef.current) videoInputRef.current.value = ''
155 if (!file) return
156 setAttachedVideo(await readMediaFile(file))
157 }
158​
159 const clearVideo = () => {
160 setAttachedVideo(null)
161 if (videoInputRef.current) videoInputRef.current.value = ''
162 }
163​
164 const handleRunningChange = useCallback((modelId: string, value: boolean) => {
165 setRunning((prev) =>
166 prev[modelId] === value ? prev : { ...prev, [modelId]: value },
167 )
168 }, [])
169​
170 const registerCard = useCallback(
171 (modelId: string, card: VideoCardHandle | null) => {
172 if (card) cardsRef.current.set(modelId, card)
173 else cardsRef.current.delete(modelId)
174 },
175 [],
176 )
177​
178 const handleGenerate = () => {
179 if (!prompt.trim()) return
180 if (mode === 'image-to-video' && !imagePreview) return
181​
182 const request: VideoRequest = {
183 prompt,
184 mode,
185 imageUrl: imagePreview,
186 video: attachedVideo,
187 }
188 setSubmitted(true)
189 for (const model of activeModels) {
190 cardsRef.current.get(model.id)?.run(request)
191 }
192 }
193​
194 /** "Generate another": drop the results themselves, not just their panel. */
195 const clearResults = () => {
196 for (const card of cardsRef.current.values()) card.clear()
197 setSubmitted(false)
198 setRunning({})
199 }
200​
201 return (
202 <div className="space-y-6">
203 <div className="flex gap-2">
204 <button
205 onClick={() => setMode('text-to-video')}
206 className={`px-4 py-2 rounded-lg font-medium transition-colors ${
207 mode === 'text-to-video'
208 ? 'bg-blue-600 text-white'
209 : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
210 }`}
211 >
212 Text-to-Video
213 </button>
214 <button
215 onClick={() => setMode('image-to-video')}
216 className={`px-4 py-2 rounded-lg font-medium transition-colors ${
217 mode === 'image-to-video'
218 ? 'bg-blue-600 text-white'
219 : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
220 }`}
221 >
222 Image-to-Video
223 </button>
224 </div>
225​
226 <div className="space-y-4">
227 <div>
228 <label className="block text-sm font-medium text-gray-300 mb-2">
229 Model
230 </label>
231 <select
232 value={selectedModel}
233 onChange={(e) => {
234 setSelectedModel(e.target.value)
235 setSubmitted(false)
236 setRunning({})
237 }}
238 disabled={isGenerating}
239 className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50"
240 >
241 <option value="all">All Models</option>
242 <optgroup label="fal.ai">
243 {falModels.map((model) => (
244 <option key={model.id} value={model.id}>
245 {model.name}
246 </option>
247 ))}
248 </optgroup>
249 <optgroup label="xAI (direct)">
250 {xaiModels.map((model) => (
251 <option key={model.id} value={model.id}>
252 {model.name}
253 </option>
254 ))}
255 </optgroup>
256 <optgroup label="Google (direct)">
257 {geminiModels.map((model) => (
258 <option key={model.id} value={model.id}>
259 {model.name}
260 </option>
261 ))}
262 </optgroup>
263 <optgroup label="BytePlus (direct)">
264 {byteplusModels.map((model) => (
265 <option key={model.id} value={model.id}>
266 {model.name}
267 </option>
268 ))}
269 </optgroup>
270 <optgroup label="OpenRouter">
271 {openrouterModels.map((model) => (
272 <option key={model.id} value={model.id}>
273 {model.name}
274 </option>
275 ))}
276 </optgroup>
277 </select>
278 </div>
279​
280 {mode === 'image-to-video' && (
281 <div>
282 <label className="block text-sm font-medium text-gray-300 mb-2">
283 Source Image
284 </label>
285 {imagePreview ? (
286 <div className="relative">
287 <img
288 src={imagePreview}
289 alt="Source"
290 className="w-full max-h-64 object-contain rounded-lg border border-gray-700"
291 />
292 <button
293 onClick={clearImage}
294 disabled={isGenerating}
295 className="absolute top-2 right-2 p-1 bg-gray-900/80 hover:bg-gray-800 rounded-full text-white disabled:opacity-50"
296 >
297 <X className="w-4 h-4" />
298 </button>
299 </div>
300 ) : (
301 <button
302 onClick={() => fileInputRef.current?.click()}
303 className="w-full p-8 border-2 border-dashed border-gray-600 hover:border-gray-500 rounded-lg text-gray-400 hover:text-gray-300 transition-colors flex flex-col items-center gap-2"
304 >
305 <Upload className="w-8 h-8" />
306 <span>Click to upload an image</span>
307 </button>
308 )}
309 <input
310 ref={fileInputRef}
311 type="file"
312 accept="image/*"
313 onChange={handleImageSelect}
314 className="hidden"
315 />
316 </div>
317 )}
318​
319 {omniInRun && (
320 <div>
321 <label className="block text-sm font-medium text-gray-300 mb-2">
322 Reference video{' '}
323 <span className="text-gray-500 font-normal">
324 (optional — Gemini Omni Flash only, clips of 3s or less)
325 </span>
326 </label>
327 {attachedVideo ? (
328 <div className="relative">
329 <video
330 src={attachedVideo.dataUrl}
331 controls
332 muted
333 className="w-full max-h-64 rounded-lg border border-gray-700"
334 />
335 <button
336 onClick={clearVideo}
337 disabled={isGenerating}
338 className="absolute top-2 right-2 p-1 bg-gray-900/80 hover:bg-gray-800 rounded-full text-white disabled:opacity-50"
339 >
340 <X className="w-4 h-4" />
341 </button>
342 </div>
343 ) : (
344 <button
345 onClick={() => videoInputRef.current?.click()}
346 className="w-full p-6 border-2 border-dashed border-gray-600 hover:border-gray-500 rounded-lg text-gray-400 hover:text-gray-300 transition-colors flex flex-col items-center gap-2"
347 >
348 <Upload className="w-6 h-6" />
349 <span>Click to attach a video clip</span>
350 </button>
351 )}
352 <input
353 ref={videoInputRef}
354 type="file"
355 accept="video/*"
356 onChange={handleVideoSelect}
357 className="hidden"
358 />
359 </div>
360 )}
361​
362 <div>
363 <div className="flex items-center justify-between mb-2">
364 <label className="text-sm font-medium text-gray-300">Prompt</label>
365 <button
366 onClick={() => setPrompt(getRandomVideoPrompt(mode))}
367 disabled={isGenerating}
368 className="flex items-center gap-1.5 px-3 py-1 text-xs font-medium text-blue-400 hover:text-blue-300 bg-blue-500/10 hover:bg-blue-500/20 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
369 >
370 <Shuffle className="w-3.5 h-3.5" />
371 Shuffle
372 </button>
373 </div>
374 <textarea
375 value={prompt}
376 onChange={(e) => setPrompt(e.target.value)}
377 placeholder={
378 mode === 'image-to-video'
379 ? 'Describe how you want the image to animate...'
380 : 'Describe the video you want to generate...'
381 }
382 className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
383 rows={3}
384 disabled={isGenerating}
385 />
386 </div>
387​
388 <button
389 onClick={handleGenerate}
390 disabled={
391 isGenerating ||
392 !prompt.trim() ||
393 (mode === 'image-to-video' && !imagePreview)
394 }
395 className="w-full px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
396 >
397 {isGenerating ? (
398 <>
399 <Loader2 className="w-5 h-5 animate-spin" />
400 Generating...
401 </>
402 ) : (
403 <>
404 <Film className="w-5 h-5" />
405 Generate Video{selectedModel === 'all' ? 's' : ''}
406 </>
407 )}
408 </button>
409 </div>
410​
411 <div className="space-y-6">
412 {submitted && (
413 <div className="flex items-center justify-between">
414 <h3 className="text-lg font-medium text-white">
415 {activeModels.length > 1 ? 'Generated Videos' : 'Generated Video'}
416 </h3>
417 {!isGenerating && (
418 <button
419 onClick={clearResults}
420 className="text-sm text-gray-400 hover:text-white underline"
421 >
422 Generate another
423 </button>
424 )}
425 </div>
426 )}
427 {activeModels.map((model) => (
428 <VideoModelCard
429 key={model.id}
430 model={model}
431 visible={submitted}
432 showTitle={activeModels.length > 1}
433 onRegister={registerCard}
434 onRunningChange={handleRunningChange}
435 />
436 ))}
437 </div>
438 </div>
439 )
441​
442/**
443 * One model's generation. `useGenerateVideo` drives the whole job lifecycle —
444 * the server streams job id, status and the finished url back on one request,
445 * so there is no polling timer or job-state machine in the UI.
446 */
447function VideoModelCard({
448 model,
449 visible,
450 showTitle,
451 onRegister,
452 onRunningChange,
453}: {
454 model: VideoModel
455 visible: boolean
456 showTitle: boolean
457 onRegister: (modelId: string, card: VideoCardHandle | null) => void
458 onRunningChange: (modelId: string, running: boolean) => void
459}) {
460 const [editPrompt, setEditPrompt] = useState('')
461 const [billing, setBilling] = useState<VideoBilling | undefined>(undefined)
462 // The hook builds its client once, so the fetcher closure is created once
463 // too: anything that changes between runs (here, the Omni interaction being
464 // continued) has to be read from a ref at call time rather than captured.
465 const previousInteractionRef = useRef<string | undefined>(undefined)
466​
467 const { generate, reset, result, jobId, videoStatus, isLoading, error } =
468 useGenerateVideo({
469 threadId: `video:${model.id}`,
470 // `options.signal` is the hook's abort signal. Forwarding it matters
471 // more here than for images: cancelling the response is what ends the
472 // server's polling loop instead of leaving it running to the timeout.
473 byok,
474 byokProvider: () => toByokProvider(model.provider),
475 fetcher: (input, options) =>
476 callWithByok(
477 generateVideoFn({
478 data: {
479 prompt: input.prompt,
480 model: model.id,
481 ...(previousInteractionRef.current
482 ? { previousInteractionId: previousInteractionRef.current }
483 : {}),
484 },
485 signal: options?.signal,
486 headers: options?.headers,
487 }),
488 ),
489 onChunk: (chunk) => {
490 const usage = readVideoBilling(chunk)
491 if (usage) setBilling(usage)
492 },
493 })
494​
495 const clear = useCallback(() => {
496 previousInteractionRef.current = undefined
497 setBilling(undefined)
498 reset()
499 }, [reset])
500​
501 const run = useCallback(
502 (request: VideoRequest) => {
503 // A new submission is a fresh video, never a continuation of the clip
504 // this card is showing. Deliberately not `reset()` first: reset stops
505 // the client, which clears the `isLoading` that makes a second
506 // `generate()` a no-op — that guard is what swallows a double-click.
507 // The stale result a failed re-run leaves behind is handled by the
508 // render gate below instead.
509 previousInteractionRef.current = undefined
510 setBilling(undefined)
511 void generate({ prompt: buildVideoPrompt(request, model) })
512 },
513 [generate, model],
514 )
515​
516 useEffect(() => {
517 onRegister(model.id, { run, clear })
518 return () => onRegister(model.id, null)
519 }, [model.id, run, clear, onRegister])
520​
521 useEffect(() => {
522 onRunningChange(model.id, isLoading)
523 }, [model.id, isLoading, onRunningChange])
524​
525 if (!visible) return null
526​
527 /**
528 * Gemini Omni Flash conversational editing: chain a new prompt onto the
529 * finished generation via its interaction id (the job id). The model
530 * applies the change while preserving everything else in the video.
531 */
532 const handleEditVideo = () => {
533 const edit = editPrompt.trim()
534 if (!edit || !result || isLoading) return
535 previousInteractionRef.current = result.jobId
536 setBilling(undefined)
537 setEditPrompt('')
538 void generate({ prompt: edit })
539 }
540​
541 const status = videoStatus?.status
542​
543 return (
544 <div className="space-y-2">
545 {showTitle && (
546 <h4 className="text-sm font-medium text-gray-300">{model.name}</h4>
547 )}
548 {isLoading && (
549 <div className="flex items-center gap-2 p-4 bg-gray-800 rounded-lg border border-gray-700">
550 <Loader2 className="w-5 h-5 animate-spin text-blue-400" />
551 <span className="text-gray-400">
552 {!jobId
553 ? 'Submitting...'
554 : status === 'processing'
555 ? `Processing${
556 videoStatus?.progress != null
557 ? ` (${videoStatus.progress}%)`
558 : '...'
559 }`
560 : 'Queued...'}
561 </span>
562 </div>
563 )}
564 {error && !isLoading && (
565 <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400">
566 {error.message}
567 </div>
568 )}
569 {/* `!error`: a failed re-run keeps the previous clip on the hook, and it
570 must not render underneath the new error. */}
571 {result && !isLoading && !error && (
572 <>
573 <div className="rounded-lg overflow-hidden border border-gray-700">
574 <video
575 src={result.url}
576 controls
577 autoPlay
578 loop
579 className="w-full h-auto"
580 />
581 </div>
582 {billing?.cost != null ? (
583 <p className="text-xs text-gray-500">
584 Billed ${billing.cost.toFixed(3)}
585 {billing.billed ? ` for ${describeBilled(billing.billed)}` : ''}
586 </p>
587 ) : (
588 billing?.billed && (
589 <p className="text-xs text-gray-500">
590 Billed {describeBilled(billing.billed)}
591 {billing.billed.unit === 'units'
592 ? ' — multiply by the endpoint unit price for USD cost'
593 : ''}
594 </p>
595 )
596 )}
597 {model.provider === 'gemini' && (
598 <div className="flex gap-2">
599 <input
600 type="text"
601 value={editPrompt}
602 onChange={(e) => setEditPrompt(e.target.value)}
603 onKeyDown={(e) => {
604 if (e.key === 'Enter') handleEditVideo()
605 }}
606 placeholder="Describe an edit — e.g. 'make it nighttime'..."
607 className="flex-1 px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50"
608 />
609 <button
610 onClick={handleEditVideo}
611 disabled={!editPrompt.trim()}
612 className="px-4 py-2 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-700 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors flex items-center gap-1.5"
613 >
614 <Wand2 className="w-4 h-4" />
615 Edit
616 </button>
617 </div>
618 )}
619 </>
620 )}
621 </div>
622 )