'use client'; import { useState, useEffect } from 'react'; import { Header } from '@/components/layout'; import { AppLayout } from '@/components/layout'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Textarea } from '@/components/ui/textarea'; import { PromptTextarea } from '@/components/forms'; import { Label } from '@/components/ui/label'; import { Card, CardContent } from '@/components/ui/card'; import { apiClient, type GenerationRequest, type JobInfo, type ModelInfo } from '@/lib/api'; import { Loader2, Download, X, Trash2, RotateCcw, Power } from 'lucide-react'; import { downloadImage, downloadAuthenticatedImage } from '@/lib/utils'; import { useLocalStorage } from '@/lib/storage'; const defaultFormData: GenerationRequest = { prompt: '', negative_prompt: '', width: 512, height: 512, steps: 20, cfg_scale: 7.5, seed: '', sampling_method: 'euler_a', scheduler: 'default', batch_count: 1, }; function Text2ImgForm() { const [formData, setFormData] = useLocalStorage( 'text2img-form-data', defaultFormData, { excludeLargeData: true, maxSize: 512 * 1024 } // 512KB limit ); const [loading, setLoading] = useState(false); const [jobInfo, setJobInfo] = useState(null); const [generatedImages, setGeneratedImages] = useState([]); const [samplers, setSamplers] = useState>([]); const [schedulers, setSchedulers] = useState>([]); const [loraModels, setLoraModels] = useState([]); const [embeddings, setEmbeddings] = useState([]); const [error, setError] = useState(null); const [pollCleanup, setPollCleanup] = useState<(() => void) | null>(null); // Cleanup polling on unmount useEffect(() => { return () => { if (pollCleanup) { pollCleanup(); } }; }, [pollCleanup]); useEffect(() => { const loadOptions = async () => { try { const [samplersData, schedulersData, loras, embeds] = await Promise.all([ apiClient.getSamplers(), apiClient.getSchedulers(), apiClient.getModels('lora'), apiClient.getModels('embedding'), ]); setSamplers(samplersData); setSchedulers(schedulersData); setLoraModels(loras.models.map(m => m.name)); setEmbeddings(embeds.models.map(m => m.name)); } catch (err) { console.error('Failed to load options:', err); } }; loadOptions(); }, []); const handleInputChange = ( e: React.ChangeEvent ) => { const { name, value } = e.target; setFormData((prev) => ({ ...prev, [name]: name === 'prompt' || name === 'negative_prompt' || name === 'seed' || name === 'sampling_method' || name === 'scheduler' ? value : Number(value), })); }; const pollJobStatus = async (jobId: string) => { const maxAttempts = 300; // 5 minutes with 2 second interval let attempts = 0; let isPolling = true; const poll = async () => { if (!isPolling) return; try { const status = await apiClient.getJobStatus(jobId); setJobInfo(status); if (status.status === 'completed') { let imageUrls: string[] = []; // Handle both old format (result.images) and new format (outputs) if (status.outputs && status.outputs.length > 0) { // New format: convert output URLs to authenticated image URLs with cache-busting imageUrls = status.outputs.map((output: any) => { const filename = output.filename; return apiClient.getImageUrl(jobId, filename); }); } else if (status.result?.images && status.result.images.length > 0) { // Old format: convert image URLs to authenticated URLs imageUrls = status.result.images.map((imageUrl: string) => { // Extract filename from URL if it's a full URL const filename = imageUrl.split('/').pop() || imageUrl; return apiClient.getImageUrl(jobId, filename); }); } // Create a new array to trigger React re-render setGeneratedImages([...imageUrls]); setLoading(false); isPolling = false; } else if (status.status === 'failed') { setError(status.error || 'Generation failed'); setLoading(false); isPolling = false; } else if (status.status === 'cancelled') { setError('Generation was cancelled'); setLoading(false); isPolling = false; } else if (attempts < maxAttempts) { attempts++; setTimeout(poll, 2000); } else { setError('Job polling timeout'); setLoading(false); isPolling = false; } } catch (err) { if (isPolling) { setError(err instanceof Error ? err.message : 'Failed to check job status'); setLoading(false); isPolling = false; } } }; poll(); // Return cleanup function return () => { isPolling = false; }; }; const handleGenerate = async (e: React.FormEvent) => { e.preventDefault(); setLoading(true); setError(null); setGeneratedImages([]); setJobInfo(null); try { const requestData = { ...formData, }; const job = await apiClient.text2img(requestData); setJobInfo(job); const jobId = job.request_id || job.id; if (jobId) { const cleanup = pollJobStatus(jobId); setPollCleanup(() => cleanup); } else { setError('No job ID returned from server'); setLoading(false); } } catch (err) { setError(err instanceof Error ? err.message : 'Failed to generate image'); setLoading(false); } }; const handleCancel = async () => { const jobId = jobInfo?.request_id || jobInfo?.id; if (jobId) { try { await apiClient.cancelJob(jobId); setLoading(false); setError('Generation cancelled'); // Cleanup polling if (pollCleanup) { pollCleanup(); setPollCleanup(null); } } catch (err) { console.error('Failed to cancel job:', err); } } }; const handleClearPrompts = () => { setFormData({ ...formData, prompt: '', negative_prompt: '' }); }; const handleResetToDefaults = () => { setFormData(defaultFormData); }; const handleServerRestart = async () => { if (!confirm('Are you sure you want to restart the server? This will cancel all running jobs.')) { return; } try { setLoading(true); await apiClient.restartServer(); setError('Server restart initiated. Please wait...'); setTimeout(() => { window.location.reload(); }, 3000); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to restart server'); setLoading(false); } }; return (
{/* Left Panel - Form */}
setFormData({ ...formData, prompt: value })} placeholder="a beautiful landscape with mountains and a lake, sunset, highly detailed..." rows={4} loras={loraModels} embeddings={embeddings} />

Tip: Use <lora:name:weight> for LoRAs (e.g., <lora:myLora:0.8>) and embedding names directly

setFormData({ ...formData, negative_prompt: value })} placeholder="blurry, low quality, distorted..." rows={2} loras={loraModels} embeddings={embeddings} />
{/* Utility Buttons */}
{loading && ( )}
{error && (
{error}
)}
{/* Right Panel - Generated Images */}

Generated Images

{generatedImages.length === 0 ? (

{loading ? 'Generating...' : 'Generated images will appear here'}

) : (
{generatedImages.map((image, index) => (
{`Generated
))}
)}
); } export default function Text2ImgPage() { return ; }