import { useRef, useState } from 'react' import { useGenerateImage, fetchServerSentEvents, fetchHttpStream, } from '@tanstack/ai-react' import { generateImageFn } from '@/lib/server-functions' import type { ImageGenerationResult, MediaPrompt } from '@tanstack/ai' import type { Mode, Provider } from '@/lib/types' interface ImageGenUIProps { provider: Provider mode: Mode testId?: string aimockPort?: number /** Show a file input and send the prompt as multimodal parts (image-to-image). */ withImageInput?: boolean } function fileToBase64(file: File): Promise { return new Promise((resolve, reject) => { const reader = new FileReader() reader.onload = () => { const result = reader.result if (typeof result !== 'string') { reject(new Error('Unexpected FileReader result')) return } resolve(result.split(',')[1] ?? '') } reader.onerror = () => reject(new Error('Failed to read file')) reader.readAsDataURL(file) }) } export function ImageGenUI({ provider, mode, testId, aimockPort, withImageInput, }: ImageGenUIProps) { const [prompt, setPrompt] = useState('') const [imageFile, setImageFile] = useState(null) const connectionOptions = () => { const body = { provider, numberOfImages: 1, testId, aimockPort } if (mode === 'sse') { return { connection: fetchServerSentEvents('/api/image'), body } } if (mode === 'http-stream') { return { connection: fetchHttpStream('/api/image/stream'), body } } return { fetcher: async (input: { prompt: MediaPrompt }) => { return generateImageFn({ data: { prompt: input.prompt, provider, numberOfImages: 1, aimockPort, testId, }, }) as Promise }, } } const { generate, result, isLoading, error, status, runId } = useGenerateImage({ threadId: testId ?? 'image-gen', ...connectionOptions(), }) const activeTuple = useRef({ runId: '', status: 'idle', isLoading: false }) if (runId && status === 'generating' && isLoading) { activeTuple.current = { runId, status, isLoading } } const handleGenerate = async () => { if (!imageFile) { await generate({ prompt }) return } const base64 = await fileToBase64(imageFile) await generate({ prompt: [ { type: 'text', content: prompt }, { type: 'image', source: { type: 'data', value: base64, mimeType: imageFile.type }, }, ], }) } return (
{activeTuple.current.runId} {activeTuple.current.status} {String(activeTuple.current.isLoading)} {runId ?? ''}
setPrompt(e.target.value)} placeholder="Describe the image..." className="flex-1 bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm" />
{withImageInput && ( setImageFile(e.target.files?.[0] ?? null)} className="text-sm text-gray-400" /> )}
{status === 'idle' ? 'idle' : isLoading ? 'loading' : error ? 'error' : result ? 'complete' : 'idle'}
{error && (
{error.message}
)} {result && (
{result.images.map((img, i) => ( {`Generated ))}
)}
) }