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

OmniStudio.tsx

601 lines22.9 KB

1import { useRef, useState } from 'react'
2import {
3 GitBranch,
4 Loader2,
5 Music,
6 RotateCcw,
7 Send,
8 Sparkles,
9 Upload,
10 X,
11} from 'lucide-react'
12import { useGenerateVideo } from '@tanstack/ai-react'
13import type { AttachedMedia } from '@/lib/media'
14import type { OmniTaskMode } from '@/lib/models'
15import type { MediaPromptPart } from '@tanstack/ai/client'
16​
17import { generateVideoFn } from '@/lib/server-functions'
18import { byok, callWithByok, toByokProvider } from '@/lib/byok'
19import { readMediaFile, toImagePart, toVideoPart } from '@/lib/media'
20​
21const OMNI_MODEL = 'gemini-omni-1.1-flash'
22/** Omni bills per second of generated video. */
23const PRICE_PER_SECOND = 0.1
24​
25type AspectRatio = '16:9' | '9:16'
26​
27/**
28 * One turn of an Omni session: the prompt (plus attachments and generation
29 * settings) and the clip it produced. `parentLocalId` records which earlier
30 * turn this one continued from — the session is a tree, not a line, since
31 * `previous_interaction_id` can point at any prior generation. `duration`
32 * is null for edit requests, which follow the source clip's length.
33 */
34interface OmniTurn {
35 localId: string
36 prompt: string
37 audioHint: string
38 images: Array<AttachedMedia>
39 video: AttachedMedia | null
40 duration: number | null
41 aspectRatio: AspectRatio
42 task: OmniTaskMode | 'auto'
43 parentLocalId: string | null
44 status: 'submitting' | 'processing' | 'completed' | 'error'
45 jobId?: string
46 url?: string
47 error?: string
49​
50const TASK_OPTIONS: Array<{ value: OmniTaskMode | 'auto'; label: string }> = [
51 { value: 'auto', label: 'Auto (model decides)' },
52 { value: 'text_to_video', label: 'Text-to-video' },
53 { value: 'image_to_video', label: 'Image-to-video' },
54 { value: 'reference_to_video', label: 'Reference-to-video' },
55 { value: 'edit', label: 'Edit' },
57​
58/**
59 * Chat-style session view for Gemini Omni Flash. Unlike the one-shot job
60 * form in VideoGenerator, every generation here is an interaction you can
61 * continue from: sending a new prompt chains it onto the selected clip via
62 * `previous_interaction_id`, and "Continue from here" on any earlier clip
63 * branches the session from that point.
64 */
65export default function OmniStudio() {
66 const [turns, setTurns] = useState<Array<OmniTurn>>([])
67 const [prompt, setPrompt] = useState('')
68 const [audioHint, setAudioHint] = useState('')
69 const [images, setImages] = useState<Array<AttachedMedia>>([])
70 const [video, setVideo] = useState<AttachedMedia | null>(null)
71 const [duration, setDuration] = useState(6)
72 const [aspectRatio, setAspectRatio] = useState<AspectRatio>('16:9')
73 const [task, setTask] = useState<OmniTaskMode | 'auto'>('auto')
74 /** localId of the turn new prompts continue from; null starts fresh. */
75 const [continueFrom, setContinueFrom] = useState<string | null>(null)
76 const imageInputRef = useRef<HTMLInputElement>(null)
77 const videoInputRef = useRef<HTMLInputElement>(null)
78 const promptRef = useRef<HTMLTextAreaElement>(null)
79 /**
80 * The turn currently on the wire, plus the request settings that go with
81 * it. `useGenerateVideo` builds its client (and captures the fetcher) once,
82 * so per-send values are read from here at call time instead of being
83 * closed over; the hook's callbacks use it to know which turn to update.
84 */
85 const submissionRef = useRef<{
86 localId: string
87 previousInteractionId?: string
88 omniOptions: {
89 duration?: number
90 aspectRatio: AspectRatio
91 task?: OmniTaskMode
92 }
93 } | null>(null)
94​
95 const updateTurn = (localId: string, patch: Partial<OmniTurn>) => {
96 setTurns((prev) =>
97 prev.map((turn) =>
98 turn.localId === localId ? { ...turn, ...patch } : turn,
99 ),
100 )
101 }
102​
103 // One hook serves the whole session: only one turn can be in flight (the
104 // composer is disabled while generating), and the timeline of finished
105 // clips is this component's own state rather than something the hook models.
106 const { generate, isLoading } = useGenerateVideo({
107 threadId: 'omni-studio',
108 byok,
109 byokProvider: () => toByokProvider('gemini'),
110 // `options.signal` is the hook's abort signal; cancelling the response is
111 // what ends the server's polling loop instead of leaving it running.
112 fetcher: (input, options) => {
113 const submission = submissionRef.current
114 if (!submission) throw new Error('No Omni turn in flight')
115 return callWithByok(
116 generateVideoFn({
117 data: {
118 prompt: input.prompt,
119 model: OMNI_MODEL,
120 ...(submission.previousInteractionId
121 ? { previousInteractionId: submission.previousInteractionId }
122 : {}),
123 omniOptions: submission.omniOptions,
124 },
125 signal: options?.signal,
126 headers: options?.headers,
127 }),
128 )
129 },
130 onJobCreated: (jobId) => {
131 const submission = submissionRef.current
132 if (submission) {
133 updateTurn(submission.localId, { status: 'processing', jobId })
134 }
135 },
136 onResult: (result) => {
137 const submission = submissionRef.current
138 if (!submission) return
139 // Clearing the ref is what re-opens the composer to the next send.
140 submissionRef.current = null
141 updateTurn(submission.localId, {
142 status: 'completed',
143 url: result.url,
144 })
145 // Conversational default: the newest finished clip becomes the one
146 // the next prompt continues from.
147 setContinueFrom(submission.localId)
148 },
149 onError: (err) => {
150 const submission = submissionRef.current
151 if (submission) {
152 submissionRef.current = null
153 updateTurn(submission.localId, {
154 status: 'error',
155 error: err.message,
156 })
157 }
158 },
159 })
160​
161 const handleImageSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
162 const files = Array.from(e.target.files ?? [])
163 if (imageInputRef.current) imageInputRef.current.value = ''
164 if (files.length === 0) return
165 try {
166 const attached = await Promise.all(files.map(readMediaFile))
167 setImages((prev) => [...prev, ...attached])
168 } catch {
169 // FileReader failures (corrupt/unreadable file) — just drop the batch.
170 }
171 }
172​
173 const handleVideoSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
174 const file = e.target.files?.[0]
175 if (videoInputRef.current) videoInputRef.current.value = ''
176 if (!file) return
177 try {
178 setVideo(await readMediaFile(file))
179 } catch {
180 // Unreadable file — leave the tray unchanged.
181 }
182 }
183​
184 const isBusy = isLoading
185​
186 const continueFromTurn = continueFrom
187 ? turns.find((turn) => turn.localId === continueFrom)
188 : undefined
189 const continueFromIndex = continueFromTurn
190 ? turns.indexOf(continueFromTurn) + 1
191 : null
192​
193 // Edits must keep the source clip's length — Omni rejects a mismatched
194 // `duration` with a 400 ("Edited video duration ... does not match config
195 // duration"). Lock the slider and omit `duration` whenever the request can
196 // be an edit: continuing a clip, task pinned to 'edit', or a video
197 // attached without pinning 'reference_to_video'.
198 const durationLocked =
199 continueFrom != null ||
200 task === 'edit' ||
201 (video != null && task !== 'reference_to_video')
202​
203 /**
204 * Put a failed turn's inputs back in the composer for adjustment and drop
205 * it from the timeline, so resubmitting replaces the failed attempt
206 * instead of starting an unrelated fresh generation.
207 */
208 const restoreTurn = (turn: OmniTurn) => {
209 setPrompt(turn.prompt)
210 setAudioHint(turn.audioHint)
211 setImages(turn.images)
212 setVideo(turn.video)
213 if (turn.duration != null) setDuration(turn.duration)
214 setAspectRatio(turn.aspectRatio)
215 setTask(turn.task)
216 setContinueFrom(turn.parentLocalId)
217 setTurns((prev) => prev.filter((t) => t.localId !== turn.localId))
218 promptRef.current?.focus()
219 }
220​
221 const handleSend = async () => {
222 // `isBusy` comes from React state, which hasn't re-rendered yet for a
223 // second click in the same tick; the ref is set synchronously below and
224 // cleared when the run settles, so it closes that window — without it a
225 // second send would overwrite the submission and strand the first turn.
226 if (!prompt.trim() || isBusy || submissionRef.current) return
227​
228 const parentJobId = continueFromTurn?.jobId
229 const localId = crypto.randomUUID()
230 const promptText = audioHint.trim()
231 ? `${prompt}\n\nAudio: ${audioHint.trim()}`
232 : prompt
233​
234 const parts: Array<MediaPromptPart> = [
235 ...images.map((image) => toImagePart(image)),
236 ...(video ? [toVideoPart(video)] : []),
237 { type: 'text', content: promptText },
238 ]
239 const builtPrompt = parts.length === 1 ? promptText : parts
240​
241 setTurns((prev) => [
242 ...prev,
243 {
244 localId,
245 prompt,
246 audioHint,
247 images,
248 video,
249 duration: durationLocked ? null : duration,
250 aspectRatio,
251 task,
252 parentLocalId: parentJobId ? continueFrom : null,
253 status: 'submitting',
254 },
255 ])
256 setPrompt('')
257 setAudioHint('')
258 setImages([])
259 setVideo(null)
260​
261 submissionRef.current = {
262 localId,
263 ...(parentJobId ? { previousInteractionId: parentJobId } : {}),
264 omniOptions: {
265 ...(durationLocked ? {} : { duration }),
266 aspectRatio,
267 ...(task !== 'auto' ? { task } : {}),
268 },
269 }
270 await generate({ prompt: builtPrompt })
271 }
272​
273 const estimatedCost = (duration * PRICE_PER_SECOND).toFixed(2)
274​
275 return (
276 <div className="space-y-6">
277 <div className="flex items-start gap-3 p-4 bg-purple-500/10 border border-purple-500/20 rounded-lg">
278 <Sparkles className="w-5 h-5 text-purple-400 shrink-0 mt-0.5" />
279 <p className="text-sm text-gray-300">
280 Every clip here is a conversation turn. Sending another prompt
281 continues from the highlighted clip — describe a change and Omni edits
282 the video while keeping everything else. Use{' '}
283 <span className="text-purple-300">Continue from here</span> on any
284 earlier clip to branch the session from that point, or clear the
285 banner to start a fresh video.
286 </p>
287 </div>
288​
289 {turns.length > 0 && (
290 <div className="space-y-4">
291 {turns.map((turn, i) => {
292 const parentPosition = turn.parentLocalId
293 ? turns.findIndex((t) => t.localId === turn.parentLocalId)
294 : -1
295 return (
296 <div
297 key={turn.localId}
298 className={`border-l-2 pl-4 space-y-2 ${
299 turn.localId === continueFrom
300 ? 'border-purple-500'
301 : 'border-gray-700'
302 }`}
303 >
304 <div className="p-3 bg-gray-800 rounded-lg border border-gray-700">
305 <div className="flex items-center gap-2 text-xs text-gray-500 mb-1">
306 <span className="font-medium text-gray-400">
307 Clip #{i + 1}
308 </span>
309 <span>
310 {turn.duration != null
311 ? `${turn.duration}s`
312 : 'source length'}{' '}
313 · {turn.aspectRatio}
314 {turn.task !== 'auto' ? ` · ${turn.task}` : ''}
315 </span>
316 {parentPosition >= 0 && (
317 <span className="flex items-center gap-1 text-purple-400">
318 <GitBranch className="w-3 h-3" />
319 continues #{parentPosition + 1}
320 </span>
321 )}
322 </div>
323 <p className="text-sm text-gray-200">{turn.prompt}</p>
324 {turn.audioHint && (
325 <p className="text-xs text-gray-400 mt-1 flex items-center gap-1">
326 <Music className="w-3 h-3" /> {turn.audioHint}
327 </p>
328 )}
329 {(turn.images.length > 0 || turn.video) && (
330 <div className="flex gap-2 mt-2">
331 {turn.images.map((image) => (
332 <img
333 key={image.id}
334 src={image.dataUrl}
335 alt={image.name}
336 className="w-12 h-12 object-cover rounded border border-gray-600"
337 />
338 ))}
339 {turn.video && (
340 <video
341 src={turn.video.dataUrl}
342 muted
343 className="w-12 h-12 object-cover rounded border border-gray-600"
344 />
345 )}
346 </div>
347 )}
348 </div>
349​
350 {(turn.status === 'submitting' ||
351 turn.status === 'processing') && (
352 <div className="flex items-center gap-2 p-4 bg-gray-800 rounded-lg border border-gray-700">
353 <Loader2 className="w-5 h-5 animate-spin text-purple-400" />
354 <span className="text-gray-400">
355 {turn.status === 'submitting'
356 ? 'Submitting...'
357 : 'Generating...'}
358 </span>
359 </div>
360 )}
361 {turn.status === 'error' && (
362 <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg space-y-2">
363 <p className="text-red-400 text-sm">{turn.error}</p>
364 <button
365 onClick={() => restoreTurn(turn)}
366 className="flex items-center gap-1.5 px-3 py-1 text-xs font-medium text-red-300 hover:text-red-200 bg-red-500/10 hover:bg-red-500/20 rounded-md transition-colors"
367 >
368 <RotateCcw className="w-3.5 h-3.5" />
369 Edit & retry — restores this prompt and its attachments
370 </button>
371 </div>
372 )}
373 {turn.status === 'completed' && turn.url && (
374 <div className="space-y-2">
375 <div className="rounded-lg overflow-hidden border border-gray-700">
376 <video
377 src={turn.url}
378 controls
379 autoPlay
380 loop
381 className="w-full h-auto"
382 />
383 </div>
384 <div className="flex items-center justify-between">
385 <p className="text-xs text-gray-500">
386 {turn.duration != null
387 ? `≈ $${(turn.duration * PRICE_PER_SECOND).toFixed(2)} for ${turn.duration}s of video`
388 : `billed at $${PRICE_PER_SECOND.toFixed(2)}/s of video`}
389 </p>
390 {turn.localId !== continueFrom && (
391 <button
392 onClick={() => {
393 setContinueFrom(turn.localId)
394 promptRef.current?.focus()
395 }}
396 className="flex items-center gap-1.5 px-3 py-1 text-xs font-medium text-purple-400 hover:text-purple-300 bg-purple-500/10 hover:bg-purple-500/20 rounded-md transition-colors"
397 >
398 <GitBranch className="w-3.5 h-3.5" />
399 Continue from here
400 </button>
401 )}
402 </div>
403 </div>
404 )}
405 </div>
406 )
407 })}
408 </div>
409 )}
410​
411 <div className="space-y-4 p-4 bg-gray-800/60 border border-gray-700 rounded-xl">
412 {continueFromIndex != null && (
413 <div className="flex items-center justify-between px-3 py-2 bg-purple-500/10 border border-purple-500/20 rounded-lg">
414 <span className="text-sm text-purple-300 flex items-center gap-2">
415 <GitBranch className="w-4 h-4" />
416 Continuing from clip #{continueFromIndex} — Omni will edit that
417 video
418 </span>
419 <button
420 onClick={() => setContinueFrom(null)}
421 className="text-xs text-gray-400 hover:text-white underline"
422 >
423 Start a new video instead
424 </button>
425 </div>
426 )}
427​
428 <textarea
429 ref={promptRef}
430 value={prompt}
431 onChange={(e) => setPrompt(e.target.value)}
432 placeholder={
433 continueFromIndex != null
434 ? "Describe the change — e.g. 'make it nighttime, add rain'..."
435 : 'Describe the video you want to generate...'
436 }
437 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-purple-500 focus:border-transparent resize-none"
438 rows={3}
439 />
440​
441 <div className="flex items-center gap-2">
442 <Music className="w-4 h-4 text-gray-500 shrink-0" />
443 <input
444 type="text"
445 value={audioHint}
446 onChange={(e) => setAudioHint(e.target.value)}
447 placeholder="Audio direction (optional) — e.g. 'calm piano', 'crowd noise, distant thunder'"
448 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-purple-500 focus:border-transparent"
449 />
450 </div>
451​
452 <div className="flex flex-wrap items-center gap-2">
453 {images.map((image) => (
454 <div key={image.id} className="relative">
455 <img
456 src={image.dataUrl}
457 alt={image.name}
458 className="w-16 h-16 object-cover rounded-lg border border-gray-600"
459 />
460 <button
461 onClick={() =>
462 setImages((prev) => prev.filter((m) => m.id !== image.id))
463 }
464 className="absolute -top-1.5 -right-1.5 p-0.5 bg-gray-900 hover:bg-gray-700 rounded-full text-white border border-gray-600"
465 >
466 <X className="w-3 h-3" />
467 </button>
468 </div>
469 ))}
470 {video && (
471 <div className="relative">
472 <video
473 src={video.dataUrl}
474 muted
475 className="w-16 h-16 object-cover rounded-lg border border-gray-600"
476 />
477 <button
478 onClick={() => setVideo(null)}
479 className="absolute -top-1.5 -right-1.5 p-0.5 bg-gray-900 hover:bg-gray-700 rounded-full text-white border border-gray-600"
480 >
481 <X className="w-3 h-3" />
482 </button>
483 </div>
484 )}
485 <button
486 onClick={() => imageInputRef.current?.click()}
487 className="flex flex-col items-center justify-center w-16 h-16 border-2 border-dashed border-gray-600 hover:border-gray-500 rounded-lg text-gray-500 hover:text-gray-400 transition-colors"
488 title="Attach reference images (up to 6)"
489 >
490 <Upload className="w-4 h-4" />
491 <span className="text-[10px] mt-0.5">Images</span>
492 </button>
493 {!video && (
494 <button
495 onClick={() => videoInputRef.current?.click()}
496 className="flex flex-col items-center justify-center w-16 h-16 border-2 border-dashed border-gray-600 hover:border-gray-500 rounded-lg text-gray-500 hover:text-gray-400 transition-colors"
497 title="Attach a reference clip (3 seconds max — longer clips are not processed correctly)"
498 >
499 <Upload className="w-4 h-4" />
500 <span className="text-[10px] mt-0.5">Clip ≤3s</span>
501 </button>
502 )}
503 <input
504 ref={imageInputRef}
505 type="file"
506 accept="image/*"
507 multiple
508 onChange={handleImageSelect}
509 className="hidden"
510 />
511 <input
512 ref={videoInputRef}
513 type="file"
514 accept="video/*"
515 onChange={handleVideoSelect}
516 className="hidden"
517 />
518 </div>
519​
520 <div className="flex flex-wrap items-center gap-4">
521 {durationLocked ? (
522 <span
523 className="text-sm text-gray-500"
524 title="Omni edits must keep the source clip's length — a mismatched duration is rejected. Pin Task to 'Reference-to-video' to control the length of a clip-conditioned generation."
525 >
526 Length follows the clip being edited
527 </span>
528 ) : (
529 <label className="flex items-center gap-2 text-sm text-gray-400">
530 Duration
531 <input
532 type="range"
533 min={3}
534 max={10}
535 step={0.5}
536 value={duration}
537 onChange={(e) => setDuration(Number(e.target.value))}
538 className="w-28 accent-purple-500"
539 />
540 <span className="text-gray-300 w-20">
541 {duration}s ≈ ${estimatedCost}
542 </span>
543 </label>
544 )}
545​
546 <div className="flex gap-1">
547 {(['16:9', '9:16'] as const).map((ratio) => (
548 <button
549 key={ratio}
550 onClick={() => setAspectRatio(ratio)}
551 className={`px-3 py-1 text-sm rounded-md transition-colors ${
552 aspectRatio === ratio
553 ? 'bg-purple-600 text-white'
554 : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
555 }`}
556 >
557 {ratio}
558 </button>
559 ))}
560 </div>
561​
562 <select
563 value={task}
564 onChange={(e) => {
565 const value = e.target.value
566 const option = TASK_OPTIONS.find((o) => o.value === value)
567 if (option) setTask(option.value)
568 }}
569 className="px-3 py-1.5 bg-gray-800 border border-gray-700 rounded-lg text-sm text-gray-300 focus:outline-none focus:ring-2 focus:ring-purple-500"
570 >
571 {TASK_OPTIONS.map((option) => (
572 <option key={option.value} value={option.value}>
573 {option.label}
574 </option>
575 ))}
576 </select>
577 </div>
578​
579 <button
580 onClick={handleSend}
581 disabled={isBusy || !prompt.trim()}
582 className="w-full px-6 py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-700 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
583 >
584 {isBusy ? (
585 <>
586 <Loader2 className="w-5 h-5 animate-spin" />
587 Generating...
588 </>
589 ) : (
590 <>
591 <Send className="w-5 h-5" />
592 {continueFromIndex != null
593 ? `Continue clip #${continueFromIndex}`
594 : 'Generate Video'}
595 </>
596 )}
597 </button>
598 </div>
599 </div>
600 )